text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def agp(args):
"""
%prog agp Siirt_Female_pistachio_23May2017_table.txt
The table file, as prepared by Dovetail Genomics, is not immediately useful
to convert gene model coordinates, as assumed by formats.chain.fromagp().
This is a quick script to do such conversion. The file structure of this
... | 0.001702 |
def catch(ignore=[],
was_doing="something important",
helpfull_tips="you should use a debugger",
gbc=None):
"""
Catch, prepare and log error
:param exc_cls: error class
:param exc: exception
:param tb: exception traceback
"""
exc_cls, exc, tb=sys.exc_info()
... | 0.005995 |
def _get_var_from_string(item):
""" Get resource variable. """
modname, varname = _split_mod_var_names(item)
if modname:
mod = __import__(modname, globals(), locals(), [varname], -1)
return getattr(mod, varname)
else:
return globals()[varname] | 0.003534 |
def isnat(obj):
"""
Check if a value is np.NaT.
"""
if obj.dtype.kind not in ('m', 'M'):
raise ValueError("%s is not a numpy datetime or timedelta")
return obj.view(int64_dtype) == iNaT | 0.004695 |
def compare_values(values0, values1):
"""Compares all the values of a single registry key."""
values0 = {v[0]: v[1:] for v in values0}
values1 = {v[0]: v[1:] for v in values1}
created = [(k, v[0], v[1]) for k, v in values1.items() if k not in values0]
deleted = [(k, v[0], v[1]) for k, v in values0.... | 0.002028 |
def _GetProxies(self):
"""Gather a list of proxies to use."""
# Detect proxies from the OS environment.
result = client_utils.FindProxies()
# Also try to connect directly if all proxies fail.
result.append("")
# Also try all proxies configured in the config system.
result.extend(config.CON... | 0.002725 |
def list_components(self, dependency_order=True):
"""
Lists the Components by dependency resolving.
Usage::
>>> manager = Manager(("./manager/tests/tests_manager/resources/components/core",))
>>> manager.register_components()
True
>>> manager.lis... | 0.006515 |
def ncp_hals(X, rank, random_state=None, init='rand', **options):
"""
Fits nonnegtaive CP Decomposition using the Hierarcial Alternating Least
Squares (HALS) Method.
Parameters
----------
X : (I_1, ..., I_N) array_like
A real array with nonnegative entries and ``X.ndim >= 3``.
rank... | 0.00171 |
def _make_options(x):
"""Standardize the options tuple format.
The returned tuple should be in the format (('label', value), ('label', value), ...).
The input can be
* an iterable of (label, value) pairs
* an iterable of values, and labels will be generated
"""
# Check if x is a mapping of... | 0.003141 |
def get(self, name, default=None):
"""
Returns an extension instance with a given name.
In case there are few extensions with a given name, the first one
will be returned. If no extensions with a given name are exist,
the `default` value will be returned.
:param name: (... | 0.003503 |
def compute_bearing(start_lat, start_lon, end_lat, end_lon):
'''
Get the compass bearing from start to end.
Formula from
http://www.movable-type.co.uk/scripts/latlong.html
'''
# make sure everything is in radians
start_lat = math.radians(start_lat)
start_lon = math.radians(start_lon)
... | 0.001053 |
def write_elec_file(filename, mesh):
"""
Read in the electrode positions and return the indices of the electrodes
# TODO: Check if you find all electrodes
"""
elecs = []
# print('Write electrodes')
electrodes = np.loadtxt(filename)
for i in electrodes:
# find
for nr, j i... | 0.001672 |
def _selectView( self ):
"""
Matches the view selection to the trees selection.
"""
scene = self.uiGanttVIEW.scene()
scene.blockSignals(True)
scene.clearSelection()
for item in self.uiGanttTREE.selectedItems():
item.viewItem().setSelected(True)... | 0.011321 |
def validateOneElement(self, doc, elem):
"""Try to validate a single element and it's attributes,
basically it does the following checks as described by the
XML-1.0 recommendation: - [ VC: Element Valid ] - [ VC:
Required Attribute ] Then call xmlValidateOneAttribute()
fo... | 0.009434 |
async def on_raw_433(self, message):
""" Nickname in use. """
if not self.registered:
self._registration_attempts += 1
# Attempt to set new nickname.
if self._attempt_nicknames:
await self.set_nickname(self._attempt_nicknames.pop(0))
else:
... | 0.006508 |
def traverse_many(self, attribute, source_sequence, target_sequence,
visitor):
"""
Traverses the given source and target sequences and makes appropriate
calls to :method:`traverse_one`.
Algorithm:
1) Build a map target item ID -> target data item from the t... | 0.002438 |
def stationary_distribution_from_eigenvector(T, ncv=None):
r"""Compute stationary distribution of stochastic matrix T.
The stationary distribution is the left eigenvector corresponding to the 1
non-degenerate eigenvalue :math: `\lambda=1`.
Input:
------
T : numpy array, shape(d,d)
Tran... | 0.002646 |
def from_py_func(cls, func):
""" Create a ``CustomJS`` instance from a Python function. The
function is translated to JavaScript using PScript.
"""
from bokeh.util.deprecation import deprecated
deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 releas... | 0.005452 |
def _check_hetcaller(item):
"""Ensure upstream SV callers requires to heterogeneity analysis are available.
"""
svs = _get_as_list(item, "svcaller")
hets = _get_as_list(item, "hetcaller")
if hets or any([x in svs for x in ["titancna", "purecn"]]):
if not any([x in svs for x in ["cnvkit", "ga... | 0.007707 |
def ionic_strength(mis, zis):
r'''Calculate the ionic strength of a solution in one of two ways,
depending on the inputs only. For Pitzer and Bromley models,
`mis` should be molalities of each component. For eNRTL models,
`mis` should be mole fractions of each electrolyte in the solution.
This will ... | 0.000765 |
def decode_network_values(ptype, plen, buf):
"""Decodes a list of DS values in collectd network format
"""
nvalues = short.unpack_from(buf, header.size)[0]
off = header.size + short.size + nvalues
valskip = double.size
# Check whether our expected packet size is the reported one
assert ((va... | 0.000878 |
def _output_results(
self):
"""
*output results*
**Key Arguments:**
# -
**Return:**
- None
.. todo::
- @review: when complete, clean _output_results method
- @review: when complete add logging
"""
sel... | 0.001547 |
def _cacheAllJobs(self):
"""
Downloads all jobs in the current job store into self.jobCache.
"""
logger.debug('Caching all jobs in job store')
self._jobCache = {jobGraph.jobStoreID: jobGraph for jobGraph in self._jobStore.jobs()}
logger.debug('{} jobs downloaded.'.format(... | 0.008798 |
def correlations(self):
"""
Calculate the correlation coefficients.
"""
corr_df = self._sensors_num_df.corr()
corr_names = []
corrs = []
for i in range(len(corr_df.index)):
for j in range(len(corr_df.index)):
c_name = corr_df.index[i]
... | 0.003322 |
def update_record(self, domain, record, record_type=None, name=None):
"""Call to GoDaddy API to update a single DNS record
:param name: only required if the record is None (deletion)
:param record_type: only required if the record is None (deletion)
:param domain: the domain where the D... | 0.00478 |
def urinorm(uri):
'''
Normalize a URI
'''
# TODO: use urllib.parse instead of these complex regular expressions
if isinstance(uri, bytes):
uri = str(uri, encoding='utf-8')
uri = uri.encode('ascii', errors='oid_percent_escape').decode('utf-8')
# _escapeme_re.sub(_pct_escape_unicode, ... | 0.000993 |
def get_stats(self, obj, stat_name):
""" Send CLI command that returns list of integer counters.
:param obj: requested object.
:param stat_name: statistics command name.
:return: list of counters.
:rtype: list(int)
"""
return [int(v) for v in self.send_command_re... | 0.008475 |
def connect_s3_bucket_to_lambda(self, bucket, function_arn, events,
prefix=None, suffix=None):
# type: (str, str, List[str], OptStr, OptStr) -> None
"""Configure S3 bucket to invoke a lambda function.
The S3 bucket must already have permission to invoke the
... | 0.001949 |
def process_rule(self,rule,pa,tuple):
''' Process a string that denotes a boolean rule.
'''
for i,v in enumerate(tuple):
rule = rule.replace(pa[i],str(v))
return eval(rule) | 0.032407 |
def list_upgrades(refresh=True, **kwargs): # pylint: disable=W0613
'''
Lists all packages available for update.
When run in global zone, it reports only upgradable packages for the global
zone.
When run in non-global zone, it can report more upgradable packages than
``pkg update -vn``, becaus... | 0.003161 |
def keysym_to_keycodes(self, keysym):
"""Look up all the keycodes that is bound to keysym. A list of
tuples (keycode, index) is returned, sorted primarily on the
lowest index and secondarily on the lowest keycode."""
try:
# Copy the map list, reversing the arguments
... | 0.00464 |
def sum_all(iterable, start):
"""Sum up an iterable starting with a start value.
In contrast to :func:`sum`, this also works on other types like
:class:`lists <list>` and :class:`sets <set>`.
"""
if hasattr(start, "__add__"):
for value in iterable:
start += value
else:
... | 0.002571 |
def sortedby(item_list, key_list, reverse=False):
""" sorts ``item_list`` using key_list
Args:
list_ (list): list to sort
key_list (list): list to sort by
reverse (bool): sort order is descending (largest first)
if reverse is True else acscending (smallest first)... | 0.000992 |
def delete_record(cls, record):
"""Delete a record and it's persistent identifiers."""
record.delete()
PersistentIdentifier.query.filter_by(
object_type='rec', object_uuid=record.id,
).update({PersistentIdentifier.status: PIDStatus.DELETED})
cls.delete_buckets(record)... | 0.005747 |
def maybe_connect(self, node_id, wakeup=True):
"""Queues a node for asynchronous connection during the next .poll()"""
if self._can_connect(node_id):
self._connecting.add(node_id)
# Wakeup signal is useful in case another thread is
# blocked waiting for incoming netwo... | 0.004141 |
def load_dataset(relative_path):
"""Imports a data file within the 'h2o_data' folder."""
assert_is_type(relative_path, str)
h2o_dir = os.path.split(__file__)[0]
for possible_file in [os.path.join(h2o_dir, relative_path),
os.path.join(h2o_dir, "h2o_data", relative_path),
... | 0.003344 |
def regret(self):
'''
Calculate expected regret, where expected regret is
maximum optimal reward - sum of collected rewards, i.e.
expected regret = T*max_k(mean_k) - sum_(t=1-->T) (reward_t)
Returns
-------
float
'''
return (sum(self.pulls)*np.m... | 0.004866 |
def generate_parser():
"""Returns a parser configured with sub-commands and arguments."""
parser = argparse.ArgumentParser(
description=constants.TACL_DESCRIPTION,
formatter_class=ParagraphFormatter)
subparsers = parser.add_subparsers(title='subcommands')
generate_align_subparser(subpars... | 0.000995 |
def encodeThetas(self, theta1, theta2):
"""Return the SDR for theta1 and theta2"""
# print >> sys.stderr, "encoded theta1 value = ", theta1
# print >> sys.stderr, "encoded theta2 value = ", theta2
t1e = self.theta1Encoder.encode(theta1)
t2e = self.theta2Encoder.encode(theta2)
# print >> sys.stde... | 0.004057 |
def get_book_currencies(self) -> List[Commodity]:
""" Returns currencies used in the book """
query = (
self.currencies_query
.order_by(Commodity.mnemonic)
)
return query.all() | 0.012712 |
def mwu(x, y, tail='two-sided'):
"""Mann-Whitney U Test (= Wilcoxon rank-sum test). It is the non-parametric
version of the independent T-test.
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
tail : string
Specify whethe... | 0.000318 |
def _format_info(format_int, format_flag=_snd.SFC_GET_FORMAT_INFO):
"""Return the ID and short description of a given format."""
format_info = _ffi.new("SF_FORMAT_INFO*")
format_info.format = format_int
_snd.sf_command(_ffi.NULL, format_flag, format_info,
_ffi.sizeof("SF_FORMAT_INFO"... | 0.002132 |
def post_comment_ajax(request, using=None):
"""
Post a comment, via an Ajax call.
"""
if not request.is_ajax():
return HttpResponseBadRequest("Expecting Ajax call")
# This is copied from django_comments.
# Basically that view does too much, and doesn't offer a hook to change the renderi... | 0.005622 |
def create_from_filedict(self, filedict):
"""
Creates h5 file from dictionary containing the file structure.
Filedict is a regular dictinary whose keys are hdf5 paths and whose
values are dictinaries containing the metadata and datasets. Metadata
is given as normal key-v... | 0.004409 |
def handle_profile_form(form):
"""Handle profile update form."""
form.process(formdata=request.form)
if form.validate_on_submit():
email_changed = False
with db.session.begin_nested():
# Update profile.
current_userprofile.username = form.username.data
cu... | 0.000769 |
def _get_category_from_pars_var(template_var, context):
'''
get category from template variable or from tree_path
'''
cat = template_var.resolve(context)
if isinstance(cat, basestring):
cat = Category.objects.get_by_tree_path(cat)
return cat | 0.003663 |
def detach(self, dwProcessId, bIgnoreExceptions = False):
"""
Detaches from a process currently being debugged.
@note: On Windows 2000 and below the process is killed.
@see: L{attach}, L{detach_from_all}
@type dwProcessId: int
@param dwProcessId: Global ID of a proces... | 0.002306 |
def from_file(cls, fn, *args, **kwargs):
"""Constructor to build an AmiraHeader object from a file
:param str fn: Amira file
:return ah: object of class ``AmiraHeader`` containing header metadata
:rtype: ah: :py:class:`ahds.header.AmiraHeader`
"""
return AmiraHea... | 0.00831 |
def attach(self, events):
"""
Attach this screen to a events that processes commands and dispatches
events. Sets up the appropriate event handlers so that the screen will
update itself automatically as the events processes data.
"""
if events is not None:
ev... | 0.002564 |
def _read_eps_ctr(tomodir):
"""Parse a CRTomo eps.ctr file.
TODO: change parameters to only provide eps.ctr file
Parameters
----------
tomodir: string
Path to directory path
Returns
-------
"""
epsctr_file = tomodir + os.sep + 'inv... | 0.001619 |
def tx_serialization_order(provider: Provider, blockhash: str, txid: str) -> int:
'''find index of this tx in the blockid'''
return provider.getblock(blockhash)["tx"].index(txid) | 0.010695 |
def permissions(self):
"""Dynamically generate dictionary of privacy options
"""
# TODO: optimize this, it's kind of a bad solution for listing a mostly
# static set of files.
# We could either add a permissions dict as an attribute or cache this
# in some way. Creating a... | 0.004577 |
def _from_docstring_rst(doc):
"""
format from docstring to ReStructured Text
"""
def format_fn(line, status):
""" format function """
if re_from_data.match(line):
line = re_from_data.sub(r"**\1** ", line)
status["add_line"] = True
line = re_from_defaults... | 0.000829 |
def has_protocol(self, name):
"""Tells if a certain protocol is available"""
return self.query(Protocol).filter(Protocol.name==name).count() != 0 | 0.012987 |
def _AtNonLeaf(self, attr_value, path):
"""Makes dictionaries expandable when dealing with plists."""
if isinstance(attr_value, dict):
for value in self.Expand(attr_value, path[1:]):
yield value
else:
for v in objectfilter.ValueExpander._AtNonLeaf(self, attr_value, path):
yield v | 0.009375 |
def scheduled_time(self):
"""Time this band was scheduled to be recorded."""
timeline = "{:04d}".format(self.basic_info['observation_timeline'][0])
return self.start_time.replace(hour=int(timeline[:2]), minute=int(timeline[2:4]), second=0, microsecond=0) | 0.010791 |
def fromimportupdate(cls, bundle, import_reg):
# type: (Bundle, ImportRegistration) -> RemoteServiceAdminEvent
"""
Creates a RemoteServiceAdminEvent object from the update of an
ImportRegistration
"""
exc = import_reg.get_exception()
if exc:
return Rem... | 0.003021 |
def to_native(self, obj, name, value): # pylint:disable=unused-argument
"""Transform the MongoDB value into a Marrow Mongo value."""
if self.mapping:
for original, new in self.mapping.items():
value = value.replace(original, new)
return load(value, self.namespace) | 0.038732 |
def listfolderpath(p):
"""
generator of list folder in the path.
folders only
"""
for entry in scandir.scandir(p):
if entry.is_dir():
yield entry.path | 0.005263 |
def open(self):
"""Open Connection.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
"""
LOGGER.debug('Connection Opening')
self.set_state(self.OPENING)
self._exceptions = []
self._channels = {}
... | 0.003591 |
def request_access_token(self, code, redirect_uri=None):
'''
Return access token as a JsonDict: {"access_token":"your-access-token","expires":12345678,"uid":1234}, expires is represented using standard unix-epoch-time
'''
redirect = redirect_uri or self._redirect_uri
resp_text = ... | 0.006383 |
def to_string(self):
"""
Return the current NDEF as a string (always 64 bytes).
"""
data = self.ndef_str
if self.ndef_type == _NDEF_URI_TYPE:
data = self._encode_ndef_uri_type(data)
elif self.ndef_type == _NDEF_TEXT_TYPE:
data = self._encode_ndef_t... | 0.003257 |
def setquit():
"""Define new built-ins 'quit' and 'exit'.
These are simply strings that display a hint on how to exit.
"""
if os.sep == ':':
eof = 'Cmd-Q'
elif os.sep == '\\':
eof = 'Ctrl-Z plus Return'
else:
eof = 'Ctrl-D (i.e. EOF)'
class Quitter(object):
... | 0.004896 |
def check_has_version(self, api):
'''An API class must have a `version` attribute.'''
if not hasattr(api, 'version'):
msg = 'The Api class "{}" lacks a `version` attribute.'
return [msg.format(api.__name__)] | 0.008097 |
def lookup(self, vtype, vname, target_id=None):
"""Return value of vname from the variable store vtype.
Valid vtypes are `strings` 'counters', and `pending`. If the value
is not found in the current steps store, earlier steps will be
checked. If not found, '', 0, or (None, None) is retu... | 0.001366 |
def create_from_yamlfile(cls, yamlfile):
"""Create a Castro data object from a yaml file contains
the likelihood data."""
data = load_yaml(yamlfile)
nebins = len(data)
emin = np.array([data[i]['emin'] for i in range(nebins)])
emax = np.array([data[i]['emax'] for i in rang... | 0.004053 |
def set_measurements(test):
"""Test phase that sets a measurement."""
test.measurements.level_none = 0
time.sleep(1)
test.measurements.level_some = 8
time.sleep(1)
test.measurements.level_all = 9
time.sleep(1)
level_all = test.get_measurement('level_all')
assert level_all.value == 9 | 0.033223 |
def interpolate_delta_t(delta_t_table, tt):
"""Return interpolated Delta T values for the times in `tt`.
The 2xN table should provide TT values as element 0 and
corresponding Delta T values for element 1. For times outside the
range of the table, a long-term formula is used instead.
"""
tt_ar... | 0.001267 |
def debug(self, *debugReqs):
"""send a debug command to control the game state's setup"""
return self._client.send(debug=sc2api_pb2.RequestDebug(debug=debugReqs)) | 0.016854 |
def checkgrad(f, fprime, x, *args,**kw_args):
"""
Analytical gradient calculation using a 3-point method
"""
LG.debug("Checking gradient ...")
import numpy as np
# using machine precision to choose h
eps = np.finfo(float).eps
step = np.sqrt(eps)*(x.min())
# shake things up a bit b... | 0.004533 |
def stft(func=None, **kwparams):
"""
Short Time Fourier Transform block processor / phase vocoder wrapper.
This function can be used in many ways:
* Directly as a signal processor builder, wrapping a spectrum block/grain
processor function;
* Directly as a decorator to a block processor;
* Called with... | 0.00396 |
def source_properties(data, segment_img, error=None, mask=None,
background=None, filter_kernel=None, wcs=None,
labels=None):
"""
Calculate photometry and morphological properties of sources defined
by a labeled segmentation image.
Parameters
----------
... | 0.000245 |
def get_page_content(id):
"""Return XHTML content of a page.
Parameters:
- id: id of a Confluence page.
"""
data = _json.loads(_api.rest("/" + str(id) + "?expand=body.storage"))
return data["body"]["storage"]["value"] | 0.004149 |
def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neocore.IO.BinaryReader):
"""
super(StorageItem, self).Deserialize(reader)
self.Value = reader.ReadVarBytes() | 0.008197 |
def current_model(self, controller_name=None, model_only=False):
'''Return the current model, qualified by its controller name.
If controller_name is specified, the current model for
that controller will be returned.
If model_only is true, only the model name, not qualified by
i... | 0.002378 |
def set_pickle_converters(encode, decode):
"""
Modify the default Pickle conversion functions. This affects all
:class:`~couchbase.bucket.Bucket` instances.
These functions will be called instead of the default ones
(``pickle.dumps`` and ``pickle.loads``) to encode and decode values to and
from... | 0.000852 |
def rollback_one_iter(self):
"""Rollback one iteration.
Returns
-------
self : Booster
Booster with rolled back one iteration.
"""
_safe_call(_LIB.LGBM_BoosterRollbackOneIter(
self.handle))
self.__is_predicted_cur_iter = [False for _ in ra... | 0.008219 |
def _packb3(obj, **options):
"""
Serialize a Python object into MessagePack bytes.
Args:
obj: a Python object
Kwargs:
ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
to a callable that packs an instance of the type
... | 0.000981 |
def get_multiplicon_leaves(self, redundant=False):
""" Return a generator of the IDs of multiplicons found at leaves
of the tree (i.e. from which no further multiplicons were derived).
Arguments:
o redundant - if true, report redundant multiplicons
"""
for n... | 0.002976 |
def sample_wr(population, k):
"Chooses k random elements (with replacement) from a population"
n = len(population)
_random, _int = random.random, int # speed hack
result = [None] * k
for i in xrange(k):
j = _int(_random() * n)
result[i] = population[j]
return result | 0.006329 |
def check_key(request):
"""
Check to see if we already have an access_key stored,
if we do then we have already gone through
OAuth. If not then we haven't and we probably need to.
"""
try:
access_key = request.session.get('oauth_token', None)
if not access_key:
return... | 0.002604 |
def install_ui_colorscheme(self, name, style_dict):
"""
Install a new UI color scheme.
"""
assert isinstance(name, six.text_type)
assert isinstance(style_dict, dict)
self.ui_styles[name] = style_dict | 0.008065 |
def get_options_for_model(self, model):
"""
Thin wrapper around ``_get_options_for_model`` to preserve the
semantic of throwing exception for models not directly registered.
"""
opts = self._get_options_for_model(model)
if not opts.registered and not opts.related:
... | 0.004274 |
def _add_colorbar(self, m, CS, ax, name):
''' Add colorbar to the map instance '''
cb = m.colorbar(CS, "right", size="5%", pad="2%")
cb.set_label(name, size=34)
cb.ax.tick_params(labelsize=18) | 0.008889 |
def enter(self, container_alias):
'''
a method to open up a terminal inside a running container
:param container_alias: string with name or id of container
:return: None
'''
title = '%s.enter' % self.__class__.__name__
# validate inputs
... | 0.005794 |
def getTextTitle(self):
"""Return a title for texts and listings
"""
request_id = self.getRequestID()
if not request_id:
return ""
analysis = self.getAnalysis()
if not analysis:
return request_id
return "%s - %s" % (request_id, analysis.T... | 0.006116 |
def transform_title(self, content_metadata_item):
"""
Return the title of the content item.
"""
title_with_locales = []
for locale in self.enterprise_configuration.get_locales():
title_with_locales.append({
'locale': locale,
'value': c... | 0.004914 |
def next_datetime(min_year = None, max_year = None):
"""
Generates a random Date and time in the range ['minYear', 'maxYear'].
This method generate dates without time (or time set to 00:00:00)
:param min_year: (optional) minimum range value
:param max_year: max range value
... | 0.011173 |
def sort_card_indices(cards, indices, ranks=None):
"""
Sorts the given Deck indices by the given ranks. Must also supply the
``Stack``, ``Deck``, or ``list`` that the indices are from.
:arg cards:
The cards the indices are from. Can be a ``Stack``, ``Deck``, or
``list``
:arg list in... | 0.003254 |
def _case_stmt(self, stmt: Statement, sctx: SchemaContext) -> None:
"""Handle case statement."""
self._handle_child(CaseNode(), stmt, sctx) | 0.012903 |
def labels(ctx):
"""Crate or update labels in github
"""
config = ctx.obj['agile']
repos = config.get('repositories')
labels = config.get('labels')
if not isinstance(repos, list):
raise CommandError(
'You need to specify the "repos" list in the config'
)
if not is... | 0.001297 |
def _set_collector_vrf(self, v, load=False):
"""
Setter method for collector_vrf, mapped from YANG variable /sflow/collector_vrf (common-def:vrf-name)
If this variable is read-only (config: false) in the
source YANG file, then _set_collector_vrf is considered as a private
method. Backends looking to... | 0.00484 |
def _catch_errors(a_func, to_catch):
"""Updates a_func to wrap exceptions with GaxError
Args:
a_func (callable): A callable.
to_catch (list[Exception]): Configures the exceptions to wrap.
Returns:
Callable: A function that will wrap certain exceptions with GaxError
"""
def ... | 0.001506 |
async def raw(self, command, *args, _conn=None, **kwargs):
"""
Send the raw command to the underlying client. Note that by using this CMD you
will lose compatibility with other backends.
Due to limitations with aiomcache client, args have to be provided as bytes.
For rest of bac... | 0.006734 |
def as_tensor_dict(self,
padding_lengths: Dict[str, Dict[str, int]] = None,
verbose: bool = False) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]:
# This complex return type is actually predefined elsewhere as a DataArray,
# but we can't use it b... | 0.00855 |
def p_pause(p):
""" statement : PAUSE expr
"""
p[0] = make_sentence('PAUSE',
make_typecast(TYPE.uinteger, p[2], p.lineno(1))) | 0.006173 |
def json_processor(entity):
'''
Unserialize raw POST data in JSON format to a Python data structure.
:param entity: raw POST data
'''
if six.PY2:
body = entity.fp.read()
else:
# https://github.com/cherrypy/cherrypy/pull/1572
contents = BytesIO()
body = entity.fp.... | 0.002963 |
def OAuthClient(
domain,
consumer_key,
consumer_secret,
token,
token_secret,
user_agent=None,
request_encoder=default_request_encoder,
response_decoder=default_response_decoder
):
"""Creates a Freshbooks client for a freshbooks domain, using
OAuth. Token management is assumed to ... | 0.002717 |
def fit_from_cfg(cls, choosers, chosen_fname, alternatives, cfgname, outcfgname=None):
"""
Parameters
----------
choosers : DataFrame
A dataframe in which rows represent choosers.
chosen_fname : string
A string indicating the column in the choosers datafra... | 0.002732 |
def standardized_compound(self):
"""Return the :class:`~pubchempy.Compound` that was produced when this Substance was standardized.
Requires an extra request. Result is cached.
"""
for c in self.record['compound']:
if c['id']['type'] == CompoundIdType.STANDARDIZED:
... | 0.008043 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.