text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def help_info(self, exc, decorated_function, arg_name, arg_spec):
""" Print debug information to stderr. (Do nothing if object was constructed with silent_checks=True)
:param exc: raised exception
:param decorated_function: target function (function to decorate)
:param arg_name: function parameter name
:para... | [
"def",
"help_info",
"(",
"self",
",",
"exc",
",",
"decorated_function",
",",
"arg_name",
",",
"arg_spec",
")",
":",
"if",
"self",
".",
"_silent_checks",
"is",
"not",
"True",
":",
"print",
"(",
"'Exception raised:'",
",",
"file",
"=",
"sys",
".",
"stderr",
... | 41.291667 | 15.041667 |
def backend_run(self):
"""Check for cached results; then run the model if needed."""
key = self.model.hash
if self.use_memory_cache and self.get_memory_cache(key):
return self._results
if self.use_disk_cache and self.get_disk_cache(key):
return self._results
... | [
"def",
"backend_run",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"model",
".",
"hash",
"if",
"self",
".",
"use_memory_cache",
"and",
"self",
".",
"get_memory_cache",
"(",
"key",
")",
":",
"return",
"self",
".",
"_results",
"if",
"self",
".",
"use_... | 40.230769 | 10.615385 |
def recent(self):
'''
List recent wiki.
'''
kwd = {
'pager': '',
'title': 'Recent Pages',
}
self.render('wiki_page/wiki_list.html',
view=MWiki.query_recent(),
format_date=tools.format_date,
... | [
"def",
"recent",
"(",
"self",
")",
":",
"kwd",
"=",
"{",
"'pager'",
":",
"''",
",",
"'title'",
":",
"'Recent Pages'",
",",
"}",
"self",
".",
"render",
"(",
"'wiki_page/wiki_list.html'",
",",
"view",
"=",
"MWiki",
".",
"query_recent",
"(",
")",
",",
"fo... | 27.846154 | 16.153846 |
def arg(name=None, **Config): # wraps the _arg decorator, in order to allow unnamed args
r"""A decorator to configure an argument of a task.
Config:
* name (str): The name of the arg. When ommited the agument will be identified through the order of configuration.
* desc (str): The description of the arg (o... | [
"def",
"arg",
"(",
"name",
"=",
"None",
",",
"*",
"*",
"Config",
")",
":",
"# wraps the _arg decorator, in order to allow unnamed args",
"if",
"name",
"is",
"not",
"None",
":",
"# allow name as a positional arg",
"Config",
"[",
"'name'",
"]",
"=",
"name",
"return"... | 39.133333 | 27 |
def focus(self, focus: Optional[URIPARM]) -> None:
""" Set the focus node(s). If no focus node is specified, the evaluation will occur for all non-BNode
graph subjects. Otherwise it can be a string, a URIRef or a list of string/URIRef combinations
:param focus: None if focus should be all URI... | [
"def",
"focus",
"(",
"self",
",",
"focus",
":",
"Optional",
"[",
"URIPARM",
"]",
")",
"->",
"None",
":",
"self",
".",
"_focus",
"=",
"normalize_uriparm",
"(",
"focus",
")",
"if",
"focus",
"else",
"None"
] | 63.142857 | 28.714286 |
def OnContentChange(self, event):
"""Event handler for updating the content"""
self.ignore_changes = True
self.SetValue(u"" if event.text is None else event.text)
self.ignore_changes = False
event.Skip() | [
"def",
"OnContentChange",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"ignore_changes",
"=",
"True",
"self",
".",
"SetValue",
"(",
"u\"\"",
"if",
"event",
".",
"text",
"is",
"None",
"else",
"event",
".",
"text",
")",
"self",
".",
"ignore_changes",
... | 26.444444 | 20.222222 |
def task(self):
"""
Find the task for this build.
Wraps the getTaskInfo RPC.
:returns: deferred that when fired returns the Task object, or None if
we could not determine the task for this build.
"""
# If we have no .task_id, this is a no-op to return ... | [
"def",
"task",
"(",
"self",
")",
":",
"# If we have no .task_id, this is a no-op to return None.",
"if",
"not",
"self",
".",
"task_id",
":",
"return",
"defer",
".",
"succeed",
"(",
"None",
")",
"return",
"self",
".",
"connection",
".",
"getTaskInfo",
"(",
"self"... | 33.692308 | 17.846154 |
def date(value,
allow_empty = False,
minimum = None,
maximum = None,
coerce_value = True,
**kwargs):
"""Validate that ``value`` is a valid date.
:param value: The value to validate.
:type value: :class:`str <python:str>` / :class:`datetime <python:datetime.datet... | [
"def",
"date",
"(",
"value",
",",
"allow_empty",
"=",
"False",
",",
"minimum",
"=",
"None",
",",
"maximum",
"=",
"None",
",",
"coerce_value",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=too-many-branches",
"if",
"not",
"value",
"and"... | 42.42029 | 21.855072 |
def spacing_file(path):
"""
Perform paranoid text spacing from file.
"""
# TODO: read line by line
with open(os.path.abspath(path)) as f:
return spacing_text(f.read()) | [
"def",
"spacing_file",
"(",
"path",
")",
":",
"# TODO: read line by line",
"with",
"open",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"as",
"f",
":",
"return",
"spacing_text",
"(",
"f",
".",
"read",
"(",
")",
")"
] | 27 | 5.285714 |
def _get_recursive_difference(self, type):
'''Returns the recursive diff between dict values'''
if type == 'intersect':
return [recursive_diff(item['old'], item['new']) for item in self._intersect]
elif type == 'added':
return [recursive_diff({}, item) for item in self._a... | [
"def",
"_get_recursive_difference",
"(",
"self",
",",
"type",
")",
":",
"if",
"type",
"==",
"'intersect'",
":",
"return",
"[",
"recursive_diff",
"(",
"item",
"[",
"'old'",
"]",
",",
"item",
"[",
"'new'",
"]",
")",
"for",
"item",
"in",
"self",
".",
"_in... | 54.1 | 22.6 |
def QA_SU_save_etf_day(engine, client=DATABASE):
"""save etf_day
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_etf_day(client=client) | [
"def",
"QA_SU_save_etf_day",
"(",
"engine",
",",
"client",
"=",
"DATABASE",
")",
":",
"engine",
"=",
"select_save_engine",
"(",
"engine",
")",
"engine",
".",
"QA_SU_save_etf_day",
"(",
"client",
"=",
"client",
")"
] | 24.583333 | 16.583333 |
def _prior_headerfooter(self):
"""|_Header| proxy on prior sectPr element or None if this is first section."""
preceding_sectPr = self._sectPr.preceding_sectPr
return (
None if preceding_sectPr is None
else _Header(preceding_sectPr, self._document_part, self._hdrftr_index... | [
"def",
"_prior_headerfooter",
"(",
"self",
")",
":",
"preceding_sectPr",
"=",
"self",
".",
"_sectPr",
".",
"preceding_sectPr",
"return",
"(",
"None",
"if",
"preceding_sectPr",
"is",
"None",
"else",
"_Header",
"(",
"preceding_sectPr",
",",
"self",
".",
"_document... | 46.428571 | 18.285714 |
def dt_from_rfc8601(date_str):
"""Convert 8601 (ISO) date string to datetime object.
Handles "Z" and milliseconds transparently.
:param date_str: Date string.
:type date_str: ``string``
:return: Date time.
:rtype: :class:`datetime.datetime`
"""
# Normalize string and adjust for milli... | [
"def",
"dt_from_rfc8601",
"(",
"date_str",
")",
":",
"# Normalize string and adjust for milliseconds. Note that Python 2.6+ has",
"# \".%f\" format, but we're going for Python 2.5, so truncate the portion.",
"date_str",
"=",
"date_str",
".",
"rstrip",
"(",
"'Z'",
")",
".",
"split",... | 33.238095 | 16.952381 |
def internal_get_frame(dbg, seq, thread_id, frame_id):
''' Converts request into python variable '''
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
hidden_ns = pydevconsole.get_ipython_hidden_vars()
xml = "<xml>"
xml += pydevd_xml.frame... | [
"def",
"internal_get_frame",
"(",
"dbg",
",",
"seq",
",",
"thread_id",
",",
"frame_id",
")",
":",
"try",
":",
"frame",
"=",
"dbg",
".",
"find_frame",
"(",
"thread_id",
",",
"frame_id",
")",
"if",
"frame",
"is",
"not",
"None",
":",
"hidden_ns",
"=",
"py... | 50.25 | 25.55 |
def spy(self):
'''
Add a spy to this stub. Return the spy.
'''
spy = Spy(self)
self._expectations.append(spy)
return spy | [
"def",
"spy",
"(",
"self",
")",
":",
"spy",
"=",
"Spy",
"(",
"self",
")",
"self",
".",
"_expectations",
".",
"append",
"(",
"spy",
")",
"return",
"spy"
] | 23.142857 | 18.857143 |
def interpolate(self, factor, minKerning, maxKerning, round=True, suppressError=True):
"""
Interpolates all pairs between two :class:`BaseKerning` objects:
**minKerning** and **maxKerning**. The interpolation occurs on a
0 to 1.0 range where **minKerning** is located at 0 and
**... | [
"def",
"interpolate",
"(",
"self",
",",
"factor",
",",
"minKerning",
",",
"maxKerning",
",",
"round",
"=",
"True",
",",
"suppressError",
"=",
"True",
")",
":",
"factor",
"=",
"normalizers",
".",
"normalizeInterpolationFactor",
"(",
"factor",
")",
"if",
"not"... | 57.742857 | 27.057143 |
def host_impl(self, run, tool):
"""Returns available hosts for the run and tool in the log directory.
In the plugin log directory, each directory contains profile data for a
single run (identified by the directory name), and files in the run
directory contains data for different tools and hosts. The fi... | [
"def",
"host_impl",
"(",
"self",
",",
"run",
",",
"tool",
")",
":",
"hosts",
"=",
"{",
"}",
"run_dir",
"=",
"self",
".",
"_run_dir",
"(",
"run",
")",
"if",
"not",
"run_dir",
":",
"logger",
".",
"warn",
"(",
"\"Cannot find asset directory for: %s\"",
",",... | 31.710526 | 21.815789 |
def initialize(self):
"""
Initialize instance attributes. You can override this method in
the subclasses.
"""
self.main_pid = os.getpid()
self.processes.extend(self.init_service_processes())
self.processes.extend(self.init_tornado_workers()) | [
"def",
"initialize",
"(",
"self",
")",
":",
"self",
".",
"main_pid",
"=",
"os",
".",
"getpid",
"(",
")",
"self",
".",
"processes",
".",
"extend",
"(",
"self",
".",
"init_service_processes",
"(",
")",
")",
"self",
".",
"processes",
".",
"extend",
"(",
... | 36.25 | 13.75 |
def monkey_patch():
"""
Monkey patches `zmq.Context` and `zmq.Socket`
If test_suite is True, the pyzmq test suite will be patched for
compatibility as well.
"""
ozmq = __import__('zmq')
ozmq.Socket = zmq.Socket
ozmq.Context = zmq.Context
ozmq.Poller = zmq.Poller
ioloop = __impor... | [
"def",
"monkey_patch",
"(",
")",
":",
"ozmq",
"=",
"__import__",
"(",
"'zmq'",
")",
"ozmq",
".",
"Socket",
"=",
"zmq",
".",
"Socket",
"ozmq",
".",
"Context",
"=",
"zmq",
".",
"Context",
"ozmq",
".",
"Poller",
"=",
"zmq",
".",
"Poller",
"ioloop",
"=",... | 28.153846 | 13.384615 |
def lineOffsetWithMinimumDistanceToPoint(point, line_start, line_end, perpendicular=False):
"""Return the offset from line (line_start, line_end) where the distance to
point is minimal"""
p = point
p1 = line_start
p2 = line_end
l = distance(p1, p2)
u = ((p[0] - p1[0]) * (p2[0] - p1[0])) + ((... | [
"def",
"lineOffsetWithMinimumDistanceToPoint",
"(",
"point",
",",
"line_start",
",",
"line_end",
",",
"perpendicular",
"=",
"False",
")",
":",
"p",
"=",
"point",
"p1",
"=",
"line_start",
"p2",
"=",
"line_end",
"l",
"=",
"distance",
"(",
"p1",
",",
"p2",
")... | 34.133333 | 19.333333 |
def create_package_file(root, master_package, subroot, py_files, opts, subs):
"""Build the text of the file and write the file."""
package = os.path.split(root)[-1]
text = format_heading(1, '%s Package' % package)
# add each package's module
for py_file in py_files:
if shall_skip(os.path.joi... | [
"def",
"create_package_file",
"(",
"root",
",",
"master_package",
",",
"subroot",
",",
"py_files",
",",
"opts",
",",
"subs",
")",
":",
"package",
"=",
"os",
".",
"path",
".",
"split",
"(",
"root",
")",
"[",
"-",
"1",
"]",
"text",
"=",
"format_heading",... | 42.366667 | 19.366667 |
def present(name, timespec, tag=None, user=None, job=None, unique_tag=False):
'''
.. versionchanged:: 2017.7.0
Add a job to queue.
job : string
Command to run.
timespec : string
The 'timespec' follows the format documented in the at(1) manpage.
tag : string
Make a tag... | [
"def",
"present",
"(",
"name",
",",
"timespec",
",",
"tag",
"=",
"None",
",",
"user",
"=",
"None",
",",
"job",
"=",
"None",
",",
"unique_tag",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
... | 24.06 | 22.58 |
def enable_reporting(self):
"""Call this method to explicitly enable reporting.
The current report will be uploaded, plus the previously recorded ones,
and the configuration will be updated so that future runs also upload
automatically.
"""
if self.status == Stats.ENABLE... | [
"def",
"enable_reporting",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"==",
"Stats",
".",
"ENABLED",
":",
"return",
"if",
"not",
"self",
".",
"enableable",
":",
"logger",
".",
"critical",
"(",
"\"Can't enable reporting\"",
")",
"return",
"self",
"... | 36.285714 | 15.714286 |
def movnam_hdu(self, extname, hdutype=ANY_HDU, extver=0):
"""
Move to the indicated HDU by name
In general, it is not necessary to use this method explicitly.
returns the one-offset extension number
"""
extname = mks(extname)
hdu = self._FITS.movnam_hdu(hdutype,... | [
"def",
"movnam_hdu",
"(",
"self",
",",
"extname",
",",
"hdutype",
"=",
"ANY_HDU",
",",
"extver",
"=",
"0",
")",
":",
"extname",
"=",
"mks",
"(",
"extname",
")",
"hdu",
"=",
"self",
".",
"_FITS",
".",
"movnam_hdu",
"(",
"hdutype",
",",
"extname",
",",... | 31.454545 | 17.090909 |
def to_yaml(self, str_or_buffer=None):
"""
Save a model respresentation to YAML.
Parameters
----------
str_or_buffer : str or file like, optional
By default a YAML string is returned. If a string is
given here the YAML will be written to that file.
... | [
"def",
"to_yaml",
"(",
"self",
",",
"str_or_buffer",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'serializing LCM model {} to YAML'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"(",
"not",
"isinstance",
"(",
"self",
".",
"probability... | 37.24 | 19.8 |
def write_modulators_to_project_file(self, tree=None):
"""
:type modulators: list of Modulator
:return:
"""
if self.project_file is None or not self.modulators:
return
if tree is None:
tree = ET.parse(self.project_file)
root = tree.getroo... | [
"def",
"write_modulators_to_project_file",
"(",
"self",
",",
"tree",
"=",
"None",
")",
":",
"if",
"self",
".",
"project_file",
"is",
"None",
"or",
"not",
"self",
".",
"modulators",
":",
"return",
"if",
"tree",
"is",
"None",
":",
"tree",
"=",
"ET",
".",
... | 27.866667 | 17.866667 |
def find_autorest_generated_folder(module_prefix="azure"):
"""Find all Autorest generated code in that module prefix.
This actually looks for a "models" package only (not file). We could be smarter if necessary.
"""
_LOGGER.info(f"Looking for Autorest generated package in {module_prefix}")
# Manual... | [
"def",
"find_autorest_generated_folder",
"(",
"module_prefix",
"=",
"\"azure\"",
")",
":",
"_LOGGER",
".",
"info",
"(",
"f\"Looking for Autorest generated package in {module_prefix}\"",
")",
"# Manually skip some namespaces for now",
"if",
"module_prefix",
"in",
"[",
"\"azure.c... | 46.666667 | 23.444444 |
def get_priors(self):
'''
Returns
-------
pd.Series
'''
priors = self.priors
priors[~np.isfinite(priors)] = 0
priors += self.starting_count
return priors | [
"def",
"get_priors",
"(",
"self",
")",
":",
"priors",
"=",
"self",
".",
"priors",
"priors",
"[",
"~",
"np",
".",
"isfinite",
"(",
"priors",
")",
"]",
"=",
"0",
"priors",
"+=",
"self",
".",
"starting_count",
"return",
"priors"
] | 16.2 | 23.8 |
def convert_cifar100(directory, output_directory,
output_filename='cifar100.hdf5'):
"""Converts the CIFAR-100 dataset to HDF5.
Converts the CIFAR-100 dataset to an HDF5 dataset compatible with
:class:`fuel.datasets.CIFAR100`. The converted dataset is saved as
'cifar100.hdf5'.
... | [
"def",
"convert_cifar100",
"(",
"directory",
",",
"output_directory",
",",
"output_filename",
"=",
"'cifar100.hdf5'",
")",
":",
"output_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"output_directory",
",",
"output_filename",
")",
"h5file",
"=",
"h5py",
".",
... | 36.716049 | 21.691358 |
def chooseReliableActiveFiringRate(cellsPerAxis, bumpSigma,
minimumActiveDiameter=None):
"""
When a cell is activated by sensory input, this implies that the phase is
within a particular small patch of the rhombus. This patch is roughly
equivalent to a circle of diam... | [
"def",
"chooseReliableActiveFiringRate",
"(",
"cellsPerAxis",
",",
"bumpSigma",
",",
"minimumActiveDiameter",
"=",
"None",
")",
":",
"firingFieldDiameter",
"=",
"2",
"*",
"(",
"1.",
"/",
"cellsPerAxis",
")",
"*",
"(",
"2.",
"/",
"math",
".",
"sqrt",
"(",
"3"... | 50.545455 | 28.787879 |
def tokenized_texts_to_sequences_generator(self, tok_texts):
"""Transforms tokenized text to a sequence of integers.
Only top "num_words" most frequent words will be taken into account.
Only words known by the tokenizer will be taken into account.
# Arguments
tokenized texts:... | [
"def",
"tokenized_texts_to_sequences_generator",
"(",
"self",
",",
"tok_texts",
")",
":",
"for",
"seq",
"in",
"tok_texts",
":",
"vect",
"=",
"[",
"]",
"for",
"w",
"in",
"seq",
":",
"# if the word is missing you get oov_index",
"i",
"=",
"self",
".",
"word_index"... | 39.3125 | 14.4375 |
def _compile_rules(self):
"""Compile the rules into the internal lexer state."""
for state, table in self.RULES.items():
patterns = list()
actions = list()
nextstates = list()
for i, row in enumerate(table):
if len(row) == 2:
... | [
"def",
"_compile_rules",
"(",
"self",
")",
":",
"for",
"state",
",",
"table",
"in",
"self",
".",
"RULES",
".",
"items",
"(",
")",
":",
"patterns",
"=",
"list",
"(",
")",
"actions",
"=",
"list",
"(",
")",
"nextstates",
"=",
"list",
"(",
")",
"for",
... | 43.15 | 10.35 |
def wait(timeout=None, flush=True):
"""Wait for an event.
Args:
timeout (Optional[int]): The time in seconds that this function will
wait before giving up and returning None.
With the default value of None, this will block forever.
flush (bool): If True a call to :any:`... | [
"def",
"wait",
"(",
"timeout",
"=",
"None",
",",
"flush",
"=",
"True",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"=",
"timeout",
"+",
"_time",
".",
"clock",
"(",
")",
"# timeout at this time",
"while",
"True",
":",
"if",
"_eventQu... | 36.074074 | 19.407407 |
def start(self, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
""" Merged copy paste from the inheritance chain with modified stdout/err behaviour """
if self.pre_start_check():
# Some other executor (or process) is running with same config:
raise AlreadyRunning(self)
... | [
"def",
"start",
"(",
"self",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
":",
"if",
"self",
".",
"pre_start_check",
"(",
")",
":",
"# Some other executor (or process) is running with same config:",
"raise",
... | 33.65625 | 14 |
def rightsibling(node):
"""
Return Right Sibling of `node`.
>>> from anytree import Node
>>> dan = Node("Dan")
>>> jet = Node("Jet", parent=dan)
>>> jan = Node("Jan", parent=dan)
>>> joe = Node("Joe", parent=dan)
>>> rightsibling(dan)
>>> rightsibling(jet)
Node('/Dan/Jan')
>... | [
"def",
"rightsibling",
"(",
"node",
")",
":",
"if",
"node",
".",
"parent",
":",
"pchildren",
"=",
"node",
".",
"parent",
".",
"children",
"idx",
"=",
"pchildren",
".",
"index",
"(",
"node",
")",
"try",
":",
"return",
"pchildren",
"[",
"idx",
"+",
"1"... | 24 | 13.36 |
def to_table(self, sort_key="wall_time", stop=None):
"""Return a table (list of lists) with timer data"""
table = [list(AbinitTimerSection.FIELDS), ]
ord_sections = self.order_sections(sort_key)
if stop is not None:
ord_sections = ord_sections[:stop]
for osect in or... | [
"def",
"to_table",
"(",
"self",
",",
"sort_key",
"=",
"\"wall_time\"",
",",
"stop",
"=",
"None",
")",
":",
"table",
"=",
"[",
"list",
"(",
"AbinitTimerSection",
".",
"FIELDS",
")",
",",
"]",
"ord_sections",
"=",
"self",
".",
"order_sections",
"(",
"sort_... | 33.076923 | 17.538462 |
def notice_settings(request):
"""
The notice settings view.
Template: :template:`notification/notice_settings.html`
Context:
notice_types
A list of all :model:`notification.NoticeType` objects.
notice_settings
A dictionary containing ``column_headers`` for eac... | [
"def",
"notice_settings",
"(",
"request",
")",
":",
"notice_types",
"=",
"NoticeType",
".",
"objects",
".",
"all",
"(",
")",
"settings_table",
"=",
"[",
"]",
"for",
"notice_type",
"in",
"notice_types",
":",
"settings_row",
"=",
"[",
"]",
"for",
"medium_id",
... | 39.215686 | 20.627451 |
def pisaParser(src, context, default_css="", xhtml=False, encoding=None, xml_output=None):
"""
- Parse HTML and get miniDOM
- Extract CSS informations, add default CSS, parse CSS
- Handle the document DOM itself and build reportlab story
- Return Context object
"""
global CSSAttrCache
C... | [
"def",
"pisaParser",
"(",
"src",
",",
"context",
",",
"default_css",
"=",
"\"\"",
",",
"xhtml",
"=",
"False",
",",
"encoding",
"=",
"None",
",",
"xml_output",
"=",
"None",
")",
":",
"global",
"CSSAttrCache",
"CSSAttrCache",
"=",
"{",
"}",
"if",
"xhtml",
... | 32.862069 | 21.241379 |
def disp(self, idx=100): # r_[0:5,1e2:1e9:1e2,-10:0]):
"""displays selected data from (files written by) the class `CMADataLogger`.
Arguments
---------
`idx`
indices corresponding to rows in the data file;
if idx is a scalar (int), the first two, then e... | [
"def",
"disp",
"(",
"self",
",",
"idx",
"=",
"100",
")",
":",
"# r_[0:5,1e2:1e9:1e2,-10:0]):",
"filenameprefix",
"=",
"self",
".",
"name_prefix",
"def",
"printdatarow",
"(",
"dat",
",",
"iteration",
")",
":",
"\"\"\"print data of iteration i\"\"\"",
"i",
"=",
"n... | 36.597222 | 21.819444 |
def _gt_from_le(self, other):
"""Return a > b. Computed by @total_ordering from (not a <= b)."""
op_result = self.__le__(other)
if op_result is NotImplemented:
return NotImplemented
return not op_result | [
"def",
"_gt_from_le",
"(",
"self",
",",
"other",
")",
":",
"op_result",
"=",
"self",
".",
"__le__",
"(",
"other",
")",
"if",
"op_result",
"is",
"NotImplemented",
":",
"return",
"NotImplemented",
"return",
"not",
"op_result"
] | 37 | 8.166667 |
def wrap(self, text, width=None, indent=None):
"""Return ``text`` wrapped to ``width`` and indented with ``indent``.
By default:
* ``width`` is ``self.options.wrap_length``
* ``indent`` is ``self.indentation``.
"""
width = width if width is not None else self.options.w... | [
"def",
"wrap",
"(",
"self",
",",
"text",
",",
"width",
"=",
"None",
",",
"indent",
"=",
"None",
")",
":",
"width",
"=",
"width",
"if",
"width",
"is",
"not",
"None",
"else",
"self",
".",
"options",
".",
"wrap_length",
"indent",
"=",
"indent",
"if",
... | 39.8 | 18.066667 |
def contains_exclusive(self, x, y):
"""
Return True if the given point is contained within the
bounding box, where the bottom and right boundaries are
considered exclusive.
"""
left, bottom, right, top = self._aarect.lbrt()
return (left <= x < right) and (bottom <... | [
"def",
"contains_exclusive",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"left",
",",
"bottom",
",",
"right",
",",
"top",
"=",
"self",
".",
"_aarect",
".",
"lbrt",
"(",
")",
"return",
"(",
"left",
"<=",
"x",
"<",
"right",
")",
"and",
"(",
"bottom"... | 40.375 | 11.625 |
def simple_preprocess(doc, deacc=False, min_len=2, max_len=15):
"""
Convert a document into a list of tokens.
This lowercases, tokenizes, de-accents (optional). -- the output are final
tokens = unicode strings, that won't be processed any further.
"""
tokens = [
token for token in toke... | [
"def",
"simple_preprocess",
"(",
"doc",
",",
"deacc",
"=",
"False",
",",
"min_len",
"=",
"2",
",",
"max_len",
"=",
"15",
")",
":",
"tokens",
"=",
"[",
"token",
"for",
"token",
"in",
"tokenize",
"(",
"doc",
",",
"lower",
"=",
"True",
",",
"deacc",
"... | 35.153846 | 25.461538 |
def splash_url_as(self, *, format='webp', size=2048):
""":class:`Asset`: The same operation as :meth:`Guild.splash_url_as`."""
return Asset._from_guild_image(self._state, self.id, self.splash, 'splashes', format=format, size=size) | [
"def",
"splash_url_as",
"(",
"self",
",",
"*",
",",
"format",
"=",
"'webp'",
",",
"size",
"=",
"2048",
")",
":",
"return",
"Asset",
".",
"_from_guild_image",
"(",
"self",
".",
"_state",
",",
"self",
".",
"id",
",",
"self",
".",
"splash",
",",
"'splas... | 81.333333 | 28 |
def parse_kal_channel(kal_out):
"""Parse kal channel scan output."""
scan_band, scan_channel, tgt_freq = determine_band_channel(kal_out)
kal_data = {"device": determine_device(kal_out),
"sample_rate": determine_sample_rate(kal_out),
"gain": determine_scan_gain(kal_out),
... | [
"def",
"parse_kal_channel",
"(",
"kal_out",
")",
":",
"scan_band",
",",
"scan_channel",
",",
"tgt_freq",
"=",
"determine_band_channel",
"(",
"kal_out",
")",
"kal_data",
"=",
"{",
"\"device\"",
":",
"determine_device",
"(",
"kal_out",
")",
",",
"\"sample_rate\"",
... | 48.615385 | 14.461538 |
def _set_ipsec(self, v, load=False):
"""
Setter method for ipsec, mapped from YANG variable /interface/fortygigabitethernet/ipv6/interface_ospfv3_conf/authentication/ipsec (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ipsec is considered as a private
me... | [
"def",
"_set_ipsec",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 70.75 | 35.625 |
def add_lv_load_area_group(self, lv_load_area_group):
"""Adds a LV load_area to _lv_load_areas if not already existing.
"""
if lv_load_area_group not in self.lv_load_area_groups():
self._lv_load_area_groups.append(lv_load_area_group) | [
"def",
"add_lv_load_area_group",
"(",
"self",
",",
"lv_load_area_group",
")",
":",
"if",
"lv_load_area_group",
"not",
"in",
"self",
".",
"lv_load_area_groups",
"(",
")",
":",
"self",
".",
"_lv_load_area_groups",
".",
"append",
"(",
"lv_load_area_group",
")"
] | 53 | 12.2 |
def view_atype(self, atype):
"""View the given atype on the atype page
:param atype: the atype to view
:type atype: :class:`jukeboxcore.djadapter.models.Atype`
:returns: None
:rtype: None
:raises: None
"""
if not self.cur_prj:
return
l... | [
"def",
"view_atype",
"(",
"self",
",",
"atype",
")",
":",
"if",
"not",
"self",
".",
"cur_prj",
":",
"return",
"log",
".",
"debug",
"(",
"'Viewing atype %s'",
",",
"atype",
".",
"name",
")",
"self",
".",
"cur_atype",
"=",
"None",
"self",
".",
"pages_tab... | 36.888889 | 18.740741 |
def get(self, task_id):
'''taobao.topats.result.get 获取异步任务结果
使用指南:http://open.taobao.com/doc/detail.htm?id=30
- 1.此接口用于获取异步任务处理的结果,传入的task_id必需属于当前的appKey才可以
- 2.此接口只返回执行完成的任务结果,未执行完的返回结果里面不包含任务结果,只有任务id,执行状态
- 3.执行完成的每个task的子任务结果内容与单个任务的结果结构一致。如:taobao.topat... | [
"def",
"get",
"(",
"self",
",",
"task_id",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.topats.result.get'",
")",
"request",
"[",
"'task_id'",
"]",
"=",
"task_id",
"self",
".",
"create",
"(",
"self",
".",
"execute",
"(",
"request",
")",
"[",
"'t... | 43.25 | 20.916667 |
def asMIMEString(self):
"""
Return a mime-multipart representation of:
- callgrind profiling statistics (cachegrind.out.pprofile)
- any SQL query issued via ZMySQLDA (query_*.sql)
- any persistent object load via ZODB.Connection (ZODB_setstate.txt)
- any path argument giv... | [
"def",
"asMIMEString",
"(",
"self",
")",
":",
"result",
"=",
"MIMEMultipart",
"(",
")",
"base_type_dict",
"=",
"{",
"'application'",
":",
"MIMEApplication",
",",
"'text'",
":",
"MIMEText",
",",
"}",
"encoder_dict",
"=",
"{",
"'application/x-kcachegrind'",
":",
... | 38.076923 | 14.74359 |
def qos(self, prefetch_size=0, prefetch_count=0, is_global=False):
'''
Set QoS on this channel.
'''
args = Writer()
args.write_long(prefetch_size).\
write_short(prefetch_count).\
write_bit(is_global)
self.send_frame(MethodFrame(self.channel_id, 60,... | [
"def",
"qos",
"(",
"self",
",",
"prefetch_size",
"=",
"0",
",",
"prefetch_count",
"=",
"0",
",",
"is_global",
"=",
"False",
")",
":",
"args",
"=",
"Writer",
"(",
")",
"args",
".",
"write_long",
"(",
"prefetch_size",
")",
".",
"write_short",
"(",
"prefe... | 34.636364 | 18.454545 |
def task(obj = None, deps = None):
"""Decorator for creating a task."""
# The decorator is not used as a function
if callable(obj):
__task(obj.__name__, obj)
return obj
# The decorator is used as a function
def __decorated(func):
__task(obj if obj else obj.__name__, deps, func)
return func
return __deco... | [
"def",
"task",
"(",
"obj",
"=",
"None",
",",
"deps",
"=",
"None",
")",
":",
"# The decorator is not used as a function",
"if",
"callable",
"(",
"obj",
")",
":",
"__task",
"(",
"obj",
".",
"__name__",
",",
"obj",
")",
"return",
"obj",
"# The decorator is used... | 24.076923 | 17.538462 |
def setup_interpolant(self):
"""Initializes the z(d) interpolation."""
# for computing nearby (z < 1) redshifts
zs = numpy.linspace(0., 1., num=self.numpoints)
ds = self.cosmology.luminosity_distance(zs).value
self.nearby_d2z = interpolate.interp1d(ds, zs, kind='linear',
... | [
"def",
"setup_interpolant",
"(",
"self",
")",
":",
"# for computing nearby (z < 1) redshifts",
"zs",
"=",
"numpy",
".",
"linspace",
"(",
"0.",
",",
"1.",
",",
"num",
"=",
"self",
".",
"numpoints",
")",
"ds",
"=",
"self",
".",
"cosmology",
".",
"luminosity_di... | 54 | 15.133333 |
def _add_tag_files(
zip_file, dir_name, payload_info_list, payload_byte_count, payload_file_count
):
"""Generate the tag files and add them to the zip."""
tag_info_list = []
_add_tag_file(zip_file, dir_name, tag_info_list, _gen_bagit_text_file_tup())
_add_tag_file(
zip_file,
dir_name... | [
"def",
"_add_tag_files",
"(",
"zip_file",
",",
"dir_name",
",",
"payload_info_list",
",",
"payload_byte_count",
",",
"payload_file_count",
")",
":",
"tag_info_list",
"=",
"[",
"]",
"_add_tag_file",
"(",
"zip_file",
",",
"dir_name",
",",
"tag_info_list",
",",
"_gen... | 34.0625 | 26.875 |
def name_targets(func):
"""
Wrap a function such that returning ``'a', 'b', 'c', [1, 2, 3]`` transforms
the value into ``dict(a=1, b=2, c=3)``.
This is useful in the case where the last parameter is an SCons command.
"""
def wrap(*a, **kw):
ret = func(*a, **kw)
return dict(zip(r... | [
"def",
"name_targets",
"(",
"func",
")",
":",
"def",
"wrap",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
":",
"ret",
"=",
"func",
"(",
"*",
"a",
",",
"*",
"*",
"kw",
")",
"return",
"dict",
"(",
"zip",
"(",
"ret",
"[",
":",
"-",
"1",
"]",
","... | 31.272727 | 17.454545 |
def _prepare_args(target_log_prob_fn,
volatility_fn,
state,
step_size,
target_log_prob=None,
grads_target_log_prob=None,
volatility=None,
grads_volatility_fn=None,
diffusion_dr... | [
"def",
"_prepare_args",
"(",
"target_log_prob_fn",
",",
"volatility_fn",
",",
"state",
",",
"step_size",
",",
"target_log_prob",
"=",
"None",
",",
"grads_target_log_prob",
"=",
"None",
",",
"volatility",
"=",
"None",
",",
"grads_volatility_fn",
"=",
"None",
",",
... | 33.287879 | 18.651515 |
def generational_replacement(random, population, parents, offspring, args):
"""Performs generational replacement with optional weak elitism.
This function performs generational replacement, which means that
the entire existing population is replaced by the offspring,
truncating to the population si... | [
"def",
"generational_replacement",
"(",
"random",
",",
"population",
",",
"parents",
",",
"offspring",
",",
"args",
")",
":",
"num_elites",
"=",
"args",
".",
"setdefault",
"(",
"'num_elites'",
",",
"0",
")",
"population",
".",
"sort",
"(",
"reverse",
"=",
... | 42.103448 | 19.034483 |
def dirty(self, value):
""" If dirty is true set the recipe to dirty flag. If false,
clear the recipe and all extension dirty flags """
if value:
self._dirty = True
else:
self._dirty = False
for extension in self.recipe_extensions:
exte... | [
"def",
"dirty",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
":",
"self",
".",
"_dirty",
"=",
"True",
"else",
":",
"self",
".",
"_dirty",
"=",
"False",
"for",
"extension",
"in",
"self",
".",
"recipe_extensions",
":",
"extension",
".",
"dirty",
... | 36.777778 | 11 |
def _run__cherrypy(app, config, mode):
"""Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed."""
assert mode == "cherrypy-wsgiserver"
try:
from cherrypy import wsgiserver
from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter
_logger.warning("WARNING: cherrypy.ws... | [
"def",
"_run__cherrypy",
"(",
"app",
",",
"config",
",",
"mode",
")",
":",
"assert",
"mode",
"==",
"\"cherrypy-wsgiserver\"",
"try",
":",
"from",
"cherrypy",
"import",
"wsgiserver",
"from",
"cherrypy",
".",
"wsgiserver",
".",
"ssl_builtin",
"import",
"BuiltinSSL... | 35.142857 | 23.77381 |
def update(self):
"""
Redraw the figure to show changed data. This is automatically called
after `start()` was run.
"""
assert threading.current_thread() == threading.main_thread()
for axis, line, interface in self.interfaces:
line.set_xdata(interface.xdata)
... | [
"def",
"update",
"(",
"self",
")",
":",
"assert",
"threading",
".",
"current_thread",
"(",
")",
"==",
"threading",
".",
"main_thread",
"(",
")",
"for",
"axis",
",",
"line",
",",
"interface",
"in",
"self",
".",
"interfaces",
":",
"line",
".",
"set_xdata",... | 42.666667 | 13.833333 |
def update(self, distributor_id, grade_id, session, trade_type=None):
'''taobao.fenxiao.cooperation.update 更新合作关系等级
供应商更新合作的分销商等级'''
request = TOPRequest('taobao.fenxiao.cooperation.update')
request['distributor_id'] = distributor_id
request['grade_id'] = grade_id
... | [
"def",
"update",
"(",
"self",
",",
"distributor_id",
",",
"grade_id",
",",
"session",
",",
"trade_type",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.fenxiao.cooperation.update'",
")",
"request",
"[",
"'distributor_id'",
"]",
"=",
"distribu... | 47.4 | 19.4 |
def get_lib_volume_mounts(base_lib_name, assembled_specs):
""" Returns a list of the formatted volume specs for a lib"""
volumes = [_get_lib_repo_volume_mount(assembled_specs['libs'][base_lib_name])]
volumes.append(get_command_files_volume_mount(base_lib_name, test=True))
for lib_name in assembled_specs... | [
"def",
"get_lib_volume_mounts",
"(",
"base_lib_name",
",",
"assembled_specs",
")",
":",
"volumes",
"=",
"[",
"_get_lib_repo_volume_mount",
"(",
"assembled_specs",
"[",
"'libs'",
"]",
"[",
"base_lib_name",
"]",
")",
"]",
"volumes",
".",
"append",
"(",
"get_command_... | 61.125 | 23.5 |
def from_json(cls, json, _reader=blobstore.BlobReader):
"""Creates an instance of the InputReader for the given input shard state.
Args:
json: The InputReader state as a dict-like object.
_reader: For dependency injection.
Returns:
An instance of the InputReader configured using the valu... | [
"def",
"from_json",
"(",
"cls",
",",
"json",
",",
"_reader",
"=",
"blobstore",
".",
"BlobReader",
")",
":",
"return",
"cls",
"(",
"json",
"[",
"cls",
".",
"BLOB_KEY_PARAM",
"]",
",",
"json",
"[",
"cls",
".",
"START_FILE_INDEX_PARAM",
"]",
",",
"json",
... | 35 | 15.733333 |
def edit(self, id):
""" Edit a VRF
"""
c.action = 'edit'
c.edit_vrf = VRF.get(int(id))
# Did we have any action passed to us?
if 'action' in request.params:
if request.params['action'] == 'edit':
if request.params['rt'].strip() == '':
... | [
"def",
"edit",
"(",
"self",
",",
"id",
")",
":",
"c",
".",
"action",
"=",
"'edit'",
"c",
".",
"edit_vrf",
"=",
"VRF",
".",
"get",
"(",
"int",
"(",
"id",
")",
")",
"# Did we have any action passed to us?",
"if",
"'action'",
"in",
"request",
".",
"params... | 31.5 | 17.375 |
def post(self, id=None):
"""
Create a new object resource
:json: Object to create
:returns: json string representation
:rtype: JSON
"""
try:
try:
base_object = json_util.loads(self.request.body)
except TypeError:
... | [
"def",
"post",
"(",
"self",
",",
"id",
"=",
"None",
")",
":",
"try",
":",
"try",
":",
"base_object",
"=",
"json_util",
".",
"loads",
"(",
"self",
".",
"request",
".",
"body",
")",
"except",
"TypeError",
":",
"base_object",
"=",
"json_util",
".",
"loa... | 35.916667 | 26.125 |
def match(self, expr) -> MatchDict:
"""Match the given expression (recursively)
Returns a :class:`MatchDict` instance that maps any wildcard names to
the expressions that the corresponding wildcard pattern matches. For
(sub-)pattern that have a `mode` attribute other than `Pattern.singl... | [
"def",
"match",
"(",
"self",
",",
"expr",
")",
"->",
"MatchDict",
":",
"res",
"=",
"MatchDict",
"(",
")",
"if",
"self",
".",
"_has_non_single_arg",
":",
"if",
"self",
".",
"_non_single_arg_on_left",
":",
"res",
".",
"merge_lists",
"=",
"1",
"else",
":",
... | 45.9625 | 16.3625 |
def validate(self, body, signature):
"""Check signature.
https://devdocs.line.me/en/#webhook-authentication
:param str body: Request body (as text)
:param str signature: X-Line-Signature value (as text)
:rtype: bool
:return: result
"""
gen_signature = hm... | [
"def",
"validate",
"(",
"self",
",",
"body",
",",
"signature",
")",
":",
"gen_signature",
"=",
"hmac",
".",
"new",
"(",
"self",
".",
"channel_secret",
",",
"body",
".",
"encode",
"(",
"'utf-8'",
")",
",",
"hashlib",
".",
"sha256",
")",
".",
"digest",
... | 28.368421 | 17.947368 |
def gnmt_print(*args, **kwargs):
"""
Wrapper for MLPerf compliance logging calls.
All arguments but 'sync' are passed to mlperf_log.gnmt_print function.
If 'sync' is set to True then the wrapper will synchronize all distributed
workers. 'sync' should be set to True for all compliance tags that requi... | [
"def",
"gnmt_print",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
".",
"pop",
"(",
"'sync'",
")",
":",
"barrier",
"(",
")",
"if",
"get_rank",
"(",
")",
"==",
"0",
":",
"kwargs",
"[",
"'stack_offset'",
"]",
"=",
"2",
"mlper... | 39.692308 | 15.230769 |
def parseBranches(self, descendants):
"""
Parse top level of latex
:param list elements: list of source objects
:return: list of filtered TreeOfContents objects
>>> toc = TOC.fromLatex(r'\section{h1}\subsection{subh1}\section{h2}\
... \subsection{subh2}')
>>> toc... | [
"def",
"parseBranches",
"(",
"self",
",",
"descendants",
")",
":",
"i",
",",
"branches",
"=",
"self",
".",
"parseTopDepth",
"(",
"descendants",
")",
",",
"[",
"]",
"for",
"descendant",
"in",
"descendants",
":",
"if",
"self",
".",
"getHeadingLevel",
"(",
... | 39.192308 | 17.038462 |
def create_wiki(self, wiki_create_params, project=None):
"""CreateWiki.
Creates the wiki resource.
:param :class:`<WikiCreateParametersV2> <azure.devops.v5_0.wiki.models.WikiCreateParametersV2>` wiki_create_params: Parameters for the wiki creation.
:param str project: Project ID or proje... | [
"def",
"create_wiki",
"(",
"self",
",",
"wiki_create_params",
",",
"project",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
".",
"_serialize",
".",
"ur... | 56.352941 | 22.647059 |
def args_match(m_args, m_kwargs, default, *args, **kwargs):
"""
:param m_args: values to match args against
:param m_kwargs: values to match kwargs against
:param arg: args to match
:param arg: kwargs to match
"""
if len(m_args) > len(args):
return False
for m_arg, arg in zip(m... | [
"def",
"args_match",
"(",
"m_args",
",",
"m_kwargs",
",",
"default",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"m_args",
")",
">",
"len",
"(",
"args",
")",
":",
"return",
"False",
"for",
"m_arg",
",",
"arg",
"in",
"zi... | 33.952381 | 11.190476 |
def get_histograms(self, request):
""" Get histograms of requested query from log service.
Unsuccessful opertaion will cause an LogException.
:type request: GetHistogramsRequest
:param request: the GetHistograms request parameters class.
:return: GetHisto... | [
"def",
"get_histograms",
"(",
"self",
",",
"request",
")",
":",
"headers",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"if",
"request",
".",
"get_topic",
"(",
")",
"is",
"not",
"None",
":",
"params",
"[",
"'topic'",
"]",
"=",
"request",
".",
"get_topic",... | 40 | 11.407407 |
def join(self, href):
"""Given a href relative to this link, return the :class:`Link` of the absolute url.
:param href: A string-like path relative to this link.
"""
return self.wrap(urlparse.urljoin(self.url, href)) | [
"def",
"join",
"(",
"self",
",",
"href",
")",
":",
"return",
"self",
".",
"wrap",
"(",
"urlparse",
".",
"urljoin",
"(",
"self",
".",
"url",
",",
"href",
")",
")"
] | 38 | 15.166667 |
def list_present(name, acl_type, acl_names=None, perms='', recurse=False, force=False):
'''
Ensure a Linux ACL list is present
Takes a list of acl names and add them to the given path
name
The acl path
acl_type
The type of the acl is used for it can be 'user' or 'group'
acl_n... | [
"def",
"list_present",
"(",
"name",
",",
"acl_type",
",",
"acl_names",
"=",
"None",
",",
"perms",
"=",
"''",
",",
"recurse",
"=",
"False",
",",
"force",
"=",
"False",
")",
":",
"if",
"acl_names",
"is",
"None",
":",
"acl_names",
"=",
"[",
"]",
"ret",
... | 43.615789 | 25.394737 |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return HI_Algorithm(key)
if key not in HI_Algorithm._member_map_:
extend_enum(HI_Algorithm, key, default)
return HI_Algorithm[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"HI_Algorithm",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"HI_Algorithm",
".",
"_member_map_",
":",
"extend_enum",
"("... | 39.142857 | 7.714286 |
def statistics(self, start=None, end=None, namespace=None):
"""Get write statistics for the specified namespace and date range"""
return self.make_context(start=start, end=end,
namespace=namespace).statistics() | [
"def",
"statistics",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"return",
"self",
".",
"make_context",
"(",
"start",
"=",
"start",
",",
"end",
"=",
"end",
",",
"namespace",
"=",
"namespac... | 64 | 14.75 |
def check_link_tag(self):
"""\
checks to see if we were able to
find open link_src on this page
"""
node = self.article.raw_doc
meta = self.parser.getElementsByTag(node, tag='link', attr='rel', value='image_src')
for item in meta:
src = self.parser.get... | [
"def",
"check_link_tag",
"(",
"self",
")",
":",
"node",
"=",
"self",
".",
"article",
".",
"raw_doc",
"meta",
"=",
"self",
".",
"parser",
".",
"getElementsByTag",
"(",
"node",
",",
"tag",
"=",
"'link'",
",",
"attr",
"=",
"'rel'",
",",
"value",
"=",
"'... | 37.25 | 15 |
def ApplyEdits(self, adds=None, updates=None, deletes=None):
"""This operation adds, updates and deletes features to the associated
feature layer or table in a single call (POST only). The apply edits
operation is performed on a feature service layer resource. The
result of this... | [
"def",
"ApplyEdits",
"(",
"self",
",",
"adds",
"=",
"None",
",",
"updates",
"=",
"None",
",",
"deletes",
"=",
"None",
")",
":",
"add_str",
",",
"update_str",
"=",
"None",
",",
"None",
"if",
"adds",
":",
"add_str",
"=",
"\",\"",
".",
"join",
"(",
"j... | 64.92 | 25.6 |
def parse(self):
"""Parse pattern list."""
result = ['']
negative = False
p = util.norm_pattern(self.pattern, not self.unix, self.raw_chars)
p = p.decode('latin-1') if self.is_bytes else p
if is_negative(p, self.flags):
negative = True
p = p[1:]... | [
"def",
"parse",
"(",
"self",
")",
":",
"result",
"=",
"[",
"''",
"]",
"negative",
"=",
"False",
"p",
"=",
"util",
".",
"norm_pattern",
"(",
"self",
".",
"pattern",
",",
"not",
"self",
".",
"unix",
",",
"self",
".",
"raw_chars",
")",
"p",
"=",
"p"... | 29.758621 | 24.344828 |
def parse_cgmlst_alleles(cgmlst_fasta):
"""Parse cgMLST alleles from fasta file
cgMLST FASTA file must have a header format of ">{marker name}|{allele name}"
Args:
cgmlst_fasta (str): cgMLST fasta file path
Returns:
dict of list: Marker name to list of allele sequences
"""
out ... | [
"def",
"parse_cgmlst_alleles",
"(",
"cgmlst_fasta",
")",
":",
"out",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"header",
",",
"seq",
"in",
"parse_fasta",
"(",
"cgmlst_fasta",
")",
":",
"if",
"not",
"'|'",
"in",
"header",
":",
"raise",
"Exception",
"(",
... | 38.058824 | 22.647059 |
def _init_io_container(self, init_value):
"""Initialize container to hold lob data.
Here either a cStringIO or a io.StringIO class is used depending on the Python version.
For CLobs ensure that an initial unicode value only contains valid ascii chars.
"""
if isinstance(init_value... | [
"def",
"_init_io_container",
"(",
"self",
",",
"init_value",
")",
":",
"if",
"isinstance",
"(",
"init_value",
",",
"CLOB_STRING_IO_CLASSES",
")",
":",
"# already a valid StringIO instance, just use it as it is",
"v",
"=",
"init_value",
"else",
":",
"# works for strings an... | 59.176471 | 30.470588 |
def chart_json(start, end, period, symbol):
""" Requests chart data from Poloniex API
Args:
start: Int epoch date to START getting market stats from.
Note that this epoch is FURTHER from the current date.
end: Int epoch date to STOP getting market stats from.
Note th... | [
"def",
"chart_json",
"(",
"start",
",",
"end",
",",
"period",
",",
"symbol",
")",
":",
"url",
"=",
"(",
"'https://poloniex.com/public?command'",
"'=returnChartData¤cyPair={0}&start={1}'",
"'&end={2}&period={3}'",
")",
".",
"format",
"(",
"symbol",
",",
"start",
... | 40.777778 | 18.888889 |
def contigsub(a,b):
'find longest common substring. return its slice coordinates (in a and b; see last line) or None if not found'
'a and b are token lists'
common=commonelts(a,b); groupsa=groupelts(a,common); groupsb=groupelts(b,common)
bestmatch=[None,None,0]; bslice=None
for i in range(len(groupsb)):
... | [
"def",
"contigsub",
"(",
"a",
",",
"b",
")",
":",
"'a and b are token lists'",
"common",
"=",
"commonelts",
"(",
"a",
",",
"b",
")",
"groupsa",
"=",
"groupelts",
"(",
"a",
",",
"common",
")",
"groupsb",
"=",
"groupelts",
"(",
"b",
",",
"common",
")",
... | 67.846154 | 35.384615 |
def geojson_to_gml(gj, set_srs=True):
"""Given a dict deserialized from a GeoJSON object, returns an lxml Element
of the corresponding GML geometry."""
tag = G(gj['type'])
if set_srs:
tag.set('srsName', 'urn:ogc:def:crs:EPSG::4326')
if gj['type'] == 'Point':
tag.append(G.pos(_revers... | [
"def",
"geojson_to_gml",
"(",
"gj",
",",
"set_srs",
"=",
"True",
")",
":",
"tag",
"=",
"G",
"(",
"gj",
"[",
"'type'",
"]",
")",
"if",
"set_srs",
":",
"tag",
".",
"set",
"(",
"'srsName'",
",",
"'urn:ogc:def:crs:EPSG::4326'",
")",
"if",
"gj",
"[",
"'ty... | 39.16129 | 20 |
def get_prices(self) -> List[PriceModel]:
""" Returns all available prices for security """
# return self.security.prices.order_by(Price.date)
from pricedb.dal import Price
pricedb = PriceDbApplication()
repo = pricedb.get_price_repository()
query = (repo.query(Price)
... | [
"def",
"get_prices",
"(",
"self",
")",
"->",
"List",
"[",
"PriceModel",
"]",
":",
"# return self.security.prices.order_by(Price.date)",
"from",
"pricedb",
".",
"dal",
"import",
"Price",
"pricedb",
"=",
"PriceDbApplication",
"(",
")",
"repo",
"=",
"pricedb",
".",
... | 38.769231 | 12.692308 |
def build_index_from_design(df, design, remove_prefix=None, types=None, axis=1, auto_convert_numeric=True, unmatched_columns='index'):
"""
Build a MultiIndex from a design table.
Supply with a table with column headings for the new multiindex
and a index containing the labels to search for in the data.... | [
"def",
"build_index_from_design",
"(",
"df",
",",
"design",
",",
"remove_prefix",
"=",
"None",
",",
"types",
"=",
"None",
",",
"axis",
"=",
"1",
",",
"auto_convert_numeric",
"=",
"True",
",",
"unmatched_columns",
"=",
"'index'",
")",
":",
"df",
"=",
"df",
... | 26.88764 | 20.41573 |
def execute(self):
"""
Execute the job, that is, execute all of its tasks.
Each produced sync map will be stored
inside the corresponding task object.
:raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution
"""
... | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Executing job\"",
")",
"if",
"self",
".",
"job",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The job object is None\"",
",",
"None",
",",
"True",
",",
"ExecuteJobExecutionError",
... | 47.875 | 27.75 |
def add_output_option(parser):
"""output option"""
parser.add_argument("-o", "--outdir", dest="outdir", type=str, default='GSEApy_reports',
metavar='', action="store",
help="The GSEApy output directory. Default: the current working directory")
parser.add_argu... | [
"def",
"add_output_option",
"(",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"\"-o\"",
",",
"\"--outdir\"",
",",
"dest",
"=",
"\"outdir\"",
",",
"type",
"=",
"str",
",",
"default",
"=",
"'GSEApy_reports'",
",",
"metavar",
"=",
"''",
",",
"actio... | 77.95 | 43.8 |
def check_application_state(self, request, callback):
"Check optional state parameter."
stored = request.session.get(self.session_key, None)
returned = request.GET.get('state', None)
check = False
if stored is not None:
if returned is not None:
check =... | [
"def",
"check_application_state",
"(",
"self",
",",
"request",
",",
"callback",
")",
":",
"stored",
"=",
"request",
".",
"session",
".",
"get",
"(",
"self",
".",
"session_key",
",",
"None",
")",
"returned",
"=",
"request",
".",
"GET",
".",
"get",
"(",
... | 41.461538 | 17.307692 |
def _get_revision(self, revision):
"""
For git backend we always return integer here. This way we ensure
that changset's revision attribute would become integer.
"""
is_null = lambda o: len(o) == revision.count('0')
try:
self.revisions[0]
except (Key... | [
"def",
"_get_revision",
"(",
"self",
",",
"revision",
")",
":",
"is_null",
"=",
"lambda",
"o",
":",
"len",
"(",
"o",
")",
"==",
"revision",
".",
"count",
"(",
"'0'",
")",
"try",
":",
"self",
".",
"revisions",
"[",
"0",
"]",
"except",
"(",
"KeyError... | 39.577778 | 21.622222 |
def is_auth(nodes):
'''
Check if nodes are already authorized
nodes
a list of nodes to be checked for authorization to the cluster
CLI Example:
.. code-block:: bash
salt '*' pcs.is_auth nodes='[node1.example.org node2.example.org]'
'''
cmd = ['pcs', 'cluster', 'auth']
... | [
"def",
"is_auth",
"(",
"nodes",
")",
":",
"cmd",
"=",
"[",
"'pcs'",
",",
"'cluster'",
",",
"'auth'",
"]",
"cmd",
"+=",
"nodes",
"return",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"cmd",
",",
"stdin",
"=",
"'\\n\\n'",
",",
"output_loglevel",
"=",
"'t... | 24.529412 | 29.941176 |
def ticket_tags(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/tags#show-tags"
api_path = "/api/v2/tickets/{id}/tags.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | [
"def",
"ticket_tags",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/tickets/{id}/tags.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"(",
"api_path",
... | 49 | 10.6 |
def _insert_breathe_configs(c, *, project_name, doxygen_xml_dirname):
"""Add breathe extension configurations to the state.
"""
if doxygen_xml_dirname is not None:
c['breathe_projects'] = {project_name: doxygen_xml_dirname}
c['breathe_default_project'] = project_name
return c | [
"def",
"_insert_breathe_configs",
"(",
"c",
",",
"*",
",",
"project_name",
",",
"doxygen_xml_dirname",
")",
":",
"if",
"doxygen_xml_dirname",
"is",
"not",
"None",
":",
"c",
"[",
"'breathe_projects'",
"]",
"=",
"{",
"project_name",
":",
"doxygen_xml_dirname",
"}"... | 43.142857 | 13.714286 |
def set(self, section, key, value):
"""set function sets a particular value for the specified key in the
specified section and writes it to the config file.
Parameters:
* **section (string):** the section under which the config should be saved. Only accepted values are - oxd, client... | [
"def",
"set",
"(",
"self",
",",
"section",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"parser",
".",
"has_section",
"(",
"section",
")",
":",
"logger",
".",
"warning",
"(",
"\"Invalid config section: %s\"",
",",
"section",
")",
"return... | 36.75 | 27.375 |
def update(self):
"""Update |QFactor| based on |FT| and the current simulation step size.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> simulationstep('1d')
>>> ft(10.0)
>>> derived.qfactor.update()
>>> derived.qfactor
qfactor(0.115741)... | [
"def",
"update",
"(",
"self",
")",
":",
"con",
"=",
"self",
".",
"subpars",
".",
"pars",
".",
"control",
"self",
"(",
"con",
".",
"ft",
"*",
"1000.",
"/",
"self",
".",
"simulationstep",
".",
"seconds",
")"
] | 31.923077 | 11.615385 |
def proto_0202(theABF):
"""protocol: MTIV."""
abf=ABF(theABF)
abf.log.info("analyzing as MTIV")
plot=ABFplot(abf)
plot.figure_height,plot.figure_width=SQUARESIZE,SQUARESIZE
plot.title=""
plot.kwargs["alpha"]=.6
plot.figure_sweeps()
# frame to uppwer/lower bounds, ignoring peaks from... | [
"def",
"proto_0202",
"(",
"theABF",
")",
":",
"abf",
"=",
"ABF",
"(",
"theABF",
")",
"abf",
".",
"log",
".",
"info",
"(",
"\"analyzing as MTIV\"",
")",
"plot",
"=",
"ABFplot",
"(",
"abf",
")",
"plot",
".",
"figure_height",
",",
"plot",
".",
"figure_wid... | 27.9 | 19.65 |
def create_from_params(cls, template_model, datastore_name, vm_cluster_model, ip_regex, refresh_ip_timeout,
auto_power_on, auto_power_off, wait_for_ip, auto_delete):
"""
:param VCenterTemplateModel template_model:
:param str datastore_name:
:param VMClusterMode... | [
"def",
"create_from_params",
"(",
"cls",
",",
"template_model",
",",
"datastore_name",
",",
"vm_cluster_model",
",",
"ip_regex",
",",
"refresh_ip_timeout",
",",
"auto_power_on",
",",
"auto_power_off",
",",
"wait_for_ip",
",",
"auto_delete",
")",
":",
"dic",
"=",
"... | 40.52 | 12.6 |
def find(self,cell_designation,cell_filter=lambda x,c: 'c' in x and x['c'] == c):
"""
finds spike containers in multi spike containers collection offspring
"""
if 'parent' in self.meta:
return (self.meta['parent'],self.meta['parent'].find(cell_designation,cell_filter=cell... | [
"def",
"find",
"(",
"self",
",",
"cell_designation",
",",
"cell_filter",
"=",
"lambda",
"x",
",",
"c",
":",
"'c'",
"in",
"x",
"and",
"x",
"[",
"'c'",
"]",
"==",
"c",
")",
":",
"if",
"'parent'",
"in",
"self",
".",
"meta",
":",
"return",
"(",
"self... | 54 | 26 |
def fill_concentric_circles(size, center, radius):
"""
Returns a path that fills a concentric circle with the given radius and center.
:param radius:
:param center:
:param size: The size of the image, used to skip points that are out of bounds.
:return: Yields iterators, where each iterator yiel... | [
"def",
"fill_concentric_circles",
"(",
"size",
",",
"center",
",",
"radius",
")",
":",
"for",
"r",
"in",
"range",
"(",
"radius",
")",
":",
"yield",
"concentric_circle",
"(",
"center",
",",
"r",
",",
"size",
"=",
"size",
")"
] | 48.083333 | 23.083333 |
def request_pdu(self):
""" Build request PDU to read coils.
:return: Byte array of 5 bytes with PDU.
"""
if None in [self.starting_address, self.quantity]:
# TODO Raise proper exception.
raise Exception
return struct.pack('>BHH', self.function_code, self... | [
"def",
"request_pdu",
"(",
"self",
")",
":",
"if",
"None",
"in",
"[",
"self",
".",
"starting_address",
",",
"self",
".",
"quantity",
"]",
":",
"# TODO Raise proper exception.",
"raise",
"Exception",
"return",
"struct",
".",
"pack",
"(",
"'>BHH'",
",",
"self"... | 33.636364 | 16.090909 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.