text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def channels(self):
"""List[:class:`abc.GuildChannel`]: Returns the channels that are under this category.
These are sorted by the official Discord UI, which places voice channels below the text channels.
"""
def comparator(channel):
return (not isinstance(channel, TextChann... | [
"def",
"channels",
"(",
"self",
")",
":",
"def",
"comparator",
"(",
"channel",
")",
":",
"return",
"(",
"not",
"isinstance",
"(",
"channel",
",",
"TextChannel",
")",
",",
"channel",
".",
"position",
")",
"ret",
"=",
"[",
"c",
"for",
"c",
"in",
"self"... | 41.818182 | 0.008511 |
def rel_humid_from_db_enth(db_temp, enthalpy, b_press=101325):
"""Relative Humidity (%) at db_temp (C), enthalpy (kJ/kg)
and Pressure b_press (Pa).
"""
assert enthalpy >= 0, 'enthalpy must be' \
'greater than 0. Got {}'.format(str(enthalpy))
hr = (enthalpy - (1.006 * db_temp)) / ((1.84 * db_... | [
"def",
"rel_humid_from_db_enth",
"(",
"db_temp",
",",
"enthalpy",
",",
"b_press",
"=",
"101325",
")",
":",
"assert",
"enthalpy",
">=",
"0",
",",
"'enthalpy must be'",
"'greater than 0. Got {}'",
".",
"format",
"(",
"str",
"(",
"enthalpy",
")",
")",
"hr",
"=",
... | 45 | 0.002421 |
def na_omit(self):
"""
Remove rows with NAs from the H2OFrame.
:returns: new H2OFrame with all rows from the original frame containing any NAs removed.
"""
fr = H2OFrame._expr(expr=ExprNode("na.omit", self), cache=self._ex._cache)
fr._ex._cache.nrows = -1
return ... | [
"def",
"na_omit",
"(",
"self",
")",
":",
"fr",
"=",
"H2OFrame",
".",
"_expr",
"(",
"expr",
"=",
"ExprNode",
"(",
"\"na.omit\"",
",",
"self",
")",
",",
"cache",
"=",
"self",
".",
"_ex",
".",
"_cache",
")",
"fr",
".",
"_ex",
".",
"_cache",
".",
"nr... | 34.888889 | 0.012422 |
def remove(self, val):
"""
Remove first occurrence of *val*.
Raises ValueError if *val* is not present.
"""
_maxes = self._maxes
if not _maxes:
raise ValueError('{0} not in list'.format(repr(val)))
key = self._key(val)
pos = bisect_left(_max... | [
"def",
"remove",
"(",
"self",
",",
"val",
")",
":",
"_maxes",
"=",
"self",
".",
"_maxes",
"if",
"not",
"_maxes",
":",
"raise",
"ValueError",
"(",
"'{0} not in list'",
".",
"format",
"(",
"repr",
"(",
"val",
")",
")",
")",
"key",
"=",
"self",
".",
"... | 28.432432 | 0.001838 |
def getWinner(self, type = 'activation'):
"""
Returns the winner of the type specified {'activation' or
'target'}.
"""
maxvalue = -10000
maxpos = -1
ttlvalue = 0
if type == 'activation':
ttlvalue = Numeric.add.reduce(self.activation)
... | [
"def",
"getWinner",
"(",
"self",
",",
"type",
"=",
"'activation'",
")",
":",
"maxvalue",
"=",
"-",
"10000",
"maxpos",
"=",
"-",
"1",
"ttlvalue",
"=",
"0",
"if",
"type",
"==",
"'activation'",
":",
"ttlvalue",
"=",
"Numeric",
".",
"add",
".",
"reduce",
... | 41.37931 | 0.009772 |
def verify_signature(self, addr):
"""
Given an address, verify whether or not it was signed by it
"""
return verify(virtualchain.address_reencode(addr), self.get_plaintext_to_sign(), self.sig) | [
"def",
"verify_signature",
"(",
"self",
",",
"addr",
")",
":",
"return",
"verify",
"(",
"virtualchain",
".",
"address_reencode",
"(",
"addr",
")",
",",
"self",
".",
"get_plaintext_to_sign",
"(",
")",
",",
"self",
".",
"sig",
")"
] | 44 | 0.013393 |
def get_suppressions(relative_filepaths, root, messages):
"""
Given every message which was emitted by the tools, and the
list of files to inspect, create a list of files to ignore,
and a map of filepath -> line-number -> codes to ignore
"""
paths_to_ignore = set()
lines_to_ignore = defaultd... | [
"def",
"get_suppressions",
"(",
"relative_filepaths",
",",
"root",
",",
"messages",
")",
":",
"paths_to_ignore",
"=",
"set",
"(",
")",
"lines_to_ignore",
"=",
"defaultdict",
"(",
"set",
")",
"messages_to_ignore",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultd... | 43.684211 | 0.002357 |
def contains(self, key):
"Exact matching."
index = self.follow_bytes(key, self.ROOT)
if index is None:
return False
return self.has_value(index) | [
"def",
"contains",
"(",
"self",
",",
"key",
")",
":",
"index",
"=",
"self",
".",
"follow_bytes",
"(",
"key",
",",
"self",
".",
"ROOT",
")",
"if",
"index",
"is",
"None",
":",
"return",
"False",
"return",
"self",
".",
"has_value",
"(",
"index",
")"
] | 30.5 | 0.010638 |
def value_derived_from_wavefunction(self,
state: np.ndarray,
qubit_map: Dict[raw_types.Qid, int]
) -> Any:
"""The value of the display, derived from the full wavefunction.
Args:
... | [
"def",
"value_derived_from_wavefunction",
"(",
"self",
",",
"state",
":",
"np",
".",
"ndarray",
",",
"qubit_map",
":",
"Dict",
"[",
"raw_types",
".",
"Qid",
",",
"int",
"]",
")",
"->",
"Any",
":"
] | 43.636364 | 0.012245 |
def edit(request):
"""
Process the inline editing form.
"""
model = apps.get_model(request.POST["app"], request.POST["model"])
obj = model.objects.get(id=request.POST["id"])
form = get_edit_form(obj, request.POST["fields"], data=request.POST,
files=request.FILES)
if ... | [
"def",
"edit",
"(",
"request",
")",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"request",
".",
"POST",
"[",
"\"app\"",
"]",
",",
"request",
".",
"POST",
"[",
"\"model\"",
"]",
")",
"obj",
"=",
"model",
".",
"objects",
".",
"get",
"(",
"id",
... | 40 | 0.001285 |
def __threshold(self, ymx_i):
"""
Calculates the difference threshold for a
given difference local maximum.
Parameters
-----------
ymx_i : float
The normalized y value of a local maximum.
"""
return ymx_i - (self.S * np.diff(self.xsn).mean()) | [
"def",
"__threshold",
"(",
"self",
",",
"ymx_i",
")",
":",
"return",
"ymx_i",
"-",
"(",
"self",
".",
"S",
"*",
"np",
".",
"diff",
"(",
"self",
".",
"xsn",
")",
".",
"mean",
"(",
")",
")"
] | 28.090909 | 0.009404 |
def setEditorData( self, editor, value ):
"""
Sets the value for the given editor to the inputed value.
:param editor | <QWidget>
value | <variant>
"""
# set the data for a multitagedit
if ( isinstance(editor, XMultiTag... | [
"def",
"setEditorData",
"(",
"self",
",",
"editor",
",",
"value",
")",
":",
"# set the data for a multitagedit\r",
"if",
"(",
"isinstance",
"(",
"editor",
",",
"XMultiTagEdit",
")",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
... | 35.321429 | 0.016732 |
def get_upvoted(self, *args, **kwargs):
"""Return a listing of the Submissions the user has upvoted.
:returns: get_content generator of Submission items.
The additional parameters are passed directly into
:meth:`.get_content`. Note: the `url` parameter cannot be altered.
As a ... | [
"def",
"get_upvoted",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_use_oauth'",
"]",
"=",
"self",
".",
"reddit_session",
".",
"is_oauth_session",
"(",
")",
"return",
"_get_redditor_listing",
"(",
"'upvoted'",
")",
"("... | 47 | 0.002454 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'response_type') and self.response_type is not None:
_dict['response_type'] = self.response_type
if hasattr(self, 'text') and self.text is not None:
_dict['text... | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'response_type'",
")",
"and",
"self",
".",
"response_type",
"is",
"not",
"None",
":",
"_dict",
"[",
"'response_type'",
"]",
"=",
"self",
".",
"respons... | 54.387097 | 0.001748 |
def process_uclust_pw_alignment_results(fasta_pairs_lines, uc_lines):
""" Process results of uclust search and align """
alignments = get_next_two_fasta_records(fasta_pairs_lines)
for hit in get_next_record_type(uc_lines, 'H'):
matching_strand = hit[4]
if matching_strand == '-':
... | [
"def",
"process_uclust_pw_alignment_results",
"(",
"fasta_pairs_lines",
",",
"uc_lines",
")",
":",
"alignments",
"=",
"get_next_two_fasta_records",
"(",
"fasta_pairs_lines",
")",
"for",
"hit",
"in",
"get_next_record_type",
"(",
"uc_lines",
",",
"'H'",
")",
":",
"match... | 39.058824 | 0.001469 |
def open_in_browser(file_location):
"""Attempt to open file located at file_location in the default web
browser."""
# If just the name of the file was given, check if it's in the Current
# Working Directory.
if not os.path.isfile(file_location):
file_location = os.path.join(os.getcwd(), fil... | [
"def",
"open_in_browser",
"(",
"file_location",
")",
":",
"# If just the name of the file was given, check if it's in the Current",
"# Working Directory.",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"file_location",
")",
":",
"file_location",
"=",
"os",
".",
"p... | 38.470588 | 0.001493 |
def duration(self):
'''
The approximate transit duration for the general case of an eccentric orbit
'''
ecc = self.ecc if not np.isnan(self.ecc) else np.sqrt(self.ecw**2 + self.esw**2)
esw = self.esw if not np.isnan(self.esw) else ecc * np.sin(self.w)
aRs = ((G *... | [
"def",
"duration",
"(",
"self",
")",
":",
"ecc",
"=",
"self",
".",
"ecc",
"if",
"not",
"np",
".",
"isnan",
"(",
"self",
".",
"ecc",
")",
"else",
"np",
".",
"sqrt",
"(",
"self",
".",
"ecw",
"**",
"2",
"+",
"self",
".",
"esw",
"**",
"2",
")",
... | 45.733333 | 0.011429 |
def adict(*classes):
'''Install one or more classes to be handled as dict.
'''
a = True
for c in classes:
# if class is dict-like, add class
# name to _dict_classes[module]
if isclass(c) and _infer_dict(c):
t = _dict_classes.get(c.__module__, ())
if c.__... | [
"def",
"adict",
"(",
"*",
"classes",
")",
":",
"a",
"=",
"True",
"for",
"c",
"in",
"classes",
":",
"# if class is dict-like, add class",
"# name to _dict_classes[module]",
"if",
"isclass",
"(",
"c",
")",
"and",
"_infer_dict",
"(",
"c",
")",
":",
"t",
"=",
... | 34.071429 | 0.010204 |
def boundary_difference_exponential(graph, xxx_todo_changeme4):
r"""
Boundary term processing adjacent voxels difference value using an exponential relationship.
An implementation of a boundary term, suitable to be used with the
`~medpy.graphcut.generate.graph_from_voxels` function.
Finds ... | [
"def",
"boundary_difference_exponential",
"(",
"graph",
",",
"xxx_todo_changeme4",
")",
":",
"(",
"original_image",
",",
"sigma",
",",
"spacing",
")",
"=",
"xxx_todo_changeme4",
"original_image",
"=",
"scipy",
".",
"asarray",
"(",
"original_image",
")",
"def",
"bo... | 41.209677 | 0.009939 |
def merge(left, right):
"""
deep merge dictionary on the left with the one
on the right.
Fill in left dictionary with right one where
the value of the key from the right one in
the left one is missing or None.
"""
if isinstance(left, dict) and isinstance(right, dict):
for key, v... | [
"def",
"merge",
"(",
"left",
",",
"right",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"dict",
")",
"and",
"isinstance",
"(",
"right",
",",
"dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"right",
".",
"items",
"(",
")",
":",
"if",
"key",... | 30.388889 | 0.001773 |
def is_cursor_on_first_line(self):
"""Return True if cursor is on the first line"""
cursor = self.textCursor()
cursor.movePosition(QTextCursor.StartOfBlock)
return cursor.atStart() | [
"def",
"is_cursor_on_first_line",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"StartOfBlock",
")",
"return",
"cursor",
".",
"atStart",
"(",
")"
] | 42.4 | 0.009259 |
def generateVariantAnnotation(self, variant):
"""
Generate a random variant annotation based on a given variant.
This generator should be seeded with a value that is unique to the
variant so that the same annotation will always be produced regardless
of the order it is generated ... | [
"def",
"generateVariantAnnotation",
"(",
"self",
",",
"variant",
")",
":",
"# To make this reproducible, make a seed based on this",
"# specific variant.",
"seed",
"=",
"self",
".",
"_randomSeed",
"+",
"variant",
".",
"start",
"+",
"variant",
".",
"end",
"randomNumberGe... | 48.416667 | 0.001688 |
def get_template(template_name, using=None):
"""
Loads and returns a template for the given name.
Raises TemplateDoesNotExist if no such template exists.
"""
engines = _engine_list(using)
for engine in engines:
try:
return engine.get_template(template_name)
except Tem... | [
"def",
"get_template",
"(",
"template_name",
",",
"using",
"=",
"None",
")",
":",
"engines",
"=",
"_engine_list",
"(",
"using",
")",
"for",
"engine",
"in",
"engines",
":",
"try",
":",
"return",
"engine",
".",
"get_template",
"(",
"template_name",
")",
"exc... | 30.384615 | 0.002457 |
def get_station_observation(station_code, token):
"""Request station data for a specific station identified by code.
A language parameter can also be specified to translate location
information (default: "en")
"""
req = requests.get(
API_ENDPOINT_OBS % (station_code),
params={
... | [
"def",
"get_station_observation",
"(",
"station_code",
",",
"token",
")",
":",
"req",
"=",
"requests",
".",
"get",
"(",
"API_ENDPOINT_OBS",
"%",
"(",
"station_code",
")",
",",
"params",
"=",
"{",
"'token'",
":",
"token",
"}",
")",
"if",
"req",
".",
"stat... | 30.75 | 0.001972 |
def a(text, mode='exec', indent=' ', file=None):
"""
Interactive convenience for displaying the AST of a code string.
Writes a pretty-formatted AST-tree to `file`.
Parameters
----------
text : str
Text of Python code to render as AST.
mode : {'exec', 'eval'}, optional
Mode... | [
"def",
"a",
"(",
"text",
",",
"mode",
"=",
"'exec'",
",",
"indent",
"=",
"' '",
",",
"file",
"=",
"None",
")",
":",
"pprint_ast",
"(",
"parse",
"(",
"text",
",",
"mode",
"=",
"mode",
")",
",",
"indent",
"=",
"indent",
",",
"file",
"=",
"file",
... | 35.052632 | 0.001462 |
def _request(self, method, url, params=None, uploads=None):
""" Request to server and handle transfer status. """
c = pycurl.Curl()
if method == self.POST:
c.setopt(c.POST, 1)
if uploads is not None:
if isinstance(uploads, dict):
# han... | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"params",
"=",
"None",
",",
"uploads",
"=",
"None",
")",
":",
"c",
"=",
"pycurl",
".",
"Curl",
"(",
")",
"if",
"method",
"==",
"self",
".",
"POST",
":",
"c",
".",
"setopt",
"(",
"c... | 30.474576 | 0.001616 |
def show_bandwidth_limit_rule(self, rule, policy, body=None):
"""Fetches information of a certain bandwidth limit rule."""
return self.get(self.qos_bandwidth_limit_rule_path %
(policy, rule), body=body) | [
"def",
"show_bandwidth_limit_rule",
"(",
"self",
",",
"rule",
",",
"policy",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"qos_bandwidth_limit_rule_path",
"%",
"(",
"policy",
",",
"rule",
")",
",",
"body",
"=",
"bod... | 59.75 | 0.008264 |
def calcDistMatchArr(matchArr, tKey, mKey):
"""Calculate the euclidean distance of all array positions in "matchArr".
:param matchArr: a dictionary of ``numpy.arrays`` containing at least two
entries that are treated as cartesian coordinates.
:param tKey: #TODO: docstring
:param mKey: #TODO: do... | [
"def",
"calcDistMatchArr",
"(",
"matchArr",
",",
"tKey",
",",
"mKey",
")",
":",
"#Calculate all sorted list of all eucledian feature distances",
"matchArrSize",
"=",
"listvalues",
"(",
"matchArr",
")",
"[",
"0",
"]",
".",
"size",
"distInfo",
"=",
"{",
"'posPairs'",
... | 37.935484 | 0.002488 |
def lemmatize(self, text):
"""Return a list of (lemma, tag) tuples.
:param str text: A string.
"""
#: Do not process empty strings (Issue #3)
if text.strip() == "":
return []
parsed_sentences = self._parse_text(text)
_lemmalist = []
for s in ... | [
"def",
"lemmatize",
"(",
"self",
",",
"text",
")",
":",
"#: Do not process empty strings (Issue #3)",
"if",
"text",
".",
"strip",
"(",
")",
"==",
"\"\"",
":",
"return",
"[",
"]",
"parsed_sentences",
"=",
"self",
".",
"_parse_text",
"(",
"text",
")",
"_lemmal... | 41.473684 | 0.00186 |
def stmts_from_json(json_in, on_missing_support='handle'):
"""Get a list of Statements from Statement jsons.
In the case of pre-assembled Statements which have `supports` and
`supported_by` lists, the uuids will be replaced with references to
Statement objects from the json, where possible. The method ... | [
"def",
"stmts_from_json",
"(",
"json_in",
",",
"on_missing_support",
"=",
"'handle'",
")",
":",
"stmts",
"=",
"[",
"]",
"uuid_dict",
"=",
"{",
"}",
"for",
"json_stmt",
"in",
"json_in",
":",
"try",
":",
"st",
"=",
"Statement",
".",
"_from_json",
"(",
"jso... | 38.591837 | 0.000516 |
def _AtNonLeaf(self, attr_value, path):
"""Called when at a non-leaf value. Should recurse and yield values."""
try:
if isinstance(attr_value, collections.Mapping):
# If it's dictionary-like, treat the dict key as the attribute..
sub_obj = attr_value.get(path[1])
if len(path) > 2:
... | [
"def",
"_AtNonLeaf",
"(",
"self",
",",
"attr_value",
",",
"path",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"attr_value",
",",
"collections",
".",
"Mapping",
")",
":",
"# If it's dictionary-like, treat the dict key as the attribute..",
"sub_obj",
"=",
"attr_val... | 41.62963 | 0.010435 |
def draw_diagram(graph, pos=None, with_labels=True, offset=None, **kwds):
"""
Draw a diagram for graph using Matplotlib.
Draw graph as a simple energy diagram with Matplotlib with options for node
positions, labeling, titles, and many other drawing features. See examples
below.
Parameters
... | [
"def",
"draw_diagram",
"(",
"graph",
",",
"pos",
"=",
"None",
",",
"with_labels",
"=",
"True",
",",
"offset",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"pos",
"is",
"None",
":",
"pos",
"=",
"diagram_layout",
"(",
"graph",
",",
"*",
"*",
... | 41.686567 | 0.00035 |
def str_dict_keys(a_dict):
"""return a modified dict where all the keys that are anything but str get
converted to str.
E.g.
>>> result = str_dict_keys({u'name': u'Peter', u'age': 99, 1: 2})
>>> # can't compare whole dicts in doctests
>>> result['name']
u'Peter'
>>> result['ag... | [
"def",
"str_dict_keys",
"(",
"a_dict",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"key",
"in",
"a_dict",
":",
"if",
"six",
".",
"PY2",
"and",
"isinstance",
"(",
"key",
",",
"six",
".",
"text_type",
")",
":",
"new_dict",
"[",
"str",
"(",
"key",
")"... | 31.525 | 0.000769 |
def externals_finder(dirname, filename):
"""Find any 'svn:externals' directories"""
found = False
f = open(filename,'rt')
for line in iter(f.readline, ''): # can't use direct iter!
parts = line.split()
if len(parts)==2:
kind,length = parts
data = f.read(int(len... | [
"def",
"externals_finder",
"(",
"dirname",
",",
"filename",
")",
":",
"found",
"=",
"False",
"f",
"=",
"open",
"(",
"filename",
",",
"'rt'",
")",
"for",
"line",
"in",
"iter",
"(",
"f",
".",
"readline",
",",
"''",
")",
":",
"# can't use direct iter!",
"... | 29.227273 | 0.010542 |
def partial_fit(self, X, y, classes=None):
"""
Runs a single epoch using the provided data
:return: This instance
"""
return self.fit(X, y, epochs=1) | [
"def",
"partial_fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"classes",
"=",
"None",
")",
":",
"return",
"self",
".",
"fit",
"(",
"X",
",",
"y",
",",
"epochs",
"=",
"1",
")"
] | 26.285714 | 0.010526 |
def reactToAMQPMessage(message, sender):
"""
React to given (AMQP) message. `message` is usually expected to be
:py:func:`collections.namedtuple` structure filled with all necessary data.
Args:
message (\*Request class): One of the structures defined in
:mod:`.requests`.
... | [
"def",
"reactToAMQPMessage",
"(",
"message",
",",
"sender",
")",
":",
"if",
"_instanceof",
"(",
"message",
",",
"GenerateContract",
")",
":",
"return",
"pdf_from_file",
"(",
"# TODO: rewrite to decorator",
"get_contract",
"(",
"*",
"*",
"message",
".",
"_asdict",
... | 34.085714 | 0.00163 |
def setup_components_and_tf_funcs(self, custom_getter=None):
"""
Constructs the memory and the optimizer objects.
Generates and stores all template functions.
"""
custom_getter = super(MemoryModel, self).setup_components_and_tf_funcs(custom_getter)
# Memory
self.... | [
"def",
"setup_components_and_tf_funcs",
"(",
"self",
",",
"custom_getter",
"=",
"None",
")",
":",
"custom_getter",
"=",
"super",
"(",
"MemoryModel",
",",
"self",
")",
".",
"setup_components_and_tf_funcs",
"(",
"custom_getter",
")",
"# Memory",
"self",
".",
"memory... | 33.516129 | 0.001403 |
def encode(self,
data: mx.sym.Symbol,
data_length: Optional[mx.sym.Symbol],
seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]:
"""
Encodes data given sequence lengths of individual examples and maximum sequence length.
:param data: Input data... | [
"def",
"encode",
"(",
"self",
",",
"data",
":",
"mx",
".",
"sym",
".",
"Symbol",
",",
"data_length",
":",
"Optional",
"[",
"mx",
".",
"sym",
".",
"Symbol",
"]",
",",
"seq_len",
":",
"int",
")",
"->",
"Tuple",
"[",
"mx",
".",
"sym",
".",
"Symbol",... | 46.214286 | 0.010606 |
def dump_queue(queue):
"""
Empties all pending items in a queue and returns them in a list.
"""
result = []
try:
while True:
item = queue.get_nowait()
result.append(item)
except: Empty
return result | [
"def",
"dump_queue",
"(",
"queue",
")",
":",
"result",
"=",
"[",
"]",
"try",
":",
"while",
"True",
":",
"item",
"=",
"queue",
".",
"get_nowait",
"(",
")",
"result",
".",
"append",
"(",
"item",
")",
"except",
":",
"Empty",
"return",
"result"
] | 22.153846 | 0.013333 |
def mixin_params(self, params):
"""
Add the mdsol:LastUpdateTime attribute
:return:
"""
super(LastUpdateMixin, self).mixin_params(params)
if self.last_update_time is not None:
params.update({"mdsol:LastUpdateTime": self.last_update_time.isoformat()}) | [
"def",
"mixin_params",
"(",
"self",
",",
"params",
")",
":",
"super",
"(",
"LastUpdateMixin",
",",
"self",
")",
".",
"mixin_params",
"(",
"params",
")",
"if",
"self",
".",
"last_update_time",
"is",
"not",
"None",
":",
"params",
".",
"update",
"(",
"{",
... | 38 | 0.012862 |
def emit_db_sequence_updates(engine):
"""Set database sequence objects to match the source db
Relevant only when generated from SQLAlchemy connection.
Needed to avoid subsequent unique key violations after DB build."""
if engine and engine.name == 'postgresql':
# not implemented for othe... | [
"def",
"emit_db_sequence_updates",
"(",
"engine",
")",
":",
"if",
"engine",
"and",
"engine",
".",
"name",
"==",
"'postgresql'",
":",
"# not implemented for other RDBMS; necessity unknown",
"conn",
"=",
"engine",
".",
"connect",
"(",
")",
"qry",
"=",
"\"\"\"SELECT 'S... | 48.473684 | 0.001065 |
def log(msg, level=0):
'''
Logs a message to the console, with optional level paramater
Args:
- msg (str): message to send to console
- level (int): log level; 0 for info, 1 for error (default = 0)
'''
red = '\033[91m'
endc = '\033[0m'
# configure the logging module
cf... | [
"def",
"log",
"(",
"msg",
",",
"level",
"=",
"0",
")",
":",
"red",
"=",
"'\\033[91m'",
"endc",
"=",
"'\\033[0m'",
"# configure the logging module",
"cfg",
"=",
"{",
"'version'",
":",
"1",
",",
"'disable_existing_loggers'",
":",
"False",
",",
"'formatters'",
... | 25.644068 | 0.001273 |
def sample_double_norm(mean, std_upper, std_lower, size):
"""Note that this function requires Scipy."""
from scipy.special import erfinv
# There's probably a better way to do this. We first draw percentiles
# uniformly between 0 and 1. We want the peak of the distribution to occur
# at `mean`. Howe... | [
"def",
"sample_double_norm",
"(",
"mean",
",",
"std_upper",
",",
"std_lower",
",",
"size",
")",
":",
"from",
"scipy",
".",
"special",
"import",
"erfinv",
"# There's probably a better way to do this. We first draw percentiles",
"# uniformly between 0 and 1. We want the peak of t... | 46.172414 | 0.000732 |
def filter_missing_rna(s2bins, bins2s, rna_cov):
"""
remove any bins that don't have 16S
"""
for bin, scaffolds in list(bins2s.items()):
c = 0
for s in scaffolds:
if s in rna_cov:
c += 1
if c == 0:
del bins2s[bin]
for scaffold, bin in l... | [
"def",
"filter_missing_rna",
"(",
"s2bins",
",",
"bins2s",
",",
"rna_cov",
")",
":",
"for",
"bin",
",",
"scaffolds",
"in",
"list",
"(",
"bins2s",
".",
"items",
"(",
")",
")",
":",
"c",
"=",
"0",
"for",
"s",
"in",
"scaffolds",
":",
"if",
"s",
"in",
... | 27.666667 | 0.002331 |
def remove_bookmark(request, id):
"""
This view deletes a bookmark.
If requested via ajax it also returns the add bookmark form to replace the
drop bookmark form.
"""
bookmark = get_object_or_404(Bookmark, id=id, user=request.user)
if request.method == "POST":
bookmark.delete()
... | [
"def",
"remove_bookmark",
"(",
"request",
",",
"id",
")",
":",
"bookmark",
"=",
"get_object_or_404",
"(",
"Bookmark",
",",
"id",
"=",
"id",
",",
"user",
"=",
"request",
".",
"user",
")",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"bookmark",
... | 37.16 | 0.001049 |
def tags(self):
""" Returns a list of all the tags applied to this view """
tag_list = self.spec.get('tag', [])
if isinstance(tag_list, (list, set, tuple)):
return list(tag_list)
return [tag_list] | [
"def",
"tags",
"(",
"self",
")",
":",
"tag_list",
"=",
"self",
".",
"spec",
".",
"get",
"(",
"'tag'",
",",
"[",
"]",
")",
"if",
"isinstance",
"(",
"tag_list",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
":",
"return",
"list",
"(",
"ta... | 39.166667 | 0.008333 |
def set_translation(self, lang, field, text):
"""
Store a translation string in the specified field for a Translatable
istance
@type lang: string
@param lang: a string with the name of the language
@type field: string
@param field: a string with the name that we... | [
"def",
"set_translation",
"(",
"self",
",",
"lang",
",",
"field",
",",
"text",
")",
":",
"# Do not allow user to set a translations in the default language",
"auto_slug_obj",
"=",
"None",
"if",
"lang",
"==",
"self",
".",
"_get_default_language",
"(",
")",
":",
"rais... | 37.583333 | 0.002161 |
def run_flow(flow, storage, flags=None, http=None):
"""Core code for a command-line application.
The ``run()`` function is called from your application and runs
through all the steps to obtain credentials. It takes a ``Flow``
argument and attempts to open an authorization server page in the
user's ... | [
"def",
"run_flow",
"(",
"flow",
",",
"storage",
",",
"flags",
"=",
"None",
",",
"http",
"=",
"None",
")",
":",
"if",
"flags",
"is",
"None",
":",
"flags",
"=",
"argparser",
".",
"parse_args",
"(",
")",
"logging",
".",
"getLogger",
"(",
")",
".",
"se... | 39.190909 | 0.000226 |
def toJson(self, data=None, pretty=False):
"""convert the flattened dictionary into json"""
if data==None: data = self.attrs
data = self.flatten(data) # don't send objects as str in json
#if pretty:
ret = json.dumps(data, indent=4, sort_keys=True)
#self.inflate() # restor... | [
"def",
"toJson",
"(",
"self",
",",
"data",
"=",
"None",
",",
"pretty",
"=",
"False",
")",
":",
"if",
"data",
"==",
"None",
":",
"data",
"=",
"self",
".",
"attrs",
"data",
"=",
"self",
".",
"flatten",
"(",
"data",
")",
"# don't send objects as str in js... | 45 | 0.021798 |
def process_presence_events(self, event_data, token, opts):
'''
Check if any minions have connected or dropped.
Send a message to the client if they have.
'''
tag = event_data['tag']
event_info = event_data['data']
minions_detected = event_info['present']
... | [
"def",
"process_presence_events",
"(",
"self",
",",
"event_data",
",",
"token",
",",
"opts",
")",
":",
"tag",
"=",
"event_data",
"[",
"'tag'",
"]",
"event_info",
"=",
"event_data",
"[",
"'data'",
"]",
"minions_detected",
"=",
"event_info",
"[",
"'present'",
... | 29.707317 | 0.00159 |
def list_all_refund_transactions(cls, **kwargs):
"""List RefundTransactions
Return a list of RefundTransactions
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_refund_transactions(asy... | [
"def",
"list_all_refund_transactions",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_refund_transactions_with_htt... | 39.391304 | 0.002155 |
def connect(self, request):
'''
Send a CONNECT control packet.
'''
state = self.__class__.__name__
return defer.fail(MQTTStateError("Unexpected connect() operation", state)) | [
"def",
"connect",
"(",
"self",
",",
"request",
")",
":",
"state",
"=",
"self",
".",
"__class__",
".",
"__name__",
"return",
"defer",
".",
"fail",
"(",
"MQTTStateError",
"(",
"\"Unexpected connect() operation\"",
",",
"state",
")",
")"
] | 34.666667 | 0.014085 |
def table_update(self, table_name, table_info):
"""Updates the Table info.
Args:
table_name: the name of the table to update as a tuple of components.
table_info: the Table resource with updated fields.
"""
url = Api._ENDPOINT + (Api._TABLES_PATH % table_name)
return datalab.utils.Http.... | [
"def",
"table_update",
"(",
"self",
",",
"table_name",
",",
"table_info",
")",
":",
"url",
"=",
"Api",
".",
"_ENDPOINT",
"+",
"(",
"Api",
".",
"_TABLES_PATH",
"%",
"table_name",
")",
"return",
"datalab",
".",
"utils",
".",
"Http",
".",
"request",
"(",
... | 42.3 | 0.002315 |
def put(self, url, json=None, data=None, **kwargs):
"""Sends a PUT request.
Args:
url(basestring): The URL of the API endpoint.
json: Data to be sent in JSON format in tbe body of the request.
data: Data to be sent in the body of the request.
**kwargs:
... | [
"def",
"put",
"(",
"self",
",",
"url",
",",
"json",
"=",
"None",
",",
"data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"check_type",
"(",
"url",
",",
"basestring",
",",
"may_be_none",
"=",
"False",
")",
"# Expected response code",
"erc",
"=",
... | 37.916667 | 0.002144 |
def setModel(self, model, relayout=True):
"""Set the model for the data, header/index and level views."""
self._model = model
sel_model = self.dataTable.selectionModel()
sel_model.currentColumnChanged.connect(
self._resizeCurrentColumnToContents)
# Asociat... | [
"def",
"setModel",
"(",
"self",
",",
"model",
",",
"relayout",
"=",
"True",
")",
":",
"self",
".",
"_model",
"=",
"model",
"sel_model",
"=",
"self",
".",
"dataTable",
".",
"selectionModel",
"(",
")",
"sel_model",
".",
"currentColumnChanged",
".",
"connect"... | 54.25 | 0.001509 |
def run(self): # No "_" in the name, but nevertheless, running in the backed
"""After the fork. Now the process starts running
"""
self.preRun_()
self.running=True
while(self.running):
self.cycle_()
self.handleSignal_()
self.postR... | [
"def",
"run",
"(",
"self",
")",
":",
"# No \"_\" in the name, but nevertheless, running in the backed",
"self",
".",
"preRun_",
"(",
")",
"self",
".",
"running",
"=",
"True",
"while",
"(",
"self",
".",
"running",
")",
":",
"self",
".",
"cycle_",
"(",
")",
"s... | 28.636364 | 0.018462 |
def set_user_attribute(self, user_name, key, value):
"""Sets a user attribute
:param user_name: name of user to modify
:param key: key of the attribute to set
:param value: value to set
:returns: True if the operation succeeded, False otherwise
:raises: HTTPResponseError... | [
"def",
"set_user_attribute",
"(",
"self",
",",
"user_name",
",",
"key",
",",
"value",
")",
":",
"res",
"=",
"self",
".",
"_make_ocs_request",
"(",
"'PUT'",
",",
"self",
".",
"OCS_SERVICE_CLOUD",
",",
"'users/'",
"+",
"parse",
".",
"quote",
"(",
"user_name"... | 34.782609 | 0.002433 |
def start(self):
"""Start the background process."""
self._lc = LoopingCall(self._download)
# Run immediately, and then every 30 seconds:
self._lc.start(30, now=True) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"_lc",
"=",
"LoopingCall",
"(",
"self",
".",
"_download",
")",
"# Run immediately, and then every 30 seconds:",
"self",
".",
"_lc",
".",
"start",
"(",
"30",
",",
"now",
"=",
"True",
")"
] | 38.8 | 0.010101 |
def _process_pair(first_fn, second_fn, error_protocol):
"""
Look at given filenames, decide which is what and try to pair them.
"""
ebook = None
metadata = None
if _is_meta(first_fn) and not _is_meta(second_fn): # 1st meta, 2nd data
logger.debug(
"Parsed: '%s' as meta, '%... | [
"def",
"_process_pair",
"(",
"first_fn",
",",
"second_fn",
",",
"error_protocol",
")",
":",
"ebook",
"=",
"None",
"metadata",
"=",
"None",
"if",
"_is_meta",
"(",
"first_fn",
")",
"and",
"not",
"_is_meta",
"(",
"second_fn",
")",
":",
"# 1st meta, 2nd data",
"... | 33.897959 | 0.00117 |
def run_job(key, node):
"""Run a job. This applies the function node, and returns a |ResultMessage|
when complete. If an exception is raised in the job, the |ResultMessage|
will have ``'error'`` status.
.. |run_job| replace:: :py:func:`run_job`"""
try:
result = node.apply()
return R... | [
"def",
"run_job",
"(",
"key",
",",
"node",
")",
":",
"try",
":",
"result",
"=",
"node",
".",
"apply",
"(",
")",
"return",
"ResultMessage",
"(",
"key",
",",
"'done'",
",",
"result",
",",
"None",
")",
"except",
"Exception",
"as",
"exc",
":",
"return",
... | 36 | 0.002257 |
def normalizeSequence(sequence, considerDimensions=None):
"""
normalize sequence by subtracting the mean and
:param sequence: a list of data samples
:param considerDimensions: a list of dimensions to consider
:return: normalized sequence
"""
seq = np.array(sequence).astype('float64')
nSampleDim = seq.sh... | [
"def",
"normalizeSequence",
"(",
"sequence",
",",
"considerDimensions",
"=",
"None",
")",
":",
"seq",
"=",
"np",
".",
"array",
"(",
"sequence",
")",
".",
"astype",
"(",
"'float64'",
")",
"nSampleDim",
"=",
"seq",
".",
"shape",
"[",
"1",
"]",
"if",
"con... | 30.111111 | 0.014311 |
def add(event, reactors, saltenv='base', test=None):
'''
Add a new reactor
CLI Example:
.. code-block:: bash
salt-run reactor.add 'salt/cloud/*/destroyed' reactors='/srv/reactor/destroy/*.sls'
'''
if isinstance(reactors, string_types):
reactors = [reactors]
sevent = salt.... | [
"def",
"add",
"(",
"event",
",",
"reactors",
",",
"saltenv",
"=",
"'base'",
",",
"test",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"reactors",
",",
"string_types",
")",
":",
"reactors",
"=",
"[",
"reactors",
"]",
"sevent",
"=",
"salt",
".",
"ut... | 28.793103 | 0.002317 |
def delete(self, message, branch=None, committer=None, author=None):
"""Delete this file.
:param str message: (required), commit message to describe the removal
:param str branch: (optional), branch where the file exists.
Defaults to the default branch of the repository.
:pa... | [
"def",
"delete",
"(",
"self",
",",
"message",
",",
"branch",
"=",
"None",
",",
"committer",
"=",
"None",
",",
"author",
"=",
"None",
")",
":",
"json",
"=",
"None",
"if",
"message",
":",
"data",
"=",
"{",
"'message'",
":",
"message",
",",
"'sha'",
"... | 46.88 | 0.001672 |
def _set(self, name, value):
"Proxy to set a property of the widget element."
return self.widget(self.widget_element._set(name, value)) | [
"def",
"_set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"return",
"self",
".",
"widget",
"(",
"self",
".",
"widget_element",
".",
"_set",
"(",
"name",
",",
"value",
")",
")"
] | 49.666667 | 0.013245 |
def _jar_classfiles(self, jar_file):
"""Returns an iterator over the classfiles inside jar_file."""
for cls in ClasspathUtil.classpath_entries_contents([jar_file]):
if cls.endswith('.class'):
yield cls | [
"def",
"_jar_classfiles",
"(",
"self",
",",
"jar_file",
")",
":",
"for",
"cls",
"in",
"ClasspathUtil",
".",
"classpath_entries_contents",
"(",
"[",
"jar_file",
"]",
")",
":",
"if",
"cls",
".",
"endswith",
"(",
"'.class'",
")",
":",
"yield",
"cls"
] | 43.8 | 0.008969 |
def move_roles(resource_root, service_name, name, role_names,
cluster_name="default"):
"""
Moves roles to the specified role config group.
The roles can be moved from any role config group belonging
to the same service. The role type of the destination group
must match the role type of the roles.
@par... | [
"def",
"move_roles",
"(",
"resource_root",
",",
"service_name",
",",
"name",
",",
"role_names",
",",
"cluster_name",
"=",
"\"default\"",
")",
":",
"return",
"call",
"(",
"resource_root",
".",
"put",
",",
"_get_role_config_group_path",
"(",
"cluster_name",
",",
"... | 39.117647 | 0.010279 |
def swap(args):
"""
%prog swap blastfile
Print out a new blast file with query and subject swapped.
"""
p = OptionParser(swap.__doc__)
opts, args = p.parse_args(args)
if len(args) < 1:
sys.exit(not p.print_help())
blastfile, = args
swappedblastfile = blastfile + ".swapped... | [
"def",
"swap",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"swap",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"<",
"1",
":",
"sys",
".",
"exit",
"(",
"not",
... | 21.565217 | 0.001931 |
def validate_json_schema(data, schema, name="task"):
"""Given data and a jsonschema, let's validate it.
This happens for tasks and chain of trust artifacts.
Args:
data (dict): the json to validate.
schema (dict): the jsonschema to validate against.
name (str, optional): the name of... | [
"def",
"validate_json_schema",
"(",
"data",
",",
"schema",
",",
"name",
"=",
"\"task\"",
")",
":",
"try",
":",
"jsonschema",
".",
"validate",
"(",
"data",
",",
"schema",
")",
"except",
"jsonschema",
".",
"exceptions",
".",
"ValidationError",
"as",
"exc",
"... | 32.363636 | 0.001364 |
def ad_address(mode, hit_id):
"""Get the address of the ad on AWS.
This is used at the end of the experiment to send participants
back to AWS where they can complete and submit the HIT.
"""
if mode == "debug":
address = '/complete'
elif mode in ["sandbox", "live"]:
username = os... | [
"def",
"ad_address",
"(",
"mode",
",",
"hit_id",
")",
":",
"if",
"mode",
"==",
"\"debug\"",
":",
"address",
"=",
"'/complete'",
"elif",
"mode",
"in",
"[",
"\"sandbox\"",
",",
"\"live\"",
"]",
":",
"username",
"=",
"os",
".",
"getenv",
"(",
"'psiturk_acce... | 41.083333 | 0.001321 |
def dem(bounds, src_crs, dst_crs, out_file, resolution):
"""Dump BC DEM to TIFF
"""
if not dst_crs:
dst_crs = "EPSG:3005"
bcdata.get_dem(bounds, out_file=out_file, src_crs=src_crs, dst_crs=dst_crs, resolution=resolution) | [
"def",
"dem",
"(",
"bounds",
",",
"src_crs",
",",
"dst_crs",
",",
"out_file",
",",
"resolution",
")",
":",
"if",
"not",
"dst_crs",
":",
"dst_crs",
"=",
"\"EPSG:3005\"",
"bcdata",
".",
"get_dem",
"(",
"bounds",
",",
"out_file",
"=",
"out_file",
",",
"src_... | 39.833333 | 0.008197 |
def get_channel_access(self, channel=None, read_mode='volatile'):
"""Get channel access
:param channel: number [1:7]
:param read_mode:
non_volatile = get non-volatile Channel Access
volatile = get present volatile (active) setting of Channel Access
:return: A Pyth... | [
"def",
"get_channel_access",
"(",
"self",
",",
"channel",
"=",
"None",
",",
"read_mode",
"=",
"'volatile'",
")",
":",
"if",
"channel",
"is",
"None",
":",
"channel",
"=",
"self",
".",
"get_network_channel",
"(",
")",
"data",
"=",
"[",
"]",
"data",
".",
... | 29.514286 | 0.000937 |
def find_types_that_changed_kind(
old_schema: GraphQLSchema, new_schema: GraphQLSchema
) -> List[BreakingChange]:
"""Find types that changed kind
Given two schemas, returns a list containing descriptions of any breaking changes
in the newSchema related to changing the type of a type.
"""
old_ty... | [
"def",
"find_types_that_changed_kind",
"(",
"old_schema",
":",
"GraphQLSchema",
",",
"new_schema",
":",
"GraphQLSchema",
")",
"->",
"List",
"[",
"BreakingChange",
"]",
":",
"old_type_map",
"=",
"old_schema",
".",
"type_map",
"new_type_map",
"=",
"new_schema",
".",
... | 36.461538 | 0.002055 |
def incremental_neighbor_graph(X, precomputed=False, k=None, epsilon=None,
weighting='none'):
'''See neighbor_graph.'''
assert ((k is not None) or (epsilon is not None)
), "Must provide `k` or `epsilon`"
assert (_issequence(k) ^ _issequence(epsilon)
), "Exactly o... | [
"def",
"incremental_neighbor_graph",
"(",
"X",
",",
"precomputed",
"=",
"False",
",",
"k",
"=",
"None",
",",
"epsilon",
"=",
"None",
",",
"weighting",
"=",
"'none'",
")",
":",
"assert",
"(",
"(",
"k",
"is",
"not",
"None",
")",
"or",
"(",
"epsilon",
"... | 30.479167 | 0.02053 |
def prune_influence_map(self):
"""Remove edges between rules causing problematic non-transitivity.
First, all self-loops are removed. After this initial step, edges are
removed between rules when they share *all* child nodes except for each
other; that is, they have a mutual relationshi... | [
"def",
"prune_influence_map",
"(",
"self",
")",
":",
"im",
"=",
"self",
".",
"get_im",
"(",
")",
"# First, remove all self-loops",
"logger",
".",
"info",
"(",
"'Removing self loops'",
")",
"edges_to_remove",
"=",
"[",
"]",
"for",
"e",
"in",
"im",
".",
"edges... | 46.90566 | 0.001182 |
def _add_q(self, q_object):
"""Add a Q-object to the current filter."""
self._criteria = self._criteria._combine(q_object, q_object.connector) | [
"def",
"_add_q",
"(",
"self",
",",
"q_object",
")",
":",
"self",
".",
"_criteria",
"=",
"self",
".",
"_criteria",
".",
"_combine",
"(",
"q_object",
",",
"q_object",
".",
"connector",
")"
] | 52 | 0.012658 |
def main():
'''
Bootstrapper CLI
'''
parser = argparse.ArgumentParser(prog='kclboot',
description='kclboot - Kinesis Client Library Bootstrapper')
subparsers = parser.add_subparsers(title='Subcommands', help='Additional help', dest='subparser')
# Common arguments
jar_path_parser =... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"'kclboot'",
",",
"description",
"=",
"'kclboot - Kinesis Client Library Bootstrapper'",
")",
"subparsers",
"=",
"parser",
".",
"add_subparsers",
"(",
"title",
"=",
... | 44.025 | 0.012222 |
def build_hpo_term(hpo_info):
"""Build a hpo_term object
Check that the information is correct and add the correct hgnc ids to the
array of genes.
Args:
hpo_info(dict)
Returns:
hpo_obj(scout.models.HpoTerm): A dictionary with hpo information
... | [
"def",
"build_hpo_term",
"(",
"hpo_info",
")",
":",
"try",
":",
"hpo_id",
"=",
"hpo_info",
"[",
"'hpo_id'",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"\"Hpo terms has to have a hpo_id\"",
")",
"LOG",
".",
"debug",
"(",
"\"Building hpo term %s\"",
... | 23.552632 | 0.013948 |
def run_step(context):
"""Run another pipeline from this step.
The parent pipeline is the current, executing pipeline. The invoked, or
child pipeline is the pipeline you are calling from this step.
Args:
context: dictionary-like pypyr.context.Context. context is mandatory.
Use... | [
"def",
"run_step",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"(",
"pipeline_name",
",",
"use_parent_context",
",",
"pipe_arg",
",",
"skip_parse",
",",
"raise_error",
",",
"loader",
",",
")",
"=",
"get_arguments",
"(",
"contex... | 39.607143 | 0.000293 |
def mean_value_difference(data, ground_truth, mask=None, normalized=False,
force_lower_is_better=True):
r"""Return difference in mean value between ``data`` and ``ground_truth``.
Parameters
----------
data : `Tensor` or `array-like`
Input data to compare to the ground ... | [
"def",
"mean_value_difference",
"(",
"data",
",",
"ground_truth",
",",
"mask",
"=",
"None",
",",
"normalized",
"=",
"False",
",",
"force_lower_is_better",
"=",
"True",
")",
":",
"if",
"not",
"hasattr",
"(",
"data",
",",
"'space'",
")",
":",
"data",
"=",
... | 30.25 | 0.000445 |
def create_folder(name, location='\\'):
r'''
Create a folder in which to create tasks.
:param str name: The name of the folder. This will be displayed in the task
scheduler.
:param str location: A string value representing the location in which to
create the folder. Default is '\\' whi... | [
"def",
"create_folder",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing folder",
"if",
"name",
"in",
"list_folders",
"(",
"location",
")",
":",
"# Connect to an existing task definition",
"return",
"'{0} already exists'",
".",
"format",
"(... | 28.666667 | 0.000865 |
def invalidate(cls, inst, name):
"""Invalidate a lazy attribute.
This obviously violates the lazy contract. A subclass of lazy
may however have a contract where invalidation is appropriate.
"""
inst_cls = inst.__class__
if not hasattr(inst, '__dict__'):
rais... | [
"def",
"invalidate",
"(",
"cls",
",",
"inst",
",",
"name",
")",
":",
"inst_cls",
"=",
"inst",
".",
"__class__",
"if",
"not",
"hasattr",
"(",
"inst",
",",
"'__dict__'",
")",
":",
"raise",
"AttributeError",
"(",
"\"'%s' object has no attribute '__dict__'\"",
"%"... | 38.238095 | 0.00243 |
def vertical_table(data, headers, sep_title='{n}. row', sep_character='*',
sep_length=27):
"""Format *data* and *headers* as an vertical table.
The values in *data* and *headers* must be strings.
:param iterable data: An :term:`iterable` (e.g. list) of rows.
:param iterable headers:... | [
"def",
"vertical_table",
"(",
"data",
",",
"headers",
",",
"sep_title",
"=",
"'{n}. row'",
",",
"sep_character",
"=",
"'*'",
",",
"sep_length",
"=",
"27",
")",
":",
"header_len",
"=",
"max",
"(",
"[",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"headers",
... | 46.357143 | 0.000755 |
def SetActiveBreakpoints(self, breakpoints_data):
"""Adds new breakpoints and removes missing ones.
Args:
breakpoints_data: updated list of active breakpoints.
"""
with self._lock:
ids = set([x['id'] for x in breakpoints_data])
# Clear breakpoints that no longer show up in active bre... | [
"def",
"SetActiveBreakpoints",
"(",
"self",
",",
"breakpoints_data",
")",
":",
"with",
"self",
".",
"_lock",
":",
"ids",
"=",
"set",
"(",
"[",
"x",
"[",
"'id'",
"]",
"for",
"x",
"in",
"breakpoints_data",
"]",
")",
"# Clear breakpoints that no longer show up in... | 36.088235 | 0.011111 |
def fromcolumns(cols, header=None, missing=None):
"""View a sequence of columns as a table, e.g.::
>>> import petl as etl
>>> cols = [[0, 1, 2], ['a', 'b', 'c']]
>>> tbl = etl.fromcolumns(cols)
>>> tbl
+----+-----+
| f0 | f1 |
+====+=====+
| 0 | 'a'... | [
"def",
"fromcolumns",
"(",
"cols",
",",
"header",
"=",
"None",
",",
"missing",
"=",
"None",
")",
":",
"return",
"ColumnsView",
"(",
"cols",
",",
"header",
"=",
"header",
",",
"missing",
"=",
"missing",
")"
] | 24.95 | 0.000964 |
def readinto(self, b):
"""Read up to len(b) bytes into the writable buffer *b* and return
the number of bytes read. If the socket is non-blocking and no bytes
are available, None is returned.
If *b* is non-empty, a 0 return value indicates that the connection
was shutdown at th... | [
"def",
"readinto",
"(",
"self",
",",
"b",
")",
":",
"self",
".",
"_checkClosed",
"(",
")",
"self",
".",
"_checkReadable",
"(",
")",
"if",
"self",
".",
"_timeout_occurred",
":",
"raise",
"IOError",
"(",
"\"cannot read from timed out object\"",
")",
"while",
"... | 35.75 | 0.00227 |
def _calculate_states(self, stimulus):
"""!
@brief Calculates states of oscillators in the network for current step and stored them except outputs of oscillators.
@param[in] stimulus (list): Stimulus for oscillators, number of stimulus should be equal to number of oscillators.
... | [
"def",
"_calculate_states",
"(",
"self",
",",
"stimulus",
")",
":",
"feeding",
"=",
"[",
"0.0",
"]",
"*",
"self",
".",
"_num_osc",
"linking",
"=",
"[",
"0.0",
"]",
"*",
"self",
".",
"_num_osc",
"outputs",
"=",
"[",
"0.0",
"]",
"*",
"self",
".",
"_n... | 44.758621 | 0.009296 |
def parmap(f, X, nprocs=multiprocessing.cpu_count()):
""" paralell map for multiprocessing """
q_in = multiprocessing.Queue(1)
q_out = multiprocessing.Queue()
proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out))
for _ in range(nprocs)]
for p in proc:
p.daemon = Tru... | [
"def",
"parmap",
"(",
"f",
",",
"X",
",",
"nprocs",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
")",
":",
"q_in",
"=",
"multiprocessing",
".",
"Queue",
"(",
"1",
")",
"q_out",
"=",
"multiprocessing",
".",
"Queue",
"(",
")",
"proc",
"=",
"[",
... | 30.555556 | 0.001764 |
def add_file_recursive(self, filename, trim=False):
"""Add a file and all its recursive dependencies to the graph.
Args:
filename: The name of the file.
trim: Whether to trim the dependencies of builtin and system files.
"""
assert not self.final, 'Trying to mutate ... | [
"def",
"add_file_recursive",
"(",
"self",
",",
"filename",
",",
"trim",
"=",
"False",
")",
":",
"assert",
"not",
"self",
".",
"final",
",",
"'Trying to mutate a final graph.'",
"self",
".",
"add_source_file",
"(",
"filename",
")",
"queue",
"=",
"collections",
... | 40.457143 | 0.002069 |
def from_json(cls, data, result=None):
"""
Create new Relation element from JSON data
:param data: Element data from JSON
:type data: Dict
:param result: The result this element belongs to
:type result: overpy.Result
:return: New instance of Relation
:rty... | [
"def",
"from_json",
"(",
"cls",
",",
"data",
",",
"result",
"=",
"None",
")",
":",
"if",
"data",
".",
"get",
"(",
"\"type\"",
")",
"!=",
"cls",
".",
"_type_value",
":",
"raise",
"exception",
".",
"ElementDataWrongType",
"(",
"type_expected",
"=",
"cls",
... | 31.90566 | 0.001721 |
def avl_insert_dir(root, new_node, direction=1):
"""
Inserts a single node all the way to the left (direction=1) or right (direction=1)
CommandLine:
python -m utool.experimental.euler_tour_tree_avl avl_insert_dir --show
python -m utool.experimental.euler_tour_tree_avl avl_insert_dir
Ex... | [
"def",
"avl_insert_dir",
"(",
"root",
",",
"new_node",
",",
"direction",
"=",
"1",
")",
":",
"if",
"root",
"is",
"None",
":",
"return",
"new_node",
"assert",
"new_node",
".",
"parent",
"is",
"None",
",",
"str",
"(",
"(",
"new_node",
",",
"new_node",
".... | 34.38 | 0.000283 |
def _get_reg_software(include_components=True,
include_updates=True):
'''
This searches the uninstall keys in the registry to find a match in the sub
keys, it will return a dict with the display name as the key and the
version as the value
Args:
include_components (bo... | [
"def",
"_get_reg_software",
"(",
"include_components",
"=",
"True",
",",
"include_updates",
"=",
"True",
")",
":",
"# Logic for this can be found in this question:",
"# https://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-progr... | 40.506329 | 0.000915 |
async def send(self, data, room=None, skip_sid=None, namespace=None,
callback=None, **kwargs):
"""Send a message to one or more connected clients.
This function emits an event with the name ``'message'``. Use
:func:`emit` to issue custom event names.
:param data: The... | [
"async",
"def",
"send",
"(",
"self",
",",
"data",
",",
"room",
"=",
"None",
",",
"skip_sid",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"emit",
"(",
"'message'"... | 61.657895 | 0.001261 |
def format_filename(self, item: Union[Post, StoryItem], target: Optional[str] = None):
"""Format filename of a :class:`Post` or :class:`StoryItem` according to ``filename-pattern`` parameter.
.. versionadded:: 4.1"""
return _PostPathFormatter(item).format(self.filename_pattern, target=target) | [
"def",
"format_filename",
"(",
"self",
",",
"item",
":",
"Union",
"[",
"Post",
",",
"StoryItem",
"]",
",",
"target",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"return",
"_PostPathFormatter",
"(",
"item",
")",
".",
"format",
"(",
"self",
... | 62.8 | 0.015723 |
def find_usage(self, service=None, use_ta=True):
"""
For each limit in the specified service (or all services if
``service`` is ``None``), query the AWS API via ``boto3``
and find the current usage amounts for that limit.
This method updates the ``current_usage`` attribute of th... | [
"def",
"find_usage",
"(",
"self",
",",
"service",
"=",
"None",
",",
"use_ta",
"=",
"True",
")",
":",
"to_get",
"=",
"self",
".",
"services",
"if",
"service",
"is",
"not",
"None",
":",
"to_get",
"=",
"dict",
"(",
"(",
"each",
",",
"self",
".",
"serv... | 44.423077 | 0.001695 |
def onecmd(self, line):
"""Do not crash the entire program when a single command fails."""
try:
return cmd.Cmd.onecmd(self, line)
except Exception as e:
print("Critical error.", e) | [
"def",
"onecmd",
"(",
"self",
",",
"line",
")",
":",
"try",
":",
"return",
"cmd",
".",
"Cmd",
".",
"onecmd",
"(",
"self",
",",
"line",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"Critical error.\"",
",",
"e",
")"
] | 37.166667 | 0.008772 |
def getCiphertextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion.
"""
plaintext_length = self.getPlaintextLen(ciphertext)
ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION
... | [
"def",
"getCiphertextLen",
"(",
"self",
",",
"ciphertext",
")",
":",
"plaintext_length",
"=",
"self",
".",
"getPlaintextLen",
"(",
"ciphertext",
")",
"ciphertext_length",
"=",
"plaintext_length",
"+",
"Encrypter",
".",
"_CTXT_EXPANSION",
"return",
"ciphertext_length"
... | 48.428571 | 0.008696 |
def tokenize_string(source):
"""Tokenize a Python source code string.
Parameters
----------
source : str
A Python source code string
"""
line_reader = StringIO(source).readline
token_generator = tokenize.generate_tokens(line_reader)
# Loop over all tokens till a backtick (`) is... | [
"def",
"tokenize_string",
"(",
"source",
")",
":",
"line_reader",
"=",
"StringIO",
"(",
"source",
")",
".",
"readline",
"token_generator",
"=",
"tokenize",
".",
"generate_tokens",
"(",
"line_reader",
")",
"# Loop over all tokens till a backtick (`) is found.",
"# Then, ... | 33.47619 | 0.001383 |
def batch_put_attributes(self, items, replace=True):
"""
Store attributes for multiple items.
:type items: dict or dict-like object
:param items: A dictionary-like object. The keys of the dictionary are
the item names and the values are themselves dictionaries
... | [
"def",
"batch_put_attributes",
"(",
"self",
",",
"items",
",",
"replace",
"=",
"True",
")",
":",
"return",
"self",
".",
"connection",
".",
"batch_put_attributes",
"(",
"self",
",",
"items",
",",
"replace",
")"
] | 42.15 | 0.00232 |
def as_list(self, decode=False):
"""
Return a list containing all the items in the list.
"""
items = self.database.lrange(self.key, 0, -1)
return [_decode(item) for item in items] if decode else items | [
"def",
"as_list",
"(",
"self",
",",
"decode",
"=",
"False",
")",
":",
"items",
"=",
"self",
".",
"database",
".",
"lrange",
"(",
"self",
".",
"key",
",",
"0",
",",
"-",
"1",
")",
"return",
"[",
"_decode",
"(",
"item",
")",
"for",
"item",
"in",
... | 39.166667 | 0.008333 |
def descendents(self):
"""Iterate over all descendent terms"""
for c in self.children:
yield c
for d in c.descendents:
yield d | [
"def",
"descendents",
"(",
"self",
")",
":",
"for",
"c",
"in",
"self",
".",
"children",
":",
"yield",
"c",
"for",
"d",
"in",
"c",
".",
"descendents",
":",
"yield",
"d"
] | 22.125 | 0.01087 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.