code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def mi(x, y, bins_x=None, bins_y=None, bins_xy=None, method='nearest-neighbors', units='bits'):
'''
compute and return the mutual information between x and y
inputs:
-------
x, y: numpy arrays of shape samples x dimension
method: 'nearest-neighbors', 'gaussian', or 'bin'
... | compute and return the mutual information between x and y
inputs:
-------
x, y: numpy arrays of shape samples x dimension
method: 'nearest-neighbors', 'gaussian', or 'bin'
units: 'bits' or 'nats'
output:
-------
mi: float
Notes:
------
... |
def get_mapping_client(self, max_concurrency=64, auto_batch=None):
"""Returns a thread unsafe mapping client. This client works
similar to a redis pipeline and returns eventual result objects.
It needs to be joined on to work properly. Instead of using this
directly you shold use the :... | Returns a thread unsafe mapping client. This client works
similar to a redis pipeline and returns eventual result objects.
It needs to be joined on to work properly. Instead of using this
directly you shold use the :meth:`map` context manager which
automatically joins.
Returns... |
def unzip(self, payload):
"""
Unzips a file
:param payload:
zip_with_rel_path: string
remove_original_zip: boolean
:return: (object)
unzipped_path: string
"""
zip_with_rel_path = payload.pop('zip_with_rel_path')
ur... | Unzips a file
:param payload:
zip_with_rel_path: string
remove_original_zip: boolean
:return: (object)
unzipped_path: string |
def get_preview_kwargs(self, **kwargs):
"""
Gets the url keyword arguments to pass to the
`preview_view` callable. If the `pass_through_kwarg`
attribute is set the value of `pass_through_attr` will
be looked up on the object.
So if you are previewing an item Obj<id=2> an... | Gets the url keyword arguments to pass to the
`preview_view` callable. If the `pass_through_kwarg`
attribute is set the value of `pass_through_attr` will
be looked up on the object.
So if you are previewing an item Obj<id=2> and
::
self.pass_through_kwarg =... |
def _build_cmdargs(argv):
""" Build command line arguments dict to use;
- displaying usages
- vint.linting.env.build_environment
This method take an argv parameter to make function pure.
"""
parser = _build_arg_parser()
namespace = parser.parse_args(argv[1:])
cmdargs = vars(namespace)
... | Build command line arguments dict to use;
- displaying usages
- vint.linting.env.build_environment
This method take an argv parameter to make function pure. |
def fetch_host_ip_and_country(host: str) -> Tuple:
"""
Fetch ip and country by host
"""
ip = fetch_host_ip(host)
if not host:
return '', ''
country = fetch_country_by_ip(ip)
return ip, country | Fetch ip and country by host |
def install(ctx, services, delete_after_install=False):
"""Install a honeypot service from the online library, local path or zipfile."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
... | Install a honeypot service from the online library, local path or zipfile. |
def path_to_node(tree, path):
"""FST node located at the given path"""
if path is None:
return None
node = tree
for key in path:
node = child_by_key(node, key)
return node | FST node located at the given path |
def parse_individual(self, individual):
"""Converts a deap individual into a full list of parameters.
Parameters
----------
individual: deap individual from optimization
Details vary according to type of optimization, but
parameters within deap individual are alwa... | Converts a deap individual into a full list of parameters.
Parameters
----------
individual: deap individual from optimization
Details vary according to type of optimization, but
parameters within deap individual are always between -1
and 1. This function conv... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
def _read(self, source):
"""
Reads and parses the config source
:param file/str source: Config source string, file name, or file pointer. If file name does not exist, it is
ignored.
:return: True if source was successfully read, otherwise False
""... | Reads and parses the config source
:param file/str source: Config source string, file name, or file pointer. If file name does not exist, it is
ignored.
:return: True if source was successfully read, otherwise False |
def optimize_batch(self, batchsize=10, returns='best', paralell=True):
"""
Run multiple optimizations using different starting coordinates.
Args:
batchsize (`int`): Number of optimizations to run.
returns (`str`): If ``'all'``, return results of all optimizations,
... | Run multiple optimizations using different starting coordinates.
Args:
batchsize (`int`): Number of optimizations to run.
returns (`str`): If ``'all'``, return results of all optimizations,
ordered by stress, ascending. If ``'best'`` return the
projection... |
def _try_dump_cnt(self):
'''Dump counters every 60 seconds'''
now = time.time()
if now - self._last_dump_cnt > 60:
self._last_dump_cnt = now
self._dump_cnt()
self._print_counter_log() | Dump counters every 60 seconds |
def l1_regularizer(weight=1.0, scope=None):
"""Define a L1 regularizer.
Args:
weight: scale the loss by this factor.
scope: Optional scope for name_scope.
Returns:
a regularizer function.
"""
def regularizer(tensor):
with tf.name_scope(scope, 'L1Regularizer', [tensor]):
l1_weight = tf.... | Define a L1 regularizer.
Args:
weight: scale the loss by this factor.
scope: Optional scope for name_scope.
Returns:
a regularizer function. |
def expand_defaults(schema, features):
"""Add to features any default transformations.
Not every column in the schema has an explicit feature transformation listed
in the featurs file. For these columns, add a default transformation based on
the schema's type. The features dict is modified by this function cal... | Add to features any default transformations.
Not every column in the schema has an explicit feature transformation listed
in the featurs file. For these columns, add a default transformation based on
the schema's type. The features dict is modified by this function call.
After this function call, every column... |
def get_groupby_statistic(data):
"""Calculate value counts and distinct count of a variable (technically a Series).
The result is cached by column name in a global variable to avoid recomputing.
Parameters
----------
data : Series
The data type of the Series.
Returns
-------
l... | Calculate value counts and distinct count of a variable (technically a Series).
The result is cached by column name in a global variable to avoid recomputing.
Parameters
----------
data : Series
The data type of the Series.
Returns
-------
list
value count and distinct cou... |
def filter(func):
"""Filters out unwanted items using the specified function.
Supports both dicts and sequences, key/value pairs are
expanded when applied to a dict.
"""
def expand_kv(kv):
return func(*kv)
def filter_values(value):
cls = type(value)
if isinstance(value,... | Filters out unwanted items using the specified function.
Supports both dicts and sequences, key/value pairs are
expanded when applied to a dict. |
def coarse_grain(self, user_sets):
r"""Coarse-grains the flux onto user-defined sets.
Parameters
----------
user_sets : list of int-iterables
sets of states that shall be distinguished in the coarse-grained flux.
Returns
-------
(sets, tpt) : (list o... | r"""Coarse-grains the flux onto user-defined sets.
Parameters
----------
user_sets : list of int-iterables
sets of states that shall be distinguished in the coarse-grained flux.
Returns
-------
(sets, tpt) : (list of int-iterables, tpt-object)
se... |
def serve_static(filename=None, prefix='', basedir=None):
"""Handler for static files: server filename in basedir/prefix.
If not specified then basedir defaults to the local third_party
directory.
"""
if not basedir:
basedir = os.path.join(os.path.dirname(__file__), 'third_party')
retur... | Handler for static files: server filename in basedir/prefix.
If not specified then basedir defaults to the local third_party
directory. |
def get_translation(self, lang, field):
"""
Return the translation string of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try t... | Return the translation string of an specific field in a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we try to get
@rtype: string
@return: Returns a tra... |
def est_propensity(self, lin='all', qua=None):
"""
Estimates the propensity scores given list of covariates to
include linearly or quadratically.
The propensity score is the conditional probability of
receiving the treatment given the observed covariates.
Estimation is done via a logistic regression.
P... | Estimates the propensity scores given list of covariates to
include linearly or quadratically.
The propensity score is the conditional probability of
receiving the treatment given the observed covariates.
Estimation is done via a logistic regression.
Parameters
----------
lin: string or list, optional
... |
def expand_time(str_time, default_unit='s', multiplier=1):
"""
helper for above functions
"""
parser = re.compile(r'(\d+)([a-zA-Z]*)')
parts = parser.findall(str_time)
result = 0.0
for value, unit in parts:
value = int(value)
unit = unit.lower()
if unit == '':
... | helper for above functions |
def form_valid(self, form, formsets):
"""
Response for valid form. In one transaction this will
save the current form and formsets, log the action
and message the user.
Returns the results of calling the `success_response` method.
"""
# check if it's a new object... | Response for valid form. In one transaction this will
save the current form and formsets, log the action
and message the user.
Returns the results of calling the `success_response` method. |
def addRnaQuantMetadata(self, fields):
"""
data elements are:
Id, annotations, description, name, readGroupId
where annotations is a comma separated list
"""
self._featureSetIds = fields["feature_set_ids"].split(',')
self._description = fields["description"]
... | data elements are:
Id, annotations, description, name, readGroupId
where annotations is a comma separated list |
def bind(nodemask):
"""
Binds the current thread and its children to the nodes specified in nodemask.
They will only run on the CPUs of the specified nodes and only be able to allocate memory from them.
@param nodemask: node mask
@type nodemask: C{set}
"""
mask = set_to_numa_nodemask(nodema... | Binds the current thread and its children to the nodes specified in nodemask.
They will only run on the CPUs of the specified nodes and only be able to allocate memory from them.
@param nodemask: node mask
@type nodemask: C{set} |
def cover_update(self, photo, **kwds):
"""
Endpoint: /album/<album_id>/cover/<photo_id>/update.json
Update the cover photo of this album.
"""
result = self._client.album.cover_update(self, photo, **kwds)
self._replace_fields(result.get_fields())
self._update_fiel... | Endpoint: /album/<album_id>/cover/<photo_id>/update.json
Update the cover photo of this album. |
def transcription(ref, est, **kwargs):
r'''Note transcription evaluation
Parameters
----------
ref : jams.Annotation
Reference annotation object
est : jams.Annotation
Estimated annotation object
kwargs
Additional keyword arguments
Returns
-------
scores : di... | r'''Note transcription evaluation
Parameters
----------
ref : jams.Annotation
Reference annotation object
est : jams.Annotation
Estimated annotation object
kwargs
Additional keyword arguments
Returns
-------
scores : dict
Dictionary of scores, where the ... |
def iso_register(iso_code):
"""
Registers Calendar class as country or region in IsoRegistry.
Registered country must set class variables ``iso`` using this decorator.
>>> from workalendar.core import Calendar
>>> @iso_register('MC-MR')
>>> class MyRegion(Calendar):
>>> 'My Region'
... | Registers Calendar class as country or region in IsoRegistry.
Registered country must set class variables ``iso`` using this decorator.
>>> from workalendar.core import Calendar
>>> @iso_register('MC-MR')
>>> class MyRegion(Calendar):
>>> 'My Region'
Region calendar is then retrievable fr... |
def get_success_url(self):
""" Returns the URL to redirect the user to upon valid form processing. """
messages.success(self.request, self.success_message)
if self.object.is_topic_head and self.object.is_topic_tail:
return reverse(
'forum:forum',
kwar... | Returns the URL to redirect the user to upon valid form processing. |
def replace_param_occurrences(string, params):
"""replace occurrences of the tuning params with their current value"""
for k, v in params.items():
string = string.replace(k, str(v))
return string | replace occurrences of the tuning params with their current value |
def IsFile(v):
"""Verify the file exists.
>>> os.path.basename(IsFile()(__file__)).startswith('validators.py')
True
>>> with raises(FileInvalid, 'not a file'):
... IsFile()("random_filename_goes_here.py")
>>> with raises(FileInvalid, 'Not a file'):
... IsFile()(None)
"""
try:
... | Verify the file exists.
>>> os.path.basename(IsFile()(__file__)).startswith('validators.py')
True
>>> with raises(FileInvalid, 'not a file'):
... IsFile()("random_filename_goes_here.py")
>>> with raises(FileInvalid, 'Not a file'):
... IsFile()(None) |
def update_ca_bundle(
target=None,
source=None,
opts=None,
merge_files=None,
):
'''
Attempt to update the CA bundle file from a URL
If not specified, the local location on disk (``target``) will be
auto-detected, if possible. If it is not found, then a new locati... | Attempt to update the CA bundle file from a URL
If not specified, the local location on disk (``target``) will be
auto-detected, if possible. If it is not found, then a new location on disk
will be created and updated.
The default ``source`` is:
http://curl.haxx.se/ca/cacert.pem
This is ... |
def union_q(token):
"""
Appends all the Q() objects.
"""
query = Q()
operation = 'and'
negation = False
for t in token:
if type(t) is ParseResults: # See tokens recursively
query &= union_q(t)
else:
if t in ('or', 'and'): # Set the new op and go to ... | Appends all the Q() objects. |
def _get_error(self, code, errors, indentation=0):
"""Get error and show the faulty line + some context
Other GLIR implementations may omit this.
"""
# Init
results = []
lines = None
if code is not None:
lines = [line.strip() for line in code.split('\n... | Get error and show the faulty line + some context
Other GLIR implementations may omit this. |
def new(self, string=None, *args, **kwargs):
"""Returns a `_ChainedHashAlgorithm` if the underlying tuple
(specifying the list of algorithms) is not empty, otherwise a
`_NopHashAlgorithm` instance is returned."""
if len(self):
hobj = _ChainedHashAlgorithm(self, *args, **kwarg... | Returns a `_ChainedHashAlgorithm` if the underlying tuple
(specifying the list of algorithms) is not empty, otherwise a
`_NopHashAlgorithm` instance is returned. |
def extract_subjects(cert_pem):
"""Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate.
Args:
cert_pem: str or bytes
PEM (Base64) encoded X.509 v3 certificate
Returns:
2-tuple:
- The primary subject string, extracted from the certificate DN.
- A se... | Extract subjects from a DataONE PEM (Base64) encoded X.509 v3 certificate.
Args:
cert_pem: str or bytes
PEM (Base64) encoded X.509 v3 certificate
Returns:
2-tuple:
- The primary subject string, extracted from the certificate DN.
- A set of equivalent identities, group membe... |
def playlist(self, playlist_id, *, include_songs=False):
"""Get information about a playlist.
Parameters:
playlist_id (str): A playlist ID.
include_songs (bool, Optional): Include songs from
the playlist in the returned dict.
Default: ``False``
Returns:
dict: Playlist information.
"""
play... | Get information about a playlist.
Parameters:
playlist_id (str): A playlist ID.
include_songs (bool, Optional): Include songs from
the playlist in the returned dict.
Default: ``False``
Returns:
dict: Playlist information. |
def validatePrepare(self, prepare: Prepare, sender: str) -> bool:
"""
Return whether the PREPARE specified is valid.
:param prepare: the PREPARE to validate
:param sender: the name of the node that sent the PREPARE
:return: True if PREPARE is valid, False otherwise
"""
... | Return whether the PREPARE specified is valid.
:param prepare: the PREPARE to validate
:param sender: the name of the node that sent the PREPARE
:return: True if PREPARE is valid, False otherwise |
def create_from_tree(cls, repo, tree, message, parent_commits=None, head=False, author=None, committer=None,
author_date=None, commit_date=None):
"""Commit the given tree, creating a commit object.
:param repo: Repo object the commit should be part of
:param tree: Tree ... | Commit the given tree, creating a commit object.
:param repo: Repo object the commit should be part of
:param tree: Tree object or hex or bin sha
the tree of the new commit
:param message: Commit message. It may be an empty string if no message is provided.
It will be co... |
def generate_cot_body(context):
"""Generate the chain of trust dictionary.
This is the unsigned and unformatted chain of trust artifact contents.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict: the unsignd and unformatted chain of trust artifact ... | Generate the chain of trust dictionary.
This is the unsigned and unformatted chain of trust artifact contents.
Args:
context (scriptworker.context.Context): the scriptworker context.
Returns:
dict: the unsignd and unformatted chain of trust artifact contents.
Raises:
ScriptWo... |
def _one_to_many_query(cls, query_obj, search4, model_attrib):
"""extends and returns a SQLAlchemy query object to allow one-to-many queries
:param query_obj: SQL Alchemy query object
:param str search4: search string
:param model_attrib: attribute in model
"""
model = m... | extends and returns a SQLAlchemy query object to allow one-to-many queries
:param query_obj: SQL Alchemy query object
:param str search4: search string
:param model_attrib: attribute in model |
def getContactTypes(self):
"""
Return an iterator of L{IContactType} providers available to this
organizer's store.
"""
yield VIPPersonContactType()
yield EmailContactType(self.store)
yield PostalContactType()
yield PhoneNumberContactType()
yield N... | Return an iterator of L{IContactType} providers available to this
organizer's store. |
def get_params(self, deep=True):
""" Get parameters for the estimator.
Args:
deep (boolean, optional) : If True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns:
params : mapping of string to any contained subobjects that are estimators.
"""
params =... | Get parameters for the estimator.
Args:
deep (boolean, optional) : If True, will return the parameters for this estimator and contained subobjects that are estimators.
Returns:
params : mapping of string to any contained subobjects that are estimators. |
def list_gewesten(self, sort=1):
'''
List all `gewesten` in Belgium.
:param integer sort: What field to sort on.
:rtype: A :class`list` of class: `Gewest`.
'''
def creator():
res = crab_gateway_request(self.client, 'ListGewesten', sort)
tmp = {}
... | List all `gewesten` in Belgium.
:param integer sort: What field to sort on.
:rtype: A :class`list` of class: `Gewest`. |
def hook_wrapper_23(stdin, stdout, prompt):
u'''Wrap a Python readline so it behaves like GNU readline.'''
try:
# call the Python hook
res = ensure_str(readline_hook(prompt))
# make sure it returned the right sort of thing
if res and not isinstance(res, str):
r... | u'''Wrap a Python readline so it behaves like GNU readline. |
def _contained_parameters(expression):
"""
Determine which parameters are contained in this expression.
:param Expression expression: expression involving parameters
:return: set of parameters contained in this expression
:rtype: set
"""
if isinstance(expression, BinaryExp):
return ... | Determine which parameters are contained in this expression.
:param Expression expression: expression involving parameters
:return: set of parameters contained in this expression
:rtype: set |
def compress(self, input_path):
"""
Compress the contents of the given directory.
:param string input_path: path of the input directory
:raises: TypeError: if the container path has not been set
:raises: ValueError: if ``input_path`` is not an existing directory
:raises:... | Compress the contents of the given directory.
:param string input_path: path of the input directory
:raises: TypeError: if the container path has not been set
:raises: ValueError: if ``input_path`` is not an existing directory
:raises: OSError: if an error occurred compressing the given... |
def predict_density(self, Xnew, Ynew):
"""
Compute the (log) density of the data Ynew at the points Xnew
Note that this computes the log density of the data individually,
ignoring correlations between them. The result is a matrix the same
shape as Ynew containing the log densiti... | Compute the (log) density of the data Ynew at the points Xnew
Note that this computes the log density of the data individually,
ignoring correlations between them. The result is a matrix the same
shape as Ynew containing the log densities. |
def num(value):
"""Convert a value from one of several bases to an int."""
if re_hex_num.match(value):
return int(value, base=16)
else:
return int(value) | Convert a value from one of several bases to an int. |
def get_requirements_transform_cfme(config):
"""Return requirement transformation function for CFME."""
def requirement_transform(requirement):
"""Requirements transform for CFME."""
requirement = copy.deepcopy(requirement)
if "id" in requirement:
del requirement["id"]
... | Return requirement transformation function for CFME. |
def iter(self, match="*", count=1000):
""" :see::meth:RedisMap.iter """
for field, value in self._client.hscan_iter(
self.key_prefix, match=match, count=count):
yield self._decode(field) | :see::meth:RedisMap.iter |
def is_inbound_presence_filter(cb):
"""
Return true if `cb` has been decorated with
:func:`inbound_presence_filter`.
"""
try:
handlers = get_magic_attr(cb)
except AttributeError:
return False
hs = HandlerSpec(
(_apply_inbound_presence_filter, ())
)
return h... | Return true if `cb` has been decorated with
:func:`inbound_presence_filter`. |
def process_module(self, node):
"""process a module
the module's content is accessible via the stream object
stream must implement the readlines method
"""
with node.stream() as stream:
self.append_stream(self.linter.current_name, stream, node.file_encoding) | process a module
the module's content is accessible via the stream object
stream must implement the readlines method |
def _delete_network(self, request, network):
"""Delete the created network when subnet creation failed."""
try:
api.neutron.network_delete(request, network.id)
LOG.debug('Delete the created network %s '
'due to subnet creation failure.', network.id)
... | Delete the created network when subnet creation failed. |
def enable_compression(self,
force: Optional[Union[bool, ContentCoding]]=None
) -> None:
"""Enables response compression encoding."""
# Backwards compatibility for when force was a bool <0.17.
if type(force) == bool:
force = Conte... | Enables response compression encoding. |
def load_config(config_file=None, profile=None, client=None,
endpoint=None, token=None, solver=None, proxy=None):
"""Load D-Wave Cloud Client configuration based on a configuration file.
Configuration values can be specified in multiple ways, ranked in the following
order (with 1 the highes... | Load D-Wave Cloud Client configuration based on a configuration file.
Configuration values can be specified in multiple ways, ranked in the following
order (with 1 the highest ranked):
1. Values specified as keyword arguments in :func:`load_config()`. These values replace
values read from a configu... |
def percbend(x, y, beta=.2):
"""
Percentage bend correlation (Wilcox 1994).
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
beta : float
Bending constant for omega (0 <= beta <= 0.5).
Returns
-------
r : flo... | Percentage bend correlation (Wilcox 1994).
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
beta : float
Bending constant for omega (0 <= beta <= 0.5).
Returns
-------
r : float
Percentage bend correlation co... |
def _add_gateway_node(self, gw_type, routing_node_gateway, network=None):
"""
Add a gateway node to existing routing tree. Gateways are only added if
they do not already exist. If they do exist, check the destinations of
the existing gateway and add destinations that are not already ther... | Add a gateway node to existing routing tree. Gateways are only added if
they do not already exist. If they do exist, check the destinations of
the existing gateway and add destinations that are not already there.
A current limitation is that if a gateway doesn't exist and the
destination... |
def _make_passage_kwargs(urn, reference):
""" Little helper used by CapitainsCtsPassage here to comply with parents args
:param urn: URN String
:param reference: Reference String
:return: Dictionary of arguments with URN based on identifier and reference
"""
kwargs = {}
if urn is not None:
... | Little helper used by CapitainsCtsPassage here to comply with parents args
:param urn: URN String
:param reference: Reference String
:return: Dictionary of arguments with URN based on identifier and reference |
def stick_perm(presenter, egg, dist_dict, strategy):
"""Computes weights for one reordering using stick-breaking method"""
# seed RNG
np.random.seed()
# unpack egg
egg_pres, egg_rec, egg_features, egg_dist_funcs = parse_egg(egg)
# reorder
regg = order_stick(presenter, egg, dist_dict, stra... | Computes weights for one reordering using stick-breaking method |
def Luv_to_LCHuv(cobj, *args, **kwargs):
"""
Convert from CIE Luv to LCH(uv).
"""
lch_l = cobj.luv_l
lch_c = math.sqrt(math.pow(cobj.luv_u, 2.0) + math.pow(cobj.luv_v, 2.0))
lch_h = math.atan2(float(cobj.luv_v), float(cobj.luv_u))
if lch_h > 0:
lch_h = (lch_h / math.pi) * 180
el... | Convert from CIE Luv to LCH(uv). |
def _setPrivate(self, private):
"""This is here to make testing easier"""
self.private = private
self.public = pow(self.generator, self.private, self.modulus) | This is here to make testing easier |
def from_file(path):
"""
Returns an AudioSegment object from the given file based on its file extension.
If the extension is wrong, this will throw some sort of error.
:param path: The path to the file, including the file extension.
:returns: An AudioSegment instance from the file.
"""
_nam... | Returns an AudioSegment object from the given file based on its file extension.
If the extension is wrong, this will throw some sort of error.
:param path: The path to the file, including the file extension.
:returns: An AudioSegment instance from the file. |
def example_delete_topics(a, topics):
""" delete topics """
# Call delete_topics to asynchronously delete topics, a future is returned.
# By default this operation on the broker returns immediately while
# topics are deleted in the background. But here we give it some time (30s)
# to propagate in t... | delete topics |
def ConsultarDepositosAcopio(self, sep="||"):
"Retorna los depósitos de acopio pertenencientes al contribuyente"
ret = self.client.consultarDepositosAcopio(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, }... | Retorna los depósitos de acopio pertenencientes al contribuyente |
def _checkMemberName(name):
"""
See if a member name indicates that it should be private.
Private variables in Python (starting with a double underscore but
not ending in a double underscore) and bed lumps (variables that
are not really private but are by common convention treat... | See if a member name indicates that it should be private.
Private variables in Python (starting with a double underscore but
not ending in a double underscore) and bed lumps (variables that
are not really private but are by common convention treated as
protected because they begin with ... |
def copy(self, target_parent, name=None, include_children=True, include_instances=True):
"""
Copy the `Part` to target parent, both of them having the same category.
.. versionadded:: 2.3
:param target_parent: `Part` object under which the desired `Part` is copied
:type target_... | Copy the `Part` to target parent, both of them having the same category.
.. versionadded:: 2.3
:param target_parent: `Part` object under which the desired `Part` is copied
:type target_parent: :class:`Part`
:param name: how the copied top-level `Part` should be called
:type nam... |
def _update_val(self, val, result_score_list):
"""Update values in the list of result scores and self._pbar during pipeline evaluation.
Parameters
----------
val: float or "Timeout"
CV scores
result_score_list: list
A list of CV scores
Returns
... | Update values in the list of result scores and self._pbar during pipeline evaluation.
Parameters
----------
val: float or "Timeout"
CV scores
result_score_list: list
A list of CV scores
Returns
-------
result_score_list: list
... |
def keyed_ordering(cls):
"""Class decorator to generate all six rich comparison methods, based on a
``__key__`` method.
Many simple classes are wrappers for very simple data, and want to defer
comparisons to that data. Rich comparison is very flexible and powerful,
but makes this simple case tedio... | Class decorator to generate all six rich comparison methods, based on a
``__key__`` method.
Many simple classes are wrappers for very simple data, and want to defer
comparisons to that data. Rich comparison is very flexible and powerful,
but makes this simple case tedious to set up. There's the stand... |
def discover(timeout=1, retries=1):
"""Discover Raumfeld devices in the network
:param timeout: The timeout in seconds
:param retries: How often the search should be retried
:returns: A list of raumfeld devices, sorted by name
"""
locations = []
group = ('239.255.255.250', 1900)
... | Discover Raumfeld devices in the network
:param timeout: The timeout in seconds
:param retries: How often the search should be retried
:returns: A list of raumfeld devices, sorted by name |
def get_term_freq_mat(self):
'''
Returns
-------
np.array with columns as categories and rows as terms
'''
freq_mat = np.zeros(shape=(self.get_num_terms(), self.get_num_categories()), dtype=int)
for cat_i in range(self.get_num_categories()):
freq_mat[:... | Returns
-------
np.array with columns as categories and rows as terms |
def set_bot_permissions(calendar_id, userid, level):
"""
:param calendar_id: an integer representing calendar ID
:param userid: a string representing the user's UW NetID
:param level: a string representing the permission level
:return: True if request is successful, False otherwise.
raise DataFa... | :param calendar_id: an integer representing calendar ID
:param userid: a string representing the user's UW NetID
:param level: a string representing the permission level
:return: True if request is successful, False otherwise.
raise DataFailureException or a corresponding TrumbaException
if the requ... |
def _is_current_user(self, some_user):
"""
Is the specified user the current user?
:param some_user: RemoteUser user we want to check against the current user
:return: boolean: True if the current user is the passed in user
"""
current_user = self.remote_store.get_current... | Is the specified user the current user?
:param some_user: RemoteUser user we want to check against the current user
:return: boolean: True if the current user is the passed in user |
def scale(val, src, dst):
"""
Scale value from src range to dst range.
If value outside bounds, it is clipped and set to
the low or high bound of dst.
Ex:
scale(0, (0.0, 99.0), (-1.0, 1.0)) == -1.0
scale(-5, (0.0, 99.0), (-1.0, 1.0)) == -1.0
"""
if val < src[0]:
ret... | Scale value from src range to dst range.
If value outside bounds, it is clipped and set to
the low or high bound of dst.
Ex:
scale(0, (0.0, 99.0), (-1.0, 1.0)) == -1.0
scale(-5, (0.0, 99.0), (-1.0, 1.0)) == -1.0 |
def xml2object(xml, verbose=False):
"""Generate XML object model from XML file or XML text
This is the inverse operation to the __str__ representation
(up to whitespace).
Input xml can be either an
* xml file
* open xml file object
Return XML_document instance.
"""
# FIXME - can ... | Generate XML object model from XML file or XML text
This is the inverse operation to the __str__ representation
(up to whitespace).
Input xml can be either an
* xml file
* open xml file object
Return XML_document instance. |
def modified_lu(q):
"""Perform a modified LU decomposition of a matrix.
This takes a matrix q with orthonormal columns, returns l, u, s such that
q - s = l * u.
Args:
q: A two dimensional orthonormal matrix q.
Returns:
A tuple of a lower triangular matrix l, an upper triangular ma... | Perform a modified LU decomposition of a matrix.
This takes a matrix q with orthonormal columns, returns l, u, s such that
q - s = l * u.
Args:
q: A two dimensional orthonormal matrix q.
Returns:
A tuple of a lower triangular matrix l, an upper triangular matrix u,
and a a... |
def save(store, *args, **kwargs):
"""Convenience function to save an array or group of arrays to the local file system.
Parameters
----------
store : MutableMapping or string
Store or path to directory in file system or name of zip file.
args : ndarray
NumPy arrays with data to save... | Convenience function to save an array or group of arrays to the local file system.
Parameters
----------
store : MutableMapping or string
Store or path to directory in file system or name of zip file.
args : ndarray
NumPy arrays with data to save.
kwargs
NumPy arrays with da... |
def format_argspec_plus(fn, grouped=True):
"""Returns a dictionary of formatted, introspected function arguments.
A enhanced variant of inspect.formatargspec to support code generation.
fn
An inspectable callable or tuple of inspect getargspec() results.
grouped
Defaults to True; include ... | Returns a dictionary of formatted, introspected function arguments.
A enhanced variant of inspect.formatargspec to support code generation.
fn
An inspectable callable or tuple of inspect getargspec() results.
grouped
Defaults to True; include (parens, around, argument) lists
Returns:
... |
def build_tables(
table_names_to_dataframes,
table_names_to_primary_keys={},
table_names_to_indices={}):
"""
Parameters
----------
table_names_to_dataframes : dict
Dictionary mapping each table name to a DataFrame
table_names_to_primary_keys : dict
Dictionary... | Parameters
----------
table_names_to_dataframes : dict
Dictionary mapping each table name to a DataFrame
table_names_to_primary_keys : dict
Dictionary mapping each table to its primary key
table_names_to_indices : dict
Dictionary mapping each table to a set of indices
Retu... |
def teams(self, page=None, year=None, simple=False, keys=False):
"""
Get list of teams.
:param page: Page of teams to view. Each page contains 500 teams.
:param year: View teams from a specific year.
:param simple: Get only vital data.
:param keys: Set to true if you onl... | Get list of teams.
:param page: Page of teams to view. Each page contains 500 teams.
:param year: View teams from a specific year.
:param simple: Get only vital data.
:param keys: Set to true if you only want the teams' keys rather than full data on them.
:return: List of Team o... |
def rmtree_p(self):
""" Like :meth:`rmtree`, but does not raise an exception if the
directory does not exist. """
try:
self.rmtree()
except OSError:
_, e, _ = sys.exc_info()
if e.errno != errno.ENOENT:
raise
return self | Like :meth:`rmtree`, but does not raise an exception if the
directory does not exist. |
def _remove_hidden_parts(projected_surface):
"""Removes parts of a projected surface that are not visible.
Args:
projected_surface (surface): the surface to use
Returns:
surface: A projected surface.
"""
surface = np.copy(projected_surface)
surface[~_make_occlusion_mask(project... | Removes parts of a projected surface that are not visible.
Args:
projected_surface (surface): the surface to use
Returns:
surface: A projected surface. |
def pbkdf2(password, salt, outlen, digesttype="sha1", iterations=2000):
"""
Interface to PKCS5_PBKDF2_HMAC function
Parameters:
@param password - password to derive key from
@param salt - random salt to use for key derivation
@param outlen - number of bytes to derive
@param digesttype - nam... | Interface to PKCS5_PBKDF2_HMAC function
Parameters:
@param password - password to derive key from
@param salt - random salt to use for key derivation
@param outlen - number of bytes to derive
@param digesttype - name of digest to use to use (default sha1)
@param iterations - number of iteration... |
def hdel(self, key, field, *fields):
"""Delete one or more hash fields."""
return self.execute(b'HDEL', key, field, *fields) | Delete one or more hash fields. |
def _get_operation_input_field_values(self, metadata, file_input):
"""Returns a dictionary of envs or file inputs for an operation.
Args:
metadata: operation metadata field
file_input: True to return a dict of file inputs, False to return envs.
Returns:
A dictionary of input field name v... | Returns a dictionary of envs or file inputs for an operation.
Args:
metadata: operation metadata field
file_input: True to return a dict of file inputs, False to return envs.
Returns:
A dictionary of input field name value pairs |
def wait(self, timeout=-1):
"""Wait for the child to exit.
Wait for at most *timeout* seconds, or indefinitely if *timeout* is
None. Return the value of the :attr:`returncode` attribute.
"""
if self._process is None:
raise RuntimeError('no child process')
if ... | Wait for the child to exit.
Wait for at most *timeout* seconds, or indefinitely if *timeout* is
None. Return the value of the :attr:`returncode` attribute. |
def deploy(self, *lambdas):
"""Deploys lambdas to AWS"""
if not self.role:
logger.error('Missing AWS Role')
raise ArgumentsError('Role required')
logger.debug('Deploying lambda {}'.format(self.lambda_name))
zfh = self.package()
if self.lambda_name in se... | Deploys lambdas to AWS |
def get_tags(self, name):
"""
Returns a list of tags.
@param str name: The name of the tag.
:rtype: list[str]
"""
tags = list()
for tag in self._tags:
if tag[0] == name:
tags.append(tag[1])
return tags | Returns a list of tags.
@param str name: The name of the tag.
:rtype: list[str] |
def run(cmd):
"""
Run a shell command
"""
cmd = [pipes.quote(c) for c in cmd]
cmd = " ".join(cmd)
cmd += "; exit 0"
# print("Running {} in {}".format(cmd, os.getcwd()))
try:
output = subprocess.check_output(cmd,
stderr=subprocess.STDOUT,
... | Run a shell command |
def state_probability(self, direction, repertoire, purview,):
"""Compute the probability of the purview in its current state given
the repertoire.
Collapses the dimensions of the repertoire that correspond to the
purview nodes onto their state. All other dimension are already
si... | Compute the probability of the purview in its current state given
the repertoire.
Collapses the dimensions of the repertoire that correspond to the
purview nodes onto their state. All other dimension are already
singular and thus receive 0 as the conditioning index.
Returns:
... |
def add_auth_hook(self, event):
"""Register event hook on reception of add_auth_hook-event"""
self.log('Adding authentication hook for', event.authenticator_name)
self.auth_hooks[event.authenticator_name] = event.event | Register event hook on reception of add_auth_hook-event |
def F_oneway(*lists):
"""
Performs a 1-way ANOVA, returning an F-value and probability given
any number of groups. From Heiman, pp.394-7.
Usage: F_oneway(*lists) where *lists is any number of lists, one per
treatment group
Returns: F value, one-tailed p-value
"""
a = len... | Performs a 1-way ANOVA, returning an F-value and probability given
any number of groups. From Heiman, pp.394-7.
Usage: F_oneway(*lists) where *lists is any number of lists, one per
treatment group
Returns: F value, one-tailed p-value |
def get_args(self):
"""
Gets the args for the query which will be escaped when being executed by the
db. All inner queries are inspected and their args are combined with this
query's args.
:return: all args for this query as a dict
:rtype: dict
"""
for ta... | Gets the args for the query which will be escaped when being executed by the
db. All inner queries are inspected and their args are combined with this
query's args.
:return: all args for this query as a dict
:rtype: dict |
def get_assignable_gradebook_ids(self, gradebook_id):
"""Gets a list of gradebooks including and under the given gradebook node in which any grade system can be assigned.
arg: gradebook_id (osid.id.Id): the ``Id`` of the
``Gradebook``
return: (osid.id.IdList) - list of assign... | Gets a list of gradebooks including and under the given gradebook node in which any grade system can be assigned.
arg: gradebook_id (osid.id.Id): the ``Id`` of the
``Gradebook``
return: (osid.id.IdList) - list of assignable gradebook ``Ids``
raise: NullArgument - ``gradebook... |
def format_subject(subject):
"""
Prepends 'Re:' to the subject. To avoid multiple 'Re:'s
a counter is added.
NOTE: Currently unused. First step to fix Issue #48.
FIXME: Any hints how to make this i18n aware are very welcome.
"""
subject_prefix_re = r'^Re\[(\d*)\]:\ '
m = re.match(subjec... | Prepends 'Re:' to the subject. To avoid multiple 'Re:'s
a counter is added.
NOTE: Currently unused. First step to fix Issue #48.
FIXME: Any hints how to make this i18n aware are very welcome. |
def get_window_size(self, windowHandle='current'):
"""
Gets the width and height of the current window.
:Usage:
::
driver.get_window_size()
"""
command = Command.GET_WINDOW_SIZE
if self.w3c:
if windowHandle != 'current':
... | Gets the width and height of the current window.
:Usage:
::
driver.get_window_size() |
def create_detector(self, detector):
"""Creates a new detector.
Args:
detector (object): the detector model object. Will be serialized as
JSON.
Returns:
dictionary of the response (created detector model).
"""
resp = self._post(self._u(sel... | Creates a new detector.
Args:
detector (object): the detector model object. Will be serialized as
JSON.
Returns:
dictionary of the response (created detector model). |
def _set_fcoe(self, v, load=False):
"""
Setter method for fcoe, mapped from YANG variable /hardware/custom_profile/kap_custom_profile/fcoe (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe is considered as a private
method. Backends looking to populate... | Setter method for fcoe, mapped from YANG variable /hardware/custom_profile/kap_custom_profile/fcoe (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe is considered as a private
method. Backends looking to populate this variable should
do so via calling this... |
def SetFlushInterval(self, flush_interval):
"""Set the flush interval.
Args:
flush_interval (int): number of events to buffer before doing a bulk
insert.
"""
self._flush_interval = flush_interval
logger.debug('Elasticsearch flush interval: {0:d}'.format(flush_interval)) | Set the flush interval.
Args:
flush_interval (int): number of events to buffer before doing a bulk
insert. |
def modelshort(self):
"""
Short version of model name
Dictionary defined in ``populations.py``::
SHORT_MODELNAMES = {'Planets':'pl',
'EBs':'eb',
'HEBs':'heb',
'BEBs':'beb',
'Blended Planets':'bpl',
... | Short version of model name
Dictionary defined in ``populations.py``::
SHORT_MODELNAMES = {'Planets':'pl',
'EBs':'eb',
'HEBs':'heb',
'BEBs':'beb',
'Blended Planets':'bpl',
'Specific BEB':'sbeb',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.