positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def show_devices(verbose=False, **kwargs):
"""Show information about connected devices.
The verbose flag sets to verbose or not.
**kwargs are passed directly to the find() function.
"""
kwargs["find_all"] = True
devices = find(**kwargs)
strings = ""
for device in devices:
if not... | Show information about connected devices.
The verbose flag sets to verbose or not.
**kwargs are passed directly to the find() function. |
def as_cnpj(numero):
"""Formata um número de CNPJ. Se o número não for um CNPJ válido apenas
retorna o argumento sem qualquer modificação.
"""
_num = digitos(numero)
if is_cnpj(_num):
return '{}.{}.{}/{}-{}'.format(
_num[:2], _num[2:5], _num[5:8], _num[8:12], _num[12:])
r... | Formata um número de CNPJ. Se o número não for um CNPJ válido apenas
retorna o argumento sem qualquer modificação. |
def lx4num(string, first):
"""
Scan a string from a specified starting position for the
end of a number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lx4num_c.html
:param string: Any character string.
:type string: str
:param first: First character to scan from in string.
:t... | Scan a string from a specified starting position for the
end of a number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lx4num_c.html
:param string: Any character string.
:type string: str
:param first: First character to scan from in string.
:type first: int
:return: last and nc... |
def apply_effect_expression_filters(
effects,
gene_expression_dict,
gene_expression_threshold,
transcript_expression_dict,
transcript_expression_threshold):
"""
Filter collection of varcode effects by given gene
and transcript expression thresholds.
Parameters
... | Filter collection of varcode effects by given gene
and transcript expression thresholds.
Parameters
----------
effects : varcode.EffectCollection
gene_expression_dict : dict
gene_expression_threshold : float
transcript_expression_dict : dict
transcript_expression_threshold : float |
def apply_sphinx_configurations(app):
'''
This method applies the various configurations users place in their ``conf.py``, in
the dictionary ``exhale_args``. The error checking seems to be robust, and
borderline obsessive, but there may very well be some glaring flaws.
When the user requests for t... | This method applies the various configurations users place in their ``conf.py``, in
the dictionary ``exhale_args``. The error checking seems to be robust, and
borderline obsessive, but there may very well be some glaring flaws.
When the user requests for the ``treeView`` to be created, this method is also... |
def run(vcf, conf_fns, lua_fns, data, basepath=None, decomposed=False):
"""Annotate a VCF file using vcfanno (https://github.com/brentp/vcfanno)
decomposed -- if set to true we'll convert allele based output into single values
to match alleles and make compatible with vcf2db
(https://github.com/qui... | Annotate a VCF file using vcfanno (https://github.com/brentp/vcfanno)
decomposed -- if set to true we'll convert allele based output into single values
to match alleles and make compatible with vcf2db
(https://github.com/quinlan-lab/vcf2db/issues/14) |
def spinn5_eth_coords(width, height, root_x=0, root_y=0):
"""Generate a list of board coordinates with Ethernet connectivity in a
SpiNNaker machine.
Specifically, generates the coordinates for the Ethernet connected chips of
SpiNN-5 boards arranged in a standard torus topology.
.. warning::
... | Generate a list of board coordinates with Ethernet connectivity in a
SpiNNaker machine.
Specifically, generates the coordinates for the Ethernet connected chips of
SpiNN-5 boards arranged in a standard torus topology.
.. warning::
In general, applications should use
:py:class:`rig.mac... |
def distance_inches_continuous(self):
"""
Measurement of the distance detected by the sensor,
in inches.
The sensor will continue to take measurements so
they are available for future reads.
Prefer using the equivalent :meth:`UltrasonicSensor.distance_inches` property.
... | Measurement of the distance detected by the sensor,
in inches.
The sensor will continue to take measurements so
they are available for future reads.
Prefer using the equivalent :meth:`UltrasonicSensor.distance_inches` property. |
def ace(args):
"""
%prog ace bamfile fastafile
convert bam format to ace format. This often allows the remapping to be
assessed as a denovo assembly format. bam file needs to be indexed. also
creates a .mates file to be used in amos/bambus, and .astat file to mark
whether the contig is unique o... | %prog ace bamfile fastafile
convert bam format to ace format. This often allows the remapping to be
assessed as a denovo assembly format. bam file needs to be indexed. also
creates a .mates file to be used in amos/bambus, and .astat file to mark
whether the contig is unique or repetitive based on A-sta... |
def _compute(self):
"""Compute r min max and labels position"""
delta = 2 * pi / self._len if self._len else 0
self._x_pos = [.5 * pi + i * delta for i in range(self._len + 1)]
for serie in self.all_series:
serie.points = [(v, self._x_pos[i])
for i... | Compute r min max and labels position |
def get_local_extrema(self, find_min=True, threshold_frac=None,
threshold_abs=None):
"""
Get all local extrema fractional coordinates in charge density,
searching for local minimum by default. Note that sites are NOT grouped
symmetrically.
Args:
... | Get all local extrema fractional coordinates in charge density,
searching for local minimum by default. Note that sites are NOT grouped
symmetrically.
Args:
find_min (bool): True to find local minimum else maximum, otherwise
find local maximum.
threshold... |
def lists(self, value, key=None):
"""
Get a list with the values of a given key
:rtype: list
"""
results = map(lambda x: x[value], self._items)
return list(results) | Get a list with the values of a given key
:rtype: list |
def _match_with_pandas(filtered, matcher):
"""Find matches in a set using Pandas' library."""
import pandas
data = [fl.to_dict() for fl in filtered]
if not data:
return []
df = pandas.DataFrame(data)
df = df.sort_values(['uuid'])
cdfs = []
criteria = matcher.matching_criteri... | Find matches in a set using Pandas' library. |
def get_input_score_end_range_metadata(self):
"""Gets the metadata for the input score start range.
return: (osid.Metadata) - metadata for the input score start
range
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented from template for... | Gets the metadata for the input score start range.
return: (osid.Metadata) - metadata for the input score start
range
*compliance: mandatory -- This method must be implemented.* |
def preprocess(self, xs):
"""Preprocess a single example.
Firstly, tokenization and the supplied preprocessing pipeline is applied. Since
this field is always sequential, the result is a list. Then, each element of
the list is preprocessed using ``self.nesting_field.preprocess`` and the... | Preprocess a single example.
Firstly, tokenization and the supplied preprocessing pipeline is applied. Since
this field is always sequential, the result is a list. Then, each element of
the list is preprocessed using ``self.nesting_field.preprocess`` and the resulting
list is returned.
... |
def boardToString(self, margins=None):
"""
return a string representation of the current board.
"""
if margins is None:
margins = {}
b = self.board
rg = range(b.size())
left = ' '*margins.get('left', 0)
s = '\n'.join(
[left + ' '.j... | return a string representation of the current board. |
def resume_session_logging(self):
"""Resume session logging."""
self._chain.ctrl.set_session_log(self.session_fd)
self.log("Session logging resumed") | Resume session logging. |
def _from_arrays(self, offset, cells, cell_type, points, deep=True):
"""
Create VTK unstructured grid from numpy arrays
Parameters
----------
offset : np.ndarray dtype=np.int64
Array indicating the start location of each cell in the cells
array.
... | Create VTK unstructured grid from numpy arrays
Parameters
----------
offset : np.ndarray dtype=np.int64
Array indicating the start location of each cell in the cells
array.
cells : np.ndarray dtype=np.int64
Array of cells. Each cell contains the num... |
async def kick_chat_member(self, chat_id: typing.Union[base.Integer, base.String], user_id: base.Integer,
until_date: typing.Union[base.Integer, None] = None) -> base.Boolean:
"""
Use this method to kick a user from a group, a supergroup or a channel.
In the case o... | Use this method to kick a user from a group, a supergroup or a channel.
In the case of supergroups and channels, the user will not be able to return to the group
on their own using invite links, etc., unless unbanned first.
The bot must be an administrator in the chat for this to work and must ... |
def newDtd(self, name, ExternalID, SystemID):
"""Creation of a new DTD for the external subset. To create an
internal subset, use xmlCreateIntSubset(). """
ret = libxml2mod.xmlNewDtd(self._o, name, ExternalID, SystemID)
if ret is None:raise treeError('xmlNewDtd() failed')
__tm... | Creation of a new DTD for the external subset. To create an
internal subset, use xmlCreateIntSubset(). |
def index_search_document(self, *, index):
"""
Create or replace search document in named index.
Checks the local cache to see if the document has changed,
and if not aborts the update, else pushes to ES, and then
resets the local cache. Cache timeout is set as "cache_expiry"
... | Create or replace search document in named index.
Checks the local cache to see if the document has changed,
and if not aborts the update, else pushes to ES, and then
resets the local cache. Cache timeout is set as "cache_expiry"
in the settings, and defaults to 60s. |
def squad(R_in, t_in, t_out):
"""Spherical "quadrangular" interpolation of rotors with a cubic spline
This is the best way to interpolate rotations. It uses the analog
of a cubic spline, except that the interpolant is confined to the
rotor manifold in a natural way. Alternative methods involving
... | Spherical "quadrangular" interpolation of rotors with a cubic spline
This is the best way to interpolate rotations. It uses the analog
of a cubic spline, except that the interpolant is confined to the
rotor manifold in a natural way. Alternative methods involving
interpolation of other coordinates on... |
def getConsole(rh):
"""
Get the virtual machine's console output.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
... | Get the virtual machine's console output.
Input:
Request Handle with the following properties:
function - 'CMDVM'
subfunction - 'CMD'
userid - userid of the virtual machine
Output:
Request Handle updated with the results.
Return code - 0: ok, non-zero... |
def offset_to_line(self, offset):
"""
Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column
numbers.
"""
offset = max(0, min(self._text_len, offset))
line_index = bisect.bisect_right(self._line_offsets, offset) - 1
return (line_index + 1, offset - self._lin... | Converts 0-based character offset to pair (line, col) of 1-based line and 0-based column
numbers. |
def set_display(self, brightness=100, brightness_mode="auto"):
"""
allows to modify display state (change brightness)
:param int brightness: display brightness [0, 100] (default: 100)
:param str brightness_mode: the brightness mode of the display
[aut... | allows to modify display state (change brightness)
:param int brightness: display brightness [0, 100] (default: 100)
:param str brightness_mode: the brightness mode of the display
[auto, manual] (default: auto) |
def create_doc_jar(self, target, open_jar, version):
"""Returns a doc jar if either scala or java docs are available for the given target."""
javadoc = self._java_doc(target)
scaladoc = self._scala_doc(target)
if javadoc or scaladoc:
jar_path = self.artifact_path(open_jar, version, suffix='-javado... | Returns a doc jar if either scala or java docs are available for the given target. |
def base_elts(elt, cls=None, depth=None):
"""Get bases elements of the input elt.
- If elt is an instance, get class and all base classes.
- If elt is a method, get all base methods.
- If elt is a class, get all base classes.
- In other case, get an empty list.
:param elt: supposed inherited e... | Get bases elements of the input elt.
- If elt is an instance, get class and all base classes.
- If elt is a method, get all base methods.
- If elt is a class, get all base classes.
- In other case, get an empty list.
:param elt: supposed inherited elt.
:param cls: cls from where find attribute... |
def variants(ctx, snpeff):
"""Print the variants in a vcf"""
head = ctx.parent.head
vcf_handle = ctx.parent.handle
outfile = ctx.parent.outfile
silent = ctx.parent.silent
print_headers(head, outfile=outfile, silent=silent)
for line in vcf_handle:
print_variant(variant_line=... | Print the variants in a vcf |
def start(self) -> None:
"""Connect websocket to deCONZ."""
if self.config:
self.websocket = self.ws_client(
self.loop, self.session, self.host,
self.config.websocketport, self.async_session_handler)
self.websocket.start()
else:
... | Connect websocket to deCONZ. |
def set_silent(self):
"""Silence most messages."""
self.set_icntl(1, -1) # output stream for error msgs
self.set_icntl(2, -1) # otuput stream for diagnostic msgs
self.set_icntl(3, -1) # output stream for global info
self.set_icntl(4, 0) | Silence most messages. |
def _unstructure_mapping(self, mapping):
"""Convert a mapping of attr classes to primitive equivalents."""
# We can reuse the mapping class, so dicts stay dicts and OrderedDicts
# stay OrderedDicts.
dispatch = self._unstructure_func.dispatch
return mapping.__class__(
... | Convert a mapping of attr classes to primitive equivalents. |
def summarize_sequence_file(source_file, file_type=None):
"""
Summarizes a sequence file, returning a tuple containing the name,
whether the file is an alignment, minimum sequence length, maximum
sequence length, average length, number of sequences.
"""
is_alignment = True
avg_length = None
... | Summarizes a sequence file, returning a tuple containing the name,
whether the file is an alignment, minimum sequence length, maximum
sequence length, average length, number of sequences. |
def close(self):
"""Close open resources."""
super(RarExtFile, self).close()
if self._fd:
self._fd.close()
self._fd = None | Close open resources. |
def _get_none_or_value(value):
'''
PRIVATE METHOD
Checks to see if the value of a primitive or built-in container such as
a list, dict, set, tuple etc is empty or none. None type is returned if the
value is empty/None/False. Number data types that are 0 will return None.
value : obj
The... | PRIVATE METHOD
Checks to see if the value of a primitive or built-in container such as
a list, dict, set, tuple etc is empty or none. None type is returned if the
value is empty/None/False. Number data types that are 0 will return None.
value : obj
The primitive or built-in container to evaluat... |
def build(source, target, versions, current_name, is_root):
"""Build Sphinx docs for one version. Includes Versions class instance with names/urls in the HTML context.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
... | Build Sphinx docs for one version. Includes Versions class instance with names/urls in the HTML context.
:raise HandledError: If sphinx-build fails. Will be logged before raising.
:param str source: Source directory to pass to sphinx-build.
:param str target: Destination directory to write documentation t... |
def get_vnetwork_portgroups_input_vcenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups")
config = get_vnetwork_portgroups
input = ET.SubElement(get_vnetwork_portgroups, "input")
... | Auto Generated Code |
def populateFromRow(self, featureSetRecord):
"""
Populates the instance variables of this FeatureSet from the specified
DB row.
"""
self._dbFilePath = featureSetRecord.dataurl
self.setAttributesJson(featureSetRecord.attributes)
self._db = Gff3DbBackend(self._dbFil... | Populates the instance variables of this FeatureSet from the specified
DB row. |
def _get_all_file_versions(self, secure_data_path, limit=None):
"""
Convenience function that returns a generator yielding the contents of all versions of
a file and its version info
secure_data_path -- full path to the file in the safety deposit box
limit -- Default(100), limit... | Convenience function that returns a generator yielding the contents of all versions of
a file and its version info
secure_data_path -- full path to the file in the safety deposit box
limit -- Default(100), limits how many records to be returned from the api at once. |
def ensure(self, connection, func, *args, **kwargs):
"""Perform an operation until success
Repeats in the face of connection errors, pursuant to retry policy.
"""
channel = None
while 1:
try:
if channel is None:
channel = connectio... | Perform an operation until success
Repeats in the face of connection errors, pursuant to retry policy. |
def _initialize(self, funs_to_tally, length):
"""Create a group named ``chain#`` to store all data for this chain."""
chain = self.nchains
self._chains[chain] = self._h5file.create_group(
'/', 'chain%d' % chain, 'chain #%d' % chain)
for name, fun in six.iteritems(funs_to_ta... | Create a group named ``chain#`` to store all data for this chain. |
def returns(self):
"""Gets a string showing the return type and modifiers for the
function in a nice display format."""
kind = "({}) ".format(self.kind) if self.kind is not None else ""
mods = ", ".join(self.modifiers) + " "
dtype = self.dtype if self.dtype is not None else... | Gets a string showing the return type and modifiers for the
function in a nice display format. |
def off(self, group):
"""Turn the LED off for a group."""
asyncio.ensure_future(self._send_led_on_off_request(group, 0),
loop=self._loop) | Turn the LED off for a group. |
def sort(ctx):
"""Sort the variants of a vcf file"""
head = ctx.parent.head
vcf_handle = ctx.parent.handle
outfile = ctx.parent.outfile
silent = ctx.parent.silent
print_headers(head, outfile=outfile, silent=silent)
for line in sort_variants(vcf_handle):
print_variant(variant_line=l... | Sort the variants of a vcf file |
def get_POST_data(self):
"""
Returns:
dict: POST data, which can be sent to webform using \
:py:mod:`urllib` or similar library
"""
self._postprocess()
# some fields need to be remapped (depends on type of media)
self._apply_mapping(
... | Returns:
dict: POST data, which can be sent to webform using \
:py:mod:`urllib` or similar library |
def _read_record(self, f, blk, chans):
"""Read raw data from a single EDF channel.
Parameters
----------
i_chan : int
index of the channel to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Re... | Read raw data from a single EDF channel.
Parameters
----------
i_chan : int
index of the channel to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Returns
-------
numpy.ndarray
... |
def agent_version(self):
"""Get the version of the Juju machine agent.
May return None if the agent is not yet available.
"""
version = self.safe_data['agent-status']['version']
if version:
return client.Number.from_json(version)
else:
return None | Get the version of the Juju machine agent.
May return None if the agent is not yet available. |
def modules(cls):
"""Collect all the public class attributes.
All class attributes should be a DI modules, this method collects them
and returns as a list.
:return: list of DI modules
:rtype: list[Union[Module, Callable]]
"""
members = inspect.getmembers(cls, la... | Collect all the public class attributes.
All class attributes should be a DI modules, this method collects them
and returns as a list.
:return: list of DI modules
:rtype: list[Union[Module, Callable]] |
def explain(self, sql=None, sql_args=None):
"""
Runs EXPLAIN on this query
:type sql: str or None
:param sql: The sql to run EXPLAIN on. If None is specified, the query will
use ``self.get_sql()``
:type sql_args: dict or None
:param sql_args: A dictionary of... | Runs EXPLAIN on this query
:type sql: str or None
:param sql: The sql to run EXPLAIN on. If None is specified, the query will
use ``self.get_sql()``
:type sql_args: dict or None
:param sql_args: A dictionary of the arguments to be escaped in the query. If None and
... |
def _generate_serializer_signatures(self, obj_name):
"""Emits the signatures of the serializer object's serializing functions."""
serial_signature = fmt_signature(
func='serialize',
args=fmt_func_args_declaration([(
'instance', '{} *'.format(obj_name))]),
... | Emits the signatures of the serializer object's serializing functions. |
def __get_job_status(self):
"""Return the Kubernetes job status"""
# Figure out status and return it
job = self.__get_job()
if "succeeded" in job.obj["status"] and job.obj["status"]["succeeded"] > 0:
job.scale(replicas=0)
if self.print_pod_logs_on_exit:
... | Return the Kubernetes job status |
def fgrad_y(self, y, return_precalc=False):
"""
gradient of f w.r.t to y ([N x 1])
:returns: Nx1 vector of derivatives, unless return_precalc is true,
then it also returns the precomputed stuff
"""
d = self.d
mpsi = self.psi
# vectorized version
... | gradient of f w.r.t to y ([N x 1])
:returns: Nx1 vector of derivatives, unless return_precalc is true,
then it also returns the precomputed stuff |
def find(self, vName):
"""Get the reference number of a vdata given its name.
The vdata can then be opened (attached) by passing this
reference number to the attach() method.
Args::
vName Name of the vdata for which the reference number
is needed. vdatas... | Get the reference number of a vdata given its name.
The vdata can then be opened (attached) by passing this
reference number to the attach() method.
Args::
vName Name of the vdata for which the reference number
is needed. vdatas names are not guaranteed to be
... |
def sample_correlations(self):
"""Returns an `ExpMatrix` containing all pairwise sample correlations.
Returns
-------
`ExpMatrix`
The sample correlation matrix.
"""
C = np.corrcoef(self.X.T)
corr_matrix = ExpMatrix(genes=self.samples, samples=self.sa... | Returns an `ExpMatrix` containing all pairwise sample correlations.
Returns
-------
`ExpMatrix`
The sample correlation matrix. |
def _cachedSqlType(cls):
"""
Cache the sqlType() into class, because it's heavy used in `toInternal`.
"""
if not hasattr(cls, "_cached_sql_type"):
cls._cached_sql_type = cls.sqlType()
return cls._cached_sql_type | Cache the sqlType() into class, because it's heavy used in `toInternal`. |
def app_factory(global_conf, **local_conf):
"""
Returns the Pulsar WSGI application.
"""
configuration_file = global_conf.get("__file__", None)
webapp = init_webapp(ini_path=configuration_file, local_conf=local_conf)
return webapp | Returns the Pulsar WSGI application. |
def getCiphertextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion.
"""
plaintext_length = self.getPlaintextLen(ciphertext)
ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION
... | Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion. |
def save(self, obj, label, format='text'):
""" Save or update obj as pkl file with name label
format can be 'text' or 'pickle'.
"""
# initialize hidden state directory
objloc = '{0}/{1}'.format(self.statedir, label)
with open(objloc, 'w') as fp:
if format... | Save or update obj as pkl file with name label
format can be 'text' or 'pickle'. |
def update_handler(feeds):
'''Update all cross-referencing filters results for feeds and others, related to them.
Intended to be called from non-Feed update hooks (like new Post saving).'''
# Check if this call is a result of actions initiated from
# one of the hooks in a higher frame (resulting in recursion)... | Update all cross-referencing filters results for feeds and others, related to them.
Intended to be called from non-Feed update hooks (like new Post saving). |
def get_agents_by_genus_type(self, agent_genus_type):
"""Gets an ``AgentList`` corresponding to the given agent genus ``Type`` which does not include agents of genus types derived from the specified ``Type``.
In plenary mode, the returned list contains all known agents or
an error results. Othe... | Gets an ``AgentList`` corresponding to the given agent genus ``Type`` which does not include agents of genus types derived from the specified ``Type``.
In plenary mode, the returned list contains all known agents or
an error results. Otherwise, the returned list may contain only
those agents th... |
def _set_scatter_signature(self):
"""Mark the amplitude and scattering matrices as up to date.
"""
self._scatter_signature = (self.thet0, self.thet, self.phi0, self.phi,
self.alpha, self.beta, self.orient) | Mark the amplitude and scattering matrices as up to date. |
def has_metadata(source, ext):
"""Returns a flag indicating if a given block of MultiMarkdown text contains metadata."""
_MMD_LIB.has_metadata.argtypes = [ctypes.c_char_p, ctypes.c_int]
_MMD_LIB.has_metadata.restype = ctypes.c_bool
return _MMD_LIB.has_metadata(source.encode('utf-8'), ext) | Returns a flag indicating if a given block of MultiMarkdown text contains metadata. |
def get_options(self, hidden=False):
"""
:param hidden: whether to return hidden options
:type hidden: bool
:returns: dictionary of all options (with option's information)
:rtype: dict
"""
return dict((opt['name'], opt) for opt in self.get_ordered_options(hidden=h... | :param hidden: whether to return hidden options
:type hidden: bool
:returns: dictionary of all options (with option's information)
:rtype: dict |
def instantiate(self, **extra_args):
""" Instantiate the model """
input_block = self.input_block.instantiate()
backbone = self.backbone.instantiate(**extra_args)
return StochasticPolicyModel(input_block, backbone, extra_args['action_space']) | Instantiate the model |
def readImages(self, path, recursive=False, numPartitions=-1,
dropImageFailures=False, sampleRatio=1.0, seed=0):
"""
Reads the directory of images from the local or remote source.
.. note:: If multiple jobs are run in parallel with different sampleRatio or recursive flag,
... | Reads the directory of images from the local or remote source.
.. note:: If multiple jobs are run in parallel with different sampleRatio or recursive flag,
there may be a race condition where one job overwrites the hadoop configs of another.
.. note:: If sample ratio is less than 1, sampli... |
def invoke(awsclient, function_name, payload, invocation_type=None,
alias_name=ALIAS_NAME, version=None, outfile=None):
"""Send a ping request to a lambda function.
:param awsclient:
:param function_name:
:param payload:
:param invocation_type:
:param alias_name:
:param version:
... | Send a ping request to a lambda function.
:param awsclient:
:param function_name:
:param payload:
:param invocation_type:
:param alias_name:
:param version:
:param outfile: write response to file
:return: ping response payload |
def readme_template(readme_template_file):
"""Display / set / update the readme template file."""
if not readme_template_file:
click.secho(dtool_config.utils.get_readme_template_fpath(
CONFIG_PATH,
))
else:
click.secho(dtool_config.utils.set_readme_template_fpath(
... | Display / set / update the readme template file. |
def _getFirstPathExpression(name):
"""Returns the first metric path in an expression."""
tokens = grammar.parseString(name)
pathExpression = None
while pathExpression is None:
if tokens.pathExpression:
pathExpression = tokens.pathExpression
elif tokens.expression:
... | Returns the first metric path in an expression. |
def template_instances(cls, dataset, capacity=0):
"""
Uses the Instances as template to create an empty dataset.
:param dataset: the original dataset
:type dataset: Instances
:param capacity: how many data rows to reserve initially (see compactify)
:type capacity: int
... | Uses the Instances as template to create an empty dataset.
:param dataset: the original dataset
:type dataset: Instances
:param capacity: how many data rows to reserve initially (see compactify)
:type capacity: int
:return: the empty dataset
:rtype: Instances |
def describe_api_deployments(restApiId, region=None, key=None, keyid=None, profile=None):
'''
Gets information about the defined API Deployments. Return list of api deployments.
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.describe_api_deployments restApiId
'''
tr... | Gets information about the defined API Deployments. Return list of api deployments.
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.describe_api_deployments restApiId |
def _push_from_buffer(self):
"""
Push a message on the stack to the IRC stream.
This is necessary to avoid Twitch overflow control.
"""
if len(self.buffer) > 0:
if time.time() - self.last_sent_time > 5:
try:
message = self.buffer.po... | Push a message on the stack to the IRC stream.
This is necessary to avoid Twitch overflow control. |
async def power(source, exponent):
"""Raise the elements of an asynchronous sequence to the given power."""
async with streamcontext(source) as streamer:
async for item in streamer:
yield item ** exponent | Raise the elements of an asynchronous sequence to the given power. |
def _calcQuadSize(corners, aspectRatio):
'''
return the size of a rectangle in perspective distortion in [px]
DEBUG: PUT THAT BACK IN??::
if aspectRatio is not given is will be determined
'''
if aspectRatio > 1: # x is bigger -> reduce y
x_length =... | return the size of a rectangle in perspective distortion in [px]
DEBUG: PUT THAT BACK IN??::
if aspectRatio is not given is will be determined |
def get_object(self, id, **args):
"""Fetches the given object from the graph."""
return self.request("{0}/{1}".format(self.version, id), args) | Fetches the given object from the graph. |
def get_local_addr(self, timeout=None):
"""
Retrieve the current local address.
:param timeout: If not given or given as ``None``, waits until
the local address is available. Otherwise,
waits for as long as specified. If the local
... | Retrieve the current local address.
:param timeout: If not given or given as ``None``, waits until
the local address is available. Otherwise,
waits for as long as specified. If the local
address is not set by the time the timeout
... |
def addfield(self, pkt, s, val):
# type: (Optional[packet.Packet], Union[str, Tuple[str, int, int]], int) -> str # noqa: E501
""" An AbstractUVarIntField prefix always consumes the remaining bits
of a BitField;if no current BitField is in use (no tuple in
entry) then the prefix leng... | An AbstractUVarIntField prefix always consumes the remaining bits
of a BitField;if no current BitField is in use (no tuple in
entry) then the prefix length is 8 bits and the whole byte is to
be consumed
@param packet.Packet|None pkt: the packet containing this field. Probably unuse... |
def invoke(self, ctx):
"""Given a context, this invokes the attached callback (if it exists)
in the right way.
"""
if self.callback is not None:
loop = asyncio.get_event_loop()
return loop.run_until_complete(self.async_invoke(ctx)) | Given a context, this invokes the attached callback (if it exists)
in the right way. |
def value(self):
"""Compute option value according to BSM model."""
return self._sign[1] * self.S0 * norm.cdf(
self._sign[1] * self.d1, 0.0, 1.0
) - self._sign[1] * self.K * np.exp(-self.r * self.T) * norm.cdf(
self._sign[1] * self.d2, 0.0, 1.0
) | Compute option value according to BSM model. |
def sum_over_energy(self):
""" Reduce a 3D counts cube to a 2D counts map
"""
# Note that the array is using the opposite convention from WCS
# so we sum over axis 0 in the array, but drop axis 2 in the WCS object
return Map(np.sum(self.counts, axis=0), self.wcs.dropaxis(2)) | Reduce a 3D counts cube to a 2D counts map |
def declare(self):
"""Declare the exchange.
Creates the exchange on the broker.
"""
self.backend.exchange_declare(exchange=self.exchange,
type=self.exchange_type,
durable=self.durable,
... | Declare the exchange.
Creates the exchange on the broker. |
def pins(swlat, swlng, nelat, nelng, pintypes='stop', *, raw=False):
"""
DVB Map Pins
(GET https://www.dvb.de/apps/map/pins)
:param swlat: South-West Bounding Box Latitude
:param swlng: South-West Bounding Box Longitude
:param nelat: North-East Bounding Box Latitude
:param nelng: North-East... | DVB Map Pins
(GET https://www.dvb.de/apps/map/pins)
:param swlat: South-West Bounding Box Latitude
:param swlng: South-West Bounding Box Longitude
:param nelat: North-East Bounding Box Latitude
:param nelng: North-East Bounding Box Longitude
:param pintypes: Types to search for, defaults to 'st... |
def _copy_searchtools(self, renderer=None):
"""Copy and patch searchtools
This uses the included Sphinx version's searchtools, but patches it to
remove automatic initialization. This is a fork of
``sphinx.util.fileutil.copy_asset``
"""
log.info(bold('copying searchtools.... | Copy and patch searchtools
This uses the included Sphinx version's searchtools, but patches it to
remove automatic initialization. This is a fork of
``sphinx.util.fileutil.copy_asset`` |
def _lincomb_impl(a, x1, b, x2, out):
"""Optimized implementation of ``out[:] = a * x1 + b * x2``."""
# Lazy import to improve `import odl` time
import scipy.linalg
size = native(x1.size)
if size < THRESHOLD_SMALL:
# Faster for small arrays
out.data[:] = a * x1.data + b * x2.data
... | Optimized implementation of ``out[:] = a * x1 + b * x2``. |
def convert(srctree, dsttree=dsttree, readonly=False, dumpall=False,
ignore_exceptions=False, fullcomp=False):
"""Walk the srctree, and convert/copy all python files
into the dsttree
"""
if fullcomp:
allow_ast_comparison()
parse_file = code_to_ast.parse_file
find_py_files ... | Walk the srctree, and convert/copy all python files
into the dsttree |
def stop(name, **kwargs):
'''
Hard power down the virtual machine, this is equivalent to pulling the power.
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
... | Hard power down the virtual machine, this is equivalent to pulling the power.
:param vm_: domain name
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:pa... |
def _state_table_name(environment=None, layer=None, stage=None):
"""The name of the state table associated to a humilis deployment."""
if environment is None:
# For backwards compatiblity
environment = os.environ.get("HUMILIS_ENVIRONMENT")
if layer is None:
layer = os.environ.get("HU... | The name of the state table associated to a humilis deployment. |
def share_network(network_id, usernames, read_only, share,**kwargs):
"""
Share a network with a list of users, identified by their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow... | Share a network with a list of users, identified by their usernames.
The read_only flag ('Y' or 'N') must be set
to 'Y' to allow write access or sharing.
The share flat ('Y' or 'N') must be set to 'Y' to allow the
project to be shared with other users |
def create_307_response(self):
"""
Creates a 307 "Temporary Redirect" response including a HTTP Warning
header with code 299 that contains the user message received during
processing the request.
"""
request = get_current_request()
msg_mb = UserMessageMember(self.... | Creates a 307 "Temporary Redirect" response including a HTTP Warning
header with code 299 that contains the user message received during
processing the request. |
def vdp_vlan_change_cb(self, port_uuid, lvid, vdp_vlan, fail_reason):
"""Callback function for updating the VDP VLAN in DB. """
LOG.info("Vlan change CB lvid %(lvid)s VDP %(vdp)s",
{'lvid': lvid, 'vdp': vdp_vlan})
self.update_vm_result(port_uuid, constants.RESULT_SUCCESS,
... | Callback function for updating the VDP VLAN in DB. |
def sanitize_words(self, words):
"""Guarantees that all textual symbols are unicode.
Note:
We do not convert numbers, only strings to unicode.
We assume that the strings are encoded in utf-8.
"""
_words = []
for w in words:
if isinstance(w, string_types) and not isinstance(w, unic... | Guarantees that all textual symbols are unicode.
Note:
We do not convert numbers, only strings to unicode.
We assume that the strings are encoded in utf-8. |
def set_inheritance(obj_name, enabled, obj_type='file', clear=False):
'''
Enable or disable an objects inheritance.
Args:
obj_name (str):
The name of the object
enabled (bool):
True to enable inheritance, False to disable
obj_type (Optional[str]):
... | Enable or disable an objects inheritance.
Args:
obj_name (str):
The name of the object
enabled (bool):
True to enable inheritance, False to disable
obj_type (Optional[str]):
The type of object. Only three objects allow inheritance. Valid
ob... |
def save_state(self):
'''
:DEPRECATED:
Periodically save the state of the environment and the agents.
'''
self._save_state()
while self.peek() != simpy.core.Infinity:
delay = max(self.peek() - self.now, self.interval)
utils.logger.debug('Step: {}'.... | :DEPRECATED:
Periodically save the state of the environment and the agents. |
def get_monitors(self) -> List[Monitor]:
"""Get a list of Monitors from the ZoneMinder API."""
raw_monitors = self._zm_request('get', ZoneMinder.MONITOR_URL)
if not raw_monitors:
_LOGGER.warning("Could not fetch monitors from ZoneMinder")
return []
monitors = []
... | Get a list of Monitors from the ZoneMinder API. |
def fetch(self):
"""
Fetch a FormInstance
:returns: Fetched FormInstance
:rtype: twilio.rest.authy.v1.form.FormInstance
"""
params = values.of({})
payload = self._version.fetch(
'GET',
self._uri,
params=params,
)
... | Fetch a FormInstance
:returns: Fetched FormInstance
:rtype: twilio.rest.authy.v1.form.FormInstance |
def set_custom_value(self, key, value):
"""Set one custom parameter with the given value.
We assume that the list of custom parameters does not already contain
the given parameter so we only append.
"""
self._owner.customParameters.append(
self._glyphs_module.GSCustom... | Set one custom parameter with the given value.
We assume that the list of custom parameters does not already contain
the given parameter so we only append. |
def html(self, report, f):
"""
Write report data to an HTML file.
"""
env = Environment(loader=PackageLoader('clan', 'templates'))
template = env.get_template('report.html')
context = {
'report': report,
'GLOBAL_ARGUMENTS': GLOBAL_ARGUMENTS,
... | Write report data to an HTML file. |
def get_all_derivatives(self, address):
"""Get all targets derived directly or indirectly from the specified target.
Note that the specified target itself is not returned.
:API: public
"""
ret = []
direct = self.get_direct_derivatives(address)
ret.extend(direct)
for t in direct:
... | Get all targets derived directly or indirectly from the specified target.
Note that the specified target itself is not returned.
:API: public |
def update_release(self, release, project, release_id):
"""UpdateRelease.
[Preview API] Update a complete release object.
:param :class:`<Release> <azure.devops.v5_1.release.models.Release>` release: Release object for update.
:param str project: Project ID or project name
:param... | UpdateRelease.
[Preview API] Update a complete release object.
:param :class:`<Release> <azure.devops.v5_1.release.models.Release>` release: Release object for update.
:param str project: Project ID or project name
:param int release_id: Id of the release to update.
:rtype: :clas... |
def gettarinfo(self, name=None, arcname=None, fileobj=None):
"""Create a TarInfo object for either the file `name' or the file
object `fileobj' (using os.fstat on its file descriptor). You can
modify some of the TarInfo's attributes before you add it using
addfile(). If given, `... | Create a TarInfo object for either the file `name' or the file
object `fileobj' (using os.fstat on its file descriptor). You can
modify some of the TarInfo's attributes before you add it using
addfile(). If given, `arcname' specifies an alternative name for the
file in the ar... |
def receive_message(self, msg):
"""Receive a messages sent to this device."""
_LOGGER.debug('Starting Device.receive_message')
if hasattr(msg, 'isack') and msg.isack:
_LOGGER.debug('Got Message ACK')
if self._sent_msg_wait_for_directACK.get('callback') is not None:
... | Receive a messages sent to this device. |
def olympusini_metadata(inistr):
"""Return OlympusSIS metadata from INI string.
No documentation is available.
"""
def keyindex(key):
# split key into name and index
index = 0
i = len(key.rstrip('0123456789'))
if i < len(key):
index = int(key[i:]) - 1
... | Return OlympusSIS metadata from INI string.
No documentation is available. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.