text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
async def get_match(self, m_id, force_update=False) -> Match:
""" get a single match by id
|methcoro|
Args:
m_id: match id
force_update (default=False): True to force an update to the Challonge API
Returns:
Match
Raises:
APIExce... | [
"async",
"def",
"get_match",
"(",
"self",
",",
"m_id",
",",
"force_update",
"=",
"False",
")",
"->",
"Match",
":",
"found_m",
"=",
"self",
".",
"_find_match",
"(",
"m_id",
")",
"if",
"force_update",
"or",
"found_m",
"is",
"None",
":",
"await",
"self",
... | 24.190476 | 21.285714 |
def get_policies_by_id(profile_manager, policy_ids):
'''
Returns a list of policies with the specified ids.
profile_manager
Reference to the profile manager.
policy_ids
List of policy ids to retrieve.
'''
try:
return profile_manager.RetrieveContent(policy_ids)
excep... | [
"def",
"get_policies_by_id",
"(",
"profile_manager",
",",
"policy_ids",
")",
":",
"try",
":",
"return",
"profile_manager",
".",
"RetrieveContent",
"(",
"policy_ids",
")",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"except... | 32 | 17.181818 |
def comm_grid(patch, cols, splits, divs, metric='Sorensen'):
"""
Calculates commonality as a function of distance for a gridded patch
Parameters
----------
{0}
divs : str
Description of how to divide x_col and y_col. Unlike SAR and EAR, only
one division can be given at a time. ... | [
"def",
"comm_grid",
"(",
"patch",
",",
"cols",
",",
"splits",
",",
"divs",
",",
"metric",
"=",
"'Sorensen'",
")",
":",
"(",
"spp_col",
",",
"count_col",
",",
"x_col",
",",
"y_col",
")",
",",
"patch",
"=",
"_get_cols",
"(",
"[",
"'spp_col'",
",",
"'co... | 34.986842 | 24.644737 |
def _setSmsMemory(self, readDelete=None, write=None):
""" Set the current SMS memory to use for read/delete/write operations """
# Switch to the correct memory type if required
if write != None and write != self._smsMemWrite:
self.write()
readDel = readDelete or self._sms... | [
"def",
"_setSmsMemory",
"(",
"self",
",",
"readDelete",
"=",
"None",
",",
"write",
"=",
"None",
")",
":",
"# Switch to the correct memory type if required",
"if",
"write",
"!=",
"None",
"and",
"write",
"!=",
"self",
".",
"_smsMemWrite",
":",
"self",
".",
"writ... | 54.583333 | 14.25 |
def mpfr_floordiv(rop, x, y, rnd):
"""
Given two MPFR numbers x and y, compute floor(x / y),
rounded if necessary using the given rounding mode.
The result is placed in 'rop'.
"""
# Algorithm notes
# ---------------
# A simple and obvious approach is to compute floor(x / y) exactly, and
... | [
"def",
"mpfr_floordiv",
"(",
"rop",
",",
"x",
",",
"y",
",",
"rnd",
")",
":",
"# Algorithm notes",
"# ---------------",
"# A simple and obvious approach is to compute floor(x / y) exactly, and",
"# then round to the nearest representable value using the given rounding",
"# mode. Thi... | 38.020408 | 23.408163 |
def select(self, domain_or_name, query='', next_token=None,
consistent_read=False):
"""
Returns a set of Attributes for item names within domain_name that
match the query. The query must be expressed in using the SELECT
style syntax rather than the original SimpleDB query... | [
"def",
"select",
"(",
"self",
",",
"domain_or_name",
",",
"query",
"=",
"''",
",",
"next_token",
"=",
"None",
",",
"consistent_read",
"=",
"False",
")",
":",
"domain",
",",
"domain_name",
"=",
"self",
".",
"get_domain_and_name",
"(",
"domain_or_name",
")",
... | 43.285714 | 20.485714 |
def ad_stat(data):
"""
Calculates the Anderson-Darling statistic for sorted values from U(0, 1).
The statistic is not defined if any of the values is exactly 0 or 1. You
will get infinity as a result and a divide-by-zero warning for such values.
The warning can be silenced or raised using numpy.err... | [
"def",
"ad_stat",
"(",
"data",
")",
":",
"samples",
"=",
"len",
"(",
"data",
")",
"factors",
"=",
"arange",
"(",
"1",
",",
"2",
"*",
"samples",
",",
"2",
")",
"return",
"-",
"samples",
"-",
"(",
"factors",
"*",
"log",
"(",
"data",
"*",
"(",
"1"... | 43.545455 | 24.090909 |
def _is_cow(path):
'''
Check if the subvolume is copy on write
'''
dirname = os.path.dirname(path)
return 'C' not in __salt__['file.lsattr'](dirname)[path] | [
"def",
"_is_cow",
"(",
"path",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"return",
"'C'",
"not",
"in",
"__salt__",
"[",
"'file.lsattr'",
"]",
"(",
"dirname",
")",
"[",
"path",
"]"
] | 28.333333 | 19.333333 |
def stats(request, server_name):
"""
Show server statistics.
"""
server_name = server_name.strip('/')
data = _context_data({
'title': _('Memcache Statistics for %s') % server_name,
'cache_stats': _get_cache_stats(server_name),
},
request)
return render_to_response('me... | [
"def",
"stats",
"(",
"request",
",",
"server_name",
")",
":",
"server_name",
"=",
"server_name",
".",
"strip",
"(",
"'/'",
")",
"data",
"=",
"_context_data",
"(",
"{",
"'title'",
":",
"_",
"(",
"'Memcache Statistics for %s'",
")",
"%",
"server_name",
",",
... | 33.272727 | 16.181818 |
def cleanup_lib(self):
""" unload the previously loaded shared library """
if not self.using_openmp:
#this if statement is necessary because shared libraries that use
#OpenMP will core dump when unloaded, this is a well-known issue with OpenMP
logging.debug('unloading... | [
"def",
"cleanup_lib",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"using_openmp",
":",
"#this if statement is necessary because shared libraries that use",
"#OpenMP will core dump when unloaded, this is a well-known issue with OpenMP",
"logging",
".",
"debug",
"(",
"'unloadi... | 53.857143 | 18.285714 |
def use_partial_data(self, sample_pct:float=0.01, seed:int=None)->'ItemList':
"Use only a sample of `sample_pct`of the full dataset and an optional `seed`."
if seed is not None: np.random.seed(seed)
rand_idx = np.random.permutation(range_of(self))
cut = int(sample_pct * len(self))
... | [
"def",
"use_partial_data",
"(",
"self",
",",
"sample_pct",
":",
"float",
"=",
"0.01",
",",
"seed",
":",
"int",
"=",
"None",
")",
"->",
"'ItemList'",
":",
"if",
"seed",
"is",
"not",
"None",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"r... | 57.333333 | 19 |
def _get_version_info():
"""
Returns the currently-installed awslimitchecker version, and a best-effort
attempt at finding the origin URL and commit/tag if installed from an
editable git clone.
:returns: awslimitchecker version
:rtype: str
"""
if os.environ.get('VERSIONCHECK_DEBUG', '')... | [
"def",
"_get_version_info",
"(",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'VERSIONCHECK_DEBUG'",
",",
"''",
")",
"!=",
"'true'",
":",
"for",
"lname",
"in",
"[",
"'versionfinder'",
",",
"'pip'",
",",
"'git'",
"]",
":",
"l",
"=",
"logging"... | 33.868421 | 16.5 |
def rewrite_with_operator_pm_cc(expr):
"""Try to rewrite expr using :class:`OperatorPlusMinusCC`
Example:
>>> A = OperatorSymbol('A', hs=1)
>>> sum = A + A.dag()
>>> sum2 = rewrite_with_operator_pm_cc(sum)
>>> print(ascii(sum2))
A^(1) + c.c.
"""
# TODO: move thi... | [
"def",
"rewrite_with_operator_pm_cc",
"(",
"expr",
")",
":",
"# TODO: move this to the toolbox",
"from",
"qnet",
".",
"algebra",
".",
"toolbox",
".",
"core",
"import",
"temporary_rules",
"def",
"_combine_operator_p_cc",
"(",
"A",
",",
"B",
")",
":",
"if",
"B",
"... | 30.622642 | 15.792453 |
def iter_variants(self):
"""Iterate over marker information."""
for variant in self._bgen.iter_variant_info():
yield Variant(
variant.name,
CHROM_STR_ENCODE.get(variant.chrom, variant.chrom),
variant.pos, [variant.a1, variant.a2],
) | [
"def",
"iter_variants",
"(",
"self",
")",
":",
"for",
"variant",
"in",
"self",
".",
"_bgen",
".",
"iter_variant_info",
"(",
")",
":",
"yield",
"Variant",
"(",
"variant",
".",
"name",
",",
"CHROM_STR_ENCODE",
".",
"get",
"(",
"variant",
".",
"chrom",
",",... | 39.125 | 15.375 |
def block(self, tofile="block.dat"):
'''
获取证券板块信息
:param tofile:
:return: pd.dataFrame or None
'''
with self.client.connect(*self.bestip):
data = self.client.get_and_parse_block_info(tofile)
return self.client.to_df(data) | [
"def",
"block",
"(",
"self",
",",
"tofile",
"=",
"\"block.dat\"",
")",
":",
"with",
"self",
".",
"client",
".",
"connect",
"(",
"*",
"self",
".",
"bestip",
")",
":",
"data",
"=",
"self",
".",
"client",
".",
"get_and_parse_block_info",
"(",
"tofile",
")... | 28.5 | 17.9 |
def add_child(self, u, v):
''' add child to search tree itself.
Arguments:
u {int} -- father id
v {int} -- child id
'''
if u == -1:
self.root = v
self.adj_list[v] = []
return
if v not in self.adj_list[u]:
s... | [
"def",
"add_child",
"(",
"self",
",",
"u",
",",
"v",
")",
":",
"if",
"u",
"==",
"-",
"1",
":",
"self",
".",
"root",
"=",
"v",
"self",
".",
"adj_list",
"[",
"v",
"]",
"=",
"[",
"]",
"return",
"if",
"v",
"not",
"in",
"self",
".",
"adj_list",
... | 26.666667 | 13.866667 |
def get_methods_names(public_properties):
"""
Generates the names of the fields where to inject the getter and setter
methods
:param public_properties: If True, returns the names of public property
accessors, else of hidden property ones
:return... | [
"def",
"get_methods_names",
"(",
"public_properties",
")",
":",
"if",
"public_properties",
":",
"prefix",
"=",
"ipopo_constants",
".",
"IPOPO_PROPERTY_PREFIX",
"else",
":",
"prefix",
"=",
"ipopo_constants",
".",
"IPOPO_HIDDEN_PROPERTY_PREFIX",
"return",
"(",
"\"{0}{1}\"... | 38.5 | 23.722222 |
def alerts(self, alert_level='High'):
"""Get a filtered list of alerts at the given alert level, and sorted by alert level."""
alerts = self.zap.core.alerts()
alert_level_value = self.alert_levels[alert_level]
alerts = sorted((a for a in alerts if self.alert_levels[a['risk']] >= alert_l... | [
"def",
"alerts",
"(",
"self",
",",
"alert_level",
"=",
"'High'",
")",
":",
"alerts",
"=",
"self",
".",
"zap",
".",
"core",
".",
"alerts",
"(",
")",
"alert_level_value",
"=",
"self",
".",
"alert_levels",
"[",
"alert_level",
"]",
"alerts",
"=",
"sorted",
... | 47.666667 | 24.333333 |
def SearchFetchable(session=None, **kwargs):
"""Search okcupid.com with the given parameters. Parameters are registered
to this function through :meth:`~okcupyd.filter.Filters.register_filter_builder`
of :data:`~okcupyd.html_search.search_filters`.
:returns: A :class:`~okcupyd.util.fetchable.Fetchable`... | [
"def",
"SearchFetchable",
"(",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"session",
"or",
"Session",
".",
"login",
"(",
")",
"return",
"util",
".",
"Fetchable",
".",
"fetch_marshall",
"(",
"SearchHTMLFetcher",
"(",
"session... | 42.535714 | 18.357143 |
def run(*args, **kwargs):
'''Returns True if successful, False if failure'''
kwargs.setdefault('env', os.environ)
kwargs.setdefault('shell', True)
try:
subprocess.check_call(' '.join(args), **kwargs)
return True
except subprocess.CalledProcessError:
logger.debug('Error runn... | [
"def",
"run",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'env'",
",",
"os",
".",
"environ",
")",
"kwargs",
".",
"setdefault",
"(",
"'shell'",
",",
"True",
")",
"try",
":",
"subprocess",
".",
"check_call",
... | 29.333333 | 18 |
def run(self, *args):
"""Show information about countries."""
params = self.parser.parse_args(args)
ct = params.code_or_term
if ct and len(ct) < 2:
self.error('Code country or term must have 2 or more characters length')
return CODE_INVALID_FORMAT_ERROR
... | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
")",
":",
"params",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"args",
")",
"ct",
"=",
"params",
".",
"code_or_term",
"if",
"ct",
"and",
"len",
"(",
"ct",
")",
"<",
"2",
":",
"self",
".",
"e... | 30.954545 | 21.909091 |
def die(self):
"""Time to quit"""
log.info('Time to die')
if self.connected:
try:
self.send('Die')
except Exception:
pass
if self._socket:
self._socket.close()
self.pop() | [
"def",
"die",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Time to die'",
")",
"if",
"self",
".",
"connected",
":",
"try",
":",
"self",
".",
"send",
"(",
"'Die'",
")",
"except",
"Exception",
":",
"pass",
"if",
"self",
".",
"_socket",
":",
"sel... | 24.363636 | 14.363636 |
def sign_in(self, timeout=60, safe=True, tries=1, channel=None):
'''
Send a sign in request to the master, sets the key information and
returns a dict containing the master publish interface to bind to
and the decrypted aes key for transport decryption.
:param int timeout: Numbe... | [
"def",
"sign_in",
"(",
"self",
",",
"timeout",
"=",
"60",
",",
"safe",
"=",
"True",
",",
"tries",
"=",
"1",
",",
"channel",
"=",
"None",
")",
":",
"auth",
"=",
"{",
"}",
"auth_timeout",
"=",
"self",
".",
"opts",
".",
"get",
"(",
"'auth_timeout'",
... | 49.436975 | 25.168067 |
def update(self, sparql_query_only=False, auto_refresh=None, update_binary=True):
'''
Method to update resources in repository. Firing this method computes the difference in the local modified graph and the original one,
creates an instance of SparqlUpdate and builds a sparql query that represents these differe... | [
"def",
"update",
"(",
"self",
",",
"sparql_query_only",
"=",
"False",
",",
"auto_refresh",
"=",
"None",
",",
"update_binary",
"=",
"True",
")",
":",
"# run diff on graphs, send as PATCH request",
"self",
".",
"_diff_graph",
"(",
")",
"sq",
"=",
"SparqlUpdate",
"... | 38.8 | 29.261538 |
def pixel(self, x, y, size=None):
"""Return color for a pixel."""
if (size is None):
size = self.sz
# Have we go to the smallest element?
if (size <= 3):
if (_middle(x, y)):
return (None)
else:
return (0, 0, 0)
d... | [
"def",
"pixel",
"(",
"self",
",",
"x",
",",
"y",
",",
"size",
"=",
"None",
")",
":",
"if",
"(",
"size",
"is",
"None",
")",
":",
"size",
"=",
"self",
".",
"sz",
"# Have we go to the smallest element?",
"if",
"(",
"size",
"<=",
"3",
")",
":",
"if",
... | 32.857143 | 11.928571 |
def create(customer, **data):
"""
Create a card instance.
:param customer: the customer id or object
:type customer: string|Customer
:param data: data required to create the card
:return: The card resource
:rtype resources.Card
"""
if isinstance(... | [
"def",
"create",
"(",
"customer",
",",
"*",
"*",
"data",
")",
":",
"if",
"isinstance",
"(",
"customer",
",",
"resources",
".",
"Customer",
")",
":",
"customer",
"=",
"customer",
".",
"id",
"http_client",
"=",
"HttpClient",
"(",
")",
"response",
",",
"_... | 32.235294 | 15.647059 |
def get_inclusion_states(self, transactions, tips):
# type: (Iterable[TransactionHash], Iterable[TransactionHash]) -> dict
"""
Get the inclusion states of a set of transactions. This is for
determining if a transaction was accepted and confirmed by the
network or not. You can sea... | [
"def",
"get_inclusion_states",
"(",
"self",
",",
"transactions",
",",
"tips",
")",
":",
"# type: (Iterable[TransactionHash], Iterable[TransactionHash]) -> dict",
"return",
"core",
".",
"GetInclusionStatesCommand",
"(",
"self",
".",
"adapter",
")",
"(",
"transactions",
"="... | 35.875 | 22.958333 |
def setup(config):
"""Setup persistence to be used in cinderlib.
By default memory persistance will be used, but there are other mechanisms
available and other ways to use custom mechanisms:
- Persistence plugins: Plugin mechanism uses Python entrypoints under
namespace cinderlib.persistence.sto... | [
"def",
"setup",
"(",
"config",
")",
":",
"if",
"config",
"is",
"None",
":",
"config",
"=",
"{",
"}",
"else",
":",
"config",
"=",
"config",
".",
"copy",
"(",
")",
"# Prevent driver dynamic loading clearing configuration options",
"volume_cmd",
".",
"CONF",
".",... | 38.232558 | 22.744186 |
def run(self, root_allowed=False):
"""Start daemon mode
:param bool root_allowed: Only used for ExecuteCmd
:return: loop
"""
self.root_allowed = root_allowed
scan_devices(self.on_push, lambda d: d.src.lower() in self.devices, self.settings.get('interface')) | [
"def",
"run",
"(",
"self",
",",
"root_allowed",
"=",
"False",
")",
":",
"self",
".",
"root_allowed",
"=",
"root_allowed",
"scan_devices",
"(",
"self",
".",
"on_push",
",",
"lambda",
"d",
":",
"d",
".",
"src",
".",
"lower",
"(",
")",
"in",
"self",
"."... | 37.375 | 18.75 |
def corner_grid(self):
"""Return a grid with only the corner points.
Returns
-------
cgrid : `RectGrid`
Grid with size 2 in non-degenerate dimensions and 1
in degenerate ones
Examples
--------
>>> g = RectGrid([0, 1], [-1, 0, 2])
... | [
"def",
"corner_grid",
"(",
"self",
")",
":",
"minmax_vecs",
"=",
"[",
"]",
"for",
"axis",
"in",
"range",
"(",
"self",
".",
"ndim",
")",
":",
"if",
"self",
".",
"shape",
"[",
"axis",
"]",
"==",
"1",
":",
"minmax_vecs",
".",
"append",
"(",
"self",
... | 30.625 | 18.041667 |
def psffunc(self, x, y, z, **kwargs):
"""Calculates a pinhole psf"""
#do_pinhole?? FIXME
if self.polychromatic:
func = psfcalc.calculate_polychrome_pinhole_psf
else:
func = psfcalc.calculate_pinhole_psf
x0, y0 = [psfcalc.vec_to_halfvec(v) for v in [x,y]]
... | [
"def",
"psffunc",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
",",
"*",
"*",
"kwargs",
")",
":",
"#do_pinhole?? FIXME",
"if",
"self",
".",
"polychromatic",
":",
"func",
"=",
"psfcalc",
".",
"calculate_polychrome_pinhole_psf",
"else",
":",
"func",
"=",
"ps... | 40.7 | 13.5 |
def compare_branches_tags_commits(self, project_id, from_id, to_id):
"""
Compare branches, tags or commits
:param project_id: The ID of a project
:param from_id: the commit sha or branch name
:param to_id: the commit sha or branch name
:return: commit list and diff betwe... | [
"def",
"compare_branches_tags_commits",
"(",
"self",
",",
"project_id",
",",
"from_id",
",",
"to_id",
")",
":",
"data",
"=",
"{",
"'from'",
":",
"from_id",
",",
"'to'",
":",
"to_id",
"}",
"request",
"=",
"requests",
".",
"get",
"(",
"'{0}/{1}/repository/comp... | 38.52381 | 19.190476 |
def local_attr_ancestors(self, name, context=None):
"""Iterate over the parents that define the given name.
:param name: The name to find definitions for.
:type name: str
:returns: The parents that define the given name.
:rtype: iterable(NodeNG)
"""
# Look up in... | [
"def",
"local_attr_ancestors",
"(",
"self",
",",
"name",
",",
"context",
"=",
"None",
")",
":",
"# Look up in the mro if we can. This will result in the",
"# attribute being looked up just as Python does it.",
"try",
":",
"ancestors",
"=",
"self",
".",
"mro",
"(",
"contex... | 36.85 | 15.15 |
def do(self, fn, message=None, *args, **kwargs):
"""Add a 'do' action to the steps. This is a function to execute
:param fn: A function
:param message: Message indicating what this function does (used for debugging if assertions fail)
"""
self.items.put(ChainItem(fn, self.do, me... | [
"def",
"do",
"(",
"self",
",",
"fn",
",",
"message",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"items",
".",
"put",
"(",
"ChainItem",
"(",
"fn",
",",
"self",
".",
"do",
",",
"message",
",",
"*",
"args",
",... | 44.625 | 22.25 |
def hash(self):
'''
:rtype: int
:return: hash of the field
'''
hashed = super(RandomBits, self).hash()
return khash(hashed, self._min_length, self._max_length, self._num_mutations, self._step, self._seed) | [
"def",
"hash",
"(",
"self",
")",
":",
"hashed",
"=",
"super",
"(",
"RandomBits",
",",
"self",
")",
".",
"hash",
"(",
")",
"return",
"khash",
"(",
"hashed",
",",
"self",
".",
"_min_length",
",",
"self",
".",
"_max_length",
",",
"self",
".",
"_num_muta... | 35.142857 | 26.571429 |
def partition_version_classifiers(
classifiers: t.Sequence[str], version_prefix: str = 'Programming Language :: Python :: ',
only_suffix: str = ' :: Only') -> t.Tuple[t.List[str], t.List[str]]:
"""Find version number classifiers in given list and partition them into 2 groups."""
versions_min, ve... | [
"def",
"partition_version_classifiers",
"(",
"classifiers",
":",
"t",
".",
"Sequence",
"[",
"str",
"]",
",",
"version_prefix",
":",
"str",
"=",
"'Programming Language :: Python :: '",
",",
"only_suffix",
":",
"str",
"=",
"' :: Only'",
")",
"->",
"t",
".",
"Tuple... | 47 | 15.5625 |
def get_docker_secret(name, default=None, cast_to=str, autocast_name=True, getenv=True, safe=True,
secrets_dir=os.path.join(root, 'var', 'run', 'secrets')):
"""This function fetches a docker secret
:param name: the name of the docker secret
:param default: the default value if no secr... | [
"def",
"get_docker_secret",
"(",
"name",
",",
"default",
"=",
"None",
",",
"cast_to",
"=",
"str",
",",
"autocast_name",
"=",
"True",
",",
"getenv",
"=",
"True",
",",
"safe",
"=",
"True",
",",
"secrets_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"... | 35.589286 | 21.428571 |
def fetch(url, **kwargs):
"""Fetches an URL and returns the response.
Parameters
----------
url : str
An URL to crawl.
spider_cls : scrapy.Spider (default: DefaultSpider)
A spider class to be used in the crawler instance.
capture_items : bool (default: True)
If enabled, ... | [
"def",
"fetch",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"DEFAULT_TIMEOUT",
")",
"kwargs",
"[",
"'return_crawler'",
"]",
"=",
"True",
"crawler",
"=",
"wait_for",
"(",
"timeout",
",",
"_... | 32.342857 | 19.142857 |
def get_inventory_by_name(nme, character):
"""
returns the inventory index by name
"""
for ndx, sk in enumerate(character["inventory"]):
#print("sk = ", sk, " , nme = ", nme)
if sk["name"] == nme:
return ndx
return 0 | [
"def",
"get_inventory_by_name",
"(",
"nme",
",",
"character",
")",
":",
"for",
"ndx",
",",
"sk",
"in",
"enumerate",
"(",
"character",
"[",
"\"inventory\"",
"]",
")",
":",
"#print(\"sk = \", sk, \" , nme = \", nme)",
"if",
"sk",
"[",
"\"name\"",
"]",
"==",
"nme... | 25.6 | 11.8 |
def check_dataset(dataset):
"""Confirm shape (3 colors x rows x cols) and values [0 to 255] are OK."""
if isinstance(dataset, numpy.ndarray) and not len(dataset.shape) == 4:
check_dataset_shape(dataset)
check_dataset_range(dataset)
else: # must be a list of arrays or a 4D NumPy array
... | [
"def",
"check_dataset",
"(",
"dataset",
")",
":",
"if",
"isinstance",
"(",
"dataset",
",",
"numpy",
".",
"ndarray",
")",
"and",
"not",
"len",
"(",
"dataset",
".",
"shape",
")",
"==",
"4",
":",
"check_dataset_shape",
"(",
"dataset",
")",
"check_dataset_rang... | 42.55 | 12.45 |
def im_open(self, *, user: str, **kwargs) -> SlackResponse:
"""Opens a direct message channel.
Args:
user (str): The user id to open a DM with. e.g. 'W1234567890'
"""
kwargs.update({"user": user})
return self.api_call("im.open", json=kwargs) | [
"def",
"im_open",
"(",
"self",
",",
"*",
",",
"user",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"SlackResponse",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"user\"",
":",
"user",
"}",
")",
"return",
"self",
".",
"api_call",
"(",
"\"im.open\"",
... | 35.875 | 16.75 |
def analyze(self):
"""Populate an enriched index by processing input items in blocks.
:return: total number of out_items written.
"""
from_date = self._out.latest_date()
if from_date:
logger.info("Reading items since " + from_date)
else:
logger.in... | [
"def",
"analyze",
"(",
"self",
")",
":",
"from_date",
"=",
"self",
".",
"_out",
".",
"latest_date",
"(",
")",
"if",
"from_date",
":",
"logger",
".",
"info",
"(",
"\"Reading items since \"",
"+",
"from_date",
")",
"else",
":",
"logger",
".",
"info",
"(",
... | 39.209302 | 23.837209 |
def handle_version_flag():
"""If the --version flag is passed, print version to stdout and exit.
Within dsub commands, --version should be the highest priority flag.
This function supplies a repeatable and DRY way of checking for the
version flag and printing the version. Callers still need to define a version... | [
"def",
"handle_version_flag",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Version parser'",
",",
"add_help",
"=",
"False",
")",
"parser",
".",
"add_argument",
"(",
"'--version'",
",",
"'-v'",
",",
"dest",
"=",
... | 46.066667 | 20.866667 |
def get_axis_variables(ds):
'''
Returns a list of variables that define an axis of the dataset
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
axis_variables = []
for ncvar in ds.get_variables_by_attributes(axis=lambda x: x is not None):
axis_variables.append(ncvar.name)
retu... | [
"def",
"get_axis_variables",
"(",
"ds",
")",
":",
"axis_variables",
"=",
"[",
"]",
"for",
"ncvar",
"in",
"ds",
".",
"get_variables_by_attributes",
"(",
"axis",
"=",
"lambda",
"x",
":",
"x",
"is",
"not",
"None",
")",
":",
"axis_variables",
".",
"append",
... | 32.8 | 23 |
def draw(
self,
show_tip_labels=True,
show_node_support=False,
use_edge_lengths=False,
orient="right",
print_args=False,
*args,
**kwargs):
"""
plot the tree using toyplot.graph.
Parameters:
-----------
show_... | [
"def",
"draw",
"(",
"self",
",",
"show_tip_labels",
"=",
"True",
",",
"show_node_support",
"=",
"False",
",",
"use_edge_lengths",
"=",
"False",
",",
"orient",
"=",
"\"right\"",
",",
"print_args",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
"... | 30.361111 | 18.027778 |
def initialize_view(self):
"""Clean the tree and view parameters"""
self.clear()
self.item_depth = 0 # To be use for collapsing/expanding one level
self.item_list = [] # To be use for collapsing/expanding one level
self.items_to_be_shown = {}
self.current_view_de... | [
"def",
"initialize_view",
"(",
"self",
")",
":",
"self",
".",
"clear",
"(",
")",
"self",
".",
"item_depth",
"=",
"0",
"# To be use for collapsing/expanding one level\r",
"self",
".",
"item_list",
"=",
"[",
"]",
"# To be use for collapsing/expanding one level\r",
"self... | 45.857143 | 16.285714 |
def infer_modifications(stmts):
"""Return inferred Modification from RegulateActivity + ActiveForm.
This function looks for combinations of Activation/Inhibition Statements
and ActiveForm Statements that imply a Modification Statement.
For example, if we know that A activates B, and pho... | [
"def",
"infer_modifications",
"(",
"stmts",
")",
":",
"linked_stmts",
"=",
"[",
"]",
"for",
"act_stmt",
"in",
"_get_statements_by_type",
"(",
"stmts",
",",
"RegulateActivity",
")",
":",
"for",
"af_stmt",
"in",
"_get_statements_by_type",
"(",
"stmts",
",",
"Activ... | 46.37037 | 18.925926 |
def _fake_openassociatorinstancepaths(self, namespace, **params):
# pylint: disable=invalid-name
"""
Implements WBEM server responder for
:meth:`~pywbem.WBEMConnection.OpenAssociatorInstancePaths`
with data from the instance repository.
"""
self._validate_namespac... | [
"def",
"_fake_openassociatorinstancepaths",
"(",
"self",
",",
"namespace",
",",
"*",
"*",
"params",
")",
":",
"# pylint: disable=invalid-name",
"self",
".",
"_validate_namespace",
"(",
"namespace",
")",
"self",
".",
"_validate_open_params",
"(",
"*",
"*",
"params",
... | 39.5 | 16.944444 |
def free_sources(self, free=True, pars=None, cuts=None,
distance=None, skydir=None, minmax_ts=None, minmax_npred=None,
exclude=None, square=False, **kwargs):
"""Free or fix sources in the ROI model satisfying the given
selection. When multiple selections are de... | [
"def",
"free_sources",
"(",
"self",
",",
"free",
"=",
"True",
",",
"pars",
"=",
"None",
",",
"cuts",
"=",
"None",
",",
"distance",
"=",
"None",
",",
"skydir",
"=",
"None",
",",
"minmax_ts",
"=",
"None",
",",
"minmax_npred",
"=",
"None",
",",
"exclude... | 37.676056 | 25.070423 |
def rmv_normal(mu, tau, size=1):
"""
Random multivariate normal variates.
"""
sig = np.linalg.cholesky(tau)
mu_size = np.shape(mu)
if size == 1:
out = np.random.normal(size=mu_size)
try:
flib.dtrsm_wrap(sig, out, 'L', 'T', 'L', 1.)
except:
out = ... | [
"def",
"rmv_normal",
"(",
"mu",
",",
"tau",
",",
"size",
"=",
"1",
")",
":",
"sig",
"=",
"np",
".",
"linalg",
".",
"cholesky",
"(",
"tau",
")",
"mu_size",
"=",
"np",
".",
"shape",
"(",
"mu",
")",
"if",
"size",
"==",
"1",
":",
"out",
"=",
"np"... | 28.392857 | 15.535714 |
def make(self, apps):
"""
Create the report from application results
"""
for subreport in self.subreports:
logger.debug('Make subreport "{0}"'.format(subreport.name))
subreport.make(apps)
for subreport in self.subreports:
subreport.compact_tab... | [
"def",
"make",
"(",
"self",
",",
"apps",
")",
":",
"for",
"subreport",
"in",
"self",
".",
"subreports",
":",
"logger",
".",
"debug",
"(",
"'Make subreport \"{0}\"'",
".",
"format",
"(",
"subreport",
".",
"name",
")",
")",
"subreport",
".",
"make",
"(",
... | 31.6 | 11.2 |
def _download_csv_from_gdocs(self, trans_csv_path, meta_csv_path):
"""
Download csv from GDoc.
:return: returns resource if worksheets are present
:except: raises PODocsError with info if communication
with GDocs lead to any errors
"""
try:
en... | [
"def",
"_download_csv_from_gdocs",
"(",
"self",
",",
"trans_csv_path",
",",
"meta_csv_path",
")",
":",
"try",
":",
"entry",
"=",
"self",
".",
"gd_client",
".",
"GetResourceById",
"(",
"self",
".",
"key",
")",
"self",
".",
"gd_client",
".",
"DownloadResource",
... | 38.35 | 13.65 |
def sphere_example():
"""A basic example of how to use the sphere agent."""
env = holodeck.make("MazeWorld")
# This command is to constantly rotate to the right
command = 2
for i in range(10):
env.reset()
for _ in range(1000):
state, reward, terminal, _ = env.step(comman... | [
"def",
"sphere_example",
"(",
")",
":",
"env",
"=",
"holodeck",
".",
"make",
"(",
"\"MazeWorld\"",
")",
"# This command is to constantly rotate to the right",
"command",
"=",
"2",
"for",
"i",
"in",
"range",
"(",
"10",
")",
":",
"env",
".",
"reset",
"(",
")",... | 33.214286 | 17.285714 |
def prepare_intercept(callback):
"""
Registers a Windows low level keyboard hook. The provided callback will
be invoked for each high-level keyboard event, and is expected to return
True if the key event should be passed to the next program, or False if
the event is to be blocked.
No event is p... | [
"def",
"prepare_intercept",
"(",
"callback",
")",
":",
"_setup_name_tables",
"(",
")",
"def",
"process_key",
"(",
"event_type",
",",
"vk",
",",
"scan_code",
",",
"is_extended",
")",
":",
"global",
"shift_is_pressed",
",",
"altgr_is_pressed",
",",
"ignore_next_righ... | 41.821918 | 21.164384 |
def _stream(self, context, message_factory):
"""write request/response into frames
Transform request/response into protocol level message objects based on
types and argstreams.
Assumption: the chunk data read from stream can fit into memory.
If arg stream is at init or streami... | [
"def",
"_stream",
"(",
"self",
",",
"context",
",",
"message_factory",
")",
":",
"args",
"=",
"[",
"]",
"try",
":",
"for",
"argstream",
"in",
"context",
".",
"argstreams",
":",
"chunk",
"=",
"yield",
"argstream",
".",
"read",
"(",
")",
"args",
".",
"... | 40.3 | 19.42 |
def _hdfs_datanode_metrics(self, beans, tags):
"""
Process HDFS Datanode metrics from given beans
"""
# Only get the first bean
bean = next(iter(beans))
bean_name = bean.get('name')
self.log.debug("Bean name retrieved: {}".format(bean_name))
for metric, ... | [
"def",
"_hdfs_datanode_metrics",
"(",
"self",
",",
"beans",
",",
"tags",
")",
":",
"# Only get the first bean",
"bean",
"=",
"next",
"(",
"iter",
"(",
"beans",
")",
")",
"bean_name",
"=",
"bean",
".",
"get",
"(",
"'name'",
")",
"self",
".",
"log",
".",
... | 37.857143 | 16.142857 |
def search(self, searchString, category="", math=False, game=False, searchFiles=False, extension=""):
"""Core function to search the indexes and return data"""
data = []
nameData = {}
fileData = {}
#Search the name index
if searchFiles:
fileData = self.searchNamesIndex(self.fileIndex, fileData, search... | [
"def",
"search",
"(",
"self",
",",
"searchString",
",",
"category",
"=",
"\"\"",
",",
"math",
"=",
"False",
",",
"game",
"=",
"False",
",",
"searchFiles",
"=",
"False",
",",
"extension",
"=",
"\"\"",
")",
":",
"data",
"=",
"[",
"]",
"nameData",
"=",
... | 33.842105 | 25.894737 |
def get_ui_class(ui_file):
"""Get UI Python class from .ui file.
Can be filename.ui or subdirectory/filename.ui
:param ui_file: The file of the ui in safe.gui.ui
:type ui_file: str
"""
os.path.sep.join(ui_file.split('/'))
ui_file_path = os.path.abspath(
os.path.join(
... | [
"def",
"get_ui_class",
"(",
"ui_file",
")",
":",
"os",
".",
"path",
".",
"sep",
".",
"join",
"(",
"ui_file",
".",
"split",
"(",
"'/'",
")",
")",
"ui_file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os... | 24.631579 | 16.631579 |
def color_electrodes(self, config_nr, ax):
"""
Color the electrodes used in specific configuration.
Voltage electrodes are yellow, Current electrodes are red ?!
"""
electrodes = np.loadtxt(options.config_file, skiprows=1)
electrodes = self.configs[~np.isnan(self.configs).... | [
"def",
"color_electrodes",
"(",
"self",
",",
"config_nr",
",",
"ax",
")",
":",
"electrodes",
"=",
"np",
".",
"loadtxt",
"(",
"options",
".",
"config_file",
",",
"skiprows",
"=",
"1",
")",
"electrodes",
"=",
"self",
".",
"configs",
"[",
"~",
"np",
".",
... | 40.238095 | 12.904762 |
def idxmin(self, axis=0, skipna=True, *args, **kwargs):
"""
Return the row label of the minimum value.
If multiple values equal the minimum, the first row label with that
value is returned.
Parameters
----------
skipna : bool, default True
Exclude NA... | [
"def",
"idxmin",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"skipna",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"skipna",
"=",
"nv",
".",
"validate_argmin_with_skipna",
"(",
"skipna",
",",
"args",
",",
"kwargs",
")",
"i",
"=",... | 29.318841 | 22.884058 |
def set_padist_gaussian_loss_cone(self, boundary_rad, expwidth):
"""Set the pitch-angle distribution to a Gaussian loss cone.
**Call signature**
*boundary_rad*
The angle inside which there are no losses, in radians.
*expwidth*
The characteristic width of the Gaussia... | [
"def",
"set_padist_gaussian_loss_cone",
"(",
"self",
",",
"boundary_rad",
",",
"expwidth",
")",
":",
"self",
".",
"in_vals",
"[",
"IN_VAL_PADIST",
"]",
"=",
"PADIST_GLC",
"self",
".",
"in_vals",
"[",
"IN_VAL_LCBDY",
"]",
"=",
"boundary_rad",
"*",
"180",
"/",
... | 36.727273 | 20.590909 |
def iter_entries(self):
"""
Generate an |_IfdEntry| instance corresponding to each entry in the
directory.
"""
for idx in range(self._entry_count):
dir_entry_offset = self._offset + 2 + (idx*12)
ifd_entry = _IfdEntryFactory(self._stream_rdr, dir_entry_offs... | [
"def",
"iter_entries",
"(",
"self",
")",
":",
"for",
"idx",
"in",
"range",
"(",
"self",
".",
"_entry_count",
")",
":",
"dir_entry_offset",
"=",
"self",
".",
"_offset",
"+",
"2",
"+",
"(",
"idx",
"*",
"12",
")",
"ifd_entry",
"=",
"_IfdEntryFactory",
"("... | 38.111111 | 16.111111 |
def bodypart_types(self, method, input=True):
"""
Get a list of I{parameter definitions} (pdefs) defined for the
specified method.
An input I{pdef} is a (I{name}, L{xsd.sxbase.SchemaObject}) tuple,
while an output I{pdef} is a L{xsd.sxbase.SchemaObject}.
@param method: ... | [
"def",
"bodypart_types",
"(",
"self",
",",
"method",
",",
"input",
"=",
"True",
")",
":",
"if",
"input",
":",
"parts",
"=",
"method",
".",
"soap",
".",
"input",
".",
"body",
".",
"parts",
"else",
":",
"parts",
"=",
"method",
".",
"soap",
".",
"outp... | 34.333333 | 17 |
def native(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a given string into a native string."""
if isinstance(s, str):
return s
if str is unicode: # Python 3.x ->
return unicodestr(s, encoding, fallback)
return bytestring(s, encoding, fallback) | [
"def",
"native",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"fallback",
"=",
"'iso-8859-1'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"str",
")",
":",
"return",
"s",
"if",
"str",
"is",
"unicode",
":",
"# Python 3.x ->",
"return",
"unicodestr",
... | 28.2 | 18.6 |
def from_dict(cls, d):
"""
Returns a COHP object from a dict representation of the COHP.
"""
if "ICOHP" in d:
icohp = {Spin(int(key)): np.array(val)
for key, val in d["ICOHP"].items()}
else:
icohp = None
return Cohp(d["efermi"... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"if",
"\"ICOHP\"",
"in",
"d",
":",
"icohp",
"=",
"{",
"Spin",
"(",
"int",
"(",
"key",
")",
")",
":",
"np",
".",
"array",
"(",
"val",
")",
"for",
"key",
",",
"val",
"in",
"d",
"[",
"\"ICOHP\"... | 35.071429 | 15.928571 |
def last(self, count=1):
"""
Returns the last record in the query (sorting by id unless modified by
`order_by`, whereupon it reverses the order passed in `order_by`).
Returns None if the query has no records.
"""
if self._order_with:
order = self._order_with.v... | [
"def",
"last",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"if",
"self",
".",
"_order_with",
":",
"order",
"=",
"self",
".",
"_order_with",
".",
"values",
"(",
")",
"[",
"0",
"]",
"order",
"=",
"\"desc\"",
"if",
"order",
"==",
"\"asc\"",
"else",... | 41.6875 | 14.9375 |
def embed_MDS(X, ndim=2, how='metric', distance_metric='euclidean',
n_jobs=1, seed=None, verbose=0):
"""Performs classic, metric, and non-metric MDS
Metric MDS is initialized using classic MDS,
non-metric MDS is initialized using metric MDS.
Parameters
----------
X: ndarray [n_sa... | [
"def",
"embed_MDS",
"(",
"X",
",",
"ndim",
"=",
"2",
",",
"how",
"=",
"'metric'",
",",
"distance_metric",
"=",
"'euclidean'",
",",
"n_jobs",
"=",
"1",
",",
"seed",
"=",
"None",
",",
"verbose",
"=",
"0",
")",
":",
"if",
"how",
"not",
"in",
"[",
"'... | 41.385714 | 19.157143 |
def clean_delete(self):
"""
Deletes this router & associated files (nvram, disks etc.)
"""
yield from self._hypervisor.send('vm clean_delete "{}"'.format(self._name))
self._hypervisor.devices.remove(self)
try:
yield from wait_run_in_executor(shutil.rmtree, se... | [
"def",
"clean_delete",
"(",
"self",
")",
":",
"yield",
"from",
"self",
".",
"_hypervisor",
".",
"send",
"(",
"'vm clean_delete \"{}\"'",
".",
"format",
"(",
"self",
".",
"_name",
")",
")",
"self",
".",
"_hypervisor",
".",
"devices",
".",
"remove",
"(",
"... | 45.416667 | 26.416667 |
def populate_jobset(job, jobset, depth):
""" Creates a set of jobs, containing jobs at difference depths of the
dependency tree, retaining dependencies as strings, not Jobs.
"""
jobset.add(job)
if len(job.dependencies) == 0:
return jobset
for j in job.dependencies:
jobset = popul... | [
"def",
"populate_jobset",
"(",
"job",
",",
"jobset",
",",
"depth",
")",
":",
"jobset",
".",
"add",
"(",
"job",
")",
"if",
"len",
"(",
"job",
".",
"dependencies",
")",
"==",
"0",
":",
"return",
"jobset",
"for",
"j",
"in",
"job",
".",
"dependencies",
... | 35.9 | 11.6 |
def read_pmc(self, pmcid):
"""Read a given PMC article.
Parameters
----------
pmcid : str
The PMC ID of the article to read. Note that only
articles in the open-access subset of PMC will work.
"""
msg = KQMLPerformative('REQUEST')
msg.set(... | [
"def",
"read_pmc",
"(",
"self",
",",
"pmcid",
")",
":",
"msg",
"=",
"KQMLPerformative",
"(",
"'REQUEST'",
")",
"msg",
".",
"set",
"(",
"'receiver'",
",",
"'READER'",
")",
"content",
"=",
"KQMLList",
"(",
"'run-pmcid'",
")",
"content",
".",
"sets",
"(",
... | 32.5 | 12 |
def check(self, file):
"""
Checks a given file against all available yara rules
:param file: Path to file
:type file:str
:returns: Python list with matched rules info
:rtype: list
"""
result = []
all_matches = []
for filerules in os.listdir... | [
"def",
"check",
"(",
"self",
",",
"file",
")",
":",
"result",
"=",
"[",
"]",
"all_matches",
"=",
"[",
"]",
"for",
"filerules",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"rulepaths",
")",
":",
"try",
":",
"rule",
"=",
"yara",
".",
"compile",
"... | 41.8 | 18.2 |
def reset(self):
"""
Releases all entities held by this Unit Of Work (i.e., removes state
information from all registered entities and clears the entity map).
"""
for ents in self.__entity_set_map.values():
for ent in ents:
EntityState.release(ent, sel... | [
"def",
"reset",
"(",
"self",
")",
":",
"for",
"ents",
"in",
"self",
".",
"__entity_set_map",
".",
"values",
"(",
")",
":",
"for",
"ent",
"in",
"ents",
":",
"EntityState",
".",
"release",
"(",
"ent",
",",
"self",
")",
"self",
".",
"__entity_set_map",
... | 39.111111 | 14.222222 |
def Action(act, *args, **kw):
"""A factory for action objects."""
# Really simple: the _do_create_* routines do the heavy lifting.
_do_create_keywords(args, kw)
if is_List(act):
return _do_create_list_action(act, kw)
return _do_create_action(act, kw) | [
"def",
"Action",
"(",
"act",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# Really simple: the _do_create_* routines do the heavy lifting.",
"_do_create_keywords",
"(",
"args",
",",
"kw",
")",
"if",
"is_List",
"(",
"act",
")",
":",
"return",
"_do_create_lis... | 38.857143 | 10.714286 |
def get_data_feed(self, train_mode=True, qname_in='input', qname_out='output', input_mapping=None):
"""Convenience function to access ``TFNode.DataFeed`` directly from this object instance."""
return TFNode.DataFeed(self.mgr, train_mode, qname_in, qname_out, input_mapping) | [
"def",
"get_data_feed",
"(",
"self",
",",
"train_mode",
"=",
"True",
",",
"qname_in",
"=",
"'input'",
",",
"qname_out",
"=",
"'output'",
",",
"input_mapping",
"=",
"None",
")",
":",
"return",
"TFNode",
".",
"DataFeed",
"(",
"self",
".",
"mgr",
",",
"trai... | 93 | 34.333333 |
def make_avsc_object(json_data, names=None):
# type: (Union[Dict[Text, Text], List[Any], Text], Optional[Names]) -> Schema
"""
Build Avro Schema from data parsed out of JSON string.
@arg names: A Name object (tracks seen names and default space)
"""
if names is None:
names = Names()
... | [
"def",
"make_avsc_object",
"(",
"json_data",
",",
"names",
"=",
"None",
")",
":",
"# type: (Union[Dict[Text, Text], List[Any], Text], Optional[Names]) -> Schema",
"if",
"names",
"is",
"None",
":",
"names",
"=",
"Names",
"(",
")",
"assert",
"isinstance",
"(",
"names",
... | 45.851064 | 17.595745 |
def agg_autocorrelation(x, param):
r"""
Calculates the value of an aggregation function :math:`f_{agg}` (e.g. the variance or the mean) over the
autocorrelation :math:`R(l)` for different lags. The autocorrelation :math:`R(l)` for lag :math:`l` is defined as
.. math::
R(l) = \frac{1}{(n-l)\sig... | [
"def",
"agg_autocorrelation",
"(",
"x",
",",
"param",
")",
":",
"# if the time series is longer than the following threshold, we use fft to calculate the acf",
"THRESHOLD_TO_USE_FFT",
"=",
"1250",
"var",
"=",
"np",
".",
"var",
"(",
"x",
")",
"n",
"=",
"len",
"(",
"x",... | 47.162791 | 35.465116 |
def boundary_maximum_exponential(graph, xxx_todo_changeme3):
r"""
Boundary term processing adjacent voxels maximum value using an exponential relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
The same as... | [
"def",
"boundary_maximum_exponential",
"(",
"graph",
",",
"xxx_todo_changeme3",
")",
":",
"(",
"gradient_image",
",",
"sigma",
",",
"spacing",
")",
"=",
"xxx_todo_changeme3",
"gradient_image",
"=",
"scipy",
".",
"asarray",
"(",
"gradient_image",
")",
"def",
"bound... | 39.355556 | 22.088889 |
def update_grammar_to_be_variable_free(grammar_dictionary: Dict[str, List[str]]):
"""
SQL is a predominately variable free language in terms of simple usage, in the
sense that most queries do not create references to variables which are not
already static tables in a dataset. However, it is possible to ... | [
"def",
"update_grammar_to_be_variable_free",
"(",
"grammar_dictionary",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
")",
":",
"# Tables in variable free grammars cannot be aliased, so we",
"# remove this functionality from the grammar.",
"grammar_dictionary",
"[... | 53 | 24.771429 |
def clean_cornell_movies(filename='cornell_movie_dialogs_corpus.zip', subdir='cornell movie-dialogs corpus'):
""" Load a dataframe of ~100k raw (uncollated) movie lines from the cornell movies dialog corpus
>>> local_filepath = download_file(BIG_URLS['cornell_movie_dialogs_corpus'][0])
>>> df = clean_c... | [
"def",
"clean_cornell_movies",
"(",
"filename",
"=",
"'cornell_movie_dialogs_corpus.zip'",
",",
"subdir",
"=",
"'cornell movie-dialogs corpus'",
")",
":",
"fullpath_zipfile",
"=",
"find_filepath",
"(",
"filename",
")",
"dirname",
"=",
"os",
".",
"path",
".",
"basename... | 49.107143 | 16.357143 |
def iter_files(self):
"""Iterate over files."""
# file_iter may be a callable or an iterator
if callable(self.file_iter):
return self.file_iter()
return iter(self.file_iter) | [
"def",
"iter_files",
"(",
"self",
")",
":",
"# file_iter may be a callable or an iterator",
"if",
"callable",
"(",
"self",
".",
"file_iter",
")",
":",
"return",
"self",
".",
"file_iter",
"(",
")",
"return",
"iter",
"(",
"self",
".",
"file_iter",
")"
] | 35.333333 | 7.5 |
def _get_self_bounds(self):
"""
Computes the bounds of the object itself (not including it's children)
in the form [[lat_min, lon_min], [lat_max, lon_max]].
"""
bounds = [[None, None], [None, None]]
for point in self.data:
bounds = [
[
... | [
"def",
"_get_self_bounds",
"(",
"self",
")",
":",
"bounds",
"=",
"[",
"[",
"None",
",",
"None",
"]",
",",
"[",
"None",
",",
"None",
"]",
"]",
"for",
"point",
"in",
"self",
".",
"data",
":",
"bounds",
"=",
"[",
"[",
"none_min",
"(",
"bounds",
"[",... | 31.684211 | 17.473684 |
def create_profile():
"""If this is the user's first login, the create_or_login function
will redirect here so that the user can set up his profile.
"""
if g.user is not None or 'openid' not in session:
return redirect(url_for('index'))
if request.method == 'POST':
name = request.for... | [
"def",
"create_profile",
"(",
")",
":",
"if",
"g",
".",
"user",
"is",
"not",
"None",
"or",
"'openid'",
"not",
"in",
"session",
":",
"return",
"redirect",
"(",
"url_for",
"(",
"'index'",
")",
")",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"... | 44.333333 | 14.722222 |
def change_password(self, usrname, oldpwd, newpwd, callback=None):
'''
Change password.
'''
params = {'usrName': usrname,
'oldPwd' : oldpwd,
'newPwd' : newpwd,
}
return self.execute_command('changePassword',
... | [
"def",
"change_password",
"(",
"self",
",",
"usrname",
",",
"oldpwd",
",",
"newpwd",
",",
"callback",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'usrName'",
":",
"usrname",
",",
"'oldPwd'",
":",
"oldpwd",
",",
"'newPwd'",
":",
"newpwd",
",",
"}",
"ret... | 35.4 | 16.8 |
def get(self, entry):
"""Gets an entry by key. Will return None if there is no
matching entry."""
try:
list = self.cache[entry.key]
return list[list.index(entry)]
except:
return None | [
"def",
"get",
"(",
"self",
",",
"entry",
")",
":",
"try",
":",
"list",
"=",
"self",
".",
"cache",
"[",
"entry",
".",
"key",
"]",
"return",
"list",
"[",
"list",
".",
"index",
"(",
"entry",
")",
"]",
"except",
":",
"return",
"None"
] | 30.5 | 11.375 |
def calcstats(data, t1, t2, sr):
"""Calculate the mean and standard deviation of some array between
t1 and t2 provided the sample rate sr.
"""
dataseg = data[sr*t1:sr*t2]
meandata = np.mean(dataseg[~np.isnan(dataseg)])
stddata = np.std(dataseg[~np.isnan(dataseg)])
return meandata, std... | [
"def",
"calcstats",
"(",
"data",
",",
"t1",
",",
"t2",
",",
"sr",
")",
":",
"dataseg",
"=",
"data",
"[",
"sr",
"*",
"t1",
":",
"sr",
"*",
"t2",
"]",
"meandata",
"=",
"np",
".",
"mean",
"(",
"dataseg",
"[",
"~",
"np",
".",
"isnan",
"(",
"datas... | 39.625 | 6.5 |
def _write_config_file(template_file):
"""
Write a config file to the source bundle location to identify the entry point.
:param template_file: path to the task template subclass (executable)
"""
config_filename = '.cloud_harness_config.json'
config_path = os.path.dirname... | [
"def",
"_write_config_file",
"(",
"template_file",
")",
":",
"config_filename",
"=",
"'.cloud_harness_config.json'",
"config_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"template_file",
")",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"templat... | 33.842105 | 20.368421 |
def _handle_subscribed(self, *args, chanId=None, channel=None, **kwargs):
"""
Handles responses to subscribe() commands - registers a channel id with
the client and assigns a data handler to it.
:param chanId: int, represent channel id as assigned by server
:param channel: str, ... | [
"def",
"_handle_subscribed",
"(",
"self",
",",
"*",
"args",
",",
"chanId",
"=",
"None",
",",
"channel",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"debug",
"(",
"\"_handle_subscribed: %s - %s - %s\"",
",",
"chanId",
",",
"channel",
",",
... | 30.833333 | 21.404762 |
def deployed(name, jboss_config, salt_source=None):
'''Ensures that the given application is deployed on server.
jboss_config:
Dict with connection properties (see state description)
salt_source:
How to find the artifact to be deployed.
target_file:
Where to look... | [
"def",
"deployed",
"(",
"name",
",",
"jboss_config",
",",
"salt_source",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"\" ======================== STATE: jboss7.deployed (name: %s) \"",
",",
"name",
")",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'... | 44.055556 | 31.796296 |
def _generic_definetext_parser(self, obj, rgb_struct):
"""Generic parser for the DefineTextN tags."""
obj.CharacterID = unpack_ui16(self._src)
obj.TextBounds = self._get_struct_rect()
obj.TextMatrix = self._get_struct_matrix()
obj.GlyphBits = glyph_bits = unpack_ui8(self._src)
... | [
"def",
"_generic_definetext_parser",
"(",
"self",
",",
"obj",
",",
"rgb_struct",
")",
":",
"obj",
".",
"CharacterID",
"=",
"unpack_ui16",
"(",
"self",
".",
"_src",
")",
"obj",
".",
"TextBounds",
"=",
"self",
".",
"_get_struct_rect",
"(",
")",
"obj",
".",
... | 41.489796 | 13 |
def validate(defaults, metadata, config):
"""
Validate configuration.
"""
for path, _, default, parent, value in zip_dicts(defaults, config):
if isinstance(default, Requirement):
# validate the current value and assign the output
parent[path[-1]] = default.validate(metad... | [
"def",
"validate",
"(",
"defaults",
",",
"metadata",
",",
"config",
")",
":",
"for",
"path",
",",
"_",
",",
"default",
",",
"parent",
",",
"value",
"in",
"zip_dicts",
"(",
"defaults",
",",
"config",
")",
":",
"if",
"isinstance",
"(",
"default",
",",
... | 36.555556 | 15.666667 |
def is_predecessor_of_other(self, predecessor, others):
"""Returns whether the predecessor is a predecessor or a predecessor
of a predecessor...of any of the others.
Args:
predecessor (str): The txn id of the predecessor.
others (list(str)): The txn id of the successor.
... | [
"def",
"is_predecessor_of_other",
"(",
"self",
",",
"predecessor",
",",
"others",
")",
":",
"return",
"any",
"(",
"predecessor",
"in",
"self",
".",
"_predecessors_by_id",
"[",
"o",
"]",
"for",
"o",
"in",
"others",
")"
] | 31.142857 | 23.928571 |
def gen_items_from_sql_csv(s: str) -> Generator[str, None, None]:
"""
Splits a comma-separated list of quoted SQL values, with ``'`` as the quote
character. Allows escaping of the quote character by doubling it. Returns
the quotes (and escaped quotes) as part of the result. Allows newlines etc.
with... | [
"def",
"gen_items_from_sql_csv",
"(",
"s",
":",
"str",
")",
"->",
"Generator",
"[",
"str",
",",
"None",
",",
"None",
"]",
":",
"# csv.reader will not both process the quotes and return the quotes;",
"# we need them to distinguish e.g. NULL from 'NULL'.",
"# log.warning('gen_ite... | 37.3 | 18.4 |
async def enqueue_job(
self,
function: str,
*args: Any,
_job_id: Optional[str] = None,
_defer_until: Optional[datetime] = None,
_defer_by: Union[None, int, float, timedelta] = None,
_expires: Union[None, int, float, timedelta] = None,
_job_try: Optional[in... | [
"async",
"def",
"enqueue_job",
"(",
"self",
",",
"function",
":",
"str",
",",
"*",
"args",
":",
"Any",
",",
"_job_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"_defer_until",
":",
"Optional",
"[",
"datetime",
"]",
"=",
"None",
",",
"_defe... | 38.583333 | 18.25 |
def parse(args):
"""
Define the available arguments
"""
from tzlocal import get_localzone
try:
timezone = get_localzone()
if isinstance(timezone, pytz.BaseTzInfo):
timezone = timezone.zone
except Exception: # pragma: no cover
timezone = 'UTC'
if timezone... | [
"def",
"parse",
"(",
"args",
")",
":",
"from",
"tzlocal",
"import",
"get_localzone",
"try",
":",
"timezone",
"=",
"get_localzone",
"(",
")",
"if",
"isinstance",
"(",
"timezone",
",",
"pytz",
".",
"BaseTzInfo",
")",
":",
"timezone",
"=",
"timezone",
".",
... | 50.745283 | 26.613208 |
def get_significant_digits(numeric_value):
"""
Returns the precision for a given floatable value.
If value is None or not floatable, returns None.
Will return positive values if the result is below 1 and will
return 0 values if the result is above or equal to 1.
:param numeric_value: the value t... | [
"def",
"get_significant_digits",
"(",
"numeric_value",
")",
":",
"try",
":",
"numeric_value",
"=",
"float",
"(",
"numeric_value",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"None",
"if",
"numeric_value",
"==",
"0",
":",
"return",
... | 35.884615 | 13.423077 |
def put_file(up_token, key, file_path, params=None,
mime_type='application/octet-stream', check_crc=False,
progress_handler=None, upload_progress_recorder=None, keep_last_modified=False):
"""上传文件到七牛
Args:
up_token: 上传凭证
key: 上传文件名
file_path... | [
"def",
"put_file",
"(",
"up_token",
",",
"key",
",",
"file_path",
",",
"params",
"=",
"None",
",",
"mime_type",
"=",
"'application/octet-stream'",
",",
"check_crc",
"=",
"False",
",",
"progress_handler",
"=",
"None",
",",
"upload_progress_recorder",
"=",
"None",... | 45.305556 | 22.277778 |
def validate(self):
"""
Validates the state of this XBlock.
Subclasses should override validate_field_data() to validate fields and override this
only for validation not related to this block's field values.
"""
validation = super(StudioEditableXBlockMixin, self).validat... | [
"def",
"validate",
"(",
"self",
")",
":",
"validation",
"=",
"super",
"(",
"StudioEditableXBlockMixin",
",",
"self",
")",
".",
"validate",
"(",
")",
"self",
".",
"validate_field_data",
"(",
"validation",
",",
"self",
")",
"return",
"validation"
] | 39.1 | 20.1 |
def addButton(
fnc,
states=("On", "Off"),
c=("w", "w"),
bc=("dg", "dr"),
pos=(20, 40),
size=24,
font="arial",
bold=False,
italic=False,
alpha=1,
angle=0,
):
"""Add a button to the renderer window.
:param list states: a list of possible states ['On', 'Off']
:p... | [
"def",
"addButton",
"(",
"fnc",
",",
"states",
"=",
"(",
"\"On\"",
",",
"\"Off\"",
")",
",",
"c",
"=",
"(",
"\"w\"",
",",
"\"w\"",
")",
",",
"bc",
"=",
"(",
"\"dg\"",
",",
"\"dr\"",
")",
",",
"pos",
"=",
"(",
"20",
",",
"40",
")",
",",
"size"... | 30.657895 | 19.447368 |
def _make_all_matchers(cls, parameters):
'''
For every parameter, create a matcher if the parameter has an
annotation.
'''
for name, param in parameters:
annotation = param.annotation
if annotation is not Parameter.empty:
yield name, cls._m... | [
"def",
"_make_all_matchers",
"(",
"cls",
",",
"parameters",
")",
":",
"for",
"name",
",",
"param",
"in",
"parameters",
":",
"annotation",
"=",
"param",
".",
"annotation",
"if",
"annotation",
"is",
"not",
"Parameter",
".",
"empty",
":",
"yield",
"name",
","... | 39.222222 | 17.222222 |
def update_intervals(self, back=None):
'''
Return the update intervals for all of the enabled fileserver backends
which support variable update intervals.
'''
back = self.backends(back)
ret = {}
for fsb in back:
fstr = '{0}.update_intervals'.format(fsb... | [
"def",
"update_intervals",
"(",
"self",
",",
"back",
"=",
"None",
")",
":",
"back",
"=",
"self",
".",
"backends",
"(",
"back",
")",
"ret",
"=",
"{",
"}",
"for",
"fsb",
"in",
"back",
":",
"fstr",
"=",
"'{0}.update_intervals'",
".",
"format",
"(",
"fsb... | 34.5 | 16.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.