text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _plot_ulims(
ax, x, y, xerr, color, capsize=5, height_fraction=0.25, elinewidth=2
):
"""
Plot upper limits as arrows with cap at value of upper limit.
uplim behaviour has been fixed in matplotlib 1.4
"""
ax.errorbar(
x, y, xerr=xerr, ls="", color=color, elinewidth=elinewidth, capsiz... | [
"def",
"_plot_ulims",
"(",
"ax",
",",
"x",
",",
"y",
",",
"xerr",
",",
"color",
",",
"capsize",
"=",
"5",
",",
"height_fraction",
"=",
"0.25",
",",
"elinewidth",
"=",
"2",
")",
":",
"ax",
".",
"errorbar",
"(",
"x",
",",
"y",
",",
"xerr",
"=",
"... | 25.125 | 0.000958 |
def write(config):
"""Commits any pending modifications, ie save a configuration file if
it has been marked "dirty" as a result of an normal
assignment. The modifications are written to the first
writable source in this config object.
.. note::
This is a static metho... | [
"def",
"write",
"(",
"config",
")",
":",
"root",
"=",
"config",
"while",
"root",
".",
"_parent",
":",
"root",
"=",
"root",
".",
"_parent",
"for",
"source",
"in",
"root",
".",
"_sources",
":",
"if",
"source",
".",
"writable",
"and",
"source",
".",
"di... | 33.333333 | 0.00243 |
def batch_indices_iterator(self, batch_size, shuffle=None, **kwargs):
"""
Create an iterator that generates mini-batch sample indices
The generated mini-batches indices take the form of nested lists of
either:
- 1D NumPy integer arrays
- slices
The list nesting ... | [
"def",
"batch_indices_iterator",
"(",
"self",
",",
"batch_size",
",",
"shuffle",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"_random_access",
":",
"raise",
"TypeError",
"(",
"'batch_indices_iterator method not supported as '",
"'one ... | 40.972973 | 0.001289 |
def Dependencies(tools):
"""
Takes in a list of tools that are being updated and returns any tools that
depend on linking to them
"""
dependencies = []
if tools:
path_dirs = PathDirs()
man = Template(join(path_dirs.meta_dir, 'plugin_manifest.cfg'))
for section in man.sect... | [
"def",
"Dependencies",
"(",
"tools",
")",
":",
"dependencies",
"=",
"[",
"]",
"if",
"tools",
":",
"path_dirs",
"=",
"PathDirs",
"(",
")",
"man",
"=",
"Template",
"(",
"join",
"(",
"path_dirs",
".",
"meta_dir",
",",
"'plugin_manifest.cfg'",
")",
")",
"for... | 43.241379 | 0.00078 |
def add(self, entity):
"""
Adds the supplied dict as a new entity
"""
result = self._http_req('connections', method='POST', payload=entity)
status = result['status']
if not status==201:
raise ServiceRegistryError(status,"Couldn't add entity")
self.debug(0x01,result)
return result['decoded'] | [
"def",
"add",
"(",
"self",
",",
"entity",
")",
":",
"result",
"=",
"self",
".",
"_http_req",
"(",
"'connections'",
",",
"method",
"=",
"'POST'",
",",
"payload",
"=",
"entity",
")",
"status",
"=",
"result",
"[",
"'status'",
"]",
"if",
"not",
"status",
... | 27.363636 | 0.045016 |
def setup(self):
"""Collect watchdog information.
Collect configuration files, custom executables for test-binary
and repair-binary, and stdout/stderr logs.
"""
conf_file = self.get_option('conf_file')
log_dir = '/var/log/watchdog'
# Get service configur... | [
"def",
"setup",
"(",
"self",
")",
":",
"conf_file",
"=",
"self",
".",
"get_option",
"(",
"'conf_file'",
")",
"log_dir",
"=",
"'/var/log/watchdog'",
"# Get service configuration and sysconfig files",
"self",
".",
"add_copy_spec",
"(",
"[",
"conf_file",
",",
"'/etc/sy... | 30.75 | 0.001576 |
def update_file(self, file_id, upload_id):
"""
Send PUT request to /files/{file_id} to update the file contents to upload_id and sets a label.
:param file_id: str uuid of file
:param upload_id: str uuid of the upload where all the file chunks where uploaded
:param label: str shor... | [
"def",
"update_file",
"(",
"self",
",",
"file_id",
",",
"upload_id",
")",
":",
"put_data",
"=",
"{",
"\"upload[id]\"",
":",
"upload_id",
",",
"}",
"return",
"self",
".",
"_put",
"(",
"\"/files/\"",
"+",
"file_id",
",",
"put_data",
",",
"content_type",
"=",... | 47.666667 | 0.008576 |
def main():
"""
NAME
lsq_redo.py
DESCRIPTION
converts a tab delimited LSQ format to PmagPy redo file and edits the magic_measurements table to mark "bad" measurements.
SYNTAX
lsq_redo.py [-h] [command line options]
OPTIONS
-h: prints help message and quits
... | [
"def",
"main",
"(",
")",
":",
"letters",
"=",
"string",
".",
"ascii_uppercase",
"for",
"l",
"in",
"string",
".",
"ascii_lowercase",
":",
"letters",
"=",
"letters",
"+",
"l",
"dir_path",
"=",
"'.'",
"if",
"'-WD'",
"in",
"sys",
".",
"argv",
":",
"ind",
... | 37.522388 | 0.021701 |
def scan_module(self, pkgpath, modpath, node):
"""Scans a module, collecting possible origins for all names, assuming
names can only become bound to values in other modules by import."""
def scan_imports(node):
if node_type(node) == 'Import':
for binding in node.name... | [
"def",
"scan_module",
"(",
"self",
",",
"pkgpath",
",",
"modpath",
",",
"node",
")",
":",
"def",
"scan_imports",
"(",
"node",
")",
":",
"if",
"node_type",
"(",
"node",
")",
"==",
"'Import'",
":",
"for",
"binding",
"in",
"node",
".",
"names",
":",
"na... | 45.225806 | 0.002095 |
def _request(self, method, *relative_path_parts, **kwargs):
"""Sends an HTTP request to the REST API and receives the requested data.
Additionally sets up pagination cursors.
:param str method: HTTP method name
:param relative_path_parts: the relative paths for the request URI
:param kwargs: argume... | [
"def",
"_request",
"(",
"self",
",",
"method",
",",
"*",
"relative_path_parts",
",",
"*",
"*",
"kwargs",
")",
":",
"uri",
"=",
"self",
".",
"_create_api_uri",
"(",
"*",
"relative_path_parts",
")",
"response",
"=",
"get",
"(",
"uri",
",",
"params",
"=",
... | 42.058824 | 0.001368 |
def stop(self):
'''
Stop the auth proc.
'''
log.info('Stopping auth process')
self.__up = False
self.socket.close() | [
"def",
"stop",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"'Stopping auth process'",
")",
"self",
".",
"__up",
"=",
"False",
"self",
".",
"socket",
".",
"close",
"(",
")"
] | 22.428571 | 0.01227 |
def respth2ck(argv=None):
"""Command-line entry point for converting a ReSpecTh XML file to a ChemKED YAML file.
"""
parser = ArgumentParser(
description='Convert a ReSpecTh XML file to a ChemKED YAML file.'
)
parser.add_argument('-i', '--input',
type=str,
... | [
"def",
"respth2ck",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"'Convert a ReSpecTh XML file to a ChemKED YAML file.'",
")",
"parser",
".",
"add_argument",
"(",
"'-i'",
",",
"'--input'",
",",
"type",
"=",
"str",
... | 38.387755 | 0.002074 |
def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET):
"""Generates a non-guessable OAuth token
OAuth (1 and 2) does not specify the format of tokens except that they
should be strings of random characters. Tokens should not be guessable
and entropy when generating the random characters is i... | [
"def",
"generate_token",
"(",
"length",
"=",
"30",
",",
"chars",
"=",
"UNICODE_ASCII_CHARACTER_SET",
")",
":",
"rand",
"=",
"SystemRandom",
"(",
")",
"return",
"''",
".",
"join",
"(",
"rand",
".",
"choice",
"(",
"chars",
")",
"for",
"x",
"in",
"range",
... | 49.9 | 0.001969 |
def conforms(element, etype, namespace: Dict[str, Any]) -> bool:
""" Determine whether element conforms to etype
:param element: Element to test for conformance
:param etype: Type to test against
:param namespace: Namespace to use to resolve forward references
:return:
"""
etype = proc_forw... | [
"def",
"conforms",
"(",
"element",
",",
"etype",
",",
"namespace",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"bool",
":",
"etype",
"=",
"proc_forward",
"(",
"etype",
",",
"namespace",
")",
"if",
"is_union",
"(",
"etype",
")",
":",
"return"... | 36.769231 | 0.002041 |
def slice(objects, position, axis, precision=1e-3, layer=0, datatype=0):
"""
Slice polygons and polygon sets at given positions along an axis.
Parameters
----------
objects : ``PolygonSet``, or list
Operand of the slice operation. If this is a list, each element
must be a ``Polygon... | [
"def",
"slice",
"(",
"objects",
",",
"position",
",",
"axis",
",",
"precision",
"=",
"1e-3",
",",
"layer",
"=",
"0",
",",
"datatype",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"layer",
",",
"list",
")",
":",
"layer",
"=",
"[",
"layer",
... | 35.645161 | 0.00044 |
def _process_hdu (self, hdu):
"We've hacked the load order a bit to get t0 and mjd0 in _process_main()."
if hdu.name == 'EVENTS':
pass
else:
super (Events, self)._process_hdu (hdu) | [
"def",
"_process_hdu",
"(",
"self",
",",
"hdu",
")",
":",
"if",
"hdu",
".",
"name",
"==",
"'EVENTS'",
":",
"pass",
"else",
":",
"super",
"(",
"Events",
",",
"self",
")",
".",
"_process_hdu",
"(",
"hdu",
")"
] | 31.857143 | 0.026201 |
def schema(name, dct, *, strict=False):
"""Create a compound tag schema.
This function is a short convenience function that makes it easy to
subclass the base `CompoundSchema` class.
The `name` argument is the name of the class and `dct` should be a
dictionnary containing the actual schema.... | [
"def",
"schema",
"(",
"name",
",",
"dct",
",",
"*",
",",
"strict",
"=",
"False",
")",
":",
"return",
"type",
"(",
"name",
",",
"(",
"CompoundSchema",
",",
")",
",",
"{",
"'__slots__'",
":",
"(",
")",
",",
"'schema'",
":",
"dct",
",",
"'strict'",
... | 42.3125 | 0.001445 |
def route_delete(name, route_table, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Delete a route from a route table.
:param name: The route to delete.
:param route_table: The route table containing the route.
:param resource_group: The resource group name assigned to the
... | [
"def",
"route_delete",
"(",
"name",
",",
"route_table",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",... | 25.441176 | 0.001114 |
def handle_uploaded_files(uploaded_files):
"""Handles downstream processes using metadata
about the uploaded files from React side."""
if uploaded_files:
uploaded_files = json.loads(uploaded_files)[0]
_id = uploaded_files.get('id')
# Strip extension from filename
_filename = ... | [
"def",
"handle_uploaded_files",
"(",
"uploaded_files",
")",
":",
"if",
"uploaded_files",
":",
"uploaded_files",
"=",
"json",
".",
"loads",
"(",
"uploaded_files",
")",
"[",
"0",
"]",
"_id",
"=",
"uploaded_files",
".",
"get",
"(",
"'id'",
")",
"# Strip extension... | 31.322581 | 0.000999 |
def compare_words_lexicographic( word_a, word_b ):
""" compare words in Tamil lexicographic order """
# sanity check for words to be all Tamil
if ( not all_tamil(word_a) ) or (not all_tamil(word_b)) :
#print("## ")
#print(word_a)
#print(word_b)
#print("Both operands need to b... | [
"def",
"compare_words_lexicographic",
"(",
"word_a",
",",
"word_b",
")",
":",
"# sanity check for words to be all Tamil",
"if",
"(",
"not",
"all_tamil",
"(",
"word_a",
")",
")",
"or",
"(",
"not",
"all_tamil",
"(",
"word_b",
")",
")",
":",
"#print(\"## \")",
"#pr... | 35.909091 | 0.027127 |
def compute_one_decoding_video_metrics(iterator, feed_dict, num_videos):
"""Computes the average of all the metric for one decoding.
Args:
iterator: dataset iterator.
feed_dict: feed dict to initialize iterator.
num_videos: number of videos.
Returns:
all_psnr: 2-D Numpy array, shape=(num_samples... | [
"def",
"compute_one_decoding_video_metrics",
"(",
"iterator",
",",
"feed_dict",
",",
"num_videos",
")",
":",
"output",
",",
"target",
"=",
"iterator",
".",
"get_next",
"(",
")",
"metrics",
"=",
"psnr_and_ssim",
"(",
"output",
",",
"target",
")",
"with",
"tf",
... | 33.066667 | 0.009794 |
def is_not_none(entity, prop, name):
"bool: True if the value of a property is not None."
return is_not_empty(entity, prop, name) and name in entity._data and getattr(entity, name) is not None | [
"def",
"is_not_none",
"(",
"entity",
",",
"prop",
",",
"name",
")",
":",
"return",
"is_not_empty",
"(",
"entity",
",",
"prop",
",",
"name",
")",
"and",
"name",
"in",
"entity",
".",
"_data",
"and",
"getattr",
"(",
"entity",
",",
"name",
")",
"is",
"no... | 66 | 0.01 |
def extract(self, progress = True, recurse = True, tex_only = False,
extract_manifest = False, path = None, **kwargs):
if path is None:
path = self.folder_out
if tex_only:
kwargs['use_cache'] = False
utils.mkdir_silent(path)
utime(path, (self.time, sel... | [
"def",
"extract",
"(",
"self",
",",
"progress",
"=",
"True",
",",
"recurse",
"=",
"True",
",",
"tex_only",
"=",
"False",
",",
"extract_manifest",
"=",
"False",
",",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
"is",
"None",
... | 42.6 | 0.009178 |
def _send_broker_aware_request(self, payloads, encoder_fn, decoder_fn):
"""
Group a list of request payloads by topic+partition and send them to
the leader broker for that partition using the supplied encode/decode
functions
Arguments:
payloads: list of object-like enti... | [
"def",
"_send_broker_aware_request",
"(",
"self",
",",
"payloads",
",",
"encoder_fn",
",",
"decoder_fn",
")",
":",
"# encoders / decoders do not maintain ordering currently",
"# so we need to keep this so we can rebuild order before returning",
"original_ordering",
"=",
"[",
"(",
... | 44.666667 | 0.000712 |
def to_avro(file_path_or_buffer, df, schema=None, codec='null', append=False):
"""
Avro file writer.
Args:
file_path_or_buffer:
Output file path or file-like object.
df: pd.DataFrame.
schema: Dict of Avro schema.
If it's set None, inferring schema.
ap... | [
"def",
"to_avro",
"(",
"file_path_or_buffer",
",",
"df",
",",
"schema",
"=",
"None",
",",
"codec",
"=",
"'null'",
",",
"append",
"=",
"False",
")",
":",
"if",
"schema",
"is",
"None",
":",
"schema",
"=",
"__schema_infer",
"(",
"df",
")",
"open_mode",
"=... | 37.448276 | 0.001795 |
def compress(condition, data, axis=0, out=None, blen=None, storage=None, create='array',
**kwargs):
"""Return selected slices of an array along given axis."""
# setup
if out is not None:
# argument is only there for numpy API compatibility
raise NotImplementedError('out argumen... | [
"def",
"compress",
"(",
"condition",
",",
"data",
",",
"axis",
"=",
"0",
",",
"out",
"=",
"None",
",",
"blen",
"=",
"None",
",",
"storage",
"=",
"None",
",",
"create",
"=",
"'array'",
",",
"*",
"*",
"kwargs",
")",
":",
"# setup",
"if",
"out",
"is... | 32.86 | 0.001773 |
def parse_json(pairs):
"""
modified from:
https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-from-json#34796078
pass this to the object_pairs_hook kwarg of json.load/loads
"""
new_pairs = []
for key, value in pairs:
if isinstance(value, unicode):... | [
"def",
"parse_json",
"(",
"pairs",
")",
":",
"new_pairs",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"pairs",
":",
"if",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"i... | 32.6 | 0.001988 |
def import_(zpool=None, new_name=None, **kwargs):
'''
.. versionadded:: 2015.5.0
Import storage pools or list pools available for import
zpool : string
Optional name of storage pool
new_name : string
Optional new name for the storage pool
mntopts : string
Comma-separa... | [
"def",
"import_",
"(",
"zpool",
"=",
"None",
",",
"new_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"## Configure pool",
"# NOTE: initialize the defaults",
"flags",
"=",
"[",
"]",
"opts",
"=",
"{",
"}",
"target",
"=",
"[",
"]",
"# NOTE: push pool... | 31.173554 | 0.001799 |
def remove_headerReference(self, type_):
"""Return rId of w:headerReference child of *type_* after removing it."""
headerReference = self.get_headerReference(type_)
rId = headerReference.rId
self.remove(headerReference)
return rId | [
"def",
"remove_headerReference",
"(",
"self",
",",
"type_",
")",
":",
"headerReference",
"=",
"self",
".",
"get_headerReference",
"(",
"type_",
")",
"rId",
"=",
"headerReference",
".",
"rId",
"self",
".",
"remove",
"(",
"headerReference",
")",
"return",
"rId"
... | 44.166667 | 0.011111 |
def _add_gene_associations(self, r_id, r_genes, gene_ids, r_tag):
"""Adds all the different kinds of genes into a list."""
genes = ET.SubElement(
r_tag, _tag('geneProductAssociation', FBC_V2))
if isinstance(r_genes, list):
e = Expression(And(*(Variable(i) for i in r_genes... | [
"def",
"_add_gene_associations",
"(",
"self",
",",
"r_id",
",",
"r_genes",
",",
"gene_ids",
",",
"r_tag",
")",
":",
"genes",
"=",
"ET",
".",
"SubElement",
"(",
"r_tag",
",",
"_tag",
"(",
"'geneProductAssociation'",
",",
"FBC_V2",
")",
")",
"if",
"isinstanc... | 48.961538 | 0.001541 |
def make_pkh_output_script(pubkey, witness=False):
'''
bytearray -> bytearray
'''
if witness and not riemann.network.SEGWIT:
raise ValueError(
'Network {} does not support witness scripts.'
.format(riemann.get_current_network_name()))
output_script = bytearray()
... | [
"def",
"make_pkh_output_script",
"(",
"pubkey",
",",
"witness",
"=",
"False",
")",
":",
"if",
"witness",
"and",
"not",
"riemann",
".",
"network",
".",
"SEGWIT",
":",
"raise",
"ValueError",
"(",
"'Network {} does not support witness scripts.'",
".",
"format",
"(",
... | 34.68 | 0.001122 |
def post_url(self):
"""
Determine which page this post lives on within the topic
and return link to anchor within that page
"""
topic = self.topic
topic_page = topic.post_set.filter(id__lt=self.id).count() / get_paginate_by() + 1
return "{0}page{1}/#post-{2... | [
"def",
"post_url",
"(",
"self",
")",
":",
"topic",
"=",
"self",
".",
"topic",
"topic_page",
"=",
"topic",
".",
"post_set",
".",
"filter",
"(",
"id__lt",
"=",
"self",
".",
"id",
")",
".",
"count",
"(",
")",
"/",
"get_paginate_by",
"(",
")",
"+",
"1"... | 45.75 | 0.010724 |
def find_vasp_calculations():
"""
Returns a list of all subdirectories that contain either a vasprun.xml file
or a compressed vasprun.xml.gz file.
Args:
None
Returns:
(List): list of all VASP calculation subdirectories.
"""
dir_list = [ './' + re.sub( r'vasprun\.xml', '', p... | [
"def",
"find_vasp_calculations",
"(",
")",
":",
"dir_list",
"=",
"[",
"'./'",
"+",
"re",
".",
"sub",
"(",
"r'vasprun\\.xml'",
",",
"''",
",",
"path",
")",
"for",
"path",
"in",
"glob",
".",
"iglob",
"(",
"'**/vasprun.xml'",
",",
"recursive",
"=",
"True",
... | 38.428571 | 0.027223 |
def edge(s, path, edge, alpha=1.0):
""" Visualization of a single edge between two nodes.
"""
path.moveto(edge.node1.x, edge.node1.y)
if edge.node2.style == BACK:
path.curveto(
edge.node1.x,
edge.node2.y,
edge.node2.x,
edge.node2.y,
... | [
"def",
"edge",
"(",
"s",
",",
"path",
",",
"edge",
",",
"alpha",
"=",
"1.0",
")",
":",
"path",
".",
"moveto",
"(",
"edge",
".",
"node1",
".",
"x",
",",
"edge",
".",
"node1",
".",
"y",
")",
"if",
"edge",
".",
"node2",
".",
"style",
"==",
"BACK... | 22.9 | 0.010482 |
def _compute_zones_sizes(self):
"""Compute panel zone sizes."""
# Left panels
left = 0
for panel in self.panels_for_zone(Panel.Position.LEFT):
if not panel.isVisible():
continue
size_hint = panel.sizeHint()
left += size_hint.width()
... | [
"def",
"_compute_zones_sizes",
"(",
"self",
")",
":",
"# Left panels",
"left",
"=",
"0",
"for",
"panel",
"in",
"self",
".",
"panels_for_zone",
"(",
"Panel",
".",
"Position",
".",
"LEFT",
")",
":",
"if",
"not",
"panel",
".",
"isVisible",
"(",
")",
":",
... | 35.393939 | 0.001667 |
def _build_command(self):
"""
Command to start the IOU process.
(to be passed to subprocess.Popen())
IOU command line:
Usage: <image> [options] <application id>
<image>: unix-js-m | unix-is-m | unix-i-m | ...
<application id>: instance identifier (0 < id <= 1024)... | [
"def",
"_build_command",
"(",
"self",
")",
":",
"command",
"=",
"[",
"self",
".",
"_path",
"]",
"if",
"len",
"(",
"self",
".",
"_ethernet_adapters",
")",
"!=",
"2",
":",
"command",
".",
"extend",
"(",
"[",
"\"-e\"",
",",
"str",
"(",
"len",
"(",
"se... | 42.583333 | 0.001435 |
def _filter_kwargs(names, dict_):
"""Filter out kwargs from a dictionary.
Parameters
----------
names : set[str]
The names to select from ``dict_``.
dict_ : dict[str, any]
The dictionary to select from.
Returns
-------
kwargs : dict[str, any]
``dict_`` where the... | [
"def",
"_filter_kwargs",
"(",
"names",
",",
"dict_",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"dict_",
".",
"items",
"(",
")",
"if",
"k",
"in",
"names",
"and",
"v",
"is",
"not",
"None",
"}"
] | 26.764706 | 0.002123 |
def from_df(cls, path:PathOrStr, train_df:DataFrame, valid_df:DataFrame, test_df:Optional[DataFrame]=None,
tokenizer:Tokenizer=None, vocab:Vocab=None, classes:Collection[str]=None, text_cols:IntsOrStrs=1,
label_cols:IntsOrStrs=0, label_delim:str=None, chunksize:int=10000, max_vocab:int=6... | [
"def",
"from_df",
"(",
"cls",
",",
"path",
":",
"PathOrStr",
",",
"train_df",
":",
"DataFrame",
",",
"valid_df",
":",
"DataFrame",
",",
"test_df",
":",
"Optional",
"[",
"DataFrame",
"]",
"=",
"None",
",",
"tokenizer",
":",
"Tokenizer",
"=",
"None",
",",
... | 88.882353 | 0.043877 |
def connect(self, callback, weak=False):
"""
Connects a new callback to this signal.
:param callback: The callback to connect.
:param weak: If `True`, only holds a weak reference to the specified
callback.
`callback` will be called whenever `emit` gets called on the... | [
"def",
"connect",
"(",
"self",
",",
"callback",
",",
"weak",
"=",
"False",
")",
":",
"if",
"weak",
":",
"callback",
"=",
"ref",
"(",
"callback",
",",
"self",
".",
"_callbacks",
".",
"remove",
")",
"self",
".",
"_callbacks",
".",
"append",
"(",
"callb... | 36.5 | 0.001779 |
def any_datetime_field(field, **kwargs):
"""
Return random value for DateTimeField,
skips auto_now and auto_now_add fields
>>> result = any_field(models.DateTimeField())
>>> type(result)
<type 'datetime.datetime'>
"""
from_date = kwargs.get('from_date', datetime(1990, 1, 1))
... | [
"def",
"any_datetime_field",
"(",
"field",
",",
"*",
"*",
"kwargs",
")",
":",
"from_date",
"=",
"kwargs",
".",
"get",
"(",
"'from_date'",
",",
"datetime",
"(",
"1990",
",",
"1",
",",
"1",
")",
")",
"to_date",
"=",
"kwargs",
".",
"get",
"(",
"'to_date... | 35.833333 | 0.002268 |
def map(kvs: Mapping[K, V], meta=None) -> Map[K, V]: # pylint:disable=redefined-builtin
"""Creates a new map."""
return Map(pmap(initial=kvs), meta=meta) | [
"def",
"map",
"(",
"kvs",
":",
"Mapping",
"[",
"K",
",",
"V",
"]",
",",
"meta",
"=",
"None",
")",
"->",
"Map",
"[",
"K",
",",
"V",
"]",
":",
"# pylint:disable=redefined-builtin",
"return",
"Map",
"(",
"pmap",
"(",
"initial",
"=",
"kvs",
")",
",",
... | 53.333333 | 0.012346 |
def invert(self,nz,A,C):
"""
Inversion and resolution of a tridiagonal matrix
A X = C
Input:
nz number of layers
a(*,1) lower diagonal (Ai,i-1)
a(*,2) principal diagonal (Ai,i)
a(*,3) upper diagonal (Ai,i+1)
c
Output
... | [
"def",
"invert",
"(",
"self",
",",
"nz",
",",
"A",
",",
"C",
")",
":",
"X",
"=",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"nz",
")",
"]",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"nz",
"-",
"1",
")",
")",
":",
"C",
"[",
"i",
"]... | 25.074074 | 0.01138 |
def haarpsi_weight_map(img1, img2, axis):
r"""Weighting map for directional features along an axis.
Parameters
----------
img1, img2 : array-like
The images to compare. They must have equal shape.
axis : {0, 1}
Direction in which to look for edge similarities.
Returns
-----... | [
"def",
"haarpsi_weight_map",
"(",
"img1",
",",
"img2",
",",
"axis",
")",
":",
"# TODO: generalize for nD",
"impl",
"=",
"'pyfftw'",
"if",
"PYFFTW_AVAILABLE",
"else",
"'numpy'",
"# Haar wavelet filters for level 3",
"dec_lo_lvl3",
"=",
"np",
".",
"repeat",
"(",
"[",
... | 32.056338 | 0.000426 |
def _run_command(self, ssh, cmd, pty=True):
"""Run a command remotely via SSH.
:param object ssh: The SSHClient
:param str cmd: The command to execute
:param list cmd: The `shlex.split` command to execute
:param bool pty: Whether to allocate a pty
:return: tuple: The st... | [
"def",
"_run_command",
"(",
"self",
",",
"ssh",
",",
"cmd",
",",
"pty",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"cmd",
",",
"str",
")",
":",
"cmd",
"=",
"shlex",
".",
"split",
"(",
"cmd",
")",
"if",
"type",
"(",
"cmd",
")",
"is",
"not",... | 33.366667 | 0.001942 |
def get_provisioned_gsi_write_units(table_name, gsi_name):
""" Returns the number of provisioned write units for the table
:type table_name: str
:param table_name: Name of the DynamoDB table
:type gsi_name: str
:param gsi_name: Name of the GSI
:returns: int -- Number of write units
"""
... | [
"def",
"get_provisioned_gsi_write_units",
"(",
"table_name",
",",
"gsi_name",
")",
":",
"try",
":",
"desc",
"=",
"DYNAMODB_CONNECTION",
".",
"describe_table",
"(",
"table_name",
")",
"except",
"JSONResponseError",
":",
"raise",
"for",
"gsi",
"in",
"desc",
"[",
"... | 33.041667 | 0.001225 |
def copyError(self, to):
"""Save the original error to the new place. """
if to is None: to__o = None
else: to__o = to._o
ret = libxml2mod.xmlCopyError(self._o, to__o)
return ret | [
"def",
"copyError",
"(",
"self",
",",
"to",
")",
":",
"if",
"to",
"is",
"None",
":",
"to__o",
"=",
"None",
"else",
":",
"to__o",
"=",
"to",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlCopyError",
"(",
"self",
".",
"_o",
",",
"to__o",
")",
"retu... | 35.5 | 0.018349 |
def maybe_a(generator):
"""
Generates either an arbitrary value of the specified generator or None.
This is a class factory, it makes a class which is a closure around the
specified generator.
"""
class MaybeAGenerator(ArbitraryInterface):
"""
A closure class around the generato... | [
"def",
"maybe_a",
"(",
"generator",
")",
":",
"class",
"MaybeAGenerator",
"(",
"ArbitraryInterface",
")",
":",
"\"\"\"\n A closure class around the generator specified above, which generates\n either that generator or None.\n \"\"\"",
"@",
"classmethod",
"def",
"... | 31.181818 | 0.001414 |
def _parseTlsDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the TLS directory.
@type rva: int
@param rva: The RVA where the TLS directory starts.
@type size: int
@param size: The size of the TLS directory.
@type magic: int
... | [
"def",
"_parseTlsDirectory",
"(",
"self",
",",
"rva",
",",
"size",
",",
"magic",
"=",
"consts",
".",
"PE32",
")",
":",
"data",
"=",
"self",
".",
"getDataAtRva",
"(",
"rva",
",",
"size",
")",
"rd",
"=",
"utils",
".",
"ReadData",
"(",
"data",
")",
"i... | 35.730769 | 0.013627 |
def analisar_retorno(retorno,
classe_resposta=RespostaSAT, campos=RespostaSAT.CAMPOS,
campos_alternativos=[], funcao=None, manter_verbatim=True):
"""Analisa o retorno (supostamente um retorno de uma função do SAT) conforme
o padrão e campos esperados. O retorno deverá possuir dados separados ent... | [
"def",
"analisar_retorno",
"(",
"retorno",
",",
"classe_resposta",
"=",
"RespostaSAT",
",",
"campos",
"=",
"RespostaSAT",
".",
"CAMPOS",
",",
"campos_alternativos",
"=",
"[",
"]",
",",
"funcao",
"=",
"None",
",",
"manter_verbatim",
"=",
"True",
")",
":",
"if... | 38.617021 | 0.002417 |
def wrap_text(paragraph, line_count, min_char_per_line=0):
"""Wraps the given text to the specified number of lines."""
one_string = strip_all_white_space(paragraph)
if min_char_per_line:
lines = wrap(one_string, width=min_char_per_line)
try:
return lines[:line_count]
except IndexError:
return lines
els... | [
"def",
"wrap_text",
"(",
"paragraph",
",",
"line_count",
",",
"min_char_per_line",
"=",
"0",
")",
":",
"one_string",
"=",
"strip_all_white_space",
"(",
"paragraph",
")",
"if",
"min_char_per_line",
":",
"lines",
"=",
"wrap",
"(",
"one_string",
",",
"width",
"="... | 33.272727 | 0.029255 |
def alpha_from_cov(plotman, alpha_cov):
'''Calculate alpha values from the coverage/2.5.
'''
abscov = np.abs(load_cov('inv/coverage.mag'))
if alpha_cov:
normcov = np.divide(abscov, 2.5)
normcov[np.where(normcov > 1)] = 1
mask = np.subtract(1, normcov)
alpha = plotman.parm... | [
"def",
"alpha_from_cov",
"(",
"plotman",
",",
"alpha_cov",
")",
":",
"abscov",
"=",
"np",
".",
"abs",
"(",
"load_cov",
"(",
"'inv/coverage.mag'",
")",
")",
"if",
"alpha_cov",
":",
"normcov",
"=",
"np",
".",
"divide",
"(",
"abscov",
",",
"2.5",
")",
"no... | 35.333333 | 0.002299 |
def ethnicities_clean():
""" Get dictionary of unformatted ethnicity types mapped to clean corresponding ethnicity strings """
eths_clean = {}
fname = pkg_resources.resource_filename(__name__, 'resources/Ethnicity_Groups.csv')
with open(fname, 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')... | [
"def",
"ethnicities_clean",
"(",
")",
":",
"eths_clean",
"=",
"{",
"}",
"fname",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"__name__",
",",
"'resources/Ethnicity_Groups.csv'",
")",
"with",
"open",
"(",
"fname",
",",
"'rU'",
")",
"as",
"csvfile",
":"... | 32.411765 | 0.022928 |
def _Liquid(T, P=0.1):
"""Supplementary release on properties of liquid water at 0.1 MPa
Parameters
----------
T : float
Temperature, [K]
P : float
Pressure, [MPa]
Although this relation is for P=0.1MPa, can be extrapoled at pressure
0.3 MPa
Returns
-------
... | [
"def",
"_Liquid",
"(",
"T",
",",
"P",
"=",
"0.1",
")",
":",
"# Check input in range of validity",
"if",
"T",
"<=",
"253.15",
"or",
"T",
">=",
"383.15",
"or",
"P",
"<",
"0.1",
"or",
"P",
">",
"0.3",
":",
"raise",
"NotImplementedError",
"(",
"\"Incoming ou... | 33.829545 | 0.000163 |
def load_models_using_filepattern(
self, filename_pattern, model, glob_args, is_main_model=False,
encoding='utf-8', add_to_local_models=True):
"""
add a new model to all relevant objects
Args:
filename_pattern: models to be loaded
model: model hol... | [
"def",
"load_models_using_filepattern",
"(",
"self",
",",
"filename_pattern",
",",
"model",
",",
"glob_args",
",",
"is_main_model",
"=",
"False",
",",
"encoding",
"=",
"'utf-8'",
",",
"add_to_local_models",
"=",
"True",
")",
":",
"if",
"(",
"model",
")",
":",
... | 41.172414 | 0.001637 |
def run(self):
""" Listen to the stream and send events to the client. """
channel = self._ssh_client.get_transport().open_session()
self._channel = channel
channel.exec_command("gerrit stream-events")
stdout = channel.makefile()
stderr = channel.makefile_stderr()
... | [
"def",
"run",
"(",
"self",
")",
":",
"channel",
"=",
"self",
".",
"_ssh_client",
".",
"get_transport",
"(",
")",
".",
"open_session",
"(",
")",
"self",
".",
"_channel",
"=",
"channel",
"channel",
".",
"exec_command",
"(",
"\"gerrit stream-events\"",
")",
"... | 42.318182 | 0.002101 |
def _commandline(self, *args, **kwargs):
"""Returns the command line (without pipes) as a list."""
# transform_args() is a hook (used in GromacsCommand very differently!)
return [self.command_name] + self.transform_args(*args, **kwargs) | [
"def",
"_commandline",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# transform_args() is a hook (used in GromacsCommand very differently!)",
"return",
"[",
"self",
".",
"command_name",
"]",
"+",
"self",
".",
"transform_args",
"(",
"*",
"args... | 64.5 | 0.019157 |
def solve_coupled_ecc_solution(F0, e0, gamma0, phase0, mc, q, t):
"""
Compute the solution to the coupled system of equations
from from Peters (1964) and Barack & Cutler (2004) at
a given time.
:param F0: Initial orbital frequency [Hz]
:param e0: Initial orbital eccentricity
:param gam... | [
"def",
"solve_coupled_ecc_solution",
"(",
"F0",
",",
"e0",
",",
"gamma0",
",",
"phase0",
",",
"mc",
",",
"q",
",",
"t",
")",
":",
"y0",
"=",
"np",
".",
"array",
"(",
"[",
"F0",
",",
"e0",
",",
"gamma0",
",",
"phase0",
"]",
")",
"y",
",",
"infod... | 29.888889 | 0.012005 |
def get_range_by_effective_partition_key(self, effective_partition_key_value):
"""Gets the range containing the given partition key
:param str effective_partition_key_value:
The partition key value.
:return:
The partition key range.
:rtype: dict
"""
... | [
"def",
"get_range_by_effective_partition_key",
"(",
"self",
",",
"effective_partition_key_value",
")",
":",
"if",
"_CollectionRoutingMap",
".",
"MinimumInclusiveEffectivePartitionKey",
"==",
"effective_partition_key_value",
":",
"return",
"self",
".",
"_orderedPartitionKeyRanges"... | 41.666667 | 0.010056 |
def clinical_kernel(x, y=None):
"""Computes clinical kernel
The clinical kernel distinguishes between continuous
ordinal,and nominal variables.
Parameters
----------
x : pandas.DataFrame, shape = (n_samples_x, n_features)
Training data
y : pandas.DataFrame, shape = (n_samples_y, n... | [
"def",
"clinical_kernel",
"(",
"x",
",",
"y",
"=",
"None",
")",
":",
"if",
"y",
"is",
"not",
"None",
":",
"if",
"x",
".",
"shape",
"[",
"1",
"]",
"!=",
"y",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'x and y have different numb... | 30.702128 | 0.001343 |
def _next(self):
"""Get the next summary and present it."""
self.summaries.rotate(-1)
current_summary = self.summaries[0]
self._update_summary(current_summary) | [
"def",
"_next",
"(",
"self",
")",
":",
"self",
".",
"summaries",
".",
"rotate",
"(",
"-",
"1",
")",
"current_summary",
"=",
"self",
".",
"summaries",
"[",
"0",
"]",
"self",
".",
"_update_summary",
"(",
"current_summary",
")"
] | 37.4 | 0.010471 |
def chunk(self, chunks=None, name_prefix='xarray-', token=None,
lock=False):
"""Coerce all arrays in this dataset into dask arrays with the given
chunks.
Non-dask arrays in this dataset will be converted to dask arrays. Dask
arrays will be rechunked to the given chunk size... | [
"def",
"chunk",
"(",
"self",
",",
"chunks",
"=",
"None",
",",
"name_prefix",
"=",
"'xarray-'",
",",
"token",
"=",
"None",
",",
"lock",
"=",
"False",
")",
":",
"try",
":",
"from",
"dask",
".",
"base",
"import",
"tokenize",
"except",
"ImportError",
":",
... | 37.53125 | 0.001217 |
def notify(title,
message,
prio='ALERT',
facility='LOCAL5',
fmt='[{title}] {message}',
retcode=None):
"""
Uses the ``syslog`` core Python module, which is not available on Windows
platforms.
Optional parameters:
* ``prio`` - Syslog prority ... | [
"def",
"notify",
"(",
"title",
",",
"message",
",",
"prio",
"=",
"'ALERT'",
",",
"facility",
"=",
"'LOCAL5'",
",",
"fmt",
"=",
"'[{title}] {message}'",
",",
"retcode",
"=",
"None",
")",
":",
"prio_map",
"=",
"{",
"'EMERG'",
":",
"syslog",
".",
"LOG_EMERG... | 25.574468 | 0.0004 |
def flatten(l, types=(list, float)):
"""
Flat nested list of lists into a single list.
"""
l = [item if isinstance(item, types) else [item] for item in l]
return [item for sublist in l for item in sublist] | [
"def",
"flatten",
"(",
"l",
",",
"types",
"=",
"(",
"list",
",",
"float",
")",
")",
":",
"l",
"=",
"[",
"item",
"if",
"isinstance",
"(",
"item",
",",
"types",
")",
"else",
"[",
"item",
"]",
"for",
"item",
"in",
"l",
"]",
"return",
"[",
"item",
... | 36.666667 | 0.013333 |
def nodeListGetString(self, list, inLine):
"""Build the string equivalent to the text contained in the
Node list made of TEXTs and ENTITY_REFs """
if list is None: list__o = None
else: list__o = list._o
ret = libxml2mod.xmlNodeListGetString(self._o, list__o, inLine)
re... | [
"def",
"nodeListGetString",
"(",
"self",
",",
"list",
",",
"inLine",
")",
":",
"if",
"list",
"is",
"None",
":",
"list__o",
"=",
"None",
"else",
":",
"list__o",
"=",
"list",
".",
"_o",
"ret",
"=",
"libxml2mod",
".",
"xmlNodeListGetString",
"(",
"self",
... | 46 | 0.012195 |
def compile(self):
'''
This function aims at giving every operator enough information so that all operator conversions can happen
independently. We also want to check, fix, and simplify the network structure here.
'''
self._prune()
self._resolve_duplicates()
self.... | [
"def",
"compile",
"(",
"self",
")",
":",
"self",
".",
"_prune",
"(",
")",
"self",
".",
"_resolve_duplicates",
"(",
")",
"self",
".",
"_fix_shapes",
"(",
")",
"self",
".",
"_infer_all_types",
"(",
")",
"self",
".",
"_check_structure",
"(",
")"
] | 38.8 | 0.010076 |
def simple_interaction(snps,pheno,Inter,Inter0=None,covs = None,K=None,test='lrt'):
"""
I-variate fixed effects interaction test for phenotype specific SNP effects
Args:
snps: [N x S] SP.array of S SNPs for N individuals (test SNPs)
pheno: [N x 1] SP.array of 1 phenotype for N individual... | [
"def",
"simple_interaction",
"(",
"snps",
",",
"pheno",
",",
"Inter",
",",
"Inter0",
"=",
"None",
",",
"covs",
"=",
"None",
",",
"K",
"=",
"None",
",",
"test",
"=",
"'lrt'",
")",
":",
"N",
"=",
"snps",
".",
"shape",
"[",
"0",
"]",
"if",
"covs",
... | 39.409091 | 0.015757 |
def parse_value(self, value):
"""Cast value to `bool`."""
parsed = super(BoolField, self).parse_value(value)
return bool(parsed) if parsed is not None else None | [
"def",
"parse_value",
"(",
"self",
",",
"value",
")",
":",
"parsed",
"=",
"super",
"(",
"BoolField",
",",
"self",
")",
".",
"parse_value",
"(",
"value",
")",
"return",
"bool",
"(",
"parsed",
")",
"if",
"parsed",
"is",
"not",
"None",
"else",
"None"
] | 45.25 | 0.01087 |
def _calc_jaccard(
markers1: dict,
markers2: dict,
):
"""Calculate jaccard index between the values of two dictionaries
Note: dict values must be sets
"""
jacc_results=np.zeros((len(markers1), len(markers2)))
j=0
for marker_group in markers1:
tmp = [len(markers2[i].intersection... | [
"def",
"_calc_jaccard",
"(",
"markers1",
":",
"dict",
",",
"markers2",
":",
"dict",
",",
")",
":",
"jacc_results",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"markers1",
")",
",",
"len",
"(",
"markers2",
")",
")",
")",
"j",
"=",
"0",
"for",
"... | 27.166667 | 0.011858 |
def RegisterLateBindingCallback(target_name, callback, **kwargs):
"""Registers a callback to be invoked when the RDFValue named is declared."""
_LATE_BINDING_STORE.setdefault(target_name, []).append((callback, kwargs)) | [
"def",
"RegisterLateBindingCallback",
"(",
"target_name",
",",
"callback",
",",
"*",
"*",
"kwargs",
")",
":",
"_LATE_BINDING_STORE",
".",
"setdefault",
"(",
"target_name",
",",
"[",
"]",
")",
".",
"append",
"(",
"(",
"callback",
",",
"kwargs",
")",
")"
] | 73.333333 | 0.013514 |
def sweep(self):
"""
Runs through entire dataset.
Returns TSS error, total correct, total count, pcorrect (a dict of layer data)
"""
self.preSweep()
if self.loadOrder == []:
raise NetworkError('No loadOrder for the inputs. Make sure inputs are properly set.',... | [
"def",
"sweep",
"(",
"self",
")",
":",
"self",
".",
"preSweep",
"(",
")",
"if",
"self",
".",
"loadOrder",
"==",
"[",
"]",
":",
"raise",
"NetworkError",
"(",
"'No loadOrder for the inputs. Make sure inputs are properly set.'",
",",
"self",
".",
"loadOrder",
")",
... | 52.545455 | 0.009342 |
def update(request, ident, stateless=False, **kwargs):
'Generate update json response'
dash_app, app = DashApp.locate_item(ident, stateless)
request_body = json.loads(request.body.decode('utf-8'))
if app.use_dash_dispatch():
# Force call through dash
view_func = app.locate_endpoint_fun... | [
"def",
"update",
"(",
"request",
",",
"ident",
",",
"stateless",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"dash_app",
",",
"app",
"=",
"DashApp",
".",
"locate_item",
"(",
"ident",
",",
"stateless",
")",
"request_body",
"=",
"json",
".",
"loads"... | 34.219512 | 0.002079 |
def __neighbor_indexes_points(self, optic_object):
"""!
@brief Return neighbors of the specified object in case of sequence of points.
@param[in] optic_object (optics_descriptor): Object for which neighbors should be returned in line with connectivity radius.
@return (list) List ... | [
"def",
"__neighbor_indexes_points",
"(",
"self",
",",
"optic_object",
")",
":",
"kdnodes",
"=",
"self",
".",
"__kdtree",
".",
"find_nearest_dist_nodes",
"(",
"self",
".",
"__sample_pointer",
"[",
"optic_object",
".",
"index_object",
"]",
",",
"self",
".",
"__eps... | 55.333333 | 0.01037 |
def elem_add(self, idx=None, name=None, **kwargs):
"""
Add an element of this model
:param idx: element idx
:param name: element name
:param kwargs: keyword arguments of the parameters
:return: allocated idx
"""
idx = self.system.devman.register_element(... | [
"def",
"elem_add",
"(",
"self",
",",
"idx",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"idx",
"=",
"self",
".",
"system",
".",
"devman",
".",
"register_element",
"(",
"dev_name",
"=",
"self",
".",
"_name",
",",
"idx",... | 31.704918 | 0.001003 |
def collapse_addresses(addresses):
"""Collapse a list of IP objects.
Example:
collapse_addresses([IPv4Network('192.0.2.0/25'),
IPv4Network('192.0.2.128/25')]) ->
[IPv4Network('192.0.2.0/24')]
Args:
addresses: An iterator of IPv4Network... | [
"def",
"collapse_addresses",
"(",
"addresses",
")",
":",
"i",
"=",
"0",
"addrs",
"=",
"[",
"]",
"ips",
"=",
"[",
"]",
"nets",
"=",
"[",
"]",
"# split IP addresses and networks",
"for",
"ip",
"in",
"addresses",
":",
"if",
"isinstance",
"(",
"ip",
",",
"... | 32 | 0.000551 |
def add_permission_view_menu(self, permission_name, view_menu_name):
"""
Adds a permission on a view or menu to the backend
:param permission_name:
name of the permission to add: 'can_add','can_edit' etc...
:param view_menu_name:
name of the v... | [
"def",
"add_permission_view_menu",
"(",
"self",
",",
"permission_name",
",",
"view_menu_name",
")",
":",
"if",
"not",
"(",
"permission_name",
"and",
"view_menu_name",
")",
":",
"return",
"None",
"pv",
"=",
"self",
".",
"find_permission_view_menu",
"(",
"permission... | 36.586207 | 0.001837 |
def _custom_validate(self, verify, trust_bundle):
"""
Called when we have set custom validation. We do this in two cases:
first, when cert validation is entirely disabled; and second, when
using a custom trust DB.
"""
# If we disabled cert validation, just say: cool.
... | [
"def",
"_custom_validate",
"(",
"self",
",",
"verify",
",",
"trust_bundle",
")",
":",
"# If we disabled cert validation, just say: cool.",
"if",
"not",
"verify",
":",
"return",
"# We want data in memory, so load it up.",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"t... | 36.163934 | 0.000883 |
def fstab(jail):
'''
Display contents of a fstab(5) file defined in specified
jail's configuration. If no file is defined, return False.
CLI Example:
.. code-block:: bash
salt '*' jail.fstab <jail name>
'''
ret = []
config = show_config(jail)
if 'fstab' in config:
... | [
"def",
"fstab",
"(",
"jail",
")",
":",
"ret",
"=",
"[",
"]",
"config",
"=",
"show_config",
"(",
"jail",
")",
"if",
"'fstab'",
"in",
"config",
":",
"c_fstab",
"=",
"config",
"[",
"'fstab'",
"]",
"elif",
"'mount.fstab'",
"in",
"config",
":",
"c_fstab",
... | 32.860465 | 0.000687 |
def get_var_name(nc):
"""Guesses the variable_name of an open NetCDF file
"""
non_variable_names = [
'lat',
'lat_bnds',
'lon',
'lon_bnds',
'time',
'latitude',
'longitude',
'bnds'
]
_vars = set(nc.variables.keys())
_vars.difference... | [
"def",
"get_var_name",
"(",
"nc",
")",
":",
"non_variable_names",
"=",
"[",
"'lat'",
",",
"'lat_bnds'",
",",
"'lon'",
",",
"'lon_bnds'",
",",
"'time'",
",",
"'latitude'",
",",
"'longitude'",
",",
"'bnds'",
"]",
"_vars",
"=",
"set",
"(",
"nc",
".",
"varia... | 20 | 0.002387 |
def LabelValueTable(self, keys=None):
"""Return LabelValue with FSM derived keys."""
keys = keys or self.superkey
# pylint: disable=E1002
return super(CliTable, self).LabelValueTable(keys) | [
"def",
"LabelValueTable",
"(",
"self",
",",
"keys",
"=",
"None",
")",
":",
"keys",
"=",
"keys",
"or",
"self",
".",
"superkey",
"# pylint: disable=E1002",
"return",
"super",
"(",
"CliTable",
",",
"self",
")",
".",
"LabelValueTable",
"(",
"keys",
")"
] | 43.2 | 0.009091 |
def set_scene_config(self, scene_id, config):
"""reconfigure a scene by scene ID"""
if not scene_id in self.state.scenes: # does that scene_id exist?
err_msg = "Requested to reconfigure scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
... | [
"def",
"set_scene_config",
"(",
"self",
",",
"scene_id",
",",
"config",
")",
":",
"if",
"not",
"scene_id",
"in",
"self",
".",
"state",
".",
"scenes",
":",
"# does that scene_id exist?",
"err_msg",
"=",
"\"Requested to reconfigure scene {sceneNum}, which does not exist\"... | 63.666667 | 0.010323 |
async def set_slave_neighbors(self):
'''Set neighbor environments for all the slave environments. Assumes
that :attr:`neighbors` are set for this multi-environment.
'''
for i, elem in enumerate(self._slave_origins):
o, addr = elem
r_slave = await self.env.connect(... | [
"async",
"def",
"set_slave_neighbors",
"(",
"self",
")",
":",
"for",
"i",
",",
"elem",
"in",
"enumerate",
"(",
"self",
".",
"_slave_origins",
")",
":",
"o",
",",
"addr",
"=",
"elem",
"r_slave",
"=",
"await",
"self",
".",
"env",
".",
"connect",
"(",
"... | 50.5 | 0.001022 |
def morphDataLists(fromList, toList, stepList):
'''
Iteratively morph fromList into toList using the values 0 to 1 in stepList
stepList: a value of 0 means no change and a value of 1 means a complete
change to the other value
'''
# If there are more than 1 pitch value, then we align the da... | [
"def",
"morphDataLists",
"(",
"fromList",
",",
"toList",
",",
"stepList",
")",
":",
"# If there are more than 1 pitch value, then we align the data in",
"# relative time.",
"# Each data point comes with a timestamp. The earliest timestamp is 0",
"# and the latest timestamp is 1. Using th... | 42.363636 | 0.001049 |
def failure_line_summary(formatter, failure_line):
"""
Create a mozlog formatted error summary string from the given failure_line.
Create a string which can be compared to a TextLogError.line string to see
if they match.
"""
if failure_line.action == "test_result":
action = "test_status... | [
"def",
"failure_line_summary",
"(",
"formatter",
",",
"failure_line",
")",
":",
"if",
"failure_line",
".",
"action",
"==",
"\"test_result\"",
":",
"action",
"=",
"\"test_status\"",
"if",
"failure_line",
".",
"subtest",
"is",
"not",
"None",
"else",
"\"test_end\"",
... | 30.785714 | 0.00225 |
def place(vertices_resources, nets, machine, constraints,
random=default_random):
"""A random placer.
This algorithm performs uniform-random placement of vertices (completely
ignoring connectivty) and thus in the general case is likely to produce
very poor quality placements. It exists primar... | [
"def",
"place",
"(",
"vertices_resources",
",",
"nets",
",",
"machine",
",",
"constraints",
",",
"random",
"=",
"default_random",
")",
":",
"# Within the algorithm we modify the resource availability values in the",
"# machine to account for the effects of the current placement. As... | 42.965909 | 0.000259 |
def genemania_force_directed(self,curveSteepness=None,defaultEdgeWeight=None,\
defaultSpringCoefficient=None,defaultSpringLength=None,EdgeAttribute=None,\
ignoreHiddenElements=None,isDeterministic=None,maxNodeMass=None,\
maxWeightCutoff=None,midpointEdges=None,minNodeMass=None,minWeightCutoff=None,\
network=Non... | [
"def",
"genemania_force_directed",
"(",
"self",
",",
"curveSteepness",
"=",
"None",
",",
"defaultEdgeWeight",
"=",
"None",
",",
"defaultSpringCoefficient",
"=",
"None",
",",
"defaultSpringLength",
"=",
"None",
",",
"EdgeAttribute",
"=",
"None",
",",
"ignoreHiddenEle... | 58.137931 | 0.038787 |
def _build_xpath_expr(attrs):
"""Build an xpath expression to simulate bs4's ability to pass in kwargs to
search for attributes when using the lxml parser.
Parameters
----------
attrs : dict
A dict of HTML attributes. These are NOT checked for validity.
Returns
-------
expr : u... | [
"def",
"_build_xpath_expr",
"(",
"attrs",
")",
":",
"# give class attribute as class_ because class is a python keyword",
"if",
"'class_'",
"in",
"attrs",
":",
"attrs",
"[",
"'class'",
"]",
"=",
"attrs",
".",
"pop",
"(",
"'class_'",
")",
"s",
"=",
"[",
"\"@{key}={... | 32.7 | 0.001486 |
def get_cycle_mrkr(self, end=False):
"""Mark cycle start or end.
Parameters
----------
end : bool
If True, marks a cycle end; otherwise, it's a cycle start
"""
if self.annot is None: # remove if buttons are disabled
self.parent.statusBar().showMe... | [
"def",
"get_cycle_mrkr",
"(",
"self",
",",
"end",
"=",
"False",
")",
":",
"if",
"self",
".",
"annot",
"is",
"None",
":",
"# remove if buttons are disabled",
"self",
".",
"parent",
".",
"statusBar",
"(",
")",
".",
"showMessage",
"(",
"'No score file loaded'",
... | 32.636364 | 0.001803 |
def convert_namespaces_ast(
ast,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
):
"""Recursively convert namespaces of BEL Entities in BEL AST using API endpoint
Canonicalization and decanonicalization is de... | [
"def",
"convert_namespaces_ast",
"(",
"ast",
",",
"api_url",
":",
"str",
"=",
"None",
",",
"namespace_targets",
":",
"Mapping",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
",",
"canonicalize",
":",
"bool",
"=",
"False",
",",
"decanonicali... | 33.694915 | 0.002444 |
def set_key(key: str, value: typing.List[str], persists: bool = True):
"""
Removes the specified key from the cauldron configs if the key exists
:param key:
The key in the cauldron configs object to remove
:param value:
:param persists:
"""
if key.endswith('_path') or key.endswith(... | [
"def",
"set_key",
"(",
"key",
":",
"str",
",",
"value",
":",
"typing",
".",
"List",
"[",
"str",
"]",
",",
"persists",
":",
"bool",
"=",
"True",
")",
":",
"if",
"key",
".",
"endswith",
"(",
"'_path'",
")",
"or",
"key",
".",
"endswith",
"(",
"'_pat... | 30.35 | 0.001597 |
def _check_load_paths(load_path):
'''
Checks the validity of the load_path, returns a sanitized version
with invalid paths removed.
'''
if load_path is None or not isinstance(load_path, six.string_types):
return None
_paths = []
for _path in load_path.split(':'):
if os.path... | [
"def",
"_check_load_paths",
"(",
"load_path",
")",
":",
"if",
"load_path",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"load_path",
",",
"six",
".",
"string_types",
")",
":",
"return",
"None",
"_paths",
"=",
"[",
"]",
"for",
"_path",
"in",
"load_path",
... | 26.7 | 0.001808 |
def notification(self):
"""Provide access to the currently displayed notification.
Returns:
:py:class:`BaseNotification`: FoxPuppet BaseNotification object.
"""
with self.selenium.context(self.selenium.CONTEXT_CHROME):
try:
root = self.selenium.f... | [
"def",
"notification",
"(",
"self",
")",
":",
"with",
"self",
".",
"selenium",
".",
"context",
"(",
"self",
".",
"selenium",
".",
"CONTEXT_CHROME",
")",
":",
"try",
":",
"root",
"=",
"self",
".",
"selenium",
".",
"find_element",
"(",
"*",
"self",
".",
... | 37.409091 | 0.00237 |
def run(src,
grammar=NODEBOX,
format=None,
outputfile=None,
iterations=1,
buff=None,
window=True,
title=None,
fullscreen=None,
close_window=False,
server=False,
port=7777,
show_vars=False,
vars=None,
namespac... | [
"def",
"run",
"(",
"src",
",",
"grammar",
"=",
"NODEBOX",
",",
"format",
"=",
"None",
",",
"outputfile",
"=",
"None",
",",
"iterations",
"=",
"1",
",",
"buff",
"=",
"None",
",",
"window",
"=",
"True",
",",
"title",
"=",
"None",
",",
"fullscreen",
"... | 30.05042 | 0.001354 |
def start(self):
"""
Start daemonization process.
"""
# If pidfile already exists, we should read pid from there; to overwrite it, if locking
# will fail, because locking attempt somehow purges the file contents.
if os.path.isfile(self.pid):
with open(self.pid... | [
"def",
"start",
"(",
"self",
")",
":",
"# If pidfile already exists, we should read pid from there; to overwrite it, if locking",
"# will fail, because locking attempt somehow purges the file contents.",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"pid",
")",
":",... | 37.494382 | 0.002043 |
def get_config_section(self, name):
"""
Get a section of a configuration
"""
if self.config.has_section(name):
return self.config.items(name)
return [] | [
"def",
"get_config_section",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"config",
".",
"has_section",
"(",
"name",
")",
":",
"return",
"self",
".",
"config",
".",
"items",
"(",
"name",
")",
"return",
"[",
"]"
] | 28.142857 | 0.009852 |
def equation_of_time_pvcdrom(dayofyear):
"""
Equation of time from PVCDROM.
`PVCDROM`_ is a website by Solar Power Lab at Arizona State
University (ASU)
.. _PVCDROM: http://www.pveducation.org/pvcdrom/2-properties-sunlight/solar-time
Parameters
----------
dayofyear : numeric
Retu... | [
"def",
"equation_of_time_pvcdrom",
"(",
"dayofyear",
")",
":",
"# day angle relative to Vernal Equinox, typically March 22 (day number 81)",
"bday",
"=",
"_calculate_simple_day_angle",
"(",
"dayofyear",
")",
"-",
"(",
"2.0",
"*",
"np",
".",
"pi",
"/",
"365.0",
")",
"*",... | 29.5625 | 0.002047 |
def _ParseShVariables(self, lines):
"""Extract env_var and path values from sh derivative shells.
Iterates over each line, word by word searching for statements that set the
path. These are either variables, or conditions that would allow a variable
to be set later in the line (e.g. export).
Args:... | [
"def",
"_ParseShVariables",
"(",
"self",
",",
"lines",
")",
":",
"paths",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
":",
"for",
"entry",
"in",
"line",
":",
"if",
"\"=\"",
"in",
"entry",
":",
"# Pad out the list so that it's always 2 elements, even if the spli... | 35.21875 | 0.01209 |
def iter_lines(f):
"""
:param f:
:type f: file
:return:
"""
linenum = 1
try:
for text in f.readlines():
# ignore lines that consist entirely of whitespace
if text.isspace():
continue
indent,value = parse_line(text)
yield... | [
"def",
"iter_lines",
"(",
"f",
")",
":",
"linenum",
"=",
"1",
"try",
":",
"for",
"text",
"in",
"f",
".",
"readlines",
"(",
")",
":",
"# ignore lines that consist entirely of whitespace",
"if",
"text",
".",
"isspace",
"(",
")",
":",
"continue",
"indent",
",... | 25.176471 | 0.011261 |
def round_to_sigfigs(num, sigfigs):
"""
Rounds a number rounded to a specific number of significant
figures instead of to a specific precision.
"""
if type(sigfigs) != int:
raise TypeError("Number of significant figures must be integer.")
elif sigfigs < 1:
raise ValueError("Numbe... | [
"def",
"round_to_sigfigs",
"(",
"num",
",",
"sigfigs",
")",
":",
"if",
"type",
"(",
"sigfigs",
")",
"!=",
"int",
":",
"raise",
"TypeError",
"(",
"\"Number of significant figures must be integer.\"",
")",
"elif",
"sigfigs",
"<",
"1",
":",
"raise",
"ValueError",
... | 35.466667 | 0.001832 |
def DIV(self, a, b):
"""Integer division operation"""
try:
result = Operators.UDIV(a, b)
except ZeroDivisionError:
result = 0
return Operators.ITEBV(256, b == 0, 0, result) | [
"def",
"DIV",
"(",
"self",
",",
"a",
",",
"b",
")",
":",
"try",
":",
"result",
"=",
"Operators",
".",
"UDIV",
"(",
"a",
",",
"b",
")",
"except",
"ZeroDivisionError",
":",
"result",
"=",
"0",
"return",
"Operators",
".",
"ITEBV",
"(",
"256",
",",
"... | 31.714286 | 0.008772 |
def next(self):
"""Returns the next batch of data."""
if self.curr_idx == len(self.idx):
raise StopIteration
i, j = self.idx[self.curr_idx]
self.curr_idx += 1
if self.major_axis == 1:
data = self.nddata[i][j:j+self.batch_size].T
label = self.n... | [
"def",
"next",
"(",
"self",
")",
":",
"if",
"self",
".",
"curr_idx",
"==",
"len",
"(",
"self",
".",
"idx",
")",
":",
"raise",
"StopIteration",
"i",
",",
"j",
"=",
"self",
".",
"idx",
"[",
"self",
".",
"curr_idx",
"]",
"self",
".",
"curr_idx",
"+=... | 40.863636 | 0.002174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.