text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def fit(self, X):
"""Fit structure-based AD. The training model memorizes the unique set of reaction signature.
Parameters
----------
X : after read rdf file
Returns
-------
self : object
"""
X = iter2array(X, dtype=ReactionContainer)
se... | [
"def",
"fit",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"iter2array",
"(",
"X",
",",
"dtype",
"=",
"ReactionContainer",
")",
"self",
".",
"_train_signatures",
"=",
"{",
"self",
".",
"__get_signature",
"(",
"x",
")",
"for",
"x",
"in",
"X",
"}",
"re... | 27.571429 | 0.007519 |
def records( self ):
"""
Returns the record set for the current settings of this browser.
:return <orb.RecordSet>
"""
if ( self.isGroupingActive() ):
self._records.setGroupBy(self.currentGrouping())
else:
self._records.setGrou... | [
"def",
"records",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"isGroupingActive",
"(",
")",
")",
":",
"self",
".",
"_records",
".",
"setGroupBy",
"(",
"self",
".",
"currentGrouping",
"(",
")",
")",
"else",
":",
"self",
".",
"_records",
".",
"setGr... | 31.727273 | 0.019499 |
def _see_remote_link_node(self, node_id, fringe=None, dist=None,
check_dsp=lambda x: True):
"""
See data remote links of the node (set output to remote links).
:param node_id:
Node id.
:type node_id: str
:param fringe:
Heapq... | [
"def",
"_see_remote_link_node",
"(",
"self",
",",
"node_id",
",",
"fringe",
"=",
"None",
",",
"dist",
"=",
"None",
",",
"check_dsp",
"=",
"lambda",
"x",
":",
"True",
")",
":",
"# Namespace shortcut.",
"node",
",",
"p_id",
",",
"c_i",
"=",
"self",
".",
... | 42.564103 | 0.002356 |
def _ns_query(self, session):
"""
Return a SQLAlchemy query that is already namespaced by the app and namespace given to this backend
during initialization.
Returns: a SQLAlchemy query object
"""
return session.query(ORMJob).filter(ORMJob.app == self.app,
... | [
"def",
"_ns_query",
"(",
"self",
",",
"session",
")",
":",
"return",
"session",
".",
"query",
"(",
"ORMJob",
")",
".",
"filter",
"(",
"ORMJob",
".",
"app",
"==",
"self",
".",
"app",
",",
"ORMJob",
".",
"namespace",
"==",
"self",
".",
"namespace",
")"... | 41.777778 | 0.007813 |
def satisifesShapeOr(cntxt: Context, n: Node, se: ShExJ.ShapeOr, _: DebugContext) -> bool:
""" Se is a ShapeOr and there is some shape expression se2 in shapeExprs such that satisfies(n, se2, G, m). """
return any(satisfies(cntxt, n, se2) for se2 in se.shapeExprs) | [
"def",
"satisifesShapeOr",
"(",
"cntxt",
":",
"Context",
",",
"n",
":",
"Node",
",",
"se",
":",
"ShExJ",
".",
"ShapeOr",
",",
"_",
":",
"DebugContext",
")",
"->",
"bool",
":",
"return",
"any",
"(",
"satisfies",
"(",
"cntxt",
",",
"n",
",",
"se2",
"... | 90 | 0.011029 |
def tempoAdjust1(self, tempoFactor):
"""
Adjust tempo based on recent active apical input only
:param tempoFactor: scaling signal to MC clock from last sequence item
:return: adjusted scaling signal
"""
if self.apicalIntersect.any():
tempoFactor = tempoFactor * 0.5
else:
tempo... | [
"def",
"tempoAdjust1",
"(",
"self",
",",
"tempoFactor",
")",
":",
"if",
"self",
".",
"apicalIntersect",
".",
"any",
"(",
")",
":",
"tempoFactor",
"=",
"tempoFactor",
"*",
"0.5",
"else",
":",
"tempoFactor",
"=",
"tempoFactor",
"*",
"2",
"return",
"tempoFact... | 23.6 | 0.008152 |
def verify_geospatial_bounds(self, ds):
"""Checks that the geospatial bounds is well formed OGC WKT"""
var = getattr(ds, 'geospatial_bounds', None)
check = var is not None
if not check:
return ratable_result(False,
"Global Attributes", # grou... | [
"def",
"verify_geospatial_bounds",
"(",
"self",
",",
"ds",
")",
":",
"var",
"=",
"getattr",
"(",
"ds",
",",
"'geospatial_bounds'",
",",
"None",
")",
"check",
"=",
"var",
"is",
"not",
"None",
"if",
"not",
"check",
":",
"return",
"ratable_result",
"(",
"Fa... | 44.55 | 0.005495 |
def opacity(self, value):
"""
Setter for **self.__opacity** attribute.
:param value: Attribute value.
:type value: float
"""
if value is not None:
assert type(value) in (int, float), "'{0}' attribute: '{1}' type is not 'int' or 'float'!".format("opacity",
... | [
"def",
"opacity",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"in",
"(",
"int",
",",
"float",
")",
",",
"\"'{0}' attribute: '{1}' type is not 'int' or 'float'!\"",
".",
"format",
"(",
"... | 32.166667 | 0.006711 |
def import_csv(file_name, **kwargs):
""" Reads control points from a CSV file and generates a 1-dimensional list of control points.
It is possible to use a different value separator via ``separator`` keyword argument. The following code segment
illustrates the usage of ``separator`` keyword argument.
... | [
"def",
"import_csv",
"(",
"file_name",
",",
"*",
"*",
"kwargs",
")",
":",
"# File delimiters",
"sep",
"=",
"kwargs",
".",
"get",
"(",
"'separator'",
",",
"\",\"",
")",
"content",
"=",
"exch",
".",
"read_file",
"(",
"file_name",
",",
"skip_lines",
"=",
"1... | 40.275862 | 0.004181 |
def initial_closure(self):
"""Computes the initial closure using the START_foo production."""
first_rule = DottedRule(self.start, 0, END_OF_INPUT)
return self.closure([first_rule]) | [
"def",
"initial_closure",
"(",
"self",
")",
":",
"first_rule",
"=",
"DottedRule",
"(",
"self",
".",
"start",
",",
"0",
",",
"END_OF_INPUT",
")",
"return",
"self",
".",
"closure",
"(",
"[",
"first_rule",
"]",
")"
] | 50.25 | 0.009804 |
def visit_Module(self, node):
""" Import module define a new variable name. """
duc = SilentDefUseChains()
duc.visit(node)
for d in duc.locals[node]:
self.result[d.name()] = d.node | [
"def",
"visit_Module",
"(",
"self",
",",
"node",
")",
":",
"duc",
"=",
"SilentDefUseChains",
"(",
")",
"duc",
".",
"visit",
"(",
"node",
")",
"for",
"d",
"in",
"duc",
".",
"locals",
"[",
"node",
"]",
":",
"self",
".",
"result",
"[",
"d",
".",
"na... | 36.5 | 0.008929 |
def following(self, user, *models, **kwargs):
"""
Returns a list of actors that the given user is following (eg who im following).
Items in the list can be of any model unless a list of restricted models are passed.
Eg following(user, User) will only return users following the given user... | [
"def",
"following",
"(",
"self",
",",
"user",
",",
"*",
"models",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"[",
"follow",
".",
"follow_object",
"for",
"follow",
"in",
"self",
".",
"following_qs",
"(",
"user",
",",
"*",
"models",
",",
"flag",
"=",... | 51.111111 | 0.010684 |
def JGE(cpu, target):
"""
Jumps short if greater or equal.
:param cpu: current CPU.
:param target: destination operand.
"""
cpu.PC = Operators.ITEBV(cpu.address_bit_size, (cpu.SF == cpu.OF), target.read(), cpu.PC) | [
"def",
"JGE",
"(",
"cpu",
",",
"target",
")",
":",
"cpu",
".",
"PC",
"=",
"Operators",
".",
"ITEBV",
"(",
"cpu",
".",
"address_bit_size",
",",
"(",
"cpu",
".",
"SF",
"==",
"cpu",
".",
"OF",
")",
",",
"target",
".",
"read",
"(",
")",
",",
"cpu",... | 31.875 | 0.01145 |
def table(self, rows, col_width=2):
'''table will print a table of entries. If the rows is
a dictionary, the keys are interpreted as column names. if
not, a numbered list is used.
'''
labels = [str(x) for x in range(1,len(rows)+1)]
if isinstance(rows, dict):
... | [
"def",
"table",
"(",
"self",
",",
"rows",
",",
"col_width",
"=",
"2",
")",
":",
"labels",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"rows",
")",
"+",
"1",
")",
"]",
"if",
"isinstance",
"(",
"rows",
... | 34.705882 | 0.008251 |
def _process_tags(self):
"""Validate standard tags and initialize attributes.
Raise ValueError if tag values are not supported.
"""
tags = self.tags
for code, (name, default, dtype, count, validate) in TIFF_TAGS.items():
if not (name in tags or default is None):
... | [
"def",
"_process_tags",
"(",
"self",
")",
":",
"tags",
"=",
"self",
".",
"tags",
"for",
"code",
",",
"(",
"name",
",",
"default",
",",
"dtype",
",",
"count",
",",
"validate",
")",
"in",
"TIFF_TAGS",
".",
"items",
"(",
")",
":",
"if",
"not",
"(",
... | 44.758621 | 0.001131 |
async def load_saved_device_info(self):
"""Load device information from the device info file."""
_LOGGER.debug("Loading saved device info.")
deviceinfo = []
if self._workdir:
_LOGGER.debug("Really Loading saved device info.")
try:
device_file = '{}... | [
"async",
"def",
"load_saved_device_info",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Loading saved device info.\"",
")",
"deviceinfo",
"=",
"[",
"]",
"if",
"self",
".",
"_workdir",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Really Loading saved device info... | 47.888889 | 0.002275 |
def read(self, length=None):
"""
Reads data from readble BIO. For test purposes.
@param length - if specifed, limits amount of data read.
If not BIO is read until end of buffer
"""
if not length is None:
if not isinstance(length, inttype) :
rai... | [
"def",
"read",
"(",
"self",
",",
"length",
"=",
"None",
")",
":",
"if",
"not",
"length",
"is",
"None",
":",
"if",
"not",
"isinstance",
"(",
"length",
",",
"inttype",
")",
":",
"raise",
"TypeError",
"(",
"\"length to read should be number\"",
")",
"buf",
... | 40.121212 | 0.00295 |
def restore(self, fade=False):
"""Restore the state of a device to that which was previously saved.
For coordinator devices restore everything. For slave devices
only restore volume etc., not transport info (transport info
comes from the slave's coordinator).
Args:
... | [
"def",
"restore",
"(",
"self",
",",
"fade",
"=",
"False",
")",
":",
"try",
":",
"if",
"self",
".",
"is_coordinator",
":",
"self",
".",
"_restore_coordinator",
"(",
")",
"finally",
":",
"self",
".",
"_restore_volume",
"(",
"fade",
")",
"# Now everything is ... | 34.916667 | 0.002323 |
def attr(self, kw=None, _attributes=None, **attrs):
"""Add a general or graph/node/edge attribute statement.
Args:
kw: Attributes target (``None`` or ``'graph'``, ``'node'``, ``'edge'``).
attrs: Attributes to be set (must be strings, may be empty).
See the :ref:`usage e... | [
"def",
"attr",
"(",
"self",
",",
"kw",
"=",
"None",
",",
"_attributes",
"=",
"None",
",",
"*",
"*",
"attrs",
")",
":",
"if",
"kw",
"is",
"not",
"None",
"and",
"kw",
".",
"lower",
"(",
")",
"not",
"in",
"(",
"'graph'",
",",
"'node'",
",",
"'edge... | 44.2 | 0.005537 |
def _function(self):
"""
This is the actual function that will be executed. It uses only information that is provided in the settings property
will be overwritten in the __init__
"""
plant = self.instruments['plant']['instance']
controler = self.instruments['controler']['... | [
"def",
"_function",
"(",
"self",
")",
":",
"plant",
"=",
"self",
".",
"instruments",
"[",
"'plant'",
"]",
"[",
"'instance'",
"]",
"controler",
"=",
"self",
".",
"instruments",
"[",
"'controler'",
"]",
"[",
"'instance'",
"]",
"plant",
".",
"update",
"(",
... | 41.622222 | 0.003652 |
def get_vnetwork_hosts_output_vnetwork_hosts_vswitch(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_hosts = ET.Element("get_vnetwork_hosts")
config = get_vnetwork_hosts
output = ET.SubElement(get_vnetwork_hosts, "output")
vn... | [
"def",
"get_vnetwork_hosts_output_vnetwork_hosts_vswitch",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_vnetwork_hosts",
"=",
"ET",
".",
"Element",
"(",
"\"get_vnetwork_hosts\"",
")",
"config",
... | 42.846154 | 0.003515 |
def getlevel(self, threshold):
"""
Returns all clusters with a maximum distance of *threshold* in between
each other
:param threshold: the maximum distance between clusters.
See :py:meth:`~cluster.cluster.Cluster.getlevel`
"""
# if it's not worth clustering, ju... | [
"def",
"getlevel",
"(",
"self",
",",
"threshold",
")",
":",
"# if it's not worth clustering, just return the data",
"if",
"len",
"(",
"self",
".",
"_input",
")",
"<=",
"1",
":",
"return",
"self",
".",
"_input",
"# initialize the cluster if not yet done",
"if",
"not"... | 29 | 0.003515 |
def leehom_general_stats_table(self):
""" Take the parsed stats from the leeHom report and add it to the
basic stats table at the top of the report """
headers = {}
headers['merged_trimming'] = {
'title': '{} Merged (Trimming)'.format(config.read_count_prefix),
'... | [
"def",
"leehom_general_stats_table",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"}",
"headers",
"[",
"'merged_trimming'",
"]",
"=",
"{",
"'title'",
":",
"'{} Merged (Trimming)'",
".",
"format",
"(",
"config",
".",
"read_count_prefix",
")",
",",
"'description'",... | 45.227273 | 0.003937 |
def _mirror_groups(self):
"""
Mirrors the user's LDAP groups in the Django database and updates the
user's membership.
"""
target_group_names = frozenset(self._get_groups().get_group_names())
current_group_names = frozenset(self._user.groups.values_list('name', flat=True)... | [
"def",
"_mirror_groups",
"(",
"self",
")",
":",
"target_group_names",
"=",
"frozenset",
"(",
"self",
".",
"_get_groups",
"(",
")",
".",
"get_group_names",
"(",
")",
")",
"current_group_names",
"=",
"frozenset",
"(",
"self",
".",
"_user",
".",
"groups",
".",
... | 48.75 | 0.007547 |
def parse_star_report (self, raw_data):
""" Parse the final STAR log file. """
regexes = {
'total_reads': r"Number of input reads \|\s+(\d+)",
'avg_input_read_length': r"Average input read length \|\s+([\d\.]+)",
'uniquely_mapped': ... | [
"def",
"parse_star_report",
"(",
"self",
",",
"raw_data",
")",
":",
"regexes",
"=",
"{",
"'total_reads'",
":",
"r\"Number of input reads \\|\\s+(\\d+)\"",
",",
"'avg_input_read_length'",
":",
"r\"Average input read length \\|\\s+([\\d\\.]+)\"",
",",
"'uniquely_mapped'",
":",
... | 70.45098 | 0.009058 |
def __get_file(self, file):
""" Get request file and do a security check """
file_object = None
if file['name'] in request.files:
file_object = request.files[file['name']]
clean_filename = secure_filename(file_object.filename)
if clean_filename == '':
... | [
"def",
"__get_file",
"(",
"self",
",",
"file",
")",
":",
"file_object",
"=",
"None",
"if",
"file",
"[",
"'name'",
"]",
"in",
"request",
".",
"files",
":",
"file_object",
"=",
"request",
".",
"files",
"[",
"file",
"[",
"'name'",
"]",
"]",
"clean_filenam... | 44.428571 | 0.00315 |
def alphanum_order(triples):
"""
Sort a list of triples by relation name.
Embedded integers are sorted numerically, but otherwise the sorting
is alphabetic.
"""
return sorted(
triples,
key=lambda t: [
int(t) if t.isdigit() else t
for t in re.split(r'([0-9... | [
"def",
"alphanum_order",
"(",
"triples",
")",
":",
"return",
"sorted",
"(",
"triples",
",",
"key",
"=",
"lambda",
"t",
":",
"[",
"int",
"(",
"t",
")",
"if",
"t",
".",
"isdigit",
"(",
")",
"else",
"t",
"for",
"t",
"in",
"re",
".",
"split",
"(",
... | 24.714286 | 0.002786 |
def field_uuid(self, attr, options):
"""Creates a form element for the UUID type."""
options['validators'].append(validators.UUIDValidator(attr.entity))
return wtf_fields.StringField, options | [
"def",
"field_uuid",
"(",
"self",
",",
"attr",
",",
"options",
")",
":",
"options",
"[",
"'validators'",
"]",
".",
"append",
"(",
"validators",
".",
"UUIDValidator",
"(",
"attr",
".",
"entity",
")",
")",
"return",
"wtf_fields",
".",
"StringField",
",",
"... | 53 | 0.009302 |
def vocab_to_json(vocab: Vocab, path: str):
"""
Saves vocabulary in human-readable json.
:param vocab: Vocabulary mapping.
:param path: Output file path.
"""
with open(path, "w", encoding=C.VOCAB_ENCODING) as out:
json.dump(vocab, out, indent=4, ensure_ascii=False)
logger.info('... | [
"def",
"vocab_to_json",
"(",
"vocab",
":",
"Vocab",
",",
"path",
":",
"str",
")",
":",
"with",
"open",
"(",
"path",
",",
"\"w\"",
",",
"encoding",
"=",
"C",
".",
"VOCAB_ENCODING",
")",
"as",
"out",
":",
"json",
".",
"dump",
"(",
"vocab",
",",
"out"... | 34.3 | 0.002841 |
def _get_interpolator(method, vectorizeable_only=False, **kwargs):
'''helper function to select the appropriate interpolator class
returns interpolator class and keyword arguments for the class
'''
interp1d_methods = ['linear', 'nearest', 'zero', 'slinear', 'quadratic',
'cubic',... | [
"def",
"_get_interpolator",
"(",
"method",
",",
"vectorizeable_only",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"interp1d_methods",
"=",
"[",
"'linear'",
",",
"'nearest'",
",",
"'zero'",
",",
"'slinear'",
",",
"'quadratic'",
",",
"'cubic'",
",",
"'pol... | 38.384615 | 0.000489 |
def _plotxw(self,*args,**kwargs): #pragma: no cover
"""
NAME:
plotxw
PURPOSE:
plot the spectrum of x
INPUT:
bovy_plot.bovy_plot args and kwargs
OUTPUT:
x(t)
HISTORY:
2010-09-21 - Written - Bovy (NYU)
"""
... | [
"def",
"_plotxw",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"#pragma: no cover",
"xw",
"=",
"self",
".",
"xw",
"(",
")",
"#BOVY: CHECK THAT THIS IS CORRECT",
"plot",
".",
"bovy_plot",
"(",
"2.",
"*",
"m",
".",
"pi",
"*",
"nu",
... | 30.157895 | 0.021997 |
def holdout(self,
train_perc=0.7,
num_rep=50,
stratified=True,
return_ids_only=False,
format='MLDataset'):
"""
Builds a generator for train and test sets for cross-validation.
"""
ids_in_class = {cid: self.... | [
"def",
"holdout",
"(",
"self",
",",
"train_perc",
"=",
"0.7",
",",
"num_rep",
"=",
"50",
",",
"stratified",
"=",
"True",
",",
"return_ids_only",
"=",
"False",
",",
"format",
"=",
"'MLDataset'",
")",
":",
"ids_in_class",
"=",
"{",
"cid",
":",
"self",
".... | 41.413043 | 0.006154 |
def _map_segmentation_mask_to_stft_domain(mask, times, frequencies, stft_times, stft_frequencies):
"""
Maps the given `mask`, which is in domain (`frequencies`, `times`) to the new domain (`stft_frequencies`, `stft_times`)
and returns the result.
"""
assert mask.shape == (frequencies.shape[0], times... | [
"def",
"_map_segmentation_mask_to_stft_domain",
"(",
"mask",
",",
"times",
",",
"frequencies",
",",
"stft_times",
",",
"stft_frequencies",
")",
":",
"assert",
"mask",
".",
"shape",
"==",
"(",
"frequencies",
".",
"shape",
"[",
"0",
"]",
",",
"times",
".",
"sh... | 45.956522 | 0.007414 |
def main():
"""Quick test for QSUsb class."""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--url', help='QSUSB URL [http://127.0.0.1:2020]',
default='http://127.0.0.1:2020')
parser.add_argument('--file', help='a test file from /&devices')
parser... | [
"def",
"main",
"(",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"'--url'",
",",
"help",
"=",
"'QSUSB URL [http://127.0.0.1:2020]'",
",",
"default",
"=",
"'http://127.0.0.1:2020'",
... | 33.604651 | 0.000672 |
def error(msg: str, resource: Optional['Resource'] = None, stream_id: Optional[int] = None):
"""
Logs a message to the Pulumi CLI's error channel, associating it with a resource
and stream_id if provided.
:param str msg: The message to send to the Pulumi CLI.
:param Optional[Resource] resource: If ... | [
"def",
"error",
"(",
"msg",
":",
"str",
",",
"resource",
":",
"Optional",
"[",
"'Resource'",
"]",
"=",
"None",
",",
"stream_id",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
":",
"engine",
"=",
"get_engine",
"(",
")",
"if",
"engine",
"is",
"... | 47.928571 | 0.00731 |
def _fits_inside_predicate(self):
"""
Return a function taking an integer point size argument that returns
|True| if the text in this fitter can be wrapped to fit entirely
within its extents when rendered at that point size.
"""
def predicate(point_size):
"""
... | [
"def",
"_fits_inside_predicate",
"(",
"self",
")",
":",
"def",
"predicate",
"(",
"point_size",
")",
":",
"\"\"\"\n Return |True| if the text in *line_source* can be wrapped to fit\n entirely within *extents* when rendered at *point_size* using the\n font defi... | 43.647059 | 0.002639 |
def report(self, fraction=None):
"""report the total progress for the current stack, optionally given the local fraction completed.
fraction=None: if given, used as the fraction of the local method so far completed.
runtimes=None: if given, used as the expected runtimes for the current stack.
"""
r = Dict()
... | [
"def",
"report",
"(",
"self",
",",
"fraction",
"=",
"None",
")",
":",
"r",
"=",
"Dict",
"(",
")",
"local_key",
"=",
"self",
".",
"stack_key",
"if",
"local_key",
"is",
"None",
":",
"return",
"{",
"}",
"runtimes",
"=",
"self",
".",
"runtimes",
"(",
"... | 39.555556 | 0.03155 |
def percolate(self, index, doc_types, query):
"""
Match a query with a document
"""
if doc_types is None:
raise RuntimeError('percolate() must be supplied with at least one doc_type')
path = self._make_path(index, doc_types, '_percolate')
body = self._encode_... | [
"def",
"percolate",
"(",
"self",
",",
"index",
",",
"doc_types",
",",
"query",
")",
":",
"if",
"doc_types",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'percolate() must be supplied with at least one doc_type'",
")",
"path",
"=",
"self",
".",
"_make_path",
... | 37.6 | 0.007792 |
def complex_state_generator_bravo(last_state=''):
"""Pick a state."""
from random import choice
states = ['ALPHA', 'BRAVO', 'BRAVO', 'DONE']
if last_state:
states.remove(last_state) # Slightly lower chances of previous state.
state = choice(states)
logging.info('Generating a state...... | [
"def",
"complex_state_generator_bravo",
"(",
"last_state",
"=",
"''",
")",
":",
"from",
"random",
"import",
"choice",
"states",
"=",
"[",
"'ALPHA'",
",",
"'BRAVO'",
",",
"'BRAVO'",
",",
"'DONE'",
"]",
"if",
"last_state",
":",
"states",
".",
"remove",
"(",
... | 26 | 0.002857 |
async def download_media(self, *args, **kwargs):
"""
Downloads the media contained in the message, if any. Shorthand
for `telethon.client.downloads.DownloadMethods.download_media`
with the ``message`` already set.
"""
return await self._client.download_media(self, *args, ... | [
"async",
"def",
"download_media",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"await",
"self",
".",
"_client",
".",
"download_media",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 46.142857 | 0.006079 |
def _StructMessageToJsonObject(message, unused_including_default=False):
"""Converts Struct message according to Proto3 JSON Specification."""
fields = message.fields
ret = {}
for key in fields:
ret[key] = _ValueMessageToJsonObject(fields[key])
return ret | [
"def",
"_StructMessageToJsonObject",
"(",
"message",
",",
"unused_including_default",
"=",
"False",
")",
":",
"fields",
"=",
"message",
".",
"fields",
"ret",
"=",
"{",
"}",
"for",
"key",
"in",
"fields",
":",
"ret",
"[",
"key",
"]",
"=",
"_ValueMessageToJsonO... | 37.571429 | 0.022305 |
def WalkControl(control: Control, includeTop: bool = False, maxDepth: int = 0xFFFFFFFF):
"""
control: `Control` or its subclass.
includeTop: bool, if True, yield (control, 0) first.
maxDepth: int, enum depth.
Yield 2 items tuple(control: Control, depth: int).
"""
if includeTop:
yield... | [
"def",
"WalkControl",
"(",
"control",
":",
"Control",
",",
"includeTop",
":",
"bool",
"=",
"False",
",",
"maxDepth",
":",
"int",
"=",
"0xFFFFFFFF",
")",
":",
"if",
"includeTop",
":",
"yield",
"control",
",",
"0",
"if",
"maxDepth",
"<=",
"0",
":",
"retu... | 32.678571 | 0.002123 |
def publish(self, synchronous=True, **kwargs):
"""Helper for publishing an existing content view.
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response ... | [
"def",
"publish",
"(",
"self",
",",
"synchronous",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"# shadow the passed-in kwargs",
"if",
"'data'",
"in",
"kwargs",
"and",
"'id'",
"not",
"in",
"kwargs",
"[",... | 53.222222 | 0.002051 |
def step(self, data):
"""
Run convolution over a single position. The data must be exactly as wide as the convolution filters.
:param data: Shape: (batch_size, kernel_width, num_hidden).
:return: Single result of a convolution. Shape: (batch_size, 1, num_hidden).
"""
# ... | [
"def",
"step",
"(",
"self",
",",
"data",
")",
":",
"# As we only run convolution over a single window that is exactly the size of the convolutional filter",
"# we can use FullyConnected instead of Convolution for efficiency reasons. Additionally we do not need to",
"# perform any masking.",
"n... | 48.296296 | 0.004511 |
def compare_agents(EnvFactory, AgentFactories, n=10, steps=1000):
"""See how well each of several agents do in n instances of an environment.
Pass in a factory (constructor) for environments, and several for agents.
Create n instances of the environment, and run each agent in copies of
each one for step... | [
"def",
"compare_agents",
"(",
"EnvFactory",
",",
"AgentFactories",
",",
"n",
"=",
"10",
",",
"steps",
"=",
"1000",
")",
":",
"envs",
"=",
"[",
"EnvFactory",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"return",
"[",
"(",
"A",
",",
"t... | 63.25 | 0.001949 |
def get_concept_item_mapping(self, concepts=None, lang=None):
"""
Get mapping of concepts to items belonging to concept.
Args:
concepts (list of Concept): Defaults to None meaning all concepts
lang (str): language of concepts, if None use language of concepts
Re... | [
"def",
"get_concept_item_mapping",
"(",
"self",
",",
"concepts",
"=",
"None",
",",
"lang",
"=",
"None",
")",
":",
"if",
"concepts",
"is",
"None",
":",
"concepts",
"=",
"self",
".",
"filter",
"(",
"active",
"=",
"True",
")",
"if",
"lang",
"is",
"not",
... | 44.695652 | 0.00381 |
def timestr_mod24(timestr: str) -> int:
"""
Given a GTFS HH:MM:SS time string, return a timestring in the same
format but with the hours taken modulo 24.
"""
try:
hours, mins, secs = [int(x) for x in timestr.split(":")]
hours %= 24
result = f"{hours:02d}:{mins:02d}:{secs:02d}... | [
"def",
"timestr_mod24",
"(",
"timestr",
":",
"str",
")",
"->",
"int",
":",
"try",
":",
"hours",
",",
"mins",
",",
"secs",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"timestr",
".",
"split",
"(",
"\":\"",
")",
"]",
"hours",
"%=",
"24",
"r... | 30.166667 | 0.005362 |
def transmission_rate(self):
"""
Returns the upstream, downstream values as a tuple in bytes per
second. Use this for periodical calling.
"""
sent = self.bytes_sent
received = self.bytes_received
traffic_call = time.time()
time_delta = traffic_call - self.... | [
"def",
"transmission_rate",
"(",
"self",
")",
":",
"sent",
"=",
"self",
".",
"bytes_sent",
"received",
"=",
"self",
".",
"bytes_received",
"traffic_call",
"=",
"time",
".",
"time",
"(",
")",
"time_delta",
"=",
"traffic_call",
"-",
"self",
".",
"last_traffic_... | 42.466667 | 0.004608 |
def completions(self):
"""
Return :class:`classes.Completion` objects. Those objects contain
information about the completions, more than just names.
:return: Completion objects, sorted by name.
:rtype: list of :class:`classes.Completion`
"""
debug.speed('complet... | [
"def",
"completions",
"(",
"self",
")",
":",
"debug",
".",
"speed",
"(",
"'completions start'",
")",
"comps",
"=",
"self",
".",
"_evaluator",
".",
"complete",
"(",
")",
"debug",
".",
"speed",
"(",
"'completions end'",
")",
"return",
"sorted",
"(",
"comps",... | 35.692308 | 0.004202 |
def is_file(value, **kwargs):
"""Indicate whether ``value`` is a file that exists on the local filesystem.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplica... | [
"def",
"is_file",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"value",
"=",
"validators",
".",
"file_exists",
"(",
"value",
",",
"*",
"*",
"kwargs",
")",
"except",
"SyntaxError",
"as",
"error",
":",
"raise",
"error",
"except",
"Excepti... | 29.15 | 0.004983 |
def profile_df(df):
""" Generate a profile of data in a dataframe.
Args:
df: the Pandas dataframe.
"""
# The bootstrap CSS messes up the Datalab display so we tweak it to not have an effect.
# TODO(gram): strip it out rather than this kludge.
return IPython.core.display.HTML(
pandas_profiling.Pro... | [
"def",
"profile_df",
"(",
"df",
")",
":",
"# The bootstrap CSS messes up the Datalab display so we tweak it to not have an effect.",
"# TODO(gram): strip it out rather than this kludge.",
"return",
"IPython",
".",
"core",
".",
"display",
".",
"HTML",
"(",
"pandas_profiling",
".",... | 36.7 | 0.018617 |
def restore_definition(self, project, definition_id, deleted):
"""RestoreDefinition.
Restores a deleted definition
:param str project: Project ID or project name
:param int definition_id: The identifier of the definition to restore.
:param bool deleted: When false, restores a del... | [
"def",
"restore_definition",
"(",
"self",
",",
"project",
",",
"definition_id",
",",
"deleted",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
... | 55.363636 | 0.00565 |
def started(name):
'''
Check if volume has been started
name
name of the volume
.. code-block:: yaml
mycluster:
glusterfs.started: []
'''
ret = {'name': name,
'changes': {},
'comment': '',
'result': False}
volinfo = __salt__['glu... | [
"def",
"started",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'result'",
":",
"False",
"}",
"volinfo",
"=",
"__salt__",
"[",
"'glusterfs.info'",
"]",
"(",
")",
"... | 26.071429 | 0.00088 |
def _create_warm_start_tuner(self, additional_parents, warm_start_type, estimator=None):
"""Creates a new ``HyperparameterTuner`` with ``WarmStartConfig``, where type will be equal to
``warm_start_type`` and``parents`` would be equal to union of ``additional_parents`` and self.
Args:
... | [
"def",
"_create_warm_start_tuner",
"(",
"self",
",",
"additional_parents",
",",
"warm_start_type",
",",
"estimator",
"=",
"None",
")",
":",
"all_parents",
"=",
"{",
"self",
".",
"latest_tuning_job",
".",
"name",
"}",
"if",
"additional_parents",
":",
"all_parents",... | 61.25 | 0.008707 |
def operate_on_bulb(self, method, params=None):
"""
Build socket and send command to the bulb through it
:param method: method you want to use
:param params: parameters needed for this method (can be a string if ony one parameter is needed)
:type method: str
... | [
"def",
"operate_on_bulb",
"(",
"self",
",",
"method",
",",
"params",
"=",
"None",
")",
":",
"# Get the message",
"self",
".",
"command",
"=",
"YeelightCommand",
"(",
"self",
".",
"next_cmd_id",
"(",
")",
",",
"method",
",",
"params",
")",
"# Send with socket... | 41.3 | 0.00355 |
def __create_table_if_not_exists(self):
# type: () -> None
"""Creates table in Dynamodb resource if it doesn't exist and
create_table is set as True.
:rtype: None
:raises: PersistenceException: When `create_table` fails on
dynamodb resource.
"""
if se... | [
"def",
"__create_table_if_not_exists",
"(",
"self",
")",
":",
"# type: () -> None",
"if",
"self",
".",
"create_table",
":",
"try",
":",
"self",
".",
"dynamodb",
".",
"create_table",
"(",
"TableName",
"=",
"self",
".",
"table_name",
",",
"KeySchema",
"=",
"[",
... | 37.368421 | 0.002059 |
def create_working_dir(config, prefix):
'''
Create a fresh temporary directory, based on the fiven prefix.
Returns the new path.
'''
# Fetch base directory from executor configuration
basepath = config.get("Execution", "directory")
if not prefix:
prefix = 'opensubmit'
f... | [
"def",
"create_working_dir",
"(",
"config",
",",
"prefix",
")",
":",
"# Fetch base directory from executor configuration",
"basepath",
"=",
"config",
".",
"get",
"(",
"\"Execution\"",
",",
"\"directory\"",
")",
"if",
"not",
"prefix",
":",
"prefix",
"=",
"'opensubmit... | 31.352941 | 0.001821 |
def max_variance_genes(data, nbins=5, frac=0.2):
"""
This function identifies the genes that have the max variance
across a number of bins sorted by mean.
Args:
data (array): genes x cells
nbins (int): number of bins to sort genes by mean expression level. Default: 10.
frac (flo... | [
"def",
"max_variance_genes",
"(",
"data",
",",
"nbins",
"=",
"5",
",",
"frac",
"=",
"0.2",
")",
":",
"# TODO: profile, make more efficient for large matrices",
"# 8000 cells: 0.325 seconds",
"# top time: sparse.csc_tocsr, csc_matvec, astype, copy, mul_scalar",
"# 73233 cells: 5.347... | 35.930233 | 0.004411 |
def _load_calib(self):
"""Load and compute intrinsic and extrinsic calibration parameters."""
# We'll build the calibration parameters as a dictionary, then
# convert it to a namedtuple to prevent it from being modified later
data = {}
# Load the calibration file
calib_f... | [
"def",
"_load_calib",
"(",
"self",
")",
":",
"# We'll build the calibration parameters as a dictionary, then",
"# convert it to a namedtuple to prevent it from being modified later",
"data",
"=",
"{",
"}",
"# Load the calibration file",
"calib_filepath",
"=",
"os",
".",
"path",
"... | 43.581818 | 0.000816 |
def list_domains(**kwargs):
'''
Return a list of available domains.
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versionadded:: 2019.2.0
:param password: password to conn... | [
"def",
"list_domains",
"(",
"*",
"*",
"kwargs",
")",
":",
"vms",
"=",
"[",
"]",
"conn",
"=",
"__get_conn",
"(",
"*",
"*",
"kwargs",
")",
"for",
"dom",
"in",
"_get_domain",
"(",
"conn",
",",
"iterable",
"=",
"True",
")",
":",
"vms",
".",
"append",
... | 23.269231 | 0.001587 |
def _identifier_filtered_iterator(graph):
"""Iterate over names in the given namespace."""
for data in graph:
for pair in _get_node_names(data):
yield pair
for member in data.get(MEMBERS, []):
for pair in _get_node_names(member):
yield pair
for ((_, ... | [
"def",
"_identifier_filtered_iterator",
"(",
"graph",
")",
":",
"for",
"data",
"in",
"graph",
":",
"for",
"pair",
"in",
"_get_node_names",
"(",
"data",
")",
":",
"yield",
"pair",
"for",
"member",
"in",
"data",
".",
"get",
"(",
"MEMBERS",
",",
"[",
"]",
... | 37.393939 | 0.00237 |
def register_device(ctx, device, model, nickname, client_type):
"""Registers a device instance under an existing device model.
Device instance fields must start with a letter or number. The device ID
can only contain letters, numbers, and the following symbols: period (.),
hyphen (-), underscore (_), a... | [
"def",
"register_device",
"(",
"ctx",
",",
"device",
",",
"model",
",",
"nickname",
",",
"client_type",
")",
":",
"session",
",",
"api_url",
",",
"project_id",
"=",
"build_client_from_context",
"(",
"ctx",
")",
"device_base_url",
"=",
"'/'",
".",
"join",
"("... | 41.828571 | 0.000668 |
def stop(self):
""" Stop all functions running in the thread handler."""
for run_event in self.run_events:
run_event.clear()
for thread in self.thread_pool:
thread.join() | [
"def",
"stop",
"(",
"self",
")",
":",
"for",
"run_event",
"in",
"self",
".",
"run_events",
":",
"run_event",
".",
"clear",
"(",
")",
"for",
"thread",
"in",
"self",
".",
"thread_pool",
":",
"thread",
".",
"join",
"(",
")"
] | 30.428571 | 0.009132 |
def print_evaluation(period=1, show_stdv=True):
"""Create a callback that prints the evaluation results.
Parameters
----------
period : int, optional (default=1)
The period to print the evaluation results.
show_stdv : bool, optional (default=True)
Whether to show stdv (if provided).... | [
"def",
"print_evaluation",
"(",
"period",
"=",
"1",
",",
"show_stdv",
"=",
"True",
")",
":",
"def",
"_callback",
"(",
"env",
")",
":",
"if",
"period",
">",
"0",
"and",
"env",
".",
"evaluation_result_list",
"and",
"(",
"env",
".",
"iteration",
"+",
"1",... | 36.666667 | 0.005063 |
def smart_search_prefix(self):
""" Perform a smart search.
The smart search function tries extract a query from
a text string. This query is then passed to the search_prefix
function, which performs the search.
"""
search_options = {}
extra_query = N... | [
"def",
"smart_search_prefix",
"(",
"self",
")",
":",
"search_options",
"=",
"{",
"}",
"extra_query",
"=",
"None",
"vrf_filter",
"=",
"None",
"if",
"'query_id'",
"in",
"request",
".",
"json",
":",
"search_options",
"[",
"'query_id'",
"]",
"=",
"request",
".",... | 38.447619 | 0.000966 |
def _get_stitch_report_path(self):
"""Checks if stitch report label / path is set. Returns absolute path."""
if self.Parameters['-r'].isOn():
stitch_path = self._absolute(str(self.Parameters['-r'].Value))
return stitch_path
elif self.Parameters['-r'].isOff():
... | [
"def",
"_get_stitch_report_path",
"(",
"self",
")",
":",
"if",
"self",
".",
"Parameters",
"[",
"'-r'",
"]",
".",
"isOn",
"(",
")",
":",
"stitch_path",
"=",
"self",
".",
"_absolute",
"(",
"str",
"(",
"self",
".",
"Parameters",
"[",
"'-r'",
"]",
".",
"... | 46.428571 | 0.009063 |
def set_nightlight(self, state):
"""Sets the night light state of the smart plug"""
packet = bytearray(16)
packet[0] = 2
if self.check_power():
packet[4] = 3 if state else 1
else:
packet[4] = 2 if state else 0
self.send_packet(0x6a, packet) | [
"def",
"set_nightlight",
"(",
"self",
",",
"state",
")",
":",
"packet",
"=",
"bytearray",
"(",
"16",
")",
"packet",
"[",
"0",
"]",
"=",
"2",
"if",
"self",
".",
"check_power",
"(",
")",
":",
"packet",
"[",
"4",
"]",
"=",
"3",
"if",
"state",
"else"... | 29.777778 | 0.01087 |
def on_site(self, site_id=None):
"""Return a :class:`QuerySet` of pages that are published on the site
defined by the ``SITE_ID`` setting.
:param site_id: specify the id of the site object to filter with.
"""
if settings.PAGE_USE_SITE_ID:
if not site_id:
... | [
"def",
"on_site",
"(",
"self",
",",
"site_id",
"=",
"None",
")",
":",
"if",
"settings",
".",
"PAGE_USE_SITE_ID",
":",
"if",
"not",
"site_id",
":",
"site_id",
"=",
"settings",
".",
"SITE_ID",
"return",
"self",
".",
"filter",
"(",
"sites",
"=",
"site_id",
... | 37.454545 | 0.004739 |
def set_mode(self, mode):
"""Configure how this console will react to the cursor writing past the
end if the console.
This is for methods that use the virtual cursor, such as
:any:`print_str`.
Args:
mode (Text): The mode to set.
Possible settings are:
... | [
"def",
"set_mode",
"(",
"self",
",",
"mode",
")",
":",
"MODES",
"=",
"[",
"'error'",
",",
"'scroll'",
"]",
"if",
"mode",
".",
"lower",
"(",
")",
"not",
"in",
"MODES",
":",
"raise",
"TDLError",
"(",
"'mode must be one of %s, got %s'",
"%",
"(",
"MODES",
... | 35.592593 | 0.00304 |
def refresh_manifest(self, synchronous=True, **kwargs):
"""Refresh previously imported manifest for Red Hat provider.
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return th... | [
"def",
"refresh_manifest",
"(",
"self",
",",
"synchronous",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"kwargs",
".",
"copy",
"(",
")",
"# shadow the passed-in kwargs",
"kwargs",
".",
"update",
"(",
"self",
".",
"_server_config",
".",
"... | 40.708333 | 0.002 |
def extend_name(suffix):
"""A factory for class decorators that modify the class name by appending some text to it.
Example:
@extend_name('_Foo')
class Class:
pass
assert Class.__name__ == 'Class_Foo'
"""
def dec(cls):
name = '{}{}'.format(cls.__name__, su... | [
"def",
"extend_name",
"(",
"suffix",
")",
":",
"def",
"dec",
"(",
"cls",
")",
":",
"name",
"=",
"'{}{}'",
".",
"format",
"(",
"cls",
".",
"__name__",
",",
"suffix",
")",
"setattr",
"(",
"cls",
",",
"'__name__'",
",",
"name",
")",
"return",
"cls",
"... | 21.222222 | 0.005013 |
def _build_key_wrapping_specification(self, value):
"""
Build a KeyWrappingSpecification struct from a dictionary.
Args:
value (dict): A dictionary containing the key/value pairs for a
KeyWrappingSpecification struct.
Returns:
KeyWrappingSpecific... | [
"def",
"_build_key_wrapping_specification",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"Key wrapping specification must be ... | 37.647059 | 0.001523 |
def clustal_align_protein(recs, work_dir, outfmt="fasta"):
"""
Align given proteins with clustalw.
recs are iterable of Biopython SeqIO objects
"""
fasta_file = op.join(work_dir, "prot-start.fasta")
align_file = op.join(work_dir, "prot.aln")
SeqIO.write(recs, file(fasta_file, "w"), "fasta")
... | [
"def",
"clustal_align_protein",
"(",
"recs",
",",
"work_dir",
",",
"outfmt",
"=",
"\"fasta\"",
")",
":",
"fasta_file",
"=",
"op",
".",
"join",
"(",
"work_dir",
",",
"\"prot-start.fasta\"",
")",
"align_file",
"=",
"op",
".",
"join",
"(",
"work_dir",
",",
"\... | 37.333333 | 0.003731 |
def _refresh(self, http):
"""Refreshes the access token.
Since the underlying App Engine app_identity implementation does its
own caching we can skip all the storage hoops and just to a refresh
using the API.
Args:
http: unused HTTP object
Raises:
... | [
"def",
"_refresh",
"(",
"self",
",",
"http",
")",
":",
"try",
":",
"scopes",
"=",
"self",
".",
"scope",
".",
"split",
"(",
")",
"(",
"token",
",",
"_",
")",
"=",
"app_identity",
".",
"get_access_token",
"(",
"scopes",
",",
"service_account_id",
"=",
... | 33.6 | 0.002894 |
def generateInstaller(self, outpath='.', signed=False):
"""
Generates the installer for this builder.
:param outpath | <str>
"""
log.info('Generating Installer....')
# generate the options for the installer
opts = {
'name': self.name(),
... | [
"def",
"generateInstaller",
"(",
"self",
",",
"outpath",
"=",
"'.'",
",",
"signed",
"=",
"False",
")",
":",
"log",
".",
"info",
"(",
"'Generating Installer....'",
")",
"# generate the options for the installer",
"opts",
"=",
"{",
"'name'",
":",
"self",
".",
"n... | 36.543307 | 0.001259 |
def _or16(ins):
''' Compares & pops top 2 operands out of the stack, and checks
if the 1st operand OR (logical) 2nd operand (top of the stack),
pushes 0 if False, 1 if True.
16 bit un/signed version
Optimizations:
If any of the operators are constants: Returns either 0 or
... | [
"def",
"_or16",
"(",
"ins",
")",
":",
"op1",
",",
"op2",
"=",
"tuple",
"(",
"ins",
".",
"quad",
"[",
"2",
":",
"]",
")",
"if",
"_int_ops",
"(",
"op1",
",",
"op2",
")",
"is",
"not",
"None",
":",
"op1",
",",
"op2",
"=",
"_int_ops",
"(",
"op1",
... | 28.305556 | 0.000949 |
def remove_component(self, name):
"""Removes an existing component with a given name, invalidating all the values computed by
the previous component."""
if name not in self.components:
raise Exception("No component named %s" % name)
del self.components[name]
del self.... | [
"def",
"remove_component",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
"not",
"in",
"self",
".",
"components",
":",
"raise",
"Exception",
"(",
"\"No component named %s\"",
"%",
"name",
")",
"del",
"self",
".",
"components",
"[",
"name",
"]",
"del",
... | 41.818182 | 0.006383 |
def translate_paths (properties, path):
""" Interpret all path properties in 'properties' as relative to 'path'
The property values are assumed to be in system-specific form, and
will be translated into normalized form.
"""
assert is_iterable_typed(properties, Property)
result = []
... | [
"def",
"translate_paths",
"(",
"properties",
",",
"path",
")",
":",
"assert",
"is_iterable_typed",
"(",
"properties",
",",
"Property",
")",
"result",
"=",
"[",
"]",
"for",
"p",
"in",
"properties",
":",
"if",
"p",
".",
"feature",
".",
"path",
":",
"values... | 30.208333 | 0.005348 |
def predict(self, h=5):
""" Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
Returns
----------
- pd.DataFrame with predicted values
"""
... | [
"def",
"predict",
"(",
"self",
",",
"h",
"=",
"5",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
"estimated",
"is",
"False",
":",
"raise",
"Exception",
"(",
"\"No latent variables estimated!\"",
")",
"else",
":",
"predictions",
",",
"_",
",",
"_",
... | 34.666667 | 0.011696 |
def _process_key_val(self, instance, key, val):
'''
Logic to let the plugin instance process the redis key/val
Split out for unit testing
@param instance: the plugin instance
@param key: the redis key
@param val: the key value from redis
'''
if instance.c... | [
"def",
"_process_key_val",
"(",
"self",
",",
"instance",
",",
"key",
",",
"val",
")",
":",
"if",
"instance",
".",
"check_precondition",
"(",
"key",
",",
"val",
")",
":",
"combined",
"=",
"'{k}:{v}'",
".",
"format",
"(",
"k",
"=",
"key",
",",
"v",
"="... | 38.2 | 0.002554 |
def get_policy_for_vhost(self, vhost, name):
"""
Get a specific policy for a vhost.
:param vhost: The virtual host the policy is for
:type vhost: str
:param name: The name of the policy
:type name: str
"""
return self._api_get('/api/policies/{0}/{1}'.form... | [
"def",
"get_policy_for_vhost",
"(",
"self",
",",
"vhost",
",",
"name",
")",
":",
"return",
"self",
".",
"_api_get",
"(",
"'/api/policies/{0}/{1}'",
".",
"format",
"(",
"urllib",
".",
"parse",
".",
"quote_plus",
"(",
"vhost",
")",
",",
"urllib",
".",
"parse... | 31.461538 | 0.004751 |
def _ParseEntryArrayObject(self, file_object, file_offset):
"""Parses an entry array object.
Args:
file_object (dfvfs.FileIO): a file-like object.
file_offset (int): offset of the entry array object relative to the start
of the file-like object.
Returns:
systemd_journal_entry_a... | [
"def",
"_ParseEntryArrayObject",
"(",
"self",
",",
"file_object",
",",
"file_offset",
")",
":",
"entry_array_object_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'systemd_journal_entry_array_object'",
")",
"try",
":",
"entry_array_object",
",",
"_",
"=",
"self",
... | 36.5 | 0.00471 |
def in6_mactoifaceid(mac, ulbit=None):
"""
Compute the interface ID in modified EUI-64 format associated
to the Ethernet address provided as input.
value taken by U/L bit in the interface identifier is basically
the reversed value of that in given MAC address it can be forced
to a specific value... | [
"def",
"in6_mactoifaceid",
"(",
"mac",
",",
"ulbit",
"=",
"None",
")",
":",
"if",
"len",
"(",
"mac",
")",
"!=",
"17",
":",
"return",
"None",
"m",
"=",
"\"\"",
".",
"join",
"(",
"mac",
".",
"split",
"(",
"':'",
")",
")",
"if",
"len",
"(",
"m",
... | 37.6 | 0.001297 |
def set_cors_config(app):
"""
Flask-Cors (3.x.x) extension set the config as CORS_*,
But we'll hold the config in CORS key.
This function will convert them to CORS_* values
:param app:
:return:
"""
if "CORS" in app.config:
for k, v in app.config["CORS"].items():
_ =... | [
"def",
"set_cors_config",
"(",
"app",
")",
":",
"if",
"\"CORS\"",
"in",
"app",
".",
"config",
":",
"for",
"k",
",",
"v",
"in",
"app",
".",
"config",
"[",
"\"CORS\"",
"]",
".",
"items",
"(",
")",
":",
"_",
"=",
"\"CORS_\"",
"+",
"k",
".",
"upper",... | 30.615385 | 0.002439 |
def get_splits_up_to(self, date_to: datetime) -> List[Split]:
""" returns splits only up to the given date """
query = (
self.book.session.query(Split)
.join(Transaction)
.filter(Split.account == self.account,
Transaction.post_date <= date_to.date(... | [
"def",
"get_splits_up_to",
"(",
"self",
",",
"date_to",
":",
"datetime",
")",
"->",
"List",
"[",
"Split",
"]",
":",
"query",
"=",
"(",
"self",
".",
"book",
".",
"session",
".",
"query",
"(",
"Split",
")",
".",
"join",
"(",
"Transaction",
")",
".",
... | 39 | 0.005571 |
def set_properties(self, subset=None, **kwargs):
"""
Convenience method for setting one or more non-data dependent
properties or each cell.
Parameters
----------
subset : IndexSlice
a valid slice for ``data`` to limit the style application to
kwargs :... | [
"def",
"set_properties",
"(",
"self",
",",
"subset",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"values",
"=",
"';'",
".",
"join",
"(",
"'{p}: {v}'",
".",
"format",
"(",
"p",
"=",
"p",
",",
"v",
"=",
"v",
")",
"for",
"p",
",",
"v",
"in",
... | 32.076923 | 0.003492 |
def add_module_file(plpy, td):
"""Database trigger for adding a module file.
When a legacy ``index.cnxml`` is added, this trigger
transforms it into html and stores it as ``index.cnxml.html``.
When a cnx-publishing ``index.cnxml.html`` is added, this trigger
checks if ``index.html.cnxml`` exists be... | [
"def",
"add_module_file",
"(",
"plpy",
",",
"td",
")",
":",
"module_ident",
"=",
"td",
"[",
"'new'",
"]",
"[",
"'module_ident'",
"]",
"filename",
"=",
"td",
"[",
"'new'",
"]",
"[",
"'filename'",
"]",
"msg",
"=",
"\"produce {}->{} for module_ident = {}\"",
"d... | 37.384615 | 0.000401 |
def add_service(self, name, long_name, preregistered=False, notify=True):
"""Add a service to the list of tracked services.
Args:
name (string): A unique short service name for the service
long_name (string): A longer, user friendly name for the service
preregistered... | [
"def",
"add_service",
"(",
"self",
",",
"name",
",",
"long_name",
",",
"preregistered",
"=",
"False",
",",
"notify",
"=",
"True",
")",
":",
"if",
"name",
"in",
"self",
".",
"services",
":",
"raise",
"ArgumentError",
"(",
"\"Could not add service because the lo... | 33.59375 | 0.004521 |
def get_environ(self, sock):
"""Create WSGI environ entries to be merged into each request."""
cipher = sock.cipher()
ssl_environ = {
"wsgi.url_scheme": "https",
"HTTPS": "on",
'SSL_PROTOCOL': cipher[1],
'SSL_CIPHER': cipher[0]
## SSL_VE... | [
"def",
"get_environ",
"(",
"self",
",",
"sock",
")",
":",
"cipher",
"=",
"sock",
".",
"cipher",
"(",
")",
"ssl_environ",
"=",
"{",
"\"wsgi.url_scheme\"",
":",
"\"https\"",
",",
"\"HTTPS\"",
":",
"\"on\"",
",",
"'SSL_PROTOCOL'",
":",
"cipher",
"[",
"1",
"... | 39.416667 | 0.012397 |
def evalfunc(cls, func, *args, **kwargs):
"""Evaluate a function with error propagation.
Inputs:
-------
``func``: callable
this is the function to be evaluated. Should return either a
number or a np.ndarray.
``*args``: other positional ar... | [
"def",
"evalfunc",
"(",
"cls",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"do_random",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"cls",
")",
":",
"return",
"x",
".",
"random",
"(",
")",
"else",
":",
... | 41.590164 | 0.001925 |
def resources(self,
start=1,
num=10):
"""
Resources lists all file resources for the organization. The start
and num paging parameters are supported.
Inputs:
start - the number of the first entry in the result set response
... | [
"def",
"resources",
"(",
"self",
",",
"start",
"=",
"1",
",",
"num",
"=",
"10",
")",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/resources\"",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"start\"",
":",
"start",
",",
"\"num\"",
":",
"nu... | 36.608696 | 0.012731 |
def _Backward3_v_Ph(P, h):
"""Backward equation for region 3, v=f(P,h)
Parameters
----------
P : float
Pressure, [MPa]
h : float
Specific enthalpy, [kJ/kg]
Returns
-------
v : float
Specific volume, [m³/kg]
"""
hf = _h_3ab(P)
if h <= hf:
retu... | [
"def",
"_Backward3_v_Ph",
"(",
"P",
",",
"h",
")",
":",
"hf",
"=",
"_h_3ab",
"(",
"P",
")",
"if",
"h",
"<=",
"hf",
":",
"return",
"_Backward3a_v_Ph",
"(",
"P",
",",
"h",
")",
"else",
":",
"return",
"_Backward3b_v_Ph",
"(",
"P",
",",
"h",
")"
] | 18.7 | 0.002545 |
def nvmlDeviceSetComputeMode(handle, mode):
r"""
/**
* Set the compute mode for the device.
*
* For all products.
* Requires root/admin permissions.
*
* The compute mode determines whether a GPU can be used for compute operations and whether it can
* be shared across contexts.... | [
"def",
"nvmlDeviceSetComputeMode",
"(",
"handle",
",",
"mode",
")",
":",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlDeviceSetComputeMode\"",
")",
"ret",
"=",
"fn",
"(",
"handle",
",",
"_nvmlComputeMode_t",
"(",
"mode",
")",
")",
"_nvmlCheckReturn",
"(",
"... | 46.421053 | 0.005552 |
def resp2flask(resp):
"""Convert an oic.utils.http_util instance to Flask."""
if isinstance(resp, Redirect) or isinstance(resp, SeeOther):
code = int(resp.status.split()[0])
raise cherrypy.HTTPRedirect(resp.message, code)
return resp.message, resp.status, resp.headers | [
"def",
"resp2flask",
"(",
"resp",
")",
":",
"if",
"isinstance",
"(",
"resp",
",",
"Redirect",
")",
"or",
"isinstance",
"(",
"resp",
",",
"SeeOther",
")",
":",
"code",
"=",
"int",
"(",
"resp",
".",
"status",
".",
"split",
"(",
")",
"[",
"0",
"]",
... | 48.5 | 0.003378 |
def value(self, n: Node) -> str:
"""Return the text value of the node"""
id_n = id(n)
idcache = self.id_cache
if id_n not in idcache:
return ""
name = idcache[id_n]
tag_cache = self.tag_cache
if name not in tag_cache:
raise Exception("Incoh... | [
"def",
"value",
"(",
"self",
",",
"n",
":",
"Node",
")",
"->",
"str",
":",
"id_n",
"=",
"id",
"(",
"n",
")",
"idcache",
"=",
"self",
".",
"id_cache",
"if",
"id_n",
"not",
"in",
"idcache",
":",
"return",
"\"\"",
"name",
"=",
"idcache",
"[",
"id_n"... | 33.625 | 0.003617 |
def institutes():
"""Display a list of all user institutes."""
institute_objs = user_institutes(store, current_user)
institutes = []
for ins_obj in institute_objs:
sanger_recipients = []
for user_mail in ins_obj.get('sanger_recipients',[]):
user_obj = store.user(user_mail)
... | [
"def",
"institutes",
"(",
")",
":",
"institute_objs",
"=",
"user_institutes",
"(",
"store",
",",
"current_user",
")",
"institutes",
"=",
"[",
"]",
"for",
"ins_obj",
"in",
"institute_objs",
":",
"sanger_recipients",
"=",
"[",
"]",
"for",
"user_mail",
"in",
"i... | 39.08 | 0.002997 |
def reload(self):
"""
Reload configuration
"""
self.read_config()
for section in self._override_config:
self.set_section_config(section, self._override_config[section]) | [
"def",
"reload",
"(",
"self",
")",
":",
"self",
".",
"read_config",
"(",
")",
"for",
"section",
"in",
"self",
".",
"_override_config",
":",
"self",
".",
"set_section_config",
"(",
"section",
",",
"self",
".",
"_override_config",
"[",
"section",
"]",
")"
] | 26.75 | 0.00905 |
def put(self, request, *args, **kwargs):
""" custom put method to support django-reversion """
with reversion.create_revision():
reversion.set_user(request.user)
reversion.set_comment('changed through the RESTful API from ip %s' % request.META['REMOTE_ADDR'])
return s... | [
"def",
"put",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"reversion",
".",
"create_revision",
"(",
")",
":",
"reversion",
".",
"set_user",
"(",
"request",
".",
"user",
")",
"reversion",
".",
"set_comment",... | 58.5 | 0.008427 |
def multizone_member_added(self, member_uuid):
"""Handle added audio group member."""
casts = self._casts
if member_uuid not in casts:
casts[member_uuid] = {'listeners': [],
'groups': set()}
casts[member_uuid]['groups'].add(self._group_uuid)
... | [
"def",
"multizone_member_added",
"(",
"self",
",",
"member_uuid",
")",
":",
"casts",
"=",
"self",
".",
"_casts",
"if",
"member_uuid",
"not",
"in",
"casts",
":",
"casts",
"[",
"member_uuid",
"]",
"=",
"{",
"'listeners'",
":",
"[",
"]",
",",
"'groups'",
":... | 48 | 0.004545 |
def element_id_by_label(browser, label):
"""Return the id of a label's for attribute"""
label = XPathSelector(browser,
unicode('//label[contains(., "%s")]' % label))
if not label:
return False
return label.get_attribute('for') | [
"def",
"element_id_by_label",
"(",
"browser",
",",
"label",
")",
":",
"label",
"=",
"XPathSelector",
"(",
"browser",
",",
"unicode",
"(",
"'//label[contains(., \"%s\")]'",
"%",
"label",
")",
")",
"if",
"not",
"label",
":",
"return",
"False",
"return",
"label",... | 38.571429 | 0.003623 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.