text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def kron_factor_4x4_to_2x2s(
matrix: np.ndarray,
) -> Tuple[complex, np.ndarray, np.ndarray]:
"""Splits a 4x4 matrix U = kron(A, B) into A, B, and a global factor.
Requires the matrix to be the kronecker product of two 2x2 unitaries.
Requires the matrix to have a non-zero determinant.
Giving an... | [
"def",
"kron_factor_4x4_to_2x2s",
"(",
"matrix",
":",
"np",
".",
"ndarray",
",",
")",
"->",
"Tuple",
"[",
"complex",
",",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
"]",
":",
"# Use the entry with the largest magnitude as a reference point.",
"a",
",",
"b"... | 32.888889 | 0.000656 |
def replace(self, src: str) -> str:
"""
Extends LaTeX syntax via regex preprocess
:param src: str
LaTeX string
:return: str
New LaTeX string
"""
if not self.readied:
self.ready()
# Brackets + simple pre replacements:
sr... | [
"def",
"replace",
"(",
"self",
",",
"src",
":",
"str",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"readied",
":",
"self",
".",
"ready",
"(",
")",
"# Brackets + simple pre replacements:",
"src",
"=",
"self",
".",
"_dict_replace",
"(",
"self",
".",
... | 27.190476 | 0.001691 |
def remove_file(self, path):
"""Removes the given file"""
self.get_file(path).remove()
self.remove_cache_buster(path) | [
"def",
"remove_file",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"get_file",
"(",
"path",
")",
".",
"remove",
"(",
")",
"self",
".",
"remove_cache_buster",
"(",
"path",
")"
] | 34.5 | 0.014184 |
def pairs(args):
"""
%prog pairs folder reference.fasta
Estimate insert size distribution. Compatible with a variety of aligners,
including BOWTIE and BWA.
"""
p = OptionParser(pairs.__doc__)
p.set_firstN()
p.set_mates()
p.set_aligner()
opts, args = p.parse_args(args)
if le... | [
"def",
"pairs",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"pairs",
".",
"__doc__",
")",
"p",
".",
"set_firstN",
"(",
")",
"p",
".",
"set_mates",
"(",
")",
"p",
".",
"set_aligner",
"(",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_a... | 31.982759 | 0.001046 |
def main_locust():
""" Performance test with locust: parse command line options and run commands.
"""
# monkey patch ssl at beginning to avoid RecursionError when running locust.
from gevent import monkey; monkey.patch_ssl()
import multiprocessing
import sys
from httprunner import logger
... | [
"def",
"main_locust",
"(",
")",
":",
"# monkey patch ssl at beginning to avoid RecursionError when running locust.",
"from",
"gevent",
"import",
"monkey",
"monkey",
".",
"patch_ssl",
"(",
")",
"import",
"multiprocessing",
"import",
"sys",
"from",
"httprunner",
"import",
"... | 33.455556 | 0.002258 |
def spectrum(self):
"""
Returns the Fourier transformed and shifted data
:return:
"""
return numpy.fft.fftshift(numpy.fft.fft(self, axis=-1), axes=-1) | [
"def",
"spectrum",
"(",
"self",
")",
":",
"return",
"numpy",
".",
"fft",
".",
"fftshift",
"(",
"numpy",
".",
"fft",
".",
"fft",
"(",
"self",
",",
"axis",
"=",
"-",
"1",
")",
",",
"axes",
"=",
"-",
"1",
")"
] | 26.428571 | 0.010471 |
def stop(self, kill=False, timeout=15):
""" terminate process and wipe out the temp work directory, but only if we actually started it"""
super(AbstractDcsController, self).stop(kill=kill, timeout=timeout)
if self._work_directory:
shutil.rmtree(self._work_directory) | [
"def",
"stop",
"(",
"self",
",",
"kill",
"=",
"False",
",",
"timeout",
"=",
"15",
")",
":",
"super",
"(",
"AbstractDcsController",
",",
"self",
")",
".",
"stop",
"(",
"kill",
"=",
"kill",
",",
"timeout",
"=",
"timeout",
")",
"if",
"self",
".",
"_wo... | 59.6 | 0.009934 |
def _file_to_abs(x, dnames, makedir=False):
"""Make a file absolute using the supplied base directory choices.
"""
if x is None or os.path.isabs(x):
return x
elif isinstance(x, six.string_types) and objectstore.is_remote(x):
return x
elif isinstance(x, six.string_types) and x.lower()... | [
"def",
"_file_to_abs",
"(",
"x",
",",
"dnames",
",",
"makedir",
"=",
"False",
")",
":",
"if",
"x",
"is",
"None",
"or",
"os",
".",
"path",
".",
"isabs",
"(",
"x",
")",
":",
"return",
"x",
"elif",
"isinstance",
"(",
"x",
",",
"six",
".",
"string_ty... | 37.789474 | 0.001359 |
def get_excluded_categories():
"""Get excluded category IDs."""
from indico_livesync.plugin import LiveSyncPlugin
return {int(x['id']) for x in LiveSyncPlugin.settings.get('excluded_categories')} | [
"def",
"get_excluded_categories",
"(",
")",
":",
"from",
"indico_livesync",
".",
"plugin",
"import",
"LiveSyncPlugin",
"return",
"{",
"int",
"(",
"x",
"[",
"'id'",
"]",
")",
"for",
"x",
"in",
"LiveSyncPlugin",
".",
"settings",
".",
"get",
"(",
"'excluded_cat... | 51 | 0.009662 |
def from_dict(cls, d):
"""
Returns CompleteCohp object from dict representation.
"""
cohp_dict = {}
efermi = d["efermi"]
energies = d["energies"]
structure = Structure.from_dict(d["structure"])
if "bonds" in d.keys():
bonds = {bond: {"length": ... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"cohp_dict",
"=",
"{",
"}",
"efermi",
"=",
"d",
"[",
"\"efermi\"",
"]",
"energies",
"=",
"d",
"[",
"\"energies\"",
"]",
"structure",
"=",
"Structure",
".",
"from_dict",
"(",
"d",
"[",
"\"structure\"",... | 46.76087 | 0.000911 |
def disconnect(self, cback):
"See signal"
return self.signal.disconnect(cback,
subscribers=self.subscribers,
instance=self.instance) | [
"def",
"disconnect",
"(",
"self",
",",
"cback",
")",
":",
"return",
"self",
".",
"signal",
".",
"disconnect",
"(",
"cback",
",",
"subscribers",
"=",
"self",
".",
"subscribers",
",",
"instance",
"=",
"self",
".",
"instance",
")"
] | 44 | 0.008929 |
def _read_para_hit_suite_list(self, code, cbit, clen, *, desc, length, version):
"""Read HIP HIT_SUITE_LIST parameter.
Structure of HIP HIT_SUITE_LIST parameter [RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 ... | [
"def",
"_read_para_hit_suite_list",
"(",
"self",
",",
"code",
",",
"cbit",
",",
"clen",
",",
"*",
",",
"desc",
",",
"length",
",",
"version",
")",
":",
"_hsid",
"=",
"list",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"clen",
")",
":",
"_hsid",
".",
... | 44.205128 | 0.001703 |
def addIncludeSchema(self, schemaLocation, schema):
"""for resolving include statements in Schema instance
schemaLocation -- schema location
schema -- schema instance
_included_schemas
"""
if not isinstance(schema, XMLSchema):
raise TypeError, 'expec... | [
"def",
"addIncludeSchema",
"(",
"self",
",",
"schemaLocation",
",",
"schema",
")",
":",
"if",
"not",
"isinstance",
"(",
"schema",
",",
"XMLSchema",
")",
":",
"raise",
"TypeError",
",",
"'expecting a Schema instance'",
"if",
"not",
"schema",
".",
"targetNamespace... | 44.307692 | 0.010204 |
def _recursive_dict_update(dict_, other, **kwargs):
"""Deep/recursive version of ``dict.update``.
If a key is present in both dictionaries, and points to
"child" dictionaries, those will be appropriately merged.
:param overwrite: Whether to overwrite exisiting dictionary values
"""
overwrite =... | [
"def",
"_recursive_dict_update",
"(",
"dict_",
",",
"other",
",",
"*",
"*",
"kwargs",
")",
":",
"overwrite",
"=",
"kwargs",
"[",
"'overwrite'",
"]",
"for",
"key",
",",
"other_value",
"in",
"iteritems",
"(",
"other",
")",
":",
"if",
"key",
"in",
"dict_",
... | 35.55 | 0.00137 |
def Overlay_setInspectMode(self, mode, **kwargs):
"""
Function path: Overlay.setInspectMode
Domain: Overlay
Method name: setInspectMode
Parameters:
Required arguments:
'mode' (type: InspectMode) -> Set an inspection mode.
Optional arguments:
'highlightConfig' (type: HighlightConfig) ->... | [
"def",
"Overlay_setInspectMode",
"(",
"self",
",",
"mode",
",",
"*",
"*",
"kwargs",
")",
":",
"expected",
"=",
"[",
"'highlightConfig'",
"]",
"passed_keys",
"=",
"list",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"assert",
"all",
"(",
"[",
"(",
"key",
... | 43.363636 | 0.033846 |
def sanitize_filename(filename):
"""
Make sure filenames are valid paths.
Returns:
str:
"""
sanitized_filename = re.sub(r'[/\\:*?"<>|]', '-', filename)
sanitized_filename = sanitized_filename.replace('&', 'and')
sanitized_filename = sanitized_filename.replace('"', '')
sanitized_... | [
"def",
"sanitize_filename",
"(",
"filename",
")",
":",
"sanitized_filename",
"=",
"re",
".",
"sub",
"(",
"r'[/\\\\:*?\"<>|]'",
",",
"'-'",
",",
"filename",
")",
"sanitized_filename",
"=",
"sanitized_filename",
".",
"replace",
"(",
"'&'",
",",
"'and'",
")",
"sa... | 32.473684 | 0.001575 |
def slice(self, tf_tensor, tensor_shape):
""""Slice out the corresponding part of tensor given the pnum variable."""
tensor_layout = self.tensor_layout(tensor_shape)
if tensor_layout.is_fully_replicated:
return self.LaidOutTensor([tf_tensor])
else:
slice_shape = self.slice_shape(tensor_shap... | [
"def",
"slice",
"(",
"self",
",",
"tf_tensor",
",",
"tensor_shape",
")",
":",
"tensor_layout",
"=",
"self",
".",
"tensor_layout",
"(",
"tensor_shape",
")",
"if",
"tensor_layout",
".",
"is_fully_replicated",
":",
"return",
"self",
".",
"LaidOutTensor",
"(",
"["... | 42.25 | 0.011577 |
def decode_content(self):
"""
Decode (decompress...) the content got from the cache, to the final
html
"""
self.content = pickle.loads(zlib.decompress(self.content)) | [
"def",
"decode_content",
"(",
"self",
")",
":",
"self",
".",
"content",
"=",
"pickle",
".",
"loads",
"(",
"zlib",
".",
"decompress",
"(",
"self",
".",
"content",
")",
")"
] | 33.333333 | 0.009756 |
def normalize_body(self, b):
"""return the body as a string, formatted to the appropriate content type
:param b: mixed, the current raw body
:returns: unicode string
"""
if b is None: return ''
if self.is_json():
# TODO ???
# I don't like this, i... | [
"def",
"normalize_body",
"(",
"self",
",",
"b",
")",
":",
"if",
"b",
"is",
"None",
":",
"return",
"''",
"if",
"self",
".",
"is_json",
"(",
")",
":",
"# TODO ???",
"# I don't like this, if we have a content type but it isn't one",
"# of the supported ones we were retur... | 40.695652 | 0.008351 |
def lookup(self, vtype, vname, target_id=None):
"""Return value of vname from the variable store vtype.
Valid vtypes are `strings` 'counters', and `pending`. If the value
is not found in the current steps store, earlier steps will be
checked. If not found, '', 0, or (None, None) is retu... | [
"def",
"lookup",
"(",
"self",
",",
"vtype",
",",
"vname",
",",
"target_id",
"=",
"None",
")",
":",
"nullvals",
"=",
"{",
"'strings'",
":",
"''",
",",
"'counters'",
":",
"0",
",",
"'pending'",
":",
"(",
"None",
",",
"None",
")",
"}",
"nullval",
"=",... | 34.731707 | 0.001366 |
def create_profile_layer(profiling):
"""Create a tabular layer with the profiling.
:param profiling: A dict containing benchmarking data.
:type profiling: safe.messaging.message.Message
:return: A tabular layer.
:rtype: QgsVectorLayer
"""
fields = [
create_field_from_definition(pro... | [
"def",
"create_profile_layer",
"(",
"profiling",
")",
":",
"fields",
"=",
"[",
"create_field_from_definition",
"(",
"profiling_function_field",
")",
",",
"create_field_from_definition",
"(",
"profiling_time_field",
")",
"]",
"if",
"setting",
"(",
"key",
"=",
"'memory_... | 35.545455 | 0.000498 |
def conversations(self, getsrcdst=None, **kargs):
"""Graphes a conversations between sources and destinations and display it
(using graphviz and imagemagick)
getsrcdst: a function that takes an element of the list and
returns the source, the destination and optionally
... | [
"def",
"conversations",
"(",
"self",
",",
"getsrcdst",
"=",
"None",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"getsrcdst",
"is",
"None",
":",
"def",
"getsrcdst",
"(",
"pkt",
")",
":",
"\"\"\"Extract src and dst addresses\"\"\"",
"if",
"'IP'",
"in",
"pkt",
":... | 46.488372 | 0.00098 |
def branches(self):
"""Return a list of branches for given repository
:return: [str]
"""
req_message = 'https://api.bitbucket.org/1.0/repositories/' + self.reponame + '/branches'
response_data = self._bitbucketAPIRequest(req_message)
return response_data.keys() | [
"def",
"branches",
"(",
"self",
")",
":",
"req_message",
"=",
"'https://api.bitbucket.org/1.0/repositories/'",
"+",
"self",
".",
"reponame",
"+",
"'/branches'",
"response_data",
"=",
"self",
".",
"_bitbucketAPIRequest",
"(",
"req_message",
")",
"return",
"response_dat... | 33.375 | 0.032847 |
def delete(self):
"""
Deletes the selected items.
"""
urls = self.selected_urls()
rep = QtWidgets.QMessageBox.question(
self.tree_view, _('Confirm delete'),
_('Are you sure about deleting the selected files/directories?'),
QtWidgets.QMessageBox... | [
"def",
"delete",
"(",
"self",
")",
":",
"urls",
"=",
"self",
".",
"selected_urls",
"(",
")",
"rep",
"=",
"QtWidgets",
".",
"QMessageBox",
".",
"question",
"(",
"self",
".",
"tree_view",
",",
"_",
"(",
"'Confirm delete'",
")",
",",
"_",
"(",
"'Are you s... | 42.633333 | 0.001529 |
def conditionally_create_kms_key(role_name, service_type):
"""
Create KMS Master Key for encryption/decryption of sensitive values in cf templates and latebind configs
Args:
role_name: name of the role that kms key is being created for; it will be given decrypt privileges.
service_type: service regist... | [
"def",
"conditionally_create_kms_key",
"(",
"role_name",
",",
"service_type",
")",
":",
"if",
"service_type",
"not",
"in",
"KMS_SERVICE_TYPES",
":",
"print_if_verbose",
"(",
"\"not eligible for kms; service_type: {} is not valid for kms\"",
".",
"format",
"(",
"service_type",... | 36.380165 | 0.009509 |
def all(self):
"""
Yield torrents in range from current page to last page
"""
return self.pages(self.url.page, self.url.max_page) | [
"def",
"all",
"(",
"self",
")",
":",
"return",
"self",
".",
"pages",
"(",
"self",
".",
"url",
".",
"page",
",",
"self",
".",
"url",
".",
"max_page",
")"
] | 31.4 | 0.012422 |
def run(self,field=None,simple=False,force=False):
"""
Loop through pixels containing catalog objects and calculate
the magnitude limit. This gets a bit convoluted due to all
the different pixel resolutions...
"""
if field is None: fields = [1,2]
else: ... | [
"def",
"run",
"(",
"self",
",",
"field",
"=",
"None",
",",
"simple",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"field",
"is",
"None",
":",
"fields",
"=",
"[",
"1",
",",
"2",
"]",
"else",
":",
"fields",
"=",
"[",
"field",
"]",
... | 46.75 | 0.017467 |
def fit_size_distribution_models(self, model_names, model_objs, input_columns,
output_columns=None, calibrate=False):
"""
Fits multitask machine learning models to predict the parameters of a size distribution
Args:
model_names: List of machine le... | [
"def",
"fit_size_distribution_models",
"(",
"self",
",",
"model_names",
",",
"model_objs",
",",
"input_columns",
",",
"output_columns",
"=",
"None",
",",
"calibrate",
"=",
"False",
")",
":",
"if",
"output_columns",
"is",
"None",
":",
"output_columns",
"=",
"[",
... | 64.859155 | 0.010695 |
def generate(self, v):
""" create and return the op string for this TermValue """
val = v.tostring(self.encoding)
return "({lhs} {op} {val})".format(lhs=self.lhs, op=self.op, val=val) | [
"def",
"generate",
"(",
"self",
",",
"v",
")",
":",
"val",
"=",
"v",
".",
"tostring",
"(",
"self",
".",
"encoding",
")",
"return",
"\"({lhs} {op} {val})\"",
".",
"format",
"(",
"lhs",
"=",
"self",
".",
"lhs",
",",
"op",
"=",
"self",
".",
"op",
",",... | 51 | 0.009662 |
def clean(self, string, n_cols=None):
"""
Required reading!
http://nedbatchelder.com/text/unipain.html
Python 2 input string will be a unicode type (unicode code points).
Curses will accept unicode if all of the points are in the ascii range.
However, if any of the c... | [
"def",
"clean",
"(",
"self",
",",
"string",
",",
"n_cols",
"=",
"None",
")",
":",
"if",
"n_cols",
"is",
"not",
"None",
"and",
"n_cols",
"<=",
"0",
":",
"return",
"''",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"stri... | 44.695652 | 0.000952 |
def release(input_dict, environment_dict):
"""
<Purpose>
Releases the specified vessels.
<Arguments>
input_dict: The commanddict representing the user's input.
environment_dict: The dictionary representing the current seash
environment.
<Side Effects>
Connects to the C... | [
"def",
"release",
"(",
"input_dict",
",",
"environment_dict",
")",
":",
"# Activate secure mode if user did not specify the insecure keyword",
"allow_ssl_insecure",
"=",
"_get_user_argument",
"(",
"input_dict",
",",
"'insecure'",
")",
"is",
"not",
"None",
"# Get the group nam... | 32.346154 | 0.013849 |
def deleteEdge(self, networkId, edgeId, verbose=None):
"""
Deletes the edge specified by the `edgeId` and `networkId` parameters.
:param networkId: SUID of the network containing the edge.
:param edgeId: SUID of the edge
:param verbose: print more
:returns: default: suc... | [
"def",
"deleteEdge",
"(",
"self",
",",
"networkId",
",",
"edgeId",
",",
"verbose",
"=",
"None",
")",
":",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"___url",
"+",
"'networks/'",
"+",
"str",
"(",
"networkId",
")",
"+",
"'/edges/'",
"+",
"s... | 37.384615 | 0.008032 |
def view(self, repo):
"""
View repository information
"""
status = "{0}disabled{1}".format(self.meta.color["RED"],
self.meta.color["ENDC"])
self.form["Status:"] = status
self.form["Default:"] = "no"
if repo in self.meta.def... | [
"def",
"view",
"(",
"self",
",",
"repo",
")",
":",
"status",
"=",
"\"{0}disabled{1}\"",
".",
"format",
"(",
"self",
".",
"meta",
".",
"color",
"[",
"\"RED\"",
"]",
",",
"self",
".",
"meta",
".",
"color",
"[",
"\"ENDC\"",
"]",
")",
"self",
".",
"for... | 49.961538 | 0.00151 |
def onlinetime_get(self, service_staff_id, start_date, end_date, session):
'''taobao.wangwang.eservice.onlinetime.get 日累计在线时长
描述:根据客服ID和日期,获取该客服"当日在线时长"。 备注:
- 1、如果是操作者ID=被查者ID,返回被查者ID的"当日在线时长"。
- 2、如果操作者是组管理员,他可以查询他的组中的所有子帐号的"当日在线时长"。
- 3、如果操作者是主账户,他可以查询所有子帐号... | [
"def",
"onlinetime_get",
"(",
"self",
",",
"service_staff_id",
",",
"start_date",
",",
"end_date",
",",
"session",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.wangwang.eservice.onlinetime.get'",
")",
"request",
"[",
"'service_staff_id'",
"]",
"=",
"service... | 41.421053 | 0.013665 |
def study_datdel(self):
"""Figure out the data delimiter."""
nodigs = r'(\D+)'
line = self.rows[self.rts + 1] # Study second line of data only.
digs = re.findall(self.datrx, line)
# if any of the numbers contain a '+' in it, it need to be escaped
# before used in the ... | [
"def",
"study_datdel",
"(",
"self",
")",
":",
"nodigs",
"=",
"r'(\\D+)'",
"line",
"=",
"self",
".",
"rows",
"[",
"self",
".",
"rts",
"+",
"1",
"]",
"# Study second line of data only.",
"digs",
"=",
"re",
".",
"findall",
"(",
"self",
".",
"datrx",
",",
... | 35.913043 | 0.001179 |
def disassemble(self, atom_labels=None, guess_element=True,
ff_label="ff_map"):
"""
Breaks down LammpsData to building blocks
(LammpsBox, ForceField and a series of Topology).
RESTRICTIONS APPLIED:
1. No complex force field defined not just on atom
... | [
"def",
"disassemble",
"(",
"self",
",",
"atom_labels",
"=",
"None",
",",
"guess_element",
"=",
"True",
",",
"ff_label",
"=",
"\"ff_map\"",
")",
":",
"atoms_df",
"=",
"self",
".",
"atoms",
".",
"copy",
"(",
")",
"if",
"\"nx\"",
"in",
"atoms_df",
".",
"c... | 46.714286 | 0.000713 |
def get_handlerecord_indices_for_key(self, key, list_of_entries):
'''
Finds the Handle entry indices of all entries that have a specific
type.
*Important:* It finds the Handle System indices! These are not
the python indices of the list, so they can not be used for
itera... | [
"def",
"get_handlerecord_indices_for_key",
"(",
"self",
",",
"key",
",",
"list_of_entries",
")",
":",
"LOGGER",
".",
"debug",
"(",
"'get_handlerecord_indices_for_key...'",
")",
"indices",
"=",
"[",
"]",
"for",
"entry",
"in",
"list_of_entries",
":",
"if",
"entry",
... | 35.434783 | 0.002389 |
def _check_attributes(self, attributes, extra=None):
"""Check if attributes given to the constructor can be used to
instanciate a valid node."""
extra = extra or ()
unknown_keys = set(attributes) - set(self._possible_attributes) - set(extra)
if unknown_keys:
logger.wa... | [
"def",
"_check_attributes",
"(",
"self",
",",
"attributes",
",",
"extra",
"=",
"None",
")",
":",
"extra",
"=",
"extra",
"or",
"(",
")",
"unknown_keys",
"=",
"set",
"(",
"attributes",
")",
"-",
"set",
"(",
"self",
".",
"_possible_attributes",
")",
"-",
... | 52.625 | 0.009346 |
def license_fallback(vendor_dir, sdist_name):
"""Hardcoded license URLs. Check when updating if those are still needed"""
libname = libname_from_dir(sdist_name)
if libname not in HARDCODED_LICENSE_URLS:
raise ValueError('No hardcoded URL for {} license'.format(libname))
url = HARDCODED_LICENSE_... | [
"def",
"license_fallback",
"(",
"vendor_dir",
",",
"sdist_name",
")",
":",
"libname",
"=",
"libname_from_dir",
"(",
"sdist_name",
")",
"if",
"libname",
"not",
"in",
"HARDCODED_LICENSE_URLS",
":",
"raise",
"ValueError",
"(",
"'No hardcoded URL for {} license'",
".",
... | 43 | 0.001751 |
def run(self, *args, **kw):
""" This may be overridden by a subclass. """
if self._runFunc is not None:
# remove the two args sent by EditParDialog which we do not use
if 'mode' in kw: kw.pop('mode')
if '_save' in kw: kw.pop('_save')
return self._runFunc(s... | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"if",
"self",
".",
"_runFunc",
"is",
"not",
"None",
":",
"# remove the two args sent by EditParDialog which we do not use",
"if",
"'mode'",
"in",
"kw",
":",
"kw",
".",
"pop",
"(",
... | 51.083333 | 0.020833 |
def export_sbgn(model):
"""Return an SBGN model string corresponding to the PySB model.
This function first calls generate_equations on the PySB model to obtain
a reaction network (i.e. individual species, reactions). It then iterates
over each reaction and and instantiates its reactants, products, and... | [
"def",
"export_sbgn",
"(",
"model",
")",
":",
"import",
"lxml",
".",
"etree",
"import",
"lxml",
".",
"builder",
"from",
"pysb",
".",
"bng",
"import",
"generate_equations",
"from",
"indra",
".",
"assemblers",
".",
"sbgn",
"import",
"SBGNAssembler",
"logger",
... | 35.391892 | 0.000371 |
def _pypsa_generator_timeseries(network, timesteps, mode=None):
"""Timeseries in PyPSA compatible format for generator instances
Parameters
----------
network : Network
The eDisGo grid topology model overall container
timesteps : array_like
Timesteps is an array-like object with ent... | [
"def",
"_pypsa_generator_timeseries",
"(",
"network",
",",
"timesteps",
",",
"mode",
"=",
"None",
")",
":",
"mv_gen_timeseries_q",
"=",
"[",
"]",
"mv_gen_timeseries_p",
"=",
"[",
"]",
"lv_gen_timeseries_q",
"=",
"[",
"]",
"lv_gen_timeseries_p",
"=",
"[",
"]",
... | 39.320755 | 0.000468 |
def close(self):
"""Closes the connection to the dongle.
Calls :meth:`reset` and then closes the serial port connection to the dongle."""
logger.debug('closing dongle, {} active connections'.format(len(self.conn_handles)))
if self.is_scanning():
logger.debug('in scan... | [
"def",
"close",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'closing dongle, {} active connections'",
".",
"format",
"(",
"len",
"(",
"self",
".",
"conn_handles",
")",
")",
")",
"if",
"self",
".",
"is_scanning",
"(",
")",
":",
"logger",
".",
"de... | 40.25 | 0.010121 |
def write(self):
"""
Writes the ``.sln`` file to disk.
"""
filters = {
'MSGUID': lambda x: ('{%s}' % x).upper(),
'relslnfile': lambda x: os.path.relpath(x, os.path.dirname(self.FileName))
}
context = {
'sln': self
}
retu... | [
"def",
"write",
"(",
"self",
")",
":",
"filters",
"=",
"{",
"'MSGUID'",
":",
"lambda",
"x",
":",
"(",
"'{%s}'",
"%",
"x",
")",
".",
"upper",
"(",
")",
",",
"'relslnfile'",
":",
"lambda",
"x",
":",
"os",
".",
"path",
".",
"relpath",
"(",
"x",
",... | 31.75 | 0.010204 |
def asciiplot(x, y, digit=1, width=50, title=None, char="="):
"""
Print out a horizontal plot using ASCII chars.
width is the textwidth (height) of the plot.
"""
ax = np.array(x)
ay = np.array(y)
if title:
print(dark(title), file=sys.stderr)
az = ay * width / ay.max()
tx = ... | [
"def",
"asciiplot",
"(",
"x",
",",
"y",
",",
"digit",
"=",
"1",
",",
"width",
"=",
"50",
",",
"title",
"=",
"None",
",",
"char",
"=",
"\"=\"",
")",
":",
"ax",
"=",
"np",
".",
"array",
"(",
"x",
")",
"ay",
"=",
"np",
".",
"array",
"(",
"y",
... | 27.85 | 0.001736 |
def main(conversion_type, input_pyc, output_pyc):
"""Convert Python bytecode from one version to another.
INPUT_PYC contains the input bytecode path name
OUTPUT_PYC contians the output bytecode path name if supplied
The --conversion type option specifies what conversion to do.
Note: there are a v... | [
"def",
"main",
"(",
"conversion_type",
",",
"input_pyc",
",",
"output_pyc",
")",
":",
"shortname",
"=",
"osp",
".",
"basename",
"(",
"input_pyc",
")",
"if",
"shortname",
".",
"endswith",
"(",
"'.pyc'",
")",
":",
"shortname",
"=",
"shortname",
"[",
":",
"... | 43.59375 | 0.002104 |
def _load_same_codes(self, refresh=False):
"""Loads the Same Codes into this object"""
if refresh is True:
self._get_same_codes()
else:
self._cached_same_codes() | [
"def",
"_load_same_codes",
"(",
"self",
",",
"refresh",
"=",
"False",
")",
":",
"if",
"refresh",
"is",
"True",
":",
"self",
".",
"_get_same_codes",
"(",
")",
"else",
":",
"self",
".",
"_cached_same_codes",
"(",
")"
] | 34 | 0.009569 |
def _asStr(self):
'''
_asStr - Get the string representation of this style
@return <str> - A string representation of this style (semicolon separated, key: value format)
'''
styleDict = self._styleDict
if styleDict:
return '; '.join([name + ': ' + ... | [
"def",
"_asStr",
"(",
"self",
")",
":",
"styleDict",
"=",
"self",
".",
"_styleDict",
"if",
"styleDict",
":",
"return",
"'; '",
".",
"join",
"(",
"[",
"name",
"+",
"': '",
"+",
"value",
"for",
"name",
",",
"value",
"in",
"styleDict",
".",
"items",
"("... | 33.818182 | 0.010471 |
def get():
""" Only API function for the config module.
:return: {dict} loaded validated configuration.
"""
config = {}
try:
config = _load_config()
except IOError:
try:
_create_default_config()
config = _load_config()
except IOError as e:
... | [
"def",
"get",
"(",
")",
":",
"config",
"=",
"{",
"}",
"try",
":",
"config",
"=",
"_load_config",
"(",
")",
"except",
"IOError",
":",
"try",
":",
"_create_default_config",
"(",
")",
"config",
"=",
"_load_config",
"(",
")",
"except",
"IOError",
"as",
"e"... | 31.741935 | 0.000986 |
def get_surface_equilibrium(self, slab_entries, delu_dict=None):
"""
Takes in a list of SlabEntries and calculates the chemical potentials
at which all slabs in the list coexists simultaneously. Useful for
building surface phase diagrams. Note that to solve for x equations
... | [
"def",
"get_surface_equilibrium",
"(",
"self",
",",
"slab_entries",
",",
"delu_dict",
"=",
"None",
")",
":",
"# Generate all possible coefficients",
"all_parameters",
"=",
"[",
"]",
"all_eqns",
"=",
"[",
"]",
"for",
"slab_entry",
"in",
"slab_entries",
":",
"se",
... | 46.022727 | 0.002418 |
def mouse_aabb(mpos,size,pos):
"""
AABB Collision checker that can be used for most axis-aligned collisions.
Intended for use in widgets to check if the mouse is within the bounds of a particular widget.
"""
return pos[0]<=mpos[0]<=pos[0]+size[0] and pos[1]<=mpos[1]<=pos[1]+size[1] | [
"def",
"mouse_aabb",
"(",
"mpos",
",",
"size",
",",
"pos",
")",
":",
"return",
"pos",
"[",
"0",
"]",
"<=",
"mpos",
"[",
"0",
"]",
"<=",
"pos",
"[",
"0",
"]",
"+",
"size",
"[",
"0",
"]",
"and",
"pos",
"[",
"1",
"]",
"<=",
"mpos",
"[",
"1",
... | 43 | 0.029316 |
def _codec_error_url_quote(e):
"""Used in :func:`uri_to_iri` after unquoting to re-quote any
invalid bytes.
"""
out = _fast_url_quote(e.object[e.start : e.end])
if PY2:
out = out.decode("utf-8")
return out, e.end | [
"def",
"_codec_error_url_quote",
"(",
"e",
")",
":",
"out",
"=",
"_fast_url_quote",
"(",
"e",
".",
"object",
"[",
"e",
".",
"start",
":",
"e",
".",
"end",
"]",
")",
"if",
"PY2",
":",
"out",
"=",
"out",
".",
"decode",
"(",
"\"utf-8\"",
")",
"return"... | 23.7 | 0.00813 |
def get_error_message(response_content):
"""Extract error message from the HTTP response
:param response_content: HTTP response from test case execution API
:returns: error message
"""
apache_regex = re.compile('.*<u>(.*)</u></p><p>.*')
match = apache_regex.search(response_content)
if match... | [
"def",
"get_error_message",
"(",
"response_content",
")",
":",
"apache_regex",
"=",
"re",
".",
"compile",
"(",
"'.*<u>(.*)</u></p><p>.*'",
")",
"match",
"=",
"apache_regex",
".",
"search",
"(",
"response_content",
")",
"if",
"match",
":",
"error_message",
"=",
"... | 33.944444 | 0.001592 |
def slugify(field_name, slug_field_name=None, mutable=False):
"""Class decorator to specify a field to slugify. Slugs are immutable by
default unless mutable=True is passed.
Usage::
@slugify('title')
def Post(Model):
title = Column(String(100))
slug = Column(String(... | [
"def",
"slugify",
"(",
"field_name",
",",
"slug_field_name",
"=",
"None",
",",
"mutable",
"=",
"False",
")",
":",
"slug_field_name",
"=",
"slug_field_name",
"or",
"'slug'",
"def",
"_set_slug",
"(",
"target",
",",
"value",
",",
"old_value",
",",
"_",
",",
"... | 34.342105 | 0.000745 |
def create_api_v4_ipv6(self):
"""Get an instance of Api V4 IPv6 services facade."""
return ApiV4IPv6(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | [
"def",
"create_api_v4_ipv6",
"(",
"self",
")",
":",
"return",
"ApiV4IPv6",
"(",
"self",
".",
"networkapi_url",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"user_ldap",
")"
] | 27.75 | 0.008734 |
def step_impl07(context, len_list):
"""Check assertions.
:param len_list: expected number of variants.
:param context: test context.
"""
assert len(context.fuzzed_string_list) == len_list
for fuzzed_string in context.fuzzed_string_list:
assert len(context.seed) == len(fuzzed_string)
... | [
"def",
"step_impl07",
"(",
"context",
",",
"len_list",
")",
":",
"assert",
"len",
"(",
"context",
".",
"fuzzed_string_list",
")",
"==",
"len_list",
"for",
"fuzzed_string",
"in",
"context",
".",
"fuzzed_string_list",
":",
"assert",
"len",
"(",
"context",
".",
... | 36.545455 | 0.002427 |
def print2file(self, logfile, print2screen, addLineFeed, *lst):
""" This function prints to the screen and logs to a file, all the strings
given.
# print2screen eg. True, *lst is a commaseparated list of strings
"""
if addLineFeed:
linefeed = '\n'
else: linefeed = ''
i... | [
"def",
"print2file",
"(",
"self",
",",
"logfile",
",",
"print2screen",
",",
"addLineFeed",
",",
"*",
"lst",
")",
":",
"if",
"addLineFeed",
":",
"linefeed",
"=",
"'\\n'",
"else",
":",
"linefeed",
"=",
"''",
"if",
"print2screen",
":",
"print",
"(",
"linefe... | 46.809524 | 0.025922 |
def split_at_single(text, sep, not_before=[], not_after=[]):
"""Works like text.split(sep) but separated fragments
cant end with not_before or start with not_after"""
n = 0
lt, s = len(text), len(sep)
last = 0
while n < lt:
if not s + n > lt:
if sep == text[n:n + s]:
... | [
"def",
"split_at_single",
"(",
"text",
",",
"sep",
",",
"not_before",
"=",
"[",
"]",
",",
"not_after",
"=",
"[",
"]",
")",
":",
"n",
"=",
"0",
"lt",
",",
"s",
"=",
"len",
"(",
"text",
")",
",",
"len",
"(",
"sep",
")",
"last",
"=",
"0",
"while... | 34.105263 | 0.001502 |
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n | [
"def",
"empty",
"(",
"self",
")",
":",
"self",
".",
"mutex",
".",
"acquire",
"(",
")",
"n",
"=",
"not",
"self",
".",
"_qsize",
"(",
")",
"self",
".",
"mutex",
".",
"release",
"(",
")",
"return",
"n"
] | 33 | 0.014778 |
def TransformerLM(vocab_size,
feature_depth=512,
feedforward_depth=2048,
num_layers=6,
num_heads=8,
dropout=0.1,
max_len=2048,
mode='train'):
"""Transformer language model (only uses the decod... | [
"def",
"TransformerLM",
"(",
"vocab_size",
",",
"feature_depth",
"=",
"512",
",",
"feedforward_depth",
"=",
"2048",
",",
"num_layers",
"=",
"6",
",",
"num_heads",
"=",
"8",
",",
"dropout",
"=",
"0.1",
",",
"max_len",
"=",
"2048",
",",
"mode",
"=",
"'trai... | 34.457143 | 0.002419 |
def OneHot(*xs, simplify=True, conj=True):
"""
Return an expression that means
"exactly one input function is true".
If *simplify* is ``True``, return a simplified expression.
If *conj* is ``True``, return a CNF.
Otherwise, return a DNF.
"""
xs = [Expression.box(x).node for x in xs]
... | [
"def",
"OneHot",
"(",
"*",
"xs",
",",
"simplify",
"=",
"True",
",",
"conj",
"=",
"True",
")",
":",
"xs",
"=",
"[",
"Expression",
".",
"box",
"(",
"x",
")",
".",
"node",
"for",
"x",
"in",
"xs",
"]",
"terms",
"=",
"list",
"(",
")",
"if",
"conj"... | 31.730769 | 0.001176 |
def wait_callback(connection):
"""callback function suitable for ``psycopg2.set_wait_callback``
pass this function to ``psycopg2.extensions.set_wait_callack`` to force any
blocking operations from psycopg2 to only block the current coroutine,
rather than the entire thread or process
to undo the ch... | [
"def",
"wait_callback",
"(",
"connection",
")",
":",
"while",
"1",
":",
"state",
"=",
"connection",
".",
"poll",
"(",
")",
"if",
"state",
"==",
"extensions",
".",
"POLL_OK",
":",
"break",
"elif",
"state",
"==",
"extensions",
".",
"POLL_READ",
":",
"descr... | 38.666667 | 0.001202 |
def setOverlayAlpha(self, ulOverlayHandle, fAlpha):
"""Sets the alpha of the overlay quad. Use 1.0 for 100 percent opacity to 0.0 for 0 percent opacity."""
fn = self.function_table.setOverlayAlpha
result = fn(ulOverlayHandle, fAlpha)
return result | [
"def",
"setOverlayAlpha",
"(",
"self",
",",
"ulOverlayHandle",
",",
"fAlpha",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayAlpha",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"fAlpha",
")",
"return",
"result"
] | 45.833333 | 0.010714 |
def transaction_cost(self):
"""
[float] 总费用
"""
return sum(position.transaction_cost for position in six.itervalues(self._positions)) | [
"def",
"transaction_cost",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"position",
".",
"transaction_cost",
"for",
"position",
"in",
"six",
".",
"itervalues",
"(",
"self",
".",
"_positions",
")",
")"
] | 32.2 | 0.018182 |
def copy_dir(bucket_name, src_path, dest_path,
aws_access_key_id=None, aws_secret_access_key=None,
aws_profile=None,
surrogate_key=None, cache_control=None,
surrogate_control=None,
create_directory_redirect_object=True):
"""Copy objects from one direc... | [
"def",
"copy_dir",
"(",
"bucket_name",
",",
"src_path",
",",
"dest_path",
",",
"aws_access_key_id",
"=",
"None",
",",
"aws_secret_access_key",
"=",
"None",
",",
"aws_profile",
"=",
"None",
",",
"surrogate_key",
"=",
"None",
",",
"cache_control",
"=",
"None",
"... | 42 | 0.000175 |
def get_command_changes(self, current_commands, updated_commands):
"""
Compares the current command with updated command to return a 3-tuple of dicts,
keyed by command name: commands_to_kill, commands_to_keep and commands_to_start.
"""
commands_to_kill = {}
commands_to_keep = {}
commands_to_... | [
"def",
"get_command_changes",
"(",
"self",
",",
"current_commands",
",",
"updated_commands",
")",
":",
"commands_to_kill",
"=",
"{",
"}",
"commands_to_keep",
"=",
"{",
"}",
"commands_to_start",
"=",
"{",
"}",
"# if the current command has a matching command in the updated... | 47.592593 | 0.008391 |
def _apply_krauss_multi_qubit(krauss: Union[Tuple[Any], Sequence[Any]],
args: 'ApplyChannelArgs') -> np.ndarray:
"""Use numpy's einsum to apply a multi-qubit channel."""
for krauss_op in krauss:
np.copyto(dst=args.target_tensor, src=args.auxiliary_buffer0)
krauss_tensor = np.reshape(
... | [
"def",
"_apply_krauss_multi_qubit",
"(",
"krauss",
":",
"Union",
"[",
"Tuple",
"[",
"Any",
"]",
",",
"Sequence",
"[",
"Any",
"]",
"]",
",",
"args",
":",
"'ApplyChannelArgs'",
")",
"->",
"np",
".",
"ndarray",
":",
"for",
"krauss_op",
"in",
"krauss",
":",
... | 44.636364 | 0.001994 |
def shannon_entropy(time_series):
"""Return the Shannon Entropy of the sample data.
Args:
time_series: Vector or string of the sample data
Returns:
The Shannon Entropy as float value
"""
# Check if string
if not isinstance(time_series, str):
time_series = list(time_ser... | [
"def",
"shannon_entropy",
"(",
"time_series",
")",
":",
"# Check if string",
"if",
"not",
"isinstance",
"(",
"time_series",
",",
"str",
")",
":",
"time_series",
"=",
"list",
"(",
"time_series",
")",
"# Create a frequency data",
"data_set",
"=",
"list",
"(",
"set... | 23.566667 | 0.001359 |
def Logs(c_type=None, grep_list=None):
""" Generically filter logs stored in log containers """
def get_logs(logs, log_entries):
try:
for log in logs:
if str(container.name) in log_entries:
log_entries[str(container.name)].append(log)
else:... | [
"def",
"Logs",
"(",
"c_type",
"=",
"None",
",",
"grep_list",
"=",
"None",
")",
":",
"def",
"get_logs",
"(",
"logs",
",",
"log_entries",
")",
":",
"try",
":",
"for",
"log",
"in",
"logs",
":",
"if",
"str",
"(",
"container",
".",
"name",
")",
"in",
... | 39.928571 | 0.000436 |
def save(self, new=None, timeout=2):
"""write ALL_VERS_DATA to disk in 'pretty' format"""
if new: self.update(new) # allow two operations (update + save) with a single command
if not self._updated: return # nothing to do
thisPkg = os.path.dirname(__file__)
filename = os.path.join... | [
"def",
"save",
"(",
"self",
",",
"new",
"=",
"None",
",",
"timeout",
"=",
"2",
")",
":",
"if",
"new",
":",
"self",
".",
"update",
"(",
"new",
")",
"# allow two operations (update + save) with a single command",
"if",
"not",
"self",
".",
"_updated",
":",
"r... | 61.807692 | 0.016544 |
def post_object(self, container, obj, headers=None, query=None, cdn=False,
body=None):
"""
POSTs the object and returns the results. This is used to
update the object's header values. Note that all headers must
be sent with the POST, unlike the account and container P... | [
"def",
"post_object",
"(",
"self",
",",
"container",
",",
"obj",
",",
"headers",
"=",
"None",
",",
"query",
"=",
"None",
",",
"cdn",
"=",
"False",
",",
"body",
"=",
"None",
")",
":",
"path",
"=",
"self",
".",
"_object_path",
"(",
"container",
",",
... | 49.666667 | 0.001795 |
def flatten_subtree(self, name): # noqa: D302
r"""
Flatten sub-tree.
Nodes that have children and no data are merged with each child
:param name: Ending hierarchy node whose sub-trees are to be
flattened
:type name: :ref:`NodeName`
:raises:
... | [
"def",
"flatten_subtree",
"(",
"self",
",",
"name",
")",
":",
"# noqa: D302",
"if",
"self",
".",
"_validate_node_name",
"(",
"name",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Argument `name` is not valid\"",
")",
"self",
".",
"_node_in_tree",
"(",
"name",
")",
... | 33.233766 | 0.000759 |
def get_key_field(ui, ui_option_name, default_val=0, default_is_number=True):
"""
parse an option from a UI object as the name of a key field.
If the named option is not set, return the default values for the tuple.
:return: a tuple of two items, first is the value of the option, second is
... | [
"def",
"get_key_field",
"(",
"ui",
",",
"ui_option_name",
",",
"default_val",
"=",
"0",
",",
"default_is_number",
"=",
"True",
")",
":",
"key",
"=",
"default_val",
"key_is_field_number",
"=",
"default_is_number",
"if",
"ui",
".",
"optionIsSet",
"(",
"ui_option_n... | 36.05 | 0.012162 |
def text_remove_empty_lines(text):
"""
Whitespace normalization:
- Strip empty lines
- Strip trailing whitespace
"""
lines = [ line.rstrip() for line in text.splitlines() if line.strip() ]
return "\n".join(lines) | [
"def",
"text_remove_empty_lines",
"(",
"text",
")",
":",
"lines",
"=",
"[",
"line",
".",
"rstrip",
"(",
")",
"for",
"line",
"in",
"text",
".",
"splitlines",
"(",
")",
"if",
"line",
".",
"strip",
"(",
")",
"]",
"return",
"\"\\n\"",
".",
"join",
"(",
... | 26.555556 | 0.020243 |
def generate_adapter(adapter, name='url_for', map_name='url_map'):
"""Generates the url building function for a map."""
values = {
u'server_name': dumps(adapter.server_name),
u'script_name': dumps(adapter.script_name),
u'subdomain': dumps(adapter.subdomain),
u'url_s... | [
"def",
"generate_adapter",
"(",
"adapter",
",",
"name",
"=",
"'url_for'",
",",
"map_name",
"=",
"'url_map'",
")",
":",
"values",
"=",
"{",
"u'server_name'",
":",
"dumps",
"(",
"adapter",
".",
"server_name",
")",
",",
"u'script_name'",
":",
"dumps",
"(",
"a... | 33 | 0.001733 |
def get_context_for_help_msgs(self, context_dict):
""" We override this method from HelpMsgMixIn to replace wrapped_func with its name """
context_dict = copy(context_dict)
context_dict['wrapped_func'] = get_callable_name(context_dict['wrapped_func'])
return context_dict | [
"def",
"get_context_for_help_msgs",
"(",
"self",
",",
"context_dict",
")",
":",
"context_dict",
"=",
"copy",
"(",
"context_dict",
")",
"context_dict",
"[",
"'wrapped_func'",
"]",
"=",
"get_callable_name",
"(",
"context_dict",
"[",
"'wrapped_func'",
"]",
")",
"retu... | 59.8 | 0.013201 |
def explode(self, vector=None, origin=None):
"""
Explode a scene around a point and vector.
Parameters
-----------
vector : (3,) float or float
Explode radially around a direction vector or spherically
origin : (3,) float
Point to explode around
... | [
"def",
"explode",
"(",
"self",
",",
"vector",
"=",
"None",
",",
"origin",
"=",
"None",
")",
":",
"if",
"origin",
"is",
"None",
":",
"origin",
"=",
"self",
".",
"centroid",
"if",
"vector",
"is",
"None",
":",
"vector",
"=",
"self",
".",
"scale",
"/",... | 35 | 0.001463 |
def guard(params, guardian, error_class=GuardError, message=''):
'''
A guard function - check parameters
with guardian function on decorated function
:param tuple or string params: guarded function parameter/s
:param function guardian: verifying the conditions for the selected parameter
:param ... | [
"def",
"guard",
"(",
"params",
",",
"guardian",
",",
"error_class",
"=",
"GuardError",
",",
"message",
"=",
"''",
")",
":",
"params",
"=",
"[",
"params",
"]",
"if",
"isinstance",
"(",
"params",
",",
"string_types",
")",
"else",
"params",
"def",
"guard_de... | 37.809524 | 0.002457 |
def get_password(self, description='', confirm=False, clear=False):
"""Get the password from a Glances client or server.
For Glances server, get the password (confirm=True, clear=False):
1) from the password file (if it exists)
2) from the CLI
Optionally: save the passwo... | [
"def",
"get_password",
"(",
"self",
",",
"description",
"=",
"''",
",",
"confirm",
"=",
"False",
",",
"clear",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"password_file",
")",
"and",
"not",
"clear",
":",
"# If t... | 45.604651 | 0.002496 |
def get_module_class(class_path):
"""
imports and returns module class from ``path.to.module.Class``
argument
"""
mod_name, cls_name = class_path.rsplit('.', 1)
try:
mod = import_module(mod_name)
except ImportError as ex:
raise EvoStreamException('Error importing module %s: ... | [
"def",
"get_module_class",
"(",
"class_path",
")",
":",
"mod_name",
",",
"cls_name",
"=",
"class_path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"try",
":",
"mod",
"=",
"import_module",
"(",
"mod_name",
")",
"except",
"ImportError",
"as",
"ex",
":",
"ra... | 28.642857 | 0.002415 |
def phase_select_property(phase=None, s=None, l=None, g=None, V_over_F=None):
r'''Determines which phase's property should be set as a default, given
the phase a chemical is, and the property values of various phases. For the
case of liquid-gas phase, returns None. If the property is not available
for t... | [
"def",
"phase_select_property",
"(",
"phase",
"=",
"None",
",",
"s",
"=",
"None",
",",
"l",
"=",
"None",
",",
"g",
"=",
"None",
",",
"V_over_F",
"=",
"None",
")",
":",
"if",
"phase",
"==",
"'s'",
":",
"return",
"s",
"elif",
"phase",
"==",
"'l'",
... | 28.043478 | 0.002247 |
def _get_index_for_insert(self, key, instance):
"""Get the index of the key to insert before or after"""
if instance == 0:
# Index method will return the first occurence of the key
index = self.keys().index(key)
else:
occurrence = -1
for index, k i... | [
"def",
"_get_index_for_insert",
"(",
"self",
",",
"key",
",",
"instance",
")",
":",
"if",
"instance",
"==",
"0",
":",
"# Index method will return the first occurence of the key",
"index",
"=",
"self",
".",
"keys",
"(",
")",
".",
"index",
"(",
"key",
")",
"else... | 43.16 | 0.001813 |
def add_chain(self, group_name, component_map):
"""
Adds the component chain to ``group_name`` in the fast5.
These are added as attributes to the group.
:param group_name: The group name you wish to add chaining data to,
e.g. ``Test_000``
:param component_map: The se... | [
"def",
"add_chain",
"(",
"self",
",",
"group_name",
",",
"component_map",
")",
":",
"self",
".",
"assert_writeable",
"(",
")",
"for",
"component",
",",
"path",
"in",
"component_map",
".",
"items",
"(",
")",
":",
"if",
"not",
"path",
".",
"startswith",
"(... | 41.192308 | 0.001825 |
def sls(name, mods=None, **kwargs):
'''
Apply the states defined by the specified SLS modules to the running
container
.. versionadded:: 2016.11.0
The container does not need to have Salt installed, but Python is required.
name
Container name or ID
mods : None
A string co... | [
"def",
"sls",
"(",
"name",
",",
"mods",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"mods",
"=",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in",
"mods",
".",
"split",
"(",
"','",
")",
"]",
"if",
"mods",
"else",
"[",
"]",
"# Figu... | 31.886957 | 0.000264 |
def _get_embedded(self, name):
'''
Return an embedded struct object to calculate the size or use _tobytes(True) to convert just the
embedded parts.
:param name: either the original type, or the name of the original type. It is always the type
used in type de... | [
"def",
"_get_embedded",
"(",
"self",
",",
"name",
")",
":",
"if",
"hasattr",
"(",
"name",
",",
"'readablename'",
")",
":",
"name",
"=",
"name",
".",
"readablename",
"t",
",",
"i",
"=",
"self",
".",
"_target",
".",
"_embedded_indices",
"[",
"name",
"]",... | 41.142857 | 0.013582 |
def compute_md5(fp, buf_size=8192, size=None):
"""
Compute MD5 hash on passed file and return results in a tuple of values.
:type fp: file
:param fp: File pointer to the file to MD5 hash. The file pointer
will be reset to its current location before the
method returns.
... | [
"def",
"compute_md5",
"(",
"fp",
",",
"buf_size",
"=",
"8192",
",",
"size",
"=",
"None",
")",
":",
"m",
"=",
"md5",
"(",
")",
"spos",
"=",
"fp",
".",
"tell",
"(",
")",
"if",
"size",
"and",
"size",
"<",
"buf_size",
":",
"s",
"=",
"fp",
".",
"r... | 32.510204 | 0.000609 |
def join(self, t2, unique=False):
"""
Join this triangulation with another. If the points are known to have no duplicates, then
set unique=False to skip the testing and duplicate removal
"""
x_v1 = np.concatenate((self.x, t2.x), axis=0)
y_v1 = np.concatenate((self.y, t2.... | [
"def",
"join",
"(",
"self",
",",
"t2",
",",
"unique",
"=",
"False",
")",
":",
"x_v1",
"=",
"np",
".",
"concatenate",
"(",
"(",
"self",
".",
"x",
",",
"t2",
".",
"x",
")",
",",
"axis",
"=",
"0",
")",
"y_v1",
"=",
"np",
".",
"concatenate",
"(",... | 34.95 | 0.009749 |
def check_order_triggers(self, current_price):
"""
Given an order and a trade event, return a tuple of
(stop_reached, limit_reached).
For market orders, will return (False, False).
For stop orders, limit_reached will always be False.
For limit orders, stop_reached will al... | [
"def",
"check_order_triggers",
"(",
"self",
",",
"current_price",
")",
":",
"if",
"self",
".",
"triggered",
":",
"return",
"(",
"self",
".",
"stop_reached",
",",
"self",
".",
"limit_reached",
",",
"False",
")",
"stop_reached",
"=",
"False",
"limit_reached",
... | 34.12069 | 0.000982 |
def parse(self, response):
"""
从 self.data 中将文章信息格式化为 :class:`.MoearPackageMobiItem`
"""
# 工作&输出路径
self.template_dir = self.settings.get('TEMPLATE_DIR')
shutil.rmtree(
self.settings.get('BUILD_SOURCE_DIR'), ignore_errors=True)
self.build_source_dir = u... | [
"def",
"parse",
"(",
"self",
",",
"response",
")",
":",
"# 工作&输出路径",
"self",
".",
"template_dir",
"=",
"self",
".",
"settings",
".",
"get",
"(",
"'TEMPLATE_DIR'",
")",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"settings",
".",
"get",
"(",
"'BUILD_SOURCE... | 43.023256 | 0.001057 |
def get_transaction_id(transaction, read_operation=True):
"""Get the transaction ID from a ``Transaction`` object.
Args:
transaction (Optional[~.firestore_v1beta1.transaction.\
Transaction]): An existing transaction that this query will
run in.
read_operation (Optional[b... | [
"def",
"get_transaction_id",
"(",
"transaction",
",",
"read_operation",
"=",
"True",
")",
":",
"if",
"transaction",
"is",
"None",
":",
"return",
"None",
"else",
":",
"if",
"not",
"transaction",
".",
"in_progress",
":",
"raise",
"ValueError",
"(",
"INACTIVE_TXN... | 39.25 | 0.000888 |
def is_generic_union(type_: Type) -> bool:
"""Determines whether a type is a Union[...].
How to do this varies for different Python versions, due to the
typing library not having a stable API. This functions smooths
over the differences.
Args:
type_: The type to check.
Returns:
... | [
"def",
"is_generic_union",
"(",
"type_",
":",
"Type",
")",
"->",
"bool",
":",
"if",
"hasattr",
"(",
"typing",
",",
"'_GenericAlias'",
")",
":",
"# 3.7",
"return",
"(",
"isinstance",
"(",
"type_",
",",
"typing",
".",
"_GenericAlias",
")",
"and",
"# type: ig... | 35.884615 | 0.001044 |
def parse_n3(row, src='csv'):
"""
takes a row from an n3 file and returns the triple
NOTE - currently parses a CSV line already split via
cyc_extract.py
"""
if row.strip() == '':
return '',''
l_root = 'opencyc'
key = ''
val = ''
if src == 'csv':
cols = row.split... | [
"def",
"parse_n3",
"(",
"row",
",",
"src",
"=",
"'csv'",
")",
":",
"if",
"row",
".",
"strip",
"(",
")",
"==",
"''",
":",
"return",
"''",
",",
"''",
"l_root",
"=",
"'opencyc'",
"key",
"=",
"''",
"val",
"=",
"''",
"if",
"src",
"==",
"'csv'",
":",... | 26.846154 | 0.009682 |
def parse_content_range_header(value, on_update=None):
"""Parses a range header into a
:class:`~werkzeug.datastructures.ContentRange` object or `None` if
parsing is not possible.
.. versionadded:: 0.7
:param value: a content range header to be parsed.
:param on_update: an optional callable tha... | [
"def",
"parse_content_range_header",
"(",
"value",
",",
"on_update",
"=",
"None",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"try",
":",
"units",
",",
"rangedef",
"=",
"(",
"value",
"or",
"''",
")",
".",
"strip",
"(",
")",
".",
"sp... | 28.44186 | 0.000791 |
def increment_cell_value(self, column_family_id, column, int_value):
"""Increments a value in an existing cell.
Assumes the value in the cell is stored as a 64 bit integer
serialized to bytes.
.. note::
This method adds a read-modify rule protobuf to the accumulated
... | [
"def",
"increment_cell_value",
"(",
"self",
",",
"column_family_id",
",",
"column",
",",
"int_value",
")",
":",
"column",
"=",
"_to_bytes",
"(",
"column",
")",
"rule_pb",
"=",
"data_v2_pb2",
".",
"ReadModifyWriteRule",
"(",
"family_name",
"=",
"column_family_id",
... | 41.372093 | 0.001098 |
def get_commit_log(name, vendor='pypi', functions={}, _depth=0):
"""
Tries to parse a changelog from the raw commit log.
:param name: str, package name
:param vendor: str, vendor
:param functions: dict, custom functions
:return: tuple, (dict -> commit log, str -> raw git log)
"""
if "fin... | [
"def",
"get_commit_log",
"(",
"name",
",",
"vendor",
"=",
"'pypi'",
",",
"functions",
"=",
"{",
"}",
",",
"_depth",
"=",
"0",
")",
":",
"if",
"\"find_changelogs\"",
"not",
"in",
"functions",
":",
"from",
".",
"finder",
"import",
"find_git_repo",
"functions... | 34.619048 | 0.001339 |
def _boundary_value(self) -> str:
"""Wrap boundary parameter value in quotes, if necessary.
Reads self.boundary and returns a unicode sting.
"""
# Refer to RFCs 7231, 7230, 5234.
#
# parameter = token "=" ( token / quoted-string )
# token = 1*tchar
... | [
"def",
"_boundary_value",
"(",
"self",
")",
"->",
"str",
":",
"# Refer to RFCs 7231, 7230, 5234.",
"#",
"# parameter = token \"=\" ( token / quoted-string )",
"# token = 1*tchar",
"# quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE",
"# qdtext = HTAB / SP / %x... | 44 | 0.001483 |
def moderate(self, environ, request, id, action, key):
try:
id = self.isso.unsign(key, max_age=2**32)
except (BadSignature, SignatureExpired):
raise Forbidden
item = self.comments.get(id)
thread = self.threads.get(item['tid'])
link = local("origin") + thr... | [
"def",
"moderate",
"(",
"self",
",",
"environ",
",",
"request",
",",
"id",
",",
"action",
",",
"key",
")",
":",
"try",
":",
"id",
"=",
"self",
".",
"isso",
".",
"unsign",
"(",
"key",
",",
"max_age",
"=",
"2",
"**",
"32",
")",
"except",
"(",
"Ba... | 41.691176 | 0.002412 |
def captured_today(self):
"""Return list of <ArloVideo> object captured today."""
if self._cached_videos is None:
self.make_video_cache()
return [vdo for vdo in self._cached_videos if vdo.created_today] | [
"def",
"captured_today",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cached_videos",
"is",
"None",
":",
"self",
".",
"make_video_cache",
"(",
")",
"return",
"[",
"vdo",
"for",
"vdo",
"in",
"self",
".",
"_cached_videos",
"if",
"vdo",
".",
"created_today",
... | 39 | 0.008368 |
def print_2x2_table(table, row_labels, col_labels, fmt="%d"):
"""
Prints a table used for Fisher's exact test. Adds row, column, and grand
totals.
:param table: The four cells of a 2x2 table: [r1c1, r1c2, r2c1, r2c2]
:param row_labels: A length-2 list of row names
:param col_labels: A length-2 ... | [
"def",
"print_2x2_table",
"(",
"table",
",",
"row_labels",
",",
"col_labels",
",",
"fmt",
"=",
"\"%d\"",
")",
":",
"grand",
"=",
"sum",
"(",
"table",
")",
"# Separate table into components and get row/col sums",
"t11",
",",
"t12",
",",
"t21",
",",
"t22",
"=",
... | 29.245614 | 0.00058 |
def read_with_selection(func):
"""Decorate a Table read method to apply ``selection`` keyword
"""
def wrapper(*args, **kwargs):
"""Execute a function, then apply a selection filter
"""
# parse selection
selection = kwargs.pop('selection', None) or []
# read table
... | [
"def",
"read_with_selection",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Execute a function, then apply a selection filter\n \"\"\"",
"# parse selection",
"selection",
"=",
"kwargs",
".",
"pop",
"(",
"... | 25.789474 | 0.001969 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.