code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _getViewerPrivateApplication(self):
"""
Get the L{PrivateApplication} object for the logged-in user who is
viewing this resource, as indicated by its C{username} attribute.
This is highly problematic because it precludes the possibility of
separating the stores of the viewer... | Get the L{PrivateApplication} object for the logged-in user who is
viewing this resource, as indicated by its C{username} attribute.
This is highly problematic because it precludes the possibility of
separating the stores of the viewer and the viewee into separate
processes, and it is o... |
def execute(command, return_output=True, log_file=None, log_settings=None, error_logfile=None, timeout=None, line_function=None, poll_timing = 0.01, logger=None, working_folder=None, env=None):
"""
Execute a program and logs standard output into a file.
:param return_output: returns the STDOUT... | Execute a program and logs standard output into a file.
:param return_output: returns the STDOUT value if True or returns the return code
:param logfile: path where log file should be written ( displayed on STDOUT if not set)
:param error_logfile: path where error log file ... |
def get_asset_admin_session_for_repository(self, repository_id=None, *args, **kwargs):
"""Gets an asset administration session for the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
return: (osid.repository.AssetAdminSession) - an
AssetAdminSessio... | Gets an asset administration session for the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
return: (osid.repository.AssetAdminSession) - an
AssetAdminSession
raise: NotFound - repository_id not found
raise: NullArgument - repository_id ... |
def installed_plugins(only_conda=False):
'''
.. versionadded:: 0.20
Parameters
----------
only_conda : bool, optional
Only consider plugins that are installed **as Conda packages**.
.. versionadded:: 0.22
Returns
-------
list
List of properties corresponding to... | .. versionadded:: 0.20
Parameters
----------
only_conda : bool, optional
Only consider plugins that are installed **as Conda packages**.
.. versionadded:: 0.22
Returns
-------
list
List of properties corresponding to each available plugin that is
**installed**.... |
def pformat(arg, width=79, height=24, compact=True):
"""Return pretty formatted representation of object as string.
Whitespace might be altered.
"""
if height is None or height < 1:
height = 1024
if width is None or width < 1:
width = 256
npopt = numpy.get_printoptions()
n... | Return pretty formatted representation of object as string.
Whitespace might be altered. |
def varOr(population, toolbox, lambda_, cxpb, mutpb):
"""Part of an evolutionary algorithm applying only the variation part
(crossover, mutation **or** reproduction). The modified individuals have
their fitness invalidated. The individuals are cloned so returned
population is independent of the input po... | Part of an evolutionary algorithm applying only the variation part
(crossover, mutation **or** reproduction). The modified individuals have
their fitness invalidated. The individuals are cloned so returned
population is independent of the input population.
:param population: A list of individuals to var... |
def reset_time_estimate(self, **kwargs):
"""Resets estimated time for the object to 0 seconds.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the... | Resets estimated time for the object to 0 seconds.
Args:
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabTimeTrackingError: If the time tracking update cannot be done |
def get_configuration(basename='scriptabit.cfg', parents=None):
"""Parses and returns the program configuration options,
taken from a combination of ini-style config file, and
command line arguments.
Args:
basename (str): The base filename.
parents (list): A list of ArgumentParser objec... | Parses and returns the program configuration options,
taken from a combination of ini-style config file, and
command line arguments.
Args:
basename (str): The base filename.
parents (list): A list of ArgumentParser objects whose arguments
should also be included in the configura... |
def compute(self, motor_pct: float, tm_diff: float) -> float:
"""
:param motor_pct: Percentage of power for motor in range [1..-1]
:param tm_diff: Time elapsed since this function was last called
:returns: velocity
"""
appliedVoltage = self._no... | :param motor_pct: Percentage of power for motor in range [1..-1]
:param tm_diff: Time elapsed since this function was last called
:returns: velocity |
def subset_sum(x, R):
"""Subsetsum by splitting
:param x: table of values
:param R: target value
:returns bool: if there is a subsequence of x with total sum R
:complexity: :math:`O(n^{\\lceil n/2 \\rceil})`
"""
k = len(x) // 2 # divide input
Y = [v for v in part_sum(x[:k])]... | Subsetsum by splitting
:param x: table of values
:param R: target value
:returns bool: if there is a subsequence of x with total sum R
:complexity: :math:`O(n^{\\lceil n/2 \\rceil})` |
def make_rpc_call(self, rpc_command):
"""
Allow a user to query a device directly using XML-requests.
:param rpc_command: (str) rpc command such as:
<Get><Operational><LLDP><NodeTable></NodeTable></LLDP></Operational></Get>
"""
# ~~~ hack: ~~~
... | Allow a user to query a device directly using XML-requests.
:param rpc_command: (str) rpc command such as:
<Get><Operational><LLDP><NodeTable></NodeTable></LLDP></Operational></Get> |
def get_form(self, step=None, data=None, files=None):
"""
Constructs the form for a given `step`. If no `step` is defined, the
current step will be determined automatically.
The form will be initialized using the `data` argument to prefill the
new form. If needed, instance or qu... | Constructs the form for a given `step`. If no `step` is defined, the
current step will be determined automatically.
The form will be initialized using the `data` argument to prefill the
new form. If needed, instance or queryset (for `ModelForm` or
`ModelFormSet`) will be added too. |
def tracks(self):
"""
Tracks list context
:return: Tracks list context
"""
if self._tracks is None:
self._tracks = TrackList(self.version, self.id)
return self._tracks | Tracks list context
:return: Tracks list context |
def to_html(self, codebase):
"""
Convert this `FunctionDoc` to HTML.
"""
body = ''
for section in ('params', 'options', 'exceptions'):
val = getattr(self, section)
if val:
body += '<h5>%s</h5>\n<dl class = "%s">%s</dl>' % (
... | Convert this `FunctionDoc` to HTML. |
def keep_alive(self):
"""
Prevent immediate Broker shutdown while deferred functions remain.
"""
self._lock.acquire()
try:
return len(self._deferred)
finally:
self._lock.release() | Prevent immediate Broker shutdown while deferred functions remain. |
def dilworth(graph):
"""Decompose a DAG into a minimum number of chains by Dilworth
:param graph: directed graph in listlist or listdict format
:assumes: graph is acyclic
:returns: table giving for each vertex the number of its chains
:complexity: same as matching
"""
n = len(graph)
mat... | Decompose a DAG into a minimum number of chains by Dilworth
:param graph: directed graph in listlist or listdict format
:assumes: graph is acyclic
:returns: table giving for each vertex the number of its chains
:complexity: same as matching |
def parse_authorization_code_response(uri, state=None):
"""Parse authorization grant response URI into a dict.
If the resource owner grants the access request, the authorization
server issues an authorization code and delivers it to the client by
adding the following parameters to the query component o... | Parse authorization grant response URI into a dict.
If the resource owner grants the access request, the authorization
server issues an authorization code and delivers it to the client by
adding the following parameters to the query component of the
redirection URI using the ``application/x-www-form-ur... |
def consume(self, char):
"""
Consume a single character and advance the state as necessary.
"""
if self.state == "stream":
self._stream(char)
elif self.state == "escape":
self._escape_sequence(char)
elif self.state == "escape-lb":
self... | Consume a single character and advance the state as necessary. |
def get_content_item_inlines(plugins=None, base=BaseContentItemInline):
"""
Dynamically generate genuine django inlines for all registered content item types.
When the `plugins` parameter is ``None``, all plugin inlines are returned.
"""
COPY_FIELDS = (
'form', 'raw_id_fields', 'filter_verti... | Dynamically generate genuine django inlines for all registered content item types.
When the `plugins` parameter is ``None``, all plugin inlines are returned. |
def _authenticate_gssapi(credentials, sock_info):
"""Authenticate using GSSAPI.
"""
if not HAVE_KERBEROS:
raise ConfigurationError('The "kerberos" module must be '
'installed to use GSSAPI authentication.')
try:
username = credentials.username
pa... | Authenticate using GSSAPI. |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'text') and self.text is not None:
_dict['text'] = self.text
if hasattr(self, 'user') and self.user is not None:
_dict['user'] = self.user
return _dict | Return a json dictionary representing this model. |
def get_dilated_1d_attention_mask(
num_heads, block_size,
num_blocks, memory_size, gap_size,
name="dilated_mask"):
"""Dilated attention with a masking strategy."""
mask = np.ones((num_heads, block_size, 2*block_size), np.bool)
# now going over every row to do the right assignment of
# memory blocks... | Dilated attention with a masking strategy. |
def info(*messages):
"""
Prints the current GloTK module and a `message`.
Taken from biolite
"""
sys.stderr.write("%s.%s: " % get_caller_info())
sys.stderr.write(' '.join(map(str, messages)))
sys.stderr.write('\n') | Prints the current GloTK module and a `message`.
Taken from biolite |
def undo(self):
"""Undo the last metadata change.
Returns
-------
up : UpdateInfo instance
"""
args = self._undo_stack.back()
if args is None:
return
self._data = deepcopy(self._data_base)
for clusters, field, value, up, undo_state i... | Undo the last metadata change.
Returns
-------
up : UpdateInfo instance |
def get_alternative_nested_val(key_tuple, dict_obj):
"""Return a value from nested dicts by any path in the given keys tuple.
Parameters
---------
key_tuple : tuple
Describe all possible paths for extraction.
dict_obj : dict
The outer-most dict to extract from.
Returns
----... | Return a value from nested dicts by any path in the given keys tuple.
Parameters
---------
key_tuple : tuple
Describe all possible paths for extraction.
dict_obj : dict
The outer-most dict to extract from.
Returns
-------
value : object
The extracted value, if exist... |
def save(self):
"""Method that saves configuration parameter changes from instance of SHConfig class to global config class and
to `config.json` file.
Example of use case
``my_config = SHConfig()`` \n
``my_config.instance_id = '<new instance id>'`` \n
``my_co... | Method that saves configuration parameter changes from instance of SHConfig class to global config class and
to `config.json` file.
Example of use case
``my_config = SHConfig()`` \n
``my_config.instance_id = '<new instance id>'`` \n
``my_config.save()`` |
def f_lock_derived_parameters(self):
"""Locks all non-empty derived parameters"""
for par in self._derived_parameters.values():
if not par.f_is_empty():
par.f_lock() | Locks all non-empty derived parameters |
def unregister_editorstack(self, editorstack):
"""Removing editorstack only if it's not the last remaining"""
self.remove_last_focus_editorstack(editorstack)
if len(self.editorstacks) > 1:
index = self.editorstacks.index(editorstack)
self.editorstacks.pop(index)
... | Removing editorstack only if it's not the last remaining |
def _prep_sample_and_config(ldetail_group, fastq_dir, fastq_final_dir):
"""Prepare output fastq file and configuration for a single sample.
Only passes non-empty files through for processing.
"""
files = []
print("->", ldetail_group[0]["name"], len(ldetail_group))
for read in ["R1", "R2"]:
... | Prepare output fastq file and configuration for a single sample.
Only passes non-empty files through for processing. |
def send_rpc_sync(self, conn_id, address, rpc_id, payload, timeout):
"""Synchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
... | Synchronously send an RPC to this IOTile device
Args:
conn_id (int): A unique identifier that will refer to this connection
address (int): the address of the tile that we wish to send the RPC to
rpc_id (int): the 16-bit id of the RPC we want to call
payload (byte... |
def observed(cls, _func):
"""
Decorate methods to be observable. If they are called on an instance
stored in a property, the model will emit before and after
notifications.
"""
def wrapper(*args, **kwargs):
self = args[0]
assert(isinstance(self, O... | Decorate methods to be observable. If they are called on an instance
stored in a property, the model will emit before and after
notifications. |
def load(self, limit=9999):
""" Function list
Get the list of all interfaces
@param key: The targeted object
@param limit: The limit of items to return
@return RETURN: A ForemanItem list
"""
subItemList = self.api.list('{}/{}/{}'.format(self.parentObjName,
... | Function list
Get the list of all interfaces
@param key: The targeted object
@param limit: The limit of items to return
@return RETURN: A ForemanItem list |
def contourf(self, *args, **kwargs):
"""Plot contours.
If a 3D or higher Data object is passed, a lower dimensional
channel can be plotted, provided the ``squeeze`` of the channel
has ``ndim==2`` and the first two axes do not span dimensions
other than those spanned by that chan... | Plot contours.
If a 3D or higher Data object is passed, a lower dimensional
channel can be plotted, provided the ``squeeze`` of the channel
has ``ndim==2`` and the first two axes do not span dimensions
other than those spanned by that channel.
Parameters
----------
... |
def ntp_authentication_key_md5(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ntp = ET.SubElement(config, "ntp", xmlns="urn:brocade.com:mgmt:brocade-ntp")
authentication_key = ET.SubElement(ntp, "authentication-key")
keyid_key = ET.SubElement(au... | Auto Generated Code |
def directory(self):
"""Directory that holds this file"""
if self._directory is None:
self._directory = self.api._load_directory(self.cid)
return self._directory | Directory that holds this file |
def split_writable_text(encoder, text, encoding):
"""Splits off as many characters from the begnning of text as
are writable with "encoding". Returns a 2-tuple (writable, rest).
"""
if not encoding:
return None, text
for idx, char in enumerate(text):
if encoder.can_encode(encoding, ... | Splits off as many characters from the begnning of text as
are writable with "encoding". Returns a 2-tuple (writable, rest). |
def _flattenMergedProteins(proteins):
"""Return a set where merged protein entries in proteins are flattened.
:param proteins: an iterable of proteins, can contain merged protein entries
in the form of tuple([protein1, protein2]).
returns a set of protein entries, where all entries are strings
... | Return a set where merged protein entries in proteins are flattened.
:param proteins: an iterable of proteins, can contain merged protein entries
in the form of tuple([protein1, protein2]).
returns a set of protein entries, where all entries are strings |
def detail_get(self, session, fields=[], **kwargs):
'''taobao.logistics.orders.detail.get 批量查询物流订单,返回详细信息
查询物流订单的详细信息,涉及用户隐私字段。(注:该API主要是提供给卖家查询物流订单使用,买家查询物流订单,建议使用taobao.logistics.trace.search)'''
request = TOPRequest('taobao.logistics.orders.detail.get')
if not fields:
... | taobao.logistics.orders.detail.get 批量查询物流订单,返回详细信息
查询物流订单的详细信息,涉及用户隐私字段。(注:该API主要是提供给卖家查询物流订单使用,买家查询物流订单,建议使用taobao.logistics.trace.search) |
def _execute_and_process_stdout(self, args, shell, handler):
"""Executes adb commands and processes the stdout with a handler.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command th... | Executes adb commands and processes the stdout with a handler.
Args:
args: string or list of strings, program arguments.
See subprocess.Popen() documentation.
shell: bool, True to run this command through the system shell,
False to invoke it directly. See... |
def csv(ctx, force, threads, mapping, data):
""" Load CSV data into a grano instance using a mapping specification. """
# Find out how many lines there are (for the progress bar).
lines = 0
for line in DictReader(data):
lines += 1
data.seek(0)
# set up objects
mapping = yaml.load(m... | Load CSV data into a grano instance using a mapping specification. |
def collate(binder, ruleset=None, includes=None):
"""Given a ``Binder`` as ``binder``, collate the content into a new set
of models.
Returns the collated binder.
"""
html_formatter = SingleHTMLFormatter(binder, includes)
raw_html = io.BytesIO(bytes(html_formatter))
collated_html = io.BytesI... | Given a ``Binder`` as ``binder``, collate the content into a new set
of models.
Returns the collated binder. |
def _tls12_SHA256PRF(secret, label, seed, req_len):
"""
Provides the implementation of TLS 1.2 PRF function as
defined in section 5 of RFC 5246:
PRF(secret, label, seed) = P_SHA256(secret, label + seed)
Parameters are:
- secret: the secret used by the HMAC in the 2 expansion
fun... | Provides the implementation of TLS 1.2 PRF function as
defined in section 5 of RFC 5246:
PRF(secret, label, seed) = P_SHA256(secret, label + seed)
Parameters are:
- secret: the secret used by the HMAC in the 2 expansion
functions (S1 and S2 are the halves of this secret).
- label: s... |
def build_swagger12_handler(schema):
"""Builds a swagger12 handler or returns None if no schema is present.
:type schema: :class:`pyramid_swagger.model.SwaggerSchema`
:rtype: :class:`SwaggerHandler` or None
"""
if schema:
return SwaggerHandler(
op_for_request=schema.validators_f... | Builds a swagger12 handler or returns None if no schema is present.
:type schema: :class:`pyramid_swagger.model.SwaggerSchema`
:rtype: :class:`SwaggerHandler` or None |
def limitReal(x, max_denominator=1000000):
"""Creates an pysmt Real constant from x.
Args:
x (number): A number to be cast to a pysmt constant.
max_denominator (int, optional): The maximum size of the denominator.
Default 1000000.
Returns:
A Real constant with the given... | Creates an pysmt Real constant from x.
Args:
x (number): A number to be cast to a pysmt constant.
max_denominator (int, optional): The maximum size of the denominator.
Default 1000000.
Returns:
A Real constant with the given value and the denominator limited. |
def _energy_coeffs(m1, m2, chi1, chi2):
""" Return the center-of-mass energy coefficients up to 3.0pN (2.5pN spin)
"""
mtot = m1 + m2
eta = m1*m2 / (mtot*mtot)
chi = (m1*chi1 + m2*chi2) / mtot
chisym = (chi1 + chi2) / 2.
beta = (113.*chi - 76.*eta*chisym)/12.
sigma12 = 79.*eta*chi1*chi2/... | Return the center-of-mass energy coefficients up to 3.0pN (2.5pN spin) |
def _getnode(self, curie):
"""
Returns IRI, or blank node curie/iri depending on
self.skolemize_blank_node setting
:param curie: str id as curie or iri
:return:
"""
if re.match(r'^_:', curie):
if self.are_bnodes_skized is True:
node = ... | Returns IRI, or blank node curie/iri depending on
self.skolemize_blank_node setting
:param curie: str id as curie or iri
:return: |
def stop(self):
"""
Request thread to stop.
Does not wait for actual termination (use join() method).
"""
if self.is_alive():
self._can_run = False
self._stop_event.set()
self._profiler.total_time += time() - self._start_time
self._... | Request thread to stop.
Does not wait for actual termination (use join() method). |
def construct_nucmer_cmdline(
fname1,
fname2,
outdir=".",
nucmer_exe=pyani_config.NUCMER_DEFAULT,
filter_exe=pyani_config.FILTER_DEFAULT,
maxmatch=False,
):
"""Returns a tuple of NUCmer and delta-filter commands
The split into a tuple was made necessary by changes to SGE/OGE. The
de... | Returns a tuple of NUCmer and delta-filter commands
The split into a tuple was made necessary by changes to SGE/OGE. The
delta-filter command must now be run as a dependency of the NUCmer
command, and be wrapped in a Python script to capture STDOUT.
NOTE: This command-line writes output data to a subd... |
def abs_energy(self, x):
"""
As in tsfresh `abs_energy <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L390>`_ \
Returns the absolute energy of the time series which is the sum over the squared values\
.. math::
... | As in tsfresh `abs_energy <https://github.com/blue-yonder/tsfresh/blob/master/tsfresh/feature_extraction/\
feature_calculators.py#L390>`_ \
Returns the absolute energy of the time series which is the sum over the squared values\
.. math::
E=\\sum_{i=1,\ldots, n}x_... |
def triangle_area(e1, e2, e3):
"""
Get the area of triangle formed by three vectors.
Parameters are three three-dimensional numpy arrays representing
vectors of triangle's edges in Cartesian space.
:returns:
Float number, the area of the triangle in squared units of coordinates,
or... | Get the area of triangle formed by three vectors.
Parameters are three three-dimensional numpy arrays representing
vectors of triangle's edges in Cartesian space.
:returns:
Float number, the area of the triangle in squared units of coordinates,
or numpy array of shape of edges with one dim... |
def hide(input_image: Union[str, IO[bytes]], message: str):
"""
Hide a message (string) in an image.
Use the red portion of a pixel (r, g, b) tuple to
hide the message string characters as ASCII values.
The red value of the first pixel is used for message_length of the string.
"""
message_l... | Hide a message (string) in an image.
Use the red portion of a pixel (r, g, b) tuple to
hide the message string characters as ASCII values.
The red value of the first pixel is used for message_length of the string. |
def _determine_resource_pool(session, vm_):
'''
Called by create() used to determine resource pool
'''
resource_pool = ''
if 'resource_pool' in vm_.keys():
resource_pool = _get_pool(vm_['resource_pool'], session)
else:
pool = session.xenapi.pool.get_all()
if not pool:
... | Called by create() used to determine resource pool |
def cmd_annotate(self, argv, help):
"""Prints annotated config"""
parser = argparse.ArgumentParser(
prog="%s annotate" % self.progname,
description=help,
)
parser.parse_args(argv)
list(self.instances.values()) # trigger instance augmentation
for g... | Prints annotated config |
def milestones(self, extra_params=None):
"""
All Milestones in this Space
"""
# Default params
params = {
'per_page': settings.MAX_PER_PAGE,
}
if extra_params:
params.update(extra_params)
return self.api._get_... | All Milestones in this Space |
def setReturnParameter(self, name, type, namespace=None, element_type=0):
"""Set the return parameter description for the call info."""
parameter = ParameterInfo(name, type, namespace, element_type)
self.retval = parameter
return parameter | Set the return parameter description for the call info. |
def _get_adj_list_directional(self, umis, counts):
''' identify all umis within the hamming distance threshold
and where the counts of the first umi is > (2 * second umi counts)-1'''
adj_list = {umi: [] for umi in umis}
if self.fuzzy_match:
for umi1 in umis:
... | identify all umis within the hamming distance threshold
and where the counts of the first umi is > (2 * second umi counts)-1 |
def fix_microsoft (foo):
"""
fix special case for `c#`, `f#`, etc.; thanks Microsoft
"""
i = 0
bar = []
while i < len(foo):
text, lemma, pos, tag = foo[i]
if (text == "#") and (i > 0):
prev_tok = bar[-1]
prev_tok[0] += "#"
prev_tok[1] += "#"... | fix special case for `c#`, `f#`, etc.; thanks Microsoft |
def get_source_scanner(self, node):
"""Fetch the source scanner for the specified node
NOTE: "self" is the target being built, "node" is
the source file for which we want to fetch the scanner.
Implies self.has_builder() is true; again, expect to only be
called from locations w... | Fetch the source scanner for the specified node
NOTE: "self" is the target being built, "node" is
the source file for which we want to fetch the scanner.
Implies self.has_builder() is true; again, expect to only be
called from locations where this is already verified.
This fu... |
def cmd_rc(self, args):
'''handle RC value override'''
if len(args) != 2:
print("Usage: rc <channel|all> <pwmvalue>")
return
value = int(args[1])
if value > 65535 or value < -1:
raise ValueError("PWM value must be a positive integer between 0 and 65535... | handle RC value override |
def get_target_hash(target_filepath):
"""
<Purpose>
Compute the hash of 'target_filepath'. This is useful in conjunction with
the "path_hash_prefixes" attribute in a delegated targets role, which tells
us which paths it is implicitly responsible for.
The repository may optionally organize targets i... | <Purpose>
Compute the hash of 'target_filepath'. This is useful in conjunction with
the "path_hash_prefixes" attribute in a delegated targets role, which tells
us which paths it is implicitly responsible for.
The repository may optionally organize targets into hashed bins to ease
target delegations... |
def update_director(self, service_id, version_number, name_key, **kwargs):
"""Update the director for a particular service and version."""
body = self._formdata(kwargs, FastlyDirector.FIELDS)
content = self._fetch("/service/%s/version/%d/director/%s" % (service_id, version_number, name_key), method="PUT", body=bo... | Update the director for a particular service and version. |
def _substitute_default(s, new_value):
"""Replaces the default value in a parameter docstring by a new value.
The docstring must conform to the numpydoc style and have the form
"something (keyname=<value-to-replace>)"
If no matching pattern is found or ``new_value`` is None, return
the input untou... | Replaces the default value in a parameter docstring by a new value.
The docstring must conform to the numpydoc style and have the form
"something (keyname=<value-to-replace>)"
If no matching pattern is found or ``new_value`` is None, return
the input untouched.
Examples
--------
>>> _repl... |
def halt(self):
"""Halts any/all running operations"""
self.explorer.halt()
self.protocoler.halt()
self.bs_calibrator.halt()
self.tone_calibrator.halt()
self.charter.halt()
self.mphone_calibrator.halt() | Halts any/all running operations |
def build(self, tokenlist):
"""Build a Wikicode object from a list tokens and return it."""
self._tokens = tokenlist
self._tokens.reverse()
self._push()
while self._tokens:
node = self._handle_token(self._tokens.pop())
self._write(node)
return self... | Build a Wikicode object from a list tokens and return it. |
def get_returner_options(virtualname=None,
ret=None,
attrs=None,
**kwargs):
'''
Get the returner options from salt.
:param str virtualname: The returner virtualname (as returned
by __virtual__()
:param ret: result of the... | Get the returner options from salt.
:param str virtualname: The returner virtualname (as returned
by __virtual__()
:param ret: result of the module that ran. dict-like object
May contain a `ret_config` key pointing to a string
If a `ret_config` is specified, config options are read fro... |
def console_print_frame(
con: tcod.console.Console,
x: int,
y: int,
w: int,
h: int,
clear: bool = True,
flag: int = BKGND_DEFAULT,
fmt: str = "",
) -> None:
"""Draw a framed rectangle with optinal text.
This uses the default background color and blend mode to fill the
rectan... | Draw a framed rectangle with optinal text.
This uses the default background color and blend mode to fill the
rectangle and the default foreground to draw the outline.
`fmt` will be printed on the inside of the rectangle, word-wrapped.
If `fmt` is empty then no title will be drawn.
.. versionchang... |
def _grab_version(self):
"""Set the version to a non-development version."""
original_version = self.vcs.version
logger.debug("Extracted version: %s", original_version)
if original_version is None:
logger.critical('No version found.')
sys.exit(1)
suggestio... | Set the version to a non-development version. |
def _cfgs_to_read(self):
"""
reads config files from various locations to build final config.
"""
# use these files to extend/overwrite the conf_values.
# Last red file always overwrites existing values!
cfg = Config.DEFAULT_CONFIG_FILE_NAME
filenames = [
... | reads config files from various locations to build final config. |
def gen_find_method(ele_type, multiple=True, extra_maps=None):
"""
将 ele_type 转换成对应的元素查找方法
e.g::
make_elt(ele_type=name, False) => find_element_by_name
make_elt(ele_type=name, True) => find_elements_by_name
:param ele_type:
:type ele_type:
:param multiple:
:type multiple:
... | 将 ele_type 转换成对应的元素查找方法
e.g::
make_elt(ele_type=name, False) => find_element_by_name
make_elt(ele_type=name, True) => find_elements_by_name
:param ele_type:
:type ele_type:
:param multiple:
:type multiple:
:param extra_maps:
:type extra_maps:
:return: |
def raise_with_traceback(exc, traceback=Ellipsis):
"""
Raise exception with existing traceback.
If traceback is not passed, uses sys.exc_info() to get traceback.
"""
if traceback == Ellipsis:
_, _, traceback = sys.exc_info()
raise exc.with_traceback(traceback) | Raise exception with existing traceback.
If traceback is not passed, uses sys.exc_info() to get traceback. |
def read_json(filepath, intkeys=True, intvalues=True):
""" read text from filepath (`open(find_filepath(expand_filepath(fp)))`) then json.loads()
>>> read_json('HTTP_1.1 Status Code Definitions.html.json')
{'100': 'Continue',
'101': 'Switching Protocols',...
"""
d = json.load(ensure_open(... | read text from filepath (`open(find_filepath(expand_filepath(fp)))`) then json.loads()
>>> read_json('HTTP_1.1 Status Code Definitions.html.json')
{'100': 'Continue',
'101': 'Switching Protocols',... |
def encode_quopri(msg):
"""Encode the message's payload in quoted-printable.
Also, add an appropriate Content-Transfer-Encoding header.
"""
orig = msg.get_payload()
encdata = _qencode(orig)
msg.set_payload(encdata)
msg['Content-Transfer-Encoding'] = 'quoted-printable' | Encode the message's payload in quoted-printable.
Also, add an appropriate Content-Transfer-Encoding header. |
def fold(table, key, f, value=None, presorted=False, buffersize=None,
tempdir=None, cache=True):
"""
Reduce rows recursively via the Python standard :func:`reduce` function.
E.g.::
>>> import petl as etl
>>> table1 = [['id', 'count'],
... [1, 3],
... ... | Reduce rows recursively via the Python standard :func:`reduce` function.
E.g.::
>>> import petl as etl
>>> table1 = [['id', 'count'],
... [1, 3],
... [1, 5],
... [2, 4],
... [2, 8]]
>>> import operator
>>> table... |
def _value_formatter(self, float_format=None, threshold=None):
"""Returns a function to be applied on each value to format it
"""
# the float_format parameter supersedes self.float_format
if float_format is None:
float_format = self.float_format
# we are going to co... | Returns a function to be applied on each value to format it |
def _load_fits(self, h5file):
""" Loads fits from h5file and returns a dictionary of fits. """
fits = {}
for key in ['mf']:
fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file)
for key in ['chif', 'vf']:
fits[key] = self._load_vector_fit(key, h5file)
... | Loads fits from h5file and returns a dictionary of fits. |
def setbit(self, name, offset, value):
"""
Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
indicating the previous value of ``offset``.
"""
value = value and 1 or 0
return self.execute_command('SETBIT', name, offset, value) | Flag the ``offset`` in ``name`` as ``value``. Returns a boolean
indicating the previous value of ``offset``. |
def set_status(self, status: Status, increment_try_count: bool=True,
filename: str=None):
'''Mark the item with the given status.
Args:
status: a value from :class:`Status`.
increment_try_count: if True, increment the ``try_count``
value
... | Mark the item with the given status.
Args:
status: a value from :class:`Status`.
increment_try_count: if True, increment the ``try_count``
value |
def chain(first_converter, second_converter, strict: bool):
"""
Utility method to chain two converters. If any of them is already a ConversionChain, this method "unpacks" it
first. Note: the created conversion chain is created with the provided 'strict' flag, that may be different
from t... | Utility method to chain two converters. If any of them is already a ConversionChain, this method "unpacks" it
first. Note: the created conversion chain is created with the provided 'strict' flag, that may be different
from the ones of the converters (if compliant). For example you may chain a 'strict' c... |
def log_future_exceptions(logger, f, ignore=()):
"""Log any exceptions set to a future
Parameters
----------
logger : logging.Logger instance
logger.exception(...) is called if the future resolves with an exception
f : Future object
Future to be monitored for exceptions
ignore :... | Log any exceptions set to a future
Parameters
----------
logger : logging.Logger instance
logger.exception(...) is called if the future resolves with an exception
f : Future object
Future to be monitored for exceptions
ignore : Exception or tuple of Exception
Exptected excep... |
async def recv(self):
"""
Receive the next frame.
"""
if self.readyState != 'live':
raise MediaStreamError
frame = await self._queue.get()
if frame is None:
self.stop()
raise MediaStreamError
return frame | Receive the next frame. |
async def update(
self,
service_id: str,
version: str,
*,
image: str = None,
rollback: bool = False
) -> bool:
"""
Update a service.
If rollback is True image will be ignored.
Args:
service_id: ID or name of the service.
... | Update a service.
If rollback is True image will be ignored.
Args:
service_id: ID or name of the service.
version: Version of the service that you want to update.
rollback: Rollback the service to the previous service spec.
Returns:
True if succe... |
def sbo_version_source(self, slackbuilds):
"""Create sbo name with version
"""
sbo_versions, sources = [], []
for sbo in slackbuilds:
status(0.02)
sbo_ver = "{0}-{1}".format(sbo, SBoGrep(sbo).version())
sbo_versions.append(sbo_ver)
sources.... | Create sbo name with version |
def p_content(self, content):
'''content : TITLE opttexts VERSION opttexts sections
| TITLE STATESTAG VERSION opttexts states_sections'''
content[0] = self.doctype(content[1], content[3], content[4], content[5])
if self.toc:
self.toc.set_articles([a for a in conten... | content : TITLE opttexts VERSION opttexts sections
| TITLE STATESTAG VERSION opttexts states_sections |
def readMyEC2Tag(tagName, connection=None):
"""
Load an EC2 tag for the running instance & print it.
:param str tagName: Name of the tag to read
:param connection: Optional boto connection
"""
assert isinstance(tagName, basestring), ("tagName must be a string but is %r" % tagName)
# Load metadata. if ==... | Load an EC2 tag for the running instance & print it.
:param str tagName: Name of the tag to read
:param connection: Optional boto connection |
def exists(self):
"""
Call the exists command to check if the redis key exists for the current
field
"""
try:
key = self.key
except DoesNotExist:
"""
If the object doesn't exists anymore, its PK is deleted, so the
"self.key"... | Call the exists command to check if the redis key exists for the current
field |
def from_file(self, filename):
""" Uploads a file from a filename on your system.
:param filename: Path to file on your system.
Example:
>>> myimage.from_file('/path/to/dinner.png')
"""
mimetype = mimetypes.guess_type(filename)[0] or "application/octal-stream"
... | Uploads a file from a filename on your system.
:param filename: Path to file on your system.
Example:
>>> myimage.from_file('/path/to/dinner.png') |
def export(results_dir, filename, do_not_try_parsing, parameters):
"""
Export results to file.
An extension in filename is required to deduce the file type. If no
extension is specified, a directory tree export will be used. Note that
this command automatically tries to parse the simulation output.... | Export results to file.
An extension in filename is required to deduce the file type. If no
extension is specified, a directory tree export will be used. Note that
this command automatically tries to parse the simulation output.
Supported extensions:
.mat (Matlab file),
.npy (Numpy file),
... |
def _add(self, codeobj):
"""Add a child (statement) to this object."""
assert isinstance(codeobj, (CodeStatement, CodeExpression))
self.body._add(codeobj) | Add a child (statement) to this object. |
def _contains_cftime_datetimes(array) -> bool:
"""Check if an array contains cftime.datetime objects
"""
try:
from cftime import datetime as cftime_datetime
except ImportError:
return False
else:
if array.dtype == np.dtype('O') and array.size > 0:
sample = array.r... | Check if an array contains cftime.datetime objects |
def removeFriend(self, user):
""" Remove the specified user from all sharing.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
"""
user = self.user(user)
url = self.FRIENDUPDATE if user.friend else self.REMOVEINVITE
url = u... | Remove the specified user from all sharing.
Parameters:
user (str): MyPlexUser, username, email of the user to be added. |
def returns(schema):
"""Create a decorator for validating function return value.
Example::
@accepts(a=int, b=int)
@returns(int)
def f(a, b):
return a + b
:param schema: The schema for adapting a given parameter.
"""
validate = parse(schema).validate
@decora... | Create a decorator for validating function return value.
Example::
@accepts(a=int, b=int)
@returns(int)
def f(a, b):
return a + b
:param schema: The schema for adapting a given parameter. |
def check_url (aggregate):
"""Helper function waiting for URL queue."""
while True:
try:
aggregate.urlqueue.join(timeout=30)
break
except urlqueue.Timeout:
# Cleanup threads every 30 seconds
aggregate.remove_stopped_threads()
if not any... | Helper function waiting for URL queue. |
def attachment_both(self, files, parentid=None):
"""
Add child attachments using title, filename
Arguments:
One or more lists or tuples containing title, file path
An optional Item ID, which will create child attachments
"""
orig = self._attachment_template("impor... | Add child attachments using title, filename
Arguments:
One or more lists or tuples containing title, file path
An optional Item ID, which will create child attachments |
def getZoom(self, resolution):
"Return the zoom level for a given resolution"
assert resolution in self.RESOLUTIONS
return self.RESOLUTIONS.index(resolution) | Return the zoom level for a given resolution |
def start_workflow(name, config, *, queue=DefaultJobQueueName.Workflow,
clear_data_store=True, store_args=None):
""" Start a single workflow by sending it to the workflow queue.
Args:
name (str): The name of the workflow that should be started. Refers to the
name of the w... | Start a single workflow by sending it to the workflow queue.
Args:
name (str): The name of the workflow that should be started. Refers to the
name of the workflow file without the .py extension.
config (Config): Reference to the configuration object from which the
settings f... |
def head(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a HEAD request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Op... | Sends a HEAD request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Optional arguments that ``request`` takes.
:return: response object |
def make_request(self, url, method='get', headers=None, data=None,
callback=None, errors=STRICT, verify=False, timeout=None, **params):
"""
Reusable method for performing requests.
:param url - URL to request
:param method - request method, default is 'get'
:... | Reusable method for performing requests.
:param url - URL to request
:param method - request method, default is 'get'
:param headers - request headers
:param data - post data
:param callback - callback to be applied to response,
default callback will par... |
def find_local_boundary(tri, triangles):
r"""Find and return the outside edges of a collection of natural neighbor triangles.
There is no guarantee that this boundary is convex, so ConvexHull is not
sufficient in some situations.
Parameters
----------
tri: Object
A Delaunay Triangulati... | r"""Find and return the outside edges of a collection of natural neighbor triangles.
There is no guarantee that this boundary is convex, so ConvexHull is not
sufficient in some situations.
Parameters
----------
tri: Object
A Delaunay Triangulation
triangles: (N, ) array
List of... |
def _initialize_part_map(self):
"""Sets up assessmentPartMap with as much information as is initially available."""
self._my_map['assessmentParts'] = []
self._my_map['questions'] = []
item_ids = self._assessment_part.get_item_ids()
if item_ids.available():
# This is a... | Sets up assessmentPartMap with as much information as is initially available. |
def noaa_prompt_1():
"""
For converting LiPD files to NOAA, we need a couple more pieces of information to create the WDS links
:return str _project: Project name
:return float _version: Version number
"""
print("Enter the project information below. We'll use this to create the WDS URL")
pr... | For converting LiPD files to NOAA, we need a couple more pieces of information to create the WDS links
:return str _project: Project name
:return float _version: Version number |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.