text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def cancel(self):
"""Cancel a running :meth:`iterconsume` session."""
for consumer_tag in self._open_consumers.values():
try:
self.backend.cancel(consumer_tag)
except KeyError:
pass
self._open_consumers.clear() | [
"def",
"cancel",
"(",
"self",
")",
":",
"for",
"consumer_tag",
"in",
"self",
".",
"_open_consumers",
".",
"values",
"(",
")",
":",
"try",
":",
"self",
".",
"backend",
".",
"cancel",
"(",
"consumer_tag",
")",
"except",
"KeyError",
":",
"pass",
"self",
"... | 35.375 | 13.75 |
def run_tfba(self, reaction):
"""Run FBA and tFBA on model."""
solver = self._get_solver(integer=True)
p = fluxanalysis.FluxBalanceProblem(self._mm, solver)
start_time = time.time()
p.add_thermodynamic()
try:
p.maximize(reaction)
except fluxanalysi... | [
"def",
"run_tfba",
"(",
"self",
",",
"reaction",
")",
":",
"solver",
"=",
"self",
".",
"_get_solver",
"(",
"integer",
"=",
"True",
")",
"p",
"=",
"fluxanalysis",
".",
"FluxBalanceProblem",
"(",
"self",
".",
"_mm",
",",
"solver",
")",
"start_time",
"=",
... | 28.6 | 19.4 |
def _wrap_ele(self, block, view, frag, extra_data=None):
"""
Does the guts of the wrapping the same way for both xblocks and asides. Their
wrappers provide other info in extra_data which gets put into the dom data- attrs.
"""
wrapped = Fragment()
data = {
'usa... | [
"def",
"_wrap_ele",
"(",
"self",
",",
"block",
",",
"view",
",",
"frag",
",",
"extra_data",
"=",
"None",
")",
":",
"wrapped",
"=",
"Fragment",
"(",
")",
"data",
"=",
"{",
"'usage'",
":",
"block",
".",
"scope_ids",
".",
"usage_id",
",",
"'block-type'",
... | 40.119048 | 22.404762 |
def twenty_five_neurons_mix_stimulated():
"Object allocation"
"If M = 0 then only object will be allocated"
params = pcnn_parameters();
params.AF = 0.1;
params.AL = 0.0;
params.AT = 0.7;
params.VF = 1.0;
params.VL = 1.0;
params.VT = 10.0;
params.M = 0.0;
... | [
"def",
"twenty_five_neurons_mix_stimulated",
"(",
")",
":",
"\"If M = 0 then only object will be allocated\"",
"params",
"=",
"pcnn_parameters",
"(",
")",
"params",
".",
"AF",
"=",
"0.1",
"params",
".",
"AL",
"=",
"0.0",
"params",
".",
"AT",
"=",
"0.7",
"params",
... | 33.222222 | 18.444444 |
def dtrajs(self):
""" get discrete trajectories """
if not self._estimated:
self.logger.info("not yet parametrized, running now.")
self.parametrize()
return self._chain[-1].dtrajs | [
"def",
"dtrajs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_estimated",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"not yet parametrized, running now.\"",
")",
"self",
".",
"parametrize",
"(",
")",
"return",
"self",
".",
"_chain",
"[",
"-",
... | 37 | 11.833333 |
def tlv_parse(data):
""" Parses a bytestring of TLV values into a dict with the tags as keys."""
parsed = {}
while data:
t, l, data = ord_byte(data[0]), ord_byte(data[1]), data[2:]
parsed[t], data = data[:l], data[l:]
return parsed | [
"def",
"tlv_parse",
"(",
"data",
")",
":",
"parsed",
"=",
"{",
"}",
"while",
"data",
":",
"t",
",",
"l",
",",
"data",
"=",
"ord_byte",
"(",
"data",
"[",
"0",
"]",
")",
",",
"ord_byte",
"(",
"data",
"[",
"1",
"]",
")",
",",
"data",
"[",
"2",
... | 36.714286 | 17.714286 |
def reset_spyder(self):
"""
Quit and reset Spyder and then Restart application.
"""
answer = QMessageBox.warning(self, _("Warning"),
_("Spyder will restart and reset to default settings: <br><br>"
"Do you want to continue?"),
QMessageBox.Ye... | [
"def",
"reset_spyder",
"(",
"self",
")",
":",
"answer",
"=",
"QMessageBox",
".",
"warning",
"(",
"self",
",",
"_",
"(",
"\"Warning\"",
")",
",",
"_",
"(",
"\"Spyder will restart and reset to default settings: <br><br>\"",
"\"Do you want to continue?\"",
")",
",",
"Q... | 40.7 | 10.7 |
def find_first_wt_parent(self, with_ip=False):
"""
Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns
a parent Biosample ID if its wild_type attribute is True.
Args:
with_ip: `bool`. True means to restrict the search to the firs... | [
"def",
"find_first_wt_parent",
"(",
"self",
",",
"with_ip",
"=",
"False",
")",
":",
"parent_id",
"=",
"self",
".",
"part_of_id",
"if",
"not",
"parent_id",
":",
"return",
"False",
"parent",
"=",
"Biosample",
"(",
"parent_id",
")",
"if",
"parent",
".",
"wild... | 46.074074 | 24.074074 |
async def result(self) -> T:
"""\
Wait for the task's termination; either the result is returned or a raised exception is reraised.
If an event is sent before the task terminates, an `EventException` is raised with the event as argument.
"""
try:
event = await self.re... | [
"async",
"def",
"result",
"(",
"self",
")",
"->",
"T",
":",
"try",
":",
"event",
"=",
"await",
"self",
".",
"recv_event",
"(",
")",
"except",
"Component",
".",
"Success",
"as",
"succ",
":",
"# success was thrown; return the result",
"result",
",",
"=",
"su... | 43.666667 | 18.944444 |
def _from_record(data):
"""
Infer a BigQuery table schema from a list of fields or a dictionary. The typeof the elements
is used. For a list, the field names are simply 'Column1', 'Column2', etc.
Args:
data: The list of fields or dictionary.
Returns:
A list of dictionaries containing fi... | [
"def",
"_from_record",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"return",
"Schema",
".",
"_from_dict_record",
"(",
"data",
")",
"elif",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"return",
"Schema",
".",
"_f... | 37.882353 | 21.176471 |
def copy_path(self):
"""Return a copy of the current path.
:returns:
A list of ``(path_operation, coordinates)`` tuples
of a :ref:`PATH_OPERATION` string
and a tuple of floats coordinates
whose content depends on the operation type:
* :obj:`M... | [
"def",
"copy_path",
"(",
"self",
")",
":",
"path",
"=",
"cairo",
".",
"cairo_copy_path",
"(",
"self",
".",
"_pointer",
")",
"result",
"=",
"list",
"(",
"_iter_path",
"(",
"path",
")",
")",
"cairo",
".",
"cairo_path_destroy",
"(",
"path",
")",
"return",
... | 37.6 | 17.3 |
def get_photos_info(photoset_id):
"""Request the photos information with the photoset id
:param photoset_id: The photoset id of flickr
:type photoset_id: str
:return: photos information
:rtype: list
"""
args = _get_request_args(
'flickr.photosets.getPhotos',
photoset_id=phot... | [
"def",
"get_photos_info",
"(",
"photoset_id",
")",
":",
"args",
"=",
"_get_request_args",
"(",
"'flickr.photosets.getPhotos'",
",",
"photoset_id",
"=",
"photoset_id",
")",
"resp",
"=",
"requests",
".",
"post",
"(",
"API_URL",
",",
"data",
"=",
"args",
")",
"re... | 29.764706 | 12.764706 |
def _spawn_thread(self, target):
""" Create a thread """
t = Thread(target=target)
t.daemon = True
t.start()
return t | [
"def",
"_spawn_thread",
"(",
"self",
",",
"target",
")",
":",
"t",
"=",
"Thread",
"(",
"target",
"=",
"target",
")",
"t",
".",
"daemon",
"=",
"True",
"t",
".",
"start",
"(",
")",
"return",
"t"
] | 25.333333 | 13.166667 |
def _is_url_like_archive(url):
# type: (str) -> bool
"""Return whether the URL looks like an archive.
"""
filename = Link(url).filename
for bad_ext in ARCHIVE_EXTENSIONS:
if filename.endswith(bad_ext):
return True
return False | [
"def",
"_is_url_like_archive",
"(",
"url",
")",
":",
"# type: (str) -> bool",
"filename",
"=",
"Link",
"(",
"url",
")",
".",
"filename",
"for",
"bad_ext",
"in",
"ARCHIVE_EXTENSIONS",
":",
"if",
"filename",
".",
"endswith",
"(",
"bad_ext",
")",
":",
"return",
... | 29.111111 | 8.555556 |
def geo_haystack(self, name, bucket_size):
""" Create a Haystack index. See:
http://www.mongodb.org/display/DOCS/Geospatial+Haystack+Indexing
:param name: Name of the indexed column
:param bucket_size: Size of the haystack buckets (see mongo docs)
"""
self.c... | [
"def",
"geo_haystack",
"(",
"self",
",",
"name",
",",
"bucket_size",
")",
":",
"self",
".",
"components",
".",
"append",
"(",
"(",
"name",
",",
"'geoHaystack'",
")",
")",
"self",
".",
"__bucket_size",
"=",
"bucket_size",
"return",
"self"
] | 41.1 | 16 |
def GetDateRange(self):
"""Return the range over which this ServicePeriod is valid.
The range includes exception dates that add service outside of
(start_date, end_date), but doesn't shrink the range if exception
dates take away service at the edges of the range.
Returns:
A tuple of "YYYYMMD... | [
"def",
"GetDateRange",
"(",
"self",
")",
":",
"start",
"=",
"self",
".",
"start_date",
"end",
"=",
"self",
".",
"end_date",
"for",
"date",
",",
"(",
"exception_type",
",",
"_",
")",
"in",
"self",
".",
"date_exceptions",
".",
"items",
"(",
")",
":",
"... | 31.962963 | 20.555556 |
def getVersionString():
"""
Function return string with version information.
It is performed by use one of three procedures: git describe,
file in .git dir and file __VERSION__.
"""
version_string = None
try:
version_string = subprocess.check_output(['git', 'describe'])
except:
... | [
"def",
"getVersionString",
"(",
")",
":",
"version_string",
"=",
"None",
"try",
":",
"version_string",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'git'",
",",
"'describe'",
"]",
")",
"except",
":",
"logger",
".",
"warning",
"(",
"'Command \"git describ... | 35.393939 | 20.30303 |
def unified_load(namespace, subclasses=None, recurse=False):
"""Provides a unified interface to both the module and class loaders,
finding modules by default or classes if given a ``subclasses`` parameter.
"""
if subclasses is not None:
return ClassLoader(recurse=recurse).load(namespace, subcla... | [
"def",
"unified_load",
"(",
"namespace",
",",
"subclasses",
"=",
"None",
",",
"recurse",
"=",
"False",
")",
":",
"if",
"subclasses",
"is",
"not",
"None",
":",
"return",
"ClassLoader",
"(",
"recurse",
"=",
"recurse",
")",
".",
"load",
"(",
"namespace",
",... | 44.333333 | 22.333333 |
def _lmder1_linear_full_rank(n, m, factor, target_fnorm1, target_fnorm2):
"""A full-rank linear function (lmder test #1)"""
def func(params, vec):
s = params.sum()
temp = 2. * s / m + 1
vec[:] = -temp
vec[:params.size] += params
def jac(params, jac):
# jac.shape = (... | [
"def",
"_lmder1_linear_full_rank",
"(",
"n",
",",
"m",
",",
"factor",
",",
"target_fnorm1",
",",
"target_fnorm2",
")",
":",
"def",
"func",
"(",
"params",
",",
"vec",
")",
":",
"s",
"=",
"params",
".",
"sum",
"(",
")",
"temp",
"=",
"2.",
"*",
"s",
"... | 28.285714 | 16.904762 |
def returnOrderBook(self, currencyPair='all', depth='50'):
"""Returns the order book for a given market, as well as a sequence
number for use with the Push API and an indicator specifying whether
the market is frozen. You may set currencyPair to "all" to get the
order books of all market... | [
"def",
"returnOrderBook",
"(",
"self",
",",
"currencyPair",
"=",
"'all'",
",",
"depth",
"=",
"'50'",
")",
":",
"return",
"self",
".",
"_public",
"(",
"'returnOrderBook'",
",",
"currencyPair",
"=",
"currencyPair",
",",
"depth",
"=",
"depth",
")"
] | 62 | 17.285714 |
def group_primers(self, my_list):
"""Group elements in list by certain number 'n'"""
new_list = []
n = 2
for i in range(0, len(my_list), n):
grouped_primers = my_list[i:i + n]
forward_primer = grouped_primers[0].split(" ")
reverse_primer = grouped_prim... | [
"def",
"group_primers",
"(",
"self",
",",
"my_list",
")",
":",
"new_list",
"=",
"[",
"]",
"n",
"=",
"2",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"my_list",
")",
",",
"n",
")",
":",
"grouped_primers",
"=",
"my_list",
"[",
"i",
":",
... | 48.5 | 18.666667 |
def info(self, params=None):
''' /v1/account/info
GET - account
Retrieve information about the current account
Link: https://www.vultr.com/api/#account_info
'''
params = params if params else dict()
return self.request('/v1/account/info', params, 'GET') | [
"def",
"info",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"params",
"if",
"params",
"else",
"dict",
"(",
")",
"return",
"self",
".",
"request",
"(",
"'/v1/account/info'",
",",
"params",
",",
"'GET'",
")"
] | 33.555556 | 18.444444 |
def get_request_message(cls, remote_info): # pylint: disable=g-bad-name
"""Gets request message or container from remote info.
Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.
Returns:
Either an instance of the request type from the remote ... | [
"def",
"get_request_message",
"(",
"cls",
",",
"remote_info",
")",
":",
"# pylint: disable=g-bad-name",
"if",
"remote_info",
"in",
"cls",
".",
"__remote_info_cache",
":",
"return",
"cls",
".",
"__remote_info_cache",
"[",
"remote_info",
"]",
"else",
":",
"return",
... | 35.666667 | 21.866667 |
def perform_edit_extension_draft_operation(self, draft_patch, publisher_name, extension_name, draft_id):
"""PerformEditExtensionDraftOperation.
[Preview API]
:param :class:`<ExtensionDraftPatch> <azure.devops.v5_1.gallery.models.ExtensionDraftPatch>` draft_patch:
:param str publisher_nam... | [
"def",
"perform_edit_extension_draft_operation",
"(",
"self",
",",
"draft_patch",
",",
"publisher_name",
",",
"extension_name",
",",
"draft_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"publisher_name",
"is",
"not",
"None",
":",
"route_values",
"[",
"'publi... | 57.826087 | 24.913043 |
def cpu_and_memory(programs, items):
"""Retrieve CPU and memory/core specified in configuration input.
"""
assert len(items) > 0, "Finding job resources but no items to process"
config = items[0]["config"]
all_cores = []
all_memory = []
algs = [config_utils.get_algorithm_config(x) for x in i... | [
"def",
"cpu_and_memory",
"(",
"programs",
",",
"items",
")",
":",
"assert",
"len",
"(",
"items",
")",
">",
"0",
",",
"\"Finding job resources but no items to process\"",
"config",
"=",
"items",
"[",
"0",
"]",
"[",
"\"config\"",
"]",
"all_cores",
"=",
"[",
"]... | 39.461538 | 14.615385 |
def is_transition_matrix(T, tol=1e-12):
r"""Check if the given matrix is a transition matrix.
Parameters
----------
T : (M, M) ndarray or scipy.sparse matrix
Matrix to check
tol : float (optional)
Floating point tolerance to check with
Returns
-------
is_transition_matr... | [
"def",
"is_transition_matrix",
"(",
"T",
",",
"tol",
"=",
"1e-12",
")",
":",
"T",
"=",
"_types",
".",
"ensure_ndarray_or_sparse",
"(",
"T",
",",
"ndim",
"=",
"2",
",",
"uniform",
"=",
"True",
",",
"kind",
"=",
"'numeric'",
")",
"if",
"_issparse",
"(",
... | 29.317073 | 23.804878 |
def _handle_request(self, request: dict) -> dict:
"""Processes Alexa requests from skill server and returns responses to Alexa.
Args:
request: Dict with Alexa request payload and metadata.
Returns:
result: Alexa formatted or error response.
"""
request_bo... | [
"def",
"_handle_request",
"(",
"self",
",",
"request",
":",
"dict",
")",
"->",
"dict",
":",
"request_body",
":",
"bytes",
"=",
"request",
"[",
"'request_body'",
"]",
"signature_chain_url",
":",
"str",
"=",
"request",
"[",
"'signature_chain_url'",
"]",
"signatu... | 43.468085 | 26.148936 |
def tensor(self, field_name, tensor_ind):
""" Returns the tensor for a given field and tensor index.
Parameters
----------
field_name : str
the name of the field to load
tensor_index : int
the index of the tensor
Returns
-------
:... | [
"def",
"tensor",
"(",
"self",
",",
"field_name",
",",
"tensor_ind",
")",
":",
"if",
"tensor_ind",
"==",
"self",
".",
"_tensor_cache_file_num",
"[",
"field_name",
"]",
":",
"return",
"self",
".",
"_tensors",
"[",
"field_name",
"]",
"filename",
"=",
"self",
... | 34.545455 | 16.318182 |
def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x):
"""Give the first value that satisfies the key test.
Args:
seq (iterable):
key (callable): test for each element of iterable
default: returned when all elements fail test
apply (callable): applied to element... | [
"def",
"first",
"(",
"seq",
",",
"key",
"=",
"lambda",
"x",
":",
"bool",
"(",
"x",
")",
",",
"default",
"=",
"None",
",",
"apply",
"=",
"lambda",
"x",
":",
"x",
")",
":",
"return",
"next",
"(",
"(",
"apply",
"(",
"x",
")",
"for",
"x",
"in",
... | 36.612903 | 26.645161 |
def _init_metadata(self):
"""stub"""
self._learning_objective_id_metadata = {
'element_id': Id(self.my_osid_object_form._authority,
self.my_osid_object_form._namespace,
'learning_objective_id'),
'element_label': 'Learning ... | [
"def",
"_init_metadata",
"(",
"self",
")",
":",
"self",
".",
"_learning_objective_id_metadata",
"=",
"{",
"'element_id'",
":",
"Id",
"(",
"self",
".",
"my_osid_object_form",
".",
"_authority",
",",
"self",
".",
"my_osid_object_form",
".",
"_namespace",
",",
"'le... | 39.666667 | 15.533333 |
def _call_func_bc(nargs, idx, ops, keys):
"""
Implements transformation of CALL_FUNCTION bc inst to Rapids expression.
The implementation follows definition of behavior defined in
https://docs.python.org/3/library/dis.html
:param nargs: number of arguments including keyword and positional argum... | [
"def",
"_call_func_bc",
"(",
"nargs",
",",
"idx",
",",
"ops",
",",
"keys",
")",
":",
"named_args",
"=",
"{",
"}",
"unnamed_args",
"=",
"[",
"]",
"args",
"=",
"[",
"]",
"# Extract arguments based on calling convention for CALL_FUNCTION_KW",
"while",
"nargs",
">",... | 41.3 | 17.25 |
def gatk_filter_rnaseq(vrn_file, data):
"""
this incorporates filters listed here, dropping clusters of variants
within a 35 nucleotide window, high fischer strand values and low
quality by depth
https://software.broadinstitute.org/gatk/guide/article?id=3891
java -jar GenomeAnalysisTK.jar -T Var... | [
"def",
"gatk_filter_rnaseq",
"(",
"vrn_file",
",",
"data",
")",
":",
"out_file",
"=",
"\"%s-filter%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"vrn_file",
")",
"if",
"not",
"file_exists",
"(",
"out_file",
")",
":",
"ref_file",
"=",
"dd",
".",
"get_ref_fil... | 51.096774 | 16.774194 |
def uniform_partition_fromintv(intv_prod, shape, nodes_on_bdry=False):
"""Return a partition of an interval product into equally sized cells.
Parameters
----------
intv_prod : `IntervalProd`
Interval product to be partitioned
shape : int or sequence of ints
Number of nodes per axis.... | [
"def",
"uniform_partition_fromintv",
"(",
"intv_prod",
",",
"shape",
",",
"nodes_on_bdry",
"=",
"False",
")",
":",
"grid",
"=",
"uniform_grid_fromintv",
"(",
"intv_prod",
",",
"shape",
",",
"nodes_on_bdry",
"=",
"nodes_on_bdry",
")",
"return",
"RectPartition",
"("... | 37.46875 | 19.390625 |
def similar(names=None, ids=None, start=0, results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None,
max_hotttnesss=None, min_hotttnesss=None, seed_catalog=None,artist_start_year_before=None, \
artist_start_year_after=None,artist_end_year_before=None,artist_end_year_afte... | [
"def",
"similar",
"(",
"names",
"=",
"None",
",",
"ids",
"=",
"None",
",",
"start",
"=",
"0",
",",
"results",
"=",
"15",
",",
"buckets",
"=",
"None",
",",
"limit",
"=",
"False",
",",
"max_familiarity",
"=",
"None",
",",
"min_familiarity",
"=",
"None"... | 37.546512 | 26.988372 |
def generic_http_header_parser_for(header_name):
"""
A parser factory to extract the request id from an HTTP header
:return: A parser that can be used to extract the request id from the current request context
:rtype: ()->str|None
"""
def parser():
request_id = request.headers.get(heade... | [
"def",
"generic_http_header_parser_for",
"(",
"header_name",
")",
":",
"def",
"parser",
"(",
")",
":",
"request_id",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"header_name",
",",
"''",
")",
".",
"strip",
"(",
")",
"if",
"not",
"request_id",
":",
"... | 31.6 | 21.066667 |
def register (type, suffixes = [], base_type = None):
""" Registers a target type, possibly derived from a 'base-type'.
If 'suffixes' are provided, they list all the suffixes that mean a file is of 'type'.
Also, the first element gives the suffix to be used when constructing and object of
't... | [
"def",
"register",
"(",
"type",
",",
"suffixes",
"=",
"[",
"]",
",",
"base_type",
"=",
"None",
")",
":",
"# Type names cannot contain hyphens, because when used as",
"# feature-values they will be interpreted as composite features",
"# which need to be decomposed.",
"if",
"__re... | 44.140351 | 22.070175 |
def ffconvert(fname, limit_states, ff, min_iml=1E-10):
"""
Convert a fragility function into a numpy array plus a bunch
of attributes.
:param fname: path to the fragility model file
:param limit_states: expected limit states
:param ff: fragility function node
:returns: a pair (array, dictio... | [
"def",
"ffconvert",
"(",
"fname",
",",
"limit_states",
",",
"ff",
",",
"min_iml",
"=",
"1E-10",
")",
":",
"with",
"context",
"(",
"fname",
",",
"ff",
")",
":",
"ffs",
"=",
"ff",
"[",
"1",
":",
"]",
"imls",
"=",
"ff",
".",
"imls",
"nodamage",
"=",... | 42.439394 | 13.924242 |
def _load_pretrained_tok2vec(nlp, loc):
"""Load pre-trained weights for the 'token-to-vector' part of the component
models, which is typically a CNN. See 'spacy pretrain'. Experimental.
"""
with loc.open("rb") as file_:
weights_data = file_.read()
loaded = []
for name, component in nlp.p... | [
"def",
"_load_pretrained_tok2vec",
"(",
"nlp",
",",
"loc",
")",
":",
"with",
"loc",
".",
"open",
"(",
"\"rb\"",
")",
"as",
"file_",
":",
"weights_data",
"=",
"file_",
".",
"read",
"(",
")",
"loaded",
"=",
"[",
"]",
"for",
"name",
",",
"component",
"i... | 41.833333 | 13 |
def gen_goal(self, y_des):
"""Generate the goal for path imitation.
For rhythmic DMPs the goal is the average of the
desired trajectory.
y_des np.array: the desired trajectory to follow
"""
goal = np.zeros(self.dmps)
for n in range(self.dmps):
... | [
"def",
"gen_goal",
"(",
"self",
",",
"y_des",
")",
":",
"goal",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"dmps",
")",
"for",
"n",
"in",
"range",
"(",
"self",
".",
"dmps",
")",
":",
"num_idx",
"=",
"~",
"np",
".",
"isnan",
"(",
"y_des",
"[",
... | 33.4 | 18.066667 |
def full_name(self):
"""
You can get full name of user.
:return: str
"""
full_name = self.first_name
if self.last_name:
full_name += ' ' + self.last_name
return full_name | [
"def",
"full_name",
"(",
"self",
")",
":",
"full_name",
"=",
"self",
".",
"first_name",
"if",
"self",
".",
"last_name",
":",
"full_name",
"+=",
"' '",
"+",
"self",
".",
"last_name",
"return",
"full_name"
] | 23 | 12.2 |
def init_app(self, app):
"""Init app with Flask instance.
You can also pass the instance of Flask later::
oauth = OAuth()
oauth.init_app(app)
"""
self.app = app
app.extensions = getattr(app, 'extensions', {})
app.extensions[self.state_key] = self | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"self",
".",
"app",
"=",
"app",
"app",
".",
"extensions",
"=",
"getattr",
"(",
"app",
",",
"'extensions'",
",",
"{",
"}",
")",
"app",
".",
"extensions",
"[",
"self",
".",
"state_key",
"]",
"=",
... | 28.181818 | 15.545455 |
def get_cycles(graph_dict, vertices=None):
"""given a dictionary representing an ordered graph (i.e. key are vertices
and values is a list of destination vertices representing edges), return a
list of detected cycles
"""
if not graph_dict:
return ()
result = []
if vertices is None:
... | [
"def",
"get_cycles",
"(",
"graph_dict",
",",
"vertices",
"=",
"None",
")",
":",
"if",
"not",
"graph_dict",
":",
"return",
"(",
")",
"result",
"=",
"[",
"]",
"if",
"vertices",
"is",
"None",
":",
"vertices",
"=",
"graph_dict",
".",
"keys",
"(",
")",
"f... | 34.615385 | 14.846154 |
def json(cls, message):
""" Print a nice JSON output
Args:
message: the message to print
"""
if type(message) is OrderedDict:
pprint(dict(message))
else:
pprint(message) | [
"def",
"json",
"(",
"cls",
",",
"message",
")",
":",
"if",
"type",
"(",
"message",
")",
"is",
"OrderedDict",
":",
"pprint",
"(",
"dict",
"(",
"message",
")",
")",
"else",
":",
"pprint",
"(",
"message",
")"
] | 22.272727 | 15.636364 |
def dinfdistdown(np, ang, fel, slp, src, statsm, distm, edgecontamination, wg, dist,
workingdir=None, mpiexedir=None, exedir=None,
log_file=None, runtime_file=None, hostfile=None):
"""Run D-inf distance down to stream"""
in_params = {'-m': '%s %s' % (TauDEM.conv... | [
"def",
"dinfdistdown",
"(",
"np",
",",
"ang",
",",
"fel",
",",
"slp",
",",
"src",
",",
"statsm",
",",
"distm",
",",
"edgecontamination",
",",
"wg",
",",
"dist",
",",
"workingdir",
"=",
"None",
",",
"mpiexedir",
"=",
"None",
",",
"exedir",
"=",
"None"... | 63.875 | 24.9375 |
def to_datetime(timestamp):
"""Return datetime object from timestamp."""
return dt.fromtimestamp(time.mktime(
time.localtime(int(str(timestamp)[:10])))) | [
"def",
"to_datetime",
"(",
"timestamp",
")",
":",
"return",
"dt",
".",
"fromtimestamp",
"(",
"time",
".",
"mktime",
"(",
"time",
".",
"localtime",
"(",
"int",
"(",
"str",
"(",
"timestamp",
")",
"[",
":",
"10",
"]",
")",
")",
")",
")"
] | 41.25 | 5.75 |
def new_calendar(self, calendar_name):
""" Creates a new calendar
:param str calendar_name: name of the new calendar
:return: a new Calendar instance
:rtype: Calendar
"""
if not calendar_name:
return None
url = self.build_url(self._endpoints.get('roo... | [
"def",
"new_calendar",
"(",
"self",
",",
"calendar_name",
")",
":",
"if",
"not",
"calendar_name",
":",
"return",
"None",
"url",
"=",
"self",
".",
"build_url",
"(",
"self",
".",
"_endpoints",
".",
"get",
"(",
"'root_calendars'",
")",
")",
"response",
"=",
... | 32.47619 | 21.666667 |
def _sizer_add(self, child):
"called when adding a control to the window"
if self.sizer:
if DEBUG: print "adding to sizer:", child.name
border = None
if not border:
border = child.sizer_border
flags = child._sizer_flags
... | [
"def",
"_sizer_add",
"(",
"self",
",",
"child",
")",
":",
"if",
"self",
".",
"sizer",
":",
"if",
"DEBUG",
":",
"print",
"\"adding to sizer:\"",
",",
"child",
".",
"name",
"border",
"=",
"None",
"if",
"not",
"border",
":",
"border",
"=",
"child",
".",
... | 44.111111 | 14.888889 |
def _drawContents(self, currentRti=None):
""" Draws the attributes of the currentRTI
"""
table = self.table
table.setUpdatesEnabled(False)
try:
table.clearContents()
verticalHeader = table.verticalHeader()
verticalHeader.setSectionResizeMode(Qt... | [
"def",
"_drawContents",
"(",
"self",
",",
"currentRti",
"=",
"None",
")",
":",
"table",
"=",
"self",
".",
"table",
"table",
".",
"setUpdatesEnabled",
"(",
"False",
")",
"try",
":",
"table",
".",
"clearContents",
"(",
")",
"verticalHeader",
"=",
"table",
... | 39.59375 | 18.875 |
def disk_check_size(ctx, param, value):
""" Validation callback for disk size parameter."""
if value:
# if we've got a prefix
if isinstance(value, tuple):
val = value[1]
else:
val = value
if val % 1024:
raise click.ClickException('Size must be ... | [
"def",
"disk_check_size",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"if",
"value",
":",
"# if we've got a prefix",
"if",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"val",
"=",
"value",
"[",
"1",
"]",
"else",
":",
"val",
"=",
"value",
... | 31.636364 | 15.909091 |
def relative_abundance(coverage):
"""
cov = number of bases / length of genome
relative abundance = [(cov) / sum(cov for all genomes)] * 100
"""
relative = {}
sums = []
for genome in coverage:
for cov in coverage[genome]:
sums.append(0)
break
for genome in coverage:
index = 0
for cov in coverage[geno... | [
"def",
"relative_abundance",
"(",
"coverage",
")",
":",
"relative",
"=",
"{",
"}",
"sums",
"=",
"[",
"]",
"for",
"genome",
"in",
"coverage",
":",
"for",
"cov",
"in",
"coverage",
"[",
"genome",
"]",
":",
"sums",
".",
"append",
"(",
"0",
")",
"break",
... | 22.461538 | 18.153846 |
def delete(self):
"""
Wraps the standard delete() method to catch expected exceptions and
raise the appropriate pyrax exceptions.
"""
try:
return super(CloudNetwork, self).delete()
except exc.Forbidden as e:
# Network is in use
raise ex... | [
"def",
"delete",
"(",
"self",
")",
":",
"try",
":",
"return",
"super",
"(",
"CloudNetwork",
",",
"self",
")",
".",
"delete",
"(",
")",
"except",
"exc",
".",
"Forbidden",
"as",
"e",
":",
"# Network is in use",
"raise",
"exc",
".",
"NetworkInUse",
"(",
"... | 37.2 | 16.2 |
def _amIdoneIterating(self, f_k_new, relative_tolerance, iteration, maximum_iterations, print_warning, verbose):
"""
Convenience function to test whether we are done iterating, same for all iteration types
REQUIRED ARGUMENTS
f_k_new (array): new free energies
f_k (array) : o... | [
"def",
"_amIdoneIterating",
"(",
"self",
",",
"f_k_new",
",",
"relative_tolerance",
",",
"iteration",
",",
"maximum_iterations",
",",
"print_warning",
",",
"verbose",
")",
":",
"yesIam",
"=",
"False",
"# Compute change from old to new estimate.",
"Delta_f_k",
"=",
"f_... | 42.786885 | 24.819672 |
def get_parent_dept_path(self):
"""Method to get the department list"""
self.logger.info("%s\t%s" % (self.request_method, self.request_url))
return self.json_response.get("parentIds", None) | [
"def",
"get_parent_dept_path",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"info",
"(",
"\"%s\\t%s\"",
"%",
"(",
"self",
".",
"request_method",
",",
"self",
".",
"request_url",
")",
")",
"return",
"self",
".",
"json_response",
".",
"get",
"(",
"\"... | 53.25 | 15.25 |
def visit_Import(self, node):
""" Check if imported module exists in MODULES. """
for alias in node.names:
current_module = MODULES
# Recursive check for submodules
for path in alias.name.split('.'):
if path not in current_module:
r... | [
"def",
"visit_Import",
"(",
"self",
",",
"node",
")",
":",
"for",
"alias",
"in",
"node",
".",
"names",
":",
"current_module",
"=",
"MODULES",
"# Recursive check for submodules",
"for",
"path",
"in",
"alias",
".",
"name",
".",
"split",
"(",
"'.'",
")",
":",... | 42.583333 | 9.833333 |
def get_environment(self):
"""
Get environment facts.
power and fan are currently not implemented
cpu is using 1-minute average
cpu hard-coded to cpu0 (i.e. only a single CPU)
"""
environment = {}
cpu_cmd = "show proc cpu"
mem_cmd = "show memory s... | [
"def",
"get_environment",
"(",
"self",
")",
":",
"environment",
"=",
"{",
"}",
"cpu_cmd",
"=",
"\"show proc cpu\"",
"mem_cmd",
"=",
"\"show memory statistics\"",
"temp_cmd",
"=",
"\"show env temperature status\"",
"output",
"=",
"self",
".",
"_send_command",
"(",
"c... | 42.697368 | 15.697368 |
def main(custom_commandline=None):
"""
Main function for esptool
custom_commandline - Optional override for default arguments parsing (that uses sys.argv), can be a list of custom arguments
as strings. Arguments and their values need to be added as individual items to the list e.g. "-b 115200" thus
... | [
"def",
"main",
"(",
"custom_commandline",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'esptool.py v%s - ESP8266 ROM Bootloader Utility'",
"%",
"__version__",
",",
"prog",
"=",
"'esptool'",
")",
"parser",
".",
... | 45.377522 | 28 |
def start_transports(self):
"""start thread transports."""
self.transport = Transport(
self.queue, self.batch_size, self.batch_interval,
self.session_factory)
thread = threading.Thread(target=self.transport.loop)
self.threads.append(thread)
thread.daemon =... | [
"def",
"start_transports",
"(",
"self",
")",
":",
"self",
".",
"transport",
"=",
"Transport",
"(",
"self",
".",
"queue",
",",
"self",
".",
"batch_size",
",",
"self",
".",
"batch_interval",
",",
"self",
".",
"session_factory",
")",
"thread",
"=",
"threading... | 37.777778 | 11.333333 |
def _combine_arglist(self, args, kwargs):
"""Combine the default values and the supplied values."""
gmxargs = self.gmxargs.copy()
gmxargs.update(self._combineargs(*args, **kwargs))
return (), gmxargs | [
"def",
"_combine_arglist",
"(",
"self",
",",
"args",
",",
"kwargs",
")",
":",
"gmxargs",
"=",
"self",
".",
"gmxargs",
".",
"copy",
"(",
")",
"gmxargs",
".",
"update",
"(",
"self",
".",
"_combineargs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
... | 45.4 | 7.2 |
def UpdateUser(username, password=None, is_admin=False):
"""Updates the password or privilege-level for a user."""
user_type, password = _GetUserTypeAndPassword(
username, password=password, is_admin=is_admin)
grr_api = maintenance_utils.InitGRRRootAPI()
grr_user = grr_api.GrrUser(username).Get()
grr_us... | [
"def",
"UpdateUser",
"(",
"username",
",",
"password",
"=",
"None",
",",
"is_admin",
"=",
"False",
")",
":",
"user_type",
",",
"password",
"=",
"_GetUserTypeAndPassword",
"(",
"username",
",",
"password",
"=",
"password",
",",
"is_admin",
"=",
"is_admin",
")... | 51.857143 | 9.142857 |
def values(self, corr_plus, corr_cross, snrv, psd,
indices, template_plus, template_cross, u_vals,
hplus_cross_corr, hpnorm, hcnorm):
""" Calculate the chisq at points given by indices.
Returns
-------
chisq: Array
Chisq values, one for each sam... | [
"def",
"values",
"(",
"self",
",",
"corr_plus",
",",
"corr_cross",
",",
"snrv",
",",
"psd",
",",
"indices",
",",
"template_plus",
",",
"template_cross",
",",
"u_vals",
",",
"hplus_cross_corr",
",",
"hpnorm",
",",
"hcnorm",
")",
":",
"if",
"self",
".",
"d... | 45.366667 | 19.7 |
def __draw_constant_line(self, value_label_style):
"Draw a constant line on the y-axis with the label"
value, label, style = value_label_style
start = self.transform_output_coordinates((0, value))[1]
stop = self.graph_width
path = etree.SubElement(self.graph, 'path', {
'd': 'M 0 %(start)s h%(stop)s' % loca... | [
"def",
"__draw_constant_line",
"(",
"self",
",",
"value_label_style",
")",
":",
"value",
",",
"label",
",",
"style",
"=",
"value_label_style",
"start",
"=",
"self",
".",
"transform_output_coordinates",
"(",
"(",
"0",
",",
"value",
")",
")",
"[",
"1",
"]",
... | 34.466667 | 13.666667 |
def __complete_info_dict(self, node_info_dict, is_open):
# Make pika credentials
creds = pika.PlainCredentials(
node_info_dict['username'],
node_info_dict['password']
)
node_info_dict['credentials'] = creds
if 'priority' in node_info_dict and node_info_di... | [
"def",
"__complete_info_dict",
"(",
"self",
",",
"node_info_dict",
",",
"is_open",
")",
":",
"# Make pika credentials",
"creds",
"=",
"pika",
".",
"PlainCredentials",
"(",
"node_info_dict",
"[",
"'username'",
"]",
",",
"node_info_dict",
"[",
"'password'",
"]",
")"... | 38.540984 | 20.639344 |
def write_gphocs(data, sidx):
"""
write the g-phocs output. This code is hella ugly bcz it's copy/pasted
directly from the old loci2gphocs script from pyrad. I figure having it
get done the stupid way is better than not having it done at all, at
least for the time being. This could probably be sped ... | [
"def",
"write_gphocs",
"(",
"data",
",",
"sidx",
")",
":",
"outfile",
"=",
"data",
".",
"outfiles",
".",
"gphocs",
"infile",
"=",
"data",
".",
"outfiles",
".",
"loci",
"infile",
"=",
"open",
"(",
"infile",
")",
"outfile",
"=",
"open",
"(",
"outfile",
... | 42.568966 | 22.5 |
def _get_adjtime_timezone():
'''
Return the timezone in /etc/adjtime of the system clock
'''
adjtime_file = '/etc/adjtime'
if os.path.exists(adjtime_file):
cmd = ['tail', '-n', '1', adjtime_file]
return __salt__['cmd.run'](cmd, python_shell=False)
elif os.path.exists('/dev/rtc'):... | [
"def",
"_get_adjtime_timezone",
"(",
")",
":",
"adjtime_file",
"=",
"'/etc/adjtime'",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"adjtime_file",
")",
":",
"cmd",
"=",
"[",
"'tail'",
",",
"'-n'",
",",
"'1'",
",",
"adjtime_file",
"]",
"return",
"__salt__",... | 31.733333 | 17.6 |
def convert_exchange_to_compounds(model):
"""Convert exchange reactions in model to exchange compounds.
Only exchange reactions in the extracellular compartment are converted.
The extracelluar compartment must be defined for the model.
Args:
model: :class:`NativeModel`.
"""
# Build set... | [
"def",
"convert_exchange_to_compounds",
"(",
"model",
")",
":",
"# Build set of exchange reactions",
"exchanges",
"=",
"set",
"(",
")",
"for",
"reaction",
"in",
"model",
".",
"reactions",
":",
"equation",
"=",
"reaction",
".",
"properties",
".",
"get",
"(",
"'eq... | 39.391304 | 19.826087 |
def chunks(l, n):
""" Yield n successive chunks from l.
"""
newn = int(len(l) / n)
for i in xrange(0, n-1):
yield l[i*newn:i*newn+newn]
yield l[n*newn-newn:] | [
"def",
"chunks",
"(",
"l",
",",
"n",
")",
":",
"newn",
"=",
"int",
"(",
"len",
"(",
"l",
")",
"/",
"n",
")",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"n",
"-",
"1",
")",
":",
"yield",
"l",
"[",
"i",
"*",
"newn",
":",
"i",
"*",
"newn",... | 25.571429 | 9.857143 |
def items(self):
""" Return a copy of the dictionary's list of (key, value) pairs. """
r = []
for key in self._safe_keys():
try:
r.append((key, self[key]))
except KeyError:
pass
return r | [
"def",
"items",
"(",
"self",
")",
":",
"r",
"=",
"[",
"]",
"for",
"key",
"in",
"self",
".",
"_safe_keys",
"(",
")",
":",
"try",
":",
"r",
".",
"append",
"(",
"(",
"key",
",",
"self",
"[",
"key",
"]",
")",
")",
"except",
"KeyError",
":",
"pass... | 29.555556 | 15 |
def url(context, view, subdomain=UNSET, *args, **kwargs):
"""
Resolves a URL in a template, using subdomain-based URL resolution.
If no subdomain is provided and a ``request`` is in the template context
when rendering, the URL will be resolved relative to the current request's
subdomain. If no ``re... | [
"def",
"url",
"(",
"context",
",",
"view",
",",
"subdomain",
"=",
"UNSET",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"subdomain",
"is",
"UNSET",
":",
"request",
"=",
"context",
".",
"get",
"(",
"'request'",
")",
"if",
"request",
"i... | 39.15625 | 25.21875 |
def __get_concurrency_maps(self, states, session=None):
"""
Get the concurrency maps.
:param states: List of states to query for
:type states: list[airflow.utils.state.State]
:return: A map from (dag_id, task_id) to # of task instances and
a map from (dag_id, task_id) t... | [
"def",
"__get_concurrency_maps",
"(",
"self",
",",
"states",
",",
"session",
"=",
"None",
")",
":",
"TI",
"=",
"models",
".",
"TaskInstance",
"ti_concurrency_query",
"=",
"(",
"session",
".",
"query",
"(",
"TI",
".",
"task_id",
",",
"TI",
".",
"dag_id",
... | 36.88 | 12.96 |
def build_module(project, env=None):
'''Build project script as module'''
from pyspider.libs import base_handler
assert 'name' in project, 'need name of project'
assert 'script' in project, 'need script of project'
if env is None:
env = {}
# fix for old non-p... | [
"def",
"build_module",
"(",
"project",
",",
"env",
"=",
"None",
")",
":",
"from",
"pyspider",
".",
"libs",
"import",
"base_handler",
"assert",
"'name'",
"in",
"project",
",",
"'need name of project'",
"assert",
"'script'",
"in",
"project",
",",
"'need script of ... | 36.892857 | 18.357143 |
def invoke_hook_spout_ack(self, message_id, complete_latency_ns):
"""invoke task hooks for every time spout acks a tuple
:type message_id: str
:param message_id: message id to which an acked tuple was anchored
:type complete_latency_ns: float
:param complete_latency_ns: complete latency in nano sec... | [
"def",
"invoke_hook_spout_ack",
"(",
"self",
",",
"message_id",
",",
"complete_latency_ns",
")",
":",
"if",
"len",
"(",
"self",
".",
"task_hooks",
")",
">",
"0",
":",
"spout_ack_info",
"=",
"SpoutAckInfo",
"(",
"message_id",
"=",
"message_id",
",",
"spout_task... | 47 | 17.066667 |
def run(self):
"""Run command."""
onnx_script = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools/mypy-onnx.py"))
returncode = subprocess.call([sys.executable, onnx_script])
sys.exit(returncode) | [
"def",
"run",
"(",
"self",
")",
":",
"onnx_script",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
",",
"\... | 50.6 | 28.6 |
def _iter_module_files():
"""This iterates over all relevant Python files. It goes through all
loaded files from modules, all files in folders of already loaded modules
as well as all files reachable through a package.
"""
# The list call is necessary on Python 3 in case the module
# dictionary... | [
"def",
"_iter_module_files",
"(",
")",
":",
"# The list call is necessary on Python 3 in case the module",
"# dictionary modifies during iteration.",
"for",
"module",
"in",
"list",
"(",
"sys",
".",
"modules",
".",
"values",
"(",
")",
")",
":",
"if",
"module",
"is",
"N... | 39.045455 | 12.681818 |
def get_vnetwork_vswitches_output_vnetwork_vswitches_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vswitches = ET.Element("get_vnetwork_vswitches")
config = get_vnetwork_vswitches
output = ET.SubElement(get_vnetwork_vswitches,... | [
"def",
"get_vnetwork_vswitches_output_vnetwork_vswitches_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_vswitches",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_vswitches\"",
")",
... | 44.461538 | 15.923077 |
def _strongly_connected_subgraph(counts, weight=1, verbose=True):
"""Trim a transition count matrix down to its maximal
strongly ergodic subgraph.
From the counts matrix, we define a graph where there exists
a directed edge between two nodes, `i` and `j` if
`counts[i][j] > weight`. We then find the... | [
"def",
"_strongly_connected_subgraph",
"(",
"counts",
",",
"weight",
"=",
"1",
",",
"verbose",
"=",
"True",
")",
":",
"n_states_input",
"=",
"counts",
".",
"shape",
"[",
"0",
"]",
"n_components",
",",
"component_assignments",
"=",
"csgraph",
".",
"connected_co... | 43.308824 | 22.897059 |
def gff(args):
"""
%prog gff *.gff
Draw exons for genes based on gff files. Each gff file should contain only
one gene, and only the "mRNA" and "CDS" feature will be drawn on the canvas.
"""
align_choices = ("left", "center", "right")
p = OptionParser(gff.__doc__)
p.add_option("--align"... | [
"def",
"gff",
"(",
"args",
")",
":",
"align_choices",
"=",
"(",
"\"left\"",
",",
"\"center\"",
",",
"\"right\"",
")",
"p",
"=",
"OptionParser",
"(",
"gff",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--align\"",
",",
"default",
"=",
"\"left\"",
... | 31.266667 | 21.088889 |
def _token_auth(self):
"""Add ThreatConnect Token Auth to Session."""
return TcExTokenAuth(
self,
self.args.tc_token,
self.args.tc_token_expires,
self.args.tc_api_path,
self.tcex.log,
) | [
"def",
"_token_auth",
"(",
"self",
")",
":",
"return",
"TcExTokenAuth",
"(",
"self",
",",
"self",
".",
"args",
".",
"tc_token",
",",
"self",
".",
"args",
".",
"tc_token_expires",
",",
"self",
".",
"args",
".",
"tc_api_path",
",",
"self",
".",
"tcex",
"... | 29 | 12.555556 |
def from_environment_or_defaults(cls, environment=None):
"""Create a Run object taking values from the local environment where possible.
The run ID comes from WANDB_RUN_ID or is randomly generated.
The run mode ("dryrun", or "run") comes from WANDB_MODE or defaults to "dryrun".
The run ... | [
"def",
"from_environment_or_defaults",
"(",
"cls",
",",
"environment",
"=",
"None",
")",
":",
"if",
"environment",
"is",
"None",
":",
"environment",
"=",
"os",
".",
"environ",
"run_id",
"=",
"environment",
".",
"get",
"(",
"env",
".",
"RUN_ID",
")",
"resum... | 44.690476 | 17.690476 |
def _compute_equations(self, x, verbose=False):
'''Compute the values and the normals (gradients) of active constraints.
Arguments:
| ``x`` -- The unknowns.
'''
# compute the error and the normals.
normals = []
values = []
signs = []
error ... | [
"def",
"_compute_equations",
"(",
"self",
",",
"x",
",",
"verbose",
"=",
"False",
")",
":",
"# compute the error and the normals.",
"normals",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"signs",
"=",
"[",
"]",
"error",
"=",
"0.0",
"if",
"verbose",
":",
"pri... | 35.195122 | 13.146341 |
def calculate_angle_bw_tangents(self, base_step, cumulative=False, masked=False):
"""To calculate angle (Radian) between two tangent vectors of global helical axis.
Parameters
----------
base_step : 1D list
List of two base-steps for which angle will be calculated.
... | [
"def",
"calculate_angle_bw_tangents",
"(",
"self",
",",
"base_step",
",",
"cumulative",
"=",
"False",
",",
"masked",
"=",
"False",
")",
":",
"if",
"(",
"len",
"(",
"base_step",
")",
"!=",
"2",
")",
":",
"raise",
"ValueError",
"(",
"\"See, documentation for s... | 41.868852 | 26.016393 |
def _basic_auth_str(username, password):
"""Returns a Basic Auth string."""
authstr = 'Basic ' + to_native_string(
b64encode(('%s:%s' % (username, password)).encode('latin1')).strip()
)
return authstr | [
"def",
"_basic_auth_str",
"(",
"username",
",",
"password",
")",
":",
"authstr",
"=",
"'Basic '",
"+",
"to_native_string",
"(",
"b64encode",
"(",
"(",
"'%s:%s'",
"%",
"(",
"username",
",",
"password",
")",
")",
".",
"encode",
"(",
"'latin1'",
")",
")",
"... | 27.375 | 21.875 |
def apply(self, flag_set: AbstractSet[Flag], operand: AbstractSet[Flag]) \
-> FrozenSet[Flag]:
"""Apply the flag operation on the two sets, returning the result.
Args:
flag_set: The flag set being operated on.
operand: The flags to use as the operand.
"""
... | [
"def",
"apply",
"(",
"self",
",",
"flag_set",
":",
"AbstractSet",
"[",
"Flag",
"]",
",",
"operand",
":",
"AbstractSet",
"[",
"Flag",
"]",
")",
"->",
"FrozenSet",
"[",
"Flag",
"]",
":",
"if",
"self",
"==",
"FlagOp",
".",
"ADD",
":",
"return",
"frozens... | 36.266667 | 14.2 |
def read_eeprom_calibration(self, temperature=False): # use default values for temperature, EEPROM values are usually not calibrated and random
'''Reading EEPROM calibration for power regulators and temperature
'''
header = self.get_format()
if header == self.HEADER_V1:
data... | [
"def",
"read_eeprom_calibration",
"(",
"self",
",",
"temperature",
"=",
"False",
")",
":",
"# use default values for temperature, EEPROM values are usually not calibrated and random",
"header",
"=",
"self",
".",
"get_format",
"(",
")",
"if",
"header",
"==",
"self",
".",
... | 68.258065 | 33.354839 |
def _set(self, path, value, build_dir=''):
"""Create and set a node by path
This creates a node from a filename or pandas DataFrame.
If `value` is a filename, it must be relative to `build_dir`.
`value` is stored as the export path.
`build_dir` defaults to the current dire... | [
"def",
"_set",
"(",
"self",
",",
"path",
",",
"value",
",",
"build_dir",
"=",
"''",
")",
":",
"assert",
"isinstance",
"(",
"path",
",",
"list",
")",
"and",
"len",
"(",
"path",
")",
">",
"0",
"if",
"isinstance",
"(",
"value",
",",
"pd",
".",
"Data... | 45.018182 | 26.345455 |
def create_table(self, model):
"""Create model and table in database.
>> migrator.create_table(model)
"""
self.orm[model._meta.table_name] = model
model._meta.database = self.database
self.ops.append(model.create_table)
return model | [
"def",
"create_table",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"orm",
"[",
"model",
".",
"_meta",
".",
"table_name",
"]",
"=",
"model",
"model",
".",
"_meta",
".",
"database",
"=",
"self",
".",
"database",
"self",
".",
"ops",
".",
"append",... | 31.222222 | 9.555556 |
def set_server_setting(settings, server=_DEFAULT_SERVER):
'''
Set the value of the setting for the SMTP virtual server.
.. note::
The setting names are case-sensitive.
:param str settings: A dictionary of the setting names and their values.
:param str server: The SMTP server name.
:r... | [
"def",
"set_server_setting",
"(",
"settings",
",",
"server",
"=",
"_DEFAULT_SERVER",
")",
":",
"if",
"not",
"settings",
":",
"_LOG",
".",
"warning",
"(",
"'No settings provided'",
")",
"return",
"False",
"# Some fields are formatted like '{data}'. Salt tries to convert th... | 38.898551 | 27.217391 |
def create(self, store_id, product_id, data):
"""
Add a new image to the product.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param product_id: The id for the product of a store.
:type product_id: :py:class:`str`
:param data: The request body ... | [
"def",
"create",
"(",
"self",
",",
"store_id",
",",
"product_id",
",",
"data",
")",
":",
"self",
".",
"store_id",
"=",
"store_id",
"self",
".",
"product_id",
"=",
"product_id",
"if",
"'id'",
"not",
"in",
"data",
":",
"raise",
"KeyError",
"(",
"'The produ... | 35.481481 | 14.222222 |
def has_option(self, section, option):
"""Checks for the existence of a given option in a given section.
Args:
section (str): name of section
option (str): name of option
Returns:
bool: whether the option exists in the given section
"""
if se... | [
"def",
"has_option",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"if",
"section",
"not",
"in",
"self",
".",
"sections",
"(",
")",
":",
"return",
"False",
"else",
":",
"option",
"=",
"self",
".",
"optionxform",
"(",
"option",
")",
"return",
... | 30.866667 | 14.066667 |
def normalise_correlation_coefficient(image_tile_dict, transformed_array, template, normed_tolerance=1):
"""As above, but for when the correlation coefficient matching method is used
"""
template_mean = np.mean(template)
template_minus_mean = template - template_mean
template_norm = np.linalg.norm(t... | [
"def",
"normalise_correlation_coefficient",
"(",
"image_tile_dict",
",",
"transformed_array",
",",
"template",
",",
"normed_tolerance",
"=",
"1",
")",
":",
"template_mean",
"=",
"np",
".",
"mean",
"(",
"template",
")",
"template_minus_mean",
"=",
"template",
"-",
... | 74.923077 | 37.692308 |
def _kernel_versions_debian():
'''
Last installed kernel name, for Debian based systems.
Returns:
List with possible names of last installed kernel
as they are probably interpreted in output of `uname -a` command.
'''
kernel_get_selections = __salt__['cmd.run']('dpkg --get-s... | [
"def",
"_kernel_versions_debian",
"(",
")",
":",
"kernel_get_selections",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"'dpkg --get-selections linux-image-*'",
")",
"kernels",
"=",
"[",
"]",
"kernel_versions",
"=",
"[",
"]",
"for",
"line",
"in",
"kernel_get_selectio... | 33.444444 | 24.111111 |
def from_json(cls, json):
"""Deserialize from json.
Args:
json: a dict of json compatible fields.
Returns:
a KeyRanges object.
Raises:
ValueError: if the json is invalid.
"""
if json["name"] in _KEYRANGES_CLASSES:
return _KEYRANGES_CLASSES[json["name"]].from_json(json)... | [
"def",
"from_json",
"(",
"cls",
",",
"json",
")",
":",
"if",
"json",
"[",
"\"name\"",
"]",
"in",
"_KEYRANGES_CLASSES",
":",
"return",
"_KEYRANGES_CLASSES",
"[",
"json",
"[",
"\"name\"",
"]",
"]",
".",
"from_json",
"(",
"json",
")",
"raise",
"ValueError",
... | 23.466667 | 18.133333 |
def next_down(x, context=None):
"""next_down(x): return the greatest representable float that's
strictly less than x.
This operation is quiet: flags are not affected.
"""
x = BigFloat._implicit_convert(x)
# make sure we don't alter any flags
with _saved_flags():
with (context if c... | [
"def",
"next_down",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"x",
"=",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
"# make sure we don't alter any flags",
"with",
"_saved_flags",
"(",
")",
":",
"with",
"(",
"context",
"if",
"context",
"is",
... | 32 | 15.461538 |
def generate_form(args):
"""Generate form."""
form_name = args.get('<form>')
logger.info('Start generating form.')
_generate_form(form_name)
logger.info('Finish generating form.') | [
"def",
"generate_form",
"(",
"args",
")",
":",
"form_name",
"=",
"args",
".",
"get",
"(",
"'<form>'",
")",
"logger",
".",
"info",
"(",
"'Start generating form.'",
")",
"_generate_form",
"(",
"form_name",
")",
"logger",
".",
"info",
"(",
"'Finish generating for... | 32.333333 | 6 |
def __parse_fc_data(fc_data):
"""Parse the forecast data from the json section."""
fc = []
for day in fc_data:
fcdata = {
CONDITION: __cond_from_desc(
__get_str(
day,
__WEATHERDESCRIPTION)
),
TEMPERATURE: __g... | [
"def",
"__parse_fc_data",
"(",
"fc_data",
")",
":",
"fc",
"=",
"[",
"]",
"for",
"day",
"in",
"fc_data",
":",
"fcdata",
"=",
"{",
"CONDITION",
":",
"__cond_from_desc",
"(",
"__get_str",
"(",
"day",
",",
"__WEATHERDESCRIPTION",
")",
")",
",",
"TEMPERATURE",
... | 38.703704 | 16.481481 |
def reverse(self, request, view_name):
"""
Returns the URL of this tenant.
"""
http_type = 'https://' if request.is_secure() else 'http://'
domain = get_current_site(request).domain
url = ''.join((http_type, self.schema_name, '.', domain, reverse(view_name)))
r... | [
"def",
"reverse",
"(",
"self",
",",
"request",
",",
"view_name",
")",
":",
"http_type",
"=",
"'https://'",
"if",
"request",
".",
"is_secure",
"(",
")",
"else",
"'http://'",
"domain",
"=",
"get_current_site",
"(",
"request",
")",
".",
"domain",
"url",
"=",
... | 29 | 20.636364 |
def _checkSetupNeeded(self, message):
"""Check an id_res message to see if it is a
checkid_immediate cancel response.
@raises SetupNeededError: if it is a checkid_immediate cancellation
"""
# In OpenID 1, we check to see if this is a cancel from
# immediate mode by the p... | [
"def",
"_checkSetupNeeded",
"(",
"self",
",",
"message",
")",
":",
"# In OpenID 1, we check to see if this is a cancel from",
"# immediate mode by the presence of the user_setup_url",
"# parameter.",
"if",
"message",
".",
"isOpenID1",
"(",
")",
":",
"user_setup_url",
"=",
"me... | 43.230769 | 15.615385 |
def nested_to_ring(nested_index, nside):
"""
Convert a HEALPix 'nested' index to a HEALPix 'ring' index
Parameters
----------
nested_index : int or `~numpy.ndarray`
Healpix index using the 'nested' ordering
nside : int or `~numpy.ndarray`
Number of pixels along the side of each ... | [
"def",
"nested_to_ring",
"(",
"nested_index",
",",
"nside",
")",
":",
"nside",
"=",
"np",
".",
"asarray",
"(",
"nside",
",",
"dtype",
"=",
"np",
".",
"intc",
")",
"return",
"_core",
".",
"nested_to_ring",
"(",
"nested_index",
",",
"nside",
")"
] | 27.8 | 18.6 |
async def status(dev: Device):
"""Display status information."""
power = await dev.get_power()
click.echo(click.style("%s" % power, bold=power))
vol = await dev.get_volume_information()
click.echo(vol.pop())
play_info = await dev.get_play_info()
if not play_info.is_idle:
click.echo... | [
"async",
"def",
"status",
"(",
"dev",
":",
"Device",
")",
":",
"power",
"=",
"await",
"dev",
".",
"get_power",
"(",
")",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"\"%s\"",
"%",
"power",
",",
"bold",
"=",
"power",
")",
")",
"vol",
"=... | 28.714286 | 15.428571 |
def create_field(field_info):
"""
Create a field by field info dict.
"""
field_type = field_info.get('type')
if field_type not in FIELDS_NAME_MAP:
raise ValueError(_('not support this field: {}').format(field_type))
field_class = FIELDS_NAME_MAP.get(field_type)
params = dict(field_in... | [
"def",
"create_field",
"(",
"field_info",
")",
":",
"field_type",
"=",
"field_info",
".",
"get",
"(",
"'type'",
")",
"if",
"field_type",
"not",
"in",
"FIELDS_NAME_MAP",
":",
"raise",
"ValueError",
"(",
"_",
"(",
"'not support this field: {}'",
")",
".",
"forma... | 34.272727 | 8.090909 |
def get_signature(self, base_commit=None):
"""Get the signature of the current state of the repository
TODO right now `get_signature` is an effectful process in that
it adds all untracked file to staging. This is the only way to get
accruate diff on new files. This is ok because we only... | [
"def",
"get_signature",
"(",
"self",
",",
"base_commit",
"=",
"None",
")",
":",
"if",
"base_commit",
"is",
"None",
":",
"base_commit",
"=",
"'HEAD'",
"self",
".",
"run",
"(",
"'add'",
",",
"'-A'",
",",
"self",
".",
"path",
")",
"sha",
"=",
"self",
".... | 33.785714 | 18.571429 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.