text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def validate_gate():
"""Check Gate connection."""
try:
credentials = get_env_credential()
LOG.debug('Found credentials: %s', credentials)
LOG.info('Gate working.')
except TypeError:
LOG.fatal('Gate connection not valid: API_URL = %s', API_URL) | 0.003484 |
def execFontDialog(self):
""" Opens a QColorDialog for the user
"""
currentFont = self.getData()
newFont, ok = QtGui.QFontDialog.getFont(currentFont, self)
if ok:
self.setData(newFont)
else:
self.setData(currentFont)
self.commitAndClose() | 0.006289 |
def plotXYCatalog(self, **kwargs):
"""
Plots the source catalog positions using matplotlib's `pyplot.plot()`
Plotting `kwargs` that can also be passed include any keywords understood
by matplotlib's `pyplot.plot()` function such as::
vmin, vmax, cmap, marker
"""
... | 0.011472 |
def do_rebootInstance(self,args):
"""Restart specified instance"""
parser = CommandArgumentParser("rebootInstance")
parser.add_argument(dest='instance',help='instance index or name');
args = vars(parser.parse_args(args))
instanceId = args['instance']
try:
ind... | 0.009346 |
def draw_samples(self, sequences, n_samples, random_state=None):
"""Sample conformations for a sequences of states.
Parameters
----------
sequences : list or list of lists
A sequence or list of sequences, in which each element corresponds
to a state label.
... | 0.001276 |
def partitionBy(self, *cols):
"""Partitions the output by the given columns on the file system.
If specified, the output is laid out on the file system similar
to Hive's partitioning scheme.
:param cols: name of columns
>>> df.write.partitionBy('year', 'month').parquet(os.path... | 0.005367 |
def register(linter):
"""Required method to auto register this checker.
:param linter: Main interface object for Pylint plugins
:type linter: Pylint object
"""
warnings.warn(
"This plugin is deprecated, use pylint.extensions.docparams instead.",
DeprecationWarning,
)
linter.... | 0.002625 |
def process_child(node):
"""This function changes class references to not have the
intermediate module name by hacking at the doctree"""
# Edit descriptions to be nicer
if isinstance(node, sphinx.addnodes.desc_addname):
if len(node.children) == 1:
child = node.children[0]
... | 0.000987 |
def main(graph: BELGraph, xlsx: str, tsvs: str):
"""Export the graph to a SPIA Excel sheet."""
if not xlsx and not tsvs:
click.secho('Specify at least one option --xlsx or --tsvs', fg='red')
sys.exit(1)
spia_matrices = bel_to_spia_matrices(graph)
if xlsx:
spia_matrices_to_excel... | 0.002463 |
def salt_refs(data, ret=None):
'''
Pull salt file references out of the states
'''
proto = 'salt://'
if ret is None:
ret = []
if isinstance(data, six.string_types):
if data.startswith(proto) and data not in ret:
ret.append(data)
if isinstance(data, list):
... | 0.002079 |
def setstrs(self, label, unit, format):
"""Set the dimension standard string attributes.
Args::
label dimension label (attribute 'long_name')
unit dimension unit (attribute 'units')
format dimension format (attribute 'format')
Returns::
None
... | 0.003711 |
def subscriptions(self):
"""Fetch and return Subscriptions associated with this user."""
if not hasattr(self, '_subscriptions'):
subscriptions_resource = self.resource.subscriptions
self._subscriptions = Subscriptions(
subscriptions_resource, self.client)
... | 0.00578 |
def create_zipfile(context):
"""This is the actual zest.releaser entry point
Relevant items in the context dict:
name
Name of the project being released
tagdir
Directory where the tag checkout is placed (*if* a tag
checkout has been made)
version
Version we're rel... | 0.001259 |
def normalize_nfc(txt):
"""
Normalize message to NFC and return bytes suitable for protobuf.
This seems to be bitcoin-qt standard of doing things.
"""
if isinstance(txt, bytes):
txt = txt.decode()
return unicodedata.normalize("NFC", txt).encode() | 0.003597 |
def denormalize_volume(volume):
'''convert volume metadata from archivant to es format'''
id = volume.get('id', None)
res = dict()
res.update(volume['metadata'])
denorm_attachments = list()
for a in volume['attachments']:
denorm_attachments.append(Archivant.de... | 0.004808 |
def complete(
text: str, kw_cache: atom.Atom["PMap[int, Keyword]"] = __INTERN
) -> Iterable[str]:
"""Return an iterable of possible completions for the given text."""
assert text.startswith(":")
interns = kw_cache.deref()
text = text[1:]
if "/" in text:
prefix, suffix = text.split("/", ... | 0.001372 |
def send_element(self, element):
"""
Send an element via the transport.
"""
with self.lock:
if self._eof or self._socket is None or not self._serializer:
logger.debug("Dropping element: {0}".format(
element_to_un... | 0.004329 |
def update_aliases(aliases,aonly,x):
"helper for ctor. takes AliasX or string as second arg"
if isinstance(x,basestring): aliases[x]=x
elif isinstance(x,sqparse2.AliasX):
if not isinstance(x.alias,basestring): raise TypeError('alias not string',type(x.alias))
if isinstance(x.name,sqparse2.NameX)... | 0.045526 |
def merge_truthy(*dicts):
"""Merge multiple dictionaries, keeping the truthy values in case of key collisions.
Accepts any number of dictionaries, or any other object that returns a 2-tuple of
key and value pairs when its `.items()` method is called.
If a key exists in multiple dictionaries passed to ... | 0.00672 |
def createBracketOrder(self, contract, quantity,
entry=0., target=0., stop=0.,
targetType=None, trailingStop=None, group=None, tif="DAY",
fillorkill=False, iceberg=False, rth=False, stop_limit=False,
transmit=True, account=None, **kwargs):
"""
creates One... | 0.029884 |
def wrap_node(self, node, options):
'''\
celery registers tasks by decorating them, and so do we, so the user
can pass a celery task and we'll wrap our code with theirs in a nice
package celery can execute.
'''
if 'celery_task' in options:
return options['cele... | 0.005348 |
def out_of_bag_mae(self):
"""
Returns the mean absolute error for predictions on the out-of-bag
samples.
"""
if not self._out_of_bag_mae_clean:
try:
self._out_of_bag_mae = self.test(self.out_of_bag_samples)
self._out_of_bag_mae_clean = ... | 0.00463 |
def upload(self, name: str) -> bool:
"""
Attempts to upload a given Docker image from this server to DockerHub.
Parameters:
name: the name of the Docker image.
Returns:
`True` if successfully uploaded, otherwise `False`.
"""
try:
out ... | 0.002103 |
def serialize(self, as_private=None):
"""
Yield a 74-byte binary blob corresponding to this node.
You must add a 4-byte prefix before converting to base58.
"""
if as_private is None:
as_private = self.secret_exponent() is not None
if self.secret_exponent() is ... | 0.004032 |
def set_eol_chars(self, text):
"""Set widget end-of-line (EOL) characters from text (analyzes text)"""
if not is_text_string(text): # testing for QString (PyQt API#1)
text = to_text_string(text)
eol_chars = sourcecode.get_eol_chars(text)
is_document_modified = eol_chars ... | 0.006723 |
def curry(f, *args0, **kwargs0):
'''
curry(f, ...) yields a function equivalent to f with all following arguments and keyword
arguments passed. This is much like the partial function, but yields a function instead of
a partial object and thus is suitable for use with pimms lazy maps.
'''
def... | 0.009302 |
def _GetEventData(
self, parser_mediator, record_index, evt_record, recovered=False):
"""Retrieves event data from the Windows EventLog (EVT) record.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
record... | 0.004751 |
def write(source_mapping, output_stream=sys.stdout):
"""This method writes a Python module respresenting all the keys
and values known to configman.
"""
# a set of classes, modules and/or functions that are values in
# configman options. These values will have to be imported in ... | 0.000639 |
def avl_split(root, node):
"""
O(log(n))
Args:
root (Node): tree root
node (Node): node to split at
Returns:
puple: (tl, tr, node)
tl contains all keys in the tree less than node
tr contains all keys in the tree greater than node
node is the ... | 0.000305 |
def AddFiles(self, hash_id_metadatas):
"""Adds multiple files to the file store.
Args:
hash_id_metadatas: A dictionary mapping hash ids to file metadata (a tuple
of hash client path and blob references).
"""
for hash_id, metadata in iteritems(hash_id_metadatas):
self.AddFile(hash_id... | 0.009063 |
def colourblind(i):
'''
colour pallete from http://tableaufriction.blogspot.ro/
allegedly suitable for colour-blind folk
SJ
'''
rawRGBs = [(162,200,236),
(255,128,14),
(171,171,171),
(95,158,209),
(89,89,89),
... | 0.043478 |
def get_notificant(self, id, **kwargs): # noqa: E501
"""Get a specific notification target # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_notificant(id, ... | 0.00227 |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(FilestatCollector, self).get_default_config()
config.update({
'path': 'files',
'user_include': None,
'user_exclude': None,
'group_includ... | 0.003571 |
def _socket_close(self):
"""cleanup after the socket is closed by the other end"""
callback = self.__callback
self.__callback = None
try:
if callback:
callback(None, InterfaceError('connection closed'))
finally:
# Flush the job queue, don't... | 0.007055 |
def workflow_stages(self) -> List[WorkflowStage]:
"""Return list of workflow stages.
Returns:
dict, resources of a specified pb
"""
workflow_stages = []
stages = DB.get_hash_value(self.key, 'workflow_stages')
for index in range(len(ast.literal_eval(stages)))... | 0.004785 |
def _load_general(data, targets, major_axis):
"""Load a list of arrays into a list of arrays specified by slices."""
for d_src, d_targets, axis in zip(data, targets, major_axis): # pylint: disable=too-many-nested-blocks
if isinstance(d_targets, nd.NDArray):
d_src.copyto(d_targets)
el... | 0.004077 |
def create(cls, bucket, key, value):
"""Create a new tag for bucket."""
with db.session.begin_nested():
obj = cls(
bucket_id=as_bucket_id(bucket),
key=key,
value=value
)
db.session.add(obj)
return obj | 0.006494 |
def arc_negative(self, xc, yc, radius, angle1, angle2):
"""Adds a circular arc of the given radius to the current path.
The arc is centered at ``(xc, yc)``,
begins at :obj:`angle1`
and proceeds in the direction of decreasing angles
to end at :obj:`angle2`.
If :obj:`angle2... | 0.001807 |
def get(self, name):
"""
Returns the struct, enum, or interface with the given name, or raises RpcException if
no elements match that name.
:Parameters:
name
Name of struct/enum/interface to return
"""
if self.structs.has_key(name):
retu... | 0.011725 |
def setedge(delta, is_multigraph, graph, orig, dest, idx, exists):
"""Change a delta to say that an edge was created or deleted"""
if is_multigraph(graph):
delta.setdefault(graph, {}).setdefault('edges', {})\
.setdefault(orig, {}).setdefault(dest, {})[idx] = bool(exists)
else:
de... | 0.002353 |
def checkGeneTreeMatchesSpeciesTree(speciesTree, geneTree, processID):
"""
Function to check ids in gene tree all match nodes in species tree
"""
def fn(tree, l):
if tree.internal:
fn(tree.left, l)
fn(tree.right, l)
else:
l.append(processID(tree.iD))
... | 0.00885 |
def apply_matrix_norm(m, v):
"""Equivalent to apply_matrix_pt(M, (p,q)) - apply_matrix_pt(M, (0,0))"""
(a, b, c, d, e, f) = m
(p, q) = v
return (a*p+c*q, b*p+d*q) | 0.005618 |
def assembleimage(patches, pmasks, gridids):
r"""
Assemble an image from a number of patches, patch masks and their grid ids.
Parameters
----------
patches : sequence
Sequence of patches.
pmasks : sequence
Sequence of associated patch mask... | 0.006631 |
def _write_core_tables(options, module, core_results):
"""
Notes
-----
Depending on function that was called for analysis, core_results may be a
list of tuples (empirical), a dataframe, an array, or a single value.
For the list of tuples from empirical, the second element of each tuple is
t... | 0.001663 |
def iter_headers(self):
''' Yield (header, value) tuples, skipping headers that are not
allowed with the current response status code. '''
headers = self._headers.items()
bad_headers = self.bad_headers.get(self._status_code)
if bad_headers:
headers = [h for h in h... | 0.003436 |
def collect_samples_straggler_mitigation(agents, train_batch_size):
"""Collects at least train_batch_size samples.
This is the legacy behavior as of 0.6, and launches extra sample tasks to
potentially improve performance but can result in many wasted samples.
"""
num_timesteps_so_far = 0
traje... | 0.000876 |
def run(self, *args, **kwargs):
"""Run the command; args/kwargs are added or replace the ones given to the constructor."""
_args, _kwargs = self._combine_arglist(args, kwargs)
results, p = self._run_command(*_args, **_kwargs)
return results | 0.011029 |
def set_to_current(self, ):
"""Set the selection to the currently open one
:returns: None
:rtype: None
:raises: None
"""
cur = self.get_current_file()
if cur is not None:
self.set_selection(cur)
else:
self.init_selection() | 0.006431 |
def addFailure(self, test: unittest.case.TestCase, exc_info: tuple) -> None:
"""
Transforms the test in a serializable version of it and sends it to a queue for further analysis
:param test: the test to save
:param exc_info: tuple of the form (Exception class, Exception instance, traceb... | 0.009259 |
def load_shutit_modules(self):
"""Responsible for loading the shutit modules based on the configured module
paths.
"""
shutit_global.shutit_global_object.yield_to_draw()
if self.loglevel <= logging.DEBUG:
self.log('ShutIt module paths now: ',level=logging.DEBUG)
self.log(self.host['shutit_module_path'],... | 0.029018 |
def update_item(self, payload, last_modified=None):
"""
Update an existing item
Accepts one argument, a dict containing Item data
"""
to_send = self.check_items([payload])[0]
if last_modified is None:
modified = payload["version"]
else:
mod... | 0.002181 |
def wrap(lower, upper, x):
"""
Circularly alias the numeric value x into the range [lower,upper).
Valid for cyclic quantities like orientations or hues.
"""
#I have no idea how I came up with this algorithm; it should be simplified.
#
# Note that Python's % operator works on floats and arra... | 0.007286 |
def create_history_filename(self):
"""Create history_filename with INITHISTORY if it doesn't exist."""
if self.history_filename and not osp.isfile(self.history_filename):
try:
encoding.writelines(self.INITHISTORY, self.history_filename)
except EnvironmentErro... | 0.005814 |
def console_width(kwargs):
""""Determine console_width."""
if sys.platform.startswith('win'):
console_width = _find_windows_console_width()
else:
console_width = _find_unix_console_width()
_width = kwargs.get('width', None)
if _width:
console_width = _width
else:
... | 0.0025 |
def update_hyperparameters(self, new_params, hyper_deriv_handling='default', exit_on_bounds=True, inf_on_error=True):
r"""Update the kernel's hyperparameters to the new parameters.
This will call :py:meth:`compute_K_L_alpha_ll` to update the state
accordingly.
Note that... | 0.003996 |
def _initialize(self, *args, **kwargs):
"""Initiaize the mapping matcher with constructor arguments."""
self.items = None
self.keys = None
self.values = None
if args:
if len(args) != 2:
raise TypeError("expected exactly two positional arguments, "
... | 0.000981 |
def intersect(left, *rights, **kwargs):
"""
Calc intersection among datasets,
:param left: collection
:param rights: collection or list of collections
:param distinct: whether to preserve duolicate entries
:return: collection
:Examples:
>>> import pandas as pd
>>> df1 = DataFrame(p... | 0.001535 |
def xdr(self):
"""Create an base64 encoded XDR string for this :class:`Asset`.
:return str: A base64 encoded XDR object representing this
:class:`Asset`.
"""
asset = Xdr.StellarXDRPacker()
asset.pack_Asset(self.to_xdr_object())
return base64.b64encode(asset.... | 0.006006 |
def key_assoc_val(d, func, exclude=None):
"""return the key associated with the value returned by func
"""
vs = list(d.values())
ks = list(d.keys())
key = ks[vs.index(func(vs))]
return key | 0.004717 |
def create(name, profile="splunk", **kwargs):
'''
Create a splunk search
CLI Example:
splunk_search.create 'my search name' search='error msg'
'''
client = _get_splunk(profile)
search = client.saved_searches.create(name, **kwargs)
# use the REST API to set owner and permissions
... | 0.001052 |
def updatepLvlNextFunc(self):
'''
A method that creates the pLvlNextFunc attribute as a sequence of
AR1-style functions. Draws on the attributes PermGroFac and PrstIncCorr.
If cycles=0, the product of PermGroFac across all periods must be 1.0,
otherwise this method is invalid.
... | 0.007709 |
def _process_interaction(self, source_id, interaction, text, pmid,
extra_annotations):
"""Process an interaction JSON tuple from the ISI output, and adds up
to one statement to the list of extracted statements.
Parameters
----------
source_id : str
... | 0.000763 |
def PrintExtractionSummary(self, processing_status):
"""Prints a summary of the extraction.
Args:
processing_status (ProcessingStatus): processing status.
"""
if not processing_status:
self._output_writer.Write(
'WARNING: missing processing status information.\n')
elif not pr... | 0.006429 |
def get_neighbors_in_shell(self, origin, r, dr):
"""
Returns all sites in a shell centered on origin (coords) between radii
r-dr and r+dr.
Args:
origin (3x1 array): Cartesian coordinates of center of sphere.
r (float): Inner radius of shell.
dr (float... | 0.003165 |
def load_keras(json_path=None, hdf5_path=None, by_name=False):
"""
Load a pre-trained Keras model.
:param json_path: The json path containing the keras model definition.
:param hdf5_path: The HDF5 path containing the pre-trained keras model weights with or without the model architecture... | 0.003028 |
def get_template_file(self):
""" Retrieves Jinja2 template file path.
"""
if os.path.exists(os.path.join(self.theme_dir, 'base.html')):
return os.path.join(self.theme_dir, 'base.html')
default_dir = os.path.join(THEMES_DIR, 'default')
if not os.path.exists(os.path.joi... | 0.004237 |
def nova(*arg):
"""
Nova annotation for adding function to process nova notification.
if event_type include wildcard, will put {pattern: function} into process_wildcard dict
else will put {event_type: function} into process dict
:param arg: event_type of notification
"""
check_event_type(O... | 0.003448 |
def _duplicateLayer(self, layerName, newLayerName):
"""
This is the environment implementation of :meth:`BaseFont.duplicateLayer`.
**layerName** will be a :ref:`type-string` representing a valid layer name.
The value will have been normalized with :func:`normalizers.normalizeLayerName`
... | 0.0076 |
def from_json_keyfile_dict(cls, keyfile_dict, scopes='',
token_uri=None, revoke_uri=None):
"""Factory constructor from parsed JSON keyfile.
Args:
keyfile_dict: dict-like object, The parsed dictionary-like object
containing the content... | 0.002195 |
def statement(self, days=60):
"""Download the :py:class:`ofxparse.Statement` given the time range
:param days: Number of days to look back at
:type days: integer
:rtype: :py:class:`ofxparser.Statement`
"""
parsed = self.download_parsed(days=days)
return parsed.ac... | 0.00597 |
def download_resource(self, download_url, target, guard):
""" Helper to download and install external resources.
"""
download_url = download_url.strip()
if not os.path.isabs(target):
target = os.path.join(config.config_dir, target)
if os.path.exists(os.path.join(targ... | 0.003824 |
def do_echo(self, params):
"""
\x1b[1mNAME\x1b[0m
echo - displays formatted data
\x1b[1mSYNOPSIS\x1b[0m
echo <fmtstr> [cmd1] [cmd2] ... [cmdN]
\x1b[1mEXAMPLES\x1b[0m
> echo hello
hello
> echo 'The value of /foo is %s' 'get /foo'
bar
"""
values = ... | 0.002674 |
def teardown_app_request(self, func: Callable) -> Callable:
"""Add a teardown request function to the app.
This is designed to be used as a decorator, and has the same
arguments as :meth:`~quart.Quart.teardown_request`. It applies
to all requests to the app this blueprint is registered ... | 0.00321 |
def load_tab_data(self):
"""Preload all data that for the tabs that will be displayed."""
for tab in self._tabs.values():
if tab.load and not tab.data_loaded:
try:
tab._data = tab.get_context_data(self.request)
except Exception:
... | 0.005025 |
def _get_geometry(self):
""" Creates a multipolygon of bounding box polygons
"""
return shapely.geometry.MultiPolygon([bbox.geometry for bbox in self.bbox_list]) | 0.016216 |
def get_autype_list(self, code_list):
"""
获取给定股票列表的复权因子
:param code_list: 股票列表,例如['HK.00700']
:return: (ret, data)
ret == RET_OK 返回pd dataframe数据,data.DataFrame数据, 数据列格式如下
ret != RET_OK 返回错误字符串
===================== =========== ====... | 0.00248 |
def CorrectWrongEmails(self, askInput=True):
'''Corrects Emails in wrong_emails'''
for email in self.wrong_emails:
corrected_email = self.CorrectEmail(email)
self.emails[self.emails.index(email)] = corrected_email
self.wrong_emails = [] | 0.007018 |
def enbase64(byte_str):
"""
Encode bytes/strings to base64.
Args:
- ``byte_str``: The string or bytes to base64 encode.
Returns:
- byte_str encoded as base64.
"""
# Python 3: base64.b64encode() expects type byte
if isinstance(byte_str, str) and not PYTHON2:
byte_s... | 0.002584 |
def parse_args():
'''Parse command line arguments'''
parser = argparse.ArgumentParser(
description='Morphology feature plotter',
epilog='Note: Makes plots of various features and superimposes\
input distributions. Plots are saved to PDF file.',
formatter_class=argparse.ArgumentDe... | 0.001328 |
def _get_sample(self, mode, encoding):
"""
Get a sample from the next current input file.
:param str mode: The mode for opening the file.
:param str|None encoding: The encoding of the file. None for open the file in binary mode.
"""
self._open_file(mode, encoding)
... | 0.007299 |
def find_nearest_color_hexstr(hexdigits, color_table=None, method='euclid'):
''' Given a three or six-character hex digit string, return the nearest
color index.
Arguments:
hexdigits: a three/6 digit hex string, e.g. 'b0b', '123456'
Returns:
int, None: index, or No... | 0.001099 |
def get_requires(self, ignored=tuple()):
""" a map of requirements to what requires it. ignored is an
optional list of globbed patterns indicating packages,
classes, etc that shouldn't be included in the provides map"""
if self._requires is None:
self._collect_requires_provi... | 0.004065 |
def _objective_function(self, data_align, data_sup, labels, w, s, theta,
bias):
"""Compute the objective function of the Semi-Supervised SRM
See :eq:`sssrm-eq`.
Parameters
----------
data_align : list of 2D arrays, element i has shape=[voxels_i, n_a... | 0.001591 |
def neurite_volume_density(neurites, neurite_type=NeuriteType.all):
'''Get the volume density per neurite
The volume density is defined as the ratio of the neurite volume and
the volume of the neurite's enclosing convex hull
'''
def vol_density(neurite):
'''volume density of a single neurit... | 0.002024 |
def field_definition_post_save(sender, instance, created, raw, **kwargs):
"""
This signal is connected by all FieldDefinition subclasses
see comment in FieldDefinitionBase for more details
"""
model_class = instance.model_def.model_class().render_state()
field = instance.construct_for_migrate()
... | 0.000882 |
def create(self, name, **kwargs):
'''
Create a dataset, including the field types. Optionally, specify args such as:
description : description of the dataset
columns : list of columns (see docs/tests for list structure)
category : must exist in /admin/metadata
... | 0.00282 |
def patch_stdout_context(self, raw=False, patch_stdout=True, patch_stderr=True):
"""
Return a context manager that will replace ``sys.stdout`` with a proxy
that makes sure that all printed text will appear above the prompt, and
that it doesn't destroy the output from the renderer.
... | 0.005263 |
def create_schema_from_xsd_directory(directory, version):
"""Create and fill the schema from a directory which contains xsd
files. It calls fill_schema_from_xsd_file for each xsd file
found.
"""
schema = Schema(version)
for f in _get_xsd_from_directory(directory):
logger.info("Loading s... | 0.002519 |
def export(self):
"""Export all attributes of the user to a dict.
:return: attributes of the user.
:rtype: dict.
"""
data = {}
data["name"] = self.name
data["contributions"] = self.contributions
data["avatar"] = self.avatar
data["followers"] = sel... | 0.00316 |
def local_bifurcation_angle(bif_point):
'''Return the opening angle between two out-going sections
in a bifurcation point
We first ensure that the input point has only two children.
The bifurcation angle is defined as the angle between the first non-zero
length segments of a bifurcation point.
... | 0.002172 |
def corelinkformat(resource):
"""
Return a formatted string representation of the corelinkformat in the tree.
:return: the string
"""
msg = "<" + resource.path + ">;"
assert(isinstance(resource, Resource))
keys = sorted(list(resource.attributes.keys()))
f... | 0.004219 |
def post(self, request, id=None, **kwargs):
"""
Handles post requests.
"""
if id:
# No posting to an object detail page
return HttpResponseForbidden()
else:
if not self.has_add_permission(request):
return HttpResponseForbidden(_... | 0.006803 |
def validate_ok_for_update(update):
"""Validate an update document."""
validate_is_mapping("update", update)
# Update can not be {}
if not update:
raise ValueError('update only works with $ operators')
first = next(iter(update))
if not first.startswith('$'):
raise ValueError('upd... | 0.002833 |
def trainHMM_fromFile(wav_file, gt_file, hmm_model_name, mt_win, mt_step):
'''
This function trains a HMM model for segmentation-classification using a single annotated audio file
ARGUMENTS:
- wav_file: the path of the audio filename
- gt_file: the path of the ground truth filename
... | 0.003388 |
def get_filter_pillar(filter_name,
pillar_key='acl',
pillarenv=None,
saltenv=None):
'''
Helper that can be used inside a state SLS,
in order to get the filter configuration given its name.
filter_name
The name of the filter.
... | 0.004283 |
def get_sec_project_activity(self):
"""
Generate the "project activity" section of the report.
"""
logger.debug("Calculating Project Activity metrics.")
data_path = os.path.join(self.data_dir, "activity")
if not os.path.exists(data_path):
os.makedirs(data_pa... | 0.002193 |
def convert_into(input_path, output_path, output_format='csv', java_options=None, **kwargs):
'''Convert tables from PDF into a file.
Args:
input_path (file like obj):
File like object of tareget PDF file.
output_path (str):
File path of output file.
output_format... | 0.002217 |
def _check_constant_params(
a, has_const=False, use_const=True, rtol=1e-05, atol=1e-08
):
"""Helper func to interaction between has_const and use_const params.
has_const use_const outcome
--------- --------- -------
True True Confirm that a has constant; return a
F... | 0.000506 |
def export(self, directory):
"""Exports the stream to the given directory. The directory can't exist.
You can later import this device by running import_stream on a device.
"""
if os.path.exists(directory):
raise FileExistsError(
"The stream export directory ... | 0.005236 |
def _get_backend_base():
"""Gets the base class for the custom database back-end.
This should be the Django PostgreSQL back-end. However,
some people are already using a custom back-end from
another package. We are nice people and expose an option
that allows them to configure the back-end we base ... | 0.000735 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.