text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def isns_isns_vrf_isns_discovery_domain_set_isns_discovery_domain_set_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
isns = ET.SubElement(config, "isns", xmlns="urn:brocade.com:mgmt:brocade-isns")
isns_vrf = ET.SubElement(isns, "isns-vrf")
... | [
"def",
"isns_isns_vrf_isns_discovery_domain_set_isns_discovery_domain_set_name",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"isns",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"isns\"",
",... | 59.357143 | 0.008294 |
def reset(self):
"""
Clear all cell activity.
"""
self.L4.reset()
for module in self.L6aModules:
module.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"L4",
".",
"reset",
"(",
")",
"for",
"module",
"in",
"self",
".",
"L6aModules",
":",
"module",
".",
"reset",
"(",
")"
] | 18.714286 | 0.014599 |
def extract_xyz_matrix_from_loop_json(pdb_lines, parsed_loop_json_contents, atoms_of_interest = backbone_atoms, expected_num_residues = None, expected_num_residue_atoms = None, allow_overlaps = False, include_all_columns = False):
'''A utility wrapper to extract_xyz_matrix_from_pdb_residue_range.
Thi... | [
"def",
"extract_xyz_matrix_from_loop_json",
"(",
"pdb_lines",
",",
"parsed_loop_json_contents",
",",
"atoms_of_interest",
"=",
"backbone_atoms",
",",
"expected_num_residues",
"=",
"None",
",",
"expected_num_residue_atoms",
"=",
"None",
",",
"allow_overlaps",
"=",
"False",
... | 97.05 | 0.020918 |
def Serialize(self, writer):
"""
Serialize full object.
Args:
writer (neo.IO.BinaryWriter):
"""
super(Header, self).Serialize(writer)
writer.WriteByte(0) | [
"def",
"Serialize",
"(",
"self",
",",
"writer",
")",
":",
"super",
"(",
"Header",
",",
"self",
")",
".",
"Serialize",
"(",
"writer",
")",
"writer",
".",
"WriteByte",
"(",
"0",
")"
] | 22.888889 | 0.009346 |
def create_bandwidth_limit_rule(self, policy, body=None):
"""Creates a new bandwidth limit rule."""
return self.post(self.qos_bandwidth_limit_rules_path % policy,
body=body) | [
"def",
"create_bandwidth_limit_rule",
"(",
"self",
",",
"policy",
",",
"body",
"=",
"None",
")",
":",
"return",
"self",
".",
"post",
"(",
"self",
".",
"qos_bandwidth_limit_rules_path",
"%",
"policy",
",",
"body",
"=",
"body",
")"
] | 52.75 | 0.009346 |
def fifo_label_correcting(self, source):
'''
API:
fifo_label_correcting(self, source)
Description:
finds shortest path from source to every other node. Returns
predecessor dictionary. If graph has a negative cycle, detects it
and returns to it.
... | [
"def",
"fifo_label_correcting",
"(",
"self",
",",
"source",
")",
":",
"pred",
"=",
"{",
"}",
"self",
".",
"get_node",
"(",
"source",
")",
".",
"set_attr",
"(",
"'distance'",
",",
"0",
")",
"pred",
"[",
"source",
"]",
"=",
"None",
"for",
"n",
"in",
... | 39.893617 | 0.001562 |
def _generate_MAC(segments=6, segment_length=2, delimiter=":", charset="0123456789abcdef"):
"""generate a non-guaranteed-unique mac address"""
addr = []
for _ in range(segments):
sub = ''.join(random.choice(charset) for _ in range(segment_length))
addr.append(sub)
... | [
"def",
"_generate_MAC",
"(",
"segments",
"=",
"6",
",",
"segment_length",
"=",
"2",
",",
"delimiter",
"=",
"\":\"",
",",
"charset",
"=",
"\"0123456789abcdef\"",
")",
":",
"addr",
"=",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"segments",
")",
":",
"sub... | 48.857143 | 0.011494 |
def get(self, remote, local=None):
""" Gets the file from FTP server
local can be:
a file: opened for writing, left open
a string: path to output file
None: contents are returned
"""
if isinstance(local, file_type): # open file, leave... | [
"def",
"get",
"(",
"self",
",",
"remote",
",",
"local",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"local",
",",
"file_type",
")",
":",
"# open file, leave open",
"local_file",
"=",
"local",
"elif",
"local",
"is",
"None",
":",
"# return string",
"loca... | 31.222222 | 0.002301 |
def parse_case(string, acronyms=None, preserve_case=False):
"""
Parse a stringiable into a list of words.
Also returns the case type, which can be one of the following:
- upper: All words are upper-case.
- lower: All words are lower-case.
- pascal: All words are title-case or upper-... | [
"def",
"parse_case",
"(",
"string",
",",
"acronyms",
"=",
"None",
",",
"preserve_case",
"=",
"False",
")",
":",
"words",
",",
"separator",
",",
"was_upper",
"=",
"_separate_words",
"(",
"string",
")",
"if",
"acronyms",
":",
"# Use advanced acronym detection with... | 31.338462 | 0.000476 |
def save_as(self, index=None):
"""Save file as...
Args:
index: self.data index for the file to save.
Returns:
False if no file name was selected or if save() was unsuccessful.
True is save() was successful.
Gets the new file name from sele... | [
"def",
"save_as",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"if",
"index",
"is",
"None",
":",
"# Save the currently edited file\r",
"index",
"=",
"self",
".",
"get_stack_index",
"(",
")",
"finfo",
"=",
"self",
".",
"data",
"[",
"index",
"]",
"# T... | 42.4 | 0.000838 |
def search_tweets(self, order):
""" Creates an query string through a given TwitterSearchOrder \
instance and takes care that it is send to the Twitter API. \
This method queries the Twitter API **without** iterating or \
reloading of further results and returns response. \
See `... | [
"def",
"search_tweets",
"(",
"self",
",",
"order",
")",
":",
"if",
"isinstance",
"(",
"order",
",",
"TwitterUserOrder",
")",
":",
"self",
".",
"__order_is_search",
"=",
"False",
"elif",
"isinstance",
"(",
"order",
",",
"TwitterSearchOrder",
")",
":",
"self",... | 40.652174 | 0.00209 |
def load_fegg(filepath, update=True):
"""
Loads pickled egg
Parameters
----------
filepath : str
Location of pickled egg
update : bool
If true, updates egg to latest format
Returns
----------
egg : Egg data object
A loaded unpickled egg
"""
try:
... | [
"def",
"load_fegg",
"(",
"filepath",
",",
"update",
"=",
"True",
")",
":",
"try",
":",
"egg",
"=",
"FriedEgg",
"(",
"*",
"*",
"dd",
".",
"io",
".",
"load",
"(",
"filepath",
")",
")",
"except",
"ValueError",
"as",
"e",
":",
"print",
"(",
"e",
")",... | 18.933333 | 0.001675 |
def diagnostics_contpix(self, data, nchunks=10, fig = "baseline_spec_with_cont_pix"):
""" Call plot_contpix once for each nth of the spectrum """
if data.contmask is None:
print("No contmask set")
else:
coeffs_all = self.coeffs
wl = data.wl
baselin... | [
"def",
"diagnostics_contpix",
"(",
"self",
",",
"data",
",",
"nchunks",
"=",
"10",
",",
"fig",
"=",
"\"baseline_spec_with_cont_pix\"",
")",
":",
"if",
"data",
".",
"contmask",
"is",
"None",
":",
"print",
"(",
"\"No contmask set\"",
")",
"else",
":",
"coeffs_... | 46.24 | 0.012712 |
def read_volume_attachment(self, name, **kwargs): # noqa: E501
"""read_volume_attachment # noqa: E501
read the specified VolumeAttachment # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>>... | [
"def",
"read_volume_attachment",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"rea... | 51.958333 | 0.001575 |
def print_exception(self, msg):
""" Print exceptions happening in separate threads
Prevent from logging a ton of them if a potentially big number of them fail the same way
"""
if self.exception_printed < 10:
self.log.error(msg)
self.exception_printed += 1 | [
"def",
"print_exception",
"(",
"self",
",",
"msg",
")",
":",
"if",
"self",
".",
"exception_printed",
"<",
"10",
":",
"self",
".",
"log",
".",
"error",
"(",
"msg",
")",
"self",
".",
"exception_printed",
"+=",
"1"
] | 43.571429 | 0.009646 |
def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
power (str):
Set the value for AC or DC power. Default ... | [
"def",
"set_hibernate_timeout",
"(",
"timeout",
",",
"power",
"=",
"'ac'",
",",
"scheme",
"=",
"None",
")",
":",
"return",
"_set_powercfg_value",
"(",
"scheme",
"=",
"scheme",
",",
"sub_group",
"=",
"'SUB_SLEEP'",
",",
"setting_guid",
"=",
"'HIBERNATEIDLE'",
"... | 29.1 | 0.000831 |
def create_datastore_for_topline(self, delete_first=0, path=None):
# type: (int, Optional[str]) -> None
"""For tabular data, create a resource in the HDX datastore which enables data preview in HDX using the built in
YAML definition for a topline. If path is not supplied, the file is first downl... | [
"def",
"create_datastore_for_topline",
"(",
"self",
",",
"delete_first",
"=",
"0",
",",
"path",
"=",
"None",
")",
":",
"# type: (int, Optional[str]) -> None",
"data",
"=",
"load_yaml",
"(",
"script_dir_plus_file",
"(",
"join",
"(",
"'..'",
",",
"'hdx_datasource_topl... | 55.142857 | 0.010191 |
def set_inputs(self, inputs):
"""Assign input voltages."""
if len(inputs) != len(self.inputs):
raise RuntimeError(
"Number of inputs {0:d} does not match number of input nodes {1:d}".format(
len(inputs), len(self.inputs)))
for i, v in zip(self.inpu... | [
"def",
"set_inputs",
"(",
"self",
",",
"inputs",
")",
":",
"if",
"len",
"(",
"inputs",
")",
"!=",
"len",
"(",
"self",
".",
"inputs",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Number of inputs {0:d} does not match number of input nodes {1:d}\"",
".",
"format",
"... | 45.25 | 0.00813 |
def manage_actor(self, monitor, actor, stop=False):
'''If an actor failed to notify itself to the arbiter for more than
the timeout, stop the actor.
:param actor: the :class:`Actor` to manage.
:param stop: if ``True``, stop the actor.
:return: if the actor is alive 0 if it is no... | [
"def",
"manage_actor",
"(",
"self",
",",
"monitor",
",",
"actor",
",",
"stop",
"=",
"False",
")",
":",
"if",
"not",
"monitor",
".",
"is_running",
"(",
")",
":",
"stop",
"=",
"True",
"if",
"not",
"actor",
".",
"is_alive",
"(",
")",
":",
"if",
"not",... | 41.333333 | 0.001125 |
def check_span(span, table):
"""
Ensure the span is valid.
A span is a list of [row, column] pairs. These coordinates
must form a rectangular shape. For example, this span will cause an
error because it is not rectangular in shape.::
span = [[0, 1], [0, 2], [1, 0]]
Spans must be
... | [
"def",
"check_span",
"(",
"span",
",",
"table",
")",
":",
"if",
"not",
"type",
"(",
"span",
")",
"is",
"list",
":",
"return",
"\"Spans must be a list of lists\"",
"for",
"pair",
"in",
"span",
":",
"if",
"not",
"type",
"(",
"pair",
")",
"is",
"list",
":... | 27.8 | 0.000463 |
def image(radar, at=None):
'''Retrieve a radar image.
:param radar: radar station no.
:param at: stat datetime, defaults to now.
'''
at = round_to_5_minutes(at or datetime.utcnow())
return ''.join([
'http://image.nmc.cn/product',
'/{0}'.format(at.year),
'/{0}'.format(at... | [
"def",
"image",
"(",
"radar",
",",
"at",
"=",
"None",
")",
":",
"at",
"=",
"round_to_5_minutes",
"(",
"at",
"or",
"datetime",
".",
"utcnow",
"(",
")",
")",
"return",
"''",
".",
"join",
"(",
"[",
"'http://image.nmc.cn/product'",
",",
"'/{0}'",
".",
"for... | 30.647059 | 0.001862 |
def recv(conn, size):
"""
Receive bytes from connection socket or stream.
If size is struct.calcsize()-compatible format, use it to unpack the data.
Otherwise, return the plain blob as bytes.
"""
try:
fmt = size
size = struct.calcsize(fmt)
except TypeError:
fmt = Non... | [
"def",
"recv",
"(",
"conn",
",",
"size",
")",
":",
"try",
":",
"fmt",
"=",
"size",
"size",
"=",
"struct",
".",
"calcsize",
"(",
"fmt",
")",
"except",
"TypeError",
":",
"fmt",
"=",
"None",
"try",
":",
"_read",
"=",
"conn",
".",
"recv",
"except",
"... | 22.655172 | 0.00146 |
def get_app_iter(self, environ):
"""Returns the application iterator for the given environ. Depending
on the request method and the current status code the return value
might be an empty response rather than the one from the response.
If the request method is `HEAD` or the status code ... | [
"def",
"get_app_iter",
"(",
"self",
",",
"environ",
")",
":",
"status",
"=",
"self",
".",
"status_code",
"if",
"environ",
"[",
"'REQUEST_METHOD'",
"]",
"==",
"'HEAD'",
"or",
"100",
"<=",
"status",
"<",
"200",
"or",
"status",
"in",
"(",
"204",
",",
"304... | 39.12 | 0.001996 |
def circular_distance_from_point(self, point, distance, **kwargs):
'''
Select earthquakes within a distance from a Point
:param point:
Centre point as instance of nhlib.geo.point.Point class
:param float distance:
Distance (km)
:returns:
Ins... | [
"def",
"circular_distance_from_point",
"(",
"self",
",",
"point",
",",
"distance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
"[",
"'distance_type'",
"]",
"is",
"'epicentral'",
":",
"locations",
"=",
"Mesh",
"(",
"self",
".",
"catalogue",
".",
"dat... | 34.037037 | 0.002116 |
def _tokenize(self, comps):
"""Split name on spaces, unless inside curly brackets or quotes."""
ps = []
for comp in comps:
ps.extend([c.strip(' ,') for c in re.split(r'\s+(?=[^{}]*(?:\{|$))', comp)])
return [p for p in ps if p] | [
"def",
"_tokenize",
"(",
"self",
",",
"comps",
")",
":",
"ps",
"=",
"[",
"]",
"for",
"comp",
"in",
"comps",
":",
"ps",
".",
"extend",
"(",
"[",
"c",
".",
"strip",
"(",
"' ,'",
")",
"for",
"c",
"in",
"re",
".",
"split",
"(",
"r'\\s+(?=[^{}]*(?:\\{... | 44.333333 | 0.01107 |
def _compute(self):
'''Overides the _compute method of EnergyBudget'''
tendencies = self._temperature_tendencies()
if 'q' in self.state:
# in a model with active water vapor, this flux should affect
# water vapor tendency, NOT air temperature tendency!
tenden... | [
"def",
"_compute",
"(",
"self",
")",
":",
"tendencies",
"=",
"self",
".",
"_temperature_tendencies",
"(",
")",
"if",
"'q'",
"in",
"self",
".",
"state",
":",
"# in a model with active water vapor, this flux should affect",
"# water vapor tendency, NOT air temperature tenden... | 52.384615 | 0.010101 |
def printDuplicatedTPEDandTFAM(tped, tfam, samples, oldSamples, prefix):
"""Print the TPED and TFAM of the duplicated samples.
:param tped: the ``tped`` containing duplicated samples.
:param tfam: the ``tfam`` containing duplicated samples.
:param samples: the updated position of the samples in the tpe... | [
"def",
"printDuplicatedTPEDandTFAM",
"(",
"tped",
",",
"tfam",
",",
"samples",
",",
"oldSamples",
",",
"prefix",
")",
":",
"# Print the TPED",
"outputTPED",
"=",
"None",
"try",
":",
"outputTPED",
"=",
"open",
"(",
"prefix",
"+",
"\".duplicated_samples.tped\"",
"... | 34.607843 | 0.000551 |
def _remove_exploration(self):
""" Called if trajectory is expanded, deletes all explored parameters from disk """
for param in self._explored_parameters.values():
if param._stored:
try:
self.f_delete_item(param)
except Exception:
... | [
"def",
"_remove_exploration",
"(",
"self",
")",
":",
"for",
"param",
"in",
"self",
".",
"_explored_parameters",
".",
"values",
"(",
")",
":",
"if",
"param",
".",
"_stored",
":",
"try",
":",
"self",
".",
"f_delete_item",
"(",
"param",
")",
"except",
"Exce... | 51.777778 | 0.008439 |
def use_value(self, value):
"""Converts value to field type or use original"""
if self.check_value(value):
return value
return self.convert_value(value) | [
"def",
"use_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"check_value",
"(",
"value",
")",
":",
"return",
"value",
"return",
"self",
".",
"convert_value",
"(",
"value",
")"
] | 36.8 | 0.010638 |
def _dens(self, R, z, phi=0., t=0.):
"""
NAME:
_dens
PURPOSE:
evaluate the density at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
density at... | [
"def",
"_dens",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"if",
"not",
"self",
".",
"isNonAxi",
"and",
"phi",
"is",
"None",
":",
"phi",
"=",
"0.",
"return",
"self",
".",
"_computeArray",
"(",
"self",... | 26.842105 | 0.011364 |
def cli(env, identifier):
"""List virtual server credentials."""
vsi = SoftLayer.VSManager(env.client)
vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
instance = vsi.get_instance(vs_id)
table = formatting.Table(['username', 'password'])
for item in instance['operatingSystem']['pa... | [
"def",
"cli",
"(",
"env",
",",
"identifier",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"instance... | 36.363636 | 0.002439 |
def sqrt(
data: AnnData,
copy: bool = False,
chunked: bool = False,
chunk_size: Optional[int] = None,
) -> Optional[AnnData]:
"""Square root the data matrix.
Computes :math:`X = \\sqrt(X)`.
Parameters
----------
data
The (annotated) data matrix of shape ``n_obs`` × ``n_vars... | [
"def",
"sqrt",
"(",
"data",
":",
"AnnData",
",",
"copy",
":",
"bool",
"=",
"False",
",",
"chunked",
":",
"bool",
"=",
"False",
",",
"chunk_size",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
")",
"->",
"Optional",
"[",
"AnnData",
"]",
":",
... | 28.341463 | 0.000832 |
def finddirs(pattern, path='.', exclude=None, recursive=True):
"""Find directories that match *pattern* in *path*"""
import fnmatch
import os
if recursive:
for root, dirnames, filenames in os.walk(path):
for pat in _to_list(pattern):
for dirname in fnmatch.filter(dirn... | [
"def",
"finddirs",
"(",
"pattern",
",",
"path",
"=",
"'.'",
",",
"exclude",
"=",
"None",
",",
"recursive",
"=",
"True",
")",
":",
"import",
"fnmatch",
"import",
"os",
"if",
"recursive",
":",
"for",
"root",
",",
"dirnames",
",",
"filenames",
"in",
"os",... | 41.26087 | 0.00103 |
def calc_ei_ic_v1(self):
"""Calculate interception evaporation and update the interception
storage accordingly.
Required control parameters:
|NmbZones|
|ZoneType|
Required flux sequences:
|EPC|
Calculated fluxes sequences:
|EI|
Updated state sequence:
|Ic|
... | [
"def",
"calc_ei_ic_v1",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"parameters",
".",
"control",
".",
"fastaccess",
"flu",
"=",
"self",
".",
"sequences",
".",
"fluxes",
".",
"fastaccess",
"sta",
"=",
"self",
".",
"sequences",
".",
"states",
".",
"... | 30.012048 | 0.000389 |
def cli(ctx, apiurl, signature, username, password):
"""Command line interface for YOURLS.
Configuration parameters can be passed as switches or stored in .yourls or
~/.yourls.
If your YOURLS server requires authentication, please provide one of the
following:
\b
• apiurl and signature
... | [
"def",
"cli",
"(",
"ctx",
",",
"apiurl",
",",
"signature",
",",
"username",
",",
"password",
")",
":",
"if",
"apiurl",
"is",
"None",
":",
"raise",
"click",
".",
"UsageError",
"(",
"\"apiurl missing. See 'yourls --help'\"",
")",
"auth_params",
"=",
"dict",
"(... | 28.6 | 0.002255 |
def get_stop_words(language, cache=True):
"""
:type language: basestring
:rtype: list
"""
try:
language = LANGUAGE_MAPPING[language]
except KeyError:
if language not in AVAILABLE_LANGUAGES:
raise StopWordError('{0}" language is unavailable.'.format(
l... | [
"def",
"get_stop_words",
"(",
"language",
",",
"cache",
"=",
"True",
")",
":",
"try",
":",
"language",
"=",
"LANGUAGE_MAPPING",
"[",
"language",
"]",
"except",
"KeyError",
":",
"if",
"language",
"not",
"in",
"AVAILABLE_LANGUAGES",
":",
"raise",
"StopWordError"... | 29.058824 | 0.000979 |
def orthonormalize_righthanded(basis):
"""Orthonormalizes righthandedly a given 3D basis.
This functions returns a right handed orthonormalize_righthandedd basis.
Since only the first two vectors in the basis are used, it does not matter
if you give two or three vectors.
Right handed means, that:
... | [
"def",
"orthonormalize_righthanded",
"(",
"basis",
")",
":",
"v1",
",",
"v2",
"=",
"basis",
"[",
":",
",",
"0",
"]",
",",
"basis",
"[",
":",
",",
"1",
"]",
"e1",
"=",
"normalize",
"(",
"v1",
")",
"e3",
"=",
"normalize",
"(",
"np",
".",
"cross",
... | 31.307692 | 0.001192 |
def __send_api_file(self, file_name):
"""
Send apidoc files from the apidoc folder to the browser.
This method replaces all absolute urls in the file by
the current url.
:param file_name: the apidoc file.
"""
file_name = join(self.app.static_folder, file_name)
... | [
"def",
"__send_api_file",
"(",
"self",
",",
"file_name",
")",
":",
"file_name",
"=",
"join",
"(",
"self",
".",
"app",
".",
"static_folder",
",",
"file_name",
")",
"with",
"codecs",
".",
"open",
"(",
"file_name",
",",
"'r'",
",",
"'utf-8'",
")",
"as",
"... | 33.135135 | 0.002377 |
def mean(self, name, **kwargs):
"""
Mean of the distribution.
"""
return np.mean(self.get(name,**kwargs)) | [
"def",
"mean",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"np",
".",
"mean",
"(",
"self",
".",
"get",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
")"
] | 26.6 | 0.021898 |
def expand_requirement(request, paths=None):
"""Expands a requirement string like 'python-2.*', 'foo-2.*+<*', etc.
Wildcards are expanded to the latest version that matches. There is also a
special wildcard '**' that will expand to the full version, but it cannot
be used in combination with '*'.
W... | [
"def",
"expand_requirement",
"(",
"request",
",",
"paths",
"=",
"None",
")",
":",
"if",
"'*'",
"not",
"in",
"request",
":",
"return",
"request",
"from",
"rez",
".",
"vendor",
".",
"version",
".",
"version",
"import",
"VersionRange",
"from",
"rez",
".",
"... | 31.212598 | 0.000978 |
def setInputFormatText( self, text ):
"""
Sets the input format text for this widget to the given value.
:param text | <str>
"""
try:
self._inputFormat = XLineEdit.InputFormat[nativestring(text)]
except KeyError:
pass | [
"def",
"setInputFormatText",
"(",
"self",
",",
"text",
")",
":",
"try",
":",
"self",
".",
"_inputFormat",
"=",
"XLineEdit",
".",
"InputFormat",
"[",
"nativestring",
"(",
"text",
")",
"]",
"except",
"KeyError",
":",
"pass"
] | 29.4 | 0.016502 |
def cached(namespace=None, service="memory", debug=False):
"""
Wrapper for tornado requests. Example
```
class MainHandler(tornado.web.RequestHandler):
@debris.tornado.cached("home-page")
def get(self):
self.write("Hello, world")
```
"""
_service = getattr(debr... | [
"def",
"cached",
"(",
"namespace",
"=",
"None",
",",
"service",
"=",
"\"memory\"",
",",
"debug",
"=",
"False",
")",
":",
"_service",
"=",
"getattr",
"(",
"debris",
".",
"services",
",",
"service",
")",
"def",
"wrapper",
"(",
"_f",
")",
":",
"@",
"fun... | 29.1 | 0.002217 |
def get_all_upper(self):
"""Return all parent GO IDs through both 'is_a' and all relationships."""
all_upper = set()
for upper in self.get_goterms_upper():
all_upper.add(upper.item_id)
all_upper |= upper.get_all_upper()
return all_upper | [
"def",
"get_all_upper",
"(",
"self",
")",
":",
"all_upper",
"=",
"set",
"(",
")",
"for",
"upper",
"in",
"self",
".",
"get_goterms_upper",
"(",
")",
":",
"all_upper",
".",
"add",
"(",
"upper",
".",
"item_id",
")",
"all_upper",
"|=",
"upper",
".",
"get_a... | 40.857143 | 0.010274 |
def bestfit(self):
"""
Returns a series with the bestfit values.
Example:
Series.bestfit()
Returns: series
The returned series contains a parameter
called 'formula' which includes the string representation
of the bestfit line.
"""
# statsmodel cannot be included on requirements.txt
# see https://g... | [
"def",
"bestfit",
"(",
"self",
")",
":",
"# statsmodel cannot be included on requirements.txt",
"# see https://github.com/scikit-learn/scikit-learn/issues/4164",
"# which shares the same issue as statsmodel",
"try",
":",
"import",
"statsmodels",
".",
"api",
"as",
"sm",
"except",
... | 27.030303 | 0.057359 |
def init_logging(logger, log_file, log_level):
"""
Initialize the naarad logger.
:param: logger: logger object to initialize
:param: log_file: log file name
:param: log_level: log level (debug, info, warn, error)
"""
with open(log_file, 'w'):
pass
numeric_level = getattr(logging, log_level.upper(), ... | [
"def",
"init_logging",
"(",
"logger",
",",
"log_file",
",",
"log_level",
")",
":",
"with",
"open",
"(",
"log_file",
",",
"'w'",
")",
":",
"pass",
"numeric_level",
"=",
"getattr",
"(",
"logging",
",",
"log_level",
".",
"upper",
"(",
")",
",",
"None",
")... | 35.130435 | 0.021687 |
def ensure_text(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to six.text_type.
For Python 2:
- `unicode` -> `unicode`
- `str` -> `unicode`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if isinstance(s, binary_type):
return s.decode(encodin... | [
"def",
"ensure_text",
"(",
"s",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"'strict'",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"binary_type",
")",
":",
"return",
"s",
".",
"decode",
"(",
"encoding",
",",
"errors",
")",
"elif",
"isinstanc... | 25.705882 | 0.002208 |
def _minimize_and_clip(optimizer, objective, var_list, clip_val=10):
"""Minimized `objective` using `optimizer` w.r.t. variables in
`var_list` while ensure the norm of the gradients for each
variable is clipped to `clip_val`
"""
gradients = optimizer.compute_gradients(objective, var_list=var_list)
... | [
"def",
"_minimize_and_clip",
"(",
"optimizer",
",",
"objective",
",",
"var_list",
",",
"clip_val",
"=",
"10",
")",
":",
"gradients",
"=",
"optimizer",
".",
"compute_gradients",
"(",
"objective",
",",
"var_list",
"=",
"var_list",
")",
"for",
"i",
",",
"(",
... | 47.3 | 0.002075 |
def about_time(fn=None, it=None):
"""Measures the execution time of a block of code, and even counts iterations
and the throughput of them, always with a beautiful "human" representation.
There's three modes of operation: context manager, callable handler and
iterator metrics.
1. Use it like a con... | [
"def",
"about_time",
"(",
"fn",
"=",
"None",
",",
"it",
"=",
"None",
")",
":",
"# has to be here to be mockable.",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"3",
")",
":",
"timer",
"=",
"time",
".",
"perf_counter",
"else",
":",
"# pragma: no... | 29.870588 | 0.001906 |
def limit_step(self, step):
"""Clip the a step within the maximum allowed range"""
if self.qmax is None:
return step
else:
return np.clip(step, -self.qmax, self.qmax) | [
"def",
"limit_step",
"(",
"self",
",",
"step",
")",
":",
"if",
"self",
".",
"qmax",
"is",
"None",
":",
"return",
"step",
"else",
":",
"return",
"np",
".",
"clip",
"(",
"step",
",",
"-",
"self",
".",
"qmax",
",",
"self",
".",
"qmax",
")"
] | 34.833333 | 0.009346 |
def _save_account(self, account, username):
""" Called when account is created/updated. With username override. """
# retrieve default project, or use null project if none
default_project_name = self._null_project
if account.default_project is not None:
default_project_name ... | [
"def",
"_save_account",
"(",
"self",
",",
"account",
",",
"username",
")",
":",
"# retrieve default project, or use null project if none",
"default_project_name",
"=",
"self",
".",
"_null_project",
"if",
"account",
".",
"default_project",
"is",
"not",
"None",
":",
"de... | 38.978261 | 0.001088 |
def app_name_from_ini_parser(ini_parser):
"""
Returns the name of the main application from the given ini file parser.
The name is found as follows:
* If the ini file contains only one app:<app name> section,
return this app name;
* Else, if the ini file contains a pipeline:main section, us... | [
"def",
"app_name_from_ini_parser",
"(",
"ini_parser",
")",
":",
"app_names",
"=",
"[",
"sect",
".",
"split",
"(",
"':'",
")",
"[",
"-",
"1",
"]",
"for",
"sect",
"in",
"ini_parser",
".",
"sections",
"(",
")",
"if",
"sect",
"[",
":",
"4",
"]",
"==",
... | 40.433333 | 0.000805 |
def experimental(name=None):
"""A simple decorator to mark functions and methods as experimental."""
def inner(func):
@functools.wraps(func)
def wrapper(*fargs, **kw):
fname = name
if name is None:
fname = func.__name__
warnings.warn("%s" % fna... | [
"def",
"experimental",
"(",
"name",
"=",
"None",
")",
":",
"def",
"inner",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"fargs",
",",
"*",
"*",
"kw",
")",
":",
"fname",
"=",
"name",
"if",
... | 35.307692 | 0.002123 |
def parents(self, node):
"""Determine all parents of node in our tree"""
return [
parent for parent in
getattr( node, 'parents', [] )
if getattr(parent, 'tree', self.TREE) == self.TREE
] | [
"def",
"parents",
"(",
"self",
",",
"node",
")",
":",
"return",
"[",
"parent",
"for",
"parent",
"in",
"getattr",
"(",
"node",
",",
"'parents'",
",",
"[",
"]",
")",
"if",
"getattr",
"(",
"parent",
",",
"'tree'",
",",
"self",
".",
"TREE",
")",
"==",
... | 34.285714 | 0.01626 |
def find_children(self, tag=None, namespace=None):
"""Searches child nodes for objects with the desired tag/namespace.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all children in
a particular namespace, specify the na... | [
"def",
"find_children",
"(",
"self",
",",
"tag",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"results",
"=",
"[",
"]",
"if",
"tag",
"and",
"namespace",
":",
"for",
"element",
"in",
"self",
".",
"children",
":",
"if",
"element",
".",
"tag",
... | 37.971429 | 0.001467 |
def kill(self):
"""Kills the running loop and waits till it gets killed."""
assert self.has_started(), "called kill() on a non-active GeventLoop"
self._stop_event.set()
self._greenlet.kill()
self._clear() | [
"def",
"kill",
"(",
"self",
")",
":",
"assert",
"self",
".",
"has_started",
"(",
")",
",",
"\"called kill() on a non-active GeventLoop\"",
"self",
".",
"_stop_event",
".",
"set",
"(",
")",
"self",
".",
"_greenlet",
".",
"kill",
"(",
")",
"self",
".",
"_cle... | 39.833333 | 0.008197 |
def parse(self, data):
"""Parse a 12 bytes packet in the Lighting2 format and return a
dictionary containing the data extracted. An example of a return value
would be:
.. code-block:: python
{
'id': "0x111F342",
'packet_length': 10,
... | [
"def",
"parse",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"validate_packet",
"(",
"data",
")",
"results",
"=",
"self",
".",
"parse_header_part",
"(",
"data",
")",
"sub_type",
"=",
"results",
"[",
"'packet_subtype'",
"]",
"id_",
"=",
"self",
".",
... | 28.698113 | 0.001271 |
def update(self, other, join='left', overwrite=True, filter_func=None,
errors='ignore'):
"""
Modify in place using non-NA values from another DataFrame.
Aligns on indices. There is no return value.
Parameters
----------
other : DataFrame, or object coerci... | [
"def",
"update",
"(",
"self",
",",
"other",
",",
"join",
"=",
"'left'",
",",
"overwrite",
"=",
"True",
",",
"filter_func",
"=",
"None",
",",
"errors",
"=",
"'ignore'",
")",
":",
"import",
"pandas",
".",
"core",
".",
"computation",
".",
"expressions",
"... | 33.791946 | 0.000579 |
def safe_call(self, kwargs, args=None):
"""
Call the underlying function safely, given a set of keyword
arguments. If successful, the function return value (likely
None) will be returned. If the underlying function raises an
exception, the return value will be the exception mes... | [
"def",
"safe_call",
"(",
"self",
",",
"kwargs",
",",
"args",
"=",
"None",
")",
":",
"# Now let's call the function",
"try",
":",
"return",
"self",
".",
"_func",
"(",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"exc",
":",
"if",
"args",
"and",
... | 41.5 | 0.001812 |
async def create(self, token):
"""Creates a new token with a given policy
Parameters:
token (Object): Token specification
Returns:
Object: token ID
The create endpoint is used to make a new token.
A token has a name, a type, and a set of ACL rules.
... | [
"async",
"def",
"create",
"(",
"self",
",",
"token",
")",
":",
"token",
"=",
"encode_token",
"(",
"token",
")",
"response",
"=",
"await",
"self",
".",
"_api",
".",
"put",
"(",
"\"/v1/acl/create\"",
",",
"data",
"=",
"token",
")",
"return",
"response",
... | 32.955556 | 0.00131 |
def generate_password(length=8, lower=True, upper=True, number=True):
"""
generates a simple password. We should not really use this in production.
:param length: the length of the password
:param lower: True of lower case characters are allowed
:param upper: True if upper case characters are allowe... | [
"def",
"generate_password",
"(",
"length",
"=",
"8",
",",
"lower",
"=",
"True",
",",
"upper",
"=",
"True",
",",
"number",
"=",
"True",
")",
":",
"lletters",
"=",
"\"abcdefghijklmnopqrstuvwxyz\"",
"uletters",
"=",
"\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"",
"# This doesn't g... | 33.387097 | 0.001878 |
def _process(self, data):
"""
Process packet received from client.
"""
try:
packet = json.loads(data)
except ValueError:
# So far, this never happened. But it would be good to have some
# protection.
logger.warning('Received invalid... | [
"def",
"_process",
"(",
"self",
",",
"data",
")",
":",
"try",
":",
"packet",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"except",
"ValueError",
":",
"# So far, this never happened. But it would be good to have some",
"# protection.",
"logger",
".",
"warning",
"(... | 34.439024 | 0.002066 |
def connect_options_node_proxy(self, name, **kwargs): # noqa: E501
"""connect_options_node_proxy # noqa: E501
connect OPTIONS requests to proxy of Node # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=Tr... | [
"def",
"connect_options_node_proxy",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
... | 47.636364 | 0.001871 |
def merge_diff(initial_config=None,
initial_path=None,
merge_config=None,
merge_path=None,
saltenv='base'):
'''
Return the merge diff, as text, after merging the merge config into the
initial config.
initial_config
The initial configur... | [
"def",
"merge_diff",
"(",
"initial_config",
"=",
"None",
",",
"initial_path",
"=",
"None",
",",
"merge_config",
"=",
"None",
",",
"merge_path",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"if",
"initial_path",
":",
"initial_config",
"=",
"__salt__"... | 39.666667 | 0.001538 |
def iter_file_commands(self):
"""Iterator returning FileCommand objects.
If an invalid file command is found, the line is silently
pushed back and iteration ends.
"""
while True:
line = self.next_line()
if line is None:
break
e... | [
"def",
"iter_file_commands",
"(",
"self",
")",
":",
"while",
"True",
":",
"line",
"=",
"self",
".",
"next_line",
"(",
")",
"if",
"line",
"is",
"None",
":",
"break",
"elif",
"len",
"(",
"line",
")",
"==",
"0",
"or",
"line",
".",
"startswith",
"(",
"... | 39.482759 | 0.001705 |
def screen_cv2(self):
"""cv2 Image of current window screen"""
pil_image = self.screen.convert('RGB')
cv2_image = np.array(pil_image)
pil_image.close()
# Convert RGB to BGR
cv2_image = cv2_image[:, :, ::-1]
return cv2_image | [
"def",
"screen_cv2",
"(",
"self",
")",
":",
"pil_image",
"=",
"self",
".",
"screen",
".",
"convert",
"(",
"'RGB'",
")",
"cv2_image",
"=",
"np",
".",
"array",
"(",
"pil_image",
")",
"pil_image",
".",
"close",
"(",
")",
"# Convert RGB to BGR \r",
"cv2_image"... | 35 | 0.010453 |
def get_path(filename):
"""
Get absolute path for filename.
:param filename: file
:return: path
"""
path = abspath(filename) if os.path.isdir(filename) else dirname(abspath(filename))
return path | [
"def",
"get_path",
"(",
"filename",
")",
":",
"path",
"=",
"abspath",
"(",
"filename",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"filename",
")",
"else",
"dirname",
"(",
"abspath",
"(",
"filename",
")",
")",
"return",
"path"
] | 24 | 0.008929 |
def forward(self, X, training=False, device='cpu'):
"""Gather and concatenate the output from forward call with
input data.
The outputs from ``self.module_.forward`` are gathered on the
compute device specified by ``device`` and then concatenated
using PyTorch :func:`~torch.cat`... | [
"def",
"forward",
"(",
"self",
",",
"X",
",",
"training",
"=",
"False",
",",
"device",
"=",
"'cpu'",
")",
":",
"y_infer",
"=",
"list",
"(",
"self",
".",
"forward_iter",
"(",
"X",
",",
"training",
"=",
"training",
",",
"device",
"=",
"device",
")",
... | 36.1875 | 0.001121 |
def stop(self, wait=1, shutdown=True, force_secondary_shutdown=False):
"""
Stops all secondaries.
'wait' specifies the time (in seconds) to wait before shutting down the
manager or returning.
If 'shutdown', shutdown the manager.
If 'force_secondary_shutdown', shutdown the... | [
"def",
"stop",
"(",
"self",
",",
"wait",
"=",
"1",
",",
"shutdown",
"=",
"True",
",",
"force_secondary_shutdown",
"=",
"False",
")",
":",
"if",
"self",
".",
"mode",
"!=",
"MODE_PRIMARY",
":",
"raise",
"ModeError",
"(",
"\"Not in primary mode!\"",
")",
"if"... | 38.608696 | 0.002198 |
def convert(self, blob, **kw):
"""Convert using unoconv converter."""
timeout = self.run_timeout
with make_temp_file(blob) as in_fn, make_temp_file(
prefix="tmp-unoconv-", suffix=".pdf"
) as out_fn:
args = ["-f", "pdf", "-o", out_fn, in_fn]
# Hack for... | [
"def",
"convert",
"(",
"self",
",",
"blob",
",",
"*",
"*",
"kw",
")",
":",
"timeout",
"=",
"self",
".",
"run_timeout",
"with",
"make_temp_file",
"(",
"blob",
")",
"as",
"in_fn",
",",
"make_temp_file",
"(",
"prefix",
"=",
"\"tmp-unoconv-\"",
",",
"suffix"... | 38.1875 | 0.002128 |
def set_value(self, value):
"""Set the value in the cache for this query."""
cache, cache_key = self._get_cache_plus_key()
cache.set(cache_key, value) | [
"def",
"set_value",
"(",
"self",
",",
"value",
")",
":",
"cache",
",",
"cache_key",
"=",
"self",
".",
"_get_cache_plus_key",
"(",
")",
"cache",
".",
"set",
"(",
"cache_key",
",",
"value",
")"
] | 42.75 | 0.011494 |
def imagetransformer_base_tpu():
"""Transformer base params for cifar-10."""
hparams = imagetransformer_bas8l_8h_big_uncond_dr03_imgnet()
update_hparams_for_tpu(hparams)
hparams.batch_size = 4
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 12
hparams.block_length = 128
... | [
"def",
"imagetransformer_base_tpu",
"(",
")",
":",
"hparams",
"=",
"imagetransformer_bas8l_8h_big_uncond_dr03_imgnet",
"(",
")",
"update_hparams_for_tpu",
"(",
"hparams",
")",
"hparams",
".",
"batch_size",
"=",
"4",
"hparams",
".",
"num_heads",
"=",
"4",
"# heads are ... | 36.625 | 0.026622 |
def copy_template(template_name, copy_to, **options):
"""Copy the specified template directory to the copy_to location"""
import django_extensions
style = color_style()
ERROR = getattr(style, 'ERROR', lambda x: x)
SUCCESS = getattr(style, 'SUCCESS', lambda x: x)
template_dir = os.path.join(dja... | [
"def",
"copy_template",
"(",
"template_name",
",",
"copy_to",
",",
"*",
"*",
"options",
")",
":",
"import",
"django_extensions",
"style",
"=",
"color_style",
"(",
")",
"ERROR",
"=",
"getattr",
"(",
"style",
",",
"'ERROR'",
",",
"lambda",
"x",
":",
"x",
"... | 42.525 | 0.002299 |
def reset_all_changes(self):
"""
Resets change tracking in this document, recursing into child Documents and
DocumentLists.
"""
self.reset_changes()
for value in self.values():
if isinstance(value, Document) or isinstance(value, DocumentList):
... | [
"def",
"reset_all_changes",
"(",
"self",
")",
":",
"self",
".",
"reset_changes",
"(",
")",
"for",
"value",
"in",
"self",
".",
"values",
"(",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Document",
")",
"or",
"isinstance",
"(",
"value",
",",
"Docum... | 37.444444 | 0.008696 |
def _get_current_userprofile():
"""Get current user profile.
.. note:: If the user is anonymous, then a
:class:`invenio_userprofiles.models.AnonymousUserProfile` instance is
returned.
:returns: The :class:`invenio_userprofiles.models.UserProfile` instance.
"""
if current_user.is_an... | [
"def",
"_get_current_userprofile",
"(",
")",
":",
"if",
"current_user",
".",
"is_anonymous",
":",
"return",
"AnonymousUserProfile",
"(",
")",
"profile",
"=",
"g",
".",
"get",
"(",
"'userprofile'",
",",
"UserProfile",
".",
"get_by_userid",
"(",
"current_user",
".... | 29.6 | 0.001637 |
def setIcon(self, icon):
"""
Sets the icon for this item to the inputed icon.
:param icon | <str> || <QIcon> || None
"""
if icon:
self._icon = QIcon(icon)
else:
self._icon = None | [
"def",
"setIcon",
"(",
"self",
",",
"icon",
")",
":",
"if",
"icon",
":",
"self",
".",
"_icon",
"=",
"QIcon",
"(",
"icon",
")",
"else",
":",
"self",
".",
"_icon",
"=",
"None"
] | 25.5 | 0.011364 |
def variable_name_from_full_name(full_name):
"""Extract the variable name from a full resource name.
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-config/variables/var-name')
"var-name"
>>> variable_name_from_full_name(
'projects/my-proj/configs/my-con... | [
"def",
"variable_name_from_full_name",
"(",
"full_name",
")",
":",
"projects",
",",
"_",
",",
"configs",
",",
"_",
",",
"variables",
",",
"result",
"=",
"full_name",
".",
"split",
"(",
"\"/\"",
",",
"5",
")",
"if",
"projects",
"!=",
"\"projects\"",
"or",
... | 43.517241 | 0.00155 |
def used(self, fieldname):
"""fieldname is used, remove from list of unused fields"""
if fieldname in self.unused:
self.unused.remove(fieldname) | [
"def",
"used",
"(",
"self",
",",
"fieldname",
")",
":",
"if",
"fieldname",
"in",
"self",
".",
"unused",
":",
"self",
".",
"unused",
".",
"remove",
"(",
"fieldname",
")"
] | 42.25 | 0.011628 |
def gradient_line(xs, ys, colormap_name='jet', ax=None):
'''Plot a 2-d line with a gradient representing ordering.
See http://stackoverflow.com/q/8500700/10601 for details.'''
if ax is None:
ax = plt.gca()
cm = plt.get_cmap(colormap_name)
npts = len(xs)-1
colors = cm(np.linspace(0, 1, num=npts))
if ha... | [
"def",
"gradient_line",
"(",
"xs",
",",
"ys",
",",
"colormap_name",
"=",
"'jet'",
",",
"ax",
"=",
"None",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"cm",
"=",
"plt",
".",
"get_cmap",
"(",
"colormap_name",
")... | 32.266667 | 0.022088 |
def global_set_option(self, opt, value):
"""set option on the correct option provider"""
self._all_options[opt].set_option(opt, value) | [
"def",
"global_set_option",
"(",
"self",
",",
"opt",
",",
"value",
")",
":",
"self",
".",
"_all_options",
"[",
"opt",
"]",
".",
"set_option",
"(",
"opt",
",",
"value",
")"
] | 49.333333 | 0.013333 |
def do_tojson(eval_ctx, value, indent=None):
"""Dumps a structure to JSON so that it's safe to use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how... | [
"def",
"do_tojson",
"(",
"eval_ctx",
",",
"value",
",",
"indent",
"=",
"None",
")",
":",
"policies",
"=",
"eval_ctx",
".",
"environment",
".",
"policies",
"dumper",
"=",
"policies",
"[",
"'json.dumps_function'",
"]",
"options",
"=",
"policies",
"[",
"'json.d... | 38.75 | 0.000787 |
def get_time_to_first_attention(self, item):
"""Get the first date at which a comment or reaction was made to the issue by someone
other than the user who created the issue
"""
comment_dates = [str_to_datetime(comment['created_at']) for comment in item['comments_data']
... | [
"def",
"get_time_to_first_attention",
"(",
"self",
",",
"item",
")",
":",
"comment_dates",
"=",
"[",
"str_to_datetime",
"(",
"comment",
"[",
"'created_at'",
"]",
")",
"for",
"comment",
"in",
"item",
"[",
"'comments_data'",
"]",
"if",
"item",
"[",
"'user'",
"... | 57.166667 | 0.008608 |
def append(self, child, *args, **kwargs):
"""See ``AbstractElement.append()``"""
e = super(AbstractStructureElement,self).append(child, *args, **kwargs)
self._setmaxid(e)
return e | [
"def",
"append",
"(",
"self",
",",
"child",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"e",
"=",
"super",
"(",
"AbstractStructureElement",
",",
"self",
")",
".",
"append",
"(",
"child",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"s... | 41.4 | 0.014218 |
def parse_reqtype(self):
"""Return the authentication body."""
if self.job_args['os_auth_version'] == 'v1.0':
return dict()
else:
setup = {
'username': self.job_args.get('os_user')
}
# Check if any prefix items are set. A prefix s... | [
"def",
"parse_reqtype",
"(",
"self",
")",
":",
"if",
"self",
".",
"job_args",
"[",
"'os_auth_version'",
"]",
"==",
"'v1.0'",
":",
"return",
"dict",
"(",
")",
"else",
":",
"setup",
"=",
"{",
"'username'",
":",
"self",
".",
"job_args",
".",
"get",
"(",
... | 38.114286 | 0.000731 |
def _get_contexts_for_squash(self, batch_signature):
"""Starting with the batch referenced by batch_signature, iterate back
through the batches and for each valid batch collect the context_id.
At the end remove contexts for txns that are other txn's predecessors.
Args:
batch... | [
"def",
"_get_contexts_for_squash",
"(",
"self",
",",
"batch_signature",
")",
":",
"batch",
"=",
"self",
".",
"_batches_by_id",
"[",
"batch_signature",
"]",
".",
"batch",
"index",
"=",
"self",
".",
"_batches",
".",
"index",
"(",
"batch",
")",
"contexts",
"=",... | 40.6 | 0.001375 |
def update_nested_dict(a, b):
"""
update nested dict `a` with another dict b.
usage::
>>> a = {'x' : { 'y': 1}}
>>> b = {'x' : {'z':2, 'y':3}, 'w': 4}
>>> update_nested_dict(a,b)
{'x': {'y': 3, 'z': 2}, 'w': 4}
"""
for k, v in b.iteritems():
if isinstance(v,... | [
"def",
"update_nested_dict",
"(",
"a",
",",
"b",
")",
":",
"for",
"k",
",",
"v",
"in",
"b",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"d",
"=",
"a",
".",
"setdefault",
"(",
"k",
",",
"{",
"}",
")",
... | 23.944444 | 0.002232 |
def get_encoder(encoding, *args, **kwargs):
"""
Returns a L{codec.Encoder} capable of encoding AMF[C{encoding}] streams.
@raise ValueError: Unknown C{encoding}.
"""
def _get_encoder_class():
if encoding == AMF0:
try:
from cpyamf import amf0
except Imp... | [
"def",
"get_encoder",
"(",
"encoding",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_get_encoder_class",
"(",
")",
":",
"if",
"encoding",
"==",
"AMF0",
":",
"try",
":",
"from",
"cpyamf",
"import",
"amf0",
"except",
"ImportError",
":",
"... | 27.28 | 0.001416 |
def get_serial_ports_list():
""" Lists serial port names
:raises EnvironmentError:
On unsupported or unknown platforms
:returns:
A list of the serial ports available on the system
"""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in rang... | [
"def",
"get_serial_ports_list",
"(",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"'win'",
")",
":",
"ports",
"=",
"[",
"'COM%s'",
"%",
"(",
"i",
"+",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"256",
")",
"]",
"elif",
"(",
"sys... | 34.294118 | 0.000834 |
def get_intent(self, intent_id):
"""Returns the intent object with the given intent_id"""
endpoint = self._intent_uri(intent_id=intent_id)
return self._get(endpoint) | [
"def",
"get_intent",
"(",
"self",
",",
"intent_id",
")",
":",
"endpoint",
"=",
"self",
".",
"_intent_uri",
"(",
"intent_id",
"=",
"intent_id",
")",
"return",
"self",
".",
"_get",
"(",
"endpoint",
")"
] | 46.5 | 0.010582 |
def copy_all_files_and_subfolders(src, dest, base_path_ignore, xtn_list):
"""
file_tools.copy_all_files_and_subfolders(src, dest, backup_path, ['*.*'])
gets list of all subfolders and copies each file to
its own folder in 'dest' folder
paths, xtn, excluded, output_file_name = 'my_files.csv')
"""
ensure_dir(dest... | [
"def",
"copy_all_files_and_subfolders",
"(",
"src",
",",
"dest",
",",
"base_path_ignore",
",",
"xtn_list",
")",
":",
"ensure_dir",
"(",
"dest",
")",
"fl",
"=",
"mod_fl",
".",
"FileList",
"(",
"[",
"src",
"]",
",",
"xtn_list",
",",
"exclude_folders",
",",
"... | 40.058824 | 0.031564 |
def _validate_edges_do_not_have_extra_links(class_name, properties):
"""Validate that edges do not have properties of Link type that aren't the edge endpoints."""
for property_name, property_descriptor in six.iteritems(properties):
if property_name in {EDGE_SOURCE_PROPERTY_NAME, EDGE_DESTINATION_PROPERT... | [
"def",
"_validate_edges_do_not_have_extra_links",
"(",
"class_name",
",",
"properties",
")",
":",
"for",
"property_name",
",",
"property_descriptor",
"in",
"six",
".",
"iteritems",
"(",
"properties",
")",
":",
"if",
"property_name",
"in",
"{",
"EDGE_SOURCE_PROPERTY_NA... | 67.6 | 0.008759 |
def agg_grid(grid, agg=None):
"""
Many functions return a 2d list with a complex data type in each cell.
For instance, grids representing environments have a set of resources,
while reading in multiple data files at once will yield a list
containing the values for that cell from each file. In order ... | [
"def",
"agg_grid",
"(",
"grid",
",",
"agg",
"=",
"None",
")",
":",
"grid",
"=",
"deepcopy",
"(",
"grid",
")",
"if",
"agg",
"is",
"None",
":",
"if",
"type",
"(",
"grid",
"[",
"0",
"]",
"[",
"0",
"]",
")",
"is",
"list",
"and",
"type",
"(",
"gri... | 39.2 | 0.00083 |
def setValue(self, value=None, update=True, delaySignal=False):
"""
Set the value of this spin.
If the value is out of bounds, it will be clipped to the nearest boundary.
If the spin is integer type, the value will be coerced to int.
Returns the actual value set.
... | [
"def",
"setValue",
"(",
"self",
",",
"value",
"=",
"None",
",",
"update",
"=",
"True",
",",
"delaySignal",
"=",
"False",
")",
":",
"if",
"value",
"is",
"None",
":",
"value",
"=",
"self",
".",
"value",
"(",
")",
"bounds",
"=",
"self",
".",
"opts",
... | 32.459459 | 0.009701 |
def _read_signer(key_filename):
"""Reads the given file as a hex key.
Args:
key_filename: The filename where the key is stored. If None,
defaults to the default key for the current user.
Returns:
Signer: the signer
Raises:
CliException: If unable to read the file.
... | [
"def",
"_read_signer",
"(",
"key_filename",
")",
":",
"filename",
"=",
"key_filename",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~'",
")",
",",
"'.sawtooth'",
... | 31.441176 | 0.000907 |
def insert_file(self, f, namespace, timestamp):
"""Inserts a file to the doc dict.
"""
doc = f.get_metadata()
doc["content"] = f.read()
self.doc_dict[f._id] = Entry(doc=doc, ns=namespace, ts=timestamp) | [
"def",
"insert_file",
"(",
"self",
",",
"f",
",",
"namespace",
",",
"timestamp",
")",
":",
"doc",
"=",
"f",
".",
"get_metadata",
"(",
")",
"doc",
"[",
"\"content\"",
"]",
"=",
"f",
".",
"read",
"(",
")",
"self",
".",
"doc_dict",
"[",
"f",
".",
"_... | 39.333333 | 0.008299 |
def prepare_rsem_reference(gtf, multifasta, build):
"""
gtf: path to GTF file (must have gene_id and transcript_id)
multifasta: path to multifasta file
build: name of organism build (e.g. hg19)
"""
if not utils.which("rsem-prepare-reference"):
logger.info("Skipping prepping RSEM referenc... | [
"def",
"prepare_rsem_reference",
"(",
"gtf",
",",
"multifasta",
",",
"build",
")",
":",
"if",
"not",
"utils",
".",
"which",
"(",
"\"rsem-prepare-reference\"",
")",
":",
"logger",
".",
"info",
"(",
"\"Skipping prepping RSEM reference because \"",
"\"rsem-prepare-refere... | 42.166667 | 0.001289 |
def numeric_value(self):
"""Numeric value assigned to element by user, np.nan if absent."""
numeric_value = self._element_dict.get("numeric_value")
return np.nan if numeric_value is None else numeric_value | [
"def",
"numeric_value",
"(",
"self",
")",
":",
"numeric_value",
"=",
"self",
".",
"_element_dict",
".",
"get",
"(",
"\"numeric_value\"",
")",
"return",
"np",
".",
"nan",
"if",
"numeric_value",
"is",
"None",
"else",
"numeric_value"
] | 56.5 | 0.008734 |
def rank_all(self,roots,optimize=False):
"""Computes rank of all vertices.
add provided roots to rank 0 vertices,
otherwise update ranking from provided roots.
The initial rank is based on precedence relationships,
optimal ranking may be derived from network flow (simplex).
... | [
"def",
"rank_all",
"(",
"self",
",",
"roots",
",",
"optimize",
"=",
"False",
")",
":",
"self",
".",
"_edge_inverter",
"(",
")",
"r",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"g",
".",
"sV",
"if",
"(",
"len",
"(",
"x",
".",
"e_in",
"(",
"... | 43.916667 | 0.011152 |
def create_time_subscription(self, instance, on_data=None, timeout=60):
"""
Create a new subscription for receiving time updates of an instance.
Time updates are emitted at 1Hz.
This method returns a future, then returns immediately. Stop the
subscription by canceling the future... | [
"def",
"create_time_subscription",
"(",
"self",
",",
"instance",
",",
"on_data",
"=",
"None",
",",
"timeout",
"=",
"60",
")",
":",
"manager",
"=",
"WebSocketSubscriptionManager",
"(",
"self",
",",
"resource",
"=",
"'time'",
")",
"# Represent subscription as a futu... | 35.416667 | 0.001527 |
def getThirdpartyLibs(self, libs, configuration = 'Development', includePlatformDefaults = True):
"""
Retrieves the ThirdPartyLibraryDetails instance for Unreal-bundled versions of the specified third-party libraries
"""
if includePlatformDefaults == True:
libs = self._defaultThirdpartyLibs() + libs
interr... | [
"def",
"getThirdpartyLibs",
"(",
"self",
",",
"libs",
",",
"configuration",
"=",
"'Development'",
",",
"includePlatformDefaults",
"=",
"True",
")",
":",
"if",
"includePlatformDefaults",
"==",
"True",
":",
"libs",
"=",
"self",
".",
"_defaultThirdpartyLibs",
"(",
... | 58.375 | 0.035865 |
def create_element_dict(self):
"""Convert a UNTL Python object into a UNTL Python dictionary."""
untl_dict = {}
# Loop through all UNTL elements in the Python object.
for element in self.children:
# If an entry for the element list hasn't been made in the
# dictio... | [
"def",
"create_element_dict",
"(",
"self",
")",
":",
"untl_dict",
"=",
"{",
"}",
"# Loop through all UNTL elements in the Python object.",
"for",
"element",
"in",
"self",
".",
"children",
":",
"# If an entry for the element list hasn't been made in the",
"# dictionary, start an... | 46.633333 | 0.001401 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.