text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def show_all_categories(call=None):
'''
Return a dict of all available categories on the cloud provider.
.. versionadded:: 2016.3.0
'''
if call == 'action':
raise SaltCloudSystemExit(
'The show_all_categories function must be called with -f or --function.'
)
conn = ... | 0.003788 |
def _upload(self, archive, region):
"""Upload function source and return source url
"""
# Generate source upload url
url = self.client.execute_command(
'generateUploadUrl',
{'parent': 'projects/{}/locations/{}'.format(
self.session.get_default_proj... | 0.002073 |
def get_child_models(self):
"""
Returns a list of ``(Model, ModelAdmin)`` tuples for ``base_model``
subclasses.
"""
child_models = []
# Loop through all models with FKs back to `base_model`.
for related_object in get_all_related_objects(self.base_model._meta):
... | 0.002242 |
def labels_to_indexed_coref_values(content_objs, labels):
'''[(content_id, FeatureCollection)] -> [Label] -> [({-1,1}, i, j)]
where 0 <= i, j < len(content_objs).
'''
cids_to_idx = {}
for i, (content_id, _) in enumerate(content_objs):
cids_to_idx[content_id] = i
idx = lambda cid: cids_t... | 0.005474 |
def _add_umis_with_fastp(read_fq, umi_fq, out_fq, cores):
"""Add UMIs to reads from separate UMI file using fastp.
"""
with utils.open_gzipsafe(umi_fq) as in_handle:
in_handle.readline() # name
umi_size = len(in_handle.readline().strip())
cmd = ("fastp -Q -A -L -G -w 1 --in1 {read_fq} -... | 0.001667 |
def derationalize_denom(expr):
"""Try to de-rationalize the denominator of the given expression.
The purpose is to allow to reconstruct e.g. ``1/sqrt(2)`` from
``sqrt(2)/2``.
Specifically, this matches `expr` against the following pattern::
Mul(..., Rational(n, d), Pow(d, Rational(1, 2)), ...... | 0.00062 |
def _kml_add_camera_triggers(kml, ulog, camera_trigger_topic_name, altitude_offset):
"""
Add camera trigger points to the map
"""
data = ulog.data_list
topic_instance = 0
cur_dataset = [elem for elem in data
if elem.name == camera_trigger_topic_name and elem.multi_id == topi... | 0.005263 |
def normalize_width(layer):
"""
When the elements of the layer have different widths, sets the width to the max elements.
Args:
layer (list): A list of elements.
"""
instructions = [instruction for instruction in filter(lambda x: x is not None, layer)]
longest... | 0.008565 |
def reverse_toctree(app, doctree, docname):
"""Reverse the order of entries in the root toctree if 'glob' is used."""
if docname == "changes":
for node in doctree.traverse():
if node.tagname == "toctree" and node.get("glob"):
node["entries"].reverse()
break | 0.003155 |
def _pull_response(self, namespace, req_type, **params):
"""
Common method for all of the Pull methods. Since all of the pull
methods operate independent of the type of data, this single function
severs as common code
This method validates the namespace, gets data on the enumera... | 0.001021 |
def _detect_fork(self):
"""Detects if lock client was forked.
Forking is detected by comparing the PID of the current
process with the stored PID.
"""
if self._pid is None:
self._pid = os.getpid()
if self._context is not None:
current_pid = os.ge... | 0.006421 |
def ekucec(handle, segno, recno, column, nvals, cvals, isnull):
"""
Update a character column entry in a specified EK record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekucec_c.html
:param handle: EK file handle.
:type handle: int
:param segno: Index of segment containing record.... | 0.001751 |
def set_cached_output(self, placeholder_name, instance, output):
"""
.. versionadded:: 0.9
Store the cached output for a rendered item.
This method can be overwritten to implement custom caching mechanisms.
By default, this function generates the cache key using :func:`... | 0.0065 |
def _get_nd_basic_indexing(self, key):
"""This function is called when key is a slice, or an integer,
or a tuple of slices or integers"""
shape = self.shape
if isinstance(key, integer_types):
if key > shape[0] - 1:
raise IndexError(
'index ... | 0.003539 |
def insert(self, point, data=None):
"""Insert a new node in the tree.
Args:
point (:obj:`tuple` of float or int): Stores the position of the
node.
data (:obj, optional): The information stored by the node.
Returns:
int: The identifier of the ... | 0.001083 |
def create_teams(obj, user, access):
"""
Will create new teams associated with the referenced obj and set the
resulting relation to the correct attribute.
The naming convention for team foreign keys is pluralname_team (for
example, instructors_team).
This function will take the access dictiona... | 0.001176 |
def _pycall_path_old(x1: int, y1: int, x2: int, y2: int, handle: Any) -> float:
"""libtcodpy style callback, needs to preserve the old userData issue."""
func, userData = ffi.from_handle(handle)
return func(x1, y1, x2, y2, userData) | 0.004098 |
def _SetValues(self, values):
"""Set values from supplied dictionary or list.
Args:
values: A Row, dict indexed by column name, or list.
Raises:
TypeError: Argument is not a list or dict, or list is not equal row
length or dictionary keys don't match.
"""
def _ToStr(value):
... | 0.009194 |
def write_output(job_id, content, conn=None):
"""writes output to the output table
:param job_id: <str> id of the job
:param content: <str> output to write
:param conn:
"""
output_job = get_job_by_id(job_id, conn)
results = {}
if output_job is not None:
entry = {
OUT... | 0.002096 |
def threshold(values, threshold):
"""
Return boolean arrays where a >= and < threshold.
Parameters
----------
values : array-like
Array of real values.
threshold : float
Threshold value
Returns
-------
(below, above) : tuple or boolean arrays
"""
values ... | 0.005038 |
def cee_map_priority_table_map_cos7_pgid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name_key = ET.SubElement(cee_map, "name")
name_key.text = kwargs.pop... | 0.004894 |
def delete_lbaas_l7rule(self, l7rule, l7policy):
"""Deletes the specified L7 rule."""
return self.delete(self.lbaas_l7rule_path % (l7policy, l7rule)) | 0.012121 |
def sign(self, secret=None):
"""Sign the generated :class:`TransactionEnvelope
<stellar_base.transaction_envelope.TransactionEnvelope>` from the list
of this builder's operations.
:param str secret: The secret seed to use if a key pair or secret was
not provided when this cl... | 0.003484 |
def interpolate_masked_data(data, mask, error=None, background=None):
"""
Interpolate over masked pixels in data and optional error or
background images.
The value of masked pixels are replaced by the mean value of the
connected neighboring non-masked pixels. This function is intended
for sing... | 0.000324 |
def get(self, account_id):
"""
Return a specific account given its ID
"""
response = self.client._make_request('/accounts/{0}'.format(account_id))
return response.json() | 0.014354 |
def typeseq(types):
"""
Returns an escape for a terminal text formatting type, or a list of types.
Valid types are:
* 'i' for 'italic'
* 'b' for 'bold'
* 'u' for 'underline'
* 'r' for 'reverse'
"""
ret = ""
for t in types:
ret += termcap.get(fmttypes[t])
... | 0.0059 |
def _rename_relation(self, old_key, new_relation):
"""Rename a relation named old_key to new_key, updating references.
Return whether or not there was a key to rename.
:param _ReferenceKey old_key: The existing key, to rename from.
:param _CachedRelation new_key: The new relation, to re... | 0.001435 |
def btc_is_p2pkh_address( address ):
"""
Is the given address a p2pkh address?
"""
vb = keylib.b58check.b58check_version_byte( address )
if vb == version_byte:
return True
else:
return False | 0.021739 |
def _on_hid_pnp(self, w_param, l_param):
"Process WM_DEVICECHANGE system messages"
new_status = "unknown"
if w_param == DBT_DEVICEARRIVAL:
# hid device attached
notify_obj = None
if int(l_param):
# Disable this error since pylint doesn't... | 0.003699 |
def parse_map_Ks(self):
"""Specular color map"""
Kd = os.path.join(self.dir, " ".join(self.values[1:]))
self.this_material.set_texture_specular_color(Kd) | 0.011299 |
def Set(self, interface_name, property_name, value, *args, **kwargs):
'''Standard D-Bus API for setting a property value'''
self.log('Set %s.%s%s' % (interface_name,
property_name,
self.format_args((value,))))
try:
... | 0.003493 |
def terminate(self, arg):
"""
Terminate instance with given EC2 ID or nametag.
"""
instance = self.get(arg)
with self.msg("Terminating %s (%s): " % (instance.name, instance.id)):
instance.rename("old-%s" % instance.name)
instance.terminate()
wh... | 0.004376 |
def to_array(self):
"""
Serializes this ChatMember to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(ChatMember, self).to_array()
array['user'] = self.user.to_array() # type User
array['status'] = u(self.... | 0.005806 |
def read_and_discard_input(environ):
"""Read 1 byte from wsgi.input, if this has not been done yet.
Returning a response without reading from a request body might confuse the
WebDAV client.
This may happen, if an exception like '401 Not authorized', or
'500 Internal error' was raised BEFORE anythin... | 0.00231 |
def get(self, resource_manager, identities):
"""Get resources by identities
"""
m = self.resolve(resource_manager.resource_type)
params = {}
client_filter = False
# Try to formulate server side query
if m.filter_name:
if m.filter_type == 'list':
... | 0.001864 |
def is_after_acc(self):
"""
Буква распологается после ударения.
"""
prev = self._prev_letter()
while True:
if not prev:
return False
if prev.is_shock():
return True
prev = prev._prev_letter() | 0.006689 |
def tspace_type(space, impl, dtype=None):
"""Select the correct corresponding tensor space.
Parameters
----------
space : `LinearSpace`
Template space from which to infer an adequate tensor space. If
it has a ``field`` attribute, ``dtype`` must be consistent with it.
impl : string
... | 0.000493 |
def getPacketSize(self):
"""
the current packet size.
:return: the current packet size based on the enabled registers.
"""
size = 0
if self.isAccelerometerEnabled():
size += 6
if self.isGyroEnabled():
size += 6
if self.isTemperature... | 0.005376 |
def replace_many(self, mongo_collection, docs,
filter_docs=None, mongo_db=None, upsert=False, collation=None,
**kwargs):
"""
Replaces many documents in a mongo collection.
Uses bulk_write with multiple ReplaceOne operations
https://api.mongodb.c... | 0.003564 |
def get_next(self, tag="<"):
"""
This function is tricky and took me a while to figure out.
The tag specifies the direction where the current edge came from.
tag ntag
---> V >----> U
cur next
This means the next vertex should follow the outs sinc... | 0.00191 |
def provision_system_vessel(items, database_name, overwrite=False, clear=False, skip_user_check=False):
"""Provisions the default system vessel"""
from hfos.provisions.base import provisionList
from hfos.database import objectmodels
vessel = objectmodels['vessel'].find_one({'name': 'Default System Ves... | 0.002275 |
def union(self, *others: 'Substitution') -> 'Substitution':
"""Try to merge the substitutions.
If a variable occurs in multiple substitutions, try to merge the replacements.
See :meth:`union_with_variable` to see how replacements are merged.
Does not modify any of the original substitu... | 0.003445 |
def close(self):
"""Close the underlying connection."""
self._closed = True
if self.receive_task:
self.receive_task.cancel()
if self.connection:
self.connection.close() | 0.008929 |
def accept_bras(cls, ops, kwargs):
"""Accept operands that are all bras, and turn that into to bra of the
operation applied to all corresponding kets"""
from qnet.algebra.core.state_algebra import Bra
kets = []
for bra in ops:
if isinstance(bra, Bra):
kets.append(bra.ket)
... | 0.002451 |
def _save_image(self, image_id, directory):
""" Saves the image as a tar archive under specified name """
for x in [0, 1, 2]:
self.log.info("Saving image %s to %s directory..." %
(image_id, directory))
self.log.debug("Try #%s..." % (x + 1))
... | 0.004084 |
def _restore_case(s, memory):
"""Restore a lowercase string's characters to their original case."""
cased_s = []
for i, c in enumerate(s):
if i + 1 > len(memory):
break
cased_s.append(c if memory[i] else c.upper())
return ''.join(cased_s) | 0.003546 |
def numKeys(self) -> int:
"""
This will iterate only over the last chunk since the name of the last
chunk indicates how many lines in total exist in all other chunks
"""
chunks = self._listChunks()
num_chunks = len(chunks)
if num_chunks == 0:
return 0
... | 0.003883 |
def seq(start=0, step=1):
"""An arithmetic sequence generator. Works with any type with + defined.
>>> seq(1, 0.25) >> item[:10]
[1, 1.25, 1.5, 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 3.25]
"""
def seq(a, d):
while 1:
yield a
a += d
return seq(start, step) | 0.037736 |
def write(self, data, dummy=None):
"""Stub Write method."""
assert not self.closed
if self.expected_write_data is None:
return
expected_data = self.expected_write_data.pop(0)
if expected_data != data:
raise ValueError('Expected %s, got %s (%s)' % (
self._dotify(expected_data),... | 0.008 |
def flush(self):
"""flush any buffered messages"""
buf = self.buf
self.buf = []
if buf:
self._flush(buf) | 0.013514 |
def norm_attr(self):
""" Normalize attr state
"""
if not self.HAS_ATTR:
return
self.HAS_ATTR = False
self.emit('call', 'COPY_ATTR', 0)
backend.REQUIRES.add('copy_attr.asm') | 0.008584 |
def apply_pending(self, panel_obj, version):
"""Apply the pending changes to an existing gene panel or create a new version of the same panel.
Args:
panel_obj(dict): panel in database to update
version(double): panel version to update
Returns:
inserted_id(st... | 0.002799 |
def main():
"""
Entry point for the VMNET tool.
"""
parser = argparse.ArgumentParser(description='%(prog)s add/remove vmnet interfaces')
parser.add_argument('-r', "--range", nargs='+', action=parse_vmnet_range(1, 255),
type=int, help="vmnet range to add (default is {} {})".f... | 0.005797 |
def get_forks(self):
"""
:calls: `GET /repos/:owner/:repo/forks <http://developer.github.com/v3/repos/forks>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
"""
return github.PaginatedList.PaginatedList(
Repository,
... | 0.009926 |
def translate(otp, to=MODHEX):
"""Return set() of possible modhex interpretations of a Yubikey otp.
If otp uses all 16 characters in its alphabet, there will be only
one possible interpretation of that Yubikey otp (except for two
Armenian keyboard layouts).
otp: Yubikey output.
to: 16-characte... | 0.000947 |
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs):
"""Open gzip compressed tar archive name for reading or writing.
Appending is not allowed.
"""
if len(mode) > 1 or mode not in "rw":
raise ValueError("mode must be 'r' or 'w'")
try:
... | 0.002854 |
def chunked_qs(qs, chunk_size=10000, fields=None):
"""
Generator to iterate over the given QuerySet, chunk_size rows at a time
Usage:
>>> qs = FailureLine.objects.filter(action='test_result')
>>> for qs in chunked_qs(qs, chunk_size=10000, fields=['id', 'message']):
... for line... | 0.001695 |
def getPrefixDirectories(self, engineRoot, delimiter=' '):
"""
Returns the list of prefix directories for this library, joined using the specified delimiter
"""
return delimiter.join(self.resolveRoot(self.prefixDirs, engineRoot)) | 0.029536 |
def get_missing_blocks(info_frags_records, matching_pairs, linkage_orderings):
"""Get missing blocks in a scaffold based on the genetic map order.
Given matching scaffold blocks/genetic map blocks (based on restriction
sites and SNP markers, respectively), move around the scaffold blocks
such that the... | 0.000735 |
def add_link_headers(response, links):
"""Return *response* with the proper link headers set, based on the contents
of *links*.
:param response: :class:`flask.Response` response object for links to be
added
:param dict links: Dictionary of links to be added
:rtype :class:`flask... | 0.003636 |
def _export_to_exporter(network, exporter, basename, export_standard_types=False):
"""
Export to exporter.
Both static and series attributes of components are exported, but only
if they have non-default values.
Parameters
----------
exporter : Exporter
Initialized exporter instance... | 0.005207 |
def fixed_legend_filter_sort(self, fixed_legend_filter_sort):
"""Sets the fixed_legend_filter_sort of this ChartSettings.
Whether to display \"Top\"- or \"Bottom\"-ranked series in the fixed legend # noqa: E501
:param fixed_legend_filter_sort: The fixed_legend_filter_sort of this ChartSetting... | 0.002621 |
def update(self, docs, golds, drop=0.0, sgd=None, losses=None, component_cfg=None):
"""Update the models in the pipeline.
docs (iterable): A batch of `Doc` objects.
golds (iterable): A batch of `GoldParse` objects.
drop (float): The droput rate.
sgd (callable): An optimizer.
... | 0.002079 |
def populate(self, priority, address, rtr, data):
"""
:return: None
"""
assert isinstance(data, bytes)
self.needs_high_priority(priority)
self.needs_no_rtr(rtr)
self.needs_data(data, 4)
self.set_attributes(priority, address, rtr)
self.relay_channel... | 0.004728 |
def _compare_replication(current, desired, region, key, keyid, profile):
'''
Replication accepts a non-ARN role name, but always returns an ARN
'''
if desired is not None and desired.get('Role'):
desired = copy.deepcopy(desired)
desired['Role'] = _get_role_arn(desired['Role'],
... | 0.006522 |
def multiselect(self, window_name, object_name, row_text_list, partial_match=False):
"""
Select multiple row
@param window_name: Window name to type in, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param object_name: Object name to... | 0.003152 |
def remove_container(name, force=False):
"""
Wrapper for docker remove_container
:returns: True if container was found and removed
"""
try:
if not force:
_get_docker().stop(name)
except APIError:
pass
try:
_get_docker().remove_container(name, force=True)... | 0.002618 |
def get_program_data_sharing_consent(username, program_uuid, enterprise_customer_uuid):
"""
Get the data sharing consent object associated with a certain user of a customer for a program.
:param username: The user that grants consent.
:param program_uuid: The program for which consent is granted.
:... | 0.004391 |
def RetryableExecutionPolicy(attempts=3, activate_hook=None):
"""
Create a :term:`execution policy` that catches any
:term:`retryable error` and sends it through the pipeline again up to
a maximum of ``attempts`` attempts.
If ``activate_hook`` is set it will be consulted prior to each request
t... | 0.000273 |
def get_bucket(self, key, rate=None, capacity=None, **kwargs):
"""Fetch a Bucket for the given key.
rate and capacity might be overridden from the Throttler defaults.
Args:
rate (float): Units regenerated by second, or None to keep
Throttler defaults
cap... | 0.003268 |
def GetWSAActionOutput(operation):
"""Find wsa:Action attribute, and return value or the default."""
attr = operation.output.action
if attr is not None:
return attr
targetNamespace = operation.getPortType().getTargetNamespace()
ptName = operation.getPortType().name
msgName = operation.ou... | 0.005435 |
def file_comparison(files0, files1):
"""Compares two dictionaries of files returning their difference.
{'created_files': [<files in files1 and not in files0>],
'deleted_files': [<files in files0 and not in files1>],
'modified_files': [<files in both files0 and files1 but different>]}
... | 0.000914 |
def process_signed_elements(self):
"""
Verifies the signature nodes:
- Checks that are Response or Assertion
- Check that IDs and reference URI are unique and consistent.
:returns: The signed elements tag names
:rtype: list
"""
sign_nodes = self.__query... | 0.004306 |
def create_sql(self, insert=False, version=False, version_fieldname=None,
fields=None, ec=None, compare=False):
"""
Create sql statement, do not process manytomany
"""
version_fieldname = version_fieldname or 'version'
#fix when d is empty, orm will not insert ... | 0.003336 |
def write_longstr(self, s):
"""Write a string up to 2**32 bytes long after encoding.
If passed a unicode string, encode as UTF-8.
"""
self._flushbits()
if isinstance(s, text_t):
s = s.encode('utf-8')
self.write_long(len(s))
self.out.write(s) | 0.006431 |
def export_widgets(self_or_cls, obj, filename, fmt=None, template=None,
json=False, json_path='', **kwargs):
"""
Render and export object as a widget to a static HTML
file. Allows supplying a custom template formatting string
with fields to interpolate 'js', 'css' ... | 0.001769 |
def push(self):
"""Push topics to Transifex."""
tx = Tx(self.tx_project_slug)
# asssemble the template catalog
template = babel.messages.catalog.Catalog()
for topic in self.desk.topics():
if topic.show_in_portal:
template.add(topic.name)
# s... | 0.002628 |
def get_comments(self):
"""
Returns the comments for the job, querying the
server if necessary.
"""
# Lazily load info
if self.info is None:
self.get_info()
if 'comments' in self.info:
return [structure['text'] for structure in self.info['... | 0.007916 |
def validate_deckspawn_p2th(provider: Provider, rawtx: dict, p2th: str) -> bool:
'''Return True if deck spawn pays to p2th in vout[0] and if the P2TH address
is correct. Otherwise raises InvalidDeckSpawn.
'''
try:
vout = rawtx["vout"][0]["scriptPubKey"].get("addresses")[0]
except TypeError:... | 0.007067 |
def should_skip_logging(func):
"""
Should we skip logging for this handler?
"""
disabled = strtobool(request.headers.get("x-request-nolog", "false"))
return disabled or getattr(func, SKIP_LOGGING, False) | 0.004464 |
def format(self, object, context, maxlevels, level):
"""Format object for a specific context, returning a string
and flags indicating whether the representation is 'readable'
and whether the object represents a recursive construct.
"""
return _safe_repr(object, context, maxlevels... | 0.006098 |
def send_workflow(self):
"""
With the workflow instance and the task invitation is assigned a role.
"""
task_invitation = TaskInvitation.objects.get(self.task_invitation_key)
wfi = task_invitation.instance
select_role = self.input['form']['select_role']
if wfi.cur... | 0.004024 |
def stop_process(self):
"""
Stops the child process.
"""
self._process.terminate()
if not self._process.waitForFinished(100):
self._process.kill() | 0.010101 |
def process_image(self, image, image_format, save_kwargs,
width, height):
"""
Return a BytesIO instance of `image` that fits in a bounding box.
Bounding box dimensions are `width`x`height`.
"""
imagefile = BytesIO()
image.thumbnail(
(wid... | 0.006329 |
def save(evt, designer):
"Basic save functionality: just replaces the gui code"
# ask the user if we should save the changes:
ok = gui.confirm("Save the changes?", "GUI2PY Designer",
cancel=True, default=True)
if ok:
wx_obj = evt.GetEventObject()
w = wx_obj.obj
... | 0.003365 |
def stop(self, ignore_state=False):
"""Stops the service."""
self.logger.debug("Stop service")
self._toggle_running(False, ignore_state) | 0.0125 |
def update_retrieved_if_new(olditem, newitem, days=180, retrieved_pid='P813'):
"""
# modifies olditem in place
"""
def ref_overwrite(oldref, newref, days):
"""
If the newref is the same as the oldref except the retrieved date is `days` newer, return True
... | 0.006839 |
def log_formatter(request=None):
"""
Log formatter used in our syslog
:param request: a request object
:returns: logging.Formatter
"""
if request:
format_str = ('%(asctime)s {ip} {name}: ENV={env} '
'REMOTE_IP=%(remote_ip)s REQUEST_ID=%(request_id)s '
... | 0.001161 |
def i2osp(x, x_len):
'''Converts the integer x to its big-endian representation of length
x_len.
'''
if x > 256**x_len:
raise exceptions.IntegerTooLarge
h = hex(x)[2:]
if h[-1] == 'L':
h = h[:-1]
if len(h) & 1 == 1:
h = '0%s' % h
x = binascii.unhexlify(h)
r... | 0.002801 |
def jsanitize(obj, strict=False, allow_bson=False):
"""
This method cleans an input json-like object, either a list or a dict or
some sequence, nested or otherwise, by converting all non-string
dictionary keys (such as int and float) to strings, and also recursively
encodes all objects using Monty's... | 0.001762 |
def checkout(self, force=False, **kwargs):
"""Checkout this head by setting the HEAD to this reference, by updating the index
to reflect the tree we point to and by updating the working tree to reflect
the latest index.
The command will fail if changed working tree files would be overwr... | 0.004788 |
def get_fw(self, fw_id):
"""Return the Firewall given its ID. """
fw = None
try:
fw = self.neutronclient.show_firewall(fw_id)
except Exception as exc:
LOG.error("Failed to get firewall list for id %(id)s, "
"Exc %(exc)s", {'id': fw_id, 'exc':... | 0.005731 |
def msll(y_true, y_pred, y_var, y_train):
"""
Mean standardised log loss under a Gaussian distribution.
Parameters
----------
y_true: ndarray
vector of true targets
y_pred: ndarray
vector of predicted targets
y_var: float or ndarray
predicted variances
y_train: n... | 0.001045 |
def get_version(package: Union[Path, str]) -> str:
"""Get the version of a package or module
Pass a module path or package name.
The former is recommended, since it also works for not yet installed packages.
Supports getting the version from
#. The directory name (as created by ``setup.py sdist``)
... | 0.002935 |
def create_new(mapreduce_id=None,
gettime=datetime.datetime.now):
"""Create a new MapreduceState.
Args:
mapreduce_id: Mapreduce id as string.
gettime: Used for testing.
"""
if not mapreduce_id:
mapreduce_id = MapreduceState.new_mapreduce_id()
state = MapreduceStat... | 0.006623 |
def compute_Kij(self, Xi, Xj, ni, nj, noise=False, hyper_deriv=None, k=None):
r"""Compute covariance matrix between datasets `Xi` and `Xj`.
Specify the orders of derivatives at each location with the `ni`, `nj`
arrays. The `include_noise` flag is passed to the covariance kernel to
... | 0.00381 |
def from_filename(filename, require=None):
"""Reads a Google service account JSON file and returns its parsed info.
Args:
filename (str): The path to the service account .json file.
require (Sequence[str]): List of keys required to be present in the
info.
Returns:
Tuple... | 0.001715 |
def _decrypt_asymmetric(
self,
decryption_algorithm,
decryption_key,
cipher_text,
padding_method,
hashing_algorithm=None):
"""
Encrypt data using asymmetric decryption.
Args:
decryption_algorithm (CryptographicA... | 0.000547 |
def get_build_params(metadata):
'''get_build_params uses get_build_metadata to retrieve corresponding meta data values for a build
:param metadata: a list, each item a dictionary of metadata, in format:
metadata = [{'key': 'repo_url', 'value': repo_url },
{'key': 'repo_id', 'value': repo_id ... | 0.006383 |
def request_check(client, exception, *msg_parms, **kwargs):
"""Make blocking request to client and raise exception if reply is not ok.
Parameters
----------
client : DeviceClient instance
exception: Exception class to raise
*msg_parms : Message parameters sent to the Message.request() call
... | 0.000698 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.