text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _parse_tol(rtol,atol):
"""Parse the tolerance keywords"""
#Process atol and rtol
if rtol is None:
rtol= -12.*nu.log(10.)
else: #pragma: no cover
rtol= nu.log(rtol)
if atol is None:
atol= -12.*nu.log(10.)
else: #pragma: no cover
atol= nu.log(atol)
return (r... | [
"def",
"_parse_tol",
"(",
"rtol",
",",
"atol",
")",
":",
"#Process atol and rtol",
"if",
"rtol",
"is",
"None",
":",
"rtol",
"=",
"-",
"12.",
"*",
"nu",
".",
"log",
"(",
"10.",
")",
"else",
":",
"#pragma: no cover",
"rtol",
"=",
"nu",
".",
"log",
"(",... | 26.5 | 0.036474 |
def run0(self):
"""Run one item (a callback or an RPC wait_any).
Returns:
A time to sleep if something happened (may be 0);
None if all queues are empty.
"""
if self.current:
self.inactive = 0
callback, args, kwds = self.current.popleft()
_logging_debug('nowevent: %s', cal... | [
"def",
"run0",
"(",
"self",
")",
":",
"if",
"self",
".",
"current",
":",
"self",
".",
"inactive",
"=",
"0",
"callback",
",",
"args",
",",
"kwds",
"=",
"self",
".",
"current",
".",
"popleft",
"(",
")",
"_logging_debug",
"(",
"'nowevent: %s'",
",",
"ca... | 33.833333 | 0.011628 |
def to_numeric(arg, errors='raise', downcast=None):
"""
Convert argument to a numeric type.
The default return dtype is `float64` or `int64`
depending on the data supplied. Use the `downcast` parameter
to obtain other dtypes.
Please note that precision loss may occur if really large numbers
... | [
"def",
"to_numeric",
"(",
"arg",
",",
"errors",
"=",
"'raise'",
",",
"downcast",
"=",
"None",
")",
":",
"if",
"downcast",
"not",
"in",
"(",
"None",
",",
"'integer'",
",",
"'signed'",
",",
"'unsigned'",
",",
"'float'",
")",
":",
"raise",
"ValueError",
"... | 34.229885 | 0.000163 |
def create_bundle(self, bundle_name, names=None, ca_only=True):
"""Create a bundle of public certs for trust distribution
This will create a bundle of both CAs and/or regular certificates.
Arguments: names - The names of certs to include in the bundle
bundle_name - The ... | [
"def",
"create_bundle",
"(",
"self",
",",
"bundle_name",
",",
"names",
"=",
"None",
",",
"ca_only",
"=",
"True",
")",
":",
"if",
"not",
"names",
":",
"if",
"ca_only",
":",
"names",
"=",
"[",
"]",
"for",
"name",
",",
"record",
"in",
"self",
".",
"st... | 39.28 | 0.001988 |
def deleteAllStyles(self, verbose=None):
"""
Deletes all vision styles except for default style
:param verbose: print more
:returns: default: successful operation
"""
response=api(url=self.___url+'styles', method="DELETE", verbose=verbose)
return response | [
"def",
"deleteAllStyles",
"(",
"self",
",",
"verbose",
"=",
"None",
")",
":",
"response",
"=",
"api",
"(",
"url",
"=",
"self",
".",
"___url",
"+",
"'styles'",
",",
"method",
"=",
"\"DELETE\"",
",",
"verbose",
"=",
"verbose",
")",
"return",
"response"
] | 27.636364 | 0.012739 |
def get_svg_layers(svg_sources):
'''
Collect layers from input svg sources.
Args:
svg_sources (list) : A list of file-like objects, each containing
one or more XML layers.
Returns
-------
(width, height), layers : (int, int), list
The first item in the tuple is the... | [
"def",
"get_svg_layers",
"(",
"svg_sources",
")",
":",
"layers",
"=",
"[",
"]",
"width",
",",
"height",
"=",
"None",
",",
"None",
"def",
"extract_length",
"(",
"attr",
")",
":",
"'Extract length in pixels.'",
"match",
"=",
"CRE_MM_LENGTH",
".",
"match",
"(",... | 34.25 | 0.00071 |
def to_file(self, filename, binary=False, **kwargs):
"""
Save gridded data to a file.
Usage
-----
x.to_file(filename, [binary, **kwargs])
Parameters
----------
filename : str
Name of output file. For text files (default), the file will be
... | [
"def",
"to_file",
"(",
"self",
",",
"filename",
",",
"binary",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"binary",
"is",
"False",
":",
"_np",
".",
"savetxt",
"(",
"filename",
",",
"self",
".",
"data",
",",
"*",
"*",
"kwargs",
")",
"e... | 36.962963 | 0.001953 |
def custom_observable_object_prefix_lax(instance):
"""Ensure custom observable objects follow naming style conventions.
"""
for key, obj in instance['objects'].items():
if ('type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES and
obj['type'] not in enums.OBSERVABLE_RESERVED_OB... | [
"def",
"custom_observable_object_prefix_lax",
"(",
"instance",
")",
":",
"for",
"key",
",",
"obj",
"in",
"instance",
"[",
"'objects'",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"'type'",
"in",
"obj",
"and",
"obj",
"[",
"'type'",
"]",
"not",
"in",
"e... | 55.818182 | 0.001603 |
def local_updatetime(port):
"""
<Purpose>
Callback for time_interface.r2py to update the time that is used
internally for nodemanager communications.
<Arguments>
port:
The port to update on. This is not used however. It is only
specified to adhere to the function signature expected ... | [
"def",
"local_updatetime",
"(",
"port",
")",
":",
"print",
"'Time update failed, could not connect to any time servers...'",
"print",
"'Your network connection may be down.'",
"print",
"\"Falling back to using your computer's local clock.\"",
"print",
"# time.time() gives us the # of secon... | 30.741935 | 0.009156 |
def Ctrl_Fn(self, n, dl = 0):
"""Ctrl + Fn1~12 组合键
"""
self.Delay(dl)
self.keyboard.press_key(self.keyboard.control_key)
self.keyboard.tap_key(self.keyboard.function_keys[n])
self.keyboard.release_key(self.keyboard.control_key) | [
"def",
"Ctrl_Fn",
"(",
"self",
",",
"n",
",",
"dl",
"=",
"0",
")",
":",
"self",
".",
"Delay",
"(",
"dl",
")",
"self",
".",
"keyboard",
".",
"press_key",
"(",
"self",
".",
"keyboard",
".",
"control_key",
")",
"self",
".",
"keyboard",
".",
"tap_key",... | 38.428571 | 0.014545 |
def set(self, name, value=True):
"set a feature value"
setattr(self, name.lower(), value) | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
"=",
"True",
")",
":",
"setattr",
"(",
"self",
",",
"name",
".",
"lower",
"(",
")",
",",
"value",
")"
] | 34.333333 | 0.019048 |
def from_images(cls, images, weights=None, filter=None, wrap=None,
aspect_adjust_width=False, aspect_adjust_height=False):
"""Create a SpriteTexturizer from a sequence of Pyglet images.
Note all the images must be able to fit into a single OpenGL texture, so
their combined size should typically be less than 10... | [
"def",
"from_images",
"(",
"cls",
",",
"images",
",",
"weights",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"wrap",
"=",
"None",
",",
"aspect_adjust_width",
"=",
"False",
",",
"aspect_adjust_height",
"=",
"False",
")",
":",
"import",
"pyglet",
"atlas",
... | 41.0625 | 0.025298 |
def tag(self, deploy_tag=''):
"""
Function is public.
Create a tag for current commit / branch.
:param deploy_tag:
:return:
"""
if APISettings.SECURE_TAGGING and deploy_tag == APISettings.GIT_ACTIVATE_PRE_TAG:
if self.check_existens_of_staging_tag_in_r... | [
"def",
"tag",
"(",
"self",
",",
"deploy_tag",
"=",
"''",
")",
":",
"if",
"APISettings",
".",
"SECURE_TAGGING",
"and",
"deploy_tag",
"==",
"APISettings",
".",
"GIT_ACTIVATE_PRE_TAG",
":",
"if",
"self",
".",
"check_existens_of_staging_tag_in_remote_repo",
"(",
")",
... | 41.235294 | 0.008368 |
def find_all(self, name=None, **attrs):
r"""Return all descendant nodes matching criteria.
:param Union[None,str] name: name of LaTeX expression
:param attrs: LaTeX expression attributes, such as item text.
:return: All descendant nodes matching criteria
:rtype: Iterator[TexNode... | [
"def",
"find_all",
"(",
"self",
",",
"name",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"for",
"descendant",
"in",
"self",
".",
"__descendants",
"(",
")",
":",
"if",
"hasattr",
"(",
"descendant",
",",
"'__match__'",
")",
"and",
"descendant",
".",
... | 33.222222 | 0.002167 |
def _compute_example_flat_helper(self, label):
"""
From the "raw example," resolves references to examples of other data
types to compute the final example.
Returns an Example object. The `value` attribute contains a
JSON-serializable representation of the example.
"""
... | [
"def",
"_compute_example_flat_helper",
"(",
"self",
",",
"label",
")",
":",
"assert",
"label",
"in",
"self",
".",
"_raw_examples",
",",
"label",
"example",
"=",
"self",
".",
"_raw_examples",
"[",
"label",
"]",
"def",
"deref_example_ref",
"(",
"dt",
",",
"val... | 41.036364 | 0.001298 |
def doc(self):
'''Algorithm from https://www.python.org/dev/peps/pep-0257/'''
if not self.__doc__:
return ""
lines = self.__doc__.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxsize
for line in lines[1:]... | [
"def",
"doc",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__doc__",
":",
"return",
"\"\"",
"lines",
"=",
"self",
".",
"__doc__",
".",
"expandtabs",
"(",
")",
".",
"splitlines",
"(",
")",
"# Determine minimum indentation (first line doesn't count):",
"ind... | 32.035714 | 0.002165 |
def _clear_cache(tgt=None,
tgt_type='glob',
clear_pillar_flag=False,
clear_grains_flag=False,
clear_mine_flag=False,
clear_mine_func_flag=None):
'''
Clear the cached data/files for the targeted minions.
'''
if tgt is No... | [
"def",
"_clear_cache",
"(",
"tgt",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"clear_pillar_flag",
"=",
"False",
",",
"clear_grains_flag",
"=",
"False",
",",
"clear_mine_flag",
"=",
"False",
",",
"clear_mine_func_flag",
"=",
"None",
")",
":",
"if",
"t... | 51.809524 | 0.001805 |
def fulltext_delete(self, transport, index, docs=None, queries=None):
"""
fulltext_delete(index, docs=None, queries=None)
.. deprecated:: 2.1.0 (Riak 2.0)
Manual index maintenance is not supported for
:ref:`Riak Search 2.0 <yz-label>`.
Removes documents from the f... | [
"def",
"fulltext_delete",
"(",
"self",
",",
"transport",
",",
"index",
",",
"docs",
"=",
"None",
",",
"queries",
"=",
"None",
")",
":",
"transport",
".",
"fulltext_delete",
"(",
"index",
",",
"docs",
",",
"queries",
")"
] | 37 | 0.002395 |
def config(config, fork_name="", origin_name=""):
"""Setting various configuration options"""
state = read(config.configfile)
any_set = False
if fork_name:
update(config.configfile, {"FORK_NAME": fork_name})
success_out("fork-name set to: {}".format(fork_name))
any_set = True
... | [
"def",
"config",
"(",
"config",
",",
"fork_name",
"=",
"\"\"",
",",
"origin_name",
"=",
"\"\"",
")",
":",
"state",
"=",
"read",
"(",
"config",
".",
"configfile",
")",
"any_set",
"=",
"False",
"if",
"fork_name",
":",
"update",
"(",
"config",
".",
"confi... | 39.785714 | 0.001754 |
def _g(self, h, xp, s):
"""Density function for blow and hop moves"""
nphi = sum(self.phi)
return (nphi / 2.0) * log(2 * pi) + nphi * \
log(s) + 0.5 * sum((h - xp) ** 2) / (s ** 2) | [
"def",
"_g",
"(",
"self",
",",
"h",
",",
"xp",
",",
"s",
")",
":",
"nphi",
"=",
"sum",
"(",
"self",
".",
"phi",
")",
"return",
"(",
"nphi",
"/",
"2.0",
")",
"*",
"log",
"(",
"2",
"*",
"pi",
")",
"+",
"nphi",
"*",
"log",
"(",
"s",
")",
"... | 30.285714 | 0.009174 |
def remove_library_search_paths(self, paths, target_name=None, configuration_name=None):
"""
Removes the given search paths from the LIBRARY_SEARCH_PATHS section of the target on the configurations
:param paths: A string or array of strings
:param target_name: Target name or list of targ... | [
"def",
"remove_library_search_paths",
"(",
"self",
",",
"paths",
",",
"target_name",
"=",
"None",
",",
"configuration_name",
"=",
"None",
")",
":",
"self",
".",
"remove_search_paths",
"(",
"XCBuildConfigurationFlags",
".",
"LIBRARY_SEARCH_PATHS",
",",
"paths",
",",
... | 69.888889 | 0.010989 |
def render_EPUB2(self, location):
"""
Creates the NCX specified file for EPUB2
"""
def make_navlabel(text):
"""
Creates and returns a navLabel element with the supplied text.
"""
navlabel = etree.Element('navLabel')
navlabel_te... | [
"def",
"render_EPUB2",
"(",
"self",
",",
"location",
")",
":",
"def",
"make_navlabel",
"(",
"text",
")",
":",
"\"\"\"\n Creates and returns a navLabel element with the supplied text.\n \"\"\"",
"navlabel",
"=",
"etree",
".",
"Element",
"(",
"'navLabel'... | 41.792683 | 0.00171 |
def _uneven_utility_transform(systematic_utilities,
alt_IDs,
rows_to_alts,
shape_params,
intercept_params,
intercept_ref_pos=None,
*args, **... | [
"def",
"_uneven_utility_transform",
"(",
"systematic_utilities",
",",
"alt_IDs",
",",
"rows_to_alts",
",",
"shape_params",
",",
"intercept_params",
",",
"intercept_ref_pos",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Convert the shape param... | 50.181818 | 0.000161 |
def _abbrieviate_direction(ext_dir_str):
"""Convert extended (non-abbrievated) directions to abbrieviation."""
return (ext_dir_str
.upper()
.replace('_', '')
.replace('-', '')
.replace(' ', '')
.replace('NORTH', 'N')
.replace('EAST', 'E')
... | [
"def",
"_abbrieviate_direction",
"(",
"ext_dir_str",
")",
":",
"return",
"(",
"ext_dir_str",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'_'",
",",
"''",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
".",
"replace",
"(",
"' '",
",",
"''",
")",
... | 32.5 | 0.002494 |
def submit(self):
"""Submit this query.
@return: A deferred from get_page
"""
self.sign()
url = self.endpoint.get_uri()
method = self.endpoint.method
params = self.signature.get_canonical_query_params()
headers = {}
kwargs = {"method": method}
... | [
"def",
"submit",
"(",
"self",
")",
":",
"self",
".",
"sign",
"(",
")",
"url",
"=",
"self",
".",
"endpoint",
".",
"get_uri",
"(",
")",
"method",
"=",
"self",
".",
"endpoint",
".",
"method",
"params",
"=",
"self",
".",
"signature",
".",
"get_canonical_... | 35.083333 | 0.002312 |
def query_geonames(self, placename):
"""
Wrap search parameters into an elasticsearch query to the geonames index
and return results.
Parameters
---------
conn: an elasticsearch Search conn, like the one returned by `setup_es()`
placename: str
the pl... | [
"def",
"query_geonames",
"(",
"self",
",",
"placename",
")",
":",
"# first first, try for country name",
"if",
"self",
".",
"is_country",
"(",
"placename",
")",
":",
"q",
"=",
"{",
"\"multi_match\"",
":",
"{",
"\"query\"",
":",
"placename",
",",
"\"fields\"",
... | 45.04878 | 0.009009 |
def appendGuideline(self, position=None, angle=None, name=None, color=None, guideline=None):
"""
Append a new guideline to the font.
>>> guideline = font.appendGuideline((50, 0), 90)
>>> guideline = font.appendGuideline((0, 540), 0, name="overshoot",
>>> color=(0, 0,... | [
"def",
"appendGuideline",
"(",
"self",
",",
"position",
"=",
"None",
",",
"angle",
"=",
"None",
",",
"name",
"=",
"None",
",",
"color",
"=",
"None",
",",
"guideline",
"=",
"None",
")",
":",
"identifier",
"=",
"None",
"if",
"guideline",
"is",
"not",
"... | 46.895833 | 0.002176 |
def to_bounding_box(self):
"""
Convert this polygon to a bounding box tightly containing the whole polygon.
Returns
-------
imgaug.BoundingBox
Tight bounding box around the polygon.
"""
# TODO get rid of this deferred import
from imgaug.augme... | [
"def",
"to_bounding_box",
"(",
"self",
")",
":",
"# TODO get rid of this deferred import",
"from",
"imgaug",
".",
"augmentables",
".",
"bbs",
"import",
"BoundingBox",
"xx",
"=",
"self",
".",
"xx",
"yy",
"=",
"self",
".",
"yy",
"return",
"BoundingBox",
"(",
"x1... | 29.4375 | 0.00823 |
def is_in(property_name, set_values, *, present_optional=False, message=None):
"""Returns a Validation that checks that a value is contained within a given set."""
def check(val):
"""Checks that a value is contained within a scope-enclosed set."""
if val is None:
return present_optional
... | [
"def",
"is_in",
"(",
"property_name",
",",
"set_values",
",",
"*",
",",
"present_optional",
"=",
"False",
",",
"message",
"=",
"None",
")",
":",
"def",
"check",
"(",
"val",
")",
":",
"\"\"\"Checks that a value is contained within a scope-enclosed set.\"\"\"",
"if",
... | 40.5 | 0.012077 |
def upload(ui, repo, name, **opts):
"""upload diffs to the code review server
Uploads the current modifications for a given change to the server.
"""
if codereview_disabled:
raise hg_util.Abort(codereview_disabled)
repo.ui.quiet = True
cl, err = LoadCL(ui, repo, name, web=True)
if err != "":
raise hg_util.... | [
"def",
"upload",
"(",
"ui",
",",
"repo",
",",
"name",
",",
"*",
"*",
"opts",
")",
":",
"if",
"codereview_disabled",
":",
"raise",
"hg_util",
".",
"Abort",
"(",
"codereview_disabled",
")",
"repo",
".",
"ui",
".",
"quiet",
"=",
"True",
"cl",
",",
"err"... | 27.294118 | 0.03125 |
def path(edges, source, sink, flavor="longest"):
"""
Calculates shortest/longest path from list of edges in a graph
>>> g = [(1,2,1),(2,3,9),(2,4,3),(2,5,2),(3,6,8),(4,6,10),(4,7,4)]
>>> g += [(6,8,7),(7,9,5),(8,9,6),(9,10,11)]
>>> path(g, 1, 8, flavor="shortest")
([1, 2, 4, 6, 8], 21)
>>> ... | [
"def",
"path",
"(",
"edges",
",",
"source",
",",
"sink",
",",
"flavor",
"=",
"\"longest\"",
")",
":",
"outgoing",
",",
"incoming",
",",
"nodes",
"=",
"node_to_edge",
"(",
"edges",
")",
"nedges",
"=",
"len",
"(",
"edges",
")",
"L",
"=",
"LPInstance",
... | 30.614035 | 0.000555 |
def __SendChunk(self, start, additional_headers=None):
"""Send the specified chunk."""
self.EnsureInitialized()
no_log_body = self.total_size is None
request = http_wrapper.Request(url=self.url, http_method='PUT')
if self.__gzip_encoded:
request.headers['Content-Encod... | [
"def",
"__SendChunk",
"(",
"self",
",",
"start",
",",
"additional_headers",
"=",
"None",
")",
":",
"self",
".",
"EnsureInitialized",
"(",
")",
"no_log_body",
"=",
"self",
".",
"total_size",
"is",
"None",
"request",
"=",
"http_wrapper",
".",
"Request",
"(",
... | 49.618182 | 0.000719 |
def fmt_size(size, binary=True):
'''
Get size and unit.
:param size: size in bytes
:type size: int
:param binary: whether use binary or standard units, defaults to True
:type binary: bool
:return: size and unit
:rtype: tuple of int and unit as str
'''
if binary:
fmt_size... | [
"def",
"fmt_size",
"(",
"size",
",",
"binary",
"=",
"True",
")",
":",
"if",
"binary",
":",
"fmt_sizes",
"=",
"binary_units",
"fmt_divider",
"=",
"1024.",
"else",
":",
"fmt_sizes",
"=",
"standard_units",
"fmt_divider",
"=",
"1000.",
"for",
"fmt",
"in",
"fmt... | 25.5 | 0.001718 |
def _thumbnail_div(target_dir, src_dir, fname, snippet, is_backref=False,
check=True):
"""Generates RST to place a thumbnail in a gallery"""
thumb, _ = _find_image_ext(
os.path.join(target_dir, 'images', 'thumb',
'sphx_glr_%s_thumb.png' % fname[:-3]))
if check... | [
"def",
"_thumbnail_div",
"(",
"target_dir",
",",
"src_dir",
",",
"fname",
",",
"snippet",
",",
"is_backref",
"=",
"False",
",",
"check",
"=",
"True",
")",
":",
"thumb",
",",
"_",
"=",
"_find_image_ext",
"(",
"os",
".",
"path",
".",
"join",
"(",
"target... | 47.285714 | 0.000987 |
def populate_from_trace_graph(self, graph: TraceGraph) -> None:
"""Populates this graph from the given one based on affected_files
"""
# Track which trace frames have been visited as we populate the full
# traces of the graph.
self._visited_trace_frame_ids: Set[int] = set()
... | [
"def",
"populate_from_trace_graph",
"(",
"self",
",",
"graph",
":",
"TraceGraph",
")",
"->",
"None",
":",
"# Track which trace frames have been visited as we populate the full",
"# traces of the graph.",
"self",
".",
"_visited_trace_frame_ids",
":",
"Set",
"[",
"int",
"]",
... | 46.214286 | 0.001513 |
def upload_file_and_send_file_offer(self, file_name, user_id, data=None, input_file_path=None,
content_type='application/octet-stream', auto_open=False,
prevent_share=False, scope='content/send'):
"""
Upload a file of any ty... | [
"def",
"upload_file_and_send_file_offer",
"(",
"self",
",",
"file_name",
",",
"user_id",
",",
"data",
"=",
"None",
",",
"input_file_path",
"=",
"None",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"auto_open",
"=",
"False",
",",
"prevent_share",
"=... | 39.703704 | 0.008197 |
def guess_width(self):
"""auto fit column width"""
if len(self.header) <= 4:
nspace = 6
elif len(self.header) <= 6:
nspace = 5
else:
nspace = 4
ncol = len(self.header)
self._width = [nspace] * ncol
width = [0] * ncol
# ... | [
"def",
"guess_width",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"header",
")",
"<=",
"4",
":",
"nspace",
"=",
"6",
"elif",
"len",
"(",
"self",
".",
"header",
")",
"<=",
"6",
":",
"nspace",
"=",
"5",
"else",
":",
"nspace",
"=",
"4",
... | 30.9 | 0.002092 |
def delete_insight(self, project_key, insight_id):
"""Delete an existing insight.
:params project_key: Project identifier, in the form of
projectOwner/projectId
:type project_key: str
:params insight_id: Insight unique id
:type insight_id: str
:raises RestApiExce... | [
"def",
"delete_insight",
"(",
"self",
",",
"project_key",
",",
"insight_id",
")",
":",
"projectOwner",
",",
"projectId",
"=",
"parse_dataset_key",
"(",
"project_key",
")",
"try",
":",
"self",
".",
"_insights_api",
".",
"delete_insight",
"(",
"projectOwner",
",",... | 38.125 | 0.002132 |
def make_input_stream():
"""Creates a :py:class:`Queue` object and a co-routine yielding from that
queue. The queue should be populated with 2-tuples of the form `(command,
message)`, where `command` is one of [`msg`, `end`].
When the `end` command is recieved, the co-routine returns, ending the
st... | [
"def",
"make_input_stream",
"(",
")",
":",
"input_queue",
"=",
"Queue",
"(",
")",
"def",
"input_stream",
"(",
")",
":",
"while",
"True",
":",
"cmd",
",",
"msg",
"=",
"input_queue",
".",
"get",
"(",
")",
"if",
"cmd",
"==",
"'end'",
":",
"input_queue",
... | 32.2 | 0.001206 |
def personastate(self):
"""Return the Persona State of the Users Profile"""
if self._personastate == None:
return None
elif self._personastate in self.PersonaState:
return self.PersonaState[self._personastate]
else:
#Invalid State
return No... | [
"def",
"personastate",
"(",
"self",
")",
":",
"if",
"self",
".",
"_personastate",
"==",
"None",
":",
"return",
"None",
"elif",
"self",
".",
"_personastate",
"in",
"self",
".",
"PersonaState",
":",
"return",
"self",
".",
"PersonaState",
"[",
"self",
".",
... | 34.888889 | 0.012422 |
def _get_interface_switch_trunk_present(
self, nexus_host, intf_type, interface):
"""Check if 'switchport trunk' configs present.
:param nexus_host: IP address of Nexus switch
:param intf_type: String which specifies interface type.
example: ethernet
... | [
"def",
"_get_interface_switch_trunk_present",
"(",
"self",
",",
"nexus_host",
",",
"intf_type",
",",
"interface",
")",
":",
"result",
"=",
"self",
".",
"get_interface_switch",
"(",
"nexus_host",
",",
"intf_type",
",",
"interface",
")",
"if_type",
"=",
"'l1PhysIf'"... | 35.5625 | 0.001711 |
def list(options):
"""
list programs that belong to the authenticated user
"""
configuration = config.get_default()
app_url = configuration['app_url']
if options.deployment != None:
deployment_name = options.deployment
else:
deployment_name = configuration['deployment_name'... | [
"def",
"list",
"(",
"options",
")",
":",
"configuration",
"=",
"config",
".",
"get_default",
"(",
")",
"app_url",
"=",
"configuration",
"[",
"'app_url'",
"]",
"if",
"options",
".",
"deployment",
"!=",
"None",
":",
"deployment_name",
"=",
"options",
".",
"d... | 34 | 0.002343 |
def adaptive_universal_transformer_multilayer_tpu():
"""Multi-layer config for adaptive Transformer on TPU."""
hparams = adaptive_universal_transformer_base_tpu()
hparams.num_inrecurrence_layers = 2
hparams.mix_with_transformer = "before_ut,after_ut"
hparams.num_mixedin_layers = 1
hparams.transformer_ffn_ty... | [
"def",
"adaptive_universal_transformer_multilayer_tpu",
"(",
")",
":",
"hparams",
"=",
"adaptive_universal_transformer_base_tpu",
"(",
")",
"hparams",
".",
"num_inrecurrence_layers",
"=",
"2",
"hparams",
".",
"mix_with_transformer",
"=",
"\"before_ut,after_ut\"",
"hparams",
... | 45.307692 | 0.023295 |
def concept_names(self):
"""
[str] 概念股分类,例如:’铁路基建’,’基金重仓’等(股票专用)
"""
try:
return self.__dict__["concept_names"]
except (KeyError, ValueError):
raise AttributeError(
"Instrument(order_book_id={}) has no attribute 'concept_names' ".format(sel... | [
"def",
"concept_names",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"__dict__",
"[",
"\"concept_names\"",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
")",
":",
"raise",
"AttributeError",
"(",
"\"Instrument(order_book_id={}) has no attribute 'con... | 34.1 | 0.008571 |
def to_table(self, columns=None, exclude_columns=None):
"""
Create a `~astropy.table.QTable` of properties.
If ``columns`` or ``exclude_columns`` are not input, then the
`~astropy.table.QTable` will include a default list of
scalar-valued properties.
Parameters
... | [
"def",
"to_table",
"(",
"self",
",",
"columns",
"=",
"None",
",",
"exclude_columns",
"=",
"None",
")",
":",
"return",
"_properties_table",
"(",
"self",
",",
"columns",
"=",
"columns",
",",
"exclude_columns",
"=",
"exclude_columns",
")"
] | 36.592593 | 0.001972 |
def sunRelation(self):
""" Returns the relation of the object with the sun. """
sun = self.chart.getObject(const.SUN)
return sunRelation(self.obj, sun) | [
"def",
"sunRelation",
"(",
"self",
")",
":",
"sun",
"=",
"self",
".",
"chart",
".",
"getObject",
"(",
"const",
".",
"SUN",
")",
"return",
"sunRelation",
"(",
"self",
".",
"obj",
",",
"sun",
")"
] | 43 | 0.011429 |
def parse_events(cls, ev_args, parent_ctx):
"""
Create an instance of this class, using the events sent into this
function. `ev_args` must be the event arguments of the ``"start"``
event.
.. seealso::
You probably should not call this method directly, but instead use... | [
"def",
"parse_events",
"(",
"cls",
",",
"ev_args",
",",
"parent_ctx",
")",
":",
"with",
"parent_ctx",
"as",
"ctx",
":",
"obj",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"attrs",
"=",
"ev_args",
"[",
"2",
"]",
"attr_map",
"=",
"cls",
".",
"ATTR_MAP... | 38.398551 | 0.000368 |
def process_raw_litho1_data(model_path):
"""
Don't forget to strip the model data first
truncate_raw_litho1_data(model path, truncated_model_path)
"""
npoints = 40962
nlayers = len(l1_layer_decode)
nentries = 9
litho_data = np.ones((nlayers, nentries, npoints)) * -99999.0
for mode... | [
"def",
"process_raw_litho1_data",
"(",
"model_path",
")",
":",
"npoints",
"=",
"40962",
"nlayers",
"=",
"len",
"(",
"l1_layer_decode",
")",
"nentries",
"=",
"9",
"litho_data",
"=",
"np",
".",
"ones",
"(",
"(",
"nlayers",
",",
"nentries",
",",
"npoints",
")... | 40.416667 | 0.012752 |
def absent(name, **kwargs):
'''
This function deletes the specified repo on the system, if it exists. It
is essentially a wrapper around pkg.del_repo.
name
The name of the package repo, as it would be referred to when running
the regular package manager commands.
**UBUNTU-SPECIFIC ... | [
"def",
"absent",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"if",
"'ppa'",
"in",
"kwargs",
"and",
"__gra... | 33.155172 | 0.000252 |
async def _defaultExpectHandler(request): # pragma: no cover
"""Default handler for Expect header.
Just send "100 Continue" to client.
raise HTTPExpectationFailed if value of header is not "100-continue"
"""
expect = request.headers.get(hdrs.EXPECT)
if request.version == HttpVersion11:
... | [
"async",
"def",
"_defaultExpectHandler",
"(",
"request",
")",
":",
"# pragma: no cover",
"expect",
"=",
"request",
".",
"headers",
".",
"get",
"(",
"hdrs",
".",
"EXPECT",
")",
"if",
"request",
".",
"version",
"==",
"HttpVersion11",
":",
"if",
"expect",
".",
... | 42.166667 | 0.001934 |
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
"""Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
"""... | [
"def",
"wait_for_property",
"(",
"self",
",",
"name",
",",
"cond",
"=",
"lambda",
"val",
":",
"val",
",",
"level_sensitive",
"=",
"True",
")",
":",
"sema",
"=",
"threading",
".",
"Semaphore",
"(",
"value",
"=",
"0",
")",
"def",
"observer",
"(",
"name",... | 53.916667 | 0.009119 |
def _on_timeout():
"""Invoked periodically to ensure that metrics that have been collected
are submitted to InfluxDB.
:rtype: tornado.concurrent.Future or None
"""
global _buffer_size
LOGGER.debug('No metrics submitted in the last %.2f seconds',
_timeout_interval / 1000.0)
... | [
"def",
"_on_timeout",
"(",
")",
":",
"global",
"_buffer_size",
"LOGGER",
".",
"debug",
"(",
"'No metrics submitted in the last %.2f seconds'",
",",
"_timeout_interval",
"/",
"1000.0",
")",
"_buffer_size",
"=",
"_pending_measurements",
"(",
")",
"if",
"_buffer_size",
"... | 28.4 | 0.002273 |
def _evaluate_dimension_fields(self) -> bool:
"""
Evaluates the dimension fields. Returns False if any of the fields could not be evaluated.
"""
for _, item in self._dimension_fields.items():
item.run_evaluate()
if item.eval_error:
return False
... | [
"def",
"_evaluate_dimension_fields",
"(",
"self",
")",
"->",
"bool",
":",
"for",
"_",
",",
"item",
"in",
"self",
".",
"_dimension_fields",
".",
"items",
"(",
")",
":",
"item",
".",
"run_evaluate",
"(",
")",
"if",
"item",
".",
"eval_error",
":",
"return",... | 36.444444 | 0.008929 |
def area(self):
"""Square Foot Area (sqft)"""
area = self.parse['attributes'].get('Shape_Area')
if area:
return round(float(area) * 10.76391) | [
"def",
"area",
"(",
"self",
")",
":",
"area",
"=",
"self",
".",
"parse",
"[",
"'attributes'",
"]",
".",
"get",
"(",
"'Shape_Area'",
")",
"if",
"area",
":",
"return",
"round",
"(",
"float",
"(",
"area",
")",
"*",
"10.76391",
")"
] | 34.6 | 0.011299 |
def _read_from_pipette(self, gcode, mount) -> Optional[str]:
'''
Read from an attached pipette's internal memory. The gcode used
determines which portion of memory is read and returned.
All motors must be disengaged to consistently read over I2C lines
gcode:
String ... | [
"def",
"_read_from_pipette",
"(",
"self",
",",
"gcode",
",",
"mount",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"allowed_mounts",
"=",
"{",
"'left'",
":",
"'L'",
",",
"'right'",
":",
"'R'",
"}",
"mount",
"=",
"allowed_mounts",
".",
"get",
"(",
"moun... | 44.441176 | 0.001295 |
def currentRecord( self ):
"""
Returns the record found at the current index for this combo box.
:rerturn <orb.Table> || None
"""
if self._currentRecord is None and self.isRequired():
self._currentRecord = self.recordAt(self.currentIndex())
... | [
"def",
"currentRecord",
"(",
"self",
")",
":",
"if",
"self",
".",
"_currentRecord",
"is",
"None",
"and",
"self",
".",
"isRequired",
"(",
")",
":",
"self",
".",
"_currentRecord",
"=",
"self",
".",
"recordAt",
"(",
"self",
".",
"currentIndex",
"(",
")",
... | 38.111111 | 0.014245 |
def delete(self):
"""
Deletes the records in the QuerySet.
"""
assert self.query.can_filter(), \
"Cannot use 'limit' or 'offset' with delete."
# Ensure that only current objects are selected.
del_query = self.filter(version_end_date__isnull=True)
# T... | [
"def",
"delete",
"(",
"self",
")",
":",
"assert",
"self",
".",
"query",
".",
"can_filter",
"(",
")",
",",
"\"Cannot use 'limit' or 'offset' with delete.\"",
"# Ensure that only current objects are selected.",
"del_query",
"=",
"self",
".",
"filter",
"(",
"version_end_da... | 38.074074 | 0.001898 |
def _get_max_page(dom):
"""
Try to guess how much pages are in book listing.
Args:
dom (obj): HTMLElement container of the page with book list.
Returns:
int: Number of pages for given category.
"""
div = dom.find("div", {"class": "razeniKnihListovani"})
if not div:
... | [
"def",
"_get_max_page",
"(",
"dom",
")",
":",
"div",
"=",
"dom",
".",
"find",
"(",
"\"div\"",
",",
"{",
"\"class\"",
":",
"\"razeniKnihListovani\"",
"}",
")",
"if",
"not",
"div",
":",
"return",
"1",
"# isolate only page numbers from links",
"links",
"=",
"di... | 23.71875 | 0.001266 |
def create_divisao_dc(self):
"""Get an instance of divisao_dc services facade."""
return DivisaoDc(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | [
"def",
"create_divisao_dc",
"(",
"self",
")",
":",
"return",
"DivisaoDc",
"(",
"self",
".",
"networkapi_url",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"user_ldap",
")"
] | 31.428571 | 0.00885 |
def tags(pode, leaf=False):
'''
Get all the tags for a given node.
Args:
pode (tuple): A packed node.
leaf (bool): If True, only return the full tags.
Returns:
list: A list of tag strings.
'''
fulltags = [tag for tag in pode[1]['tags']]
if not leaf:
return f... | [
"def",
"tags",
"(",
"pode",
",",
"leaf",
"=",
"False",
")",
":",
"fulltags",
"=",
"[",
"tag",
"for",
"tag",
"in",
"pode",
"[",
"1",
"]",
"[",
"'tags'",
"]",
"]",
"if",
"not",
"leaf",
":",
"return",
"fulltags",
"# longest first",
"retn",
"=",
"[",
... | 24.84 | 0.00155 |
def get_class_alias(klass):
"""
Tries to find a suitable L{pyamf.ClassAlias} subclass for C{klass}.
"""
for k, v in pyamf.ALIAS_TYPES.iteritems():
for kl in v:
try:
if issubclass(klass, kl):
return k
except TypeError:
# ... | [
"def",
"get_class_alias",
"(",
"klass",
")",
":",
"for",
"k",
",",
"v",
"in",
"pyamf",
".",
"ALIAS_TYPES",
".",
"iteritems",
"(",
")",
":",
"for",
"kl",
"in",
"v",
":",
"try",
":",
"if",
"issubclass",
"(",
"klass",
",",
"kl",
")",
":",
"return",
... | 31.214286 | 0.002222 |
def _find_C(C, points, vertices, equations, extended_payoff, IC, tol):
"""
Find all the intersection points between the current convex hull
and the two IC constraints. It is done by iterating simplex
counterclockwise.
Parameters
----------
C : ndarray(float, ndim=2)
The 4 by 2 array... | [
"def",
"_find_C",
"(",
"C",
",",
"points",
",",
"vertices",
",",
"equations",
",",
"extended_payoff",
",",
"IC",
",",
"tol",
")",
":",
"n",
"=",
"0",
"weights",
"=",
"np",
".",
"empty",
"(",
"2",
")",
"# vertices is ordered counterclockwise",
"for",
"i",... | 31.180328 | 0.00051 |
def templated(template=None):
"""Template decorator.
Ref: http://flask.pocoo.org/docs/patterns/viewdecorators/
"""
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
template_name = template
if template_name is None:
template_nam... | [
"def",
"templated",
"(",
"template",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"template_name",
"=",
"template",
"if",... | 34.052632 | 0.001504 |
def check_cliches_write_good(text):
"""Check the text.
source: write-good
source_url: https://github.com/btford/write-good
"""
err = "cliches.write_good"
msg = u"'{}' is a cliché."
cliches = [
"a chip off the old block",
"a clean slate",
"a dark and stormy night... | [
"def",
"check_cliches_write_good",
"(",
"text",
")",
":",
"err",
"=",
"\"cliches.write_good\"",
"msg",
"=",
"u\"'{}' is a cliché.\"",
"cliches",
"=",
"[",
"\"a chip off the old block\"",
",",
"\"a clean slate\"",
",",
"\"a dark and stormy night\"",
",",
"\"a far cry\"",
"... | 28.985915 | 0.000047 |
def scale_cb(self, setting, value):
"""Handle callback related to image scaling."""
zoomlevel = self.zoom.calc_level(value)
self.t_.set(zoomlevel=zoomlevel)
self.redraw(whence=0) | [
"def",
"scale_cb",
"(",
"self",
",",
"setting",
",",
"value",
")",
":",
"zoomlevel",
"=",
"self",
".",
"zoom",
".",
"calc_level",
"(",
"value",
")",
"self",
".",
"t_",
".",
"set",
"(",
"zoomlevel",
"=",
"zoomlevel",
")",
"self",
".",
"redraw",
"(",
... | 34.333333 | 0.009479 |
def label_from_lists(self, train_labels:Iterator, valid_labels:Iterator, label_cls:Callable=None, **kwargs)->'LabelList':
"Use the labels in `train_labels` and `valid_labels` to label the data. `label_cls` will overwrite the default."
label_cls = self.train.get_label_cls(train_labels, label_cls)
... | [
"def",
"label_from_lists",
"(",
"self",
",",
"train_labels",
":",
"Iterator",
",",
"valid_labels",
":",
"Iterator",
",",
"label_cls",
":",
"Callable",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
"->",
"'LabelList'",
":",
"label_cls",
"=",
"self",
".",
"trai... | 72.625 | 0.020408 |
def enum(self, desc, func=None, args=None, krgs=None):
"""Add a menu entry whose name will be an auto indexed number."""
name = str(len(self.entries)+1)
self.entries.append(MenuEntry(name, desc, func, args or [], krgs or {})) | [
"def",
"enum",
"(",
"self",
",",
"desc",
",",
"func",
"=",
"None",
",",
"args",
"=",
"None",
",",
"krgs",
"=",
"None",
")",
":",
"name",
"=",
"str",
"(",
"len",
"(",
"self",
".",
"entries",
")",
"+",
"1",
")",
"self",
".",
"entries",
".",
"ap... | 61.5 | 0.012048 |
def in_transaction(self):
"""
:return: True if there is an open transaction.
"""
self._in_transaction = self._in_transaction and self.is_connected
return self._in_transaction | [
"def",
"in_transaction",
"(",
"self",
")",
":",
"self",
".",
"_in_transaction",
"=",
"self",
".",
"_in_transaction",
"and",
"self",
".",
"is_connected",
"return",
"self",
".",
"_in_transaction"
] | 34.833333 | 0.009346 |
def damerau_levenshtein_distance(self, s1, s2):
""" Dervied algorithm from the following website:
https://www.guyrutenberg.com/2008/12/15/damerau-levenshtein-distance-in-python/
Gives us the distance between two words.
"""
d = {}
lenstr1 = len(s1)
lenstr2 = len(s2... | [
"def",
"damerau_levenshtein_distance",
"(",
"self",
",",
"s1",
",",
"s2",
")",
":",
"d",
"=",
"{",
"}",
"lenstr1",
"=",
"len",
"(",
"s1",
")",
"lenstr2",
"=",
"len",
"(",
"s2",
")",
"for",
"i",
"in",
"xrange",
"(",
"-",
"1",
",",
"lenstr1",
"+",
... | 37.642857 | 0.021277 |
def _GetTimeValues(self, number_of_seconds):
"""Determines time values.
Args:
number_of_seconds (int|decimal.Decimal): number of seconds.
Returns:
tuple[int, int, int, int]: days, hours, minutes, seconds.
"""
number_of_seconds = int(number_of_seconds)
number_of_minutes, seconds = ... | [
"def",
"_GetTimeValues",
"(",
"self",
",",
"number_of_seconds",
")",
":",
"number_of_seconds",
"=",
"int",
"(",
"number_of_seconds",
")",
"number_of_minutes",
",",
"seconds",
"=",
"divmod",
"(",
"number_of_seconds",
",",
"60",
")",
"number_of_hours",
",",
"minutes... | 36 | 0.001934 |
def _add_services(self, this_service, other_services):
"""Add services.
Add services to the deployment where this_service is the local charm
that we're testing and other_services are the other services that
are being used in the local amulet tests.
"""
if thi... | [
"def",
"_add_services",
"(",
"self",
",",
"this_service",
",",
"other_services",
")",
":",
"if",
"this_service",
"[",
"'name'",
"]",
"!=",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
":",
"s",
"=",
"this_service",
"[",
... | 40.060606 | 0.001477 |
def write_comment(self, comment):
"""
Write a comment into the header
"""
self._FITS.write_comment(self._ext+1, str(comment)) | [
"def",
"write_comment",
"(",
"self",
",",
"comment",
")",
":",
"self",
".",
"_FITS",
".",
"write_comment",
"(",
"self",
".",
"_ext",
"+",
"1",
",",
"str",
"(",
"comment",
")",
")"
] | 30.6 | 0.012739 |
def add(self, *args, **kwargs):
"""Add Cookie objects by their names, or create new ones under
specified names.
Any unnamed arguments are interpreted as existing cookies, and
are added under the value in their .name attribute. With keyword
arguments, the key is interpreted as th... | [
"def",
"add",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Only the first one is accessible through the main interface,",
"# others accessible through get_all (all_cookies).",
"for",
"cookie",
"in",
"args",
":",
"self",
".",
"all_cookies",
".",
... | 41.545455 | 0.002139 |
def dependents_of_addresses(self, addresses):
"""Given an iterable of addresses, yield all of those addresses dependents."""
seen = OrderedSet(addresses)
for address in addresses:
seen.update(self._dependent_address_map[address])
seen.update(self._implicit_dependent_address_map[address])
ret... | [
"def",
"dependents_of_addresses",
"(",
"self",
",",
"addresses",
")",
":",
"seen",
"=",
"OrderedSet",
"(",
"addresses",
")",
"for",
"address",
"in",
"addresses",
":",
"seen",
".",
"update",
"(",
"self",
".",
"_dependent_address_map",
"[",
"address",
"]",
")"... | 46 | 0.012195 |
def next_occurrences(self, n=None, since=None):
"""Yield the next planned occurrences after the date "since"
The `since` argument can be either a date or datetime onject.
If not given, it defaults to the date of the last event that's
already planned.
If `n` is given, the result... | [
"def",
"next_occurrences",
"(",
"self",
",",
"n",
"=",
"None",
",",
"since",
"=",
"None",
")",
":",
"scheme",
"=",
"self",
".",
"recurrence_scheme",
"if",
"scheme",
"is",
"None",
":",
"return",
"(",
")",
"db",
"=",
"Session",
".",
"object_session",
"("... | 38.5 | 0.001101 |
def folderScan(self,abfFolder=None):
"""populate class properties relating to files in the folder."""
if abfFolder is None and 'abfFolder' in dir(self):
abfFolder=self.abfFolder
else:
self.abfFolder=abfFolder
self.abfFolder=os.path.abspath(self.abfFolder)
... | [
"def",
"folderScan",
"(",
"self",
",",
"abfFolder",
"=",
"None",
")",
":",
"if",
"abfFolder",
"is",
"None",
"and",
"'abfFolder'",
"in",
"dir",
"(",
"self",
")",
":",
"abfFolder",
"=",
"self",
".",
"abfFolder",
"else",
":",
"self",
".",
"abfFolder",
"="... | 50.633333 | 0.016796 |
def id_pools(self):
"""
Gets the IdPools API client.
Returns:
IdPools:
"""
if not self.__id_pools:
self.__id_pools = IdPools(self.__connection)
return self.__id_pools | [
"def",
"id_pools",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__id_pools",
":",
"self",
".",
"__id_pools",
"=",
"IdPools",
"(",
"self",
".",
"__connection",
")",
"return",
"self",
".",
"__id_pools"
] | 23 | 0.008368 |
def _collect_layer_outputs(mod, data, include_layer=None, max_num_examples=None, logger=None):
"""Collect layer outputs and save them in a dictionary mapped by layer names."""
collector = _LayerOutputCollector(include_layer=include_layer, logger=logger)
num_examples = _collect_layer_statistics(mod, data, co... | [
"def",
"_collect_layer_outputs",
"(",
"mod",
",",
"data",
",",
"include_layer",
"=",
"None",
",",
"max_num_examples",
"=",
"None",
",",
"logger",
"=",
"None",
")",
":",
"collector",
"=",
"_LayerOutputCollector",
"(",
"include_layer",
"=",
"include_layer",
",",
... | 78.6 | 0.012594 |
def __trim_beats(localscore, beats, trim):
"""Final post-processing: throw out spurious leading/trailing beats"""
smooth_boe = scipy.signal.convolve(localscore[beats],
scipy.signal.hann(5),
'same')
if trim:
threshold = 0... | [
"def",
"__trim_beats",
"(",
"localscore",
",",
"beats",
",",
"trim",
")",
":",
"smooth_boe",
"=",
"scipy",
".",
"signal",
".",
"convolve",
"(",
"localscore",
"[",
"beats",
"]",
",",
"scipy",
".",
"signal",
".",
"hann",
"(",
"5",
")",
",",
"'same'",
"... | 31.066667 | 0.002083 |
def intuition(args):
'''
Main simulation wrapper
Load the configuration, run the engine and return the analyze.
'''
# Use the provided context builder to fill:
# - config: General behavior
# - strategy: Modules properties
# - market: The universe we will trade on
with setup.Co... | [
"def",
"intuition",
"(",
"args",
")",
":",
"# Use the provided context builder to fill:",
"# - config: General behavior",
"# - strategy: Modules properties",
"# - market: The universe we will trade on",
"with",
"setup",
".",
"Context",
"(",
"args",
"[",
"'context'",
"]",
... | 35.977273 | 0.000615 |
def validate_message_dict(self, request_body):
"""With the JSON dict that will be sent to SendGrid's API,
check the content for SendGrid API keys - throw exception if found.
:param request_body: The JSON dict that will be sent to SendGrid's
API.
... | [
"def",
"validate_message_dict",
"(",
"self",
",",
"request_body",
")",
":",
"# Handle string in edge-case",
"if",
"isinstance",
"(",
"request_body",
",",
"str",
")",
":",
"self",
".",
"validate_message_text",
"(",
"request_body",
")",
"# Default param",
"elif",
"isi... | 41.769231 | 0.0018 |
def _makeBaseDir(basedir, quiet):
"""
Make worker base directory if needed.
@param basedir: worker base directory relative path
@param quiet: if True, don't print info messages
@raise CreateWorkerError: on error making base directory
"""
if os.path.exists(basedir):
if not quiet:
... | [
"def",
"_makeBaseDir",
"(",
"basedir",
",",
"quiet",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"basedir",
")",
":",
"if",
"not",
"quiet",
":",
"print",
"(",
"\"updating existing installation\"",
")",
"return",
"if",
"not",
"quiet",
":",
"pri... | 28.318182 | 0.001553 |
def rcts(self, command, *args, **kwargs):
'''General function for applying a rolling R function to a timeserie'''
cls = self.__class__
name = kwargs.pop('name','')
date = kwargs.pop('date',None)
data = kwargs.pop('data',None)
kwargs.pop('bycolumn',None)
ts ... | [
"def",
"rcts",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"name",
"=",
"kwargs",
".",
"pop",
"(",
"'name'",
",",
"''",
")",
"date",
"=",
"kwargs",
".",
"pop",
"(",
"'d... | 41.9 | 0.021028 |
def get_issue_comments(self):
"""
:calls: `GET /repos/:owner/:repo/issues/:number/comments <http://developer.github.com/v3/issues/comments>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.IssueComment.IssueComment`
"""
return github.PaginatedList.Paginated... | [
"def",
"get_issue_comments",
"(",
"self",
")",
":",
"return",
"github",
".",
"PaginatedList",
".",
"PaginatedList",
"(",
"github",
".",
"IssueComment",
".",
"IssueComment",
",",
"self",
".",
"_requester",
",",
"self",
".",
"issue_url",
"+",
"\"/comments\"",
",... | 41.727273 | 0.008529 |
def intersect(self, other_seg, tol=None):
"""Finds the intersections of two segments.
returns a list of tuples (t1, t2) such that
self.point(t1) == other_seg.point(t2).
Note: This will fail if the two segments coincide for more than a
finite collection of points.
tol is n... | [
"def",
"intersect",
"(",
"self",
",",
"other_seg",
",",
"tol",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"other_seg",
",",
"Line",
")",
":",
"assert",
"other_seg",
".",
"end",
"!=",
"other_seg",
".",
"start",
"and",
"self",
".",
"end",
"!=",
"s... | 46.477273 | 0.000958 |
def next_history(self, e): # (C-n)
u'''Move forward through the history list, fetching the next
command. '''
self._history.next_history(self.l_buffer)
self.finalize() | [
"def",
"next_history",
"(",
"self",
",",
"e",
")",
":",
"# (C-n)\r",
"self",
".",
"_history",
".",
"next_history",
"(",
"self",
".",
"l_buffer",
")",
"self",
".",
"finalize",
"(",
")"
] | 39.8 | 0.009852 |
def rpc_get_names(self, filename, source, offset):
"""Return the list of possible names"""
names = jedi.api.names(source=source,
path=filename, encoding='utf-8',
all_scopes=True,
definitions=True,
... | [
"def",
"rpc_get_names",
"(",
"self",
",",
"filename",
",",
"source",
",",
"offset",
")",
":",
"names",
"=",
"jedi",
".",
"api",
".",
"names",
"(",
"source",
"=",
"source",
",",
"path",
"=",
"filename",
",",
"encoding",
"=",
"'utf-8'",
",",
"all_scopes"... | 43.65 | 0.002242 |
def overlapping(startAttribute, # X
endAttribute, # Y
startValue, # A
endValue, # B
):
"""
Return an L{axiom.iaxiom.IComparison} (an object that can be passed as the
'comparison' argument to Store.query/.sum/.count) which will const... | [
"def",
"overlapping",
"(",
"startAttribute",
",",
"# X",
"endAttribute",
",",
"# Y",
"startValue",
",",
"# A",
"endValue",
",",
"# B",
")",
":",
"assert",
"startValue",
"<=",
"endValue",
"return",
"OR",
"(",
"AND",
"(",
"startAttribute",
">=",
"startValue",
... | 32.617647 | 0.000875 |
def _cursorRight(self):
""" Handles "cursor right" events """
if self.cursorPos < len(self.inputBuffer):
self.cursorPos += 1
sys.stdout.write(console.CURSOR_RIGHT)
sys.stdout.flush() | [
"def",
"_cursorRight",
"(",
"self",
")",
":",
"if",
"self",
".",
"cursorPos",
"<",
"len",
"(",
"self",
".",
"inputBuffer",
")",
":",
"self",
".",
"cursorPos",
"+=",
"1",
"sys",
".",
"stdout",
".",
"write",
"(",
"console",
".",
"CURSOR_RIGHT",
")",
"s... | 38.166667 | 0.008547 |
def _to_pandas(ob):
"""Convert an array-like to a pandas object.
Parameters
----------
ob : array-like
The object to convert.
Returns
-------
pandas_structure : pd.Series or pd.DataFrame
The correct structure based on the dimensionality of the data.
"""
if isinstanc... | [
"def",
"_to_pandas",
"(",
"ob",
")",
":",
"if",
"isinstance",
"(",
"ob",
",",
"(",
"pd",
".",
"Series",
",",
"pd",
".",
"DataFrame",
")",
")",
":",
"return",
"ob",
"if",
"ob",
".",
"ndim",
"==",
"1",
":",
"return",
"pd",
".",
"Series",
"(",
"ob... | 23.708333 | 0.001689 |
def add_worksheet_progress_percentage(portal):
"""Adds getProgressPercentage metadata to worksheets catalog
"""
add_metadata(portal, CATALOG_WORKSHEET_LISTING, "getProgressPercentage")
logger.info("Reindexing Worksheets ...")
query = dict(portal_type="Worksheet")
brains = api.search(query, CATAL... | [
"def",
"add_worksheet_progress_percentage",
"(",
"portal",
")",
":",
"add_metadata",
"(",
"portal",
",",
"CATALOG_WORKSHEET_LISTING",
",",
"\"getProgressPercentage\"",
")",
"logger",
".",
"info",
"(",
"\"Reindexing Worksheets ...\"",
")",
"query",
"=",
"dict",
"(",
"p... | 42.928571 | 0.001629 |
def translate(root_list, use_bag_semantics=False):
"""
Translate a list of relational algebra trees into SQL statements.
:param root_list: a list of tree roots
:param use_bag_semantics: flag for using relational algebra bag semantics
:return: a list of SQL statements
"""
translator = (Trans... | [
"def",
"translate",
"(",
"root_list",
",",
"use_bag_semantics",
"=",
"False",
")",
":",
"translator",
"=",
"(",
"Translator",
"(",
")",
"if",
"use_bag_semantics",
"else",
"SetTranslator",
"(",
")",
")",
"return",
"[",
"translator",
".",
"translate",
"(",
"ro... | 43.2 | 0.002268 |
def _call(self, x):
"""Return ``self(x)``."""
if abs(x.ufuncs.sum() / self.sum_value - 1) <= self.sum_rtol:
return 0
else:
return np.inf | [
"def",
"_call",
"(",
"self",
",",
"x",
")",
":",
"if",
"abs",
"(",
"x",
".",
"ufuncs",
".",
"sum",
"(",
")",
"/",
"self",
".",
"sum_value",
"-",
"1",
")",
"<=",
"self",
".",
"sum_rtol",
":",
"return",
"0",
"else",
":",
"return",
"np",
".",
"i... | 25.571429 | 0.010811 |
def find_domain(session, name):
"""Find a domain.
Find a domain by its domain name using the given `session`.
When the domain does not exist the function will
return `None`.
:param session: database session
:param name: name of the domain to find
:returns: a domain object; `None` when the... | [
"def",
"find_domain",
"(",
"session",
",",
"name",
")",
":",
"domain",
"=",
"session",
".",
"query",
"(",
"Domain",
")",
".",
"filter",
"(",
"Domain",
".",
"domain",
"==",
"name",
")",
".",
"first",
"(",
")",
"return",
"domain"
] | 26.176471 | 0.002169 |
def register_exporter(name, base_class):
"""
Register an exporter to use for a :class:`Part <cqparts.Part>`,
:class:`Assembly <cqparts.Assembly>`, or both
(with :class:`Component <cqparts.Component>`).
Registration is necessary to use with
:meth:`Component.exporter() <cqparts.Component.exporter... | [
"def",
"register_exporter",
"(",
"name",
",",
"base_class",
")",
":",
"# Verify params",
"if",
"not",
"isinstance",
"(",
"name",
",",
"str",
")",
"or",
"(",
"not",
"name",
")",
":",
"raise",
"TypeError",
"(",
"\"invalid name: %r\"",
"%",
"name",
")",
"if",... | 36.241379 | 0.002316 |
def get(self,
variable_path: str,
default: t.Optional[t.Any] = None,
coerce_type: t.Optional[t.Type] = None,
coercer: t.Optional[t.Callable] = None,
**kwargs):
"""
Reads a value of ``variable_path`` from consul kv storage.
:param varia... | [
"def",
"get",
"(",
"self",
",",
"variable_path",
":",
"str",
",",
"default",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Any",
"]",
"=",
"None",
",",
"coerce_type",
":",
"t",
".",
"Optional",
"[",
"t",
".",
"Type",
"]",
"=",
"None",
",",
"coercer"... | 38.857143 | 0.008072 |
def _Bound_hs(h, s):
"""Region definition for input h and s
Parameters
----------
h : float
Specific enthalpy, [kJ/kg]
s : float
Specific entropy, [kJ/kgK]
Returns
-------
region : float
IAPWS-97 region code
References
----------
Wagner, W; Kretzsch... | [
"def",
"_Bound_hs",
"(",
"h",
",",
"s",
")",
":",
"region",
"=",
"None",
"s13",
"=",
"_Region1",
"(",
"623.15",
",",
"100",
")",
"[",
"\"s\"",
"]",
"s13s",
"=",
"_Region1",
"(",
"623.15",
",",
"Ps_623",
")",
"[",
"\"s\"",
"]",
"sTPmax",
"=",
"_Re... | 27.894118 | 0.000204 |
def missing_datetimes(self, finite_datetimes):
"""
Override in subclasses to do bulk checks.
Returns a sorted list.
This is a conservative base implementation that brutally checks completeness, instance by instance.
Inadvisable as it may be slow.
"""
return [d ... | [
"def",
"missing_datetimes",
"(",
"self",
",",
"finite_datetimes",
")",
":",
"return",
"[",
"d",
"for",
"d",
"in",
"finite_datetimes",
"if",
"not",
"self",
".",
"_instantiate_task_cls",
"(",
"self",
".",
"datetime_to_parameter",
"(",
"d",
")",
")",
".",
"comp... | 37.454545 | 0.009479 |
def vault_file(env, default):
"""The path to a misc Vault file
This function will check for the env override on a file
path, compute a fully qualified OS appropriate path to
the desired file and return it if it exists. Otherwise
returns None
"""
home = os.environ['HOME'] if 'HOME' in os.envi... | [
"def",
"vault_file",
"(",
"env",
",",
"default",
")",
":",
"home",
"=",
"os",
".",
"environ",
"[",
"'HOME'",
"]",
"if",
"'HOME'",
"in",
"os",
".",
"environ",
"else",
"os",
".",
"environ",
"[",
"'USERPROFILE'",
"]",
"filename",
"=",
"os",
".",
"enviro... | 34.733333 | 0.001869 |
def collection_composition(collection, raw=False):
"""
This method retrieve the total of documents, articles (citable documents),
issues and bibliografic references of a journal
arguments
collection: SciELO 3 letters Acronym
issn: Journal ISSN
return for journal context
{
"cita... | [
"def",
"collection_composition",
"(",
"collection",
",",
"raw",
"=",
"False",
")",
":",
"tc",
"=",
"ThriftClient",
"(",
")",
"body",
"=",
"{",
"\"query\"",
":",
"{",
"\"filtered\"",
":",
"{",
"}",
"}",
"}",
"fltr",
"=",
"{",
"}",
"query",
"=",
"{",
... | 21.337662 | 0.000582 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.