text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def has_parent_objective_banks(self, objective_bank_id):
"""Tests if the ``ObjectiveBank`` has any parents.
arg: objective_bank_id (osid.id.Id): the ``Id`` of an
objective bank
return: (boolean) - ``true`` if the objective bank has parents,
``false`` otherwise... | 0.003135 |
def heightmap_add_fbm(
hm: np.ndarray,
noise: tcod.noise.Noise,
mulx: float,
muly: float,
addx: float,
addy: float,
octaves: float,
delta: float,
scale: float,
) -> None:
"""Add FBM noise to the heightmap.
The noise coordinate for each map cell is
`((x + addx) * mulx / w... | 0.000737 |
def make_perfect_cd(wcs):
""" Create a perfect (square, orthogonal, undistorted) CD matrix from the
input WCS.
"""
def_scale = (wcs.pscale) / 3600.
def_orientat = np.deg2rad(wcs.orientat)
perfect_cd = def_scale * np.array(
[[-np.cos(def_orientat),np.sin(def_orientat)],
[np.s... | 0.007752 |
def reraise_as(new_exception_or_type):
"""
Obtained from https://github.com/dcramer/reraise/blob/master/src/reraise.py
>>> try:
>>> do_something_crazy()
>>> except Exception:
>>> reraise_as(UnhandledException)
"""
__traceback_hide__ = True # NOQA
e_type, e_value, e_tracebac... | 0.001385 |
def _check_authentication(self, request, request_args, request_kwargs):
"""
Checks a request object to determine if that request contains a valid,
and authenticated JWT.
It returns a tuple:
1. Boolean whether the request is authenticated with a valid JWT
2. HTTP status c... | 0.00226 |
def valueReadPreprocessor(valueString, replaceParamsFile=None):
"""
Apply global pre-processing to values during reading throughout the project.
Args:
valueString (str): String representing the value to be preprocessed.
replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of... | 0.00313 |
def get_subaccount_info(self):
"""Get information about a sub account."""
method = 'GET'
endpoint = '/rest/v1/users/{}/subaccounts'.format(
self.client.sauce_username)
return self.client.request(method, endpoint) | 0.007813 |
def to_dict(self):
"""
Convert current Pipeline (i.e. its attributes) into a dictionary
:return: python dictionary
"""
pipeline_desc_as_dict = {
'uid': self._uid,
'name': self._name,
'state': self._state,
'state_history': self._s... | 0.004587 |
def send(self, data):
"""
Sends the given data to the socket via UDP
"""
try:
self.socket.sendto(data.encode('utf8') + b'\n', (self.host, self.port))
except (socket.error, RuntimeError):
# Socket errors should fail silently so they don't affect anything el... | 0.011799 |
def deregister(self, pin_num=None, direction=None):
"""De-registers callback functions
:param pin_num: The pin number. If None then all functions are de-registered
:type pin_num: int
:param direction: The event direction. If None then all functions for the
give... | 0.015094 |
def get_centroids(data,k,labels,centroids,data_norms):
"""
For each element in the dataset, choose the closest centroid
Parameters
------------
data: array-like, shape= (m_samples,n_samples)
K: integer, number of K clusters
centroids: array-like, shape=(K, n_samples)
labels: ... | 0.019704 |
def ensure_path_exists(dir_path):
"""
Make sure that a path exists
"""
if not os.path.exists(dir_path):
mkdir(dir_path)
return True
return False | 0.005556 |
def isthaichar(ch: str) -> bool:
"""
Check if a character is Thai
เป็นอักษรไทยหรือไม่
:param str ch: input character
:return: True or False
"""
ch_val = ord(ch)
if ch_val >= 3584 and ch_val <= 3711:
return True
return False | 0.003731 |
def auto_detect(workdir):
""" Return string signifying the SCM used in the given directory.
Currently, 'git' is supported. Anything else returns 'unknown'.
"""
# Any additions here also need a change to `SCM_PROVIDERS`!
if os.path.isdir(os.path.join(workdir, '.git')) and os.path.isfile(os.path.... | 0.005076 |
def filter_by_program(self, prg, opFile):
"""
parse the log files and extract entries from all
logfiles to one file per program (program is the
2nd to last entry each logfile)
"""
log_1 = open(self.process_file, 'r')
log_2 = open(self.command_file, 'r')
... | 0.006024 |
def _run_submission(self, metadata):
"""Runs submission inside Docker container.
Args:
metadata: dictionary with submission metadata
Returns:
True if status code of Docker command was success (i.e. zero),
False otherwise.
"""
if self._use_gpu:
docker_binary = 'nvidia-docker... | 0.00495 |
def visit_root(self, _, children):
"""The main node holding all the query.
Arguments
---------
_ (node) : parsimonious.nodes.Node.
children : list
- 0: for ``WS`` (whitespace): ``None``.
- 1: for ``NAMED_RESOURCE``: an instance of a subclass of ``.resourc... | 0.003058 |
def insert(self, loc, column, value, allow_duplicates=False):
"""
Insert column into DataFrame at specified location.
Raises a ValueError if `column` is already contained in the DataFrame,
unless `allow_duplicates` is set to True.
Parameters
----------
loc : int... | 0.002522 |
def get_filename(file):
"""
Safe method to retrieve only the name of the file.
:param file: Path of the file to retrieve the name from.
:return: None if the file is non-existant, otherwise the filename (extension included)
:rtype: None, str
"""
if not os.path.exists(file):
return Non... | 0.005495 |
def wait(self, timeout=None):
"""
Block until all jobs in the ThreadPool are finished. Beware that this can
make the program run into a deadlock if another thread adds new jobs to the
pool!
# Raises
Timeout: If the timeout is exceeded.
"""
if not self.__running:
raise RuntimeErro... | 0.005263 |
def setup_logical_port_connectivity(self, context, port_db,
hosting_device_id):
"""Establishes connectivity for a logical port.
This is done by hot plugging the interface(VIF) corresponding to the
port from the VM.
"""
hosting_port = port_... | 0.002134 |
def help_center_articles_labels_list(self, locale=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/labels#list-all-labels"
api_path = "/api/v2/help_center/articles/labels.json"
if locale:
api_opt_path = "/api/v2/help_center/{locale}/articles/labels.json"
... | 0.007177 |
def get_driver_class(provider):
"""
Return the driver class
:param provider: str - provider name
:return:
"""
if "." in provider:
parts = provider.split('.')
kls = parts.pop()
path = '.'.join(parts)
module = import_module(path)
if not hasattr(module, kls):... | 0.00177 |
def as_wfn(self):
"""
Returns the CPE Name as WFN string of version 2.3.
Only shows the first seven components.
:return: CPE Name as WFN string
:rtype: string
:exception: TypeError - incompatible version
"""
wfn = []
wfn.append(CPE2_3_WFN.CPE_PRE... | 0.001658 |
def register_producer(cls, producer):
"""
Register a default producer for events to use.
:param producer: the default producer to to dispatch events on.
"""
log.info('@Registry.register_producer `{}`'
.format(producer.__class__.__name__))
cls._producer = ... | 0.005764 |
def chunked(self):
"""Returns a boolean indicating if the guild is "chunked".
A chunked guild means that :attr:`member_count` is equal to the
number of members stored in the internal :attr:`members` cache.
If this value returns ``False``, then you should request for
offline mem... | 0.004132 |
def set_data_length(self, length):
# type: (int) -> None
'''
A method to set the length of the data that this Directory Record
points to.
Parameters:
length - The new length for the data.
Returns:
The length of the data that this Directory Record points... | 0.008 |
def Write(self, grr_message):
"""Write the message into the transaction log.
Args:
grr_message: A GrrMessage instance.
"""
grr_message = grr_message.SerializeToString()
try:
winreg.SetValueEx(_GetServiceKey(), "Transaction", 0, winreg.REG_BINARY,
grr_message)
... | 0.010695 |
def __embed_branch(dfs_data):
"""Builds the combinatorial embedding of the graph. Returns whether the graph is planar."""
u = dfs_data['ordering'][0]
dfs_data['LF'] = []
dfs_data['RF'] = []
dfs_data['FG'] = {}
n = dfs_data['graph'].num_nodes()
f0 = (0, n)
g0 = (0, n)
L0 = {'u': 0, 'v... | 0.008706 |
def payload(self):
"""Extracts and returns the serialized object."""
try:
rdf_cls = self.classes.get(self.name)
if rdf_cls:
value = rdf_cls.FromSerializedString(self.data)
value.age = self.embedded_age
return value
except TypeError:
return None | 0.013378 |
def create_api_object_group_permission_general(self):
"""Get an instance of Api Vip Requests services facade."""
return ApiObjectGroupPermissionGeneral(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | 0.007143 |
def make_driveritem_deviceitem_devicename(device_name, condition='is', negate=False, preserve_case=False):
"""
Create a node for DriverItem/DeviceItem/DeviceName
:return: A IndicatorItem represented as an Element node
"""
document = 'DriverItem'
search = 'DriverItem/DeviceItem/DeviceName'
... | 0.008636 |
def post_mark_translated(self, post_id, check_translation,
partially_translated):
"""Mark post as translated (Requires login) (UNTESTED).
If you set check_translation and partially_translated to 1 post will
be tagged as 'translated_request'
Parameters:
... | 0.004032 |
def police_priority_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name = ET.SubElement(police_priority_map, "name")
name.t... | 0.006897 |
def build(args):
"""
%prog build [prot.fasta] cds.fasta [options] --outdir=outdir
This function wraps on the following steps:
1. msa using ClustalW2 or MUSCLE(default)
2. (optional) alignment editing using Gblocks
3. build NJ tree using PHYLIP in EMBOSS package
seq names should be unique... | 0.004558 |
def diagonal_gaussian_posterior_builder(
getter, name, shape=None, *args, **kwargs):
"""A pre-canned builder for diagonal gaussian posterior distributions.
Given a true `getter` function and arguments forwarded from `tf.get_variable`,
return a distribution object for a diagonal posterior over a variable of t... | 0.007908 |
def obj(extract=None, child_transform=None, transform=None):
"""Returns a partial of get_obj that only needs a source argument."""
return lambda source: get_obj(source, extract, child_transform, transform) | 0.014354 |
def fix_script(path):
"""Replace #!python with #!/path/to/python
Return True if file was changed."""
# XXX RECORD hashes will need to be updated
if os.path.isfile(path):
with open(path, 'rb') as script:
firstline = script.readline()
if not firstline.startswith(b'#!python'... | 0.001529 |
def validate_key(key: str):
"""
Validates the given key.
:param key: the key to validate
:raises InvalidKeyError: raised if the given key is invalid
"""
if "//" in key:
raise DoubleSlashKeyError(key)
elif normpath(key) != key:
raise NonNorm... | 0.0059 |
def load_tiff_multipage(tiff_filename, dtype='float32'):
"""
Load a multipage tiff into a single variable in x,y,z format.
Arguments:
tiff_filename: Filename of source data
dtype: data type to use for the returned tensor
Returns:
Array containing contents from i... | 0.00097 |
async def jsk_git(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Shortcut for 'jsk sh git'. Invokes the system shell.
"""
return await ctx.invoke(self.jsk_shell, argument=Codeblock(argument.language, "git " + argument.content)) | 0.014286 |
def blobs(n_variables=11, n_centers=5, cluster_std=1.0, n_observations=640) -> AnnData:
"""Gaussian Blobs.
Parameters
----------
n_variables : `int`, optional (default: 11)
Dimension of feature space.
n_centers : `int`, optional (default: 5)
Number of cluster centers.
cluster_st... | 0.002735 |
def _generate_create_dict(self,
size=None,
hostname=None,
domain=None,
location=None,
os=None,
port_speed=None,
... | 0.00509 |
def extractContent(self, text):
"""Extract the content of comment text.
"""
m = self.nextValidComment(text)
return '' if m is None else m.group(1) | 0.011111 |
def run(self):
"""Runs the process."""
# Prevent the KeyboardInterrupt being raised inside the process.
# This will prevent a process from generating a traceback when interrupted.
signal.signal(signal.SIGINT, signal.SIG_IGN)
# A SIGTERM signal handler is necessary to make sure IPC is cleaned up
... | 0.001178 |
def nrefs(self, tag):
"""Determine the number of tags of a given type in a vgroup.
Args::
tag tag type to look for in the vgroup
Returns::
number of members identified by this tag type
C library equivalent : Vnrefs
... | 0.004695 |
def get_output(self):
"""
Retrieve the stored data in full.
This call may block if the reading thread has not yet terminated.
"""
self._closing = True
if not self.has_finished():
if self._debug:
# Main thread overtook stream reading thread.
... | 0.001663 |
def ipfn_np(self, m, aggregates, dimensions, weight_col='total'):
"""
Runs the ipfn method from a matrix m, aggregates/marginals and the dimension(s) preserved.
For example:
from ipfn import ipfn
import numpy as np
m = np.array([[8., 4., 6., 7.], [3., 6., 5., 2.], [9., 11... | 0.003007 |
def markDownloaded(self, media):
""" Mark the file as downloaded (by the nature of Plex it will be marked as downloaded within
any SyncItem where it presented).
Parameters:
media (base.Playable): the media to be marked as downloaded.
"""
url = '/sync/%s/i... | 0.009195 |
def get_organizer(self, id, **data):
"""
GET /organizers/:id/
Gets an :format:`organizer` by ID as ``organizer``.
"""
return self.get("/organizers/{0}/".format(id), data=data) | 0.013393 |
def wait_for(func):
"""
A decorator to invoke a function periodically until it returns a truthy
value.
"""
def wrapped(*args, **kwargs):
timeout = kwargs.pop('timeout', 15)
start = time()
result = None
while time() - start < timeout:
result = func(*args... | 0.002262 |
def remove_metadata_key(self, key, prefix=None):
"""
Removes the specified key from the storage object's metadata. If the
key does not exist in the metadata, nothing is done.
"""
self.manager.remove_metadata_key(self, key, prefix=prefix) | 0.00722 |
def splitstring(string, splitcharacter=' ', part=None):
"""
Split a string based on a character and get the parts as a list.
:type string: string
:param string: The string to split.
:type splitcharacter: string
:param splitcharacter: The character to split for the string.
:type part: inte... | 0.00099 |
def add_germline_variants(self, germline_nucs, coding_pos):
"""Add potential germline variants into the nucleotide sequence.
Sequenced individuals may potentially have a SNP at a somatic mutation position.
Therefore they may differ from the reference genome. This method updates the gene
... | 0.005042 |
def dense_rank(series, ascending=True):
"""
Equivalent to `series.rank(method='dense', ascending=ascending)`.
Args:
series: column to rank.
Kwargs:
ascending (bool): whether to rank in ascending order (default is `True`).
"""
ranks = series.rank(method='dense', ascending=ascen... | 0.005848 |
def decode(self,
dataset_split=None,
decode_from_file=False,
checkpoint_path=None):
"""Decodes from dataset or file."""
if decode_from_file:
decoding.decode_from_file(self._estimator,
self._decode_hparams.decode_from_file,
... | 0.008253 |
def handle_rfx(sender, message):
"""
Handles RF message events from the AlarmDecoder.
"""
# Check for our target serial number and loop
if message.serial_number == RF_DEVICE_SERIAL_NUMBER and message.loop[0] == True:
print(message.serial_number, 'triggered loop #1') | 0.010204 |
def _setup_catalog(portal, catalog_id, catalog_definition):
"""
Given a catalog definition it updates the indexes, columns and content_type
definitions of the catalog.
:portal: the Plone site object
:catalog_id: a string as the catalog id
:catalog_definition: a dictionary like
{
... | 0.000534 |
def update(self, unique_name=values.unset, default_ttl=values.unset,
callback_url=values.unset, geo_match_level=values.unset,
number_selection_behavior=values.unset,
intercept_callback_url=values.unset,
out_of_session_callback_url=values.unset,
... | 0.007104 |
def update_shared_sources(f):
"""
Context manager to ensures data sources shared between multiple
plots are cleared and updated appropriately avoiding warnings and
allowing empty frames on subplots. Expects a list of
shared_sources and a mapping of the columns expected columns for
each source in... | 0.001762 |
def fileinfo(fileobj, filename=None, content_type=None, existing=None):
"""Tries to extract from the given input the actual file object, filename and content_type
This is used by the create and replace methods to correctly deduce their parameters
from the available information when possible.
... | 0.009852 |
def simxJointGetForce(clientID, jointHandle, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
force = ct.c_float()
return c_GetJointForce(clientID, jointHandle, ct.byref(force), operationMode), force.value | 0.01049 |
def iter_random_chars(bits,
keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Yields a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entr... | 0.001314 |
def min_conflicts_value(csp, var, current):
"""Return the value that will give var the least number of conflicts.
If there is a tie, choose at random."""
return argmin_random_tie(csp.domains[var],
lambda val: csp.nconflicts(var, val, current)) | 0.003521 |
def parse_bismark_mbias(self, f):
""" Parse the Bismark M-Bias plot data """
s = f['s_name']
self.bismark_mbias_data['meth']['CpG_R1'][s] = {}
self.bismark_mbias_data['meth']['CHG_R1'][s] = {}
self.bismark_mbias_data['meth']['CHH_R1'][s] = {}
self.bismark_mbias_data['cov'... | 0.002447 |
def get_registered_instances(self, include_removed=False):
""" Return the persisted names of all instances across all registered configs.
"""
rval = []
configs = self.state.get('config_files', {}).values()
if include_removed:
configs.extend(self.state.get('remove_conf... | 0.006061 |
def query_bulk(names):
"""Query server with multiple entries."""
answers = [__threaded_query(name) for name in names]
while True:
if all([a.done() for a in answers]):
break
sleep(1)
return [answer.result() for answer in answers] | 0.00365 |
def list_queue(self, embed_last_unused_offers=False):
"""List all the tasks queued up or waiting to be scheduled.
:returns: list of queue items
:rtype: list[:class:`marathon.models.queue.MarathonQueueItem`]
"""
if embed_last_unused_offers:
params = {'embed': 'lastUnu... | 0.005535 |
def write_raw_byte(self, value):
"""
Writes an 8-bit byte directly to the bus
"""
self.bus.write_byte(self.address, value)
self.log.debug("write_raw_byte: Wrote 0x%02X" % value) | 0.009217 |
def _display_token(self):
"""
Display token information or redirect to login prompt if none is
available.
"""
if self.token is None:
return "301 Moved", "", {"Location": "/login"}
return ("200 OK",
self.TOKEN_TEMPLATE.format(
... | 0.004866 |
def saved_searches_factory_helper(splunk_connection_info):
"""Return a valid splunklib.client.SavedSearches object
kwargs:
- see splunklib.client.connect()
"""
if not ISplunkConnectionInfo.providedBy(splunk_connection_info):
DoesNotImplement('argument did not provide expected interf... | 0.003676 |
def get_as_nullable_type(self, key, value_type):
"""
Converts map element into a value defined by specied typecode.
If conversion is not possible it returns None.
:param key: an index of element to get.
:param value_type: the TypeCode that defined the type of the result
... | 0.005825 |
def _retry_task(provider, job_descriptor, task_id, task_attempt):
"""Retry task_id (numeric id) assigning it task_attempt."""
td_orig = job_descriptor.find_task_descriptor(task_id)
new_task_descriptors = [
job_model.TaskDescriptor({
'task-id': task_id,
'task-attempt': task_attempt
... | 0.009642 |
def _set_rbridge_id(self, v, load=False):
"""
Setter method for rbridge_id, mapped from YANG variable /preprovision/rbridge_id (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_rbridge_id is considered as a private
method. Backends looking to populate this varia... | 0.003675 |
def parse_instruction(string, location, tokens):
"""Parse an ARM instruction.
"""
mnemonic_str = tokens.get("mnemonic")
operands = [op for op in tokens.get("operands", [])]
instr = ArmInstruction(
string,
mnemonic_str["ins"],
operands,
arch_info.architecture_mode
... | 0.00319 |
def LoadFromString(cls, yaml_doc):
"""Creates an AdWordsClient with information stored in a yaml string.
Args:
yaml_doc: The yaml string containing the cached AdWords data.
Returns:
An AdWordsClient initialized with the values cached in the string.
Raises:
A GoogleAdsValueError if t... | 0.001548 |
def _place_ticks_horizontal(self):
"""Display the ticks for a horizontal scale."""
# first tick
tick = self.ticks[0]
label = self.ticklabels[0]
x = self.convert_to_pixels(tick)
half_width = label.winfo_reqwidth() / 2
if x - half_width < 0:
x = half_wid... | 0.002312 |
def unique(self, name):
"""Make a variable name unique by appending a number if needed."""
# Make sure the name is valid
name = self.valid(name)
# Make sure it's not too long
name = self.trim(name)
# Now make sure it's unique
unique_name = name
i = 2
while unique_name in self.names:
... | 0.007126 |
def Laliberte_viscosity(T, ws, CASRNs):
r'''Calculate the viscosity of an aqueous mixture using the form proposed by [1]_.
Parameters are loaded by the function as needed. Units are Kelvin and Pa*s.
.. math::
\mu_m = \mu_w^{w_w} \Pi\mu_i^{w_i}
Parameters
----------
T : float
Te... | 0.002708 |
def verify_config_container(object_):
"""Verify object is a valid config container
Valid config containers provide zope.interface.common.mapping.IEnumerableMapping
or an iterable of zope.interface.common.mapping.IEnumerableMapping.
verification is performed by checking required interfaces attr... | 0.00995 |
def unreplicate_vm_image(self, vm_image_name):
'''
Unreplicate a VM image from all regions This operation
is only for publishers. You have to be registered as image publisher
with Microsoft Azure to be able to call this
vm_image_name:
Specifies the name of the VM Ima... | 0.002674 |
def asyncPipeUnion(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that asynchronously merges multiple source together.
Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : unused
... | 0.001647 |
def percentileofscore(inlist, score, histbins=10, defaultlimits=None):
"""
Returns the percentile value of a score relative to the distribution
given by inlist. Formula depends on the values used to histogram the data(!).
Usage: lpercentileofscore(inlist,score,histbins=10,defaultlimits=None)
"""
h, lrl, bi... | 0.003401 |
def __createElementNS(self, root, uri, name, value):
'''
Creates and returns an element with a qualified name and a name space
@param root:Element Parent element
@param uri:str Namespace URI
@param tag:str Tag name.
'''
tag = root.ownerDocument.createElementNS(to_... | 0.003676 |
def _parse_path(self, path):
"""
Parses a Registry path and returns the hive and key.
@type path: str
@param path: Registry path.
@rtype: tuple( int, str )
@return: Tuple containing the hive handle and the subkey path.
For a local Registry, the hive handle... | 0.003419 |
def outputs_of(self, idx, create=False):
""" Get a set of the outputs for a given node index.
"""
if create and not idx in self.edges:
self.edges[idx] = set()
return self.edges[idx] | 0.013333 |
def get_resource_mapping():
"""Map resources used in the routes to portal types
:returns: Mapping of resource->portal_type
:rtype: dict
"""
portal_types = get_portal_types()
resources = map(portal_type_to_resource, portal_types)
return dict(zip(resources, portal_types)) | 0.003344 |
def collaborators(self):
"""
| Comment: Who are currently CC'ed on the ticket
"""
if self.api and self.collaborator_ids:
return self.api._get_users(self.collaborator_ids) | 0.009302 |
def markPartitionForEvent(self, db_name, tbl_name, part_vals, eventType):
"""
Parameters:
- db_name
- tbl_name
- part_vals
- eventType
"""
self.send_markPartitionForEvent(db_name, tbl_name, part_vals, eventType)
self.recv_markPartitionForEvent() | 0.003509 |
def generic_find_uq_constraint_name(table, columns, insp):
"""Utility to find a unique constraint name in alembic migrations"""
for uq in insp.get_unique_constraints(table):
if columns == set(uq['column_names']):
return uq['name'] | 0.003861 |
def mcc(y_true, y_pred, round=True):
"""Matthews correlation coefficient
"""
y_true, y_pred = _mask_value_nan(y_true, y_pred)
if round:
y_true = np.round(y_true)
y_pred = np.round(y_pred)
return skm.matthews_corrcoef(y_true, y_pred) | 0.003731 |
def parse_args(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
"""Parse arguments from functions
Args:
bels: BEL string as list of chars
char_locs: char locations for parens, commas and quotes
parsed: function locations
errors: er... | 0.002525 |
def is_signature_equal(cls, sig_a, sig_b):
"""Compares two signatures using a constant time algorithm to avoid timing attacks."""
if len(sig_a) != len(sig_b):
return False
invalid_chars = 0
for char_a, char_b in zip(sig_a, sig_b):
if char_a != char_b:
... | 0.007958 |
def mode_key_up(self, viewer, keyname):
"""This method is called when a key is pressed in a mode and was
not handled by some other handler with precedence, such as a
subcanvas.
"""
# Is this a mode key?
if keyname not in self.mode_map:
# <== no
ret... | 0.002621 |
def parse_parameters(self, parameters):
"""Parses and sets parameters in the model."""
self.parameters = []
for param_name, param_value in parameters.items():
p = Parameter(param_name, param_value)
if p:
self.parameters.append(p) | 0.006803 |
def is_error(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.ERROR | 0.012658 |
def _match_and_pop(self, regex_pattern):
"""Pop one event from each of the event queues whose names
match (in a sense of regular expression) regex_pattern.
"""
results = []
self.lock.acquire()
for name in self.event_dict.keys():
if re.match(regex_pattern, name... | 0.005245 |
def deserialize(serialized_script):
'''
bytearray -> str
'''
deserialized = []
i = 0
while i < len(serialized_script):
current_byte = serialized_script[i]
if current_byte == 0xab:
raise NotImplementedError('OP_CODESEPARATOR is a bad idea.')
if current_byte <= ... | 0.000558 |
def _to_lower_alpha_only(s):
"""Return a lowercased string with non alphabetic chars removed.
White spaces are not to be removed."""
s = re.sub(r'\n', ' ', s.lower())
return re.sub(r'[^a-z\s]', '', s) | 0.004587 |
def get_resource_value(self, device_id, resource_path, fix_path=True, timeout=None):
"""Get a resource value for a given device and resource path by blocking thread.
Example usage:
.. code-block:: python
try:
v = api.get_resource_value(device_id, path)
... | 0.007149 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.