text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def search_reference_sets(
self, accession=None, md5checksum=None, assembly_id=None):
"""
Returns an iterator over the ReferenceSets fulfilling the specified
conditions.
:param str accession: If not null, return the reference sets for which
the `accession` matche... | [
"def",
"search_reference_sets",
"(",
"self",
",",
"accession",
"=",
"None",
",",
"md5checksum",
"=",
"None",
",",
"assembly_id",
"=",
"None",
")",
":",
"request",
"=",
"protocol",
".",
"SearchReferenceSetsRequest",
"(",
")",
"request",
".",
"accession",
"=",
... | 51.48 | 0.001526 |
def _get_action(trans):
"""
Return the action inferred from the transformation `trans`.
and the parameter going with this action
An _Action.ADD_MARK goes with a Mark
while an _Action.ADD_ACCENT goes with an Accent
"""
# TODO: VIQR-like convention
mark_action = {
'^': (_Action.ADD... | [
"def",
"_get_action",
"(",
"trans",
")",
":",
"# TODO: VIQR-like convention",
"mark_action",
"=",
"{",
"'^'",
":",
"(",
"_Action",
".",
"ADD_MARK",
",",
"Mark",
".",
"HAT",
")",
",",
"'+'",
":",
"(",
"_Action",
".",
"ADD_MARK",
",",
"Mark",
".",
"BREVE",... | 31.096774 | 0.001006 |
def get_wildcard_mimetype(self):
""" Returns the mimetype if the client sends */* """
mimetype = self.wildcard_mimetype
if mimetype is None: # class inherits from module default
mimetype = WILDCARD_MIMETYPE
if mimetype is None: # module is set to None?
mimetype = 'application/rdf+xml'
return mimetype | [
"def",
"get_wildcard_mimetype",
"(",
"self",
")",
":",
"mimetype",
"=",
"self",
".",
"wildcard_mimetype",
"if",
"mimetype",
"is",
"None",
":",
"# class inherits from module default",
"mimetype",
"=",
"WILDCARD_MIMETYPE",
"if",
"mimetype",
"is",
"None",
":",
"# modul... | 38.75 | 0.0347 |
def get(package_str, classname):
'''Retrieve from the internal cache a class instance. All arguments are case-insensitive'''
if (package_str in _dynamo_cache) and (classname in _dynamo_cache[package_str]):
return _dynamo_cache[package_str][classname]
return None | [
"def",
"get",
"(",
"package_str",
",",
"classname",
")",
":",
"if",
"(",
"package_str",
"in",
"_dynamo_cache",
")",
"and",
"(",
"classname",
"in",
"_dynamo_cache",
"[",
"package_str",
"]",
")",
":",
"return",
"_dynamo_cache",
"[",
"package_str",
"]",
"[",
... | 55.8 | 0.014134 |
def _nemo_accpars(self,vo,ro):
"""
NAME:
_nemo_accpars
PURPOSE:
return the accpars potential parameters for use of this potential with NEMO
INPUT:
vo - velocity unit in km/s
ro - length unit in kpc
OUTPUT:
accpars str... | [
"def",
"_nemo_accpars",
"(",
"self",
",",
"vo",
",",
"ro",
")",
":",
"warnings",
".",
"warn",
"(",
"\"NEMO's LogPot does not allow flattening in z (for some reason); therefore, flip y and z in NEMO wrt galpy; also does not allow the triaxial b parameter\"",
",",
"galpyWarning",
")"... | 26.266667 | 0.015912 |
def replace_activations(self, linked_stmts=None):
"""Remove RegulateActivity Statements that can be inferred out.
This function iterates over self.statements and looks for
RegulateActivity Statements that either match or are refined by
inferred RegulateActivity Statements that were link... | [
"def",
"replace_activations",
"(",
"self",
",",
"linked_stmts",
"=",
"None",
")",
":",
"if",
"linked_stmts",
"is",
"None",
":",
"linked_stmts",
"=",
"self",
".",
"infer_activations",
"(",
"self",
".",
"statements",
")",
"new_stmts",
"=",
"[",
"]",
"for",
"... | 45.894737 | 0.002246 |
def delta_hv(scatterer):
"""
Delta_hv for the current setup.
Args:
scatterer: a Scatterer instance.
Returns:
Delta_hv [rad].
"""
Z = scatterer.get_Z()
return np.arctan2(Z[2,3] - Z[3,2], -Z[2,2] - Z[3,3]) | [
"def",
"delta_hv",
"(",
"scatterer",
")",
":",
"Z",
"=",
"scatterer",
".",
"get_Z",
"(",
")",
"return",
"np",
".",
"arctan2",
"(",
"Z",
"[",
"2",
",",
"3",
"]",
"-",
"Z",
"[",
"3",
",",
"2",
"]",
",",
"-",
"Z",
"[",
"2",
",",
"2",
"]",
"-... | 19.833333 | 0.02008 |
def Left(self, n = 1, dl = 0):
"""左方向键n次
"""
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.left_key, n) | [
"def",
"Left",
"(",
"self",
",",
"n",
"=",
"1",
",",
"dl",
"=",
"0",
")",
":",
"self",
".",
"Delay",
"(",
"dl",
")",
"self",
".",
"keyboard",
".",
"tap_key",
"(",
"self",
".",
"keyboard",
".",
"left_key",
",",
"n",
")"
] | 27.2 | 0.042857 |
def offset(self, offset):
"""
Apply an OFFSET to the query and return the newly resulting Query.
"""
query = self._copy()
query._offset = offset
return query | [
"def",
"offset",
"(",
"self",
",",
"offset",
")",
":",
"query",
"=",
"self",
".",
"_copy",
"(",
")",
"query",
".",
"_offset",
"=",
"offset",
"return",
"query"
] | 28.428571 | 0.009756 |
def coPrime(l):
"""returns 'True' if the values in the list L are all co-prime
otherwise, it returns 'False'. """
for i, j in combinations(l, 2):
if euclid(i, j) != 1:
return False
return True | [
"def",
"coPrime",
"(",
"l",
")",
":",
"for",
"i",
",",
"j",
"in",
"combinations",
"(",
"l",
",",
"2",
")",
":",
"if",
"euclid",
"(",
"i",
",",
"j",
")",
"!=",
"1",
":",
"return",
"False",
"return",
"True"
] | 32.142857 | 0.008658 |
def build_import_keychain( cls, keychain_dir, namespace_id, pubkey_hex ):
"""
Generate all possible NAME_IMPORT addresses from the NAMESPACE_REVEAL public key
"""
pubkey_addr = virtualchain.BitcoinPublicKey(str(pubkey_hex)).address()
# do we have a cached one on disk?
c... | [
"def",
"build_import_keychain",
"(",
"cls",
",",
"keychain_dir",
",",
"namespace_id",
",",
"pubkey_hex",
")",
":",
"pubkey_addr",
"=",
"virtualchain",
".",
"BitcoinPublicKey",
"(",
"str",
"(",
"pubkey_hex",
")",
")",
".",
"address",
"(",
")",
"# do we have a cac... | 35.9375 | 0.01058 |
def expose(template=None,
generic=False,
route=None,
**kw):
'''
Decorator used to flag controller methods as being "exposed" for
access via HTTP, and to configure that access.
:param template: The path to a template, relative to the base template
d... | [
"def",
"expose",
"(",
"template",
"=",
"None",
",",
"generic",
"=",
"False",
",",
"route",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"content_type",
"=",
"kw",
".",
"get",
"(",
"'content_type'",
",",
"'text/html'",
")",
"if",
"template",
"==",
"'js... | 37.422535 | 0.000367 |
def is_coord_subset_pbc(subset, superset, atol=1e-8, mask=None):
"""
Tests if all fractional coords in subset are contained in superset.
Args:
subset, superset: List of fractional coords
atol (float or size 3 array): Tolerance for matching
mask (boolean array): Mask of matches that ... | [
"def",
"is_coord_subset_pbc",
"(",
"subset",
",",
"superset",
",",
"atol",
"=",
"1e-8",
",",
"mask",
"=",
"None",
")",
":",
"c1",
"=",
"np",
".",
"array",
"(",
"subset",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"c2",
"=",
"np",
".",
"array",
... | 36.954545 | 0.001199 |
def get_period_starters(df):
"""TODO
"""
def players_from_play(play):
"""Figures out what players are in the game based on the players
mentioned in a play. Returns away and home players as two sets.
:param play: A dictionary representing a parsed play.
:returns: (aw_players... | [
"def",
"get_period_starters",
"(",
"df",
")",
":",
"def",
"players_from_play",
"(",
"play",
")",
":",
"\"\"\"Figures out what players are in the game based on the players\n mentioned in a play. Returns away and home players as two sets.\n\n :param play: A dictionary representin... | 42.676471 | 0.000337 |
def size_attachments(self):
"""returns the number of bytes that the cleansed attachments take up on disk"""
total_size = 0
for attachment in self.fs_cleansed_attachments:
total_size += stat(attachment).st_size
return total_size | [
"def",
"size_attachments",
"(",
"self",
")",
":",
"total_size",
"=",
"0",
"for",
"attachment",
"in",
"self",
".",
"fs_cleansed_attachments",
":",
"total_size",
"+=",
"stat",
"(",
"attachment",
")",
".",
"st_size",
"return",
"total_size"
] | 45 | 0.014545 |
def convert_argmax(node, **kwargs):
"""Map MXNet's argmax operator attributes to onnx's ArgMax operator
and return the created node.
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
axis = int(attrs.get("axis"))
keepdims = get_boolean_attribute_value(attrs, "keepdims")
node = onnx.h... | [
"def",
"convert_argmax",
"(",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"name",
",",
"input_nodes",
",",
"attrs",
"=",
"get_inputs",
"(",
"node",
",",
"kwargs",
")",
"axis",
"=",
"int",
"(",
"attrs",
".",
"get",
"(",
"\"axis\"",
")",
")",
"keepdims"... | 26.5 | 0.002024 |
def to_numpy(X):
"""Generic function to convert a pytorch tensor to numpy.
Returns X when it already is a numpy array.
"""
if isinstance(X, np.ndarray):
return X
if is_pandas_ndframe(X):
return X.values
if not is_torch_data_type(X):
raise TypeError("Cannot convert thi... | [
"def",
"to_numpy",
"(",
"X",
")",
":",
"if",
"isinstance",
"(",
"X",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"X",
"if",
"is_pandas_ndframe",
"(",
"X",
")",
":",
"return",
"X",
".",
"values",
"if",
"not",
"is_torch_data_type",
"(",
"X",
")",
... | 19.954545 | 0.002174 |
def Git(repository, directory, rev=None, prefix=None, shallow_clone=True):
"""
Get a clone of the given repo
Args:
repository (str): Git URL of the SOURCE repo.
directory (str): Name of the repo folder on disk.
tgt_root (str): TARGET folder for the git repo.
Defaults to ... | [
"def",
"Git",
"(",
"repository",
",",
"directory",
",",
"rev",
"=",
"None",
",",
"prefix",
"=",
"None",
",",
"shallow_clone",
"=",
"True",
")",
":",
"repository_loc",
"=",
"str",
"(",
"prefix",
")",
"if",
"prefix",
"is",
"None",
":",
"repository_loc",
... | 27.722222 | 0.000968 |
def to_packets(pages, strict=False):
"""Construct a list of packet data from a list of Ogg pages.
If strict is true, the first page must start a new packet,
and the last page must end the last packet.
"""
serial = pages[0].serial
sequence = pages[0].sequence
pac... | [
"def",
"to_packets",
"(",
"pages",
",",
"strict",
"=",
"False",
")",
":",
"serial",
"=",
"pages",
"[",
"0",
"]",
".",
"serial",
"sequence",
"=",
"pages",
"[",
"0",
"]",
".",
"sequence",
"packets",
"=",
"[",
"]",
"if",
"strict",
":",
"if",
"pages",
... | 33.823529 | 0.001691 |
def name_usage(key = None, name = None, data = 'all', language = None,
datasetKey = None, uuid = None, sourceId = None, rank = None, shortname = None,
limit = 100, offset = None, **kwargs):
'''
Lookup details for specific names in all taxonomies in GBIF.
:param key: [fixnum] A GBIF key for a taxon
:param name: [... | [
"def",
"name_usage",
"(",
"key",
"=",
"None",
",",
"name",
"=",
"None",
",",
"data",
"=",
"'all'",
",",
"language",
"=",
"None",
",",
"datasetKey",
"=",
"None",
",",
"uuid",
"=",
"None",
",",
"sourceId",
"=",
"None",
",",
"rank",
"=",
"None",
",",
... | 46.027027 | 0.028744 |
def getObjectsInHouse(self, house):
""" Returns a list with all objects in a house. """
res = [obj for obj in self if house.hasObject(obj)]
return ObjectList(res) | [
"def",
"getObjectsInHouse",
"(",
"self",
",",
"house",
")",
":",
"res",
"=",
"[",
"obj",
"for",
"obj",
"in",
"self",
"if",
"house",
".",
"hasObject",
"(",
"obj",
")",
"]",
"return",
"ObjectList",
"(",
"res",
")"
] | 45.75 | 0.010753 |
def parse_hosted_zone(e_zone, connection):
"""
This a common parser that allows the passing of any valid HostedZone
tag. It will spit out the appropriate HostedZone object for the tag.
:param lxml.etree._Element e_zone: The root node of the etree parsed
response from the API.
:param Route53... | [
"def",
"parse_hosted_zone",
"(",
"e_zone",
",",
"connection",
")",
":",
"# This dict will be used to instantiate a HostedZone instance to yield.",
"kwargs",
"=",
"{",
"}",
"# Within HostedZone tags are a number of sub-tags that include info",
"# about the instance.",
"for",
"e_field"... | 38.820513 | 0.001289 |
def _get_adaptation_matrix(wp_src, wp_dst, observer, adaptation):
"""
Calculate the correct transformation matrix based on origin and target
illuminants. The observer angle must be the same between illuminants.
See colormath.color_constants.ADAPTATION_MATRICES for a list of possible
adaptations.
... | [
"def",
"_get_adaptation_matrix",
"(",
"wp_src",
",",
"wp_dst",
",",
"observer",
",",
"adaptation",
")",
":",
"# Get the appropriate transformation matrix, [MsubA].",
"m_sharp",
"=",
"color_constants",
".",
"ADAPTATION_MATRICES",
"[",
"adaptation",
"]",
"# In case the white-... | 34.871795 | 0.000715 |
def get_image(self, float_key="floats", to_chw=True):
"""
get image list from ImageFrame
"""
tensors = callBigDlFunc(self.bigdl_type,
"localImageFrameToImageTensor", self.value, float_key, to_chw)
return map(lambda tensor: tensor.to_ndarray(), t... | [
"def",
"get_image",
"(",
"self",
",",
"float_key",
"=",
"\"floats\"",
",",
"to_chw",
"=",
"True",
")",
":",
"tensors",
"=",
"callBigDlFunc",
"(",
"self",
".",
"bigdl_type",
",",
"\"localImageFrameToImageTensor\"",
",",
"self",
".",
"value",
",",
"float_key",
... | 45.857143 | 0.012232 |
def delete_publication(self, pub_id, schema='upload'):
""" Delete dataset from upload schema"""
if schema == 'upload':
user = 'upload_admin'
elif schema == 'public':
user = 'catroot'
if not self.user == 'catroot':
assert self.user == user, \
... | [
"def",
"delete_publication",
"(",
"self",
",",
"pub_id",
",",
"schema",
"=",
"'upload'",
")",
":",
"if",
"schema",
"==",
"'upload'",
":",
"user",
"=",
"'upload_admin'",
"elif",
"schema",
"==",
"'public'",
":",
"user",
"=",
"'catroot'",
"if",
"not",
"self",... | 33.75 | 0.0012 |
def delete(name, remove=False, force=False):
'''
Remove a user from the minion
CLI Example:
.. code-block:: bash
salt '*' user.delete name remove=True force=True
'''
if salt.utils.data.is_true(force):
log.warning(
'userdel does not support force-deleting user while... | [
"def",
"delete",
"(",
"name",
",",
"remove",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"salt",
".",
"utils",
".",
"data",
".",
"is_true",
"(",
"force",
")",
":",
"log",
".",
"warning",
"(",
"'userdel does not support force-deleting user whi... | 24.65 | 0.001953 |
def _aux_data(self, i):
""" Get a deep copy NDArray of the i-th aux data array associated with the
BaseSparseNDArray.
This function blocks. Do not use it in performance critical code.
"""
self.wait_to_read()
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetAuxND... | [
"def",
"_aux_data",
"(",
"self",
",",
"i",
")",
":",
"self",
".",
"wait_to_read",
"(",
")",
"hdl",
"=",
"NDArrayHandle",
"(",
")",
"check_call",
"(",
"_LIB",
".",
"MXNDArrayGetAuxNDArray",
"(",
"self",
".",
"handle",
",",
"i",
",",
"ctypes",
".",
"byre... | 38 | 0.010283 |
def phone_search_query(self, **kwargs):
"""
Query the Yelp Phone Search API.
documentation: https://www.yelp.com/developers/documentation/v3/business_search_phone
required parameters:
* phone - phone number
"""
if not kwargs.get('... | [
"def",
"phone_search_query",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
".",
"get",
"(",
"'phone'",
")",
":",
"raise",
"ValueError",
"(",
"'A valid phone number (parameter \"phone\") must be provided.'",
")",
"return",
"self",
".",
"_... | 35.923077 | 0.010438 |
def process_request(self, request_object):
"""Process Create Resource Request"""
resource = request_object.entity_cls.create(**request_object.data)
return ResponseSuccessCreated(resource) | [
"def",
"process_request",
"(",
"self",
",",
"request_object",
")",
":",
"resource",
"=",
"request_object",
".",
"entity_cls",
".",
"create",
"(",
"*",
"*",
"request_object",
".",
"data",
")",
"return",
"ResponseSuccessCreated",
"(",
"resource",
")"
] | 41.6 | 0.009434 |
def get_distance_term(self, C, rrup, mag):
"""
Returns distance scaling term
"""
return (C["r1"] + C["r2"] * mag) *\
np.log(np.sqrt(rrup ** 2. + C["h1"] ** 2.)) | [
"def",
"get_distance_term",
"(",
"self",
",",
"C",
",",
"rrup",
",",
"mag",
")",
":",
"return",
"(",
"C",
"[",
"\"r1\"",
"]",
"+",
"C",
"[",
"\"r2\"",
"]",
"*",
"mag",
")",
"*",
"np",
".",
"log",
"(",
"np",
".",
"sqrt",
"(",
"rrup",
"**",
"2.... | 33.166667 | 0.009804 |
def fnames(self, names):
"""Ensure constant size of fnames"""
names = list(names[:len(self._fnames)])
self._fnames = names + self._fnames[len(names):] | [
"def",
"fnames",
"(",
"self",
",",
"names",
")",
":",
"names",
"=",
"list",
"(",
"names",
"[",
":",
"len",
"(",
"self",
".",
"_fnames",
")",
"]",
")",
"self",
".",
"_fnames",
"=",
"names",
"+",
"self",
".",
"_fnames",
"[",
"len",
"(",
"names",
... | 42.75 | 0.011494 |
def _find_packages(root):
"""
Helper for ``build_index()``: Yield a list of tuples
``(pkg_xml, zf, subdir)``, where:
- ``pkg_xml`` is an ``ElementTree.Element`` holding the xml for a
package
- ``zf`` is a ``zipfile.ZipFile`` for the package's contents.
- ``subdir`` is the subdirectory (relative to... | [
"def",
"_find_packages",
"(",
"root",
")",
":",
"# Find all packages.",
"packages",
"=",
"[",
"]",
"for",
"dirname",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root",
")",
":",
"relpath",
"=",
"'/'",
".",
"join",
"(",
"_path_from",
"(... | 39.431818 | 0.012936 |
def setup(self):
"""
Performs backup if necessary.
"""
if self.backup:
shutil.copy(self.input_file, "{}.orig".format(self.input_file)) | [
"def",
"setup",
"(",
"self",
")",
":",
"if",
"self",
".",
"backup",
":",
"shutil",
".",
"copy",
"(",
"self",
".",
"input_file",
",",
"\"{}.orig\"",
".",
"format",
"(",
"self",
".",
"input_file",
")",
")"
] | 28.833333 | 0.011236 |
def del_calculation(job_id, confirmed=False):
"""
Delete a calculation and all associated outputs.
"""
if logs.dbcmd('get_job', job_id) is None:
print('There is no job %d' % job_id)
return
if confirmed or confirm(
'Are you sure you want to (abort and) delete this calcula... | [
"def",
"del_calculation",
"(",
"job_id",
",",
"confirmed",
"=",
"False",
")",
":",
"if",
"logs",
".",
"dbcmd",
"(",
"'get_job'",
",",
"job_id",
")",
"is",
"None",
":",
"print",
"(",
"'There is no job %d'",
"%",
"job_id",
")",
"return",
"if",
"confirmed",
... | 33.714286 | 0.001374 |
def where(self, where_string, **kwargs):
"""
Select from a given Table or Column with the specified WHERE clause
string. Additional keywords are passed to ExploreSqlDB.query(). For
convenience, if there is no '=', '>', '<', 'like', or 'LIKE' clause
in the WHERE statement .where()... | [
"def",
"where",
"(",
"self",
",",
"where_string",
",",
"*",
"*",
"kwargs",
")",
":",
"col",
",",
"id_col",
"=",
"self",
".",
"_query_helper",
"(",
"by",
"=",
"None",
")",
"where_string",
"=",
"str",
"(",
"where_string",
")",
"# Coerce here, for .__contains... | 42.258065 | 0.001493 |
def iplot_bloch_multivector(rho, figsize=None):
""" Create a bloch sphere representation.
Graphical representation of the input array, using as much bloch
spheres as qubit are required.
Args:
rho (array): State vector or density matrix
figsize (tuple): Figure size i... | [
"def",
"iplot_bloch_multivector",
"(",
"rho",
",",
"figsize",
"=",
"None",
")",
":",
"# HTML",
"html_template",
"=",
"Template",
"(",
"\"\"\"\n <p>\n <div id=\"content_$divNumber\" style=\"position: absolute; z-index: 1;\">\n <div id=\"bloch_$divNumber\"></div>\n ... | 28.691358 | 0.001664 |
def _call_config(self, method, *args, **kwargs):
"""Call the configuration at the given method which must take a section name
as first argument"""
return getattr(self._config, method)(self._section_name, *args, **kwargs) | [
"def",
"_call_config",
"(",
"self",
",",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"getattr",
"(",
"self",
".",
"_config",
",",
"method",
")",
"(",
"self",
".",
"_section_name",
",",
"*",
"args",
",",
"*",
"*",
"kwarg... | 60.25 | 0.016393 |
def add(entry_point, all_entry_points, auto_write, scripts_path):
'''Add Scrim scripts for a python project'''
click.echo()
if not entry_point and not all_entry_points:
raise click.UsageError(
'Missing required option: --entry_point or --all_entry_points'
)
if not os.path.ex... | [
"def",
"add",
"(",
"entry_point",
",",
"all_entry_points",
",",
"auto_write",
",",
"scripts_path",
")",
":",
"click",
".",
"echo",
"(",
")",
"if",
"not",
"entry_point",
"and",
"not",
"all_entry_points",
":",
"raise",
"click",
".",
"UsageError",
"(",
"'Missin... | 33.157143 | 0.000418 |
def box(extents=None, transform=None, **kwargs):
"""
Return a cuboid.
Parameters
------------
extents : float, or (3,) float
Edge lengths
transform: (4, 4) float
Transformation matrix
**kwargs:
passed to Trimesh to create box
Returns
------------
geometry : ... | [
"def",
"box",
"(",
"extents",
"=",
"None",
",",
"transform",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# vertices of the cube",
"vertices",
"=",
"[",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"1",
",",
"0",
",",
"1",
",",
"0",
... | 30.745455 | 0.000573 |
def create_message(self):
"""Returns a message body to send in this email. Should be from email.mime.*"""
body = dedent("""\
Received exception {exception} on {queue} from worker {worker}:
{traceback}
Payload:
{payload}
""").format(exception=self._exception,
... | [
"def",
"create_message",
"(",
"self",
")",
":",
"body",
"=",
"dedent",
"(",
"\"\"\"\\\n Received exception {exception} on {queue} from worker {worker}:\n\n {traceback}\n\n Payload:\n {payload}\n\n \"\"\"",
")",
".",
"format",
"(",
"exception",
"=",
... | 27.666667 | 0.013592 |
def reverse(
self,
query,
exactly_one=True,
timeout=DEFAULT_SENTINEL,
language=None,
):
"""
Return an address by location point.
:param query: The coordinates for which you wish to obtain the
closest human-readable addr... | [
"def",
"reverse",
"(",
"self",
",",
"query",
",",
"exactly_one",
"=",
"True",
",",
"timeout",
"=",
"DEFAULT_SENTINEL",
",",
"language",
"=",
"None",
",",
")",
":",
"position",
"=",
"self",
".",
"_coerce_point_to_string",
"(",
"query",
")",
"params",
"=",
... | 39.604167 | 0.002053 |
def close(self):
"""Closes this response."""
if self._connection:
self._connection.close()
self._response.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_connection",
":",
"self",
".",
"_connection",
".",
"close",
"(",
")",
"self",
".",
"_response",
".",
"close",
"(",
")"
] | 29 | 0.013423 |
def mwl(self, event):
"""Mouse Wheel - under tkinter we seem to need Tk v8.5+ for this """
if event.num == 4: # up on Linux
self.top.f.canvas.yview_scroll(-1*self._tmwm, 'units')
elif event.num == 5: # down on Linux
self.top.f.canvas.yview_scroll(1*self._tmwm, 'units')
... | [
"def",
"mwl",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"num",
"==",
"4",
":",
"# up on Linux",
"self",
".",
"top",
".",
"f",
".",
"canvas",
".",
"yview_scroll",
"(",
"-",
"1",
"*",
"self",
".",
"_tmwm",
",",
"'units'",
")",
"elif"... | 57.625 | 0.010684 |
def __validate_required_fields(self, document):
""" Validates that required fields are not missing.
:param document: The document being validated.
"""
try:
required = set(field for field, definition in self.schema.items()
if self._resolve_rules_set... | [
"def",
"__validate_required_fields",
"(",
"self",
",",
"document",
")",
":",
"try",
":",
"required",
"=",
"set",
"(",
"field",
"for",
"field",
",",
"definition",
"in",
"self",
".",
"schema",
".",
"items",
"(",
")",
"if",
"self",
".",
"_resolve_rules_set",
... | 43.9 | 0.001486 |
def _run(self): # pylint: disable=method-hidden
"""Spawn sub tasks, wait for stop signal."""
conn_params = self.connection.get_connection_params()
# See http://initd.org/psycopg/docs/module.html#psycopg2.connect and
# http://www.postgresql.org/docs/current/static/libpq-connect.html
... | [
"def",
"_run",
"(",
"self",
")",
":",
"# pylint: disable=method-hidden",
"conn_params",
"=",
"self",
".",
"connection",
".",
"get_connection_params",
"(",
")",
"# See http://initd.org/psycopg/docs/module.html#psycopg2.connect and",
"# http://www.postgresql.org/docs/current/static/l... | 41.527273 | 0.001283 |
def find_chunks(tagged, language="en"):
""" The input is a list of [token, tag]-items.
The output is a list of [token, tag, chunk]-items:
The/DT nice/JJ fish/NN is/VBZ dead/JJ ./. =>
The/DT/B-NP nice/JJ/I-NP fish/NN/I-NP is/VBZ/B-VP dead/JJ/B-ADJP ././O
"""
chunked = [x for x in tagg... | [
"def",
"find_chunks",
"(",
"tagged",
",",
"language",
"=",
"\"en\"",
")",
":",
"chunked",
"=",
"[",
"x",
"for",
"x",
"in",
"tagged",
"]",
"tags",
"=",
"\"\"",
".",
"join",
"(",
"\"%s%s\"",
"%",
"(",
"tag",
",",
"SEPARATOR",
")",
"for",
"token",
","... | 48 | 0.000888 |
def is_authenticated(self):
"""
Checks whether the library has the authentication and that is not expired
:return: True if authenticated, False otherwise
"""
token = self.con.token_backend.token
if not token:
token = self.con.token_backend.get_token()
... | [
"def",
"is_authenticated",
"(",
"self",
")",
":",
"token",
"=",
"self",
".",
"con",
".",
"token_backend",
".",
"token",
"if",
"not",
"token",
":",
"token",
"=",
"self",
".",
"con",
".",
"token_backend",
".",
"get_token",
"(",
")",
"return",
"token",
"i... | 36.1 | 0.008108 |
def PopulateForm(self):
"""
+-----------------------------------------------------------------------+
| +--- splitter ------------------------------------------------------+ |
| | +-- list widget--------------+ +- IdaSettingsView -------------+ | |
| | | ... | [
"def",
"PopulateForm",
"(",
"self",
")",
":",
"hbox",
"=",
"QtWidgets",
".",
"QHBoxLayout",
"(",
"self",
".",
"parent",
")",
"self",
".",
"_splitter",
"=",
"QtWidgets",
".",
"QSplitter",
"(",
"QtCore",
".",
"Qt",
".",
"Horizontal",
")",
"self",
".",
"_... | 61.913043 | 0.009679 |
def from_array(array):
"""
Deserialize a new PassportData from a given dictionary.
:return: new PassportData instance.
:rtype: PassportData
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_nam... | [
"def",
"from_array",
"(",
"array",
")",
":",
"if",
"array",
"is",
"None",
"or",
"not",
"array",
":",
"return",
"None",
"# end if",
"assert_type_or_raise",
"(",
"array",
",",
"dict",
",",
"parameter_name",
"=",
"\"array\"",
")",
"data",
"=",
"{",
"}",
"da... | 32.388889 | 0.008333 |
def get_location(self, location):
"""
For an index location return a dict of the index and value. This is optimized for speed because
it does not need to lookup the index location with a search. Also can accept relative indexing from the end of
the SEries in standard python notation [-3,... | [
"def",
"get_location",
"(",
"self",
",",
"location",
")",
":",
"return",
"{",
"self",
".",
"index_name",
":",
"self",
".",
"_index",
"[",
"location",
"]",
",",
"self",
".",
"data_name",
":",
"self",
".",
"_data",
"[",
"location",
"]",
"}"
] | 54.9 | 0.010753 |
def chained(wrapping_exc):
# pylint: disable=W0212
"""
Embeds the current exception information into the given one (which
will replace the current one).
For example::
try:
...
except OSError as ex:
raise chained(MyError("database not found!"))
"""
t, ... | [
"def",
"chained",
"(",
"wrapping_exc",
")",
":",
"# pylint: disable=W0212",
"t",
",",
"v",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"if",
"not",
"t",
":",
"return",
"wrapping_exc",
"wrapping_exc",
".",
"_inner_exc",
"=",
"v",
"lines",
"=",
"trac... | 27.315789 | 0.001862 |
def ensure_datetime(obj):
"""Return the object if it is a datetime-like object
Parameters
----------
obj : Object to be tested.
Returns
-------
The original object if it is a datetime-like object
Raises
------
TypeError if `obj` is not datetime-like
"""
_VALID_TYPES = ... | [
"def",
"ensure_datetime",
"(",
"obj",
")",
":",
"_VALID_TYPES",
"=",
"(",
"str",
",",
"datetime",
".",
"datetime",
",",
"cftime",
".",
"datetime",
",",
"np",
".",
"datetime64",
")",
"if",
"isinstance",
"(",
"obj",
",",
"_VALID_TYPES",
")",
":",
"return",... | 25.904762 | 0.001773 |
def upload_collection_configs(self, collection, fs_path):
'''
Uploads collection configurations from a specified directory to zookeeper.
'''
coll_path = fs_path
if not os.path.isdir(coll_path):
raise ValueError("{} Doesn't Exist".format(coll_path))
s... | [
"def",
"upload_collection_configs",
"(",
"self",
",",
"collection",
",",
"fs_path",
")",
":",
"coll_path",
"=",
"fs_path",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"coll_path",
")",
":",
"raise",
"ValueError",
"(",
"\"{} Doesn't Exist\"",
".",
"for... | 41.333333 | 0.013158 |
def expression(sceneid, tile_x, tile_y, tile_z, expr=None, **kwargs):
"""
Apply expression on data.
Attributes
----------
sceneid : str
Landsat id, Sentinel id, CBERS ids or file url.
tile_x : int
Mercator tile X index.
tile_y : int
Mercator tile Y index.
tile_z... | [
"def",
"expression",
"(",
"sceneid",
",",
"tile_x",
",",
"tile_y",
",",
"tile_z",
",",
"expr",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"expr",
":",
"raise",
"Exception",
"(",
"\"Missing expression\"",
")",
"bands_names",
"=",
"tuple"... | 26.569231 | 0.001675 |
def Run(self):
"""
Main entry point for ClearManager class.
Does the following steps:
- Parse script arguments.
- Optionally print or update database tables.
- Get all configuration settings from database.
- Optionally parse directory for file extraction.
- Recursively parse source dir... | [
"def",
"Run",
"(",
"self",
")",
":",
"self",
".",
"_GetArgs",
"(",
")",
"goodlogging",
".",
"Log",
".",
"Info",
"(",
"\"CLEAR\"",
",",
"\"Using database: {0}\"",
".",
"format",
"(",
"self",
".",
"_databasePath",
")",
")",
"self",
".",
"_db",
"=",
"data... | 36 | 0.013054 |
def get_stops(
feed: "Feed",
date: Optional[str] = None,
trip_id: Optional[str] = None,
route_id: Optional[str] = None,
*,
in_stations: bool = False,
) -> DataFrame:
"""
Return a section of ``feed.stops``.
Parameters
-----------
feed : Feed
date : string
YYYYMMDD... | [
"def",
"get_stops",
"(",
"feed",
":",
"\"Feed\"",
",",
"date",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"trip_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"route_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"*",
... | 29.016949 | 0.000565 |
def build_event_set(event):
"""
Turn an EventStream event into a set of event types that ORES
uses internally.
"""
event_set = set()
if re.match(r"([^\.]+.)?mediawiki\.revision-create$",
event['meta']['topic']):
event_set.add('edit')
user_groups = event.get('perf... | [
"def",
"build_event_set",
"(",
"event",
")",
":",
"event_set",
"=",
"set",
"(",
")",
"if",
"re",
".",
"match",
"(",
"r\"([^\\.]+.)?mediawiki\\.revision-create$\"",
",",
"event",
"[",
"'meta'",
"]",
"[",
"'topic'",
"]",
")",
":",
"event_set",
".",
"add",
"(... | 30.25 | 0.001335 |
def build_ctx(pythonpath=None):
"""
Decorator that makes decorated function use BuildContext instead of \
Context instance. BuildContext instance has more methods.
:param pythonpath: Path or list of paths to add to environment variable
PYTHONPATH. Each path can be absolute path, or relative pat... | [
"def",
"build_ctx",
"(",
"pythonpath",
"=",
"None",
")",
":",
"# If argument `pythonpath` is string",
"if",
"isinstance",
"(",
"pythonpath",
",",
"str",
")",
":",
"# Create paths list containing the string",
"path_s",
"=",
"[",
"pythonpath",
"]",
"# If argument `pythonp... | 31.389381 | 0.000273 |
def redraw_now(self, whence=0):
"""Redraw the displayed image.
Parameters
----------
whence
See :meth:`get_rgb_object`.
"""
try:
time_start = time.time()
self.redraw_data(whence=whence)
# finally update the window drawabl... | [
"def",
"redraw_now",
"(",
"self",
",",
"whence",
"=",
"0",
")",
":",
"try",
":",
"time_start",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"redraw_data",
"(",
"whence",
"=",
"whence",
")",
"# finally update the window drawable from the offscreen surface",
... | 34.941176 | 0.002457 |
def legend(self):
''' Splattable list of :class:`~bokeh.models.annotations.Legend` objects.
'''
panels = self.above + self.below + self.left + self.right + self.center
legends = [obj for obj in panels if isinstance(obj, Legend)]
return _legend_attr_splat(legends) | [
"def",
"legend",
"(",
"self",
")",
":",
"panels",
"=",
"self",
".",
"above",
"+",
"self",
".",
"below",
"+",
"self",
".",
"left",
"+",
"self",
".",
"right",
"+",
"self",
".",
"center",
"legends",
"=",
"[",
"obj",
"for",
"obj",
"in",
"panels",
"if... | 42.571429 | 0.009868 |
def ppo_tiny_world_model():
"""Atari parameters with world model as policy."""
hparams = ppo_original_params()
hparams.policy_network = "next_frame_basic_deterministic"
hparams_keys = hparams.values().keys()
video_hparams = basic_deterministic_params.next_frame_tiny()
for (name, value) in six.iteritems(vide... | [
"def",
"ppo_tiny_world_model",
"(",
")",
":",
"hparams",
"=",
"ppo_original_params",
"(",
")",
"hparams",
".",
"policy_network",
"=",
"\"next_frame_basic_deterministic\"",
"hparams_keys",
"=",
"hparams",
".",
"values",
"(",
")",
".",
"keys",
"(",
")",
"video_hpara... | 37.461538 | 0.022044 |
def _buildToilState(self, jobGraph, jobStore, jobCache=None):
"""
Traverses tree of jobs from the root jobGraph (rootJob) building the
ToilState class.
If jobCache is passed, it must be a dict from job ID to JobGraph
object. Jobs will be loaded from the cache (which can be downl... | [
"def",
"_buildToilState",
"(",
"self",
",",
"jobGraph",
",",
"jobStore",
",",
"jobCache",
"=",
"None",
")",
":",
"def",
"getJob",
"(",
"jobId",
")",
":",
"if",
"jobCache",
"is",
"not",
"None",
":",
"if",
"jobId",
"in",
"jobCache",
":",
"return",
"jobCa... | 53.61 | 0.008608 |
def count_waiting_jobs(cls, names):
"""
Return the number of all jobs waiting in queues with the given names
"""
return sum([queue.waiting.llen() for queue in cls.get_all(names)]) | [
"def",
"count_waiting_jobs",
"(",
"cls",
",",
"names",
")",
":",
"return",
"sum",
"(",
"[",
"queue",
".",
"waiting",
".",
"llen",
"(",
")",
"for",
"queue",
"in",
"cls",
".",
"get_all",
"(",
"names",
")",
"]",
")"
] | 41.4 | 0.009479 |
def convert_field(self, name, field):
"""
Convert a single field from a Peewee model field to a validator field.
:param name: Name of the field as defined on this validator.
:param name: Peewee field instance.
:return: Validator field.
"""
if PEEWEE3:
... | [
"def",
"convert_field",
"(",
"self",
",",
"name",
",",
"field",
")",
":",
"if",
"PEEWEE3",
":",
"field_type",
"=",
"field",
".",
"field_type",
".",
"lower",
"(",
")",
"else",
":",
"field_type",
"=",
"field",
".",
"db_field",
"pwv_field",
"=",
"ModelValid... | 35.36 | 0.002201 |
def cleanse(span):
'''Convert a string of text into a lowercase string with no
punctuation and only spaces for whitespace.
:param span: string
'''
try:
## attempt to force it to utf8, which might fail
span = span.encode('utf8', 'ignore')
except:
pass
## lowercase, st... | [
"def",
"cleanse",
"(",
"span",
")",
":",
"try",
":",
"## attempt to force it to utf8, which might fail",
"span",
"=",
"span",
".",
"encode",
"(",
"'utf8'",
",",
"'ignore'",
")",
"except",
":",
"pass",
"## lowercase, strip punctuation, and shrink all whitespace",
"span",... | 30.764706 | 0.009276 |
def start(self):
"""
Start all the processes
"""
Global.LOGGER.info("starting the flow manager")
self._start_actions()
self._start_message_fetcher()
Global.LOGGER.debug("flow manager started") | [
"def",
"start",
"(",
"self",
")",
":",
"Global",
".",
"LOGGER",
".",
"info",
"(",
"\"starting the flow manager\"",
")",
"self",
".",
"_start_actions",
"(",
")",
"self",
".",
"_start_message_fetcher",
"(",
")",
"Global",
".",
"LOGGER",
".",
"debug",
"(",
"\... | 30.125 | 0.008065 |
def login(self, user, passwd):
"""
Logs into the wiki with username *user* and password *passwd*. Returns
``True`` on successful login.
:param user: username
:param passwd: password
:returns: ``True`` on successful login, otherwise ``False``
"""
def do_lo... | [
"def",
"login",
"(",
"self",
",",
"user",
",",
"passwd",
")",
":",
"def",
"do_login",
"(",
"self",
",",
"user",
",",
"passwd",
",",
"token",
"=",
"None",
")",
":",
"\"\"\"\n Login function that handles CSRF protection (see `MediaWiki bug\n 23076`... | 37.03125 | 0.001645 |
def import_string(import_name, silent=False):
"""Imports an object based on a string. This is useful if you want to
use import paths as endpoints or something similar. An import path can
be specified either in dotted notation (``xml.sax.saxutils.escape``)
or with a colon as object delimiter (``xml.sax... | [
"def",
"import_string",
"(",
"import_name",
",",
"silent",
"=",
"False",
")",
":",
"try",
":",
"if",
"':'",
"in",
"import_name",
":",
"module",
",",
"obj_name",
"=",
"import_name",
".",
"split",
"(",
"':'",
",",
"1",
")",
"elif",
"'.'",
"in",
"import_n... | 39.115385 | 0.00096 |
def get_valid_parent_pages(self, user):
"""
Identifies possible parent pages for the current user by first looking
at allowed_parent_page_models() on self.model to limit options to the
correct type of page, then checking permissions on those individual
pages to make sure we have ... | [
"def",
"get_valid_parent_pages",
"(",
"self",
",",
"user",
")",
":",
"# Start with empty qs",
"parents_qs",
"=",
"Page",
".",
"objects",
".",
"none",
"(",
")",
"# Add pages of the correct type",
"for",
"pt",
"in",
"self",
".",
"model",
".",
"allowed_parent_page_mo... | 40.904762 | 0.002275 |
def create_archiver(typename):
"""Returns Archivers in common configurations.
:API: public
The typename must correspond to one of the following:
'tar' Returns a tar archiver that applies no compression and emits .tar files.
'tgz' Returns a tar archiver that applies gzip compression and emits .tar.gz fil... | [
"def",
"create_archiver",
"(",
"typename",
")",
":",
"archiver",
"=",
"_ARCHIVER_BY_TYPE",
".",
"get",
"(",
"typename",
")",
"if",
"not",
"archiver",
":",
"raise",
"ValueError",
"(",
"'No archiver registered for {!r}'",
".",
"format",
"(",
"typename",
")",
")",
... | 50.5 | 0.011662 |
def iterate(self, name, interval, **kwargs):
'''
Returns a generator that iterates over all the intervals and returns
data for various timestamps, in the form:
( unix_timestamp, data )
This will check for all timestamp buckets that might exist between
the first and last timestamp in a series... | [
"def",
"iterate",
"(",
"self",
",",
"name",
",",
"interval",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"self",
".",
"_intervals",
".",
"get",
"(",
"interval",
")",
"if",
"not",
"config",
":",
"raise",
"UnknownInterval",
"(",
"interval",
")",
... | 37 | 0.00843 |
def get(self, index):
"""
Get the element by index. If index is out of bounds for
the internal list, None is returned. Indexes cannot be
negative.
:param int index: retrieve element by positive index in list
:rtype: SubElement or None
"""
if self ... | [
"def",
"get",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
"and",
"(",
"index",
"<=",
"len",
"(",
"self",
")",
"-",
"1",
")",
":",
"return",
"self",
".",
"_result_cache",
"[",
"index",
"]"
] | 34.818182 | 0.010178 |
def save_kb_dyn_config(kb_id, field, expression, collection=None):
"""Save a dynamic knowledge base configuration.
:param kb_id: the id
:param field: the field where values are extracted
:param expression: ..using this expression
:param collection: ..in a certain collection (default is all)
"""... | [
"def",
"save_kb_dyn_config",
"(",
"kb_id",
",",
"field",
",",
"expression",
",",
"collection",
"=",
"None",
")",
":",
"# check that collection exists",
"if",
"collection",
":",
"collection",
"=",
"Collection",
".",
"query",
".",
"filter_by",
"(",
"name",
"=",
... | 36.785714 | 0.001894 |
def _patch_tcpserver():
"""
Patch shutdown_request to open blocking interaction after the end of the
request
"""
shutdown_request = TCPServer.shutdown_request
def shutdown_request_patched(*args, **kwargs):
thread = current_thread()
shutdown_request(*args, **kwargs)
if th... | [
"def",
"_patch_tcpserver",
"(",
")",
":",
"shutdown_request",
"=",
"TCPServer",
".",
"shutdown_request",
"def",
"shutdown_request_patched",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"current_thread",
"(",
")",
"shutdown_request",
"(",
... | 31.857143 | 0.002179 |
def p_numeric_literal(self, p):
"""numeric_literal : NUMBER"""
p[0] = self.asttypes.Number(p[1])
p[0].setpos(p) | [
"def",
"p_numeric_literal",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Number",
"(",
"p",
"[",
"1",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | 33 | 0.014815 |
async def load_blob(reader, elem_type, params=None, elem=None):
"""
Loads blob from reader to the element. Returns the loaded blob.
:param reader:
:param elem_type:
:param params:
:param elem:
:return:
"""
ivalue = await load_varint(reader)
fvalue = bytearray(ivalue)
await r... | [
"async",
"def",
"load_blob",
"(",
"reader",
",",
"elem_type",
",",
"params",
"=",
"None",
",",
"elem",
"=",
"None",
")",
":",
"ivalue",
"=",
"await",
"load_varint",
"(",
"reader",
")",
"fvalue",
"=",
"bytearray",
"(",
"ivalue",
")",
"await",
"reader",
... | 22 | 0.001742 |
def _pointInside(self, point):
"""
Subclasses may override this method.
"""
from fontTools.pens.pointInsidePen import PointInsidePen
pen = PointInsidePen(glyphSet=self.layer, testPoint=point, evenOdd=False)
self.draw(pen)
return pen.getResult() | [
"def",
"_pointInside",
"(",
"self",
",",
"point",
")",
":",
"from",
"fontTools",
".",
"pens",
".",
"pointInsidePen",
"import",
"PointInsidePen",
"pen",
"=",
"PointInsidePen",
"(",
"glyphSet",
"=",
"self",
".",
"layer",
",",
"testPoint",
"=",
"point",
",",
... | 36.625 | 0.01 |
def _sanitize_instance_name(name, max_length):
"""Instance names must start with a lowercase letter.
All following characters must be a dash, lowercase letter,
or digit.
"""
name = str(name).lower() # make all letters lowercase
name = re.sub(r'[^-a-z0-9]', '', name) # remove inva... | [
"def",
"_sanitize_instance_name",
"(",
"name",
",",
"max_length",
")",
":",
"name",
"=",
"str",
"(",
"name",
")",
".",
"lower",
"(",
")",
"# make all letters lowercase",
"name",
"=",
"re",
".",
"sub",
"(",
"r'[^-a-z0-9]'",
",",
"''",
",",
"name",
")",
"#... | 44.75 | 0.001825 |
def discard(self, key):
"""
Banana banana
"""
if key in self.map:
key, prev, nxt = self.map.pop(key)
prev[2] = nxt
nxt[1] = prev | [
"def",
"discard",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
"in",
"self",
".",
"map",
":",
"key",
",",
"prev",
",",
"nxt",
"=",
"self",
".",
"map",
".",
"pop",
"(",
"key",
")",
"prev",
"[",
"2",
"]",
"=",
"nxt",
"nxt",
"[",
"1",
"]",
... | 23.625 | 0.010204 |
def get_user_by_id(uid,**kwargs):
"""
Get a user by username
"""
user_id = kwargs.get('user_id')
try:
user_i = _get_user(uid)
return user_i
except NoResultFound:
return None | [
"def",
"get_user_by_id",
"(",
"uid",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"try",
":",
"user_i",
"=",
"_get_user",
"(",
"uid",
")",
"return",
"user_i",
"except",
"NoResultFound",
":",
"return",
... | 21.6 | 0.008889 |
def createAndCleanTPED(tped, tfam, snps, prefix, chosenSNPs, completion,
concordance, snpsToComplete, tfamFileName, completionT,
concordanceT):
"""Complete a TPED for duplicated SNPs.
:param tped: a representation of the ``tped`` of duplicated markers.
:param t... | [
"def",
"createAndCleanTPED",
"(",
"tped",
",",
"tfam",
",",
"snps",
",",
"prefix",
",",
"chosenSNPs",
",",
"completion",
",",
"concordance",
",",
"snpsToComplete",
",",
"tfamFileName",
",",
"completionT",
",",
"concordanceT",
")",
":",
"zeroedOutFile",
"=",
"N... | 40.014423 | 0.000234 |
def _mesh_to_material(mesh, metallic=0.0, rough=0.0):
"""
Create a simple GLTF material for a mesh using the most
commonly occurring color in that mesh.
Parameters
------------
mesh: trimesh.Trimesh
Mesh to create a material from
Returns
------------
material: dict
In G... | [
"def",
"_mesh_to_material",
"(",
"mesh",
",",
"metallic",
"=",
"0.0",
",",
"rough",
"=",
"0.0",
")",
":",
"try",
":",
"# just get the most commonly occurring color",
"color",
"=",
"mesh",
".",
"visual",
".",
"main_color",
"except",
"BaseException",
":",
"color",... | 24.878788 | 0.001172 |
def xpath_pick_one(self, xpaths):
"""
Try each of the xpaths successively until
a single element is found. If no xpath succeeds
then raise the last UnexpectedContentException caught.
"""
for xpathi, xpath in enumerate(xpaths):
try:
return self.xpath(xpath, [1, 1])[0]
except UnexpectedCont... | [
"def",
"xpath_pick_one",
"(",
"self",
",",
"xpaths",
")",
":",
"for",
"xpathi",
",",
"xpath",
"in",
"enumerate",
"(",
"xpaths",
")",
":",
"try",
":",
"return",
"self",
".",
"xpath",
"(",
"xpath",
",",
"[",
"1",
",",
"1",
"]",
")",
"[",
"0",
"]",
... | 31.166667 | 0.033766 |
def generate_circle_output():
"""Build sequence for Circle CI 2.0 config.yml
builds the circleci structure
also links individual jobs into a workflow graph
"""
base = new_base()
workflow = networkx.DiGraph()
LOG.info('%s python versions', len(python_versions))
LOG.info('%s mbed cloud ho... | [
"def",
"generate_circle_output",
"(",
")",
":",
"base",
"=",
"new_base",
"(",
")",
"workflow",
"=",
"networkx",
".",
"DiGraph",
"(",
")",
"LOG",
".",
"info",
"(",
"'%s python versions'",
",",
"len",
"(",
"python_versions",
")",
")",
"LOG",
".",
"info",
"... | 32.833333 | 0.00219 |
def read(self, timeout=None):
'''
Read from the transport. If timeout>0, will only block for `timeout`
seconds.
'''
e = None
if not hasattr(self, '_sock'):
return None
try:
# Note that we ignore both None and 0, i.e. we either block with a... | [
"def",
"read",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"e",
"=",
"None",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_sock'",
")",
":",
"return",
"None",
"try",
":",
"# Note that we ignore both None and 0, i.e. we either block with a",
"# timeout or ... | 35.16 | 0.001107 |
def _update_state_from_shard_states(self, state, shard_states, control):
"""Update mr state by examing shard states.
Args:
state: current mapreduce state as MapreduceState.
shard_states: an iterator over shard states.
control: model.MapreduceControl entity.
"""
# Initialize vars.
... | [
"def",
"_update_state_from_shard_states",
"(",
"self",
",",
"state",
",",
"shard_states",
",",
"control",
")",
":",
"# Initialize vars.",
"state",
".",
"active_shards",
",",
"state",
".",
"aborted_shards",
",",
"state",
".",
"failed_shards",
"=",
"0",
",",
"0",
... | 39.952381 | 0.008433 |
def do_rtn(self, args):
"""rtn <addr> <net> ... """
args = args.split()
if _debug: ReadPropertyConsoleCmd._debug("do_rtn %r", args)
# provide the address and a list of network numbers
router_address = Address(args[0])
network_list = [int(arg) for arg in args[1:]]
... | [
"def",
"do_rtn",
"(",
"self",
",",
"args",
")",
":",
"args",
"=",
"args",
".",
"split",
"(",
")",
"if",
"_debug",
":",
"ReadPropertyConsoleCmd",
".",
"_debug",
"(",
"\"do_rtn %r\"",
",",
"args",
")",
"# provide the address and a list of network numbers",
"router... | 40 | 0.008889 |
def sign_up(self):
"""Accept HIT, give consent and start experiment.
This uses Selenium to click through buttons on the ad,
consent, and instruction pages.
"""
try:
self.driver.get(self.URL)
logger.info("Loaded ad page.")
begin = WebDriverWait... | [
"def",
"sign_up",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"driver",
".",
"get",
"(",
"self",
".",
"URL",
")",
"logger",
".",
"info",
"(",
"\"Loaded ad page.\"",
")",
"begin",
"=",
"WebDriverWait",
"(",
"self",
".",
"driver",
",",
"10",
")",
... | 42.15625 | 0.002174 |
def detect_false_positive_direct_metabolites(
candidates, biomass_reactions, cytosol, extra, reaction_fluxes,
metabolite_fluxes):
"""
Weed out false positive direct metabolites.
False positives exists in the extracellular
compartment with flux from the cytosolic compartment and are part... | [
"def",
"detect_false_positive_direct_metabolites",
"(",
"candidates",
",",
"biomass_reactions",
",",
"cytosol",
",",
"extra",
",",
"reaction_fluxes",
",",
"metabolite_fluxes",
")",
":",
"for",
"met",
"in",
"candidates",
":",
"is_internal",
"=",
"met",
".",
"compartm... | 44.65 | 0.000365 |
def sort_index(
self,
axis=0,
level=None,
ascending=True,
inplace=False,
kind="quicksort",
na_position="last",
sort_remaining=True,
by=None,
):
"""Sort a DataFrame by one of the indices (columns or index).
Args:
... | [
"def",
"sort_index",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"level",
"=",
"None",
",",
"ascending",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"kind",
"=",
"\"quicksort\"",
",",
"na_position",
"=",
"\"last\"",
",",
"sort_remaining",
"=",
"True",
... | 37.285714 | 0.002333 |
def validate_password_confirmation(self, value):
""" password_confirmation check """
if value != self.initial_data['password']:
raise serializers.ValidationError(_('Password confirmation mismatch'))
return value | [
"def",
"validate_password_confirmation",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"!=",
"self",
".",
"initial_data",
"[",
"'password'",
"]",
":",
"raise",
"serializers",
".",
"ValidationError",
"(",
"_",
"(",
"'Password confirmation mismatch'",
")",
"... | 48.6 | 0.012146 |
def disassemble_around(self, lpAddress, dwSize = 64):
"""
Disassemble around the given address.
@type lpAddress: int
@param lpAddress: Memory address where to read the code from.
@type dwSize: int
@param dwSize: Delta offset.
Code will be read from lpAddre... | [
"def",
"disassemble_around",
"(",
"self",
",",
"lpAddress",
",",
"dwSize",
"=",
"64",
")",
":",
"dwDelta",
"=",
"int",
"(",
"float",
"(",
"dwSize",
")",
"/",
"2.0",
")",
"addr_1",
"=",
"lpAddress",
"-",
"dwDelta",
"addr_2",
"=",
"lpAddress",
"size_1",
... | 36.96875 | 0.010708 |
def getDocFactory(self, fragmentName, default=None):
"""
For a given fragment, return a loaded Nevow template.
@param fragmentName: the name of the template (can include relative
paths).
@param default: a default loader; only used if provided and the
given fragment name... | [
"def",
"getDocFactory",
"(",
"self",
",",
"fragmentName",
",",
"default",
"=",
"None",
")",
":",
"if",
"fragmentName",
"in",
"self",
".",
"cachedLoaders",
":",
"return",
"self",
".",
"cachedLoaders",
"[",
"fragmentName",
"]",
"segments",
"=",
"fragmentName",
... | 34.52 | 0.002255 |
def from_fp(self, file_pointer, comment_lead=['c']):
"""
Read a WCNF formula from a file pointer. A file pointer should be
specified as an argument. The only default argument is
``comment_lead``, which can be used for parsing specific comment
lines.
:... | [
"def",
"from_fp",
"(",
"self",
",",
"file_pointer",
",",
"comment_lead",
"=",
"[",
"'c'",
"]",
")",
":",
"self",
".",
"nv",
"=",
"0",
"self",
".",
"hard",
"=",
"[",
"]",
"self",
".",
"soft",
"=",
"[",
"]",
"self",
".",
"wght",
"=",
"[",
"]",
... | 34.84 | 0.002233 |
def eplotter(task, data): # CRYSTAL, VASP, EXCITING
'''
eplotter is like bdplotter but less complicated
'''
results, color, fdata = [], None, []
if task == 'optstory':
color = '#CC0000'
clickable = True
for n, i in enumerate(data):
fdata.append([n, i[4]])
... | [
"def",
"eplotter",
"(",
"task",
",",
"data",
")",
":",
"# CRYSTAL, VASP, EXCITING",
"results",
",",
"color",
",",
"fdata",
"=",
"[",
"]",
",",
"None",
",",
"[",
"]",
"if",
"task",
"==",
"'optstory'",
":",
"color",
"=",
"'#CC0000'",
"clickable",
"=",
"T... | 29.925926 | 0.008393 |
def get_association(id, **kwargs):
"""
Fetch an association object by ID
"""
results = search_associations(id=id, **kwargs)
assoc = results['associations'][0] if len(results['associations']) > 0 else {}
return assoc | [
"def",
"get_association",
"(",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"results",
"=",
"search_associations",
"(",
"id",
"=",
"id",
",",
"*",
"*",
"kwargs",
")",
"assoc",
"=",
"results",
"[",
"'associations'",
"]",
"[",
"0",
"]",
"if",
"len",
"(",
... | 33.285714 | 0.008368 |
def initialize_delete_state_map(self):
"""This is a mapping of delete result message string to state. """
self.fabric_state_del_map = {
fw_const.INIT_STATE_STR: fw_const.OS_IN_NETWORK_STATE,
fw_const.OS_IN_NETWORK_DEL_FAIL:
fw_const.OS_IN_NETWORK_STATE,
... | [
"def",
"initialize_delete_state_map",
"(",
"self",
")",
":",
"self",
".",
"fabric_state_del_map",
"=",
"{",
"fw_const",
".",
"INIT_STATE_STR",
":",
"fw_const",
".",
"OS_IN_NETWORK_STATE",
",",
"fw_const",
".",
"OS_IN_NETWORK_DEL_FAIL",
":",
"fw_const",
".",
"OS_IN_N... | 47.305556 | 0.001151 |
async def inline_query(self, bot, query, *, offset=None, geo_point=None):
"""
Makes the given inline query to the specified bot
i.e. ``@vote My New Poll`` would be as follows:
>>> client = ...
>>> client.inline_query('vote', 'My New Poll')
Args:
bot (`entity... | [
"async",
"def",
"inline_query",
"(",
"self",
",",
"bot",
",",
"query",
",",
"*",
",",
"offset",
"=",
"None",
",",
"geo_point",
"=",
"None",
")",
":",
"bot",
"=",
"await",
"self",
".",
"get_input_entity",
"(",
"bot",
")",
"result",
"=",
"await",
"self... | 33.222222 | 0.001625 |
def update_fit_box(self, new_fit=False):
"""
alters fit_box lists to match with changes in specimen or new/
removed interpretations
Parameters
----------
new_fit : boolean representing if there is a new fit
Alters
------
fit_box selection and cho... | [
"def",
"update_fit_box",
"(",
"self",
",",
"new_fit",
"=",
"False",
")",
":",
"# get new fit data",
"if",
"self",
".",
"s",
"in",
"list",
"(",
"self",
".",
"pmag_results_data",
"[",
"'specimens'",
"]",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"fit... | 32.25641 | 0.001543 |
def _get_workflow_by_name(workflow_name, user_uuid):
"""From Workflows named as `workflow_name` the latest run_number.
Only use when you are sure that workflow_name is not UUIDv4.
:rtype: reana-db.models.Workflow
"""
from reana_db.models import Workflow
workflow = Workflow.query.filter(
... | [
"def",
"_get_workflow_by_name",
"(",
"workflow_name",
",",
"user_uuid",
")",
":",
"from",
"reana_db",
".",
"models",
"import",
"Workflow",
"workflow",
"=",
"Workflow",
".",
"query",
".",
"filter",
"(",
"Workflow",
".",
"name",
"==",
"workflow_name",
",",
"Work... | 35.95 | 0.001355 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.