code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def update_user(bridge_user):
"""
Update only the user attributes provided.
Return a list of BridgeUsers objects with custom fields.
"""
if bridge_user.bridge_id:
url = author_id_url(bridge_user.bridge_id)
else:
url = author_uid_url(bridge_user.netid)
resp = patch_resource(ur... | Update only the user attributes provided.
Return a list of BridgeUsers objects with custom fields. |
def default_downloader(directory, urls, filenames, url_prefix=None,
clear=False):
"""Downloads or clears files from URLs and filenames.
Parameters
----------
directory : str
The directory in which downloaded files are saved.
urls : list
A list of URLs to downl... | Downloads or clears files from URLs and filenames.
Parameters
----------
directory : str
The directory in which downloaded files are saved.
urls : list
A list of URLs to download.
filenames : list
A list of file names for the corresponding URLs.
url_prefix : str, optiona... |
def update_from(self, mapping):
"""
Updates the set of parameters from a mapping for keys that already exist
"""
for key, value in mapping.items():
if key in self:
if isinstance(value, Parameter):
value = value.value
self[ke... | Updates the set of parameters from a mapping for keys that already exist |
def _ttr(self, kloc, cache, **kwargs):
"""
Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal(), chaospy.Exponential())
>>> print(numpy.around(dist.ttr([[1, 2, 3], [1, 2, 3], [1, 2, 3]]), 4))
[[[0.5 0.5 0.5 ]
[0.0833 0.0667 0.0643]
... | Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal(), chaospy.Exponential())
>>> print(numpy.around(dist.ttr([[1, 2, 3], [1, 2, 3], [1, 2, 3]]), 4))
[[[0.5 0.5 0.5 ]
[0.0833 0.0667 0.0643]
[0. 0. 0. ]]
<BLANKLINE... |
def _compute_line(source_code, start, length):
"""
Compute line(s) numbers and starting/ending columns
from a start/end offset. All numbers start from 1.
Not done in an efficient way
"""
total_length = len(source_code)
source_code = source_code.splitl... | Compute line(s) numbers and starting/ending columns
from a start/end offset. All numbers start from 1.
Not done in an efficient way |
def _detect_bytelen_from_str(s):
# type: (str) -> int
""" _detect_bytelen_from_str returns the length of the machine
representation of an AbstractUVarIntField starting at the beginning
of s and which is assumed to expand over multiple bytes
(value > _max_prefix_value).
... | _detect_bytelen_from_str returns the length of the machine
representation of an AbstractUVarIntField starting at the beginning
of s and which is assumed to expand over multiple bytes
(value > _max_prefix_value).
@param str s: the string to parse. It is assumed that it is a multiby... |
def get_as_integer_with_default(self, key, default_value):
"""
Converts map element into an integer or returns default value if conversion is not possible.
:param key: an index of element to get.
:param default_value: the default value
:return: integer value ot the element or ... | Converts map element into an integer or returns default value if conversion is not possible.
:param key: an index of element to get.
:param default_value: the default value
:return: integer value ot the element or default value if conversion is not supported. |
def schwefelmult(self, x, pen_fac=1e4):
"""multimodal Schwefel function with domain -500..500"""
y = [x] if isscalar(x[0]) else x
N = len(y[0])
f = array([418.9829 * N - 1.27275661e-5 * N - sum(x * np.sin(np.abs(x)**0.5))
+ pen_fac * sum((abs(x) > 500) * (abs(x) - 500)**2... | multimodal Schwefel function with domain -500..500 |
def fetch_object_from_db_by_pk(self,
obj: Any,
table: str,
fieldlist: Sequence[str],
pkvalue: Any) -> bool:
"""Fetches object from database table by PK value. Writes back t... | Fetches object from database table by PK value. Writes back to
object. Returns True/False for success/failure. |
def get_cpu_info_json():
'''
Returns the CPU info by using the best sources of information for your OS.
Returns the result in a json string
'''
import json
output = None
# If running under pyinstaller, run normally
if getattr(sys, 'frozen', False):
info = _get_cpu_info_internal()
output = json.dumps(info... | Returns the CPU info by using the best sources of information for your OS.
Returns the result in a json string |
def _pick_statement(self, block_address, stmt_idx):
"""
Include a statement in the final slice.
:param int block_address: Address of the basic block.
:param int stmt_idx: Statement ID.
"""
# TODO: Support context-sensitivity
# Sanity check
if n... | Include a statement in the final slice.
:param int block_address: Address of the basic block.
:param int stmt_idx: Statement ID. |
def project_delete_notif(self, tenant_id, tenant_name):
"""Tenant Delete notification. """
if not self.fw_init:
return
rtr_name = '_'.join([fw_constants.TENANT_EDGE_RTR, tenant_name])
self.os_helper.delete_router_by_name(rtr_name, tenant_id) | Tenant Delete notification. |
def stream_close(self, listenKey):
"""Close out a user data stream.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#close-user-data-stream-user_stream
:param listenKey: required
:type listenKey: str
:returns: API response
.. code-... | Close out a user data stream.
https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#close-user-data-stream-user_stream
:param listenKey: required
:type listenKey: str
:returns: API response
.. code-block:: python
{}
:raise... |
def get_ftype_counts(self):
"""
Return counts of unique ftypes in this object.
.. deprecated:: 0.23.0
This is useful for SparseDataFrame or for DataFrames containing
sparse arrays.
Returns
-------
dtype : Series
Series with the count of colu... | Return counts of unique ftypes in this object.
.. deprecated:: 0.23.0
This is useful for SparseDataFrame or for DataFrames containing
sparse arrays.
Returns
-------
dtype : Series
Series with the count of columns with each type and
sparsity (den... |
def select_fds(read_fds, timeout, selector=AutoSelector):
"""
Wait for a list of file descriptors (`read_fds`) to become ready for
reading. This chooses the most appropriate select-tool for use in
prompt-toolkit.
"""
# Map to ensure that we return the objects that were passed in originally.
... | Wait for a list of file descriptors (`read_fds`) to become ready for
reading. This chooses the most appropriate select-tool for use in
prompt-toolkit. |
def officialPriceSSE(symbols=None, on_data=None, token='', version=''):
'''The Official Price message is used to disseminate the IEX Official Opening and Closing Prices.
These messages will be provided only for IEX Listed Securities.
https://iexcloud.io/docs/api/#deep-official-price
Args:
sym... | The Official Price message is used to disseminate the IEX Official Opening and Closing Prices.
These messages will be provided only for IEX Listed Securities.
https://iexcloud.io/docs/api/#deep-official-price
Args:
symbols (string); Tickers to request
on_data (function): Callback on data
... |
def iodp_srm_lore(srm_file, dir_path=".", input_dir_path="",noave=False,comp_depth_key='Depth CSF-B (m)',\
meas_file="srm_arch_measurements.txt", spec_file="srm_arch_specimens.txt",\
samp_file='srm_arch_samples.txt',site_file='srm_arch_sites.txt',lat="",lon=""):
"""
Convert IODP a... | Convert IODP archive half measurement files into MagIC file(s).
Parameters
----------
srm_file : str
input csv file downloaded from LIMS online repository
dir_path : str
output directory, default "."
input_dir_path : str
input file directory IF different from dir_path, defau... |
def evaluate(self, values):
''' Evaluates the expression to an integer
values is a dictionnary that associates n-bit variables to integer
values. Every symbolic variables used in the expression must be
represented.
For instance, let x and y 4-bit variables, and e = x+y:
... | Evaluates the expression to an integer
values is a dictionnary that associates n-bit variables to integer
values. Every symbolic variables used in the expression must be
represented.
For instance, let x and y 4-bit variables, and e = x+y:
>>> mba = MBA(4)
>>> x = mba.... |
def real_nvp_default_template(hidden_layers,
shift_only=False,
activation=tf.nn.relu,
name=None,
*args, # pylint: disable=keyword-arg-before-vararg
**kwargs):
"""Build... | Build a scale-and-shift function using a multi-layer neural network.
This will be wrapped in a make_template to ensure the variables are only
created once. It takes the `d`-dimensional input x[0:d] and returns the `D-d`
dimensional outputs `loc` ("mu") and `log_scale` ("alpha").
The default template does not ... |
def date_in_range(date1, date2, range):
"""Check if two date objects are within a specific range"""
date_obj1 = convert_date(date1)
date_obj2 = convert_date(date2)
return (date_obj2 - date_obj1).days <= range | Check if two date objects are within a specific range |
def update_logging_config(context, log_name=None, file_name='worker.log'):
"""Update python logging settings from config.
By default, this sets the ``scriptworker`` log settings, but this will
change if some other package calls this function or specifies the ``log_name``.
* Use formatting from config ... | Update python logging settings from config.
By default, this sets the ``scriptworker`` log settings, but this will
change if some other package calls this function or specifies the ``log_name``.
* Use formatting from config settings.
* Log to screen if ``verbose``
* Add a rotating logfile from con... |
def write_transcriptions(utterances: List[Utterance],
tgt_dir: Path, ext: str, lazy: bool) -> None:
""" Write the utterance transcriptions to files in the tgt_dir. Is lazy and
checks if the file already exists.
Args:
utterances: A list of Utterance objects to be written.
... | Write the utterance transcriptions to files in the tgt_dir. Is lazy and
checks if the file already exists.
Args:
utterances: A list of Utterance objects to be written.
tgt_dir: The directory in which to write the text of the utterances,
one file per utterance.
ext: The file ... |
def transit_update_key(self, name, min_decryption_version=None, min_encryption_version=None, deletion_allowed=None,
mount_point='transit'):
"""POST /<mount_point>/keys/<name>/config
:param name:
:type name:
:param min_decryption_version:
:type min_decr... | POST /<mount_point>/keys/<name>/config
:param name:
:type name:
:param min_decryption_version:
:type min_decryption_version:
:param min_encryption_version:
:type min_encryption_version:
:param deletion_allowed:
:type deletion_allowed:
:param mount... |
def score_small_straight_yatzy(dice: List[int]) -> int:
"""
Small straight scoring according to yatzy rules
"""
dice_set = set(dice)
if _are_two_sets_equal({1, 2, 3, 4, 5}, dice_set):
return sum(dice)
return 0 | Small straight scoring according to yatzy rules |
def checkform (form, env):
"""Check form data. throw exception on error
Be sure to NOT print out any user-given data as HTML code, so use
only plain strings as exception text."""
# check lang support
if "language" in form:
lang = formvalue(form, 'language')
if lang in _supported_lang... | Check form data. throw exception on error
Be sure to NOT print out any user-given data as HTML code, so use
only plain strings as exception text. |
def register_timer_task_in_sec(self, task, second):
"""Registers a new timer task
:param task: function to be run at a specified second from now
:param second: how many seconds to wait before the timer is triggered
"""
# Python time is in float
second_in_float = float(second)
expiration = t... | Registers a new timer task
:param task: function to be run at a specified second from now
:param second: how many seconds to wait before the timer is triggered |
def resendFaxRN_multi(self, CorpNum, OrgRequestNum, SenderNum, SenderName, Receiver, ReserveDT=None, UserID=None,
title=None, RequestNum=None):
""" ν©μ€ μ μ‘
args
CorpNum : νλΉνμ μ¬μ
μλ²νΈ
OrgRequestNum : μλ³Έ ν©μ€ μ μ‘μ ν λΉν μ μ‘μμ²λ²νΈ
SenderNum... | ν©μ€ μ μ‘
args
CorpNum : νλΉνμ μ¬μ
μλ²νΈ
OrgRequestNum : μλ³Έ ν©μ€ μ μ‘μ ν λΉν μ μ‘μμ²λ²νΈ
SenderNum : λ°μ μ λ²νΈ
SenderName : λ°μ μλͺ
Receiver : μμ μμ 보 λ°°μ΄
ReserveDT : μμ½μκ°(νμ yyyyMMddHHmmss)
UserID : νλΉνμ μμ΄λ
... |
def interp(self, date: timetools.Date) -> float:
"""Perform a linear value interpolation for the given `date` and
return the result.
Instantiate a 1-dimensional |SeasonalParameter| object:
>>> from hydpy.core.parametertools import SeasonalParameter
>>> class Par(SeasonalParamet... | Perform a linear value interpolation for the given `date` and
return the result.
Instantiate a 1-dimensional |SeasonalParameter| object:
>>> from hydpy.core.parametertools import SeasonalParameter
>>> class Par(SeasonalParameter):
... NDIM = 1
... TYPE = float
... |
def upload_from_stream(self, filename, source, chunk_size_bytes=None,
metadata=None, session=None):
"""Uploads a user file to a GridFS bucket.
Reads the contents of the user file from `source` and uploads
it to the file `filename`. Source can be a string or file-like ... | Uploads a user file to a GridFS bucket.
Reads the contents of the user file from `source` and uploads
it to the file `filename`. Source can be a string or file-like object.
For example::
my_db = MongoClient().test
fs = GridFSBucket(my_db)
file_id = fs.upload_from_... |
def _make_scm(current_target):
"""
Create an Scm for a component.
Arguments
component - The component being operated on.
"""
# pylint: disable=protected-access
tool_key = devpipeline_core.toolsupport.choose_tool_key(
current_target, devpipeline_scm._SCM_TOOL_KEYS
)
return d... | Create an Scm for a component.
Arguments
component - The component being operated on. |
def type_list(self, index_name):
'''
List the types available in an index
'''
request = self.session
url = 'http://%s:%s/%s/_mapping' % (self.host, self.port, index_name)
response = request.get(url)
if request.status_code == 200:
return response[index_... | List the types available in an index |
def getDescsV2(flags, fs_list=(), hs_list=(), ss_list=(), os_list=()):
"""
Return a FunctionFS descriptor suitable for serialisation.
flags (int)
Any combination of VIRTUAL_ADDR, EVENTFD, ALL_CTRL_RECIP,
CONFIG0_SETUP.
{fs,hs,ss,os}_list (list of descriptors)
Instances of the fo... | Return a FunctionFS descriptor suitable for serialisation.
flags (int)
Any combination of VIRTUAL_ADDR, EVENTFD, ALL_CTRL_RECIP,
CONFIG0_SETUP.
{fs,hs,ss,os}_list (list of descriptors)
Instances of the following classes:
{fs,hs,ss}_list:
USBInterfaceDescriptor
... |
def get_for(self, historics_id, with_estimate=None):
""" Get the historic query for the given ID
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param historics_id: playback id of the query
:type historics_id: str
:return... | Get the historic query for the given ID
Uses API documented at http://dev.datasift.com/docs/api/rest-api/endpoints/historicsget
:param historics_id: playback id of the query
:type historics_id: str
:return: dict of REST API output with headers attached
:rtyp... |
def obj(extract=None, child_transform=None, transform=None):
"""Returns a partial of get_obj that only needs a source argument."""
return lambda source: get_obj(source, extract, child_transform, transform) | Returns a partial of get_obj that only needs a source argument. |
def convert_ulog2kml(ulog_file_name, output_file_name, position_topic_name=
'vehicle_gps_position', colors=_kml_default_colors, altitude_offset=0,
minimum_interval_s=0.1, style=None, camera_trigger_topic_name=None):
"""
Coverts and ULog file to a CSV file.
:param u... | Coverts and ULog file to a CSV file.
:param ulog_file_name: The ULog filename to open and read
:param output_file_name: KML Output file name
:param position_topic_name: either name of a topic (must have 'lon', 'lat' &
'alt' fields), or a list of topic names
:param colors: lambda function wit... |
def row_coordinates(self, X):
"""Returns the row principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
# Check input
if self.check_input:
utils.check_array(X, dtype=[str, np.number])
# Prepare input
X = self._prepare_input(X)
return... | Returns the row principal coordinates. |
def mpi_fork(n, extra_mpi_args=[]):
"""Re-launches the current script with workers
Returns "parent" for original parent, "child" for MPI children
"""
if n <= 1:
return "child"
if os.getenv("IN_MPI") is None:
env = os.environ.copy()
env.update(
MKL_NUM_THREADS="1",... | Re-launches the current script with workers
Returns "parent" for original parent, "child" for MPI children |
async def patch_register(self, register: Dict, request: 'Request'):
"""
Store all options in the "choices" sub-register. We store both the
text and the potential intent, in order to match both regular
quick reply clicks but also the user typing stuff on his keyboard that
matches ... | Store all options in the "choices" sub-register. We store both the
text and the potential intent, in order to match both regular
quick reply clicks but also the user typing stuff on his keyboard that
matches more or less the content of quick replies. |
def _gen(self, optimized, splitstring):
"""Generates a new random object generated from the nonterminal
Args:
optimized (bool): mode of operation - if enabled not all
CNF rules are included (mitigate O(n^3))
splitstring (bool): A boolean for enabling o... | Generates a new random object generated from the nonterminal
Args:
optimized (bool): mode of operation - if enabled not all
CNF rules are included (mitigate O(n^3))
splitstring (bool): A boolean for enabling or disabling
Returns:
str: The g... |
def samefile(file1, file2):
# type: (str, str) -> bool
"""Provide an alternative for os.path.samefile on Windows/Python2"""
if hasattr(os.path, 'samefile'):
return os.path.samefile(file1, file2)
else:
path1 = os.path.normcase(os.path.abspath(file1))
path2 = os.path.normcase(os.pa... | Provide an alternative for os.path.samefile on Windows/Python2 |
def ripple_carry_add(A, B, cin=0):
"""Return symbolic logic for an N-bit ripple carry adder."""
if len(A) != len(B):
raise ValueError("expected A and B to be equal length")
ss, cs = list(), list()
for i, a in enumerate(A):
c = (cin if i == 0 else cs[i-1])
ss.append(a ^ B[i] ^ c)
... | Return symbolic logic for an N-bit ripple carry adder. |
def operation_upload(uploader, sources, verify, do_compile, do_file, do_restart):
"""The upload operation"""
sources, destinations = destination_from_source(sources)
if len(destinations) == len(sources):
if uploader.prepare():
for filename, dst in zip(sources, destinations):
... | The upload operation |
def find_untranscribed_wavs(wav_path: Path, transcription_path: Path, label_type: str) -> List[str]:
"""Find the prefixes for all the wav files that do not have an associated transcription
Args:
wav_path: Path to search for wav files in
transcription_path: Path to search for transcriptions in
... | Find the prefixes for all the wav files that do not have an associated transcription
Args:
wav_path: Path to search for wav files in
transcription_path: Path to search for transcriptions in
label_type: The type of labels for transcriptions. Eg "phonemes" "phonemes_and_tones"
Returns:
... |
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
... | Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None |
def cfg_intf(self, protocol_interface, phy_interface=None):
"""Called by application to add an interface to the list. """
self.intf_list.append(protocol_interface)
self.cfg_lldp_interface(protocol_interface, phy_interface) | Called by application to add an interface to the list. |
def single_gate_matrix(gate, params=None):
"""Get the matrix for a single qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
array: A numpy array representing the matrix
"""
# Converting sym to floats improves the... | Get the matrix for a single qubit.
Args:
gate(str): the single qubit gate name
params(list): the operation parameters op['params']
Returns:
array: A numpy array representing the matrix |
def plot_composition(df, intervals, axes=None):
"""
Plot time series of generics and label underlying instruments which
these series are composed of.
Parameters:
-----------
df: pd.DataFrame
DataFrame of time series to be plotted. Each column is a generic time
series.
interv... | Plot time series of generics and label underlying instruments which
these series are composed of.
Parameters:
-----------
df: pd.DataFrame
DataFrame of time series to be plotted. Each column is a generic time
series.
intervals: pd.DataFrame
A DataFrame including information ... |
def asMIMEString(self):
"""
Return a mime-multipart representation of:
- callgrind profiling statistics (cachegrind.out.pprofile)
- any SQL query issued via ZMySQLDA (query_*.sql)
- any persistent object load via ZODB.Connection (ZODB_setstate.txt)
- any path argument giv... | Return a mime-multipart representation of:
- callgrind profiling statistics (cachegrind.out.pprofile)
- any SQL query issued via ZMySQLDA (query_*.sql)
- any persistent object load via ZODB.Connection (ZODB_setstate.txt)
- any path argument given to unrestrictedTraverse
(unrest... |
def _PathStripPrefix(self, path):
"""Strips the prefix from a path.
Args:
path (str): Windows path to strip the prefix from.
Returns:
str: path without the prefix or None if the path is not supported.
"""
if path.startswith('\\\\.\\') or path.startswith('\\\\?\\'):
if len(path) <... | Strips the prefix from a path.
Args:
path (str): Windows path to strip the prefix from.
Returns:
str: path without the prefix or None if the path is not supported. |
def update(self, records, context):
"""
Updates the modified data in the database for the
inputted record. If the dryRun flag is specified then
the command will be logged but not executed.
:param record | <orb.Table>
lookup | <orb.LookupOptions>
... | Updates the modified data in the database for the
inputted record. If the dryRun flag is specified then
the command will be logged but not executed.
:param record | <orb.Table>
lookup | <orb.LookupOptions>
options | <orb.Context>
:retu... |
def delete_package(owner, repo, identifier):
"""Delete a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
_, _, headers = client.packages_delete_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratelimits.maybe_rate_li... | Delete a package in a repository. |
def _yass_vars(self):
""" Global variables """
utc = arrow.utcnow()
return {
"NAME": __title__,
"VERSION": __version__,
"URL": __uri__,
"GENERATOR": "%s %s" % (__title__, __version__),
"YEAR": utc.year
} | Global variables |
def _make_inc_temp(self, suffix="", prefix="", directory_name="/tmp/ray"):
"""Return a incremental temporary file name. The file is not created.
Args:
suffix (str): The suffix of the temp file.
prefix (str): The prefix of the temp file.
directory_name (str) : The bas... | Return a incremental temporary file name. The file is not created.
Args:
suffix (str): The suffix of the temp file.
prefix (str): The prefix of the temp file.
directory_name (str) : The base directory of the temp file.
Returns:
A string of file name. If ... |
def adapt_timefield_value(self, value):
"""
Transform a time value to an object compatible with what is expected
by the backend driver for time columns.
"""
if value is None:
return None
# SQL Server doesn't support microseconds
if isinstance(value, st... | Transform a time value to an object compatible with what is expected
by the backend driver for time columns. |
def _cli_check_family(family, data_dir):
'''Checks that a basis set family exists and if not, raises a helpful exception'''
if family is None:
return None
family = family.lower()
if not family in api.get_families(data_dir):
errstr = "Basis set family '" + family + "' does not exist.\n"... | Checks that a basis set family exists and if not, raises a helpful exception |
def _add_node(self, node):
"""Add a new node to node_list and give the node an ID.
Args:
node: An instance of Node.
Returns:
node_id: An integer.
"""
node_id = len(self.node_list)
self.node_to_id[node] = node_id
self.node_list.append(node)
... | Add a new node to node_list and give the node an ID.
Args:
node: An instance of Node.
Returns:
node_id: An integer. |
def cnst_AT(self, Y):
r"""Compute :math:`A^T \mathbf{y}` where
.. math::
A^T \mathbf{y} = \left( \begin{array}{cc} A_0^T & A_1^T
\end{array} \right) \left( \begin{array}{c} \mathbf{y}_0
\\ \mathbf{y}_1 \end{array} \right) = A_0^T \mathbf{y}_0 +
A_1^T \mathbf{... | r"""Compute :math:`A^T \mathbf{y}` where
.. math::
A^T \mathbf{y} = \left( \begin{array}{cc} A_0^T & A_1^T
\end{array} \right) \left( \begin{array}{c} \mathbf{y}_0
\\ \mathbf{y}_1 \end{array} \right) = A_0^T \mathbf{y}_0 +
A_1^T \mathbf{y}_1 \;\;. |
def asset_add_asset(self, *args, **kwargs):
"""Add more assets to the asset.
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_asset:
return
dialog = AssetAdderDialog(asset=self.cur_asset)
dialog.exec_()
assets = dialog.ass... | Add more assets to the asset.
:returns: None
:rtype: None
:raises: None |
def commit(self):
"""
Put the document into the new state.
"""
if self.textAfter is None:
# If this is the first 'commit' call then do not make
# any changes but store the current document state
# and its style.
line, col = self.qteWidget.g... | Put the document into the new state. |
def addmember(self, value):
"""Adds a single member to this group's list of members.
Tries to convert to :class:`tincan.Agent`
:param value: The member to add to this group
:type value: :class:`tincan.Agent`
"""
if value is not None and not isinstance(value, Agent):
... | Adds a single member to this group's list of members.
Tries to convert to :class:`tincan.Agent`
:param value: The member to add to this group
:type value: :class:`tincan.Agent` |
def source_raw_reset(self):
"""Return input and raw source and perform a full reset.
"""
out = self.source
out_r = self.source_raw
self.reset()
return out, out_r | Return input and raw source and perform a full reset. |
def group_list():
'''
.. versionadded:: 2016.11.0
Lists all groups known by pacman on this system
CLI Example:
.. code-block:: bash
salt '*' pkg.group_list
'''
ret = {'installed': [],
'partially_installed': [],
'available': []}
# find out what's available
... | .. versionadded:: 2016.11.0
Lists all groups known by pacman on this system
CLI Example:
.. code-block:: bash
salt '*' pkg.group_list |
def _adjust_probability_vec_best(population, fitnesses, probability_vec,
adjust_rate):
"""Shift probabilities towards the best solution."""
best_solution = max(zip(fitnesses, population))[1]
# Shift probabilities towards best solution
return _adjust(probability_vec, bes... | Shift probabilities towards the best solution. |
def to_fs_path(uri):
"""Returns the filesystem path of the given URI.
Will handle UNC paths and normalize windows drive letters to lower-case. Also
uses the platform specific path separator. Will *not* validate the path for
invalid characters and semantics. Will *not* look at the scheme of this URI.
... | Returns the filesystem path of the given URI.
Will handle UNC paths and normalize windows drive letters to lower-case. Also
uses the platform specific path separator. Will *not* validate the path for
invalid characters and semantics. Will *not* look at the scheme of this URI. |
def remove_var(var):
'''
Remove a variable from the make.conf
Return a dict containing the new value for the variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.remove_var 'LINGUAS'
... | Remove a variable from the make.conf
Return a dict containing the new value for the variable::
{'<variable>': {'old': '<old-value>',
'new': '<new-value>'}}
CLI Example:
.. code-block:: bash
salt '*' makeconf.remove_var 'LINGUAS' |
def parse(self, wsdl):
"""Parse the given C{wsdl} data and build the associated schemas.
@param wdsl: A string containing the raw xml of the WDSL definition
to parse.
@return: A C{dict} mapping response type names to their schemas.
"""
parser = etree.XMLParser(remove... | Parse the given C{wsdl} data and build the associated schemas.
@param wdsl: A string containing the raw xml of the WDSL definition
to parse.
@return: A C{dict} mapping response type names to their schemas. |
def panel_index(time, panels, names=None):
"""
Returns a multi-index suitable for a panel-like DataFrame.
Parameters
----------
time : array-like
Time index, does not have to repeat
panels : array-like
Panel index, does not have to repeat
names : list, optional
List ... | Returns a multi-index suitable for a panel-like DataFrame.
Parameters
----------
time : array-like
Time index, does not have to repeat
panels : array-like
Panel index, does not have to repeat
names : list, optional
List containing the names of the indices
Returns
--... |
def hostname(self):
"""str: hostname of the current session."""
hostname_artifact = self._hostnames.get(self.CURRENT_SESSION, None)
if not hostname_artifact:
return ''
return hostname_artifact.name or '' | str: hostname of the current session. |
def edit(self, title=None, body=None, assignee=None, state=None,
milestone=None, labels=None):
"""Edit this issue.
:param str title: Title of the issue
:param str body: markdown formatted body (description) of the issue
:param str assignee: login name of user the issue shou... | Edit this issue.
:param str title: Title of the issue
:param str body: markdown formatted body (description) of the issue
:param str assignee: login name of user the issue should be assigned
to
:param str state: accepted values: ('open', 'closed')
:param int mileston... |
def load_public_key(source):
"""
Loads a public key into a PublicKey object
:param source:
A byte string of file contents, a unicode string filename or an
asn1crypto.keys.PublicKeyInfo object
:raises:
ValueError - when any of the parameters contain an invalid value
Type... | Loads a public key into a PublicKey object
:param source:
A byte string of file contents, a unicode string filename or an
asn1crypto.keys.PublicKeyInfo object
:raises:
ValueError - when any of the parameters contain an invalid value
TypeError - when any of the parameters are of... |
def specific_gravity(self, value):
""" Set the relative weight of the solid """
value = clean_float(value)
if value is None:
return
specific_gravity = self._calc_specific_gravity()
if specific_gravity is not None and not ct.isclose(specific_gravity, value, rel_tol=sel... | Set the relative weight of the solid |
def extract_response(raw_response):
"""Extract requests response object.
only extract those status_code in [200, 300).
:param raw_response: a requests.Resposne object.
:return: content of response.
"""
data = urlread(raw_response)
if is_success_response(raw_response):
return data
... | Extract requests response object.
only extract those status_code in [200, 300).
:param raw_response: a requests.Resposne object.
:return: content of response. |
def _runner(self, job, runtime_context):
""" Job running thread. """
try:
job.run(runtime_context)
except WorkflowException as err:
_logger.exception("Got workflow error")
self.exceptions.append(err)
except Exception as err: # pylint: disable=broad-ex... | Job running thread. |
def receive_delivered(self, delivered: Delivered):
""" Handle a Delivered message.
The Delivered message is how the UDP transport guarantees persistence
by the partner node. The message itself is not part of the raiden
protocol, but it's required by this transport to provide the require... | Handle a Delivered message.
The Delivered message is how the UDP transport guarantees persistence
by the partner node. The message itself is not part of the raiden
protocol, but it's required by this transport to provide the required
properties. |
def simple_wcs(px_x, px_y, ra_deg, dec_deg, px_scale_deg_px, rot_deg,
cdbase=[1, 1]):
"""Calculate a set of WCS keywords for a 2D simple instrument FITS
file with a 'standard' RA/DEC pixel projection.
Parameters
----------
px_x
(ZERO-based) reference pixel of field in X
... | Calculate a set of WCS keywords for a 2D simple instrument FITS
file with a 'standard' RA/DEC pixel projection.
Parameters
----------
px_x
(ZERO-based) reference pixel of field in X
(usually center of field)
px_y
(ZERO-based) reference pixel of field in Y
(usually c... |
def contains(polygon, point):
"""
Tests whether point lies within the polygon
"""
in_hole = functools.reduce(
lambda P, Q: P and Q,
[interior.covers(point) for interior in polygon.interiors]
) if polygon.interiors else False
return polygon.covers(p... | Tests whether point lies within the polygon |
def _get_storage_resource(self):
"""Gets the SmartStorage resource if exists.
:raises: IloCommandNotSupportedError if the resource SmartStorage
doesn't exist.
:returns the tuple of SmartStorage URI, Headers and settings.
"""
system = self._get_host_details()
... | Gets the SmartStorage resource if exists.
:raises: IloCommandNotSupportedError if the resource SmartStorage
doesn't exist.
:returns the tuple of SmartStorage URI, Headers and settings. |
def get_block(self, x, y, z):
"""Get a block from relative x,y,z."""
sy,by = divmod(y, 16)
section = self.get_section(sy)
if section == None:
return None
return section.get_block(x, by, z) | Get a block from relative x,y,z. |
def get_institutes_trend_graph_urls(start, end):
""" Get all institute trend graphs. """
graph_list = []
for institute in Institute.objects.all():
urls = get_institute_trend_graph_url(institute, start, end)
urls['institute'] = institute
graph_list.append(urls)
return graph_list | Get all institute trend graphs. |
def minion_runner(self, load):
'''
Execute a runner from a minion, return the runner's function data
'''
if 'peer_run' not in self.opts:
return {}
if not isinstance(self.opts['peer_run'], dict):
return {}
if any(key not in load for key in ('fun', '... | Execute a runner from a minion, return the runner's function data |
def _increment_last_byte(data):
"""Get the last byte in the array and increment it
:param bytes_string:
:return:
"""
if not isinstance(data, bytes_types):
if isinstance(data, six.string_types):
data = data.encode('utf-8')
else:
data = six.b(str(data))
s =... | Get the last byte in the array and increment it
:param bytes_string:
:return: |
def run_wait(name, location='\\'):
r'''
Run a scheduled task and return when the task finishes
:param str name: The name of the task to run.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\S... | r'''
Run a scheduled task and return when the task finishes
:param str name: The name of the task to run.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\System32\tasks).
:return: True if s... |
def common(self, other):
'''
Return the common part of these two mults. This is the largest mult
which can be safely subtracted from both the originals. The multiplier
on this mult could be zero: this is the case if, for example, the
multiplicands disagree.
'''
if self.multiplicand == other.multiplica... | Return the common part of these two mults. This is the largest mult
which can be safely subtracted from both the originals. The multiplier
on this mult could be zero: this is the case if, for example, the
multiplicands disagree. |
def exists(self, bucket_name, object_name):
"""
Checks for the existence of a file in Google Cloud Storage.
:param bucket_name: The Google cloud storage bucket where the object is.
:type bucket_name: str
:param object_name: The name of the blob_name to check in the Google cloud
... | Checks for the existence of a file in Google Cloud Storage.
:param bucket_name: The Google cloud storage bucket where the object is.
:type bucket_name: str
:param object_name: The name of the blob_name to check in the Google cloud
storage bucket.
:type object_name: str |
def force_delete_file(file_path):
''' force delete a file '''
if os.path.isfile(file_path):
try:
os.remove(file_path)
return file_path
except:
return FileSystemUtils.add_unique_postfix(file_path)
else:
... | force delete a file |
def list_containers(self, page_size=None):
"""
Lists the containers visible to this client.
Containers are returned in lexicographical order.
:rtype: :class:`.Container` iterator
"""
params = {}
if page_size is not None:
params['limit'] = page_size
... | Lists the containers visible to this client.
Containers are returned in lexicographical order.
:rtype: :class:`.Container` iterator |
def bed_to_interval(orig_bed, bam_file):
"""Add header and format BED bait and target files for Picard if necessary.
"""
with open(orig_bed) as in_handle:
line = in_handle.readline()
if line.startswith("@"):
yield orig_bed
else:
with pysam.Samfile(bam_file, "rb") as bam_handl... | Add header and format BED bait and target files for Picard if necessary. |
def for_version(self, version_guid):
"""
Return a UsageLocator for the same block in a different branch of the course.
"""
return self.replace(course_key=self.course_key.for_version(version_guid)) | Return a UsageLocator for the same block in a different branch of the course. |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._tab is not None:
return False
if self._payment is not None:
return False
if self._request_reference_split_the_bill is not None:
return False
return True | :rtype: bool |
def _RunClientAction(self, action, request, parser_factory, path_type):
"""Runs the client action with the request and parses the result."""
responses = list(action(request))
if parser_factory is None:
return responses
# parse the responses
parsed_responses = []
for response in respons... | Runs the client action with the request and parses the result. |
def get_listener_count(self):
"""Returns the number of listeners on the network"""
return _number(
_extract(
self._request(self.ws_prefix + ".getInfo", cacheable=True), "listeners"
)
) | Returns the number of listeners on the network |
def get_sites(self, domain=None, show=True, proxy=None, timeout=0):
"""
GET Wikimedia sites via Extension:SiteMatrix
https://www.mediawiki.org/wiki/Extension:SiteMatrix
Optional params:
- [domain]: filter sites on this domain, e.g. 'wiktionary.org'
Optional arguments:
... | GET Wikimedia sites via Extension:SiteMatrix
https://www.mediawiki.org/wiki/Extension:SiteMatrix
Optional params:
- [domain]: filter sites on this domain, e.g. 'wiktionary.org'
Optional arguments:
- [show]: <bool> echo page data if true
- [proxy]: <str> use this HTTP pr... |
def to_dict(self):
"""
Get a dictionary of the attributes of this Language object, which
can be useful for constructing a similar object.
"""
if self._dict is not None:
return self._dict
result = {}
for key in self.ATTRIBUTES:
value = geta... | Get a dictionary of the attributes of this Language object, which
can be useful for constructing a similar object. |
def p_radl(self, t):
"""radl : radl radl_sentence
| radl_sentence"""
if len(t) == 2:
t[0] = RADL()
t[0].add(t[1])
else:
t[0] = t[1]
t[0].add(t[2]) | radl : radl radl_sentence
| radl_sentence |
def register_for_deleted_asset(self, asset_id):
"""Registers for notification of a deleted asset.
``AssetReceiver.deletedAssets()`` is invoked when the specified
asset is deleted or removed from this repository.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to
... | Registers for notification of a deleted asset.
``AssetReceiver.deletedAssets()`` is invoked when the specified
asset is deleted or removed from this repository.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to
monitor
raise: NullArgument - ``asset_id`` is ... |
def tarzip_data(root_dir, output_file):
"""
Given a root directory, adds all its children to a tarball (compressed)
:param root_dir:
:param output_file:
:return:
"""
if root_dir is None:
raise ValueError('Must be a valid directory path', root_dir)
t = tarfile.open(output_file, '... | Given a root directory, adds all its children to a tarball (compressed)
:param root_dir:
:param output_file:
:return: |
def _get_tree_paths(tree, node_id, depth=0):
"""
Returns all paths through the tree as list of node_ids
"""
if node_id == _tree.TREE_LEAF:
raise ValueError("Invalid node_id %s" % _tree.TREE_LEAF)
left_child = tree.children_left[node_id]
right_child = tree.children_right[node_id]
if... | Returns all paths through the tree as list of node_ids |
def as_bookmark_class(xso_class):
"""
Decorator to register `xso_class` as a custom bookmark class.
This is necessary to store and retrieve such bookmarks.
The registered class must be a subclass of the abstract base class
:class:`Bookmark`.
:raises TypeError: if `xso_class` is not a subclass ... | Decorator to register `xso_class` as a custom bookmark class.
This is necessary to store and retrieve such bookmarks.
The registered class must be a subclass of the abstract base class
:class:`Bookmark`.
:raises TypeError: if `xso_class` is not a subclass of :class:`Bookmark`. |
def configure(self, options, conf):
"""Configure which kinds of exceptions trigger plugin.
"""
self.conf = conf
self.enabled = options.epdb_debugErrors or options.epdb_debugFailures
self.enabled_for_errors = options.epdb_debugErrors
self.enabled_for_failures = options.epd... | Configure which kinds of exceptions trigger plugin. |
def _set_map_apply(self, v, load=False):
"""
Setter method for map_apply, mapped from YANG variable /qos_mpls/map_apply (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_map_apply is considered as a private
method. Backends looking to populate this variable... | Setter method for map_apply, mapped from YANG variable /qos_mpls/map_apply (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_map_apply is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_map_apply(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.