text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def widget(self, which_viz='viz'):
'''
Generate a widget visualization using the widget. The export_viz_to_widget
method passes the visualization JSON to the instantiated widget, which is
returned and visualized on the front-end.
'''
if hasattr(self, 'widget_class') == True:
self.widget_in... | [
"def",
"widget",
"(",
"self",
",",
"which_viz",
"=",
"'viz'",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'widget_class'",
")",
"==",
"True",
":",
"self",
".",
"widget_instance",
"=",
"self",
".",
"widget_class",
"(",
"network",
"=",
"self",
".",
"ex... | 47.307692 | 0.017544 |
def save_and_check(response, local_file, expected_checksum):
"""Save the content of an http response and verify the checksum matches."""
with open(local_file, 'wb') as handle:
for chunk in response.iter_content(4096):
handle.write(chunk)
actual_checksum = md5sum(local_file)
if actua... | [
"def",
"save_and_check",
"(",
"response",
",",
"local_file",
",",
"expected_checksum",
")",
":",
"with",
"open",
"(",
"local_file",
",",
"'wb'",
")",
"as",
"handle",
":",
"for",
"chunk",
"in",
"response",
".",
"iter_content",
"(",
"4096",
")",
":",
"handle... | 39.923077 | 0.001883 |
def get_user_cache_key(**kwargs):
""" Generate suitable key to cache twitter tag context
"""
key = 'get_tweets_%s' % ('_'.join([str(kwargs[key]) for key in sorted(kwargs) if kwargs[key]]))
not_allowed = re.compile('[^%s]' % ''.join([chr(i) for i in range(33, 128)]))
key = not_allowed.sub('', key)
... | [
"def",
"get_user_cache_key",
"(",
"*",
"*",
"kwargs",
")",
":",
"key",
"=",
"'get_tweets_%s'",
"%",
"(",
"'_'",
".",
"join",
"(",
"[",
"str",
"(",
"kwargs",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"sorted",
"(",
"kwargs",
")",
"if",
"kwargs",
"["... | 46.571429 | 0.009036 |
def _estimateCubicCurveLength(pt0, pt1, pt2, pt3, precision=10):
"""
Estimate the length of this curve by iterating
through it and averaging the length of the flat bits.
"""
points = []
length = 0
step = 1.0 / precision
factors = range(0, precision + 1)
for i in factors:
poin... | [
"def",
"_estimateCubicCurveLength",
"(",
"pt0",
",",
"pt1",
",",
"pt2",
",",
"pt3",
",",
"precision",
"=",
"10",
")",
":",
"points",
"=",
"[",
"]",
"length",
"=",
"0",
"step",
"=",
"1.0",
"/",
"precision",
"factors",
"=",
"range",
"(",
"0",
",",
"p... | 31.5625 | 0.001923 |
def record_iterator(xml):
"""
Iterate over all ``<record>`` tags in `xml`.
Args:
xml (str/file): Input string with XML. UTF-8 is prefered encoding,
unicode should be ok.
Yields:
MARCXMLRecord: For each corresponding ``<record>``.
"""
# handle file-like o... | [
"def",
"record_iterator",
"(",
"xml",
")",
":",
"# handle file-like objects",
"if",
"hasattr",
"(",
"xml",
",",
"\"read\"",
")",
":",
"xml",
"=",
"xml",
".",
"read",
"(",
")",
"dom",
"=",
"None",
"try",
":",
"dom",
"=",
"dhtmlparser",
".",
"parseString",... | 25.826087 | 0.001623 |
def GroupsSensorsGet(self, group_id, parameters):
"""
Retrieve sensors shared within the group.
@param group_id (int) - Id of the group to retrieve sensors from
@param parameters (dictionary) - Additional parameters for the call
@r... | [
"def",
"GroupsSensorsGet",
"(",
"self",
",",
"group_id",
",",
"parameters",
")",
":",
"if",
"self",
".",
"__SenseApiCall",
"(",
"\"/groups/{0}/sensors.json\"",
".",
"format",
"(",
"group_id",
")",
",",
"\"GET\"",
",",
"parameters",
"=",
"parameters",
")",
":",... | 44.5 | 0.012579 |
def parse_proxy_line(line):
"""
Parse proxy details from the raw text line.
The text line could be in one of the following formats:
* host:port
* host:port:username:password
"""
line = line.strip()
match = RE_SIMPLE_PROXY.search(line)
if match:
return match.group(1), match.... | [
"def",
"parse_proxy_line",
"(",
"line",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"match",
"=",
"RE_SIMPLE_PROXY",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"return",
"match",
".",
"group",
"(",
"1",
")",
",",
"match",
".",
... | 26 | 0.001855 |
def merge_cookies(cookiejar, cookies):
"""Add cookies to cookiejar and returns a merged CookieJar.
:param cookiejar: CookieJar object to add the cookies to.
:param cookies: Dictionary or CookieJar object to be added.
:rtype: CookieJar
"""
if not isinstance(cookiejar, cookielib.CookieJar):
... | [
"def",
"merge_cookies",
"(",
"cookiejar",
",",
"cookies",
")",
":",
"if",
"not",
"isinstance",
"(",
"cookiejar",
",",
"cookielib",
".",
"CookieJar",
")",
":",
"raise",
"ValueError",
"(",
"'You can only merge into CookieJar'",
")",
"if",
"isinstance",
"(",
"cooki... | 35.238095 | 0.001316 |
def unescape(self):
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
>>> Markup('Main » <em>About</em>').unescape()
'Main » <em>About</em>'
"""
from ._constants import HTML_ENTITIES
def hand... | [
"def",
"unescape",
"(",
"self",
")",
":",
"from",
".",
"_constants",
"import",
"HTML_ENTITIES",
"def",
"handle_match",
"(",
"m",
")",
":",
"name",
"=",
"m",
".",
"group",
"(",
"1",
")",
"if",
"name",
"in",
"HTML_ENTITIES",
":",
"return",
"unichr",
"(",... | 34.291667 | 0.002364 |
def record_match_subfields(rec, tag, ind1=" ", ind2=" ", sub_key=None,
sub_value='', sub_key2=None, sub_value2='',
case_sensitive=True):
"""
Find subfield instances in a particular field.
It tests values in 1 of 3 possible ways:
- Does a subfield c... | [
"def",
"record_match_subfields",
"(",
"rec",
",",
"tag",
",",
"ind1",
"=",
"\" \"",
",",
"ind2",
"=",
"\" \"",
",",
"sub_key",
"=",
"None",
",",
"sub_value",
"=",
"''",
",",
"sub_key2",
"=",
"None",
",",
"sub_value2",
"=",
"''",
",",
"case_sensitive",
... | 40.555556 | 0.000446 |
def object_links(self, multihash, **kwargs):
"""Returns the links pointed to by the specified object.
.. code-block:: python
>>> c.object_links('QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDx … ca7D')
{'Hash': 'QmTkzDwWqPbnAh5YiV5VwcTLnGdwSNsNTn2aDxdXBFca7D',
'Links': [
... | [
"def",
"object_links",
"(",
"self",
",",
"multihash",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"multihash",
",",
")",
"return",
"self",
".",
"_client",
".",
"request",
"(",
"'/object/links'",
",",
"args",
",",
"decoder",
"=",
"'json'",
",",... | 43.612903 | 0.001447 |
def update(self):
"""Update the ports list."""
if self.input_method == 'local':
# Only refresh:
# * if there is not other scanning thread
# * every refresh seconds (define in the configuration file)
if self._thread is None:
thread_is_runnin... | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"input_method",
"==",
"'local'",
":",
"# Only refresh:",
"# * if there is not other scanning thread",
"# * every refresh seconds (define in the configuration file)",
"if",
"self",
".",
"_thread",
"is",
"None",
":"... | 37.291667 | 0.002179 |
def dot(r1, r2):
"""Compute the dot product
Arguments:
| ``r1``, ``r2`` -- two :class:`Vector3` objects
(Returns a Scalar)
"""
if r1.size != r2.size:
raise ValueError("Both arguments must have the same input size.")
if r1.deriv != r2.deriv:
raise ValueError("Both... | [
"def",
"dot",
"(",
"r1",
",",
"r2",
")",
":",
"if",
"r1",
".",
"size",
"!=",
"r2",
".",
"size",
":",
"raise",
"ValueError",
"(",
"\"Both arguments must have the same input size.\"",
")",
"if",
"r1",
".",
"deriv",
"!=",
"r2",
".",
"deriv",
":",
"raise",
... | 30.076923 | 0.002481 |
def tokenize(string, language=None, escape='___'):
"""
Given a string, return a list of math symbol tokens
"""
# Set all words to lowercase
string = string.lower()
# Ignore punctuation
if len(string) and not string[-1].isalnum():
character = string[-1]
string = string[:-1] +... | [
"def",
"tokenize",
"(",
"string",
",",
"language",
"=",
"None",
",",
"escape",
"=",
"'___'",
")",
":",
"# Set all words to lowercase",
"string",
"=",
"string",
".",
"lower",
"(",
")",
"# Ignore punctuation",
"if",
"len",
"(",
"string",
")",
"and",
"not",
"... | 28.37931 | 0.001175 |
def user_password_requirements(self, user_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users#get-a-list-of-password-requirements"
api_path = "/api/v2/users/{user_id}/password/requirements.json"
api_path = api_path.format(user_id=user_id)
return self.call(api_path, **k... | [
"def",
"user_password_requirements",
"(",
"self",
",",
"user_id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/users/{user_id}/password/requirements.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"user_id",
"=",
"user_id",
")",
"return",... | 64.4 | 0.009202 |
def mark_pausing(self):
"""Requests that the service move to the Paused state, without waiting for it to do so.
Raises if the service is not currently in the Running state.
"""
with self._lock:
self._set_state(self._PAUSING, self._RUNNING) | [
"def",
"mark_pausing",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_set_state",
"(",
"self",
".",
"_PAUSING",
",",
"self",
".",
"_RUNNING",
")"
] | 36.571429 | 0.01145 |
def moran_cultural(network):
"""Generalized cultural Moran process.
At eachtime step, an individual is chosen to receive information from
another individual. Nobody dies, but perhaps their ideas do.
"""
if not network.transmissions(): # first step, replacer is a source
replacer = random.ch... | [
"def",
"moran_cultural",
"(",
"network",
")",
":",
"if",
"not",
"network",
".",
"transmissions",
"(",
")",
":",
"# first step, replacer is a source",
"replacer",
"=",
"random",
".",
"choice",
"(",
"network",
".",
"nodes",
"(",
"type",
"=",
"Source",
")",
")"... | 36.736842 | 0.001397 |
def write(self, message):
"""
(coroutine)
Write a single message into the pipe.
"""
if self.done_f.done():
raise BrokenPipeError
try:
yield From(write_message_to_pipe(self.pipe_instance.pipe_handle, message))
except BrokenPipeError:
... | [
"def",
"write",
"(",
"self",
",",
"message",
")",
":",
"if",
"self",
".",
"done_f",
".",
"done",
"(",
")",
":",
"raise",
"BrokenPipeError",
"try",
":",
"yield",
"From",
"(",
"write_message_to_pipe",
"(",
"self",
".",
"pipe_instance",
".",
"pipe_handle",
... | 27.692308 | 0.008065 |
def ProcessHuntFlowDone(flow_obj, status_msg=None):
"""Notifis hunt about a given hunt-induced flow completion."""
if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id):
hunt_obj = hunt.StopHuntIfCPUOrNetworkLimitsExceeded(
flow_obj.parent_hunt_id)
hunt.CompleteHuntIfExpirationTimeReached(hunt_obj)
... | [
"def",
"ProcessHuntFlowDone",
"(",
"flow_obj",
",",
"status_msg",
"=",
"None",
")",
":",
"if",
"not",
"hunt",
".",
"IsLegacyHunt",
"(",
"flow_obj",
".",
"parent_hunt_id",
")",
":",
"hunt_obj",
"=",
"hunt",
".",
"StopHuntIfCPUOrNetworkLimitsExceeded",
"(",
"flow_... | 35.771429 | 0.008554 |
def setnx(self, key, value):
"""Set the value of a key, only if the key does not exist."""
fut = self.execute(b'SETNX', key, value)
return wait_convert(fut, bool) | [
"def",
"setnx",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"fut",
"=",
"self",
".",
"execute",
"(",
"b'SETNX'",
",",
"key",
",",
"value",
")",
"return",
"wait_convert",
"(",
"fut",
",",
"bool",
")"
] | 45.75 | 0.010753 |
def append(self, data):
"""Append the given `data` to the output.
:arg data: If a list, it is formatted as a bullet list with each
entry in the list being a separate bullet. Otherwise if it is a
string, the string is added as a paragraph.
:raises: ValueError if `data` ... | [
"def",
"append",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"# First we need to clean up the data.",
"#",
"# Gerrit creates new bullet items when it gets newline characters",
"# withi... | 41.461538 | 0.001208 |
def display(text, mode='exec', file=None):
"""
Show `text`, rendered as AST and as Bytecode.
Parameters
----------
text : str
Text of Python code to render.
mode : {'exec', 'eval'}, optional
Mode for `ast.parse` and `compile`. Default is 'exec'.
file : None or file-like obj... | [
"def",
"display",
"(",
"text",
",",
"mode",
"=",
"'exec'",
",",
"file",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"sys",
".",
"stdout",
"ast_section",
"=",
"StringIO",
"(",
")",
"a",
"(",
"text",
",",
"mode",
"=",
"mode... | 25.9 | 0.001241 |
def iter_leaf_names(self, is_leaf_fn=None):
"""Returns an iterator over the leaf names under this node."""
for n in self.iter_leaves(is_leaf_fn=is_leaf_fn):
yield n.name | [
"def",
"iter_leaf_names",
"(",
"self",
",",
"is_leaf_fn",
"=",
"None",
")",
":",
"for",
"n",
"in",
"self",
".",
"iter_leaves",
"(",
"is_leaf_fn",
"=",
"is_leaf_fn",
")",
":",
"yield",
"n",
".",
"name"
] | 48.5 | 0.010152 |
def parameters_to_tuples(self, params, collection_formats):
"""Get parameters as list of tuples, formatting collections.
:param params: Parameters as dict or list of two-tuples
:param dict collection_formats: Parameter collection formats
:return: Parameters as list of tuples, collection... | [
"def",
"parameters_to_tuples",
"(",
"self",
",",
"params",
",",
"collection_formats",
")",
":",
"new_params",
"=",
"[",
"]",
"if",
"collection_formats",
"is",
"None",
":",
"collection_formats",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iterit... | 45.172414 | 0.001495 |
def add_snow(img, snow_point, brightness_coeff):
"""Bleaches out pixels, mitation snow.
From https://github.com/UjjwalSaxena/Automold--Road-Augmentation-Library
Args:
img:
snow_point:
brightness_coeff:
Returns:
"""
non_rgb_warning(img)
input_dtype = img.dtype
... | [
"def",
"add_snow",
"(",
"img",
",",
"snow_point",
",",
"brightness_coeff",
")",
":",
"non_rgb_warning",
"(",
"img",
")",
"input_dtype",
"=",
"img",
".",
"dtype",
"needs_float",
"=",
"False",
"snow_point",
"*=",
"127.5",
"# = 255 / 2",
"snow_point",
"+=",
"85",... | 26.142857 | 0.001756 |
def import_categories(self, category_nodes):
"""
Import all the categories from 'wp:category' nodes,
because categories in 'item' nodes are not necessarily
all the categories and returning it in a dict for
database optimizations.
"""
self.write_out(self.style.STEP... | [
"def",
"import_categories",
"(",
"self",
",",
"category_nodes",
")",
":",
"self",
".",
"write_out",
"(",
"self",
".",
"style",
".",
"STEP",
"(",
"'- Importing categories\\n'",
")",
")",
"categories",
"=",
"{",
"}",
"for",
"category_node",
"in",
"category_nodes... | 42.538462 | 0.001768 |
def identifier_director(**kwargs):
"""Direct the identifier elements based on their qualifier."""
qualifier = kwargs.get('qualifier', '')
content = kwargs.get('content', '')
if qualifier == 'ISBN':
return CitationISBN(content=content)
elif qualifier == 'ISSN':
return CitationISSN(con... | [
"def",
"identifier_director",
"(",
"*",
"*",
"kwargs",
")",
":",
"qualifier",
"=",
"kwargs",
".",
"get",
"(",
"'qualifier'",
",",
"''",
")",
"content",
"=",
"kwargs",
".",
"get",
"(",
"'content'",
",",
"''",
")",
"if",
"qualifier",
"==",
"'ISBN'",
":",... | 36.928571 | 0.001887 |
def Proxy(self, status, headers, exc_info=None):
"""Save args, defer start_response until response body is parsed.
Create output buffer for body to be written into.
Note: this is not quite WSGI compliant: The body should come back as an
iterator returned from calling service_app() but instead, StartR... | [
"def",
"Proxy",
"(",
"self",
",",
"status",
",",
"headers",
",",
"exc_info",
"=",
"None",
")",
":",
"self",
".",
"call_context",
"[",
"'status'",
"]",
"=",
"status",
"self",
".",
"call_context",
"[",
"'headers'",
"]",
"=",
"headers",
"self",
".",
"call... | 42.391304 | 0.001003 |
def register_fields(w):
"""
Register shapefile fields.
"""
PARAMS_LIST = [BASE_PARAMS, GEOMETRY_PARAMS, MFD_PARAMS]
for PARAMS in PARAMS_LIST:
for _, param, dtype in PARAMS:
w.field(param, fieldType=dtype, size=FIELD_SIZE)
PARAMS_LIST = [
RATE_PARAMS, STRIKE_PARAMS, ... | [
"def",
"register_fields",
"(",
"w",
")",
":",
"PARAMS_LIST",
"=",
"[",
"BASE_PARAMS",
",",
"GEOMETRY_PARAMS",
",",
"MFD_PARAMS",
"]",
"for",
"PARAMS",
"in",
"PARAMS_LIST",
":",
"for",
"_",
",",
"param",
",",
"dtype",
"in",
"PARAMS",
":",
"w",
".",
"field... | 33.166667 | 0.001629 |
def make_PCEExtension_for_prebuilding_Code(
name, Code, prebuild_sources, srcdir,
downloads=None, **kwargs):
"""
If subclass of codeexport.Generic_Code needs to have some of it
sources compiled to objects and cached in a `prebuilt/` directory
at invocation of `setup.py build_ext` this co... | [
"def",
"make_PCEExtension_for_prebuilding_Code",
"(",
"name",
",",
"Code",
",",
"prebuild_sources",
",",
"srcdir",
",",
"downloads",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"glob",
"from",
".",
"dist",
"import",
"PCEExtension",
"build_files",
... | 37.025 | 0.000329 |
def change_default(
kls,
key,
new_default,
new_converter=None,
new_reference_value=None,
):
"""return a new configman Option object that is a copy of an existing one,
giving the new one a different default value"""
an_option = kls.get_required_config()[key].copy()
an_option.default =... | [
"def",
"change_default",
"(",
"kls",
",",
"key",
",",
"new_default",
",",
"new_converter",
"=",
"None",
",",
"new_reference_value",
"=",
"None",
",",
")",
":",
"an_option",
"=",
"kls",
".",
"get_required_config",
"(",
")",
"[",
"key",
"]",
".",
"copy",
"... | 31.5625 | 0.001923 |
def get(pb_or_dict, key, default=_SENTINEL):
"""Retrieve the given key off of the object.
If a default is specified, return it if the key is not found, otherwise
raise KeyError.
Args:
pb_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
object.
key (str): The ... | [
"def",
"get",
"(",
"pb_or_dict",
",",
"key",
",",
"default",
"=",
"_SENTINEL",
")",
":",
"# We may need to get a nested key. Resolve this.",
"key",
",",
"subkey",
"=",
"_resolve_subkeys",
"(",
"key",
")",
"# Attempt to get the value from the two types of objects we know bao... | 40.26 | 0.000485 |
def async_process(funcs, *args, executor=False, sol=None, callback=None, **kw):
"""
Execute `func(*args)` in an asynchronous parallel process.
:param funcs:
Functions to be executed.
:type funcs: list[callable]
:param args:
Arguments to be passed to first function call.
:type a... | [
"def",
"async_process",
"(",
"funcs",
",",
"*",
"args",
",",
"executor",
"=",
"False",
",",
"sol",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"name",
"=",
"_executor_name",
"(",
"executor",
",",
"sol",
".",
"dsp",
")"... | 24.659091 | 0.000887 |
def unitary_operator(state_vector):
"""
Uses QR factorization to create a unitary operator
that can encode an arbitrary normalized vector into
the wavefunction of a quantum state.
Assumes that the state of the input qubits is to be expressed as
.. math::
(1, 0, \\ldots, 0)^T
:par... | [
"def",
"unitary_operator",
"(",
"state_vector",
")",
":",
"if",
"not",
"np",
".",
"allclose",
"(",
"[",
"np",
".",
"linalg",
".",
"norm",
"(",
"state_vector",
")",
"]",
",",
"[",
"1",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"Vector must be normalize... | 30.891892 | 0.001696 |
def get_xy_rotation_and_scale(header):
"""
CREDIT: See IDL code at
http://www.astro.washington.edu/docs/idl/cgi-bin/getpro/library32.html?GETROT
"""
def calc_from_cd(cd1_1, cd1_2, cd2_1, cd2_2):
# TODO: Check if first coordinate in CTYPE is latitude
# if (ctype EQ 'DEC-') or (strmi... | [
"def",
"get_xy_rotation_and_scale",
"(",
"header",
")",
":",
"def",
"calc_from_cd",
"(",
"cd1_1",
",",
"cd1_2",
",",
"cd2_1",
",",
"cd2_2",
")",
":",
"# TODO: Check if first coordinate in CTYPE is latitude",
"# if (ctype EQ 'DEC-') or (strmid(ctype, 1) EQ 'LAT') then $",
"# ... | 29.011111 | 0.001481 |
def normalize_surfs(in_file, transform_file, newpath=None):
""" Re-center GIFTI coordinates to fit align to native T1 space
For midthickness surfaces, add MidThickness metadata
Coordinate update based on:
https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceAp... | [
"def",
"normalize_surfs",
"(",
"in_file",
",",
"transform_file",
",",
"newpath",
"=",
"None",
")",
":",
"img",
"=",
"nb",
".",
"load",
"(",
"in_file",
")",
"transform",
"=",
"load_transform",
"(",
"transform_file",
")",
"pointset",
"=",
"img",
".",
"get_ar... | 43.297872 | 0.001922 |
def _get_socket_no_auth(self):
"""Get or create a SocketInfo. Can raise ConnectionFailure."""
# We use the pid here to avoid issues with fork / multiprocessing.
# See test.test_client:TestClient.test_fork for an example of
# what could go wrong otherwise
if self.pid != os.getpid(... | [
"def",
"_get_socket_no_auth",
"(",
"self",
")",
":",
"# We use the pid here to avoid issues with fork / multiprocessing.",
"# See test.test_client:TestClient.test_fork for an example of",
"# what could go wrong otherwise",
"if",
"self",
".",
"pid",
"!=",
"os",
".",
"getpid",
"(",
... | 37.944444 | 0.001428 |
def _export_all_keyword(self):
"""
Export method for keyword tab files
"""
data = {}
for fluid_idx, fluid in enumerate(self.metadata["fluids"]):
data[fluid] = {}
with open(self.abspath) as fobj:
text = fobj.read()
t... | [
"def",
"_export_all_keyword",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"for",
"fluid_idx",
",",
"fluid",
"in",
"enumerate",
"(",
"self",
".",
"metadata",
"[",
"\"fluids\"",
"]",
")",
":",
"data",
"[",
"fluid",
"]",
"=",
"{",
"}",
"with",
"open",... | 41.863636 | 0.002123 |
def info(self):
"""
tuple of the start_pc, end_pc, handler_pc and catch_type_ref
"""
return (self.start_pc, self.end_pc,
self.handler_pc, self.get_catch_type()) | [
"def",
"info",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"start_pc",
",",
"self",
".",
"end_pc",
",",
"self",
".",
"handler_pc",
",",
"self",
".",
"get_catch_type",
"(",
")",
")"
] | 29 | 0.009569 |
async def encoder_config(self, pin_a, pin_b, cb=None, cb_type=None,
hall_encoder=False):
"""
This command enables the rotary encoder support and will
enable encoder reporting.
This command is not part of StandardFirmata. For 2 pin + ground
encoders, ... | [
"async",
"def",
"encoder_config",
"(",
"self",
",",
"pin_a",
",",
"pin_b",
",",
"cb",
"=",
"None",
",",
"cb_type",
"=",
"None",
",",
"hall_encoder",
"=",
"False",
")",
":",
"# checked when encoder data is returned",
"self",
".",
"hall_encoder",
"=",
"hall_enco... | 36.641026 | 0.002045 |
def segments(self, using=None, **kwargs):
"""
Provide low level segments information that a Lucene index (shard
level) is built with.
Any additional keyword arguments will be passed to
``Elasticsearch.indices.segments`` unchanged.
"""
return self._get_connection(... | [
"def",
"segments",
"(",
"self",
",",
"using",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_get_connection",
"(",
"using",
")",
".",
"indices",
".",
"segments",
"(",
"index",
"=",
"self",
".",
"_name",
",",
"*",
"*",
"kwa... | 40.333333 | 0.008086 |
def init_algebra(*, default_hs_cls='LocalSpace'):
"""Initialize the algebra system
Args:
default_hs_cls (str): The name of the :class:`.LocalSpace` subclass
that should be used when implicitly creating Hilbert spaces, e.g.
in :class:`.OperatorSymbol`
"""
from qnet.algeb... | [
"def",
"init_algebra",
"(",
"*",
",",
"default_hs_cls",
"=",
"'LocalSpace'",
")",
":",
"from",
"qnet",
".",
"algebra",
".",
"core",
".",
"hilbert_space_algebra",
"import",
"LocalSpace",
"from",
"qnet",
".",
"algebra",
".",
"core",
".",
"abstract_quantum_algebra"... | 43.625 | 0.001403 |
def after(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts after the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If gi... | [
"def",
"after",
"(",
"self",
",",
"callback",
":",
"Union",
"[",
"Callable",
",",
"str",
"]",
")",
"->",
"\"Control\"",
":",
"if",
"isinstance",
"(",
"callback",
",",
"Control",
")",
":",
"callback",
"=",
"callback",
".",
"_after",
"self",
".",
"_after... | 44.538462 | 0.010152 |
def prepare_infrastructure():
"""Entry point for preparing the infrastructure in a specific env."""
runner = ForemastRunner()
runner.write_configs()
runner.create_app()
archaius = runner.configs[runner.env]['app']['archaius_enabled']
eureka = runner.configs[runner.env]['app']['eureka_enabled']... | [
"def",
"prepare_infrastructure",
"(",
")",
":",
"runner",
"=",
"ForemastRunner",
"(",
")",
"runner",
".",
"write_configs",
"(",
")",
"runner",
".",
"create_app",
"(",
")",
"archaius",
"=",
"runner",
".",
"configs",
"[",
"runner",
".",
"env",
"]",
"[",
"'... | 31.882353 | 0.000895 |
def configure(self, src_dir, build_dir, **kwargs):
"""This function builds the cmake configure command."""
del kwargs
ex_path = self._ex_args.get("project_path")
if ex_path:
src_dir = os.path.join(src_dir, ex_path)
return [{"args": ["cmake", src_dir] + self._config_a... | [
"def",
"configure",
"(",
"self",
",",
"src_dir",
",",
"build_dir",
",",
"*",
"*",
"kwargs",
")",
":",
"del",
"kwargs",
"ex_path",
"=",
"self",
".",
"_ex_args",
".",
"get",
"(",
"\"project_path\"",
")",
"if",
"ex_path",
":",
"src_dir",
"=",
"os",
".",
... | 42 | 0.008746 |
def setval(key, val, dict_=None, delim=DEFAULT_TARGET_DELIM):
'''
Set a value under the dictionary hierarchy identified
under the key. The target 'foo/bar/baz' returns the
dictionary hierarchy {'foo': {'bar': {'baz': {}}}}.
.. note::
Currently this doesn't work with integers, i.e.
... | [
"def",
"setval",
"(",
"key",
",",
"val",
",",
"dict_",
"=",
"None",
",",
"delim",
"=",
"DEFAULT_TARGET_DELIM",
")",
":",
"if",
"not",
"dict_",
":",
"dict_",
"=",
"{",
"}",
"prev_hier",
"=",
"dict_",
"dict_hier",
"=",
"key",
".",
"split",
"(",
"delim"... | 26.703704 | 0.001339 |
def digester(data):
"""Create SHA-1 hash, get digest, b64 encode, split every 60 char."""
if not isinstance(data, six.binary_type):
data = data.encode('utf_8')
hashof = hashlib.sha1(data).digest()
encoded_hash = base64.b64encode(hashof)
if not isinstance(encoded_hash, six.string_types):
... | [
"def",
"digester",
"(",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"six",
".",
"binary_type",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"'utf_8'",
")",
"hashof",
"=",
"hashlib",
".",
"sha1",
"(",
"data",
")",
".",
"dige... | 41.454545 | 0.002146 |
def wordify(text):
"""Generate a list of words given text, removing punctuation.
Parameters
----------
text : unicode
A piece of english text.
Returns
-------
words : list
List of words.
"""
stopset = set(nltk.corpus.stopwords.words('english'))
tokens = nltk.Wor... | [
"def",
"wordify",
"(",
"text",
")",
":",
"stopset",
"=",
"set",
"(",
"nltk",
".",
"corpus",
".",
"stopwords",
".",
"words",
"(",
"'english'",
")",
")",
"tokens",
"=",
"nltk",
".",
"WordPunctTokenizer",
"(",
")",
".",
"tokenize",
"(",
"text",
")",
"re... | 24.25 | 0.002481 |
def autoasync(coro=None, *, loop=None, forever=False, pass_loop=False):
'''
Convert an asyncio coroutine into a function which, when called, is
evaluted in an event loop, and the return value returned. This is intented
to make it easy to write entry points into asyncio coroutines, which
otherwise ne... | [
"def",
"autoasync",
"(",
"coro",
"=",
"None",
",",
"*",
",",
"loop",
"=",
"None",
",",
"forever",
"=",
"False",
",",
"pass_loop",
"=",
"False",
")",
":",
"if",
"coro",
"is",
"None",
":",
"return",
"lambda",
"c",
":",
"autoasync",
"(",
"c",
",",
"... | 38.275862 | 0.000293 |
def _log_disconnect(self):
"""Decrement connection count"""
if self.logged:
self.server.stats.on_conn_closed()
self.logged = False | [
"def",
"_log_disconnect",
"(",
"self",
")",
":",
"if",
"self",
".",
"logged",
":",
"self",
".",
"server",
".",
"stats",
".",
"on_conn_closed",
"(",
")",
"self",
".",
"logged",
"=",
"False"
] | 33.2 | 0.011765 |
def cache(handle=lambda *args, **kwargs: None, args=UNDEFINED, kwargs=UNDEFINED, ignore=UNDEFINED, call_stack=UNDEFINED, callback=UNDEFINED, subsequent_rvalue=UNDEFINED):
"""
Store a call descriptor
:param lambda handle: Any callable will work here. The method to cache.
:param tuple args: The arguments... | [
"def",
"cache",
"(",
"handle",
"=",
"lambda",
"*",
"args",
",",
"*",
"*",
"kwargs",
":",
"None",
",",
"args",
"=",
"UNDEFINED",
",",
"kwargs",
"=",
"UNDEFINED",
",",
"ignore",
"=",
"UNDEFINED",
",",
"call_stack",
"=",
"UNDEFINED",
",",
"callback",
"=",... | 46.329268 | 0.009021 |
def get_signed_query_params_v2(credentials, expiration, string_to_sign):
"""Gets query parameters for creating a signed URL.
:type credentials: :class:`google.auth.credentials.Signing`
:param credentials: The credentials used to create a private key
for signing text.
:type expi... | [
"def",
"get_signed_query_params_v2",
"(",
"credentials",
",",
"expiration",
",",
"string_to_sign",
")",
":",
"ensure_signed_credentials",
"(",
"credentials",
")",
"signature_bytes",
"=",
"credentials",
".",
"sign_bytes",
"(",
"string_to_sign",
")",
"signature",
"=",
"... | 36.758621 | 0.000914 |
async def update_info(self):
"""Update current price info async."""
query = gql(
"""
{
viewer {
home(id: "%s") {
appNickname
features {
realTimeConsumptionEnabled
}
currentSubscription {... | [
"async",
"def",
"update_info",
"(",
"self",
")",
":",
"query",
"=",
"gql",
"(",
"\"\"\"\n {\n viewer {\n home(id: \"%s\") {\n appNickname\n features {\n realTimeConsumptionEnabled\n }\n currentSub... | 24.222222 | 0.001259 |
def message(subject, message, access_token, all_members=False,
project_member_ids=None, base_url=OH_BASE_URL):
"""
Send an email to individual users or in bulk. To learn more about Open
Humans OAuth2 projects, go to:
https://www.openhumans.org/direct-sharing/oauth2-features/
:param subj... | [
"def",
"message",
"(",
"subject",
",",
"message",
",",
"access_token",
",",
"all_members",
"=",
"False",
",",
"project_member_ids",
"=",
"None",
",",
"base_url",
"=",
"OH_BASE_URL",
")",
":",
"url",
"=",
"urlparse",
".",
"urljoin",
"(",
"base_url",
",",
"'... | 48.147059 | 0.000599 |
def atlasdb_renew_peer( peer_hostport, now, con=None, path=None ):
"""
Renew a peer's discovery time
"""
with AtlasDBOpen(con=con, path=path) as dbcon:
if now is None:
now = time.time()
sql = "UPDATE peers SET discovery_time = ? WHERE peer_hostport = ?;"
args = (now,... | [
"def",
"atlasdb_renew_peer",
"(",
"peer_hostport",
",",
"now",
",",
"con",
"=",
"None",
",",
"path",
"=",
"None",
")",
":",
"with",
"AtlasDBOpen",
"(",
"con",
"=",
"con",
",",
"path",
"=",
"path",
")",
"as",
"dbcon",
":",
"if",
"now",
"is",
"None",
... | 27.75 | 0.010893 |
def compile(node,
uri,
filename=None,
default_filters=None,
buffer_filters=None,
imports=None,
future_imports=None,
source_encoding=None,
generate_magic_comment=True,
disable_u... | [
"def",
"compile",
"(",
"node",
",",
"uri",
",",
"filename",
"=",
"None",
",",
"default_filters",
"=",
"None",
",",
"buffer_filters",
"=",
"None",
",",
"imports",
"=",
"None",
",",
"future_imports",
"=",
"None",
",",
"source_encoding",
"=",
"None",
",",
"... | 41.162791 | 0.00883 |
def _parse_lines(self, diff_lines):
"""
Given the diff lines output from `git diff` for a particular
source file, return a tuple of `(ADDED_LINES, DELETED_LINES)`
where `ADDED_LINES` and `DELETED_LINES` are lists of line
numbers added/deleted respectively.
Raises a `Git... | [
"def",
"_parse_lines",
"(",
"self",
",",
"diff_lines",
")",
":",
"added_lines",
"=",
"[",
"]",
"deleted_lines",
"=",
"[",
"]",
"current_line_new",
"=",
"None",
"current_line_old",
"=",
"None",
"for",
"line",
"in",
"diff_lines",
":",
"# If this is the start of th... | 35.463768 | 0.000795 |
def _selectedBlockNumbers(self):
"""Return selected block numbers and tuple (startBlockNumber, endBlockNumber)
"""
startBlock, endBlock = self._selectedBlocks()
return startBlock.blockNumber(), endBlock.blockNumber() | [
"def",
"_selectedBlockNumbers",
"(",
"self",
")",
":",
"startBlock",
",",
"endBlock",
"=",
"self",
".",
"_selectedBlocks",
"(",
")",
"return",
"startBlock",
".",
"blockNumber",
"(",
")",
",",
"endBlock",
".",
"blockNumber",
"(",
")"
] | 48.8 | 0.012097 |
def json(self, *, # type: ignore
loads: Callable[[Any], Any]=json.loads) -> None:
"""Return parsed JSON data.
.. versionadded:: 0.22
"""
return loads(self.data) | [
"def",
"json",
"(",
"self",
",",
"*",
",",
"# type: ignore",
"loads",
":",
"Callable",
"[",
"[",
"Any",
"]",
",",
"Any",
"]",
"=",
"json",
".",
"loads",
")",
"->",
"None",
":",
"return",
"loads",
"(",
"self",
".",
"data",
")"
] | 28.714286 | 0.024155 |
def get_cert_contents(kwargs):
"""Builds parameters with server cert file contents.
Args:
kwargs(dict): The keyword args passed to ensure_server_cert_exists,
optionally containing the paths to the cert, key and chain files.
Returns:
dict: A dictionary containing the appropriate... | [
"def",
"get_cert_contents",
"(",
"kwargs",
")",
":",
"paths",
"=",
"{",
"\"certificate\"",
":",
"kwargs",
".",
"get",
"(",
"\"path_to_certificate\"",
")",
",",
"\"private_key\"",
":",
"kwargs",
".",
"get",
"(",
"\"path_to_private_key\"",
")",
",",
"\"chain\"",
... | 29.254902 | 0.000649 |
def read_address(self, ip_address):
'''
a method to retrieve details about an elastic ip address associated with account on AWS
:param ip_address: string with elastic ipv4 address on ec2
:return: dictionary with ip address details
'''
t... | [
"def",
"read_address",
"(",
"self",
",",
"ip_address",
")",
":",
"title",
"=",
"'%s.read_address'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs",
"input_fields",
"=",
"{",
"'ip_address'",
":",
"ip_address",
"}",
"for",
"key",
",",
"value... | 34.282609 | 0.008631 |
def p_expression_eql(self, p):
'expression : expression EQL expression'
p[0] = Eql(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_expression_eql",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Eql",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",... | 41 | 0.011976 |
def _page_to_text(page):
"""Extract the text from a page.
Args:
page: a unicode string
Returns:
a unicode string
"""
# text start tag looks like "<text ..otherstuff>"
start_pos = page.find(u"<text")
assert start_pos != -1
end_tag_pos = page.find(u">", start_pos)
assert end_tag_pos != -1
end... | [
"def",
"_page_to_text",
"(",
"page",
")",
":",
"# text start tag looks like \"<text ..otherstuff>\"",
"start_pos",
"=",
"page",
".",
"find",
"(",
"u\"<text\"",
")",
"assert",
"start_pos",
"!=",
"-",
"1",
"end_tag_pos",
"=",
"page",
".",
"find",
"(",
"u\">\"",
",... | 23.777778 | 0.024719 |
def plot_voight_painting(painting, palette='colorblind', flank='right',
ax=None, height_factor=0.01):
"""Plot a painting of shared haplotype prefixes.
Parameters
----------
painting : array_like, int, shape (n_variants, n_haplotypes)
Painting array.
ax : axes, optio... | [
"def",
"plot_voight_painting",
"(",
"painting",
",",
"palette",
"=",
"'colorblind'",
",",
"flank",
"=",
"'right'",
",",
"ax",
"=",
"None",
",",
"height_factor",
"=",
"0.01",
")",
":",
"import",
"seaborn",
"as",
"sns",
"from",
"matplotlib",
".",
"colors",
"... | 28.901961 | 0.000656 |
def sentence2freqt(docgraph, root, successors=None, include_pos=False,
escape_func=FREQT_ESCAPE_FUNC):
"""convert a sentence subgraph into a FREQT string."""
if successors is None:
successors = sorted_bfs_successors(docgraph, root)
if root in successors: # root node has children... | [
"def",
"sentence2freqt",
"(",
"docgraph",
",",
"root",
",",
"successors",
"=",
"None",
",",
"include_pos",
"=",
"False",
",",
"escape_func",
"=",
"FREQT_ESCAPE_FUNC",
")",
":",
"if",
"successors",
"is",
"None",
":",
"successors",
"=",
"sorted_bfs_successors",
... | 52 | 0.001111 |
def ascolumn(x, dtype = None):
'''Convert ``x`` into a ``column``-type ``numpy.ndarray``.'''
x = asarray(x, dtype)
return x if len(x.shape) >= 2 else x.reshape(len(x),1) | [
"def",
"ascolumn",
"(",
"x",
",",
"dtype",
"=",
"None",
")",
":",
"x",
"=",
"asarray",
"(",
"x",
",",
"dtype",
")",
"return",
"x",
"if",
"len",
"(",
"x",
".",
"shape",
")",
">=",
"2",
"else",
"x",
".",
"reshape",
"(",
"len",
"(",
"x",
")",
... | 45.25 | 0.021739 |
def draw_pdf(f, arg, bound, bins=100, scale=1.0, density=True,
normed_pdf=False, ax=None, **kwds):
"""
draw pdf with given argument and bounds.
**Arguments**
* **f** your pdf. The first argument is assumed to be independent
variable
* **arg** argument can be tuple o... | [
"def",
"draw_pdf",
"(",
"f",
",",
"arg",
",",
"bound",
",",
"bins",
"=",
"100",
",",
"scale",
"=",
"1.0",
",",
"density",
"=",
"True",
",",
"normed_pdf",
"=",
"False",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"edges",
"=",
"np",... | 30.1875 | 0.002006 |
def function(self,p):
"""
Return a square-wave grating (alternating black and white bars).
"""
return np.around(
0.5 +
0.5*np.sin(pi*(p.duty_cycle-0.5)) +
0.5*np.sin(p.frequency*2*pi*self.pattern_y + p.phase)) | [
"def",
"function",
"(",
"self",
",",
"p",
")",
":",
"return",
"np",
".",
"around",
"(",
"0.5",
"+",
"0.5",
"*",
"np",
".",
"sin",
"(",
"pi",
"*",
"(",
"p",
".",
"duty_cycle",
"-",
"0.5",
")",
")",
"+",
"0.5",
"*",
"np",
".",
"sin",
"(",
"p"... | 33.75 | 0.01083 |
def get_repos(self):
"""
:calls: `GET /teams/:id/repos <http://developer.github.com/v3/orgs/teams>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Repository.Repository`
"""
return github.PaginatedList.PaginatedList(
github.Repository.Repositor... | [
"def",
"get_repos",
"(",
"self",
")",
":",
"return",
"github",
".",
"PaginatedList",
".",
"PaginatedList",
"(",
"github",
".",
"Repository",
".",
"Repository",
",",
"self",
".",
"_requester",
",",
"self",
".",
"url",
"+",
"\"/repos\"",
",",
"None",
")"
] | 36.454545 | 0.009732 |
def delete_user(iam_client, user, mfa_serial = None, keep_user = False, terminated_groups = []):
"""
Delete IAM user
:param iam_client:
:param user:
:param mfa_serial:
:param keep_user:
:param terminated_groups:
:return:
"""
errors = []
printInfo('Deleting user %s...' % user... | [
"def",
"delete_user",
"(",
"iam_client",
",",
"user",
",",
"mfa_serial",
"=",
"None",
",",
"keep_user",
"=",
"False",
",",
"terminated_groups",
"=",
"[",
"]",
")",
":",
"errors",
"=",
"[",
"]",
"printInfo",
"(",
"'Deleting user %s...'",
"%",
"user",
")",
... | 38.321739 | 0.011281 |
def in6_ifaceidtomac(ifaceid): # TODO: finish commenting function behavior
"""
Extract the mac address from provided iface ID. Iface ID is provided
in printable format ("XXXX:XXFF:FEXX:XXXX", eventually compressed). None
is returned on error.
"""
try:
ifaceid = inet_pton(socket.AF_INET... | [
"def",
"in6_ifaceidtomac",
"(",
"ifaceid",
")",
":",
"# TODO: finish commenting function behavior",
"try",
":",
"ifaceid",
"=",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"\"::\"",
"+",
"ifaceid",
")",
"[",
"8",
":",
"16",
"]",
"except",
":",
"return",
... | 37.55 | 0.011688 |
def _deactivate(self):
"""Remove the fetcher from cache and mark it not active."""
self.cache.remove_fetcher(self)
if self.active:
self._deactivated() | [
"def",
"_deactivate",
"(",
"self",
")",
":",
"self",
".",
"cache",
".",
"remove_fetcher",
"(",
"self",
")",
"if",
"self",
".",
"active",
":",
"self",
".",
"_deactivated",
"(",
")"
] | 36.4 | 0.010753 |
def add_nic(self, instance_id, net_id):
"""Add a Network Interface Controller"""
#TODO: upgrade with port_id and fixed_ip in future
self.client.servers.interface_attach(
instance_id, None, net_id, None)
return True | [
"def",
"add_nic",
"(",
"self",
",",
"instance_id",
",",
"net_id",
")",
":",
"#TODO: upgrade with port_id and fixed_ip in future",
"self",
".",
"client",
".",
"servers",
".",
"interface_attach",
"(",
"instance_id",
",",
"None",
",",
"net_id",
",",
"None",
")",
"r... | 42.166667 | 0.011628 |
def update(self, content):
"""Enumerates the bytes of the supplied bytearray and updates the CRC-64.
No return value.
"""
for byte in content:
self._crc64 = (self._crc64 >> 8) ^ self._lookup_table[(self._crc64 & 0xff) ^ byte] | [
"def",
"update",
"(",
"self",
",",
"content",
")",
":",
"for",
"byte",
"in",
"content",
":",
"self",
".",
"_crc64",
"=",
"(",
"self",
".",
"_crc64",
">>",
"8",
")",
"^",
"self",
".",
"_lookup_table",
"[",
"(",
"self",
".",
"_crc64",
"&",
"0xff",
... | 38.142857 | 0.014652 |
def removeHtmlTags(self, text):
"""convert bad tags into HTML identities"""
sb = []
text = self.removeHtmlComments(text)
bits = text.split(u'<')
sb.append(bits.pop(0))
tagstack = []
tablestack = tagstack
for x in bits:
m = _tagPattern.match(x)
if not m:
continue
slash, t, params, brace, res... | [
"def",
"removeHtmlTags",
"(",
"self",
",",
"text",
")",
":",
"sb",
"=",
"[",
"]",
"text",
"=",
"self",
".",
"removeHtmlComments",
"(",
"text",
")",
"bits",
"=",
"text",
".",
"split",
"(",
"u'<'",
")",
"sb",
".",
"append",
"(",
"bits",
".",
"pop",
... | 25.673267 | 0.037133 |
def create_widget(self):
""" Create the underlying widget.
"""
d = self.declaration
self.widget = RelativeLayout(self.get_context(), None, d.style) | [
"def",
"create_widget",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"declaration",
"self",
".",
"widget",
"=",
"RelativeLayout",
"(",
"self",
".",
"get_context",
"(",
")",
",",
"None",
",",
"d",
".",
"style",
")"
] | 29.166667 | 0.011111 |
def MAPGenoToTrans(parsedGTF,feature):
"""
Gets all positions of all bases in an exon
:param df: a Pandas dataframe with 'start','end', and 'strand' information for each entry.
df must contain 'seqname','feature','start','end','strand','frame','gene_id',
'transcript_id','exo... | [
"def",
"MAPGenoToTrans",
"(",
"parsedGTF",
",",
"feature",
")",
":",
"GenTransMap",
"=",
"parsedGTF",
"[",
"parsedGTF",
"[",
"\"feature\"",
"]",
"==",
"feature",
"]",
"def",
"getExonsPositions",
"(",
"df",
")",
":",
"start",
"=",
"int",
"(",
"df",
"[",
"... | 41.4 | 0.02439 |
def setHint(self, text):
"""
Sets the hint to the inputed text. The same hint will be used for
all editors in this widget.
:param text | <str>
"""
texts = nativestring(text).split(' ')
for i, text in enumerate(texts):
... | [
"def",
"setHint",
"(",
"self",
",",
"text",
")",
":",
"texts",
"=",
"nativestring",
"(",
"text",
")",
".",
"split",
"(",
"' '",
")",
"for",
"i",
",",
"text",
"in",
"enumerate",
"(",
"texts",
")",
":",
"editor",
"=",
"self",
".",
"editorAt",
"(",
... | 28.733333 | 0.011236 |
def galprop_ringkey(self, **kwargs):
""" return the sourcekey for galprop input maps : specifies the component and ring
"""
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
self._replace_none(kwargs_copy)
try:
return NameFactory.galprop... | [
"def",
"galprop_ringkey",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs_copy",
"=",
"self",
".",
"base_dict",
".",
"copy",
"(",
")",
"kwargs_copy",
".",
"update",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"_replace_none",
"(",
"kwargs_copy",
... | 39.7 | 0.009852 |
def call_method(self, method):
"""
Calls a blocking method in an executor, in order to preserve the non-blocking behaviour
If ``method`` is a coroutine, yields from it and returns, no need to execute in
in an executor.
:param method: The method or coroutine to be called (with n... | [
"def",
"call_method",
"(",
"self",
",",
"method",
")",
":",
"if",
"self",
".",
"_method_is_async_generator",
"(",
"method",
")",
":",
"result",
"=",
"yield",
"method",
"(",
")",
"else",
":",
"result",
"=",
"yield",
"self",
".",
"executor",
".",
"submit",... | 37.2 | 0.008741 |
def verify_callable_argspec(callable_,
expected_args=Argument.ignore,
expect_starargs=Argument.ignore,
expect_kwargs=Argument.ignore):
"""
Checks the callable_ to make sure that it satisfies the given
expectations.
expec... | [
"def",
"verify_callable_argspec",
"(",
"callable_",
",",
"expected_args",
"=",
"Argument",
".",
"ignore",
",",
"expect_starargs",
"=",
"Argument",
".",
"ignore",
",",
"expect_kwargs",
"=",
"Argument",
".",
"ignore",
")",
":",
"if",
"not",
"callable",
"(",
"cal... | 29.8125 | 0.000406 |
def AddStatEntry(self, stat_entry, timestamp):
"""Registers stat entry at a given timestamp."""
if timestamp in self._stat_entries:
message = ("Duplicated stat entry write for path '%s' of type '%s' at "
"timestamp '%s'. Old: %s. New: %s.")
message %= ("/".join(self._components), s... | [
"def",
"AddStatEntry",
"(",
"self",
",",
"stat_entry",
",",
"timestamp",
")",
":",
"if",
"timestamp",
"in",
"self",
".",
"_stat_entries",
":",
"message",
"=",
"(",
"\"Duplicated stat entry write for path '%s' of type '%s' at \"",
"\"timestamp '%s'. Old: %s. New: %s.\"",
"... | 39.157895 | 0.009186 |
def init_model_based_tags(self, model):
"""Initializing the model based memory and NIC information tags.
It should be called just after instantiating a RIBCL object.
ribcl = ribcl.RIBCLOperations(host, login, password, timeout,
port, cacert=cacert... | [
"def",
"init_model_based_tags",
"(",
"self",
",",
"model",
")",
":",
"self",
".",
"model",
"=",
"model",
"if",
"'G7'",
"in",
"self",
".",
"model",
":",
"self",
".",
"MEMORY_SIZE_TAG",
"=",
"\"MEMORY_SIZE\"",
"self",
".",
"MEMORY_SIZE_NOT_PRESENT_TAG",
"=",
"... | 39.913043 | 0.002128 |
def get_widget(self, page, language, fallback=Textarea):
"""Given the name of a placeholder return a `Widget` subclass
like Textarea or TextInput."""
import sys
PY3 = sys.version > '3'
is_string = type(self.widget) == type(str())
if not PY3:
is_string = type(s... | [
"def",
"get_widget",
"(",
"self",
",",
"page",
",",
"language",
",",
"fallback",
"=",
"Textarea",
")",
":",
"import",
"sys",
"PY3",
"=",
"sys",
".",
"version",
">",
"'3'",
"is_string",
"=",
"type",
"(",
"self",
".",
"widget",
")",
"==",
"type",
"(",
... | 35.882353 | 0.009585 |
def approved_funds(pronac, dt):
"""
Verifica se o valor total de um projeto é um
outlier em relação
aos projetos do mesmo seguimento cultural
Dataframes: planilha_orcamentaria
"""
funds_df = data.approved_funds_by_projects
project = (
funds_df
.loc[funds_df['PRONAC'] == ... | [
"def",
"approved_funds",
"(",
"pronac",
",",
"dt",
")",
":",
"funds_df",
"=",
"data",
".",
"approved_funds_by_projects",
"project",
"=",
"(",
"funds_df",
".",
"loc",
"[",
"funds_df",
"[",
"'PRONAC'",
"]",
"==",
"pronac",
"]",
")",
"project",
"=",
"project"... | 27.935484 | 0.001116 |
def read_namespaced_job_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_job_status # noqa: E501
read status of the specified Job # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=... | [
"def",
"read_namespaced_job_status",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return... | 50.086957 | 0.001704 |
def snippet(code, locations, sep=' | ', colmark=('-', '^'), context=5):
'''Given a code and list of locations, convert to snippet lines.
return will include line number, a separator (``sep``), then
line contents.
At most ``context`` lines are shown before each location line.
A... | [
"def",
"snippet",
"(",
"code",
",",
"locations",
",",
"sep",
"=",
"' | '",
",",
"colmark",
"=",
"(",
"'-'",
",",
"'^'",
")",
",",
"context",
"=",
"5",
")",
":",
"if",
"not",
"locations",
":",
"return",
"[",
"]",
"lines",
"=",
"code",
".",
"split"... | 40.129032 | 0.00157 |
def unregisterThread(self, name):
"""
Unregister the Thread registered under the given name.
Make sure that the given Thread is properly stopped, or that a reference is
kept in another place. Once unregistered, this class will not keep any
other references to the Thread.
Parameters
----------
name: st... | [
"def",
"unregisterThread",
"(",
"self",
",",
"name",
")",
":",
"if",
"not",
"name",
"in",
"self",
".",
"thread_list",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Thread {0} is not registered!\"",
".",
"format",
"(",
"name",
")",
")",
"raise",
"Except... | 31.842105 | 0.028892 |
def _determine_function_name_type(node, config=None):
"""Determine the name type whose regex the a function's name should match.
:param node: A function node.
:type node: astroid.node_classes.NodeNG
:param config: Configuration from which to pull additional property classes.
:type config: :class:`o... | [
"def",
"_determine_function_name_type",
"(",
"node",
",",
"config",
"=",
"None",
")",
":",
"property_classes",
",",
"property_names",
"=",
"_get_properties",
"(",
"config",
")",
"if",
"not",
"node",
".",
"is_method",
"(",
")",
":",
"return",
"\"function\"",
"i... | 38.416667 | 0.002116 |
def _get_frag_constr_table(self, start_atom=None, predefined_table=None,
use_lookup=None, bond_dict=None):
"""Create a construction table for a Zmatrix.
A construction table is basically a Zmatrix without the values
for the bond lenghts, angles and dihedrals.
... | [
"def",
"_get_frag_constr_table",
"(",
"self",
",",
"start_atom",
"=",
"None",
",",
"predefined_table",
"=",
"None",
",",
"use_lookup",
"=",
"None",
",",
"bond_dict",
"=",
"None",
")",
":",
"if",
"use_lookup",
"is",
"None",
":",
"use_lookup",
"=",
"settings",... | 44.271429 | 0.000473 |
def fix(args):
"""
%prog fix bedfile > newbedfile
Fix non-standard bed files. One typical problem is start > end.
"""
p = OptionParser(fix.__doc__)
p.add_option("--minspan", default=0, type="int",
help="Enforce minimum span [default: %default]")
p.set_outfile()
opts, ar... | [
"def",
"fix",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"fix",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--minspan\"",
",",
"default",
"=",
"0",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Enforce minimum span [default: %defaul... | 27.893617 | 0.001474 |
def cooccurrence(quantized_image, labels, scale_i=3, scale_j=0):
"""Calculates co-occurrence matrices for all the objects in the image.
Return an array P of shape (nobjects, nlevels, nlevels) such that
P[o, :, :] is the cooccurence matrix for object o.
quantized_image -- a numpy array of integer type
... | [
"def",
"cooccurrence",
"(",
"quantized_image",
",",
"labels",
",",
"scale_i",
"=",
"3",
",",
"scale_j",
"=",
"0",
")",
":",
"labels",
"=",
"labels",
".",
"astype",
"(",
"int",
")",
"nlevels",
"=",
"quantized_image",
".",
"max",
"(",
")",
"+",
"1",
"n... | 44.311475 | 0.002172 |
def _skw_matches_comparator(kw0, kw1):
"""Compare 2 single keywords objects.
First by the number of their spans (ie. how many times they were found),
if it is equal it compares them by lenghts of their labels.
"""
def compare(a, b):
return (a > b) - (a < b)
list_comparison = compare(le... | [
"def",
"_skw_matches_comparator",
"(",
"kw0",
",",
"kw1",
")",
":",
"def",
"compare",
"(",
"a",
",",
"b",
")",
":",
"return",
"(",
"a",
">",
"b",
")",
"-",
"(",
"a",
"<",
"b",
")",
"list_comparison",
"=",
"compare",
"(",
"len",
"(",
"kw1",
"[",
... | 35.857143 | 0.001294 |
def num_orifices(FlowPlant, RatioVCOrifice, HeadLossOrifice, DiamOrifice):
"""Return the number of orifices."""
#Inputs do not need to be checked here because they are checked by
#functions this function calls.
return np.ceil(area_orifice(HeadLossOrifice, RatioVCOrifice,
... | [
"def",
"num_orifices",
"(",
"FlowPlant",
",",
"RatioVCOrifice",
",",
"HeadLossOrifice",
",",
"DiamOrifice",
")",
":",
"#Inputs do not need to be checked here because they are checked by",
"#functions this function calls.",
"return",
"np",
".",
"ceil",
"(",
"area_orifice",
"("... | 56.142857 | 0.012531 |
def fetch(args):
"""
%prog fetch "query"
OR
%prog fetch queries.txt
Please provide a UniProt compatible `query` to retrieve data. If `query` contains
spaces, please remember to "quote" it.
You can also specify a `filename` which contains queries, one per line.
Follow this syntax <... | [
"def",
"fetch",
"(",
"args",
")",
":",
"import",
"re",
"import",
"csv",
"p",
"=",
"OptionParser",
"(",
"fetch",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--format\"",
",",
"default",
"=",
"\"tab\"",
",",
"choices",
"=",
"valid_formats",
",",
... | 34.679245 | 0.002116 |
def _generateModel1(numCategories):
""" Generate the initial, first order, and second order transition
probabilities for 'model1'. For this model, we generate the following
set of sequences:
0-10-15 (1X)
0-11-16 (1X)
0-12-17 (1X)
0-13-18 (1X)
0-14-19 (1X)
1-10-20 (1X)
1-11-21 (1X)
1-12-22 (1X)... | [
"def",
"_generateModel1",
"(",
"numCategories",
")",
":",
"# --------------------------------------------------------------------",
"# Initial probabilities, 0 and 1 equally likely",
"initProb",
"=",
"numpy",
".",
"zeros",
"(",
"numCategories",
")",
"initProb",
"[",
"0",
"]",
... | 32.184 | 0.018327 |
def _len_lcs(x, y):
"""Returns the length of the Longest Common Subsequence between two seqs.
Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence
Args:
x: sequence of words
y: sequence of words
Returns
integer: Length of LCS between x and y
"""
table = _lcs(x, y)
n, m =... | [
"def",
"_len_lcs",
"(",
"x",
",",
"y",
")",
":",
"table",
"=",
"_lcs",
"(",
"x",
",",
"y",
")",
"n",
",",
"m",
"=",
"len",
"(",
"x",
")",
",",
"len",
"(",
"y",
")",
"return",
"table",
"[",
"n",
",",
"m",
"]"
] | 22.8 | 0.014045 |
def make_context_aware(func, numargs):
"""
Check if given function has no more arguments than given. If so, wrap it
into another function that takes extra argument and drops it.
Used to support user providing callback functions that are not context aware.
"""
try:
if inspect.ismethod(fun... | [
"def",
"make_context_aware",
"(",
"func",
",",
"numargs",
")",
":",
"try",
":",
"if",
"inspect",
".",
"ismethod",
"(",
"func",
")",
":",
"arg_count",
"=",
"len",
"(",
"inspect",
".",
"getargspec",
"(",
"func",
")",
".",
"args",
")",
"-",
"1",
"elif",... | 33.8 | 0.002301 |
def _function_header(subpackage, func):
"""Generate the docstring of a function."""
args = inspect.formatargspec(*inspect.getfullargspec(func))
return "{name}{args}".format(name=_full_name(subpackage, func),
args=args,
) | [
"def",
"_function_header",
"(",
"subpackage",
",",
"func",
")",
":",
"args",
"=",
"inspect",
".",
"formatargspec",
"(",
"*",
"inspect",
".",
"getfullargspec",
"(",
"func",
")",
")",
"return",
"\"{name}{args}\"",
".",
"format",
"(",
"name",
"=",
"_full_name",... | 49.5 | 0.009934 |
def find_all_files(self):
"""
Find files including those in subrepositories.
"""
files = self.find_files()
subrepo_files = (
posixpath.join(subrepo.location, filename)
for subrepo in self.subrepos()
for filename in subrepo.find_files()
)
return itertools.chain(files, subrepo_files) | [
"def",
"find_all_files",
"(",
"self",
")",
":",
"files",
"=",
"self",
".",
"find_files",
"(",
")",
"subrepo_files",
"=",
"(",
"posixpath",
".",
"join",
"(",
"subrepo",
".",
"location",
",",
"filename",
")",
"for",
"subrepo",
"in",
"self",
".",
"subrepos"... | 26.818182 | 0.039344 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.