text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def as_plural(result_key):
"""
Given a result key, return in the plural form.
"""
# Not at all guaranteed to work in all cases...
if result_key.endswith('y'):
return re.sub("y$", "ies", result_key)
elif result_key.endswith('address'):
return result_key + 'es'
elif result_key.... | [
"def",
"as_plural",
"(",
"result_key",
")",
":",
"# Not at all guaranteed to work in all cases...",
"if",
"result_key",
".",
"endswith",
"(",
"'y'",
")",
":",
"return",
"re",
".",
"sub",
"(",
"\"y$\"",
",",
"\"ies\"",
",",
"result_key",
")",
"elif",
"result_key"... | 31.8 | 8.466667 |
def marvcli_run(ctx, datasets, deps, excluded_nodes, force, force_dependent,
force_deps, keep, keep_going, list_nodes,
list_dependent, selected_nodes, update_detail,
update_listing, cachesize, collections):
"""Run nodes for selected datasets.
Datasets are specifi... | [
"def",
"marvcli_run",
"(",
"ctx",
",",
"datasets",
",",
"deps",
",",
"excluded_nodes",
",",
"force",
",",
"force_dependent",
",",
"force_deps",
",",
"keep",
",",
"keep_going",
",",
"list_nodes",
",",
"list_dependent",
",",
"selected_nodes",
",",
"update_detail",... | 39.798165 | 20.201835 |
def Square(x, a, b, c):
"""Second order polynomial
Inputs:
-------
``x``: independent variable
``a``: coefficient of the second-order term
``b``: coefficient of the first-order term
``c``: additive constant
Formula:
--------
``a*x^2 + b*x + c``
"""
r... | [
"def",
"Square",
"(",
"x",
",",
"a",
",",
"b",
",",
"c",
")",
":",
"return",
"a",
"*",
"x",
"**",
"2",
"+",
"b",
"*",
"x",
"+",
"c"
] | 22.266667 | 17.666667 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'document') and self.document is not None:
_dict['document'] = self.document
if hasattr(self, 'targets') and self.targets is not None:
_dict['targets'] = self.t... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'document'",
")",
"and",
"self",
".",
"document",
"is",
"not",
"None",
":",
"_dict",
"[",
"'document'",
"]",
"=",
"self",
".",
"document",
"if",
"... | 42.5 | 15.375 |
def create(optimizer, max_lr, min_lr, cycles, cycle_len=1, cycle_mult=1, interpolate='linear', init_lr=0, init_iter=0):
""" Vel factory function """
return CyclePhase(
max_lr=max_lr,
min_lr=min_lr,
cycles=cycles,
cycle_len=cycle_len,
cycle_mult=cycle_mult,
interpo... | [
"def",
"create",
"(",
"optimizer",
",",
"max_lr",
",",
"min_lr",
",",
"cycles",
",",
"cycle_len",
"=",
"1",
",",
"cycle_mult",
"=",
"1",
",",
"interpolate",
"=",
"'linear'",
",",
"init_lr",
"=",
"0",
",",
"init_iter",
"=",
"0",
")",
":",
"return",
"C... | 32.461538 | 19.076923 |
def copy(self, **kwargs):
"""Copy a message, optionally replace attributes with kwargs."""
msg = Message(self.encode(), self.gateway)
for key, val in kwargs.items():
setattr(msg, key, val)
return msg | [
"def",
"copy",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"Message",
"(",
"self",
".",
"encode",
"(",
")",
",",
"self",
".",
"gateway",
")",
"for",
"key",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"setattr",
"(",... | 39.666667 | 9 |
def add_sibling(self, pos=None, arc_element_type=None, description=None, story_element_node=None, **kwargs):
'''
Overrides the default `treebeard` function, adding additional integrity checks.
'''
if 'mile' in arc_element_type:
if self.get_depth() == 1:
raise ... | [
"def",
"add_sibling",
"(",
"self",
",",
"pos",
"=",
"None",
",",
"arc_element_type",
"=",
"None",
",",
"description",
"=",
"None",
",",
"story_element_node",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'mile'",
"in",
"arc_element_type",
":",
"... | 50.166667 | 25.611111 |
def to_array(self):
"""
Serializes this StickerSet to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(StickerSet, self).to_array()
array['name'] = u(self.name) # py2: type unicode, py3: type str
array['tit... | [
"def",
"to_array",
"(",
"self",
")",
":",
"array",
"=",
"super",
"(",
"StickerSet",
",",
"self",
")",
".",
"to_array",
"(",
")",
"array",
"[",
"'name'",
"]",
"=",
"u",
"(",
"self",
".",
"name",
")",
"# py2: type unicode, py3: type str",
"array",
"[",
"... | 33.6875 | 24.9375 |
def p_defaultFlavor(p):
"""defaultFlavor : ',' FLAVOR '(' flavorListWithComma ')'"""
flist = p[4]
# Create dictionary of default flavors based on DSP0004 definition
# of defaults for flavors. This insures that all possible flavors keywords
# are defined in the created dictionary.
flavors = {'ENA... | [
"def",
"p_defaultFlavor",
"(",
"p",
")",
":",
"flist",
"=",
"p",
"[",
"4",
"]",
"# Create dictionary of default flavors based on DSP0004 definition",
"# of defaults for flavors. This insures that all possible flavors keywords",
"# are defined in the created dictionary.",
"flavors",
"... | 38.4 | 12.8 |
def direct_normal_radiation(self, value=9999.0):
"""Corresponds to IDD Field `direct_normal_radiation`
Args:
value (float): value for IDD Field `direct_normal_radiation`
Unit: Wh/m2
value >= 0.0
Missing value: 9999.0
if `value`... | [
"def",
"direct_normal_radiation",
"(",
"self",
",",
"value",
"=",
"9999.0",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"float",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to... | 36.666667 | 19.851852 |
def _unique_by_email(users_and_watches):
"""Given a sequence of (User/EmailUser, [Watch, ...]) pairs
clustered by email address (which is never ''), yield from each
cluster a single pair like this::
(User/EmailUser, [Watch, Watch, ...]).
The User/Email is that of...
(1) the first incoming pa... | [
"def",
"_unique_by_email",
"(",
"users_and_watches",
")",
":",
"def",
"ensure_user_has_email",
"(",
"user",
",",
"cluster_email",
")",
":",
"\"\"\"Make sure the user in the user-watch pair has an email address.\n\n The caller guarantees us an email from either the user or the watc... | 39.603774 | 17.735849 |
def add(self, action):
"""Add an action to the execution queue."""
self._state_machine.transition_to_add()
self._actions.append(action) | [
"def",
"add",
"(",
"self",
",",
"action",
")",
":",
"self",
".",
"_state_machine",
".",
"transition_to_add",
"(",
")",
"self",
".",
"_actions",
".",
"append",
"(",
"action",
")"
] | 39 | 7.25 |
def set(conf):
"""Applies a configuration to the global config object"""
for name, value in conf.items():
if value is not None:
setattr(Conf, name.upper(), value) | [
"def",
"set",
"(",
"conf",
")",
":",
"for",
"name",
",",
"value",
"in",
"conf",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"setattr",
"(",
"Conf",
",",
"name",
".",
"upper",
"(",
")",
",",
"value",
")"
] | 40.4 | 8.6 |
def dependencies(dist, recursive=False, info=False):
"""Yield distribution's dependencies."""
def case_sorted(items):
"""Return unique list sorted in case-insensitive order."""
return sorted(set(items), key=lambda i: i.lower())
def requires(distribution):
"""Return the requirements... | [
"def",
"dependencies",
"(",
"dist",
",",
"recursive",
"=",
"False",
",",
"info",
"=",
"False",
")",
":",
"def",
"case_sorted",
"(",
"items",
")",
":",
"\"\"\"Return unique list sorted in case-insensitive order.\"\"\"",
"return",
"sorted",
"(",
"set",
"(",
"items",... | 38.85 | 16.95 |
def prepare_calc_dir(self):
'''
Prepare the calculation directory for VASP execution.
This needs to be re-implemented for each local setup.
The following code reflects just my particular setup.
'''
with open("vasprun.conf","w") as f:
f.write('NODES="nodes=%s:p... | [
"def",
"prepare_calc_dir",
"(",
"self",
")",
":",
"with",
"open",
"(",
"\"vasprun.conf\"",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'NODES=\"nodes=%s:ppn=%d\"\\n'",
"%",
"(",
"self",
".",
"nodes",
",",
"self",
".",
"ppn",
")",
")",
"... | 42.181818 | 17.818182 |
def _open(self, filename):
"""
Open the input file. Set self._fp to point to it. Read the first
line of parameters.
@param filename: A C{str} filename containing JSON BLAST records.
@raise ValueError: if the first line of the file isn't valid JSON,
if the input file ... | [
"def",
"_open",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.bz2'",
")",
":",
"if",
"six",
".",
"PY3",
":",
"self",
".",
"_fp",
"=",
"bz2",
".",
"open",
"(",
"filename",
",",
"mode",
"=",
"'rt'",
",",
"encodi... | 39.411765 | 21 |
def action_log_create(sender, instance, created, **kwargs):
"""
Signal receiver that creates a log entry when a model instance is first saved to the database.
Direct use is discouraged, connect your model through :py:func:`actionslog.registry.register` instead.
"""
if created:
changes = mod... | [
"def",
"action_log_create",
"(",
"sender",
",",
"instance",
",",
"created",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"created",
":",
"changes",
"=",
"model_instance_diff",
"(",
"None",
",",
"instance",
")",
"log_entry",
"=",
"LogAction",
".",
"objects",
".... | 36.857143 | 23 |
def moving_hfs_rank(h, size, start=0, stop=None):
"""Helper function for plotting haplotype frequencies in moving windows.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
size : int
The window size (number of variants).
start : int, o... | [
"def",
"moving_hfs_rank",
"(",
"h",
",",
"size",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"None",
")",
":",
"# determine windows",
"windows",
"=",
"np",
".",
"asarray",
"(",
"list",
"(",
"index_windows",
"(",
"h",
",",
"size",
"=",
"size",
",",
"sta... | 25.755102 | 21.122449 |
def cssselect(self, expr, translator='html'):
"""
Run the CSS expression on this element and its children,
returning a list of the results.
Equivalent to lxml.cssselect.CSSSelect(expr, translator='html')(self)
-- note that pre-compiling the expression can provide a substantial
... | [
"def",
"cssselect",
"(",
"self",
",",
"expr",
",",
"translator",
"=",
"'html'",
")",
":",
"# Do the import here to make the dependency optional.",
"from",
"lxml",
".",
"cssselect",
"import",
"CSSSelector",
"return",
"CSSSelector",
"(",
"expr",
",",
"translator",
"="... | 42.25 | 17.75 |
def setup_regex(self):
"""Sets up the patterns and compiled regex objects for parsing types."""
#Regex for matching the entire body of the type and getting top-level modifiers.
self._RX_TYPE = r"\n\s*type(?P<modifiers>,\s+(public|private))?(\s*::)?\s+(?P<name>[A-Za-z0-9_]+)" + \
... | [
"def",
"setup_regex",
"(",
"self",
")",
":",
"#Regex for matching the entire body of the type and getting top-level modifiers.",
"self",
".",
"_RX_TYPE",
"=",
"r\"\\n\\s*type(?P<modifiers>,\\s+(public|private))?(\\s*::)?\\s+(?P<name>[A-Za-z0-9_]+)\"",
"+",
"r\"(?P<contents>.+?)end\\s*type(... | 65.45 | 29.25 |
def check_failed_login(self):
"""
'Private method', check failed logins, it's used for wath_login decorator
"""
last_attempt = self.get_last_failed_access_attempt()
if not last_attempt:
# create a new entry
user_access = self._FailedAccessAttemptModel(ip_... | [
"def",
"check_failed_login",
"(",
"self",
")",
":",
"last_attempt",
"=",
"self",
".",
"get_last_failed_access_attempt",
"(",
")",
"if",
"not",
"last_attempt",
":",
"# create a new entry",
"user_access",
"=",
"self",
".",
"_FailedAccessAttemptModel",
"(",
"ip_address",... | 38.27027 | 22.486486 |
def junos_facts(**kwargs):
'''
.. versionadded:: 2019.2.0
The complete list of Junos facts collected by ``junos-eznc``.
CLI Example:
.. code-block:: bash
salt '*' napalm.junos_facts
'''
prep = _junos_prep_fun(napalm_device) # pylint: disable=undefined-variable
if not prep['r... | [
"def",
"junos_facts",
"(",
"*",
"*",
"kwargs",
")",
":",
"prep",
"=",
"_junos_prep_fun",
"(",
"napalm_device",
")",
"# pylint: disable=undefined-variable",
"if",
"not",
"prep",
"[",
"'result'",
"]",
":",
"return",
"prep",
"facts",
"=",
"dict",
"(",
"napalm_dev... | 31.307692 | 20.846154 |
def biopax_process_pc_pathsbetween():
"""Process PathwayCommons paths between genes, return INDRA Statements."""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
genes = body.get('genes')
bp = biopax.process_pc_pathsbetw... | [
"def",
"biopax_process_pc_pathsbetween",
"(",
")",
":",
"if",
"request",
".",
"method",
"==",
"'OPTIONS'",
":",
"return",
"{",
"}",
"response",
"=",
"request",
".",
"body",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"body",
"=",
"json",
... | 39.333333 | 8.444444 |
def _is_under_root(self, full_path):
"""Guard against arbitrary file retrieval."""
if (path.abspath(full_path) + path.sep)\
.startswith(path.abspath(self.root) + path.sep):
return True
else:
return False | [
"def",
"_is_under_root",
"(",
"self",
",",
"full_path",
")",
":",
"if",
"(",
"path",
".",
"abspath",
"(",
"full_path",
")",
"+",
"path",
".",
"sep",
")",
".",
"startswith",
"(",
"path",
".",
"abspath",
"(",
"self",
".",
"root",
")",
"+",
"path",
".... | 37.285714 | 13.714286 |
def _delay(self, ms):
"""Implement default delay mechanism.
"""
if ms:
self.Delay(ms)
else:
if self.default_delay:
self.Delay(self.default_delay) | [
"def",
"_delay",
"(",
"self",
",",
"ms",
")",
":",
"if",
"ms",
":",
"self",
".",
"Delay",
"(",
"ms",
")",
"else",
":",
"if",
"self",
".",
"default_delay",
":",
"self",
".",
"Delay",
"(",
"self",
".",
"default_delay",
")"
] | 26.25 | 12.25 |
def GateBranches(x, **unused_kwargs):
"""Implements a gating function on a (memory, gate, candidate) tuple.
Final update is memory * gate + (1-gate) * candidate
This gating equation may also be referred to as Highway Network.
Highway Networks: https://arxiv.org/abs/1505.00387
Args:
x: A tuple of (memor... | [
"def",
"GateBranches",
"(",
"x",
",",
"*",
"*",
"unused_kwargs",
")",
":",
"assert",
"len",
"(",
"x",
")",
"==",
"3",
",",
"x",
"state",
",",
"gate",
",",
"candidate",
"=",
"x",
"return",
"gate",
"*",
"state",
"+",
"(",
"1.0",
"-",
"gate",
")",
... | 28.117647 | 19.058824 |
def _get_sorted_inputs(filename, delimiter="\n"):
"""Returning inputs sorted according to decreasing length.
This causes inputs of similar lengths to be processed in the same batch,
facilitating early stopping for short sequences.
Longer sequences are sorted first so that if you're going to get OOMs,
you'll... | [
"def",
"_get_sorted_inputs",
"(",
"filename",
",",
"delimiter",
"=",
"\"\\n\"",
")",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"Getting sorted inputs\"",
")",
"with",
"tf",
".",
"gfile",
".",
"Open",
"(",
"filename",
")",
"as",
"f",
":",
"text",
"="... | 33.911765 | 19.117647 |
def _handle_error_response(response_body):
""""Translates an error response into an exception.
Args:
response_body (str): The decoded response data.
Raises:
google.auth.exceptions.RefreshError
"""
try:
error_data = json.loads(response_body)
error_details = '{}: {}'.... | [
"def",
"_handle_error_response",
"(",
"response_body",
")",
":",
"try",
":",
"error_data",
"=",
"json",
".",
"loads",
"(",
"response_body",
")",
"error_details",
"=",
"'{}: {}'",
".",
"format",
"(",
"error_data",
"[",
"'error'",
"]",
",",
"error_data",
".",
... | 30 | 14.7 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'concepts') and self.concepts is not None:
_dict['concepts'] = self.concepts._to_dict()
if hasattr(self, 'emotion') and self.emotion is not None:
_dict['emotion... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'concepts'",
")",
"and",
"self",
".",
"concepts",
"is",
"not",
"None",
":",
"_dict",
"[",
"'concepts'",
"]",
"=",
"self",
".",
"concepts",
".",
"_... | 57.416667 | 21.708333 |
def remove_item(name, system_wide=False):
'''Removes a program from startup.
Removes a program from startup.
Args:
name (str) : The name of the program (as known to the system) to remove. See :func:``list_items``.
system_wide (bool): Remove it from system-wide startup.
Note:
``system_wide`` require... | [
"def",
"remove_item",
"(",
"name",
",",
"system_wide",
"=",
"False",
")",
":",
"desktop_env",
"=",
"system",
".",
"get_name",
"(",
")",
"if",
"desktop_env",
"==",
"'windows'",
":",
"import",
"winreg",
"if",
"system_wide",
":",
"startup_dir",
"=",
"os",
"."... | 28.597222 | 27.569444 |
def command_line_arguments(command_line_parameters):
"""Defines the command line parameters that are accepted."""
# create parser
parser = argparse.ArgumentParser(description='Execute baseline algorithms with default parameters', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# add parameters
# - t... | [
"def",
"command_line_arguments",
"(",
"command_line_parameters",
")",
":",
"# create parser",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Execute baseline algorithms with default parameters'",
",",
"formatter_class",
"=",
"argparse",
".",
"A... | 63.390244 | 47.829268 |
def check_directory_paths(self, *args):
"""
Ensure all arguments correspond to directories
"""
for path in enumerate(args):
path = path[1]
if path is not None:
try:
self.check_directory_path(path)
except OSError ... | [
"def",
"check_directory_paths",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"path",
"in",
"enumerate",
"(",
"args",
")",
":",
"path",
"=",
"path",
"[",
"1",
"]",
"if",
"path",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"check_directory_pa... | 30.461538 | 8.923077 |
def reschedule(self, date, callable_name=None, content_object=None,
expires='7d', args=None, kwargs=None):
"""Schedule a clone of this job."""
# Resolve date relative to the expected start of the current job.
if isinstance(date, basestring):
date = parse_timedelta(... | [
"def",
"reschedule",
"(",
"self",
",",
"date",
",",
"callable_name",
"=",
"None",
",",
"content_object",
"=",
"None",
",",
"expires",
"=",
"'7d'",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"# Resolve date relative to the expected start of... | 44.6 | 13.55 |
def _filter_list_to_conjunction_expression(filter_list):
"""Convert a list of filters to an Expression that is the conjunction of all of them."""
if not isinstance(filter_list, list):
raise AssertionError(u'Expected `list`, Received: {}.'.format(filter_list))
if any((not isinstance(filter_block, Fil... | [
"def",
"_filter_list_to_conjunction_expression",
"(",
"filter_list",
")",
":",
"if",
"not",
"isinstance",
"(",
"filter_list",
",",
"list",
")",
":",
"raise",
"AssertionError",
"(",
"u'Expected `list`, Received: {}.'",
".",
"format",
"(",
"filter_list",
")",
")",
"if... | 65.444444 | 28.555556 |
def query(self, query_type, query=None):
"""Run the given query on the connection (POST request to /query)"""
return self.handleresult(self.r.post(urljoin(self.url + "query/",
query_type),
data=json.dumps(q... | [
"def",
"query",
"(",
"self",
",",
"query_type",
",",
"query",
"=",
"None",
")",
":",
"return",
"self",
".",
"handleresult",
"(",
"self",
".",
"r",
".",
"post",
"(",
"urljoin",
"(",
"self",
".",
"url",
"+",
"\"query/\"",
",",
"query_type",
")",
",",
... | 66 | 18.8 |
def load_neuron(handle, reader=None):
'''Build section trees from an h5 or swc file'''
rdw = load_data(handle, reader)
if isinstance(handle, StringType):
name = os.path.splitext(os.path.basename(handle))[0]
else:
name = None
return FstNeuron(rdw, name) | [
"def",
"load_neuron",
"(",
"handle",
",",
"reader",
"=",
"None",
")",
":",
"rdw",
"=",
"load_data",
"(",
"handle",
",",
"reader",
")",
"if",
"isinstance",
"(",
"handle",
",",
"StringType",
")",
":",
"name",
"=",
"os",
".",
"path",
".",
"splitext",
"(... | 35.125 | 12.875 |
def select(self, db):
"""Change the selected database for the current connection."""
if not isinstance(db, int):
raise TypeError("DB must be of int type, not {!r}".format(db))
if db < 0:
raise ValueError("DB must be greater or equal 0, got {!r}"
... | [
"def",
"select",
"(",
"self",
",",
"db",
")",
":",
"if",
"not",
"isinstance",
"(",
"db",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"DB must be of int type, not {!r}\"",
".",
"format",
"(",
"db",
")",
")",
"if",
"db",
"<",
"0",
":",
"raise",
... | 44 | 13.777778 |
def devserver_cmd(argv=sys.argv[1:]): # pragma: no cover
"""\
Serve the web API for development.
Usage:
pld-devserver [options]
Options:
-h --help Show this screen.
--host=<host> The host to use [default: 0.0.0.0].
--port=<port> The port to use [default: 5000].
--de... | [
"def",
"devserver_cmd",
"(",
"argv",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
")",
":",
"# pragma: no cover",
"arguments",
"=",
"docopt",
"(",
"devserver_cmd",
".",
"__doc__",
",",
"argv",
"=",
"argv",
")",
"initialize_config",
"(",
")",
"app",
".",
... | 25.478261 | 20.826087 |
def _Open(self, path_spec, mode='rb'):
"""Opens the file system defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the APFS volume could n... | [
"def",
"_Open",
"(",
"self",
",",
"path_spec",
",",
"mode",
"=",
"'rb'",
")",
":",
"if",
"not",
"path_spec",
".",
"HasParent",
"(",
")",
":",
"raise",
"errors",
".",
"PathSpecError",
"(",
"'Unsupported path specification without parent.'",
")",
"if",
"path_spe... | 36.261905 | 21.166667 |
def get_cell_type(cell):
'''
Returns a type to be used in table cell analysis. This is either
'basestring' or '(int, float)'.
'''
cell_type = None
if isinstance(cell, basestring) and cell:
cell_type = basestring
elif isinstance(cell, (int, float)):
cell_type = (int, float)
... | [
"def",
"get_cell_type",
"(",
"cell",
")",
":",
"cell_type",
"=",
"None",
"if",
"isinstance",
"(",
"cell",
",",
"basestring",
")",
"and",
"cell",
":",
"cell_type",
"=",
"basestring",
"elif",
"isinstance",
"(",
"cell",
",",
"(",
"int",
",",
"float",
")",
... | 27.333333 | 18.166667 |
def scale_means(self, hs_dims=None, prune=False):
"""Get cube means."""
slices_means = [ScaleMeans(slice_).data for slice_ in self.slices]
if hs_dims and self.ndim > 1:
# Intersperse scale means with nans if H&S specified, and 2D. No
# need to modify 1D, as only one mean... | [
"def",
"scale_means",
"(",
"self",
",",
"hs_dims",
"=",
"None",
",",
"prune",
"=",
"False",
")",
":",
"slices_means",
"=",
"[",
"ScaleMeans",
"(",
"slice_",
")",
".",
"data",
"for",
"slice_",
"in",
"self",
".",
"slices",
"]",
"if",
"hs_dims",
"and",
... | 53.384615 | 23 |
def forward(self, inputs, token_types, valid_length=None): # pylint: disable=arguments-differ
"""Generate the unnormalized score for the given the input sequences.
Parameters
----------
inputs : NDArray, shape (batch_size, seq_length)
Input words for the sequences.
... | [
"def",
"forward",
"(",
"self",
",",
"inputs",
",",
"token_types",
",",
"valid_length",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"bert_output",
"=",
"self",
".",
"bert",
"(",
"inputs",
",",
"token_types",
",",
"valid_length",
")",
"output",
... | 42.380952 | 21.809524 |
def encrypt_binary(self, binary, *args, **kwargs):
"""
input: bytes, output: bytes
"""
return self.encrypt(binary, *args, **kwargs) | [
"def",
"encrypt_binary",
"(",
"self",
",",
"binary",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"encrypt",
"(",
"binary",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 31.8 | 5.4 |
def get_alerts_for(self, trigger):
"""
Retrieves all of the alerts that were fired for the specified Trigger
:param trigger: the trigger
:type trigger: `pyowm.alertapi30.trigger.Trigger`
:return: list of `pyowm.alertapi30.alert.Alert` objects
"""
assert trigger is... | [
"def",
"get_alerts_for",
"(",
"self",
",",
"trigger",
")",
":",
"assert",
"trigger",
"is",
"not",
"None",
"assert",
"isinstance",
"(",
"trigger",
".",
"id",
",",
"str",
")",
",",
"\"Value must be a string\"",
"status",
",",
"data",
"=",
"self",
".",
"http_... | 45.928571 | 13.071429 |
def QA_SU_save_index_day(client=DATABASE, ui_log=None, ui_progress=None):
"""save index_day
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
__index_list = QA_fetch_get_stock_list('index')
coll = client.index_day
coll.create_index(
[('code',
... | [
"def",
"QA_SU_save_index_day",
"(",
"client",
"=",
"DATABASE",
",",
"ui_log",
"=",
"None",
",",
"ui_progress",
"=",
"None",
")",
":",
"__index_list",
"=",
"QA_fetch_get_stock_list",
"(",
"'index'",
")",
"coll",
"=",
"client",
".",
"index_day",
"coll",
".",
"... | 34.889908 | 15.091743 |
def get_programs(self):
"""
Get a Pyquil Program corresponding to each term in the PauliSum and a coefficient
for each program
:return: (programs, coefficients)
"""
programs = [term.program for term in self.terms]
coefficients = np.array([term.coefficient for ter... | [
"def",
"get_programs",
"(",
"self",
")",
":",
"programs",
"=",
"[",
"term",
".",
"program",
"for",
"term",
"in",
"self",
".",
"terms",
"]",
"coefficients",
"=",
"np",
".",
"array",
"(",
"[",
"term",
".",
"coefficient",
"for",
"term",
"in",
"self",
".... | 36.6 | 17.6 |
def add_hook(self, sequence, h):
"""Create a tree.Hook"""
sequence.parser_tree = parsing.Hook(h.name, h.listparam)
return True | [
"def",
"add_hook",
"(",
"self",
",",
"sequence",
",",
"h",
")",
":",
"sequence",
".",
"parser_tree",
"=",
"parsing",
".",
"Hook",
"(",
"h",
".",
"name",
",",
"h",
".",
"listparam",
")",
"return",
"True"
] | 33.75 | 13.25 |
def dumps(self):
"""
Dump this instance as YAML.
"""
with closing(StringIO()) as fileobj:
self.dump(fileobj)
return fileobj.getvalue() | [
"def",
"dumps",
"(",
"self",
")",
":",
"with",
"closing",
"(",
"StringIO",
"(",
")",
")",
"as",
"fileobj",
":",
"self",
".",
"dump",
"(",
"fileobj",
")",
"return",
"fileobj",
".",
"getvalue",
"(",
")"
] | 23 | 10.75 |
def _GetChromeWebStorePage(self, extension_identifier):
"""Retrieves the page for the extension from the Chrome store website.
Args:
extension_identifier (str): Chrome extension identifier.
Returns:
str: page content or None.
"""
web_store_url = self._WEB_STORE_URL.format(xid=extension... | [
"def",
"_GetChromeWebStorePage",
"(",
"self",
",",
"extension_identifier",
")",
":",
"web_store_url",
"=",
"self",
".",
"_WEB_STORE_URL",
".",
"format",
"(",
"xid",
"=",
"extension_identifier",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"we... | 31.8 | 23.35 |
def anophelesParams(self):
"""
:rtype: AnophelesParams
"""
list_of_anopheles = []
for anophelesParams in self.itn.findall("anophelesParams"):
list_of_anopheles.append(AnophelesParams(anophelesParams))
return list_of_anopheles | [
"def",
"anophelesParams",
"(",
"self",
")",
":",
"list_of_anopheles",
"=",
"[",
"]",
"for",
"anophelesParams",
"in",
"self",
".",
"itn",
".",
"findall",
"(",
"\"anophelesParams\"",
")",
":",
"list_of_anopheles",
".",
"append",
"(",
"AnophelesParams",
"(",
"ano... | 34.75 | 12.25 |
def from_yaml(cls, path):
"""Return an instance from a YAML file."""
import yaml
with path.open(mode='r') as fp:
self = cls.from_cwl(yaml.safe_load(fp), __reference__=path)
return self | [
"def",
"from_yaml",
"(",
"cls",
",",
"path",
")",
":",
"import",
"yaml",
"with",
"path",
".",
"open",
"(",
"mode",
"=",
"'r'",
")",
"as",
"fp",
":",
"self",
"=",
"cls",
".",
"from_cwl",
"(",
"yaml",
".",
"safe_load",
"(",
"fp",
")",
",",
"__refer... | 27.875 | 21.125 |
def return_opml_response(self, context, **response_kwargs):
'''
Returns export data as an opml file.
'''
self.template_name = 'fiction_outlines/outline.opml'
response = super().render_to_response(context, content_type='text/xml', **response_kwargs)
response['Content-Dispo... | [
"def",
"return_opml_response",
"(",
"self",
",",
"context",
",",
"*",
"*",
"response_kwargs",
")",
":",
"self",
".",
"template_name",
"=",
"'fiction_outlines/outline.opml'",
"response",
"=",
"super",
"(",
")",
".",
"render_to_response",
"(",
"context",
",",
"con... | 51.875 | 30.625 |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Transport(key)
if key not in Transport._member_map_:
extend_enum(Transport, key, default)
return Transport[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"Transport",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"Transport",
".",
"_member_map_",
":",
"extend_enum",
"(",
"T... | 37.428571 | 7.714286 |
def update(self, *args, **kwargs):
"""Update the values of several attributes in a single operation."""
self._write_op(self._update_nosync, *args, **kwargs) | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_write_op",
"(",
"self",
".",
"_update_nosync",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 56.666667 | 8.666667 |
def get_group_category(self, category):
"""
Get a single group category.
:calls: `GET /api/v1/group_categories/:group_category_id \
<https://canvas.instructure.com/doc/api/group_categories.html#method.group_categories.show>`_
:param category: The object or ID of the category.
... | [
"def",
"get_group_category",
"(",
"self",
",",
"category",
")",
":",
"category_id",
"=",
"obj_or_id",
"(",
"category",
",",
"\"category\"",
",",
"(",
"GroupCategory",
",",
")",
")",
"response",
"=",
"self",
".",
"__requester",
".",
"request",
"(",
"'GET'",
... | 37 | 23 |
def XMPP_display(self,*arg):
""" For XMPP Demo
輸出到 XMPP 之樣式。
"""
MA = ''
for i in arg:
MAs = '- MA%02s: %.2f %s(%s)\n' % (
unicode(i),
self.MA(i),
self.MAC(i),
unicode(self.MA_serial(i)[0])
)
MA = MA + MAs
vol = '- Volume: %s %s(%s)' % (
... | [
"def",
"XMPP_display",
"(",
"self",
",",
"*",
"arg",
")",
":",
"MA",
"=",
"''",
"for",
"i",
"in",
"arg",
":",
"MAs",
"=",
"'- MA%02s: %.2f %s(%s)\\n'",
"%",
"(",
"unicode",
"(",
"i",
")",
",",
"self",
".",
"MA",
"(",
"i",
")",
",",
"self",
".",
... | 25.255814 | 16.790698 |
def split_molecule_subgraphs(self, bonds, allow_reverse=False,
alterations=None):
"""
Split MoleculeGraph into two or more MoleculeGraphs by
breaking a set of bonds. This function uses
MoleculeGraph.break_edge repeatedly to create
disjoint graphs ... | [
"def",
"split_molecule_subgraphs",
"(",
"self",
",",
"bonds",
",",
"allow_reverse",
"=",
"False",
",",
"alterations",
"=",
"None",
")",
":",
"self",
".",
"set_node_attributes",
"(",
")",
"original",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"for",
"b... | 43.576577 | 21.954955 |
def r_bergomi(H,T,eta,xi,rho,S0,r,N,M,dW=None,dW_orth=None,cholesky = False,return_v=False):
'''
Return M Euler-Maruyama sample paths with N time steps of (S_t,v_t), where
(S_t,v_t) follows the rBergomi model of mathematical finance
:rtype: M x N x d array
'''
times = np.linspace(0, T, N)
... | [
"def",
"r_bergomi",
"(",
"H",
",",
"T",
",",
"eta",
",",
"xi",
",",
"rho",
",",
"S0",
",",
"r",
",",
"N",
",",
"M",
",",
"dW",
"=",
"None",
",",
"dW_orth",
"=",
"None",
",",
"cholesky",
"=",
"False",
",",
"return_v",
"=",
"False",
")",
":",
... | 40.909091 | 25.181818 |
def call_command(name, *args, **options):
"""
Calls the given command, with the given options and args/kwargs.
This is the primary API you should use for calling specific commands.
Some examples:
call_command('syncdb')
call_command('shell', plain=True)
call_command('sqlall', 'm... | [
"def",
"call_command",
"(",
"name",
",",
"*",
"args",
",",
"*",
"*",
"options",
")",
":",
"# Load the command object.",
"try",
":",
"app_name",
"=",
"get_commands",
"(",
")",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"CommandError",
"(",
"\"Unk... | 32.735294 | 17.735294 |
def remove_ephemeral_listener(self, uid):
"""Remove ephemeral listener with given uid."""
self.ephemeral_listeners[:] = (listener for listener in self.ephemeral_listeners
if listener['uid'] != uid) | [
"def",
"remove_ephemeral_listener",
"(",
"self",
",",
"uid",
")",
":",
"self",
".",
"ephemeral_listeners",
"[",
":",
"]",
"=",
"(",
"listener",
"for",
"listener",
"in",
"self",
".",
"ephemeral_listeners",
"if",
"listener",
"[",
"'uid'",
"]",
"!=",
"uid",
"... | 62.25 | 18.5 |
def regularize_array(A):
"""
Takes an np.ndarray as an input.
- If the array is one-dimensional, it's assumed to be an array of input values.
- If the array is more than one-dimensional, its last index is assumed to curse
over spatial dimension.
Either way, the return value is at least tw... | [
"def",
"regularize_array",
"(",
"A",
")",
":",
"if",
"not",
"isinstance",
"(",
"A",
",",
"np",
".",
"ndarray",
")",
":",
"A",
"=",
"np",
".",
"array",
"(",
"A",
",",
"dtype",
"=",
"float",
")",
"else",
":",
"A",
"=",
"np",
".",
"asarray",
"(",
... | 24 | 23.185185 |
def get_perm_name(cls, resource, method):
""" Compose permission name
@param resource the resource
@param method the request method (case doesn't matter).
"""
return '%s_%s_%s' % (
cls.PREFIX,
cls._get_resource_name(resource),
method.lower()) | [
"def",
"get_perm_name",
"(",
"cls",
",",
"resource",
",",
"method",
")",
":",
"return",
"'%s_%s_%s'",
"%",
"(",
"cls",
".",
"PREFIX",
",",
"cls",
".",
"_get_resource_name",
"(",
"resource",
")",
",",
"method",
".",
"lower",
"(",
")",
")"
] | 28.181818 | 14 |
def update(self, message):
"""
Update zone statuses based on the current message.
:param message: message to use to update the zone tracking
:type message: :py:class:`~alarmdecoder.messages.Message` or :py:class:`~alarmdecoder.messages.ExpanderMessage`
"""
if isinstance(... | [
"def",
"update",
"(",
"self",
",",
"message",
")",
":",
"if",
"isinstance",
"(",
"message",
",",
"ExpanderMessage",
")",
":",
"zone",
"=",
"-",
"1",
"if",
"message",
".",
"type",
"==",
"ExpanderMessage",
".",
"ZONE",
":",
"zone",
"=",
"self",
".",
"e... | 40.777778 | 22.703704 |
def _apply_user_agent(headers, user_agent):
"""Adds a user-agent to the headers.
Args:
headers: dict, request headers to add / modify user
agent within.
user_agent: str, the user agent to add.
Returns:
dict, the original headers passed in, but modified if the
... | [
"def",
"_apply_user_agent",
"(",
"headers",
",",
"user_agent",
")",
":",
"if",
"user_agent",
"is",
"not",
"None",
":",
"if",
"'user-agent'",
"in",
"headers",
":",
"headers",
"[",
"'user-agent'",
"]",
"=",
"(",
"user_agent",
"+",
"' '",
"+",
"headers",
"[",... | 29.631579 | 18.947368 |
def press_button(self, value):
"""
Click the button with the given label.
"""
button = find_button(world.browser, value)
if not button:
raise AssertionError(
"Cannot find a button named '{}'.".format(value))
button.click() | [
"def",
"press_button",
"(",
"self",
",",
"value",
")",
":",
"button",
"=",
"find_button",
"(",
"world",
".",
"browser",
",",
"value",
")",
"if",
"not",
"button",
":",
"raise",
"AssertionError",
"(",
"\"Cannot find a button named '{}'.\"",
".",
"format",
"(",
... | 28.666667 | 10.444444 |
def open_bag(dir_bag):
"""
Open Bag at the given path
:param str dir_bag: Path to Bag
:return obj: Bag
"""
logger_bagit.info("enter open_bag")
try:
bag = bagit.Bag(dir_bag)
logger_bagit.info("opened bag")
return bag
except Exception as e:
print("Error: fai... | [
"def",
"open_bag",
"(",
"dir_bag",
")",
":",
"logger_bagit",
".",
"info",
"(",
"\"enter open_bag\"",
")",
"try",
":",
"bag",
"=",
"bagit",
".",
"Bag",
"(",
"dir_bag",
")",
"logger_bagit",
".",
"info",
"(",
"\"opened bag\"",
")",
"return",
"bag",
"except",
... | 27.2 | 12.4 |
def write(self):
'''Write the job to the corresponding plist.'''
with open(self.me, 'w') as f:
f.write(self.printMe(self.tag, self.value)) | [
"def",
"write",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"me",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"printMe",
"(",
"self",
".",
"tag",
",",
"self",
".",
"value",
")",
")"
] | 40.75 | 14.25 |
def set_font(self, family,style='',size=0):
"Select a font; size given in points"
family=family.lower()
if(family==''):
family=self.font_family
if(family=='arial'):
family='helvetica'
elif(family=='symbol' or family=='zapfdingbats'):
style=''
... | [
"def",
"set_font",
"(",
"self",
",",
"family",
",",
"style",
"=",
"''",
",",
"size",
"=",
"0",
")",
":",
"family",
"=",
"family",
".",
"lower",
"(",
")",
"if",
"(",
"family",
"==",
"''",
")",
":",
"family",
"=",
"self",
".",
"font_family",
"if",
... | 41.875 | 16.75 |
def export(self, version, export_dir):
"""
Create prov entities and activities.
"""
atts = [
(PROV['type'], self.type),
]
atts += [
(PROV['label'], self.label)
]
if self.extent_rsl is not None:
atts += [
... | [
"def",
"export",
"(",
"self",
",",
"version",
",",
"export_dir",
")",
":",
"atts",
"=",
"[",
"(",
"PROV",
"[",
"'type'",
"]",
",",
"self",
".",
"type",
")",
",",
"]",
"atts",
"+=",
"[",
"(",
"PROV",
"[",
"'label'",
"]",
",",
"self",
".",
"label... | 27.977273 | 18.931818 |
def serialize(self, pid, record, links_factory=None, **kwargs):
"""Serialize a single record.
:param pid: Persistent identifier instance.
:param record: Record instance.
:param links_factory: Factory function for record links.
"""
data = self.serializer.serialize(pid, re... | [
"def",
"serialize",
"(",
"self",
",",
"pid",
",",
"record",
",",
"links_factory",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"serializer",
".",
"serialize",
"(",
"pid",
",",
"record",
",",
"links_factory",
")",
"source",
... | 45.066667 | 19.466667 |
def list_chunks(l, n):
"""
Return a list of chunks
:param l: List
:param n: int The number of items per chunk
:return: List
"""
if n < 1:
n = 1
return [l[i:i + n] for i in range(0, len(l), n)] | [
"def",
"list_chunks",
"(",
"l",
",",
"n",
")",
":",
"if",
"n",
"<",
"1",
":",
"n",
"=",
"1",
"return",
"[",
"l",
"[",
"i",
":",
"i",
"+",
"n",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"l",
")",
",",
"n",
")",
"]"
] | 22.3 | 14.9 |
def write_gtiff_file(f_name, n_rows, n_cols, data, geotransform, srs, nodata_value,
gdal_type=GDT_Float32):
"""Output Raster to GeoTiff format file.
Args:
f_name: output gtiff file name.
n_rows: Row count.
n_cols: Col count.
data:... | [
"def",
"write_gtiff_file",
"(",
"f_name",
",",
"n_rows",
",",
"n_cols",
",",
"data",
",",
"geotransform",
",",
"srs",
",",
"nodata_value",
",",
"gdal_type",
"=",
"GDT_Float32",
")",
":",
"UtilClass",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"dirname",
... | 45.235294 | 19.029412 |
def delete(self, photo_id, album_id=0):
"""Delete a photo from the logged in users account.
:param photo_id: The okcupid id of the photo to delete.
:param album_id: The album from which to delete the photo.
"""
if isinstance(photo_id, Info):
photo_id = photo_id.id
... | [
"def",
"delete",
"(",
"self",
",",
"photo_id",
",",
"album_id",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"photo_id",
",",
"Info",
")",
":",
"photo_id",
"=",
"photo_id",
".",
"id",
"return",
"self",
".",
"_session",
".",
"okc_post",
"(",
"'photouplo... | 36.857143 | 12.142857 |
def Grieves_Thodos(zs, Tcs, Aijs):
r'''Calculates critical temperature of a mixture according to
mixing rules in [1]_.
.. math::
T_{cm} = \sum_{i} \frac{T_{ci}}{1 + (1/x_i)\sum_j A_{ij} x_j}
For a binary mxiture, this simplifies to:
.. math::
T_{cm} = \frac{T_{c1}}{1 + (x_2/x_1)A_... | [
"def",
"Grieves_Thodos",
"(",
"zs",
",",
"Tcs",
",",
"Aijs",
")",
":",
"if",
"not",
"none_and_length_check",
"(",
"[",
"zs",
",",
"Tcs",
"]",
")",
":",
"raise",
"Exception",
"(",
"'Function inputs are incorrect format'",
")",
"Tcm",
"=",
"0",
"for",
"i",
... | 33.418182 | 26.909091 |
def run( self ):
"""
Interact with the blockchain peer,
until we get a socket error or we
exit the loop explicitly.
Return True on success
Raise on error
"""
self.handshake()
try:
self.loop()
except socket.error, se:
... | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"handshake",
"(",
")",
"try",
":",
"self",
".",
"loop",
"(",
")",
"except",
"socket",
".",
"error",
",",
"se",
":",
"if",
"self",
".",
"finished",
":",
"return",
"True",
"else",
":",
"raise"
] | 21.722222 | 15.388889 |
def make_niche_grid(res_dict, world_size=(60, 60)):
"""
Converts dictionary specifying where resources are to nested lists
specifying what sets of resources are where.
res_dict - a dictionary in which keys are resources in the environment
and values are list of tuples representing the cells they're... | [
"def",
"make_niche_grid",
"(",
"res_dict",
",",
"world_size",
"=",
"(",
"60",
",",
"60",
")",
")",
":",
"# Initialize array to represent world",
"world",
"=",
"initialize_grid",
"(",
"world_size",
",",
"set",
"(",
")",
")",
"# Fill in data on niches present in each ... | 35.291667 | 21.875 |
def disassemble_string(self, lpAddress, code):
"""
Disassemble instructions from a block of binary code.
@type lpAddress: int
@param lpAddress: Memory address where the code was read from.
@type code: str
@param code: Binary code to disassemble.
@rtype: list... | [
"def",
"disassemble_string",
"(",
"self",
",",
"lpAddress",
",",
"code",
")",
":",
"aProcess",
"=",
"self",
".",
"get_process",
"(",
")",
"return",
"aProcess",
".",
"disassemble_string",
"(",
"lpAddress",
",",
"code",
")"
] | 36.75 | 16.15 |
def nicename(name):
'''Make ``name`` a more user friendly string.
Capitalise the first letter and replace dash and underscores with a space
'''
name = to_string(name)
return capfirst(' '.join(name.replace('-', ' ').replace('_', ' ').split())) | [
"def",
"nicename",
"(",
"name",
")",
":",
"name",
"=",
"to_string",
"(",
"name",
")",
"return",
"capfirst",
"(",
"' '",
".",
"join",
"(",
"name",
".",
"replace",
"(",
"'-'",
",",
"' '",
")",
".",
"replace",
"(",
"'_'",
",",
"' '",
")",
".",
"spli... | 36.714286 | 27.571429 |
def do_track(self, arg):
"""
track expression
Display a graph showing which objects are referred by the
value of the expression. This command requires pypy to be in
the current PYTHONPATH.
"""
try:
from rpython.translator.tool.reftracker import track... | [
"def",
"do_track",
"(",
"self",
",",
"arg",
")",
":",
"try",
":",
"from",
"rpython",
".",
"translator",
".",
"tool",
".",
"reftracker",
"import",
"track",
"except",
"ImportError",
":",
"print",
"(",
"'** cannot import pypy.translator.tool.reftracker **'",
",",
"... | 28.8 | 19.3 |
def percent_point(self, U):
"""Given a cdf value, returns a value in original space.
Args:
U(numpy.array): cdf values in [0,1]
Returns:
numpy.array: value in original space
"""
self.check_fit()
return scipy.optimize.brentq(self._brentq_cdf(U), -... | [
"def",
"percent_point",
"(",
"self",
",",
"U",
")",
":",
"self",
".",
"check_fit",
"(",
")",
"return",
"scipy",
".",
"optimize",
".",
"brentq",
"(",
"self",
".",
"_brentq_cdf",
"(",
"U",
")",
",",
"-",
"1000.0",
",",
"1000.0",
")"
] | 27 | 20.75 |
def add_hba_entry(self, *, type='host', database, user, address=None,
auth_method, auth_options=None):
"""Add a record to pg_hba.conf."""
status = self.get_status()
if status == 'not-initialized':
raise ClusterError(
'cannot modify HBA records: c... | [
"def",
"add_hba_entry",
"(",
"self",
",",
"*",
",",
"type",
"=",
"'host'",
",",
"database",
",",
"user",
",",
"address",
"=",
"None",
",",
"auth_method",
",",
"auth_options",
"=",
"None",
")",
":",
"status",
"=",
"self",
".",
"get_status",
"(",
")",
... | 35.676471 | 19.558824 |
def closeGlyphsOverGSUB(gsub, glyphs):
""" Use the FontTools subsetter to perform a closure over the GSUB table
given the initial `glyphs` (set of glyph names, str). Update the set
in-place adding all the glyph names that can be reached via GSUB
substitutions from this initial set.
"""
subsetter... | [
"def",
"closeGlyphsOverGSUB",
"(",
"gsub",
",",
"glyphs",
")",
":",
"subsetter",
"=",
"subset",
".",
"Subsetter",
"(",
")",
"subsetter",
".",
"glyphs",
"=",
"glyphs",
"gsub",
".",
"closure_glyphs",
"(",
"subsetter",
")"
] | 44.222222 | 9.444444 |
def rebase_array(d, recursive=False):
"""Transform an indexed dictionary (such as those returned by the dzn2dict
function when parsing arrays) into an multi-dimensional list.
Parameters
----------
d : dict
The indexed dictionary to convert.
bool : recursive
Whether to rebase the... | [
"def",
"rebase_array",
"(",
"d",
",",
"recursive",
"=",
"False",
")",
":",
"arr",
"=",
"[",
"]",
"min_val",
",",
"max_val",
"=",
"_extremes",
"(",
"d",
".",
"keys",
"(",
")",
")",
"for",
"idx",
"in",
"range",
"(",
"min_val",
",",
"max_val",
"+",
... | 25.75 | 17.791667 |
def check_misc(text):
"""Avoid mixing metaphors.
source: Garner's Modern American Usage
source_url: http://bit.ly/1T4alrY
"""
err = "mixed_metaphors.misc.misc"
msg = u"Mixed metaphor. Try '{}'."
preferences = [
["cream rises to the top", ["cream rises to the crop"]],
... | [
"def",
"check_misc",
"(",
"text",
")",
":",
"err",
"=",
"\"mixed_metaphors.misc.misc\"",
"msg",
"=",
"u\"Mixed metaphor. Try '{}'.\"",
"preferences",
"=",
"[",
"[",
"\"cream rises to the top\"",
",",
"[",
"\"cream rises to the crop\"",
"]",
"]",
",",
"[",
"\"fasten yo... | 33.526316 | 21.368421 |
def __add(self, val):
"""
Helper method for range addition. It is allowed to add only one compact subrange or ``range_t`` object at once.
Parameters
----------
val : int or tuple or list or range
Integer or range to add.
Returns
-------
__ha... | [
"def",
"__add",
"(",
"self",
",",
"val",
")",
":",
"if",
"not",
"isinstance",
"(",
"val",
",",
"range_t",
")",
":",
"#sanitize it",
"val",
"=",
"{",
"self",
".",
"__val_convert",
"(",
"val",
")",
"}",
"# convert to a set, coz I like it that way.",
"else",
... | 24.740741 | 24.444444 |
def extract(self, html, encoding=None, as_blocks=False):
"""
Extract the main content and/or comments from an HTML document and
return it as a string or as a sequence of block objects.
Args:
html (str): HTML document as a string.
encoding (str): Encoding of ``htm... | [
"def",
"extract",
"(",
"self",
",",
"html",
",",
"encoding",
"=",
"None",
",",
"as_blocks",
"=",
"False",
")",
":",
"preds",
",",
"blocks",
"=",
"self",
".",
"predict",
"(",
"html",
",",
"encoding",
"=",
"encoding",
",",
"return_blocks",
"=",
"True",
... | 44.857143 | 25.52381 |
def SelectArtifacts(cls,
os_name=None,
cpe=None,
labels=None,
restrict_checks=None):
"""Takes targeting info, identifies artifacts to fetch.
Args:
os_name: 0+ OS names.
cpe: 0+ CPE identifiers.
labels: 0+ ... | [
"def",
"SelectArtifacts",
"(",
"cls",
",",
"os_name",
"=",
"None",
",",
"cpe",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"restrict_checks",
"=",
"None",
")",
":",
"results",
"=",
"set",
"(",
")",
"for",
"condition",
"in",
"cls",
".",
"Conditions",
... | 32.208333 | 16.625 |
def tokenize(self, source, name=None, filename=None, state=None):
"""Calls tokeniter + tokenize and wraps it in a token stream.
"""
stream = self.tokeniter(source, name, filename, state)
return TokenStream(self.wrap(stream, name, filename), name, filename) | [
"def",
"tokenize",
"(",
"self",
",",
"source",
",",
"name",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"state",
"=",
"None",
")",
":",
"stream",
"=",
"self",
".",
"tokeniter",
"(",
"source",
",",
"name",
",",
"filename",
",",
"state",
")",
"re... | 56.8 | 16.8 |
def stop(self):
"""Stop listening."""
self.zeroconf.unregister_service(self.service_info)
self.zeroconf.close()
self.server.stop() | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"zeroconf",
".",
"unregister_service",
"(",
"self",
".",
"service_info",
")",
"self",
".",
"zeroconf",
".",
"close",
"(",
")",
"self",
".",
"server",
".",
"stop",
"(",
")"
] | 31.6 | 13.8 |
def from_shape(cls, shape):
"""Try to linearize a curve (or an already linearized curve).
Args:
shape (Union[SubdividedCurve, \
~bezier._geometric_intersection.Linearization]): A curve or an
already linearized curve.
Returns:
Union[Subdivided... | [
"def",
"from_shape",
"(",
"cls",
",",
"shape",
")",
":",
"# NOTE: In the below we replace ``isinstance(a, B)`` with",
"# ``a.__class__ is B``, which is a 3-3.5x speedup.",
"if",
"shape",
".",
"__class__",
"is",
"cls",
":",
"return",
"shape",
"else",
":",
"error",
"=... | 32.538462 | 17.538462 |
def register_actions(self, shortcut_manager):
"""Register callback methods for triggered actions
:param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings
between shortcuts and actions.
"""
shortcut_manager.add_callback_for... | [
"def",
"register_actions",
"(",
"self",
",",
"shortcut_manager",
")",
":",
"shortcut_manager",
".",
"add_callback_for_action",
"(",
"\"delete\"",
",",
"self",
".",
"remove_action_callback",
")",
"shortcut_manager",
".",
"add_callback_for_action",
"(",
"\"add\"",
",",
... | 62.727273 | 31 |
def add(self, item, position=5):
"""Add an item to the list unless it is already present.
If the item is an expression, then a semicolon will be appended to it
in the final compiled code.
"""
if item in self.items:
return
self.items[item] = position
... | [
"def",
"add",
"(",
"self",
",",
"item",
",",
"position",
"=",
"5",
")",
":",
"if",
"item",
"in",
"self",
".",
"items",
":",
"return",
"self",
".",
"items",
"[",
"item",
"]",
"=",
"position",
"self",
".",
"_add_dep",
"(",
"item",
")",
"self",
".",... | 33.416667 | 12.333333 |
def release():
"""
Release current version to pypi
"""
with settings(warn_only=True):
r = local(clom.git['diff-files']('--quiet', '--ignore-submodules', '--'))
if r.return_code != 0:
abort('There are uncommitted changes, commit or stash them before releasing')
version = open('... | [
"def",
"release",
"(",
")",
":",
"with",
"settings",
"(",
"warn_only",
"=",
"True",
")",
":",
"r",
"=",
"local",
"(",
"clom",
".",
"git",
"[",
"'diff-files'",
"]",
"(",
"'--quiet'",
",",
"'--ignore-submodules'",
",",
"'--'",
")",
")",
"if",
"r",
".",... | 34.166667 | 21.5 |
def loadFile(self, fileName, rtiClass=None,
position=None, parentIndex=QtCore.QModelIndex()):
""" Loads a file in the repository as a repo tree item of class rtiClass.
Autodetects the RTI type if rtiClass is None.
If position is None the child will be appended as the las... | [
"def",
"loadFile",
"(",
"self",
",",
"fileName",
",",
"rtiClass",
"=",
"None",
",",
"position",
"=",
"None",
",",
"parentIndex",
"=",
"QtCore",
".",
"QModelIndex",
"(",
")",
")",
":",
"logger",
".",
"info",
"(",
"\"Loading data from: {!r}\"",
".",
"format"... | 57.571429 | 22.285714 |
def read_release_version():
"""Read version information from VERSION file"""
try:
with open(VERSION_FILE, "r") as infile:
version = str(infile.read().strip())
if len(version) == 0:
version = None
return version
except IOError:
return None | [
"def",
"read_release_version",
"(",
")",
":",
"try",
":",
"with",
"open",
"(",
"VERSION_FILE",
",",
"\"r\"",
")",
"as",
"infile",
":",
"version",
"=",
"str",
"(",
"infile",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
")",
"if",
"len",
"(",
"vers... | 29.7 | 14.5 |
def is_managed(using=None):
"""
Checks whether the transaction manager is in manual or in auto state.
"""
if using is None:
managed = False
for using in tldap.backend.connections:
connection = tldap.backend.connections[using]
if connection.is_managed():
... | [
"def",
"is_managed",
"(",
"using",
"=",
"None",
")",
":",
"if",
"using",
"is",
"None",
":",
"managed",
"=",
"False",
"for",
"using",
"in",
"tldap",
".",
"backend",
".",
"connections",
":",
"connection",
"=",
"tldap",
".",
"backend",
".",
"connections",
... | 33.538462 | 11.538462 |
def json_files_serializer(objs, status=None):
"""JSON Files Serializer.
:parma objs: A list of:class:`invenio_files_rest.models.ObjectVersion`
instances.
:param status: A HTTP Status. (Default: ``None``)
:returns: A Flask response with JSON data.
:rtype: :py:class:`flask.Response`.
"""
... | [
"def",
"json_files_serializer",
"(",
"objs",
",",
"status",
"=",
"None",
")",
":",
"files",
"=",
"[",
"file_serializer",
"(",
"obj",
")",
"for",
"obj",
"in",
"objs",
"]",
"return",
"make_response",
"(",
"json",
".",
"dumps",
"(",
"files",
")",
",",
"st... | 37.454545 | 12.909091 |
def prop_or(default, key, dct_or_obj):
"""
Ramda propOr implementation. This also resolves object attributes, so key
can be a dict prop or an attribute of dct_or_obj
:param default: Value if dct_or_obj doesn't have key_or_prop or the resolved value is null
:param key:
:param dct_or_obj:
... | [
"def",
"prop_or",
"(",
"default",
",",
"key",
",",
"dct_or_obj",
")",
":",
"# Note that hasattr is a builtin and getattr is a ramda function, hence the different arg position",
"if",
"isinstance",
"(",
"dict",
",",
"dct_or_obj",
")",
":",
"value",
"=",
"dct_or_obj",
"[",
... | 39.45 | 21.45 |
def dovds(data):
"""
calculates vector difference sum for demagnetization data
"""
vds, X = 0, []
for rec in data:
X.append(dir2cart(rec))
for k in range(len(X) - 1):
xdif = X[k + 1][0] - X[k][0]
ydif = X[k + 1][1] - X[k][1]
zdif = X[k + 1][2] - X[k][2]
v... | [
"def",
"dovds",
"(",
"data",
")",
":",
"vds",
",",
"X",
"=",
"0",
",",
"[",
"]",
"for",
"rec",
"in",
"data",
":",
"X",
".",
"append",
"(",
"dir2cart",
"(",
"rec",
")",
")",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"X",
")",
"-",
"1",
"... | 30.285714 | 12.428571 |
def intersect(self, other):
"""Find the mutual tensor factors of two Hilbert spaces."""
if other is FullSpace:
return self
if other is TrivialSpace:
return TrivialSpace
if isinstance(other, ProductSpace):
other_ops = set(other.operands)
else:
... | [
"def",
"intersect",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"FullSpace",
":",
"return",
"self",
"if",
"other",
"is",
"TrivialSpace",
":",
"return",
"TrivialSpace",
"if",
"isinstance",
"(",
"other",
",",
"ProductSpace",
")",
":",
"other_op... | 37 | 10.916667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.