text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_series_by_name(self, series_name):
"""Perform lookup for series
:param str series_name: series name found within filename
:returns: instance of series
:rtype: object
"""
series = trakt.Trakt['search'].query(series_name, 'show')
if not series:
... | [
"def",
"get_series_by_name",
"(",
"self",
",",
"series_name",
")",
":",
"series",
"=",
"trakt",
".",
"Trakt",
"[",
"'search'",
"]",
".",
"query",
"(",
"series_name",
",",
"'show'",
")",
"if",
"not",
"series",
":",
"return",
"None",
",",
"'Not Found'",
"r... | 33.181818 | 13.272727 |
def add_node(self, info):
""" Handles adding a Node to the graph.
"""
if not info.initialized:
return
graph = self._request_graph(info.ui.control)
if graph is None:
return
IDs = [v.ID for v in graph.nodes]
node = Node(ID=make_unique_name... | [
"def",
"add_node",
"(",
"self",
",",
"info",
")",
":",
"if",
"not",
"info",
".",
"initialized",
":",
"return",
"graph",
"=",
"self",
".",
"_request_graph",
"(",
"info",
".",
"ui",
".",
"control",
")",
"if",
"graph",
"is",
"None",
":",
"return",
"IDs"... | 26 | 19.263158 |
def __assert_equal(expected, returned, assert_print_result=True):
'''
Test if two objects are equal
'''
result = "Pass"
try:
if assert_print_result:
assert (expected == returned), "{0} is not equal to {1}".format(expected, returned)
else:
... | [
"def",
"__assert_equal",
"(",
"expected",
",",
"returned",
",",
"assert_print_result",
"=",
"True",
")",
":",
"result",
"=",
"\"Pass\"",
"try",
":",
"if",
"assert_print_result",
":",
"assert",
"(",
"expected",
"==",
"returned",
")",
",",
"\"{0} is not equal to {... | 34.714286 | 22.714286 |
def pickle_dump(self):
"""Save the status of the object in pickle format."""
with open(os.path.join(self.workdir, self.PICKLE_FNAME), mode="wb") as fh:
pickle.dump(self, fh) | [
"def",
"pickle_dump",
"(",
"self",
")",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"workdir",
",",
"self",
".",
"PICKLE_FNAME",
")",
",",
"mode",
"=",
"\"wb\"",
")",
"as",
"fh",
":",
"pickle",
".",
"dump",
"(",
"s... | 49.5 | 16.75 |
def print_defaults():
"""Pretty-print the contents of :data:`DEFAULTS`"""
maxlen = max([len(x) for x in DEFAULTS])
for key in DEFAULTS:
value = DEFAULTS[key]
if isinstance(value, (list, set)):
value = ', '.join(value)
print "%*s: %s" % (maxlen, key, value) | [
"def",
"print_defaults",
"(",
")",
":",
"maxlen",
"=",
"max",
"(",
"[",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"DEFAULTS",
"]",
")",
"for",
"key",
"in",
"DEFAULTS",
":",
"value",
"=",
"DEFAULTS",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"value",
... | 37.125 | 7.75 |
def format_tsv_line(source, edge, target, value=None, metadata=None):
"""
Render a single line for TSV file with data flow described
:type source str
:type edge str
:type target str
:type value float
:type metadata str
:rtype: str
"""
return '{source}\t{edge}\t{target}\t{value}\... | [
"def",
"format_tsv_line",
"(",
"source",
",",
"edge",
",",
"target",
",",
"value",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"return",
"'{source}\\t{edge}\\t{target}\\t{value}\\t{metadata}'",
".",
"format",
"(",
"source",
"=",
"source",
",",
"edge",
... | 28.166667 | 19.833333 |
def make_docs(*args, **kwargs):
"""Make the documents for a `Request` or `Reply`.
Takes a variety of argument styles, returns a list of dicts.
Used by `make_prototype_request` and `make_reply`, which are in turn used by
`MockupDB.receives`, `Request.replies`, and so on. See examples in
tutorial.
... | [
"def",
"make_docs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"err_msg",
"=",
"\"Can't interpret args: \"",
"if",
"not",
"args",
"and",
"not",
"kwargs",
":",
"return",
"[",
"]",
"if",
"not",
"args",
":",
"# OpReply(ok=1, ismaster=True).",
"return"... | 31.581818 | 19.109091 |
def validate_response(self, iface_name, func_name, resp):
"""
Validates that the response matches the return type for the function
Returns two element tuple: (bool, string)
- `bool` - True if valid, False if not
- `string` - Description of validation error, or None if valid
... | [
"def",
"validate_response",
"(",
"self",
",",
"iface_name",
",",
"func_name",
",",
"resp",
")",
":",
"self",
".",
"interface",
"(",
"iface_name",
")",
".",
"function",
"(",
"func_name",
")",
".",
"validate_response",
"(",
"resp",
")"
] | 31.888889 | 20.666667 |
def reporter(self):
"""
Creates .xlsx reports using xlsxwriter
"""
# Create a workbook to store the report. Using xlsxwriter rather than a simple csv format, as I want to be
# able to have appropriately sized, multi-line cells
workbook = xlsxwriter.Workbook(os.path.join(s... | [
"def",
"reporter",
"(",
"self",
")",
":",
"# Create a workbook to store the report. Using xlsxwriter rather than a simple csv format, as I want to be",
"# able to have appropriately sized, multi-line cells",
"workbook",
"=",
"xlsxwriter",
".",
"Workbook",
"(",
"os",
".",
"path",
".... | 57.796296 | 25.722222 |
def make_serviceitem_name(name, condition='is', negate=False, preserve_case=False):
"""
Create a node for ServiceItem/name
:return: A IndicatorItem represented as an Element node
"""
document = 'ServiceItem'
search = 'ServiceItem/name'
content_type = 'string'
content = name
ii_n... | [
"def",
"make_serviceitem_name",
"(",
"name",
",",
"condition",
"=",
"'is'",
",",
"negate",
"=",
"False",
",",
"preserve_case",
"=",
"False",
")",
":",
"document",
"=",
"'ServiceItem'",
"search",
"=",
"'ServiceItem/name'",
"content_type",
"=",
"'string'",
"conten... | 38.923077 | 21.846154 |
def get(src_hdfs_path, dest_path, **kwargs):
"""\
Copy the contents of ``src_hdfs_path`` to ``dest_path``.
``dest_path`` is forced to be interpreted as an ordinary local
path (see :func:`~path.abspath`). The source file is opened for
reading and the copy is opened for writing. Additional keyword
... | [
"def",
"get",
"(",
"src_hdfs_path",
",",
"dest_path",
",",
"*",
"*",
"kwargs",
")",
":",
"cp",
"(",
"src_hdfs_path",
",",
"path",
".",
"abspath",
"(",
"dest_path",
",",
"local",
"=",
"True",
")",
",",
"*",
"*",
"kwargs",
")"
] | 44.2 | 18.7 |
def _astoref16(ins):
''' Stores 2º operand content into address of 1st operand.
storef16 a, x => *(&a) = x
'''
output = _addr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
if indirect:
outp... | [
"def",
"_astoref16",
"(",
"ins",
")",
":",
"output",
"=",
"_addr",
"(",
"ins",
".",
"quad",
"[",
"1",
"]",
")",
"value",
"=",
"ins",
".",
"quad",
"[",
"2",
"]",
"if",
"value",
"[",
"0",
"]",
"==",
"'*'",
":",
"value",
"=",
"value",
"[",
"1",
... | 23.92 | 20.56 |
def _friends_leaveoneout_radius(points, ftype):
"""Internal method used to compute the radius (half-side-length) for each
ball (cube) used in :class:`RadFriends` (:class:`SupFriends`) using
leave-one-out (LOO) cross-validation."""
# Construct KDTree to enable quick nearest-neighbor lookup for
# our... | [
"def",
"_friends_leaveoneout_radius",
"(",
"points",
",",
"ftype",
")",
":",
"# Construct KDTree to enable quick nearest-neighbor lookup for",
"# our resampled objects.",
"kdtree",
"=",
"spatial",
".",
"KDTree",
"(",
"points",
")",
"if",
"ftype",
"==",
"'balls'",
":",
"... | 39.947368 | 22.210526 |
def ex6_2(n):
"""
Generate a triangle pulse as described in Example 6-2
of Chapter 6.
You need to supply an index array n that covers at least [-2, 5].
The function returns the hard-coded signal of the example.
Parameters
----------
n : time index ndarray covering at least -2 ... | [
"def",
"ex6_2",
"(",
"n",
")",
":",
"x",
"=",
"np",
".",
"zeros",
"(",
"len",
"(",
"n",
")",
")",
"for",
"k",
",",
"nn",
"in",
"enumerate",
"(",
"n",
")",
":",
"if",
"nn",
">=",
"-",
"2",
"and",
"nn",
"<=",
"5",
":",
"x",
"[",
"k",
"]",... | 25 | 19.466667 |
def work_once(self, free_pool_slots=1, max_jobs=None):
""" Does one lookup for new jobs, inside the inner work loop """
dequeued_jobs = 0
available_queues = [
queue for queue in self.queues
if queue.root_id not in self.paused_queues and
queue.id not in self.... | [
"def",
"work_once",
"(",
"self",
",",
"free_pool_slots",
"=",
"1",
",",
"max_jobs",
"=",
"None",
")",
":",
"dequeued_jobs",
"=",
"0",
"available_queues",
"=",
"[",
"queue",
"for",
"queue",
"in",
"self",
".",
"queues",
"if",
"queue",
".",
"root_id",
"not"... | 35.679245 | 24.320755 |
def iterativeFetch(query, batchSize=default_batch_size):
"""
Returns rows of a sql fetch query on demand
"""
while True:
rows = query.fetchmany(batchSize)
if not rows:
break
rowDicts = sqliteRowsToDicts(rows)
for rowDict in rowDicts:
yield rowDict | [
"def",
"iterativeFetch",
"(",
"query",
",",
"batchSize",
"=",
"default_batch_size",
")",
":",
"while",
"True",
":",
"rows",
"=",
"query",
".",
"fetchmany",
"(",
"batchSize",
")",
"if",
"not",
"rows",
":",
"break",
"rowDicts",
"=",
"sqliteRowsToDicts",
"(",
... | 28.090909 | 10.636364 |
def set_c(a, op, b):
"""
Given a relational operator, compare two sets of any data type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/set_c.html
:param a: First set.
:type a: spiceypy.utils.support_types.SpiceCell
:param op: Comparison operator.
:type op: str
:param b: Secon... | [
"def",
"set_c",
"(",
"a",
",",
"op",
",",
"b",
")",
":",
"assert",
"isinstance",
"(",
"a",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"isinstance",
"(",
"b",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"a",
".",
"dtype",
"==",
"b",
".",
... | 33.238095 | 16.47619 |
def serialize(self, method="urlencoded", lev=0, **kwargs):
"""
Convert this instance to another representation. Which representation
is given by the choice of serialization method.
:param method: A serialization method. Presently 'urlencoded', 'json',
'jwt' and 'dic... | [
"def",
"serialize",
"(",
"self",
",",
"method",
"=",
"\"urlencoded\"",
",",
"lev",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"\"to_%s\"",
"%",
"method",
")",
"(",
"lev",
"=",
"lev",
",",
"*",
"*",
"kwargs",... | 45.833333 | 19.333333 |
def all_mouse_sprites(self):
"""Returns flat list of the sprite tree for simplified iteration"""
def all_recursive(sprites):
if not sprites:
return
for sprite in sprites:
if sprite.visible:
yield sprite
for... | [
"def",
"all_mouse_sprites",
"(",
"self",
")",
":",
"def",
"all_recursive",
"(",
"sprites",
")",
":",
"if",
"not",
"sprites",
":",
"return",
"for",
"sprite",
"in",
"sprites",
":",
"if",
"sprite",
".",
"visible",
":",
"yield",
"sprite",
"for",
"child",
"in... | 32.214286 | 17.285714 |
def mock_import(do_not_mock=None, **mock_kwargs):
"""
Mocks import statements by ignoring ImportErrors
and replacing the missing module with a Mock.
:param str|unicode|list[str|unicode] do_not_mock: names of modules
that should exists, and an ImportError could be raised for.
:param mock_kwa... | [
"def",
"mock_import",
"(",
"do_not_mock",
"=",
"None",
",",
"*",
"*",
"mock_kwargs",
")",
":",
"do_not_mock",
"=",
"_to_list",
"(",
"do_not_mock",
")",
"def",
"try_import",
"(",
"module_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
... | 40 | 20.48 |
def provides_member_resource(obj):
"""
Checks if the given type or instance provides the
:class:`everest.resources.interfaces.IMemberResource` interface.
"""
if isinstance(obj, type):
obj = object.__new__(obj)
return IMemberResource in provided_by(obj) | [
"def",
"provides_member_resource",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"type",
")",
":",
"obj",
"=",
"object",
".",
"__new__",
"(",
"obj",
")",
"return",
"IMemberResource",
"in",
"provided_by",
"(",
"obj",
")"
] | 34.625 | 8.875 |
def train_encoder(X, y, fold_count, encoder):
"""
Defines folds and performs the data preprocessing (categorical encoding, NaN imputation, normalization)
Returns a list with {X_train, y_train, X_test, y_test}, average fit_encoder_time and average score_encoder_time
Note: We normalize all features (not ... | [
"def",
"train_encoder",
"(",
"X",
",",
"y",
",",
"fold_count",
",",
"encoder",
")",
":",
"kf",
"=",
"StratifiedKFold",
"(",
"n_splits",
"=",
"fold_count",
",",
"shuffle",
"=",
"True",
",",
"random_state",
"=",
"2001",
")",
"encoder",
"=",
"deepcopy",
"("... | 44.704545 | 27.613636 |
def is_callable_tag(tag):
""" Determine whether :tag: is a valid callable string tag.
String is assumed to be valid callable if it starts with '{{'
and ends with '}}'.
:param tag: String name of tag.
"""
return (isinstance(tag, six.string_types) and
tag.strip().startswith('{{') and... | [
"def",
"is_callable_tag",
"(",
"tag",
")",
":",
"return",
"(",
"isinstance",
"(",
"tag",
",",
"six",
".",
"string_types",
")",
"and",
"tag",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'{{'",
")",
"and",
"tag",
".",
"strip",
"(",
")",
".",
"en... | 31.818182 | 14.181818 |
def get_ns2nts(results, fldnames=None, **kws):
"""Get namedtuples of GOEA results, split into BP, MF, CC."""
ns2nts = cx.defaultdict(list)
nts = MgrNtGOEAs(results).get_goea_nts_all(fldnames, **kws)
for ntgoea in nts:
ns2nts[ntgoea.NS].append(ntgoea)
return ns2nts | [
"def",
"get_ns2nts",
"(",
"results",
",",
"fldnames",
"=",
"None",
",",
"*",
"*",
"kws",
")",
":",
"ns2nts",
"=",
"cx",
".",
"defaultdict",
"(",
"list",
")",
"nts",
"=",
"MgrNtGOEAs",
"(",
"results",
")",
".",
"get_goea_nts_all",
"(",
"fldnames",
",",
... | 44.285714 | 10.428571 |
def sync_imports( self, quiet = False ):
"""Return a context manager to control imports onto all the engines
in the underlying cluster. This method is used within a ``with`` statement.
Any imports should be done with no experiments running, otherwise the
method will block until the clus... | [
"def",
"sync_imports",
"(",
"self",
",",
"quiet",
"=",
"False",
")",
":",
"self",
".",
"open",
"(",
")",
"return",
"self",
".",
"_client",
"[",
":",
"]",
".",
"sync_imports",
"(",
"quiet",
"=",
"quiet",
")"
] | 50.857143 | 26.214286 |
def same_cell(c):
"""Return True if all Mentions in the given candidate are from the same Cell.
:param c: The candidate whose Mentions are being compared
:rtype: boolean
"""
return all(
_to_span(c[i]).sentence.cell is not None
and _to_span(c[i]).sentence.cell == _to_span(c[0]).sente... | [
"def",
"same_cell",
"(",
"c",
")",
":",
"return",
"all",
"(",
"_to_span",
"(",
"c",
"[",
"i",
"]",
")",
".",
"sentence",
".",
"cell",
"is",
"not",
"None",
"and",
"_to_span",
"(",
"c",
"[",
"i",
"]",
")",
".",
"sentence",
".",
"cell",
"==",
"_to... | 32.272727 | 19.545455 |
def MD_restrained(dirname='MD_POSRES', **kwargs):
"""Set up MD with position restraints.
Additional itp files should be in the same directory as the top file.
Many of the keyword arguments below already have sensible values. Note that
setting *mainselection* = ``None`` will disable many of the automat... | [
"def",
"MD_restrained",
"(",
"dirname",
"=",
"'MD_POSRES'",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"info",
"(",
"\"[{dirname!s}] Setting up MD with position restraints...\"",
".",
"format",
"(",
"*",
"*",
"vars",
"(",
")",
")",
")",
"kwargs",
".",
... | 43.244898 | 23.112245 |
def note(self, info):
"""Record some info to the report.
:param info: Dictionary of info to record. Note that previous info
recorded under the same keys will not be overwritten.
"""
if self.recording:
if self.notes is None:
raise ValueError("This repo... | [
"def",
"note",
"(",
"self",
",",
"info",
")",
":",
"if",
"self",
".",
"recording",
":",
"if",
"self",
".",
"notes",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"This report has already been submitted\"",
")",
"self",
".",
"notes",
".",
"extend",
"(",
... | 39.4 | 17.9 |
def object_present(container, name, path, profile):
'''
Ensures a object is presnt.
:param container: Container name
:type container: ``str``
:param name: Object name in cloud
:type name: ``str``
:param path: Local path to file
:type path: ``str``
:param profile: The profile k... | [
"def",
"object_present",
"(",
"container",
",",
"name",
",",
"path",
",",
"profile",
")",
":",
"existing_object",
"=",
"__salt__",
"[",
"'libcloud_storage.get_container_object'",
"]",
"(",
"container",
",",
"name",
",",
"profile",
")",
"if",
"existing_object",
"... | 32.181818 | 23.454545 |
def db_set_indexing(cls, is_indexing, impl, working_dir):
"""
Set lockfile path as to whether or not the system is indexing.
NOT THREAD SAFE, USE ONLY FOR CRASH DETECTION.
"""
indexing_lockfile_path = config.get_lockfile_filename(impl, working_dir)
if is_indexing:
... | [
"def",
"db_set_indexing",
"(",
"cls",
",",
"is_indexing",
",",
"impl",
",",
"working_dir",
")",
":",
"indexing_lockfile_path",
"=",
"config",
".",
"get_lockfile_filename",
"(",
"impl",
",",
"working_dir",
")",
"if",
"is_indexing",
":",
"# make sure this exists",
"... | 33.882353 | 17.764706 |
def get_email_domain(emailaddr):
"""
Return the domain component of an email address. Returns None if the
provided string cannot be parsed as an email address.
>>> get_email_domain('test@example.com')
'example.com'
>>> get_email_domain('test+trailing@example.com')
'example.com'
>>> get_... | [
"def",
"get_email_domain",
"(",
"emailaddr",
")",
":",
"realname",
",",
"address",
"=",
"email",
".",
"utils",
".",
"parseaddr",
"(",
"emailaddr",
")",
"try",
":",
"username",
",",
"domain",
"=",
"address",
".",
"split",
"(",
"'@'",
")",
"if",
"not",
"... | 30.52 | 15.56 |
def _pearson_correlation(self, imgs_to_decode):
""" Decode images using Pearson's r.
Computes the correlation between each input image and each feature
image across voxels.
Args:
imgs_to_decode: An ndarray of images to decode, with voxels in rows
and images ... | [
"def",
"_pearson_correlation",
"(",
"self",
",",
"imgs_to_decode",
")",
":",
"x",
",",
"y",
"=",
"imgs_to_decode",
".",
"astype",
"(",
"float",
")",
",",
"self",
".",
"feature_images",
".",
"astype",
"(",
"float",
")",
"return",
"self",
".",
"_xy_corr",
... | 37.941176 | 23.058824 |
def revnet(name, x, hparams, reverse=True):
"""'hparams.depth' steps of generative flow.
Args:
name: variable scope for the revnet block.
x: 4-D Tensor, shape=(NHWC).
hparams: HParams.
reverse: bool, forward or backward pass.
Returns:
x: 4-D Tensor, shape=(NHWC).
objective: float.
"""
... | [
"def",
"revnet",
"(",
"name",
",",
"x",
",",
"hparams",
",",
"reverse",
"=",
"True",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
")",
":",
"steps",
"=",
"np",
".",
"arange",
"(",
"hparams"... | 27 | 15.913043 |
def websafe_dither(self):
"""Return the two websafe colors nearest to this one.
Returns:
A tuple of two grapefruit.Color instances which are the two
web safe colors closest this one.
>>> c = Color.from_rgb(1.0, 0.45, 0.0)
>>> c1, c2 = c.websafe_dither()
>>> c1
Color(1.0, 0.4, 0.0, ... | [
"def",
"websafe_dither",
"(",
"self",
")",
":",
"return",
"(",
"Color",
"(",
"rgb_to_websafe",
"(",
"*",
"self",
".",
"__rgb",
")",
",",
"'rgb'",
",",
"self",
".",
"__a",
",",
"self",
".",
"__wref",
")",
",",
"Color",
"(",
"rgb_to_websafe",
"(",
"alt... | 29.111111 | 21 |
def invert_relation(self, relation):
"""
Invert or deinvert *relation*.
"""
if self.is_relation_inverted(relation):
rel = self._deinversions.get(relation, relation[:-3])
else:
rel = self._inversions.get(relation, relation + '-of')
if rel is None:
... | [
"def",
"invert_relation",
"(",
"self",
",",
"relation",
")",
":",
"if",
"self",
".",
"is_relation_inverted",
"(",
"relation",
")",
":",
"rel",
"=",
"self",
".",
"_deinversions",
".",
"get",
"(",
"relation",
",",
"relation",
"[",
":",
"-",
"3",
"]",
")"... | 33.846154 | 14.923077 |
def _find_matching_instance(cache_key):
"""Find a running TensorBoard instance compatible with the cache key.
Returns:
A `TensorBoardInfo` object, or `None` if none matches the cache key.
"""
infos = get_all()
candidates = [info for info in infos if info.cache_key == cache_key]
for candidate in sorted(... | [
"def",
"_find_matching_instance",
"(",
"cache_key",
")",
":",
"infos",
"=",
"get_all",
"(",
")",
"candidates",
"=",
"[",
"info",
"for",
"info",
"in",
"infos",
"if",
"info",
".",
"cache_key",
"==",
"cache_key",
"]",
"for",
"candidate",
"in",
"sorted",
"(",
... | 37.5 | 21 |
def parse_200_row(row: list) -> NmiDetails:
""" Parse NMI data details record (200) """
return NmiDetails(row[1], row[2], row[3], row[4], row[5], row[6],
row[7], int(row[8]), parse_datetime(row[9])) | [
"def",
"parse_200_row",
"(",
"row",
":",
"list",
")",
"->",
"NmiDetails",
":",
"return",
"NmiDetails",
"(",
"row",
"[",
"1",
"]",
",",
"row",
"[",
"2",
"]",
",",
"row",
"[",
"3",
"]",
",",
"row",
"[",
"4",
"]",
",",
"row",
"[",
"5",
"]",
",",... | 57 | 15.25 |
def get_current(cls):
"""Get the context for the current env, if there is one.
Returns:
`ResolvedContext`: Current context, or None if not in a resolved env.
"""
filepath = os.getenv("REZ_RXT_FILE")
if not filepath or not os.path.exists(filepath):
return ... | [
"def",
"get_current",
"(",
"cls",
")",
":",
"filepath",
"=",
"os",
".",
"getenv",
"(",
"\"REZ_RXT_FILE\"",
")",
"if",
"not",
"filepath",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filepath",
")",
":",
"return",
"None",
"return",
"cls",
".",
... | 31.727273 | 18.909091 |
def setEmissionClass(self, typeID, clazz):
"""setEmissionClass(string, string) -> None
Sets the emission class of vehicles of this type.
"""
self._connection._sendStringCmd(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_EMISSIONCLASS, typeID, clazz) | [
"def",
"setEmissionClass",
"(",
"self",
",",
"typeID",
",",
"clazz",
")",
":",
"self",
".",
"_connection",
".",
"_sendStringCmd",
"(",
"tc",
".",
"CMD_SET_VEHICLETYPE_VARIABLE",
",",
"tc",
".",
"VAR_EMISSIONCLASS",
",",
"typeID",
",",
"clazz",
")"
] | 40.285714 | 14.285714 |
def ssh_client(host):
"""Start an ssh client.
:param host: the host
:type host: str
:returns: ssh client
:rtype: Paramiko client
"""
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host)
return ssh | [
"def",
"ssh_client",
"(",
"host",
")",
":",
"ssh",
"=",
"paramiko",
".",
"SSHClient",
"(",
")",
"ssh",
".",
"set_missing_host_key_policy",
"(",
"paramiko",
".",
"AutoAddPolicy",
"(",
")",
")",
"ssh",
".",
"connect",
"(",
"host",
")",
"return",
"ssh"
] | 23 | 16.666667 |
def get_unread_topics(self, topics, user):
""" Returns a list of unread topics for the given user from a given set of topics. """
unread_topics = []
# A user which is not authenticated will never see a topic as unread.
# If there are no topics to consider, we stop here.
if not u... | [
"def",
"get_unread_topics",
"(",
"self",
",",
"topics",
",",
"user",
")",
":",
"unread_topics",
"=",
"[",
"]",
"# A user which is not authenticated will never see a topic as unread.",
"# If there are no topics to consider, we stop here.",
"if",
"not",
"user",
".",
"is_authent... | 47.755556 | 26.244444 |
def _start_managers(self):
"""
(internal) starts input and output pool queue manager threads.
"""
self._task_queue = _Weave(self._tasks, self.stride)
# here we determine the size of the maximum memory consumption
self._semaphore_value = (self.buffer or (len(self._tasks) *... | [
"def",
"_start_managers",
"(",
"self",
")",
":",
"self",
".",
"_task_queue",
"=",
"_Weave",
"(",
"self",
".",
"_tasks",
",",
"self",
".",
"stride",
")",
"# here we determine the size of the maximum memory consumption",
"self",
".",
"_semaphore_value",
"=",
"(",
"s... | 44.458333 | 19.708333 |
def _get_disk_size(self, device):
'''
Get a size of a disk.
'''
out = __salt__['cmd.run_all']("df {0}".format(device))
if out['retcode']:
msg = "Disk size info error: {0}".format(out['stderr'])
log.error(msg)
raise SIException(msg)
dev... | [
"def",
"_get_disk_size",
"(",
"self",
",",
"device",
")",
":",
"out",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"\"df {0}\"",
".",
"format",
"(",
"device",
")",
")",
"if",
"out",
"[",
"'retcode'",
"]",
":",
"msg",
"=",
"\"Disk size info error: {0}\"... | 41.25 | 26.875 |
def get_os_version_codename(codename, version_map=OPENSTACK_CODENAMES):
'''Determine OpenStack version number from codename.'''
for k, v in six.iteritems(version_map):
if v == codename:
return k
e = 'Could not derive OpenStack version for '\
'codename: %s' % codename
error_ou... | [
"def",
"get_os_version_codename",
"(",
"codename",
",",
"version_map",
"=",
"OPENSTACK_CODENAMES",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"version_map",
")",
":",
"if",
"v",
"==",
"codename",
":",
"return",
"k",
"e",
"=",
"'C... | 39.625 | 16.125 |
def getcloud(site, feed_id=None):
""" Returns the tag cloud for a site or a site's subscriber.
"""
cloudict = fjcache.cache_get(site.id, 'tagclouds')
if not cloudict:
cloudict = cloudata(site)
fjcache.cache_set(site, 'tagclouds', cloudict)
# A subscriber's tag cloud has been requested.
if feed_id:
feed_id... | [
"def",
"getcloud",
"(",
"site",
",",
"feed_id",
"=",
"None",
")",
":",
"cloudict",
"=",
"fjcache",
".",
"cache_get",
"(",
"site",
".",
"id",
",",
"'tagclouds'",
")",
"if",
"not",
"cloudict",
":",
"cloudict",
"=",
"cloudata",
"(",
"site",
")",
"fjcache"... | 26.235294 | 15.941176 |
def add_transaction(self, transaction):
# type: (ProposedTransaction) -> None
"""
Adds a transaction to the bundle.
If the transaction message is too long, it will be split
automatically into multiple transactions.
"""
if self.hash:
raise RuntimeError... | [
"def",
"add_transaction",
"(",
"self",
",",
"transaction",
")",
":",
"# type: (ProposedTransaction) -> None",
"if",
"self",
".",
"hash",
":",
"raise",
"RuntimeError",
"(",
"'Bundle is already finalized.'",
")",
"if",
"transaction",
".",
"value",
"<",
"0",
":",
"ra... | 35.416667 | 16.916667 |
def _get_end_event(parser, tagName):
"""Check that the next event is the end of a particular XML tag."""
(event, node) = six.next(parser)
if event != pulldom.END_ELEMENT or node.tagName != tagName:
raise ParseError(
'Expecting %s end tag, got %s %s' % (tagName, event, node.tagName)) | [
"def",
"_get_end_event",
"(",
"parser",
",",
"tagName",
")",
":",
"(",
"event",
",",
"node",
")",
"=",
"six",
".",
"next",
"(",
"parser",
")",
"if",
"event",
"!=",
"pulldom",
".",
"END_ELEMENT",
"or",
"node",
".",
"tagName",
"!=",
"tagName",
":",
"ra... | 38.75 | 20.625 |
def wait_not(method, timeout, fail_on_timeout=None, **kwargs):
"""
Wait ``timeout`` seconds until ``method(**kwargs)`` returns a ``value`` that *not value==True*.
Returns last ``value``.
If time expired and ``fail_on_timeout`` specified, then raise TimeoutException.
:param method:
:param timeo... | [
"def",
"wait_not",
"(",
"method",
",",
"timeout",
",",
"fail_on_timeout",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Waiter",
"(",
"lambda",
"value",
":",
"not",
"value",
")",
".",
"start",
"(",
"method",
",",
"timeout",
",",
"fail_on_t... | 36.307692 | 25.846154 |
def crawl_ax(self, ax):
"""Crawl the axes and process all elements within"""
with self.renderer.draw_axes(ax=ax,
props=utils.get_axes_properties(ax)):
for line in ax.lines:
self.draw_line(ax, line)
for text in ax.texts:
... | [
"def",
"crawl_ax",
"(",
"self",
",",
"ax",
")",
":",
"with",
"self",
".",
"renderer",
".",
"draw_axes",
"(",
"ax",
"=",
"ax",
",",
"props",
"=",
"utils",
".",
"get_axes_properties",
"(",
"ax",
")",
")",
":",
"for",
"line",
"in",
"ax",
".",
"lines",... | 47.2 | 12.733333 |
def PyDbLite_to_csv(src,dest=None,dialect='excel'):
"""Convert a PyDbLite base to a CSV file
src is the PyDbLite.Base instance
dest is the file-like object for the CSV output
dialect is the same as in csv module"""
import csv
fieldnames = ["__id__","__version__"]+src.fields
if dest is... | [
"def",
"PyDbLite_to_csv",
"(",
"src",
",",
"dest",
"=",
"None",
",",
"dialect",
"=",
"'excel'",
")",
":",
"import",
"csv",
"fieldnames",
"=",
"[",
"\"__id__\"",
",",
"\"__version__\"",
"]",
"+",
"src",
".",
"fields",
"if",
"dest",
"is",
"None",
":",
"d... | 38.470588 | 12.294118 |
def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=False):
"""
Validates the certificate path and that the certificate is valid for
the key usage and extended key usage purposes specified.
:param key_usage:
A set of unicode strings of the required... | [
"def",
"validate_usage",
"(",
"self",
",",
"key_usage",
",",
"extended_key_usage",
"=",
"None",
",",
"extended_optional",
"=",
"False",
")",
":",
"self",
".",
"_validate_path",
"(",
")",
"validate_usage",
"(",
"self",
".",
"_context",
",",
"self",
".",
"_cer... | 34.064516 | 21.483871 |
def at_time(cls, at, target):
"""
Construct a DelayedCommand to come due at `at`, where `at` may be
a datetime or timestamp.
"""
at = cls._from_timestamp(at)
cmd = cls.from_datetime(at)
cmd.delay = at - now()
cmd.target = target
return cmd | [
"def",
"at_time",
"(",
"cls",
",",
"at",
",",
"target",
")",
":",
"at",
"=",
"cls",
".",
"_from_timestamp",
"(",
"at",
")",
"cmd",
"=",
"cls",
".",
"from_datetime",
"(",
"at",
")",
"cmd",
".",
"delay",
"=",
"at",
"-",
"now",
"(",
")",
"cmd",
".... | 30.2 | 10.6 |
def hash_coloured(text):
"""Return a ANSI coloured text based on its hash"""
ansi_code = int(sha256(text.encode('utf-8')).hexdigest(), 16) % 230
return colored(text, ansi_code=ansi_code) | [
"def",
"hash_coloured",
"(",
"text",
")",
":",
"ansi_code",
"=",
"int",
"(",
"sha256",
"(",
"text",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
")",
",",
"16",
")",
"%",
"230",
"return",
"colored",
"(",
"text",
",",
"ansi_code",
... | 48.75 | 13 |
def _meters_per_pixel(zoom, lat=0.0, tilesize=256):
"""
Return the pixel resolution for a given mercator tile zoom and lattitude.
Parameters
----------
zoom: int
Mercator zoom level
lat: float, optional
Latitude in decimal degree (default: 0)
tilesize: int, optional
... | [
"def",
"_meters_per_pixel",
"(",
"zoom",
",",
"lat",
"=",
"0.0",
",",
"tilesize",
"=",
"256",
")",
":",
"return",
"(",
"math",
".",
"cos",
"(",
"lat",
"*",
"math",
".",
"pi",
"/",
"180.0",
")",
"*",
"2",
"*",
"math",
".",
"pi",
"*",
"6378137",
... | 24.142857 | 21.190476 |
def _R2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rderiv
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT... | [
"def",
"_R2deriv",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"return",
"1.",
"/",
"(",
"R",
"**",
"2.",
"+",
"z",
"**",
"2.",
")",
"**",
"(",
"self",
".",
"alpha",
"/",
"2.",
")",
"-",
"self",
... | 29.555556 | 15.111111 |
def get_id(self):
"""Converts a User ID and parts of a User password hash to a token."""
# This function is used by Flask-Login to store a User ID securely as a browser cookie.
# The last part of the password is included to invalidate tokens when password change.
# user_id and password_... | [
"def",
"get_id",
"(",
"self",
")",
":",
"# This function is used by Flask-Login to store a User ID securely as a browser cookie.",
"# The last part of the password is included to invalidate tokens when password change.",
"# user_id and password_ends_with are encrypted, timestamped and signed.",
"#... | 51 | 28.058824 |
def _query(lamp_id, state, action='', method='GET'):
'''
Query the URI
:return:
'''
# Because salt.utils.query is that dreadful... :(
err = None
url = "{0}/lights{1}".format(CONFIG['uri'],
lamp_id and '/{0}'.format(lamp_id) or '') \
+ (action and ... | [
"def",
"_query",
"(",
"lamp_id",
",",
"state",
",",
"action",
"=",
"''",
",",
"method",
"=",
"'GET'",
")",
":",
"# Because salt.utils.query is that dreadful... :(",
"err",
"=",
"None",
"url",
"=",
"\"{0}/lights{1}\"",
".",
"format",
"(",
"CONFIG",
"[",
"'uri'"... | 28.25 | 22.678571 |
def is_deprecated(cls, label, datacenter=None):
"""Check if image if flagged as deprecated."""
images = cls.list(datacenter, label)
images_visibility = dict([(image['label'], image['visibility'])
for image in images])
return images_visibility.get(label, ... | [
"def",
"is_deprecated",
"(",
"cls",
",",
"label",
",",
"datacenter",
"=",
"None",
")",
":",
"images",
"=",
"cls",
".",
"list",
"(",
"datacenter",
",",
"label",
")",
"images_visibility",
"=",
"dict",
"(",
"[",
"(",
"image",
"[",
"'label'",
"]",
",",
"... | 56.166667 | 13.833333 |
def taskFailed(self, *args, **kwargs):
"""
Task Failed Messages
When a task ran, but failed to complete successfully a message is posted
to this exchange. This is same as worker ran task-specific code, but the
task specific code exited non-zero.
This exchange outputs: `... | [
"def",
"taskFailed",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"ref",
"=",
"{",
"'exchange'",
":",
"'task-failed'",
",",
"'name'",
":",
"'taskFailed'",
",",
"'routingKey'",
":",
"[",
"{",
"'constant'",
":",
"'primary'",
",",
"'m... | 35.375 | 23.525 |
def remove(self, index):
'''
Delete one or more relationship, by index, from the extent
index - either a single index or a list of indices
'''
raise NotImplementedError
if hasattr(index, '__iter__'):
ind = set(index)
else:
ind = [index]
... | [
"def",
"remove",
"(",
"self",
",",
"index",
")",
":",
"raise",
"NotImplementedError",
"if",
"hasattr",
"(",
"index",
",",
"'__iter__'",
")",
":",
"ind",
"=",
"set",
"(",
"index",
")",
"else",
":",
"ind",
"=",
"[",
"index",
"]",
"# Rebuild relationships, ... | 33 | 24 |
def wire(self):
"""
Returns (Register, int) tuple where the int is the index of
the wire else None
"""
if self.data_dict['type'] not in ['in', 'out']:
raise QiskitError('The node %s is not an input/output node' % str(self))
return self.data_dict.get('wire') | [
"def",
"wire",
"(",
"self",
")",
":",
"if",
"self",
".",
"data_dict",
"[",
"'type'",
"]",
"not",
"in",
"[",
"'in'",
",",
"'out'",
"]",
":",
"raise",
"QiskitError",
"(",
"'The node %s is not an input/output node'",
"%",
"str",
"(",
"self",
")",
")",
"retu... | 38.75 | 15.75 |
def from_maps(*maps):
"""
Creates a new AnyValueMap by merging two or more maps.
Maps defined later in the list override values from previously defined maps.
:param maps: an array of maps to be merged
:return: a newly created AnyValueMap.
"""
result = StringValu... | [
"def",
"from_maps",
"(",
"*",
"maps",
")",
":",
"result",
"=",
"StringValueMap",
"(",
")",
"if",
"maps",
"==",
"None",
"or",
"len",
"(",
"maps",
")",
"==",
"0",
":",
"return",
"result",
"for",
"map",
"in",
"maps",
":",
"for",
"(",
"k",
",",
"v",
... | 27.95 | 18.45 |
def mean_squared_error(output, target, is_mean=False, name="mean_squared_error"):
"""Return the TensorFlow expression of mean-square-error (L2) of two batch of data.
Parameters
----------
output : Tensor
2D, 3D or 4D tensor i.e. [batch_size, n_feature], [batch_size, height, width] or [batch_siz... | [
"def",
"mean_squared_error",
"(",
"output",
",",
"target",
",",
"is_mean",
"=",
"False",
",",
"name",
"=",
"\"mean_squared_error\"",
")",
":",
"# with tf.name_scope(name):",
"if",
"output",
".",
"get_shape",
"(",
")",
".",
"ndims",
"==",
"2",
":",
"# [batch_si... | 46.425 | 32.025 |
def load(cls, partname, content_type, blob, package):
"""
Called by ``docx.opc.package.PartFactory`` to load an image part from
a package being opened by ``Document(...)`` call.
"""
return cls(partname, content_type, blob) | [
"def",
"load",
"(",
"cls",
",",
"partname",
",",
"content_type",
",",
"blob",
",",
"package",
")",
":",
"return",
"cls",
"(",
"partname",
",",
"content_type",
",",
"blob",
")"
] | 42.833333 | 12.5 |
def parallel_bulk(
client,
actions,
thread_count=4,
chunk_size=500,
max_chunk_bytes=100 * 1024 * 1024,
queue_size=4,
expand_action_callback=expand_action,
*args,
**kwargs
):
"""
Parallel version of the bulk helper run in multiple threads at once.
:arg client: instance of... | [
"def",
"parallel_bulk",
"(",
"client",
",",
"actions",
",",
"thread_count",
"=",
"4",
",",
"chunk_size",
"=",
"500",
",",
"max_chunk_bytes",
"=",
"100",
"*",
"1024",
"*",
"1024",
",",
"queue_size",
"=",
"4",
",",
"expand_action_callback",
"=",
"expand_action... | 38.548387 | 24 |
def _run_once(self):
"""Run once, should be called only from loop()"""
try:
self.do_wait()
self._execute_wakeup_tasks()
self._trigger_timers()
except Exception as e:
Log.error("Error occured during _run_once(): " + str(e))
Log.error(traceback.format_exc())
self.should_exi... | [
"def",
"_run_once",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"do_wait",
"(",
")",
"self",
".",
"_execute_wakeup_tasks",
"(",
")",
"self",
".",
"_trigger_timers",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"Log",
".",
"error",
"(",
"\"Error... | 31.9 | 13.8 |
def new(cls, password, rounds):
"""Creates a PasswordHash from the given password."""
if isinstance(password, str):
password = password.encode('utf-8')
return cls(cls._new(password, rounds)) | [
"def",
"new",
"(",
"cls",
",",
"password",
",",
"rounds",
")",
":",
"if",
"isinstance",
"(",
"password",
",",
"str",
")",
":",
"password",
"=",
"password",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"cls",
"(",
"cls",
".",
"_new",
"(",
"password",... | 44.4 | 5 |
def discover(self, metafile):
"""
Determine what summary stats, time series, and CDF csv exist for the reports that need to be diffed.
:return: boolean: return whether the summary stats / time series / CDF csv summary was successfully located
"""
for report in self.reports:
if report.remote_lo... | [
"def",
"discover",
"(",
"self",
",",
"metafile",
")",
":",
"for",
"report",
"in",
"self",
".",
"reports",
":",
"if",
"report",
".",
"remote_location",
"==",
"'local'",
":",
"if",
"naarad",
".",
"utils",
".",
"is_valid_file",
"(",
"os",
".",
"path",
"."... | 51.054054 | 25.378378 |
def filter(fastq, sam, paired = False):
"""
filter sequences that are shown to be mapped in the sam file
reads not in sam file are in *.filtered.fastq
reads that are in the sam file are in *.matched.fastq
"""
if paired is False:
list = sam_list(sam)
else:
list = sam_list_paired(sam)
if paired is False:
f... | [
"def",
"filter",
"(",
"fastq",
",",
"sam",
",",
"paired",
"=",
"False",
")",
":",
"if",
"paired",
"is",
"False",
":",
"list",
"=",
"sam_list",
"(",
"sam",
")",
"else",
":",
"list",
"=",
"sam_list_paired",
"(",
"sam",
")",
"if",
"paired",
"is",
"Fal... | 26.642857 | 14.142857 |
def get_expression_target(expression: Expression, expr_vars: InheritedDict) -> BindingTarget:
'''Factory method to create expression target'''
root = expression.get_object_tree()
if len(root.children) != 1 or not PROPERTY_EXPRESSION_REGEX.fullmatch(expression.code):
error = BindingError('Expression ... | [
"def",
"get_expression_target",
"(",
"expression",
":",
"Expression",
",",
"expr_vars",
":",
"InheritedDict",
")",
"->",
"BindingTarget",
":",
"root",
"=",
"expression",
".",
"get_object_tree",
"(",
")",
"if",
"len",
"(",
"root",
".",
"children",
")",
"!=",
... | 57.5 | 23.3 |
def predict(self, X):
"""
Assign classes to test data.
Parameters
----------
X : array
Test data, of dimension N times d (rows are examples, columns
are data dimensions)
Returns
-------
y_predicted : array
A vector of ... | [
"def",
"predict",
"(",
"self",
",",
"X",
")",
":",
"predictions_proba",
"=",
"self",
".",
"predict_proba",
"(",
"X",
")",
"predictions",
"=",
"[",
"]",
"allclasses",
"=",
"copy",
".",
"copy",
"(",
"self",
".",
"classes",
")",
"allclasses",
".",
"append... | 36.555556 | 19.444444 |
def abbreviate_dashed(s):
"""Abbreviates each part of string that is delimited by a '-'."""
r = []
for part in s.split('-'):
r.append(abbreviate(part))
return '-'.join(r) | [
"def",
"abbreviate_dashed",
"(",
"s",
")",
":",
"r",
"=",
"[",
"]",
"for",
"part",
"in",
"s",
".",
"split",
"(",
"'-'",
")",
":",
"r",
".",
"append",
"(",
"abbreviate",
"(",
"part",
")",
")",
"return",
"'-'",
".",
"join",
"(",
"r",
")"
] | 31.5 | 13.333333 |
def spline_interpolate(x_axis, y_axis, x_new_axis):
"""Interpolate a y = f(x) function using Spline interpolation algorithm,
x_new_axis has to be in range of x_axis.
`Spline interpolation <https://en.wikipedia.org/wiki/Spline_interpolation>`_
is a popular interpolation method. Way more accurate than l... | [
"def",
"spline_interpolate",
"(",
"x_axis",
",",
"y_axis",
",",
"x_new_axis",
")",
":",
"f",
"=",
"interp1d",
"(",
"x_axis",
",",
"y_axis",
",",
"kind",
"=",
"\"cubic\"",
")",
"return",
"f",
"(",
"x_new_axis",
")"
] | 42.3 | 18.3 |
def pylxd_save_object(obj):
''' Saves an object (profile/image/container) and
translate its execpetion on failure
obj :
The object to save
This is an internal method, no CLI Example.
'''
try:
obj.save()
except pylxd.exceptions.LXDAPIException as e:
raise Command... | [
"def",
"pylxd_save_object",
"(",
"obj",
")",
":",
"try",
":",
"obj",
".",
"save",
"(",
")",
"except",
"pylxd",
".",
"exceptions",
".",
"LXDAPIException",
"as",
"e",
":",
"raise",
"CommandExecutionError",
"(",
"six",
".",
"text_type",
"(",
"e",
")",
")",
... | 23.666667 | 22.333333 |
def get_ip_by_equip_and_vip(self, equip_name, id_evip):
"""
Get a available IP in the Equipment related Environment VIP
:param equip_name: Equipment Name.
:param id_evip: Vip environment identifier. Integer value and greater than zero.
:return: Dictionary with the following str... | [
"def",
"get_ip_by_equip_and_vip",
"(",
"self",
",",
"equip_name",
",",
"id_evip",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_evip",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'Vip environment is invalid or was not informed.'",
")",
"ip_map",
"=",
"d... | 41.8 | 29.514286 |
def _reset(cls):
"""If we have forked since the watch dictionaries were initialized, all
that has is garbage, so clear it."""
if os.getpid() != cls._cls_pid:
cls._cls_pid = os.getpid()
cls._cls_instances_by_target.clear()
cls._cls_thread_by_target.clear() | [
"def",
"_reset",
"(",
"cls",
")",
":",
"if",
"os",
".",
"getpid",
"(",
")",
"!=",
"cls",
".",
"_cls_pid",
":",
"cls",
".",
"_cls_pid",
"=",
"os",
".",
"getpid",
"(",
")",
"cls",
".",
"_cls_instances_by_target",
".",
"clear",
"(",
")",
"cls",
".",
... | 44.142857 | 5.714286 |
def transpose(self, name=None):
"""Returns matching `Conv2DTranspose` module.
Args:
name: Optional string assigning name of transpose module. The default name
is constructed by appending "_transpose" to `self.name`.
Returns:
`Conv2DTranspose` module.
Raises:
base.NotSupported... | [
"def",
"transpose",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"any",
"(",
"x",
">",
"1",
"for",
"x",
"in",
"self",
".",
"_rate",
")",
":",
"raise",
"base",
".",
"NotSupportedError",
"(",
"\"Cannot transpose a dilated convolution module.\"",
")... | 37.651163 | 19.046512 |
def save_stack(stack):
"""
Saves a stack object to a flatfile.
:param caliendo.hooks.CallStack stack: The stack to save.
"""
global CACHE_
serialized = pickle.dumps(stack, PPROT)
CACHE_['stacks']["{0}.{1}".format(stack.module, stack.caller)] = serialized
write_out() | [
"def",
"save_stack",
"(",
"stack",
")",
":",
"global",
"CACHE_",
"serialized",
"=",
"pickle",
".",
"dumps",
"(",
"stack",
",",
"PPROT",
")",
"CACHE_",
"[",
"'stacks'",
"]",
"[",
"\"{0}.{1}\"",
".",
"format",
"(",
"stack",
".",
"module",
",",
"stack",
"... | 26.363636 | 19.090909 |
def get_property(self):
"""Establishes access of Property values"""
prop = super(File, self).get_property()
# scope is the Property instance
scope = self
def fdel(self):
"""Set value to utils.undefined on delete"""
if self._get(scope.name) is not None:
... | [
"def",
"get_property",
"(",
"self",
")",
":",
"prop",
"=",
"super",
"(",
"File",
",",
"self",
")",
".",
"get_property",
"(",
")",
"# scope is the Property instance",
"scope",
"=",
"self",
"def",
"fdel",
"(",
"self",
")",
":",
"\"\"\"Set value to utils.undefine... | 31.647059 | 17.235294 |
def add_handler(self, handler):
''' Add an additional handler
Args:
handler:
A dictionary of handler configuration for the handler
that should be added. See :func:`__init__` for details
on valid parameters.
'''
handler['logger'... | [
"def",
"add_handler",
"(",
"self",
",",
"handler",
")",
":",
"handler",
"[",
"'logger'",
"]",
"=",
"self",
".",
"_get_logger",
"(",
"handler",
")",
"handler",
"[",
"'reads'",
"]",
"=",
"0",
"handler",
"[",
"'data_read'",
"]",
"=",
"0",
"self",
".",
"... | 31.785714 | 19.214286 |
def compute_forward_returns(factor,
prices,
periods=(1, 5, 10),
filter_zscore=None,
cumulative_returns=True):
"""
Finds the N period forward returns (as percent change) for each asset
provided.
... | [
"def",
"compute_forward_returns",
"(",
"factor",
",",
"prices",
",",
"periods",
"=",
"(",
"1",
",",
"5",
",",
"10",
")",
",",
"filter_zscore",
"=",
"None",
",",
"cumulative_returns",
"=",
"True",
")",
":",
"factor_dateindex",
"=",
"factor",
".",
"index",
... | 38.325581 | 21.829457 |
def edit(self, data_src, value):
"""
Edit data layer.
:param data_src: Name of :class:`DataSource` to edit.
:type data_src: str
:param value: Values to edit.
:type value: dict
"""
# check if opening file
if 'filename' in value:
items =... | [
"def",
"edit",
"(",
"self",
",",
"data_src",
",",
"value",
")",
":",
"# check if opening file",
"if",
"'filename'",
"in",
"value",
":",
"items",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"reg",
".",
"data_source",
".",
"iteritems",
"(",
... | 36.647059 | 13.941176 |
def make_reports(self, stats, old_stats):
"""render registered reports"""
sect = Section("Report", "%s statements analysed." % (self.stats["statement"]))
for checker in self.report_order():
for reportid, r_title, r_cb in self._reports[checker]:
if not self.report_is_e... | [
"def",
"make_reports",
"(",
"self",
",",
"stats",
",",
"old_stats",
")",
":",
"sect",
"=",
"Section",
"(",
"\"Report\"",
",",
"\"%s statements analysed.\"",
"%",
"(",
"self",
".",
"stats",
"[",
"\"statement\"",
"]",
")",
")",
"for",
"checker",
"in",
"self"... | 43.733333 | 12.466667 |
def temporary_attr(obj, name, value):
"""
Context manager that removes key from dictionary on closing
The dictionary will hold the key for the duration of
the context.
Parameters
----------
obj : object
Object onto which to add a temporary attribute.
name : str
Name of ... | [
"def",
"temporary_attr",
"(",
"obj",
",",
"name",
",",
"value",
")",
":",
"setattr",
"(",
"obj",
",",
"name",
",",
"value",
")",
"try",
":",
"yield",
"obj",
"finally",
":",
"delattr",
"(",
"obj",
",",
"name",
")"
] | 22.809524 | 19.571429 |
def _create(self):
""" Create new object on IxNetwork.
:return: IXN object reference.
"""
if 'name' in self._data:
obj_ref = self.api.add(self.obj_parent(), self.obj_type(), name=self.obj_name())
else:
obj_ref = self.api.add(self.obj_parent(), self.obj_t... | [
"def",
"_create",
"(",
"self",
")",
":",
"if",
"'name'",
"in",
"self",
".",
"_data",
":",
"obj_ref",
"=",
"self",
".",
"api",
".",
"add",
"(",
"self",
".",
"obj_parent",
"(",
")",
",",
"self",
".",
"obj_type",
"(",
")",
",",
"name",
"=",
"self",
... | 31.916667 | 19.75 |
def from_blob(cls, blob, stage=0):
""":return: Minimal entry resembling the given blob object"""
time = pack(">LL", 0, 0)
return IndexEntry((blob.mode, blob.binsha, stage << CE_STAGESHIFT, blob.path,
time, time, 0, 0, 0, 0, blob.size)) | [
"def",
"from_blob",
"(",
"cls",
",",
"blob",
",",
"stage",
"=",
"0",
")",
":",
"time",
"=",
"pack",
"(",
"\">LL\"",
",",
"0",
",",
"0",
")",
"return",
"IndexEntry",
"(",
"(",
"blob",
".",
"mode",
",",
"blob",
".",
"binsha",
",",
"stage",
"<<",
... | 56.4 | 16.2 |
def create_filter(extended, from_id, to_id, rtr_only, rtr_too):
"""
Calculates AMR and ACR using CAN-ID as parameter.
:param bool extended:
if True parameters from_id and to_id contains 29-bit CAN-ID
:param int from_id:
first CAN-ID which should be received
... | [
"def",
"create_filter",
"(",
"extended",
",",
"from_id",
",",
"to_id",
",",
"rtr_only",
",",
"rtr_too",
")",
":",
"return",
"[",
"{",
"\"can_id\"",
":",
"Ucan",
".",
"calculate_acr",
"(",
"extended",
",",
"from_id",
",",
"to_id",
",",
"rtr_only",
",",
"r... | 36.076923 | 26.230769 |
def load(self,filename):
""" entry point load the pest control file. sniffs the first non-comment line to detect the version (if present)
Parameters
----------
filename : str
pst filename
Raises
------
lots of exceptions for incorrect format
... | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
",",
"\"couldn't find control file {0}\"",
".",
"format",
"(",
"filename",
")",
"f",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
... | 36.027027 | 21.594595 |
def check_child_validity(self, child):
"""Check validity of passed child object
The method is called by state child objects (transitions, data flows) when these are initialized or changed. The
method checks the type of the child and then checks its validity in the context of the state.
... | [
"def",
"check_child_validity",
"(",
"self",
",",
"child",
")",
":",
"# First let the state do validity checks for outcomes and data ports",
"valid",
",",
"message",
"=",
"super",
"(",
"ContainerState",
",",
"self",
")",
".",
"check_child_validity",
"(",
"child",
")",
... | 55.952381 | 26.571429 |
def printStatistics(completion, concordance, tpedSamples, oldSamples, prefix):
"""Print the statistics in a file.
:param completion: the completion of each duplicated samples.
:param concordance: the concordance of each duplicated samples.
:param tpedSamples: the updated position of the samples in the ... | [
"def",
"printStatistics",
"(",
"completion",
",",
"concordance",
",",
"tpedSamples",
",",
"oldSamples",
",",
"prefix",
")",
":",
"# Compute the completion percentage on none zero values",
"none_zero_indexes",
"=",
"np",
".",
"where",
"(",
"completion",
"[",
"1",
"]",
... | 39.666667 | 21.448718 |
def health_state(consul_url=None, token=None, state=None, **kwargs):
'''
Returns the checks in the state provided on the path.
:param consul_url: The Consul server URL.
:param state: The state to show checks for. The supported states
are any, unknown, passing, warning, or critical.
... | [
"def",
"health_state",
"(",
"consul_url",
"=",
"None",
",",
"token",
"=",
"None",
",",
"state",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"{",
"}",
"query_params",
"=",
"{",
"}",
"if",
"not",
"consul_url",
":",
"consul_url",
"=",
... | 32.408163 | 22.734694 |
def internal_tally(self):
"""Store the trace of stochastics for the computation of the covariance.
This trace is completely independent from the backend used by the
sampler to store the samples."""
chain = []
for stochastic in self.stochastics:
chain.append(np.ravel(s... | [
"def",
"internal_tally",
"(",
"self",
")",
":",
"chain",
"=",
"[",
"]",
"for",
"stochastic",
"in",
"self",
".",
"stochastics",
":",
"chain",
".",
"append",
"(",
"np",
".",
"ravel",
"(",
"stochastic",
".",
"value",
")",
")",
"self",
".",
"_trace",
"."... | 47.5 | 11.75 |
def delete(self, bucket, key, extra_args=None, subscribers=None):
"""Delete an S3 object.
:type bucket: str
:param bucket: The name of the bucket.
:type key: str
:param key: The name of the S3 object to delete.
:type extra_args: dict
:param extra_args: Extra ar... | [
"def",
"delete",
"(",
"self",
",",
"bucket",
",",
"key",
",",
"extra_args",
"=",
"None",
",",
"subscribers",
"=",
"None",
")",
":",
"if",
"extra_args",
"is",
"None",
":",
"extra_args",
"=",
"{",
"}",
"if",
"subscribers",
"is",
"None",
":",
"subscribers... | 35.0625 | 20.8125 |
def cross_validation_models(self):
"""
Obtain a list of cross-validation models.
:returns: list of H2OModel objects.
"""
cvmodels = self._model_json["output"]["cross_validation_models"]
if cvmodels is None: return None
m = []
for p in cvmodels: m.append(h... | [
"def",
"cross_validation_models",
"(",
"self",
")",
":",
"cvmodels",
"=",
"self",
".",
"_model_json",
"[",
"\"output\"",
"]",
"[",
"\"cross_validation_models\"",
"]",
"if",
"cvmodels",
"is",
"None",
":",
"return",
"None",
"m",
"=",
"[",
"]",
"for",
"p",
"i... | 31.909091 | 14.636364 |
def make_kdtree(ra, decl):
'''This makes a `scipy.spatial.CKDTree` on (`ra`, `decl`).
Parameters
----------
ra,decl : array-like
The right ascension and declination coordinate pairs in decimal degrees.
Returns
-------
`scipy.spatial.CKDTree`
The cKDTRee object generated b... | [
"def",
"make_kdtree",
"(",
"ra",
",",
"decl",
")",
":",
"# get the xyz unit vectors from ra,decl",
"# since i had to remind myself:",
"# https://en.wikipedia.org/wiki/Equatorial_coordinate_system",
"cosdecl",
"=",
"np",
".",
"cos",
"(",
"np",
".",
"radians",
"(",
"decl",
... | 26.677419 | 23.322581 |
def delete(self, adjustEstimate=None, newEstimate=None, increaseBy=None):
"""Delete this worklog entry from its associated issue.
:param adjustEstimate: one of ``new``, ``leave``, ``manual`` or ``auto``.
``auto`` is the default and adjusts the estimate automatically.
``leave`` l... | [
"def",
"delete",
"(",
"self",
",",
"adjustEstimate",
"=",
"None",
",",
"newEstimate",
"=",
"None",
",",
"increaseBy",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"adjustEstimate",
"is",
"not",
"None",
":",
"params",
"[",
"'adjustEstimate'",
"]"... | 49.777778 | 22.777778 |
def decode(buff):
"""
Transforms the raw buffer data read in into a list of bytes
"""
pp = list(map(ord, buff))
if 0 == len(pp) == 1:
pp = []
return pp | [
"def",
"decode",
"(",
"buff",
")",
":",
"pp",
"=",
"list",
"(",
"map",
"(",
"ord",
",",
"buff",
")",
")",
"if",
"0",
"==",
"len",
"(",
"pp",
")",
"==",
"1",
":",
"pp",
"=",
"[",
"]",
"return",
"pp"
] | 19.875 | 16.625 |
def json_or_jsonp(func):
"""Wrap response in JSON or JSONP style"""
@wraps(func)
def _(*args, **kwargs):
mimetype = 'application/javascript'
callback = request.args.get('callback', None)
if callback is None:
content = func(*args, **kwargs)
else:
conte... | [
"def",
"json_or_jsonp",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"_",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"mimetype",
"=",
"'application/javascript'",
"callback",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'c... | 33.846154 | 18 |
def _init_client(self, from_archive=False):
"""Init client"""
return DockerHubClient(archive=self.archive, from_archive=from_archive) | [
"def",
"_init_client",
"(",
"self",
",",
"from_archive",
"=",
"False",
")",
":",
"return",
"DockerHubClient",
"(",
"archive",
"=",
"self",
".",
"archive",
",",
"from_archive",
"=",
"from_archive",
")"
] | 36.75 | 20.5 |
def _get_names_part(self, part):
"""Get some part of the "N" entry in the vCard as a list
:param part: the name to get e.g. "prefix" or "given"
:type part: str
:returns: a list of entries for this name part
:rtype: list(str)
"""
try:
the_list = getat... | [
"def",
"_get_names_part",
"(",
"self",
",",
"part",
")",
":",
"try",
":",
"the_list",
"=",
"getattr",
"(",
"self",
".",
"vcard",
".",
"n",
".",
"value",
",",
"part",
")",
"except",
"AttributeError",
":",
"return",
"[",
"]",
"else",
":",
"# check if lis... | 32.666667 | 17.611111 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.