text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def read_length_and_key(fp):
"""
Helper to read descriptor key.
"""
length = read_fmt('I', fp)[0]
key = fp.read(length or 4)
if length == 0 and key not in _TERMS:
logger.debug('Unknown term: %r' % (key))
_TERMS.add(key)
return key | 0.00365 |
def diff_to_new_interesting_lines(unified_diff_lines: List[str]
) -> Dict[int, str]:
"""
Extracts a set of 'interesting' lines out of a GNU unified diff format.
Format:
gnu.org/software/diffutils/manual/html_node/Detailed-Unified.html
@@ from-line-numbers to-l... | 0.00051 |
def to_ipv4(self):
"""
Convert (an IPv6) IP address to an IPv4 address, if possible.
Only works for IPv4-compat (::/96), IPv4-mapped (::ffff/96), and 6-to-4
(2002::/16) addresses.
>>> ip = IP('2002:c000:022a::')
>>> print(ip.to_ipv4())
192.0.2.42
"""
... | 0.00344 |
def _parse_ip_stats_link_show(raw_result):
"""
Parse the 'ip -s link show dev <dev>' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show interface command in a \
dictionary of the form:
::
{
'rx_b... | 0.000743 |
def _get_configured_module(option_name, known_modules=None):
"""Get the module specified by the value of option_name. The value of the
configuration option will be used to load the module by name from the known
module list or treated as a path if not found in known_modules.
Args:
option_name: na... | 0.001099 |
def dig(host):
'''
Performs a DNS lookup with dig
CLI Example:
.. code-block:: bash
salt '*' network.dig archlinux.org
'''
cmd = 'dig {0}'.format(salt.utils.network.sanitize_host(host))
return __salt__['cmd.run'](cmd) | 0.003906 |
def define(cls, start, step, num, dtype=None):
"""Define a new `Index`.
The output is basically::
start + numpy.arange(num) * step
Parameters
----------
start : `Number`
The starting value of the index.
step : `Number`
The step size... | 0.001826 |
def get_name(self, label_type):
"""
returns the most preferred label name
if there isn't any correct name in the list
it will return newest label name
"""
if label_type in self._label_values:
return self._label_values[label_type][0]
else:
r... | 0.005571 |
def integral_scale(u, t, tau1=0.0, tau2=1.0):
"""Calculate the integral scale of a time series by integrating up to
the first zero crossing.
"""
tau, rho = autocorr_coeff(u, t, tau1, tau2)
zero_cross_ind = np.where(np.diff(np.sign(rho)))[0][0]
int_scale = np.trapz(rho[:zero_cross_ind], tau... | 0.002778 |
def gaussian_prior_model_for_arguments(self, arguments):
"""
Parameters
----------
arguments: {Prior: float}
A dictionary of arguments
Returns
-------
prior_models: [PriorModel]
A new list of prior models with gaussian priors
"""
... | 0.004532 |
def _fsync_files(filenames):
"""Call fsync() a list of file names
The filenames should be absolute paths already.
"""
touched_directories = set()
mode = os.O_RDONLY
# Windows
if hasattr(os, 'O_BINARY'):
mode |= os.O_BINARY
for filename in filenames:
fd = os.open(file... | 0.001366 |
def transform_grid_from_reference_frame(self, grid):
"""Transform a grid of (y,x) coordinates from the reference frame of the profile to the original observer \
reference frame, including a translation from the profile's centre.
Parameters
----------
grid : TransformedGrid(ndarr... | 0.005929 |
def load_repo(client, path=None, index='git'):
"""
Parse a git repository with all it's commits and load it into elasticsearch
using `client`. If the index doesn't exist it will be created.
"""
path = dirname(dirname(abspath(__file__))) if path is None else path
repo_name = basename(path)
re... | 0.002562 |
def get_field_type(f):
"""Obtain the type name of a GRPC Message field."""
types = (t[5:] for t in dir(f) if t[:4] == 'TYPE' and
getattr(f, t) == f.type)
return next(types) | 0.005076 |
def pop_group(self):
"""Terminates the redirection begun by a call to :meth:`push_group`
or :meth:`push_group_with_content`
and returns a new pattern containing the results
of all drawing operations performed to the group.
The :meth:`pop_group` method calls :meth:`restore`,
... | 0.002618 |
def posterior_to_xarray(self):
"""Convert the posterior to an xarray dataset."""
# Do not make pyro a requirement
from pyro.infer import EmpiricalMarginal
try: # Try pyro>=0.3 release syntax
data = {
name: np.expand_dims(samples.enumerate_support().squeeze()... | 0.002791 |
def new(self, bytes_to_skip):
# type: (int) -> None
'''
Create a new Rock Ridge Sharing Protocol record.
Parameters:
bytes_to_skip - The number of bytes to skip.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdl... | 0.008969 |
def fetch_all(self, R, depth=1, **kwargs):
"Request multiple objects from API"
d, e = self._fetcher.fetch_all(R, depth, kwargs)
if e: raise e
return d | 0.016484 |
def on_data(self, data):
"""
The function called when new data has arrived.
:param data: The list of data records received.
"""
for d in data:
self._populate_sub_entity(d, 'Device')
self._populate_sub_entity(d, 'Rule')
date = dates.localize_da... | 0.006873 |
def get_edu_text(text_subtree):
"""return the text of the given EDU subtree"""
assert text_subtree.label() == SubtreeType.text
return u' '.join(word.decode('utf-8') for word in text_subtree.leaves()) | 0.004739 |
def get_bbox(self, primitive):
"""Get the bounding box for the mesh"""
accessor = primitive.attributes.get('POSITION')
return accessor.min, accessor.max | 0.011364 |
def _ConvertAttributeValueToDict(cls, attribute_value):
"""Converts an attribute value into a JSON dictionary.
Args:
attribute_value (object): an attribute value.
Returns:
dict|list: The JSON serialized object which can be a dictionary or a list.
"""
if isinstance(attribute_value, py2t... | 0.008339 |
def sum_2_dictionaries(dicta, dictb):
"""Given two dictionaries of totals, where each total refers to a key
in the dictionary, add the totals.
E.g.: dicta = { 'a' : 3, 'b' : 1 }
dictb = { 'a' : 1, 'c' : 5 }
dicta + dictb = { 'a' : 4, 'b' : 1, 'c' : 5 }
@param dicta:... | 0.001295 |
def is_notifying(cls, user_or_email, instance):
"""Check if the watch created by notify exists."""
return super(InstanceEvent, cls).is_notifying(user_or_email,
object_id=instance.pk) | 0.007937 |
def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True):
"""
Scale all the datasets in the scene.
Scaling in performed independently on the X, Y and Z axis.
A scale of zero is illegal and will be replaced with one.
"""
if xscale is None:
... | 0.002381 |
def _generate_payload(author_icon, title, report):
'''
Prepare the payload for Slack
:param author_icon: The url for the thumbnail to be displayed
:param title: The title of the message
:param report: A dictionary with the report of the Salt function
:return: The payload ready for Slack
'''
... | 0.002476 |
def persist(self, name):
"""
clear any expiration TTL set on the object
:param name: str the name of the redis key
:return: Future()
"""
with self.pipe as pipe:
return pipe.persist(self.redis_key(name)) | 0.007491 |
def drop(n, it, constructor=list):
"""
>>> first(10,drop(10,xrange(sys.maxint),iter))
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
"""
return constructor(itertools.islice(it,n,None)) | 0.015152 |
def kube_node_status_condition(self, metric, scraper_config):
""" The ready status of a cluster node. v1.0+"""
base_check_name = scraper_config['namespace'] + '.node'
metric_name = scraper_config['namespace'] + '.nodes.by_condition'
by_condition_counter = Counter()
for sample in... | 0.005414 |
def _ppf(self, uloc, left, right, cache):
"""
Point percentile function.
Example:
>>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9]))
[0.1 0.2 0.9]
>>> print(chaospy.Add(chaospy.Uniform(), 2).inv([0.1, 0.2, 0.9]))
[2.1 2.2 2.9]
>>> print... | 0.001837 |
def _build(value, property_path=None):
""" The generic schema definition build method.
:param value: The value to build a schema definition for
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:return: The built schema definition
:rtype: Dict... | 0.000971 |
def _init_fncsortnt(flds):
"""Return a sort function for sorting header GO IDs found in sections."""
if 'tinfo' in flds:
if 'D1' in flds:
return lambda ntgo: [ntgo.NS, -1*ntgo.tinfo, ntgo.depth, ntgo.D1, ntgo.alt]
else:
return lambda ntgo: [ntgo.NS... | 0.010204 |
def raw(self):
# type: () -> ClientRawResponse
"""Get current page as ClientRawResponse.
:rtype: ClientRawResponse
"""
raw = ClientRawResponse(self.current_page, self._response)
if self._raw_headers:
raw.add_headers(self._raw_headers)
return raw | 0.009554 |
def coverage(self):
"""
Get the fraction of this title sequence that is matched by its reads.
@return: The C{float} fraction of the title sequence matched by its
reads.
"""
intervals = ReadIntervals(self.subjectLength)
for hsp in self.hsps():
inte... | 0.005013 |
def _get_correct_module(mod):
"""returns imported module
check if is ``leonardo_module_conf`` specified and then import them
"""
module_location = getattr(
mod, 'leonardo_module_conf',
getattr(mod, "LEONARDO_MODULE_CONF", None))
if module_location:
mod = import_module(module... | 0.00142 |
def all_solidity_variables_used_as_args(self):
"""
Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender)
"""
if self._all_solidity_variables_used_as_args is None:
self._all_solid... | 0.007576 |
def compile(pattern, flags=0, auto_compile=None, **kwargs): # noqa A001
"""Compile both the search or search and replace into one object."""
if isinstance(pattern, Bregex):
if auto_compile is not None:
raise ValueError("Cannot compile Bregex with a different auto_compile!")
elif fl... | 0.005068 |
def create_config_tree(config, modules, prefix=''):
'''Cause every possible configuration sub-dictionary to exist.
This is intended to be called very early in the configuration
sequence. For each module, it checks that the corresponding
configuration item exists in `config` and creates it as an empty
... | 0.00075 |
def get_public_ip_validator():
""" Retrieves a validator for public IP address. Accepting all defaults will perform a check
for an existing name or ID with no ARM-required -type parameter. """
from msrestazure.tools import is_valid_resource_id, resource_id
def simple_validator(cmd, namespace):
... | 0.003218 |
def get_node_name_from_id(node_id, nodes):
"""
Get the name of a node when given the node_id
:param int node_id: The ID of a node
:param list nodes: list of nodes from :py:meth:`generate_nodes`
:return: node name
:rtype: str
"""
node_name = ''
for... | 0.004211 |
def to_phonetics(self):
"""Transcribe phonetics."""
tr = Transcriber()
self.transcribed_phonetics = [tr.transcribe(line) for line in self.text] | 0.017964 |
def _deserialize(x, elementType, compress, relicReadBinFunc):
"""
Deserializes a bytearray @x, into an @element of the correct type,
using the a relic read_bin function and the specified @compressed flag.
This is the underlying implementation for deserialize G1, G2, and Gt.
"""
# Convert the byt... | 0.001575 |
def hasProp(self, name):
"""Search an attribute associated to a node This function also
looks in DTD attribute declaration for #FIXED or default
declaration values unless DTD use has been turned off. """
ret = libxml2mod.xmlHasProp(self._o, name)
if ret is None:return None
... | 0.010724 |
def get_method(self, name, arg_types=()):
"""
searches for the method matching the name and having argument type
descriptors matching those in arg_types.
Parameters
==========
arg_types : sequence of strings
each string is a parameter type, in the non-pretty fo... | 0.002294 |
def custom_getter_scope(custom_getter):
"""
Args:
custom_getter: the same as in :func:`tf.get_variable`
Returns:
The current variable scope with a custom_getter.
"""
scope = tf.get_variable_scope()
if get_tf_version_tuple() >= (1, 5):
with tf.variable_scope(
... | 0.001543 |
def _add_seg_to_output(out, data, enumerate_chroms=False):
"""Export outputs to 'seg' format compatible with IGV and GenePattern.
"""
out_file = "%s.seg" % os.path.splitext(out["cns"])[0]
if not utils.file_exists(out_file):
with file_transaction(data, out_file) as tx_out_file:
cmd = ... | 0.003165 |
def eigvec_to_eigdispl(v, q, frac_coords, mass):
"""
Converts a single eigenvector to an eigendisplacement in the primitive cell
according to the formula::
exp(2*pi*i*(frac_coords \\dot q) / sqrt(mass) * v
Compared to the modulation option in phonopy, here all the additional
mu... | 0.005797 |
def miscellaneous_menu(self, value):
"""
Setter for **self.__miscellaneous_menu** attribute.
:param value: Attribute value.
:type value: QMenu
"""
if value is not None:
assert type(value) is QMenu, "'{0}' attribute: '{1}' type is not 'QMenu'!".format(
... | 0.0075 |
def configure_sessionmaker(graph):
"""
Create the SQLAlchemy session class.
"""
engine_routing_strategy = getattr(graph, graph.config.sessionmaker.engine_routing_strategy)
if engine_routing_strategy.supports_multiple_binds:
ScopedFactory.infect(graph, "postgres")
class RoutingSession(... | 0.004386 |
def to_file(self, destination, format='csv', csv_delimiter=',', csv_header=True):
"""Save the results to a local file in CSV format.
Args:
destination: path on the local filesystem for the saved results.
format: the format to use for the exported data; currently only 'csv' is supported.
csv_d... | 0.009356 |
def list(cls, datacenter=None):
"""List virtual machine vlan
(in the future it should also handle PaaS vlan)."""
options = {}
if datacenter:
datacenter_id = int(Datacenter.usable_id(datacenter))
options['datacenter_id'] = datacenter_id
return cls.call('h... | 0.005764 |
def get_task_signature(cls, instance, serialized_instance, **kwargs):
"""
Delete each resource using specific executor.
Convert executors to task and combine all deletion task into single sequential task.
"""
cleanup_tasks = [
ProjectResourceCleanupTask().si(
... | 0.004587 |
def predict(self, features):
"""
Make prediction with feature matrix
:param features: feature matrix with dimension (numSamples, numInputs)
:return: predictions with dimension (numSamples, numOutputs)
"""
H = self.calculateHiddenLayerActivation(features)
prediction = np.dot(H, self.beta)
... | 0.002959 |
def sinus_values_by_hz(framerate, hz, max_value):
"""
Create sinus values with the given framerate and Hz.
Note:
We skip the first zero-crossing, so the values can be used directy in a loop.
>>> values = sinus_values_by_hz(22050, 1200, 255)
>>> len(values) # 22050 / 1200Hz = 18,375
18
>... | 0.001852 |
def experiments_predictions_attachments_download(self, experiment_id, run_id, resource_id):
"""Download a data file that has been attached with a successful model
run.
Parameters
----------
experiment_id : string
Unique experiment identifier
model_id : string... | 0.003752 |
def submit(self, txn, timeout=None):
"""
Submit a transaction.
Processes multiple requests in a single transaction.
A transaction increments the revision of the key-value store
and generates events with the same revision for every
completed request.
It is not al... | 0.000803 |
def utctimetuple(self):
"Return UTC time tuple compatible with time.gmtime()."
offset = self.utcoffset()
if offset:
self -= offset
y, m, d = self.year, self.month, self.day
hh, mm, ss = self.hour, self.minute, self.second
return _build_struct_time(y, m, d, hh,... | 0.006042 |
def _format_job_instance(job):
'''
Format the job instance correctly
'''
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': salt.utils.json.loads(job.get('arg', '[]')),
# unlikely but safeguard from invalid returns
'Target': job.get('tgt', 'unknown-targe... | 0.001992 |
def clear_children(self):
"""Clears the children.
raise: NoAccess - ``Metadata.isRequired()`` or
``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
if (self.get_children_metadata().is_read_only() or
... | 0.00432 |
def generate_headerlet(outwcs,template,wcsname,outname=None):
""" Create a headerlet based on the updated HSTWCS object
This function uses 'template' as the basis for the headerlet.
This file can either be the original wcspars['refimage'] or
wcspars['coeffsfile'], in this order of preferenc... | 0.004625 |
def get_event(self, client, check):
"""
Returns an event for a given client & check name.
"""
data = self._request('GET', '/events/{}/{}'.format(client, check))
return data.json() | 0.009132 |
def show_options(self, key=""):
"""Returns a copy the options :class:`~pandas.DataFrame`.
Called on jupyter notebook, it will print them in pretty
:class:`~pandas.DataFrame` format.
:param str key: First identifier of the option. If not provided,
all options are returned.
... | 0.003817 |
def organization(self, login):
"""Returns a Organization object for the login name
:param str login: (required), login name of the org
:returns: :class:`Organization <github3.orgs.Organization>`
"""
url = self._build_url('orgs', login)
json = self._json(self._get(url), 2... | 0.005249 |
def _decompose_pattern(self, pattern):
"""
Given a path pattern with format declaration, generates a
four-tuple (glob_pattern, regexp pattern, fields, type map)
"""
sep = '~lancet~sep~'
float_codes = ['e','E','f', 'F','g', 'G', 'n']
typecodes = dict([(k,float) for... | 0.017241 |
def export_roles(path_prefix='/', region=None, key=None, keyid=None, profile=None):
'''
Get all IAM role details. Produces results that can be used to create an
sls file.
CLI Example:
salt-call boto_iam.export_roles --out=txt | sed "s/local: //" > iam_roles.sls
'''
conn = _get_conn(reg... | 0.004 |
def __assert_false(returned):
'''
Test if an boolean is False
'''
result = "Pass"
if isinstance(returned, str):
try:
returned = bool(returned)
except ValueError:
raise
try:
assert (returned is False), "{0... | 0.004348 |
def _discover_mac(self):
""" Discovers MAC address of device.
Discovery is done by sending a UDP broadcast.
All configured devices reply. The response contains
the MAC address in both needed formats.
Discovery of multiple switches must be done synchronously.
:returns: ... | 0.002448 |
def from_nuniq_interval_set(cls, nuniq_is):
"""
Convert an IntervalSet containing NUNIQ intervals to an IntervalSet representing HEALPix
cells following the NESTED numbering scheme.
Parameters
----------
nuniq_is : `IntervalSet`
IntervalSet object storing HEA... | 0.003856 |
def get_output_cache_key(self, placeholder_name, instance):
"""
.. versionadded:: 0.9
Return the default cache key which is used to store a rendered item.
By default, this function generates the cache key using :func:`get_output_cache_base_key`.
"""
cachekey = self.... | 0.005639 |
def getScript(self, scriptname):
''' return the specified script if one exists (possibly inherited from
a base target)
'''
for t in self.hierarchy:
s = t.getScript(scriptname)
if s:
return s
return None | 0.006993 |
def configure_sbi(self, sbi_config: dict, schema_path: str = None):
"""Add a new SBI to the database associated with this subarray.
Args:
sbi_config (dict): SBI configuration.
schema_path (str, optional): Path to the SBI config schema.
"""
if not self.active:
... | 0.003484 |
def helioZ(self,*args,**kwargs):
"""
NAME:
helioZ
PURPOSE:
return Heliocentric Galactic rectangular z-coordinate (aka "Z")
INPUT:
t - (optional) time at which to get Z (can be Quantity)
obs=[X,Y,Z] - (optional) position of observer
... | 0.011294 |
def embed_code_links(app, exception):
"""Embed hyperlinks to documentation into example code"""
if exception is not None:
return
# No need to waste time embedding hyperlinks when not running the examples
# XXX: also at the time of writing this fixes make html-noplot
# for some reason I don'... | 0.000892 |
def reraise(self, cause_cls_finder=None):
"""Re-raise captured exception (possibly trying to recreate)."""
if self._exc_info:
six.reraise(*self._exc_info)
else:
# Attempt to regenerate the full chain (and then raise
# from the root); without a traceback, oh we... | 0.001408 |
def convert_text_to_rouge_format(text, title="dummy title"):
"""
Convert a text to a format ROUGE understands. The text is
assumed to contain one sentence per line.
text: The text to convert, containg one sentence per line.
title: Optional title for the text. The titl... | 0.002181 |
def load_fixture(fixture_file):
"""
Populate the database from a JSON file. Reads the JSON file FIXTURE_FILE
and uses it to populate the database. Fuxture files should consist of a
dictionary mapping database names to arrays of objects to store in those
databases.
"""
utils.check_for_local_s... | 0.001078 |
def get_variable_days(self, year):
"""
Add Late Summer holiday (First Monday of September)
"""
days = super(LateSummer, self).get_variable_days(year)
days.append((
self.get_nth_weekday_in_month(year, 9, MON),
"Late Summer Holiday"
))
return... | 0.006154 |
def get_layer(self):
""" retrieve layer from DB """
if self.layer:
return
try:
self.layer = Layer.objects.get(slug=self.kwargs['slug'])
except Layer.DoesNotExist:
raise Http404(_('Layer not found')) | 0.007519 |
def from_total_moment_rate(cls, min_mag, b_val, char_mag,
total_moment_rate, bin_width):
"""
Define Youngs and Coppersmith 1985 MFD by constraing cumulative a
value and characteristic rate from total moment rate.
The cumulative a value and characteristic ra... | 0.000847 |
def _mean_prediction(self, lmda, Y, scores, h, t_params):
""" Creates an h-step ahead mean prediction
Parameters
----------
lmda : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
... | 0.010451 |
def wrap_method(
func,
default_retry=None,
default_timeout=None,
client_info=client_info.DEFAULT_CLIENT_INFO,
):
"""Wrap an RPC method with common behavior.
This applies common error wrapping, retry, and timeout behavior a function.
The wrapped function will take optional ``retry`` and ``ti... | 0.000257 |
def _init_map(self, record_types=None, **kwargs):
"""Initialize form map"""
osid_objects.OsidObjectForm._init_map(self, record_types=record_types)
self._my_map['assignedObjectiveBankIds'] = [str(kwargs['objective_bank_id'])]
self._my_map['courseIds'] = self._courses_default
self.... | 0.006073 |
def compute_coeffs_discrete(xyz, mass, nmax, lmax, r_s,
skip_odd=False, skip_even=False, skip_m=False,
compute_var=False):
"""
Compute the expansion coefficients for representing the density distribution of input points
as a basis function expansion. T... | 0.008917 |
def _update_console(self, value=None):
"""
Update the progress bar to the given value (out of the total
given to the constructor).
"""
if self._total == 0:
frac = 1.0
else:
frac = float(value) / float(self._total)
file = self._file
... | 0.001515 |
def setitem(self, key, value):
# type: (Any, Any, Any) -> Any
'''Takes an object, a key, and a value and produces a new object
that is a copy of the original but with ``value`` as the new value of
``key``.
The following equality should hold for your definition:
.. code-block:: python
... | 0.000801 |
def lowest(self, rtol=1.e-5, atol=1.e-8):
"""Return a sample set containing the lowest-energy samples.
A sample is included if its energy is within tolerance of the lowest
energy in the sample set. The following equation is used to determine
if two values are equivalent:
absolu... | 0.001403 |
def _set_ldp_fec_vcs(self, v, load=False):
"""
Setter method for ldp_fec_vcs, mapped from YANG variable /mpls_state/ldp/fec/ldp_fec_vcs (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_fec_vcs is considered as a private
method. Backends looking to popu... | 0.00575 |
def int(self, var, default=NOTSET):
"""
:rtype: int
"""
return self.get_value(var, cast=int, default=default) | 0.014184 |
def add_iri_thermal_plasma(inst, glat_label='glat', glong_label='glong',
alt_label='alt'):
"""
Uses IRI (International Reference Ionosphere) model to simulate an ionosphere.
Uses pyglow module to run IRI. Configured to use actual solar parameters to run
model.
... | 0.01634 |
def init_app(self, app):
"""Initialize a :class:`~flask.Flask` application for use with
this extension.
"""
self._jobs = []
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['restpoints'] = self
app.restpoints_instance = self
... | 0.004193 |
def resource_get(name):
"""used to fetch the resource path of the given name.
<name> must match a name of defined resource in metadata.yaml
returns either a path or False if resource not available
"""
if not name:
return False
cmd = ['resource-get', name]
try:
return subpr... | 0.00237 |
def get_and_check_project(valid_vcs_rules, source_url):
"""Given vcs rules and a source_url, return the project.
The project is in the path, but is the repo name.
`releases/mozilla-beta` is the path; `mozilla-beta` is the project.
Args:
valid_vcs_rules (tuple of frozendicts): the valid vcs rul... | 0.0025 |
def safe_input(prompt):
"""
Prompts user for input. Correctly handles prompt message encoding.
"""
if sys.version_info < (3,0):
if isinstance(prompt, compat.text_type):
# Python 2.x: unicode → bytes
encoding = locale.getpreferredencoding() or 'utf-8'
prompt ... | 0.003883 |
def ws025(self, value=None):
""" Corresponds to IDD Field `ws025`
Wind speed corresponding to 2.5% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `ws025`
Unit: m/s
if `value` is None it will not be checked against ... | 0.003963 |
def num_samples(input_filepath):
'''
Show number of samples (0 if unavailable).
Parameters
----------
input_filepath : str
Path to audio file.
Returns
-------
n_samples : int
total number of samples in audio file.
Returns 0 if empty or unavailable
'''
va... | 0.001938 |
def selectisnot(table, field, value, complement=False):
"""Select rows where the given field `is not` the given value."""
return selectop(table, field, value, operator.is_not, complement=complement) | 0.009662 |
def _get_catalysts_in_reaction(reaction: Reaction) -> Set[BaseAbundance]:
"""Return nodes that are both in reactants and reactions in a reaction."""
return {
reactant
for reactant in reaction.reactants
if reactant in reaction.products
} | 0.003676 |
def _to_fields(self, *values):
"""
Take a list of values, which must be primary keys of the model linked
to the related collection, and return a list of related fields.
"""
result = []
for related_instance in values:
if not isinstance(related_instance, model.R... | 0.003922 |
def generate_basic(self):
"""RFC 2617."""
from base64 import b64encode
if not self.basic_auth:
creds = self.username + ':' + self.password
self.basic_auth = 'Basic '
self.basic_auth += b64encode(creds.encode('UTF-8')).decode('UTF-8')
return self.basic_... | 0.006173 |
def create_payload(self):
"""Create the payload doc.
Returns:
str
"""
doc = etree.fromstring(self.message)
self.payload = etree.tostring(doc, encoding="utf-8")
self.payload = urlsafe_b64encode(self.payload).decode("ascii")
return self.payload | 0.006431 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.