text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def try_ntime(max_try, func, *args, **kwargs):
"""
Try execute a function n times, until no exception raised or tried
``max_try`` times.
**中文文档**
反复尝试执行一个函数若干次。直到成功为止或是重复尝试 ``max_try`` 次。期间
只要有一次成功, 就正常返回。如果一次都没有成功, 则行为跟最后一次执行了
``func(*args, **kwargs)`` 一样。
"""
if max_try < 1:
... | [
"def",
"try_ntime",
"(",
"max_try",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"max_try",
"<",
"1",
":",
"raise",
"ValueError",
"for",
"i",
"in",
"range",
"(",
"max_try",
")",
":",
"try",
":",
"return",
"func",
"(",
"... | 23.428571 | 0.001953 |
def _forward_iterator(self):
"Returns a forward iterator over the trie"
path = [(self, 0, Bits())]
while path:
node, idx, prefix = path.pop()
if idx==0 and node.value is not None and not node.prune_value:
yield (self._unpickle_key(prefix), self._unpickle_v... | [
"def",
"_forward_iterator",
"(",
"self",
")",
":",
"path",
"=",
"[",
"(",
"self",
",",
"0",
",",
"Bits",
"(",
")",
")",
"]",
"while",
"path",
":",
"node",
",",
"idx",
",",
"prefix",
"=",
"path",
".",
"pop",
"(",
")",
"if",
"idx",
"==",
"0",
"... | 47 | 0.008696 |
def command(self):
"""
Returns a string representing the command you have to type to
obtain the same packet
"""
f = []
for fn, fv in six.iteritems(self.fields):
fld = self.get_field(fn)
if isinstance(fv, (list, dict, set)) and len(fv) == 0:
... | [
"def",
"command",
"(",
"self",
")",
":",
"f",
"=",
"[",
"]",
"for",
"fn",
",",
"fv",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"fields",
")",
":",
"fld",
"=",
"self",
".",
"get_field",
"(",
"fn",
")",
"if",
"isinstance",
"(",
"fv",
",",
... | 35.333333 | 0.002296 |
def delete(stack, region, profile):
"""
Delete the given CloudFormation stack.
"""
ini_data = {}
environment = {}
environment['stack_name'] = stack
if region:
environment['region'] = region
else:
environment['region'] = find_myself()
if profile:
environment[... | [
"def",
"delete",
"(",
"stack",
",",
"region",
",",
"profile",
")",
":",
"ini_data",
"=",
"{",
"}",
"environment",
"=",
"{",
"}",
"environment",
"[",
"'stack_name'",
"]",
"=",
"stack",
"if",
"region",
":",
"environment",
"[",
"'region'",
"]",
"=",
"regi... | 20.136364 | 0.002155 |
def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize the value to a new element and returns the element."""
dict_value = self._converter.to_dict(value)
return self._dictionary.serialize... | [
"def",
"serialize",
"(",
"self",
",",
"value",
",",
"# type: Any",
"state",
"# type: _ProcessorState",
")",
":",
"# type: (...) -> ET.Element",
"dict_value",
"=",
"self",
".",
"_converter",
".",
"to_dict",
"(",
"value",
")",
"return",
"self",
".",
"_dictionary",
... | 36.777778 | 0.011799 |
def filter_by_transcript_expression(
self,
transcript_expression_dict,
min_expression_value=0.0):
"""
Filters variants down to those which have overlap a transcript whose
expression value in the transcript_expression_dict argument is greater
than min_e... | [
"def",
"filter_by_transcript_expression",
"(",
"self",
",",
"transcript_expression_dict",
",",
"min_expression_value",
"=",
"0.0",
")",
":",
"return",
"self",
".",
"filter_any_above_threshold",
"(",
"multi_key_fn",
"=",
"lambda",
"variant",
":",
"variant",
".",
"trans... | 38.409091 | 0.002309 |
def solve(A, b, x0=None, tol=1e-5, maxiter=400, return_solver=False,
existing_solver=None, verb=True, residuals=None):
"""Solve Ax=b.
Solve the arbitrary system Ax=b with the best out-of-the box choice for a
solver. The matrix A can be non-Hermitian, indefinite, Hermitian
positive-definite, ... | [
"def",
"solve",
"(",
"A",
",",
"b",
",",
"x0",
"=",
"None",
",",
"tol",
"=",
"1e-5",
",",
"maxiter",
"=",
"400",
",",
"return_solver",
"=",
"False",
",",
"existing_solver",
"=",
"None",
",",
"verb",
"=",
"True",
",",
"residuals",
"=",
"None",
")",
... | 33.22314 | 0.000242 |
def image_to_url(image, colormap=None, origin='upper'):
"""
Infers the type of an image argument and transforms it into a URL.
Parameters
----------
image: string, file or array-like object
* If string, it will be written directly in the output file.
* If file, it's content will be ... | [
"def",
"image_to_url",
"(",
"image",
",",
"colormap",
"=",
"None",
",",
"origin",
"=",
"'upper'",
")",
":",
"if",
"isinstance",
"(",
"image",
",",
"str",
")",
"and",
"not",
"_is_url",
"(",
"image",
")",
":",
"fileformat",
"=",
"os",
".",
"path",
".",... | 44.138889 | 0.000616 |
def set_auth_key_from_file(user,
source,
config='.ssh/authorized_keys',
saltenv='base',
fingerprint_hash_type=None):
'''
Add a key to the authorized_keys file, using a file as the source.
CLI Example... | [
"def",
"set_auth_key_from_file",
"(",
"user",
",",
"source",
",",
"config",
"=",
"'.ssh/authorized_keys'",
",",
"saltenv",
"=",
"'base'",
",",
"fingerprint_hash_type",
"=",
"None",
")",
":",
"# TODO: add support for pulling keys from other file sources as well",
"lfile",
... | 32.946429 | 0.001053 |
def dir_ensure(location, recursive=False, mode=None,
owner=None, group=None, use_sudo=False):
""" cuisine dir_ensure doesn't do sudo, so we implement our own
Ensures that there is a remote directory at the given location,
optionally updating its mode/owner/group.
If we are not updating th... | [
"def",
"dir_ensure",
"(",
"location",
",",
"recursive",
"=",
"False",
",",
"mode",
"=",
"None",
",",
"owner",
"=",
"None",
",",
"group",
"=",
"None",
",",
"use_sudo",
"=",
"False",
")",
":",
"args",
"=",
"''",
"if",
"recursive",
":",
"args",
"=",
"... | 34.666667 | 0.00085 |
def extract_response(raw_response):
"""Extract requests response object.
only extract those status_code in [200, 300).
:param raw_response: a requests.Resposne object.
:return: content of response.
"""
data = urlread(raw_response)
if is_success_response(raw_response):
return data
... | [
"def",
"extract_response",
"(",
"raw_response",
")",
":",
"data",
"=",
"urlread",
"(",
"raw_response",
")",
"if",
"is_success_response",
"(",
"raw_response",
")",
":",
"return",
"data",
"elif",
"is_failure_response",
"(",
"raw_response",
")",
":",
"raise",
"Remo... | 28.833333 | 0.001866 |
def profiling_query_formatter(view, context, query_document, name):
"""Format a ProfilingQuery entry for a ProfilingRequest detail field
Parameters
----------
query_document : model.ProfilingQuery
"""
return Markup(
''.join(
[
'<div class="pymongo-query row">... | [
"def",
"profiling_query_formatter",
"(",
"view",
",",
"context",
",",
"query_document",
",",
"name",
")",
":",
"return",
"Markup",
"(",
"''",
".",
"join",
"(",
"[",
"'<div class=\"pymongo-query row\">'",
",",
"'<div class=\"col-md-1\">'",
",",
"'<a href=\"{}\">'",
"... | 35.941176 | 0.00239 |
def build_tr(tr, meta_data, row_spans):
"""
This will return a single tr element, with all tds already populated.
"""
# Create a blank tr element.
tr_el = etree.Element('tr')
w_namespace = get_namespace(tr, 'w')
visited_nodes = []
for el in tr:
if el in visited_nodes:
... | [
"def",
"build_tr",
"(",
"tr",
",",
"meta_data",
",",
"row_spans",
")",
":",
"# Create a blank tr element.",
"tr_el",
"=",
"etree",
".",
"Element",
"(",
"'tr'",
")",
"w_namespace",
"=",
"get_namespace",
"(",
"tr",
",",
"'w'",
")",
"visited_nodes",
"=",
"[",
... | 38.04878 | 0.000312 |
def _make_hostport(conn, default_host, default_port, default_user='', default_password=None):
"""Convert a '[user[:pass]@]host:port' string to a Connection tuple.
If the given connection is empty, use defaults.
If no port is given, use the default.
Args:
conn (str): the string describing the t... | [
"def",
"_make_hostport",
"(",
"conn",
",",
"default_host",
",",
"default_port",
",",
"default_user",
"=",
"''",
",",
"default_password",
"=",
"None",
")",
":",
"parsed",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"'//%s'",
"%",
"conn",
")",
"return... | 39.190476 | 0.002372 |
def get(cls, parent, name):
"""Get an instance matching the parent and name"""
return cls.query.filter_by(parent=parent, name=name).one_or_none() | [
"def",
"get",
"(",
"cls",
",",
"parent",
",",
"name",
")",
":",
"return",
"cls",
".",
"query",
".",
"filter_by",
"(",
"parent",
"=",
"parent",
",",
"name",
"=",
"name",
")",
".",
"one_or_none",
"(",
")"
] | 53 | 0.012422 |
def filter(self, term_doc_matrix):
'''
Parameters
----------
term_doc_matrix : TermDocMatrix
Returns
-------
TermDocMatrix pmi-filterd term doc matrix
'''
df = term_doc_matrix.get_term_freq_df()
if len(df) == 0:
return term_doc_matrix
low_pmi_bigrams = get_low_pmi_bigrams(self._threshold_coef... | [
"def",
"filter",
"(",
"self",
",",
"term_doc_matrix",
")",
":",
"df",
"=",
"term_doc_matrix",
".",
"get_term_freq_df",
"(",
")",
"if",
"len",
"(",
"df",
")",
"==",
"0",
":",
"return",
"term_doc_matrix",
"low_pmi_bigrams",
"=",
"get_low_pmi_bigrams",
"(",
"se... | 29.619048 | 0.034268 |
def is_bit_mask(enumeration, potential_mask):
"""
A utility function that checks if the provided value is a composite bit
mask of enumeration values in the specified enumeration class.
Args:
enumeration (class): One of the mask enumeration classes found in this
file. These include:
... | [
"def",
"is_bit_mask",
"(",
"enumeration",
",",
"potential_mask",
")",
":",
"if",
"not",
"isinstance",
"(",
"potential_mask",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"False",
"mask_enumerations",
"=",
"(",
"CryptographicUsageMask",
",",
"ProtectionSto... | 29.842105 | 0.000854 |
def find_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE,
create=False):
"""Look for rdata with the specified name and type in the zone,
and return an rdataset encapsulating it.
The I{name}, I{rdtype}, and I{covers} parameters may be
strings, in which case t... | [
"def",
"find_rdataset",
"(",
"self",
",",
"name",
",",
"rdtype",
",",
"covers",
"=",
"dns",
".",
"rdatatype",
".",
"NONE",
",",
"create",
"=",
"False",
")",
":",
"name",
"=",
"self",
".",
"_validate_name",
"(",
"name",
")",
"if",
"isinstance",
"(",
"... | 40.857143 | 0.002049 |
def get_surveys(self):
"""Gets all surveys in account
Args:
None
Returns:
list: a list of all surveys
"""
payload = {
'Request': 'getSurveys',
'Format': 'JSON'
}
r = self._session.get(QUALT... | [
"def",
"get_surveys",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'Request'",
":",
"'getSurveys'",
",",
"'Format'",
":",
"'JSON'",
"}",
"r",
"=",
"self",
".",
"_session",
".",
"get",
"(",
"QUALTRICS_URL",
",",
"params",
"=",
"payload",
")",
"output",
... | 24.9375 | 0.012077 |
def user(val, **kwargs): # pylint: disable=unused-argument
'''
This can be either a string or a numeric uid
'''
if not isinstance(val, six.integer_types):
# Try to convert to integer. This will fail if the value is a
# username. This is OK, as we check below to make sure that the
... | [
"def",
"user",
"(",
"val",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"if",
"not",
"isinstance",
"(",
"val",
",",
"six",
".",
"integer_types",
")",
":",
"# Try to convert to integer. This will fail if the value is a",
"# username. This is OK... | 45.842105 | 0.001125 |
def _get_info_score(info):
"""
Helper function for _bestmove_get_info.
Example inputs:
score cp -100 <- engine is behind 100 centipawns
score mate 3 <- engine has big lead or checkmated opponent
"""
search = re.search(pattern="score (?P<eval>\w+) ... | [
"def",
"_get_info_score",
"(",
"info",
")",
":",
"search",
"=",
"re",
".",
"search",
"(",
"pattern",
"=",
"\"score (?P<eval>\\w+) (?P<value>-?\\d+)\"",
",",
"string",
"=",
"info",
")",
"return",
"{",
"\"score\"",
":",
"{",
"\"eval\"",
":",
"search",
".",
"gr... | 39.545455 | 0.013483 |
def stage_all(self):
"""
Stages all changed and untracked files
"""
LOGGER.info('Staging all files')
self.repo.git.add(A=True) | [
"def",
"stage_all",
"(",
"self",
")",
":",
"LOGGER",
".",
"info",
"(",
"'Staging all files'",
")",
"self",
".",
"repo",
".",
"git",
".",
"add",
"(",
"A",
"=",
"True",
")"
] | 26.833333 | 0.012048 |
def re_general(Vel, Area, PerimWetted, Nu):
"""Return the Reynolds Number for a general cross section."""
#Checking input validity - inputs not checked here are checked by
#functions this function calls.
ut.check_range([Vel, ">=0", "Velocity"], [Nu, ">0", "Nu"])
return 4 * radius_hydraulic_general(A... | [
"def",
"re_general",
"(",
"Vel",
",",
"Area",
",",
"PerimWetted",
",",
"Nu",
")",
":",
"#Checking input validity - inputs not checked here are checked by",
"#functions this function calls.",
"ut",
".",
"check_range",
"(",
"[",
"Vel",
",",
"\">=0\"",
",",
"\"Velocity\"",... | 58.833333 | 0.00838 |
def rgb_to_hsv(r, g=None, b=None):
"""Convert the color from RGB coordinates to HSV.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, v) tuple in the range:
h[0...360],... | [
"def",
"rgb_to_hsv",
"(",
"r",
",",
"g",
"=",
"None",
",",
"b",
"=",
"None",
")",
":",
"if",
"type",
"(",
"r",
")",
"in",
"[",
"list",
",",
"tuple",
"]",
":",
"r",
",",
"g",
",",
"b",
"=",
"r",
"v",
"=",
"float",
"(",
"max",
"(",
"r",
"... | 19.975 | 0.022673 |
def unit(n, d=None, j=None, tt_instance=True):
''' Generates e_j _vector in tt.vector format
---------
Parameters:
n - modes (either integer or array)
d - dimensionality (integer)
j - position of 1 in full-format e_j (integer)
tt_instance - if True, returns tt.vector;
... | [
"def",
"unit",
"(",
"n",
",",
"d",
"=",
"None",
",",
"j",
"=",
"None",
",",
"tt_instance",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"int",
")",
":",
"if",
"d",
"is",
"None",
":",
"d",
"=",
"1",
"n",
"=",
"n",
"*",
"_np",
... | 26.285714 | 0.001311 |
def run(command, parser, cl_args, unknown_args):
""" run command """
try:
clusters = tracker_access.get_clusters()
except:
Log.error("Fail to connect to tracker: \'%s\'", cl_args["tracker_url"])
return False
print('Available clusters:')
for cluster in clusters:
print(' %s' % cluster)
return... | [
"def",
"run",
"(",
"command",
",",
"parser",
",",
"cl_args",
",",
"unknown_args",
")",
":",
"try",
":",
"clusters",
"=",
"tracker_access",
".",
"get_clusters",
"(",
")",
"except",
":",
"Log",
".",
"error",
"(",
"\"Fail to connect to tracker: \\'%s\\'\"",
",",
... | 28.636364 | 0.024615 |
def do_thing():
"""Execute command line cryptorito actions"""
if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file":
encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4])
elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file":
decrypt_file(sys.argv[2], sys.argv[3])
elif len(sys.argv) ... | [
"def",
"do_thing",
"(",
")",
":",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"==",
"5",
"and",
"sys",
".",
"argv",
"[",
"1",
"]",
"==",
"\"encrypt_file\"",
":",
"encrypt_file",
"(",
"sys",
".",
"argv",
"[",
"2",
"]",
",",
"sys",
".",
"argv",
"[... | 43.681818 | 0.001018 |
def next(self):
"""Next point in iteration
"""
x, y = next(self.scan)
xs = int(round(x))
ys = int(round(y))
return xs, ys | [
"def",
"next",
"(",
"self",
")",
":",
"x",
",",
"y",
"=",
"next",
"(",
"self",
".",
"scan",
")",
"xs",
"=",
"int",
"(",
"round",
"(",
"x",
")",
")",
"ys",
"=",
"int",
"(",
"round",
"(",
"y",
")",
")",
"return",
"xs",
",",
"ys"
] | 23.285714 | 0.011834 |
def from_object(updates):
"Update same name (or prefixed) settings."
import sys
config = sys.modules[__name__]
prefix = config.__name__.split('.')[0].upper()
keys = [k for k in config.__dict__ if \
k != from_object.__name__ and not k.startswith('_')]
get_value = lambda c, k: hasattr... | [
"def",
"from_object",
"(",
"updates",
")",
":",
"import",
"sys",
"config",
"=",
"sys",
".",
"modules",
"[",
"__name__",
"]",
"prefix",
"=",
"config",
".",
"__name__",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"keys",
"="... | 40.461538 | 0.011152 |
def _create_lookup(self, branched_action_space):
"""
Creates a Dict that maps discrete actions (scalars) to branched actions (lists).
Each key in the Dict maps to one unique set of branched actions, and each value
contains the List of branched actions.
"""
possible_vals =... | [
"def",
"_create_lookup",
"(",
"self",
",",
"branched_action_space",
")",
":",
"possible_vals",
"=",
"[",
"range",
"(",
"_num",
")",
"for",
"_num",
"in",
"branched_action_space",
"]",
"all_actions",
"=",
"[",
"list",
"(",
"_action",
")",
"for",
"_action",
"in... | 57.454545 | 0.009346 |
def configure_splitevaluator(self):
"""
Configures and returns the SplitEvaluator and Classifier instance as tuple.
:return: evaluator and classifier
:rtype: tuple
"""
if self.classification:
speval = javabridge.make_instance("weka/experiment/ClassifierSplitE... | [
"def",
"configure_splitevaluator",
"(",
"self",
")",
":",
"if",
"self",
".",
"classification",
":",
"speval",
"=",
"javabridge",
".",
"make_instance",
"(",
"\"weka/experiment/ClassifierSplitEvaluator\"",
",",
"\"()V\"",
")",
"else",
":",
"speval",
"=",
"javabridge",... | 43.615385 | 0.010363 |
def prune_graph(graph_str, package_name):
"""Prune a package graph so it only contains nodes accessible from the
given package.
Args:
graph_str (str): Dot-language graph string.
package_name (str): Name of package of interest.
Returns:
Pruned graph, as a string.
"""
# f... | [
"def",
"prune_graph",
"(",
"graph_str",
",",
"package_name",
")",
":",
"# find nodes of interest",
"g",
"=",
"read_dot",
"(",
"graph_str",
")",
"nodes",
"=",
"set",
"(",
")",
"for",
"node",
",",
"attrs",
"in",
"g",
".",
"node_attr",
".",
"iteritems",
"(",
... | 28.195652 | 0.000745 |
def setOutputObject(self, newOutput=output.CalcpkgOutput(True, True)):
"""Set an object where all output from calcpkg will be redirected to for this repository"""
self.output = newOutput | [
"def",
"setOutputObject",
"(",
"self",
",",
"newOutput",
"=",
"output",
".",
"CalcpkgOutput",
"(",
"True",
",",
"True",
")",
")",
":",
"self",
".",
"output",
"=",
"newOutput"
] | 62.666667 | 0.026316 |
def acquire(self, blocking=True, timeout=None):
"""Acquire the lock.
If *blocking* is true (the default), then this will block until the
lock can be acquired. The *timeout* parameter specifies an optional
timeout in seconds.
The return value is a boolean indicating whether the ... | [
"def",
"acquire",
"(",
"self",
",",
"blocking",
"=",
"True",
",",
"timeout",
"=",
"None",
")",
":",
"hub",
"=",
"get_hub",
"(",
")",
"try",
":",
"# switcher.__call__ needs to be synchronized with a lock IF it can",
"# be called from different threads. This is the case her... | 48.326923 | 0.00078 |
def fadeGrid(self, fSeconds, bFadeIn):
"""Fading the Grid in or out in fSeconds"""
fn = self.function_table.fadeGrid
fn(fSeconds, bFadeIn) | [
"def",
"fadeGrid",
"(",
"self",
",",
"fSeconds",
",",
"bFadeIn",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"fadeGrid",
"fn",
"(",
"fSeconds",
",",
"bFadeIn",
")"
] | 31.8 | 0.01227 |
def initialize(self, configfile=None):
"""Initialize and load the Fortran library (and model, if applicable).
The Fortran library is loaded and ctypes is used to annotate functions
inside the library. The Fortran library's initialization is called.
Normally a path to an ``*.ini`` model... | [
"def",
"initialize",
"(",
"self",
",",
"configfile",
"=",
"None",
")",
":",
"if",
"configfile",
"is",
"not",
"None",
":",
"self",
".",
"configfile",
"=",
"configfile",
"try",
":",
"self",
".",
"configfile",
"except",
"AttributeError",
":",
"raise",
"ValueE... | 43.628571 | 0.001922 |
def calczmax(self):
"""
NAME:
calczmax
PURPOSE:
calculate the maximum height
INPUT:
OUTPUT:
zmax
HISTORY:
2012-06-01 - Written - Bovy (IAS)
"""
if hasattr(self,'_zmax'): #pragma: no cover
return self.... | [
"def",
"calczmax",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_zmax'",
")",
":",
"#pragma: no cover",
"return",
"self",
".",
"_zmax",
"Ez",
"=",
"calcEz",
"(",
"self",
".",
"_z",
",",
"self",
".",
"_vz",
",",
"self",
".",
"_verticalp... | 30.428571 | 0.026166 |
def iterparse(filelike, encoding=None, handler_class=DrillHandler, xpath=None):
"""
:param filelike: A file-like object with a ``read`` method
:returns: An iterator yielding :class:`XmlElement` objects
"""
parser = expat.ParserCreate(encoding)
elem_iter = DrillElementIterator(filelike, parser)
... | [
"def",
"iterparse",
"(",
"filelike",
",",
"encoding",
"=",
"None",
",",
"handler_class",
"=",
"DrillHandler",
",",
"xpath",
"=",
"None",
")",
":",
"parser",
"=",
"expat",
".",
"ParserCreate",
"(",
"encoding",
")",
"elem_iter",
"=",
"DrillElementIterator",
"(... | 43 | 0.001751 |
def create (netParams=None, simConfig=None, output=False):
''' Sequence of commands to create network '''
from .. import sim
import __main__ as top
if not netParams: netParams = top.netParams
if not simConfig: simConfig = top.simConfig
sim.initialize(netParams, simConfig) # create network obje... | [
"def",
"create",
"(",
"netParams",
"=",
"None",
",",
"simConfig",
"=",
"None",
",",
"output",
"=",
"False",
")",
":",
"from",
".",
".",
"import",
"sim",
"import",
"__main__",
"as",
"top",
"if",
"not",
"netParams",
":",
"netParams",
"=",
"top",
".",
"... | 61.25 | 0.011055 |
def cmd_genobstacles(self, args):
'''genobstacles command parser'''
usage = "usage: genobstacles <start|stop|restart|clearall|status|set>"
if len(args) == 0:
print(usage)
return
if args[0] == "set":
gen_settings.command(args[1:])
elif args[0] =... | [
"def",
"cmd_genobstacles",
"(",
"self",
",",
"args",
")",
":",
"usage",
"=",
"\"usage: genobstacles <start|stop|restart|clearall|status|set>\"",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"print",
"(",
"usage",
")",
"return",
"if",
"args",
"[",
"0",
"]",
... | 36.058824 | 0.001588 |
def execute_task(task_id,
verbosity=None,
runmode='run',
sigmode=None,
monitor_interval=5,
resource_monitor_interval=60):
'''Execute single or master task, return a dictionary'''
tf = TaskFile(task_id)
# this will automati... | [
"def",
"execute_task",
"(",
"task_id",
",",
"verbosity",
"=",
"None",
",",
"runmode",
"=",
"'run'",
",",
"sigmode",
"=",
"None",
",",
"monitor_interval",
"=",
"5",
",",
"resource_monitor_interval",
"=",
"60",
")",
":",
"tf",
"=",
"TaskFile",
"(",
"task_id"... | 35.54 | 0.001095 |
def crossmap(fas, reads, options, no_shrink, keepDB, threads, cluster, nodes):
"""
map all read sets against all fasta files
"""
if cluster is True:
threads = '48'
btc = []
for fa in fas:
btd = bowtiedb(fa, keepDB)
F, R, U = reads
if F is not False:
if... | [
"def",
"crossmap",
"(",
"fas",
",",
"reads",
",",
"options",
",",
"no_shrink",
",",
"keepDB",
",",
"threads",
",",
"cluster",
",",
"nodes",
")",
":",
"if",
"cluster",
"is",
"True",
":",
"threads",
"=",
"'48'",
"btc",
"=",
"[",
"]",
"for",
"fa",
"in... | 37.952381 | 0.011621 |
def createCombinedSequenceColumn(network, networkConfig, suffix=""):
"""
Create a a single column containing one L4, one L2, and one TM.
networkConfig is a dict that must contain the following keys (additional keys
ok):
{
"externalInputSize": 1024,
"sensorInputSize": 1024,
"L2Params": {
... | [
"def",
"createCombinedSequenceColumn",
"(",
"network",
",",
"networkConfig",
",",
"suffix",
"=",
"\"\"",
")",
":",
"externalInputName",
"=",
"\"externalInput\"",
"+",
"suffix",
"sensorInputName",
"=",
"\"sensorInput\"",
"+",
"suffix",
"L4ColumnName",
"=",
"\"L4Column\... | 38.252747 | 0.012321 |
def vm_netstats(vm_=None):
'''
Return combined network counters used by the vms on this hyper in a
list of dicts:
.. code-block:: python
[
'your-vm': {
'io_read_kbs' : 0,
'io_total_read_kbs' : 0,
'io_total_write_kbs' ... | [
"def",
"vm_netstats",
"(",
"vm_",
"=",
"None",
")",
":",
"with",
"_get_xapi_session",
"(",
")",
"as",
"xapi",
":",
"def",
"_info",
"(",
"vm_",
")",
":",
"ret",
"=",
"{",
"}",
"vm_rec",
"=",
"_get_record_by_label",
"(",
"xapi",
",",
"'VM'",
",",
"vm_"... | 27.574468 | 0.000745 |
def postOptions(self):
"""
Display details about the ports which already exist.
"""
store = self.parent.parent.getStore()
port = None
factories = {}
for portType in [TCPPort, SSLPort, StringEndpointPort]:
for port in store.query(portType):
... | [
"def",
"postOptions",
"(",
"self",
")",
":",
"store",
"=",
"self",
".",
"parent",
".",
"parent",
".",
"getStore",
"(",
")",
"port",
"=",
"None",
"factories",
"=",
"{",
"}",
"for",
"portType",
"in",
"[",
"TCPPort",
",",
"SSLPort",
",",
"StringEndpointPo... | 46.38 | 0.001267 |
async def quit(self, message=None):
""" Quit network. """
if message is None:
message = self.DEFAULT_QUIT_MESSAGE
await self.rawmsg('QUIT', message)
await self.disconnect(expected=True) | [
"async",
"def",
"quit",
"(",
"self",
",",
"message",
"=",
"None",
")",
":",
"if",
"message",
"is",
"None",
":",
"message",
"=",
"self",
".",
"DEFAULT_QUIT_MESSAGE",
"await",
"self",
".",
"rawmsg",
"(",
"'QUIT'",
",",
"message",
")",
"await",
"self",
".... | 32 | 0.008696 |
def add_alias(self, entry):
""" Adds id to the current list 'aliased_by'
"""
assert isinstance(entry, SymbolVAR)
self.aliased_by.append(entry) | [
"def",
"add_alias",
"(",
"self",
",",
"entry",
")",
":",
"assert",
"isinstance",
"(",
"entry",
",",
"SymbolVAR",
")",
"self",
".",
"aliased_by",
".",
"append",
"(",
"entry",
")"
] | 34 | 0.011494 |
def get_policy_info(policy_name,
policy_class,
adml_language='en-US'):
r'''
Returns information about a specified policy
Args:
policy_name (str):
The name of the policy to lookup
policy_class (str):
The class of policy, i.e. ma... | [
"def",
"get_policy_info",
"(",
"policy_name",
",",
"policy_class",
",",
"adml_language",
"=",
"'en-US'",
")",
":",
"# return the possible policy names and element names",
"ret",
"=",
"{",
"'policy_name'",
":",
"policy_name",
",",
"'policy_class'",
":",
"policy_class",
"... | 44.13198 | 0.00225 |
def box(n_traces=5,n=100,mode=None):
"""
Returns a DataFrame with the required format for
a box plot
Parameters:
-----------
n_traces : int
Number of traces
n : int
Number of points for each trace
mode : string
Format for each item
'abc' for alphabet columns
'stocks' for random stock name... | [
"def",
"box",
"(",
"n_traces",
"=",
"5",
",",
"n",
"=",
"100",
",",
"mode",
"=",
"None",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"[",
"np",
".",
"random",
".",
"chisquare",
"(",
"np",
".",
"random",
".",
"randint",
"(",
"2",
",",
"1... | 23.736842 | 0.061834 |
def cbow_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for CBOW training objective."""
contexts_data, contexts_row, contexts_col = contexts
centers = mx.nd.array(centers, dtype=index_dtype)
contexts = mx.nd.sparse.csr_matrix(
(contexts_data, (contexts_row, contexts_... | [
"def",
"cbow_batch",
"(",
"centers",
",",
"contexts",
",",
"num_tokens",
",",
"dtype",
",",
"index_dtype",
")",
":",
"contexts_data",
",",
"contexts_row",
",",
"contexts_col",
"=",
"contexts",
"centers",
"=",
"mx",
".",
"nd",
".",
"array",
"(",
"centers",
... | 52.5 | 0.002342 |
def clustering_gmm(data,
n_clusters,
tol=1e-7,
min_covar=None,
scale='logicle'):
"""
Find clusters in an array using a Gaussian Mixture Model.
Before clustering, `data` can be automatically rescaled as specified by
the `scale` ... | [
"def",
"clustering_gmm",
"(",
"data",
",",
"n_clusters",
",",
"tol",
"=",
"1e-7",
",",
"min_covar",
"=",
"None",
",",
"scale",
"=",
"'logicle'",
")",
":",
"# Initialize min_covar parameter",
"# Parameter is initialized differently depending on scikit's version",
"if",
"... | 36.764045 | 0.001488 |
def calculate(self, token_list_x, token_list_y):
'''
Calculate similarity with the Dice coefficient.
Concrete method.
Args:
token_list_x: [token, token, token, ...]
token_list_y: [token, token, token, ...]
Returns... | [
"def",
"calculate",
"(",
"self",
",",
"token_list_x",
",",
"token_list_y",
")",
":",
"x",
",",
"y",
"=",
"self",
".",
"unique",
"(",
"token_list_x",
",",
"token_list_y",
")",
"try",
":",
"result",
"=",
"2",
"*",
"len",
"(",
"x",
"&",
"y",
")",
"/",... | 28.2 | 0.008576 |
def addAccount(self, username, domain, password, avatars=None,
protocol=u'email', disabled=0, internal=False,
verified=True):
"""
Create a user account, add it to this LoginBase, and return it.
This method must be called within a transaction in my store.
... | [
"def",
"addAccount",
"(",
"self",
",",
"username",
",",
"domain",
",",
"password",
",",
"avatars",
"=",
"None",
",",
"protocol",
"=",
"u'email'",
",",
"disabled",
"=",
"0",
",",
"internal",
"=",
"False",
",",
"verified",
"=",
"True",
")",
":",
"# unico... | 38.463768 | 0.00147 |
def load_har_log_entries(file_path):
""" load HAR file and return log entries list
Args:
file_path (str)
Returns:
list: entries
[
{
"request": {},
"response": {}
},
{
"re... | [
"def",
"load_har_log_entries",
"(",
"file_path",
")",
":",
"with",
"io",
".",
"open",
"(",
"file_path",
",",
"\"r+\"",
",",
"encoding",
"=",
"\"utf-8-sig\"",
")",
"as",
"f",
":",
"try",
":",
"content_json",
"=",
"json",
".",
"loads",
"(",
"f",
".",
"re... | 25.555556 | 0.001397 |
def get_activity_search_session(self):
"""Gets the OsidSession associated with the activity search
service.
return: (osid.learning.ActivitySearchSession) - a
ActivitySearchSession
raise: OperationFailed - unable to complete request
raise: Unimplemented - suppor... | [
"def",
"get_activity_search_session",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"supports_activity_search",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"import",
"sessions",
"except",
"ImportError",
":",
"raise",
"Operati... | 36.304348 | 0.002334 |
def encode_categorical(table, columns=None, **kwargs):
"""
Encode categorical columns with `M` categories into `M-1` columns according
to the one-hot scheme.
Parameters
----------
table : pandas.DataFrame
Table with categorical columns to encode.
columns : list-like, optional, defa... | [
"def",
"encode_categorical",
"(",
"table",
",",
"columns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"table",
",",
"pandas",
".",
"Series",
")",
":",
"if",
"not",
"is_categorical_dtype",
"(",
"table",
".",
"dtype",
")",
"... | 35.2 | 0.002211 |
def spectral_bandwidth(y=None, sr=22050, S=None, n_fft=2048, hop_length=512,
win_length=None, window='hann', center=True, pad_mode='reflect',
freq=None, centroid=None, norm=True, p=2):
'''Compute p'th-order spectral bandwidth:
(sum_k S[k] * (freq[k] - centroid)... | [
"def",
"spectral_bandwidth",
"(",
"y",
"=",
"None",
",",
"sr",
"=",
"22050",
",",
"S",
"=",
"None",
",",
"n_fft",
"=",
"2048",
",",
"hop_length",
"=",
"512",
",",
"win_length",
"=",
"None",
",",
"window",
"=",
"'hann'",
",",
"center",
"=",
"True",
... | 32.460993 | 0.000636 |
def should_execute(self):
"""Confirm if proposed-plan should be executed."""
return self.args.apply and (self.args.no_confirm or self.confirm_execution()) | [
"def",
"should_execute",
"(",
"self",
")",
":",
"return",
"self",
".",
"args",
".",
"apply",
"and",
"(",
"self",
".",
"args",
".",
"no_confirm",
"or",
"self",
".",
"confirm_execution",
"(",
")",
")"
] | 56 | 0.017647 |
def JMS_to_FormFlavor_lep(C, dd):
"""From JMS to semileptonic Fierz basis for Classes V.
C should be the JMS basis and `ddll` should be of the
form 'sbl_eni_tau', 'dbl_munu_e' etc."""
b = dflav[dd[0]]
s = dflav[dd[1]]
return {
'CVLL_' + dd + 'mm' : C["VedLL"][1, 1, s, b],
'CVRR_'... | [
"def",
"JMS_to_FormFlavor_lep",
"(",
"C",
",",
"dd",
")",
":",
"b",
"=",
"dflav",
"[",
"dd",
"[",
"0",
"]",
"]",
"s",
"=",
"dflav",
"[",
"dd",
"[",
"1",
"]",
"]",
"return",
"{",
"'CVLL_'",
"+",
"dd",
"+",
"'mm'",
":",
"C",
"[",
"\"VedLL\"",
"... | 47.833333 | 0.011956 |
def expandvars(text, environ=None):
"""Expand shell variables of form $var and ${var}.
Unknown variables are left unchanged.
Args:
text (str): String to expand.
environ (dict): Environ dict to use for expansions, defaults to
os.environ.
Returns:
The expanded string... | [
"def",
"expandvars",
"(",
"text",
",",
"environ",
"=",
"None",
")",
":",
"if",
"'$'",
"not",
"in",
"text",
":",
"return",
"text",
"i",
"=",
"0",
"if",
"environ",
"is",
"None",
":",
"environ",
"=",
"os",
".",
"environ",
"while",
"True",
":",
"m",
... | 23.138889 | 0.001152 |
def iterator_mix(*iterators):
"""
Iterating over list of iterators.
Bit like zip, but zip stops after the
shortest iterator is empty, abd here
we go one until all iterators are empty.
"""
while True:
one_left = False
for it in iterators:
try:
yiel... | [
"def",
"iterator_mix",
"(",
"*",
"iterators",
")",
":",
"while",
"True",
":",
"one_left",
"=",
"False",
"for",
"it",
"in",
"iterators",
":",
"try",
":",
"yield",
"it",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"pass",
"else",
":",
"one_lef... | 23.05 | 0.002083 |
def setdefault(elt, key, default, ctx=None):
"""
Get a local property and create default value if local property does not
exist.
:param elt: local proprety elt to get/create. Not None methods.
:param str key: proprety name.
:param default: property value to set if key no in local properties... | [
"def",
"setdefault",
"(",
"elt",
",",
"key",
",",
"default",
",",
"ctx",
"=",
"None",
")",
":",
"result",
"=",
"default",
"# get the best context",
"if",
"ctx",
"is",
"None",
":",
"ctx",
"=",
"find_ctx",
"(",
"elt",
"=",
"elt",
")",
"# get elt properties... | 28 | 0.00119 |
def draw_anti_aliased_pixels(self, x, y1, y2, color):
""" vertical anti-aliasing at y1 and y2 """
y_max = max(y1, y2)
y_max_int = int(y_max)
alpha = y_max - y_max_int
if alpha > 0.0 and alpha < 1.0 and y_max_int + 1 < self.image_height:
current_pix = self.pixel[int(... | [
"def",
"draw_anti_aliased_pixels",
"(",
"self",
",",
"x",
",",
"y1",
",",
"y2",
",",
"color",
")",
":",
"y_max",
"=",
"max",
"(",
"y1",
",",
"y2",
")",
"y_max_int",
"=",
"int",
"(",
"y_max",
")",
"alpha",
"=",
"y_max",
"-",
"y_max_int",
"if",
"alph... | 44 | 0.001854 |
def memory_usage(proc=-1, interval=.1, timeout=None, timestamps=False,
include_children=False, max_usage=False, retval=False,
stream=None):
"""
Return the memory usage of a process or piece of code
Parameters
----------
proc : {int, string, tuple, subprocess.Popen}... | [
"def",
"memory_usage",
"(",
"proc",
"=",
"-",
"1",
",",
"interval",
"=",
".1",
",",
"timeout",
"=",
"None",
",",
"timestamps",
"=",
"False",
",",
"include_children",
"=",
"False",
",",
"max_usage",
"=",
"False",
",",
"retval",
"=",
"False",
",",
"strea... | 35.653061 | 0.000743 |
def cross_validate(self, ax, info=''):
'''
Cross-validate to find the optimal value of :py:obj:`lambda`.
:param ax: The current :py:obj:`matplotlib.pyplot` axis instance to \
plot the cross-validation results.
:param str info: The label to show in the bottom right-hand co... | [
"def",
"cross_validate",
"(",
"self",
",",
"ax",
",",
"info",
"=",
"''",
")",
":",
"# Loop over all chunks",
"ax",
"=",
"np",
".",
"atleast_1d",
"(",
"ax",
")",
"for",
"b",
",",
"brkpt",
"in",
"enumerate",
"(",
"self",
".",
"breakpoints",
")",
":",
"... | 40.623037 | 0.000252 |
def require_qt(func):
"""Specify that a function requires a Qt application.
Use this decorator to specify that a function needs a running
Qt application before it can run. An error is raised if that is not
the case.
"""
@wraps(func)
def wrapped(*args, **kwargs):
if not QApplication... | [
"def",
"require_qt",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"QApplication",
".",
"instance",
"(",
")",
":",
"# pragma: no cover",
"raise",
"RuntimeError... | 33.071429 | 0.002101 |
def list_pr_comments(repo: GithubRepository, pull_id: int
) -> List[Dict[str, Any]]:
"""
References:
https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue
"""
url = ("https://api.github.com/repos/{}/{}/issues/{}/comments"
"?access_token={}".fo... | [
"def",
"list_pr_comments",
"(",
"repo",
":",
"GithubRepository",
",",
"pull_id",
":",
"int",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"url",
"=",
"(",
"\"https://api.github.com/repos/{}/{}/issues/{}/comments\"",
"\"?access_token={}\""... | 43.5 | 0.00125 |
def get_fax(self, fax_id, **kwargs): # noqa: E501
"""Get a fax record # noqa: E501
Get a specific fax record details like duration, pages etc. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>... | [
"def",
"get_fax",
"(",
"self",
",",
"fax_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"self",
".",
"get_fax_with_http_in... | 40.666667 | 0.002288 |
def trac_tickets(self):
'''
Looks for any of the following trac ticket formats in the description field:
t12345, t 12345, T12345, T 12345, #12345, # 12345, ticket 12345, TICKET 12345
'''
# ticket_numbers = re.findall(re.compile("([t#]\s?[0-9]{2,})|([t#][0-9]{2,})", re.IGNORE... | [
"def",
"trac_tickets",
"(",
"self",
")",
":",
"# ticket_numbers = re.findall(re.compile(\"([t#]\\s?[0-9]{2,})|([t#][0-9]{2,})\", re.IGNORECASE), self.description)",
"ticket_numbers",
"=",
"re",
".",
"findall",
"(",
"r\"^[tT#]\\s?[0-9]+\"",
",",
"self",
".",
"description",
")",
... | 51.5 | 0.010899 |
def process_exception(self, request: AxesHttpRequest, exception): # pylint: disable=inconsistent-return-statements
"""
Exception handler that processes exceptions raised by the Axes signal handler when request fails with login.
Only ``axes.exceptions.AxesSignalPermissionDenied`` exception is h... | [
"def",
"process_exception",
"(",
"self",
",",
"request",
":",
"AxesHttpRequest",
",",
"exception",
")",
":",
"# pylint: disable=inconsistent-return-statements",
"if",
"isinstance",
"(",
"exception",
",",
"AxesSignalPermissionDenied",
")",
":",
"return",
"get_lockout_respo... | 51.333333 | 0.010638 |
def obs_groups(self):
"""get the observation groups
Returns
-------
obs_groups : list
a list of unique observation groups
"""
og = list(self.observation_data.groupby("obgnme").groups.keys())
#og = list(map(pst_utils.SFMT, og))
return og | [
"def",
"obs_groups",
"(",
"self",
")",
":",
"og",
"=",
"list",
"(",
"self",
".",
"observation_data",
".",
"groupby",
"(",
"\"obgnme\"",
")",
".",
"groups",
".",
"keys",
"(",
")",
")",
"#og = list(map(pst_utils.SFMT, og))",
"return",
"og"
] | 25.25 | 0.009554 |
def varianceOfLaplacian(img):
''''LAPV' algorithm (Pech2000)'''
lap = cv2.Laplacian(img, ddepth=-1)#cv2.cv.CV_64F)
stdev = cv2.meanStdDev(lap)[1]
s = stdev[0]**2
return s[0] | [
"def",
"varianceOfLaplacian",
"(",
"img",
")",
":",
"lap",
"=",
"cv2",
".",
"Laplacian",
"(",
"img",
",",
"ddepth",
"=",
"-",
"1",
")",
"#cv2.cv.CV_64F)\r",
"stdev",
"=",
"cv2",
".",
"meanStdDev",
"(",
"lap",
")",
"[",
"1",
"]",
"s",
"=",
"stdev",
... | 32.166667 | 0.015152 |
def matches(property_name, regex, *, present_optional=False, message=None):
"""Returns a Validation that checks a property against a regex."""
def check(val):
"""Checks that a value matches a scope-enclosed regex."""
if not val:
return present_optional
else:
return True if rege... | [
"def",
"matches",
"(",
"property_name",
",",
"regex",
",",
"*",
",",
"present_optional",
"=",
"False",
",",
"message",
"=",
"None",
")",
":",
"def",
"check",
"(",
"val",
")",
":",
"\"\"\"Checks that a value matches a scope-enclosed regex.\"\"\"",
"if",
"not",
"v... | 38.9 | 0.01005 |
def ximplot(ycut, title=None, show=True, plot_bbox=(0, 0),
geometry=(0, 0, 640, 480), tight_layout=True,
debugplot=None):
"""Auxiliary function to display 1d plot.
Parameters
----------
ycut : 1d numpy array, float
Array to be displayed.
title : string
Plot t... | [
"def",
"ximplot",
"(",
"ycut",
",",
"title",
"=",
"None",
",",
"show",
"=",
"True",
",",
"plot_bbox",
"=",
"(",
"0",
",",
"0",
")",
",",
"geometry",
"=",
"(",
"0",
",",
"0",
",",
"640",
",",
"480",
")",
",",
"tight_layout",
"=",
"True",
",",
... | 31.478723 | 0.000328 |
def create_config_files(directory):
"""
For each VPN file in directory/vpns, create a new configuration
file and all the associated directories
Note: the expected directory structure is
args.directory
-----vpns (contains the OpenVPN config files
-----configs (contains the Centinel config fi... | [
"def",
"create_config_files",
"(",
"directory",
")",
":",
"logging",
".",
"info",
"(",
"\"Starting to create config files from openvpn files\"",
")",
"vpn_dir",
"=",
"return_abs_path",
"(",
"directory",
",",
"\"vpns\"",
")",
"conf_dir",
"=",
"return_abs_path",
"(",
"d... | 39.645833 | 0.000513 |
def record_strip_empty_fields(rec, tag=None):
"""
Remove empty subfields and fields from the record.
If 'tag' is not None, only a specific tag of the record will be stripped,
otherwise the whole record.
:param rec: A record dictionary structure
:type rec: dictionary
:param tag: The tag... | [
"def",
"record_strip_empty_fields",
"(",
"rec",
",",
"tag",
"=",
"None",
")",
":",
"# Check whole record",
"if",
"tag",
"is",
"None",
":",
"tags",
"=",
"rec",
".",
"keys",
"(",
")",
"for",
"tag",
"in",
"tags",
":",
"record_strip_empty_fields",
"(",
"rec",
... | 33.727273 | 0.00131 |
def create_default_units_and_dimensions():
"""
Adds the units and the dimensions reading a json file. It adds only dimensions and units that are not inside the db
It is possible adding new dimensions and units to the DB just modifiyin the json file
"""
default_units_file_location = os.path.r... | [
"def",
"create_default_units_and_dimensions",
"(",
")",
":",
"default_units_file_location",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
... | 41.855072 | 0.008119 |
def get_queryset(self):
"""
Returns a queryset of models for the month requested
"""
qs = super(BaseCalendarMonthView, self).get_queryset()
year = self.get_year()
month = self.get_month()
date_field = self.get_date_field()
end_date_field = self.get_end_d... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"super",
"(",
"BaseCalendarMonthView",
",",
"self",
")",
".",
"get_queryset",
"(",
")",
"year",
"=",
"self",
".",
"get_year",
"(",
")",
"month",
"=",
"self",
".",
"get_month",
"(",
")",
"date_fie... | 38.258065 | 0.002055 |
def get_dicts_generator(word_min_freq=4,
char_min_freq=2,
word_ignore_case=False,
char_ignore_case=False):
"""Get word and character dictionaries from sentences.
:param word_min_freq: The minimum frequency of a word.
:param char_min_fr... | [
"def",
"get_dicts_generator",
"(",
"word_min_freq",
"=",
"4",
",",
"char_min_freq",
"=",
"2",
",",
"word_ignore_case",
"=",
"False",
",",
"char_ignore_case",
"=",
"False",
")",
":",
"word_count",
",",
"char_count",
"=",
"{",
"}",
",",
"{",
"}",
"def",
"get... | 41.568627 | 0.001382 |
def make_ordinary_result(result, key, trajectory=None, reload=True):
"""Turns a given shared data item into a an ordinary one.
:param result: Result container with shared data
:param key: The name of the shared data
:param trajectory:
The trajectory, only needed if shared data has
no a... | [
"def",
"make_ordinary_result",
"(",
"result",
",",
"key",
",",
"trajectory",
"=",
"None",
",",
"reload",
"=",
"True",
")",
":",
"shared_data",
"=",
"result",
".",
"f_get",
"(",
"key",
")",
"if",
"trajectory",
"is",
"not",
"None",
":",
"shared_data",
".",... | 29.791667 | 0.001355 |
def integrate_days(self, days=1.0, verbose=True):
"""Integrates the model forward for a specified number of days.
It convertes the given number of days into years and calls
:func:`integrate_years`.
:param float days: integration time for the model in days
... | [
"def",
"integrate_days",
"(",
"self",
",",
"days",
"=",
"1.0",
",",
"verbose",
"=",
"True",
")",
":",
"years",
"=",
"days",
"/",
"const",
".",
"days_per_year",
"self",
".",
"integrate_years",
"(",
"years",
"=",
"years",
",",
"verbose",
"=",
"verbose",
... | 33.903226 | 0.00185 |
def _any_would_run(func, filenames, *args):
"""True if a linter function would be called on any of filenames."""
if os.environ.get("_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING", None):
return True
for filename in filenames:
# suppress(E204)
stamp_args, stamp_kwargs = _run_lint_on_fi... | [
"def",
"_any_would_run",
"(",
"func",
",",
"filenames",
",",
"*",
"args",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING\"",
",",
"None",
")",
":",
"return",
"True",
"for",
"filename",
"in",
"filenames",
... | 38.888889 | 0.001395 |
def referenceLengths(self):
"""
Get the lengths of wanted references.
@raise UnknownReference: If a reference id is not present in the
SAM/BAM file.
@return: A C{dict} of C{str} reference id to C{int} length with a key
for each reference id in C{self.referenceIds... | [
"def",
"referenceLengths",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"with",
"samfile",
"(",
"self",
".",
"filename",
")",
"as",
"sam",
":",
"if",
"self",
".",
"referenceIds",
":",
"for",
"referenceId",
"in",
"self",
".",
"referenceIds",
":",
"ti... | 39.2 | 0.001992 |
def _get_localization_env(self, inputs, user_project):
"""Return a dict with variables for the 'localization' action."""
# Add variables for paths that need to be localized, for example:
# INPUT_COUNT: 1
# INPUT_0: MY_INPUT_FILE
# INPUT_RECURSIVE_0: 0
# INPUT_SRC_0: gs://mybucket/mypath/myfile
... | [
"def",
"_get_localization_env",
"(",
"self",
",",
"inputs",
",",
"user_project",
")",
":",
"# Add variables for paths that need to be localized, for example:",
"# INPUT_COUNT: 1",
"# INPUT_0: MY_INPUT_FILE",
"# INPUT_RECURSIVE_0: 0",
"# INPUT_SRC_0: gs://mybucket/mypath/myfile",
"# INP... | 36.5 | 0.00858 |
def _format_rules_for_eos(self, rules):
"""Format list of rules for EOS and sort into ingress/egress rules"""
in_rules = []
eg_rules = []
for rule in rules:
protocol = rule.get('protocol')
cidr = rule.get('remote_ip_prefix', 'any')
min_port = rule.get(... | [
"def",
"_format_rules_for_eos",
"(",
"self",
",",
"rules",
")",
":",
"in_rules",
"=",
"[",
"]",
"eg_rules",
"=",
"[",
"]",
"for",
"rule",
"in",
"rules",
":",
"protocol",
"=",
"rule",
".",
"get",
"(",
"'protocol'",
")",
"cidr",
"=",
"rule",
".",
"get"... | 47.25 | 0.002075 |
def calc_adc_params(self):
"""
Compute appropriate adc_gain and baseline parameters for adc
conversion, given the physical signal and the fmts.
Returns
-------
adc_gains : list
List of calculated `adc_gain` values for each channel.
baselines : list
... | [
"def",
"calc_adc_params",
"(",
"self",
")",
":",
"adc_gains",
"=",
"[",
"]",
"baselines",
"=",
"[",
"]",
"if",
"np",
".",
"where",
"(",
"np",
".",
"isinf",
"(",
"self",
".",
"p_signal",
")",
")",
"[",
"0",
"]",
".",
"size",
":",
"raise",
"ValueEr... | 38.345794 | 0.000475 |
def get_cell_length(flow_model):
"""Get flow direction induced cell length dict.
Args:
flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported.
"""
assert flow_model.lower() in FlowModelConst.d8_lens
return FlowModelConst.d8_lens.get(flow_model.lower()... | [
"def",
"get_cell_length",
"(",
"flow_model",
")",
":",
"assert",
"flow_model",
".",
"lower",
"(",
")",
"in",
"FlowModelConst",
".",
"d8_lens",
"return",
"FlowModelConst",
".",
"d8_lens",
".",
"get",
"(",
"flow_model",
".",
"lower",
"(",
")",
")"
] | 45 | 0.009346 |
def coroutine(func):
"""
Initializes coroutine essentially priming it to the yield statement.
Used as a decorator over functions that generate coroutines.
.. code-block:: python
# Basic coroutine producer/consumer pattern
from translate import coroutine
@coroutine
def ... | [
"def",
"coroutine",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"initialization",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"start",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"next",
"(",
"start",
... | 21.5 | 0.001236 |
def push_file():
""" Push a file to the server """ #NOTE beware that reading post data in flask causes hang until file upload is complete
session_token = request.headers['session_token']
repository = request.headers['repository']
#===
current_user = have_authenticated_user(request.environ['REMO... | [
"def",
"push_file",
"(",
")",
":",
"#NOTE beware that reading post data in flask causes hang until file upload is complete",
"session_token",
"=",
"request",
".",
"headers",
"[",
"'session_token'",
"]",
"repository",
"=",
"request",
".",
"headers",
"[",
"'repository'",
"]",... | 37.675 | 0.013583 |
def _addKeyToQueue(self, keychr, modFlags=0, globally=False):
"""Add keypress to queue.
Parameters: key character or constant referring to a non-alpha-numeric
key (e.g. RETURN or TAB)
modifiers
global or app specific
Returns: None or r... | [
"def",
"_addKeyToQueue",
"(",
"self",
",",
"keychr",
",",
"modFlags",
"=",
"0",
",",
"globally",
"=",
"False",
")",
":",
"# Awkward, but makes modifier-key-only combinations possible",
"# (since sendKeyWithModifiers() calls this)",
"if",
"not",
"keychr",
":",
"return",
... | 41.40625 | 0.001106 |
def update_router(self, router, body=None):
"""Updates a router."""
return self.put(self.router_path % (router), body=body) | [
"def",
"update_router",
"(",
"self",
",",
"router",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"put",
"(",
"self",
".",
"router_path",
"%",
"(",
"router",
")",
",",
"body",
"=",
"body",
")"
] | 45.666667 | 0.014388 |
def create_or_update_vmextension(call=None, kwargs=None): # pylint: disable=unused-argument
'''
.. versionadded:: 2019.2.0
Create or update a VM extension object "inside" of a VM object.
required kwargs:
.. code-block:: yaml
extension_name: myvmextension
virtual_machine_name: m... | [
"def",
"create_or_update_vmextension",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"# pylint: disable=unused-argument",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"if",
"'extension_name'",
"not",
"in",
"kwargs",
":",
"raise... | 33.403846 | 0.001957 |
def connect_get_namespaced_pod_proxy(self, name, namespace, **kwargs): # noqa: E501
"""connect_get_namespaced_pod_proxy # noqa: E501
connect GET requests to proxy of Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please... | [
"def",
"connect_get_namespaced_pod_proxy",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"... | 52.782609 | 0.001618 |
def move(self, d_xyz, inplace=False):
"""
Translate the whole Space in x, y and z coordinates.
:param d_xyz: displacement in x, y(, and z).
:type d_xyz: tuple (len=2 or 3)
:param inplace: If True, the moved ``pyny.Space`` is copied and
added to the cu... | [
"def",
"move",
"(",
"self",
",",
"d_xyz",
",",
"inplace",
"=",
"False",
")",
":",
"state",
"=",
"Polygon",
".",
"verify",
"Polygon",
".",
"verify",
"=",
"False",
"if",
"len",
"(",
"d_xyz",
")",
"==",
"2",
":",
"d_xyz",
"=",
"(",
"d_xyz",
"[",
"0"... | 33.888889 | 0.008502 |
def _einsum_equation(input_shapes, output_shape):
"""Turn shapes into an einsum equation.
e.g. "ij,jk->ik"
Args:
input_shapes: a list of Shapes
output_shape: a Shape
Returns:
a string
"""
ret = []
next_letter = ord("a")
dim_to_letter = {}
for shape_num, shape in enumerate(input_shapes + ... | [
"def",
"_einsum_equation",
"(",
"input_shapes",
",",
"output_shape",
")",
":",
"ret",
"=",
"[",
"]",
"next_letter",
"=",
"ord",
"(",
"\"a\"",
")",
"dim_to_letter",
"=",
"{",
"}",
"for",
"shape_num",
",",
"shape",
"in",
"enumerate",
"(",
"input_shapes",
"+"... | 23.230769 | 0.017488 |
def putrequest(self, method, url, skip_host=0, skip_accept_encoding=0):
"""Send a request to the server.
`method' specifies an HTTP request method, e.g. 'GET'.
`url' specifies the object being requested, e.g. '/index.html'.
`skip_host' if True does not add automatically a 'Host:' header... | [
"def",
"putrequest",
"(",
"self",
",",
"method",
",",
"url",
",",
"skip_host",
"=",
"0",
",",
"skip_accept_encoding",
"=",
"0",
")",
":",
"# if a prior response has been completed, then forget about it.",
"if",
"self",
".",
"__response",
"and",
"self",
".",
"__res... | 43.834783 | 0.00097 |
def get_extra_vehicle_info(self, authentication_info):
"""Get extra data from the API."""
import requests
base_url = "https://secure.ritassist.nl/GenericServiceJSONP.ashx"
query = "?f=CheckExtraVehicleInfo" \
"&token={token}" \
"&equipmentId={identifier}"... | [
"def",
"get_extra_vehicle_info",
"(",
"self",
",",
"authentication_info",
")",
":",
"import",
"requests",
"base_url",
"=",
"\"https://secure.ritassist.nl/GenericServiceJSONP.ashx\"",
"query",
"=",
"\"?f=CheckExtraVehicleInfo\"",
"\"&token={token}\"",
"\"&equipmentId={identifier}\""... | 37.136364 | 0.002387 |
def allow_implicit_stop(gen_func):
"""
Fix the backwards-incompatible PEP-0479 gotcha/bug
https://www.python.org/dev/peps/pep-0479
"""
@functools.wraps(gen_func)
def wrapper(*args, **kwargs):
with warnings.catch_warnings():
for cls in [DeprecationWarning, PendingDeprecationWa... | [
"def",
"allow_implicit_stop",
"(",
"gen_func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"gen_func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"for",
"cls"... | 34.5 | 0.001282 |
def _pdf_find_urls(bytes, mimetype):
""" This function finds URLs inside of PDF bytes. """
# Start with only the ASCII bytes. Limit it to 12+ character strings.
try:
ascii_bytes = b' '.join(re.compile(b'[\x00\x09\x0A\x0D\x20-\x7E]{12,}').findall(bytes))
ascii_bytes = ascii_bytes.replace(b'\... | [
"def",
"_pdf_find_urls",
"(",
"bytes",
",",
"mimetype",
")",
":",
"# Start with only the ASCII bytes. Limit it to 12+ character strings.",
"try",
":",
"ascii_bytes",
"=",
"b' '",
".",
"join",
"(",
"re",
".",
"compile",
"(",
"b'[\\x00\\x09\\x0A\\x0D\\x20-\\x7E]{12,}'",
")"... | 38.419355 | 0.015561 |
def xinfo_help(self):
"""Retrieve help regarding the ``XINFO`` sub-commands"""
fut = self.execute(b'XINFO', b'HELP')
return wait_convert(fut, lambda l: b'\n'.join(l)) | [
"def",
"xinfo_help",
"(",
"self",
")",
":",
"fut",
"=",
"self",
".",
"execute",
"(",
"b'XINFO'",
",",
"b'HELP'",
")",
"return",
"wait_convert",
"(",
"fut",
",",
"lambda",
"l",
":",
"b'\\n'",
".",
"join",
"(",
"l",
")",
")"
] | 46.75 | 0.010526 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.