text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def kth_to_last_eval(head, k):
"""
This is a suboptimal, hacky method using eval(), which is not
safe for user input. We guard against danger by ensuring k in an int
"""
if not isinstance(k, int) or not head.val:
return False
nexts = '.'.join(['next' for n in range(1, k+1)])
seeker... | [
"def",
"kth_to_last_eval",
"(",
"head",
",",
"k",
")",
":",
"if",
"not",
"isinstance",
"(",
"k",
",",
"int",
")",
"or",
"not",
"head",
".",
"val",
":",
"return",
"False",
"nexts",
"=",
"'.'",
".",
"join",
"(",
"[",
"'next'",
"for",
"n",
"in",
"ra... | 26.166667 | 0.002049 |
def exec_command(self, command, bufsize=-1, get_pty=False):
"""
Execute a command in the connection
@param command: command to execute
@type command: str
@param bufsize: buffer size
@type bufsize: int
@param get_pty: get pty
@type get_pty: bool
... | [
"def",
"exec_command",
"(",
"self",
",",
"command",
",",
"bufsize",
"=",
"-",
"1",
",",
"get_pty",
"=",
"False",
")",
":",
"self",
".",
"last_command",
"=",
"command",
"return",
"self",
".",
"cli",
".",
"exec_command",
"(",
"command",
",",
"bufsize",
"... | 32.190476 | 0.002874 |
def add_virtualfields(self, names, methods):
"""Returns a view of this array with the given methods added as virtual
fields. Specifically, the given methods are added using add_properties
and their names are added to the list of virtual fields. Virtual fields
are properties that are assu... | [
"def",
"add_virtualfields",
"(",
"self",
",",
"names",
",",
"methods",
")",
":",
"if",
"isinstance",
"(",
"names",
",",
"string_types",
")",
":",
"names",
"=",
"[",
"names",
"]",
"methods",
"=",
"[",
"methods",
"]",
"out",
"=",
"self",
".",
"add_proper... | 46.466667 | 0.002813 |
def unit_conversion(array, unit_prefix, current_prefix=""):
"""
Converts an array or value to of a certain
unit scale to another unit scale.
Accepted units are:
E - exa - 1e18
P - peta - 1e15
T - tera - 1e12
G - giga - 1e9
M - mega - 1e6
k - kilo - 1e3
m - milli - 1e-3
... | [
"def",
"unit_conversion",
"(",
"array",
",",
"unit_prefix",
",",
"current_prefix",
"=",
"\"\"",
")",
":",
"UnitDict",
"=",
"{",
"'E'",
":",
"1e18",
",",
"'P'",
":",
"1e15",
",",
"'T'",
":",
"1e12",
",",
"'G'",
":",
"1e9",
",",
"'M'",
":",
"1e6",
",... | 26.55 | 0.002421 |
def increment_version(context):
"""Increments the __version__ attribute of your module's __init__."""
attributes.replace_attribute(
context.module_name, '__version__', context.new_version, dry_run=context.dry_run
)
log.info(
'Bumped version from %s to %s' % (context.current_version, con... | [
"def",
"increment_version",
"(",
"context",
")",
":",
"attributes",
".",
"replace_attribute",
"(",
"context",
".",
"module_name",
",",
"'__version__'",
",",
"context",
".",
"new_version",
",",
"dry_run",
"=",
"context",
".",
"dry_run",
")",
"log",
".",
"info",... | 37.222222 | 0.008746 |
def add(self, transport, address=None):
"""
add a new recipient to be addressable by this MessageDispatcher
generate a new uuid address if one is not specified
"""
if not address:
address = str(uuid.uuid1())
if address in self.recipients:
... | [
"def",
"add",
"(",
"self",
",",
"transport",
",",
"address",
"=",
"None",
")",
":",
"if",
"not",
"address",
":",
"address",
"=",
"str",
"(",
"uuid",
".",
"uuid1",
"(",
")",
")",
"if",
"address",
"in",
"self",
".",
"recipients",
":",
"self",
".",
... | 30.666667 | 0.004219 |
def get_restricted_sites(self, request):
"""
The sites on which the user has permission on.
To return the permissions, the method check for the ``get_sites``
method on the user instance (e.g.: ``return request.user.get_sites()``)
which must return the queryset of enabled sites.
... | [
"def",
"get_restricted_sites",
"(",
"self",
",",
"request",
")",
":",
"try",
":",
"return",
"request",
".",
"user",
".",
"get_sites",
"(",
")",
"except",
"AttributeError",
":",
"# pragma: no cover",
"return",
"Site",
".",
"objects",
".",
"none",
"(",
")"
] | 39.058824 | 0.002941 |
def cover(session):
"""Run the final coverage report.
This outputs the coverage report aggregating coverage from the unit
test runs (not system test runs), and then erases coverage data.
"""
session.interpreter = 'python3.6'
session.install('coverage', 'pytest-cov')
session.run('coverage', '... | [
"def",
"cover",
"(",
"session",
")",
":",
"session",
".",
"interpreter",
"=",
"'python3.6'",
"session",
".",
"install",
"(",
"'coverage'",
",",
"'pytest-cov'",
")",
"session",
".",
"run",
"(",
"'coverage'",
",",
"'report'",
",",
"'--show-missing'",
",",
"'--... | 43.888889 | 0.002481 |
def to_dict(self):
'''Save this service port connector into a dictionary.'''
d = {'connectorId': self.connector_id,
'name': self.name,
'sourceServicePort': self.source_service_port.to_dict(),
'targetServicePort': self.target_service_port.to_dict()}
... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"'connectorId'",
":",
"self",
".",
"connector_id",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'sourceServicePort'",
":",
"self",
".",
"source_service_port",
".",
"to_dict",
"(",
")",
",",
"'targ... | 40.142857 | 0.004635 |
def process_extensions(
headers: Headers,
available_extensions: Optional[Sequence[ServerExtensionFactory]],
) -> Tuple[Optional[str], List[Extension]]:
"""
Handle the Sec-WebSocket-Extensions HTTP request header.
Accept or reject each extension proposed in the client request... | [
"def",
"process_extensions",
"(",
"headers",
":",
"Headers",
",",
"available_extensions",
":",
"Optional",
"[",
"Sequence",
"[",
"ServerExtensionFactory",
"]",
"]",
",",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"str",
"]",
",",
"List",
"[",
"Extension",
"]"... | 40.4 | 0.00151 |
def iterkeys(self):
"""
Returns an iterator that crawls the entire Windows Registry.
"""
stack = collections.deque(self._hives)
stack.reverse()
return self.__iterate(stack) | [
"def",
"iterkeys",
"(",
"self",
")",
":",
"stack",
"=",
"collections",
".",
"deque",
"(",
"self",
".",
"_hives",
")",
"stack",
".",
"reverse",
"(",
")",
"return",
"self",
".",
"__iterate",
"(",
"stack",
")"
] | 30.571429 | 0.009091 |
def get_ip_list_by_multi_process_ping(ip_list=[], n=0, _type='stock'):
''' 根据ping排序返回可用的ip列表
2019 03 31 取消参数filename
:param ip_list: ip列表
:param n: 最多返回的ip数量, 当可用ip数量小于n,返回所有可用的ip;n=0时,返回所有可用ip
:param _type: ip类型
:return: 可以ping通的ip列表
'''
cache = QA_util_cache()
results = cache.get(... | [
"def",
"get_ip_list_by_multi_process_ping",
"(",
"ip_list",
"=",
"[",
"]",
",",
"n",
"=",
"0",
",",
"_type",
"=",
"'stock'",
")",
":",
"cache",
"=",
"QA_util_cache",
"(",
")",
"results",
"=",
"cache",
".",
"get",
"(",
"_type",
")",
"if",
"results",
":"... | 33.410256 | 0.002983 |
def load_hpo(adapter, disease_lines, hpo_disease_lines=None, hpo_lines=None, hpo_gene_lines=None):
"""Load the hpo terms and hpo diseases into database
Args:
adapter(MongoAdapter)
disease_lines(iterable(str)): These are the omim genemap2 information
hpo_lines(iterable(str))
... | [
"def",
"load_hpo",
"(",
"adapter",
",",
"disease_lines",
",",
"hpo_disease_lines",
"=",
"None",
",",
"hpo_lines",
"=",
"None",
",",
"hpo_gene_lines",
"=",
"None",
")",
":",
"# Create a map from gene aliases to gene objects",
"alias_genes",
"=",
"adapter",
".",
"gene... | 35.392857 | 0.006876 |
def save_record(self, agent_id, t_step, key, value):
'''
Save a collection of records to the database.
Database writes are cached.
'''
value = self.convert(key, value)
self._tups.append(Record(agent_id=agent_id,
t_step=t_step,
... | [
"def",
"save_record",
"(",
"self",
",",
"agent_id",
",",
"t_step",
",",
"key",
",",
"value",
")",
":",
"value",
"=",
"self",
".",
"convert",
"(",
"key",
",",
"value",
")",
"self",
".",
"_tups",
".",
"append",
"(",
"Record",
"(",
"agent_id",
"=",
"a... | 37.5 | 0.004338 |
def language(self, value=None):
"""No arguments: Get the document's language (ISO-639-3) from metadata
Argument: Set the document's language (ISO-639-3) in metadata
"""
if not (value is None):
if (self.metadatatype == "native"):
self.metadata['language'] = ... | [
"def",
"language",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"not",
"(",
"value",
"is",
"None",
")",
":",
"if",
"(",
"self",
".",
"metadatatype",
"==",
"\"native\"",
")",
":",
"self",
".",
"metadata",
"[",
"'language'",
"]",
"=",
"val... | 37.25 | 0.003273 |
def adjustUncertToExposureTime(facExpTime, uncertMap, evtLenMap):
'''
Adjust image uncertainty (measured at exposure time t0)
to new exposure time
facExpTime --> new exp.time / reference exp.time =(t/t0)
uncertMap --> 2d array mapping image uncertainty
evtLen --> 2d array mappi... | [
"def",
"adjustUncertToExposureTime",
"(",
"facExpTime",
",",
"uncertMap",
",",
"evtLenMap",
")",
":",
"#fit parameters, obtained from ####[simulateUncertDependencyOnExpTime]\r",
"params",
"=",
"np",
".",
"array",
"(",
"#a facExpTime f_0 f_inf ... | 48.02 | 0.013878 |
def _flush(self, buffer, start, end):
"""
Flush the write buffer of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
Supported only with page blobs.
end (int): End of buffer p... | [
"def",
"_flush",
"(",
"self",
",",
"buffer",
",",
"start",
",",
"end",
")",
":",
"buffer_size",
"=",
"len",
"(",
"buffer",
")",
"if",
"not",
"buffer_size",
":",
"return",
"# Write range normally",
"with",
"self",
".",
"_size_lock",
":",
"if",
"end",
">",... | 37.592593 | 0.00096 |
def get_html_values(self, pydict, recovery_name=True):
"""Convert naive get response data to human readable field name format.
using html data format.
"""
new_dict = {"id": pydict["id"]}
for field in self:
if field.key in pydict:
if recovery_n... | [
"def",
"get_html_values",
"(",
"self",
",",
"pydict",
",",
"recovery_name",
"=",
"True",
")",
":",
"new_dict",
"=",
"{",
"\"id\"",
":",
"pydict",
"[",
"\"id\"",
"]",
"}",
"for",
"field",
"in",
"self",
":",
"if",
"field",
".",
"key",
"in",
"pydict",
"... | 36.846154 | 0.00611 |
def read_data(self, **kwargs):
"""
get the data from the service
:param kwargs: contain keyword args : trigger_id and model name
:type kwargs: dict
:rtype: dict
"""
date_triggered = kwargs.get('date_triggered')
trigger_id = kwargs.get('tri... | [
"def",
"read_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"date_triggered",
"=",
"kwargs",
".",
"get",
"(",
"'date_triggered'",
")",
"trigger_id",
"=",
"kwargs",
".",
"get",
"(",
"'trigger_id'",
")",
"kwargs",
"[",
"'model_name'",
"]",
"=",
"'R... | 39.282051 | 0.002548 |
def _print_dict(elem_dict):
"""
Print a dict in a readable way
"""
for key, value in sorted(elem_dict.iteritems()):
if isinstance(value, collections.Iterable):
print(key, len(value))
else:
print(key, value) | [
"def",
"_print_dict",
"(",
"elem_dict",
")",
":",
"for",
"key",
",",
"value",
"in",
"sorted",
"(",
"elem_dict",
".",
"iteritems",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Iterable",
")",
":",
"print",
"(",
"key",
... | 28.222222 | 0.003817 |
def nested(self, format_callback=None):
"""
Return the graph as a nested list.
"""
seen = set()
roots = []
for root in self.edges.get(None, ()):
roots.extend(self._nested(root, seen, format_callback))
return roots | [
"def",
"nested",
"(",
"self",
",",
"format_callback",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"roots",
"=",
"[",
"]",
"for",
"root",
"in",
"self",
".",
"edges",
".",
"get",
"(",
"None",
",",
"(",
")",
")",
":",
"roots",
".",
"exten... | 30.333333 | 0.007117 |
def _vector_pattern_uniform_op_right(func):
"""decorator for operator overloading when VectorPatternUniform is on
the right"""
@wraps(func)
def verif(self, patt):
if isinstance(patt, numbers.Number):
return TransversePatternUniform(func(self, self._tdsph... | [
"def",
"_vector_pattern_uniform_op_right",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"verif",
"(",
"self",
",",
"patt",
")",
":",
"if",
"isinstance",
"(",
"patt",
",",
"numbers",
".",
"Number",
")",
":",
"return",
"TransversePatternUnif... | 46.75 | 0.008741 |
def reasoning_routine(self, groups, check, priority_flag=3,
_top_level=True):
"""
print routine performed
@param list groups: the Result groups
@param str check: checker name
@param int priority_flag: indicates the weight of the groups
@param boo... | [
"def",
"reasoning_routine",
"(",
"self",
",",
"groups",
",",
"check",
",",
"priority_flag",
"=",
"3",
",",
"_top_level",
"=",
"True",
")",
":",
"sort_fn",
"=",
"lambda",
"x",
":",
"x",
".",
"weight",
"groups_sorted",
"=",
"sorted",
"(",
"groups",
",",
... | 41.773333 | 0.002183 |
def display_prediction(basis, num_basis=4, wlim=(-1.,1.), fig=None, ax=None, xlim=None, ylim=None, num_points=1000, offset=0.0, **kwargs):
"""Interactive widget for displaying a prediction function based on summing separate basis functions.
:param basis: a function handle that calls the basis functions.
:ty... | [
"def",
"display_prediction",
"(",
"basis",
",",
"num_basis",
"=",
"4",
",",
"wlim",
"=",
"(",
"-",
"1.",
",",
"1.",
")",
",",
"fig",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"xlim",
"=",
"None",
",",
"ylim",
"=",
"None",
",",
"num_points",
"=",
... | 32.106383 | 0.005464 |
def remove_all_callbacks(self):
""" Removes all registered callbacks."""
for cb_id in list(self._next_tick_callback_removers.keys()):
self.remove_next_tick_callback(cb_id)
for cb_id in list(self._timeout_callback_removers.keys()):
self.remove_timeout_callback(cb_id)
... | [
"def",
"remove_all_callbacks",
"(",
"self",
")",
":",
"for",
"cb_id",
"in",
"list",
"(",
"self",
".",
"_next_tick_callback_removers",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"remove_next_tick_callback",
"(",
"cb_id",
")",
"for",
"cb_id",
"in",
"list",
... | 53 | 0.00464 |
def _update_bytes(self, defns, start=0):
"""Updates the 'bytes' field in all FieldDefinition.
Any FieldDefinition.bytes which is undefined (None) or '@prev'
will have its bytes field computed based on its data type size
and where the previous FieldDefinition ended (or the start
... | [
"def",
"_update_bytes",
"(",
"self",
",",
"defns",
",",
"start",
"=",
"0",
")",
":",
"pos",
"=",
"slice",
"(",
"start",
",",
"start",
")",
"for",
"fd",
"in",
"defns",
":",
"if",
"fd",
".",
"bytes",
"==",
"'@prev'",
"or",
"fd",
".",
"bytes",
"is",... | 41.46875 | 0.004418 |
def hilbert_amplitude(ts):
"""Amplitude of the analytic signal, using the Hilbert transform"""
output = np.abs(signal.hilbert(signal.detrend(ts, axis=0), axis=0))
return Timeseries(output, ts.tspan, labels=ts.labels) | [
"def",
"hilbert_amplitude",
"(",
"ts",
")",
":",
"output",
"=",
"np",
".",
"abs",
"(",
"signal",
".",
"hilbert",
"(",
"signal",
".",
"detrend",
"(",
"ts",
",",
"axis",
"=",
"0",
")",
",",
"axis",
"=",
"0",
")",
")",
"return",
"Timeseries",
"(",
"... | 56.25 | 0.004386 |
def classify_resource_type(resource):
"""
Determine if the specified resource is remote or local.
We can handle three remote resource types from the command line,
remote RPMs, directory indexes, and input files. They're
classified by matching the following patterns:
- Remote RPMS start with ht... | [
"def",
"classify_resource_type",
"(",
"resource",
")",
":",
"if",
"is_remote_package",
"(",
"resource",
")",
":",
"juicer",
".",
"utils",
".",
"Log",
".",
"log_debug",
"(",
"\"Classified %s as a remote package\"",
"%",
"resource",
")",
"return",
"REMOTE_PKG_TYPE",
... | 43 | 0.003791 |
def set_params(w, src):
"""
Set source parameters.
"""
params = extract_source_params(src)
# this is done because for characteristic sources geometry is in
# 'surface' attribute
params.update(extract_geometry_params(src))
mfd_pars, rate_pars = extract_mfd_params(src)
params.update(m... | [
"def",
"set_params",
"(",
"w",
",",
"src",
")",
":",
"params",
"=",
"extract_source_params",
"(",
"src",
")",
"# this is done because for characteristic sources geometry is in",
"# 'surface' attribute",
"params",
".",
"update",
"(",
"extract_geometry_params",
"(",
"src",
... | 28.428571 | 0.001215 |
def _parse_new_contract_args(*args, **kwargs):
"""Parse argument for new_contract() function."""
# No arguments
if (not args) and (not kwargs):
return [
{
"name": "argument_invalid",
"msg": "Argument `*[argument_name]*` is not valid",
"type... | [
"def",
"_parse_new_contract_args",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# No arguments",
"if",
"(",
"not",
"args",
")",
"and",
"(",
"not",
"kwargs",
")",
":",
"return",
"[",
"{",
"\"name\"",
":",
"\"argument_invalid\"",
",",
"\"msg\"",
"... | 35.904762 | 0.002584 |
def _mom(self, k, left, right, cache):
"""
Statistical moments.
Example:
>>> print(numpy.around(chaospy.Uniform().mom([0, 1, 2, 3]), 4))
[1. 0.5 0.3333 0.25 ]
>>> print(numpy.around(chaospy.Pow(chaospy.Uniform(), 2).mom([0, 1, 2, 3]), 4))
... | [
"def",
"_mom",
"(",
"self",
",",
"k",
",",
"left",
",",
"right",
",",
"cache",
")",
":",
"if",
"isinstance",
"(",
"right",
",",
"Dist",
")",
":",
"raise",
"StochasticallyDependentError",
"(",
"\"distribution as exponent not supported.\"",
")",
"if",
"not",
"... | 48.766667 | 0.004021 |
def fill_signed_info(self, signed_info):
"""
Fills the SignedInfo node
:param signed_info: SignedInfo node
:type signed_info: lxml.etree.Element
:return: None
"""
for reference in signed_info.findall(
'ds:Reference', namespaces=constants.NS_MAP
... | [
"def",
"fill_signed_info",
"(",
"self",
",",
"signed_info",
")",
":",
"for",
"reference",
"in",
"signed_info",
".",
"findall",
"(",
"'ds:Reference'",
",",
"namespaces",
"=",
"constants",
".",
"NS_MAP",
")",
":",
"self",
".",
"calculate_reference",
"(",
"refere... | 33.727273 | 0.005249 |
def select_record(self, table, where=None, values=None, orderby=None, limit=None, columns=None):
''' Support these keywords where, values, orderby, limit and columns'''
query = self.schema.query_builder.build_select(table, where, orderby, limit, columns)
return table.to_table(self.execute(query,... | [
"def",
"select_record",
"(",
"self",
",",
"table",
",",
"where",
"=",
"None",
",",
"values",
"=",
"None",
",",
"orderby",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"columns",
"=",
"None",
")",
":",
"query",
"=",
"self",
".",
"schema",
".",
"quer... | 85.75 | 0.011561 |
def _query_server_pos(self, conn, file_length):
"""
Queries server to find out what bytes it currently has.
Returns (server_start, server_end), where the values are inclusive.
For example, (0, 2) would mean that the server has bytes 0, 1, *and* 2.
Raises ResumableUploadExceptio... | [
"def",
"_query_server_pos",
"(",
"self",
",",
"conn",
",",
"file_length",
")",
":",
"resp",
"=",
"self",
".",
"_query_server_state",
"(",
"conn",
",",
"file_length",
")",
"if",
"resp",
".",
"status",
"==",
"200",
":",
"return",
"(",
"0",
",",
"file_lengt... | 50.155556 | 0.002173 |
def expool(name):
"""
Confirm the existence of a kernel variable in the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/expool_c.html
:param name: Name of the variable whose value is to be returned.
:type name: str
:return: True when the variable is in the pool.
:rtype... | [
"def",
"expool",
"(",
"name",
")",
":",
"name",
"=",
"stypes",
".",
"stringToCharP",
"(",
"name",
")",
"found",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"libspice",
".",
"expool_c",
"(",
"name",
",",
"ctypes",
".",
"byref",
"(",
"found",
")",
")",
"r... | 30.866667 | 0.002096 |
def find_datafile(name, search_path, codecs=get_codecs()):
"""
find all matching data files in search_path
search_path: path of directories to load from
codecs: allow to override from list of installed
returns array of tuples (codec_object, filename)
"""
return munge.find_datafile(name, sear... | [
"def",
"find_datafile",
"(",
"name",
",",
"search_path",
",",
"codecs",
"=",
"get_codecs",
"(",
")",
")",
":",
"return",
"munge",
".",
"find_datafile",
"(",
"name",
",",
"search_path",
",",
"codecs",
")"
] | 41.125 | 0.002976 |
async def fetch_user(self, user_id):
"""|coro|
Retrieves a :class:`~discord.User` based on their ID. This can only
be used by bot accounts. You do not have to share any guilds
with the user to get this information, however many operations
do require that you do.
.. note... | [
"async",
"def",
"fetch_user",
"(",
"self",
",",
"user_id",
")",
":",
"data",
"=",
"await",
"self",
".",
"http",
".",
"get_user",
"(",
"user_id",
")",
"return",
"User",
"(",
"state",
"=",
"self",
".",
"_connection",
",",
"data",
"=",
"data",
")"
] | 28.129032 | 0.003326 |
def stem(self, s):
"""
Performs stemming on the string.
:param s: the string to stem
:type s: str
:return: the stemmed string
:rtype: str
"""
return javabridge.get_env().get_string(self.__stem(javabridge.get_env().new_string_utf(s))) | [
"def",
"stem",
"(",
"self",
",",
"s",
")",
":",
"return",
"javabridge",
".",
"get_env",
"(",
")",
".",
"get_string",
"(",
"self",
".",
"__stem",
"(",
"javabridge",
".",
"get_env",
"(",
")",
".",
"new_string_utf",
"(",
"s",
")",
")",
")"
] | 28.9 | 0.010067 |
def inline_transform(filename, key):
"""Encrypt file inline.
Encrypts a given file with the given key,
and replaces it directly without any extra
space requirement.
:param filename: The name of the file to encrypt.
:type filename: str
:param key: The key used to encrypt the file.
:type... | [
"def",
"inline_transform",
"(",
"filename",
",",
"key",
")",
":",
"pos",
"=",
"0",
"for",
"chunk",
",",
"fp",
"in",
"iter_transform",
"(",
"filename",
",",
"key",
")",
":",
"fp",
".",
"seek",
"(",
"pos",
")",
"fp",
".",
"write",
"(",
"chunk",
")",
... | 26.222222 | 0.002045 |
async def enable_analog_reporting(self, pin):
"""
Enables analog reporting. By turning reporting on for a single pin,
:param pin: Analog pin number. For example for A0, the number is 0.
:returns: No return value
"""
command = [PrivateConstants.REPORT_ANALOG + pin,
... | [
"async",
"def",
"enable_analog_reporting",
"(",
"self",
",",
"pin",
")",
":",
"command",
"=",
"[",
"PrivateConstants",
".",
"REPORT_ANALOG",
"+",
"pin",
",",
"PrivateConstants",
".",
"REPORTING_ENABLE",
"]",
"await",
"self",
".",
"_send_command",
"(",
"command",... | 36.363636 | 0.004878 |
def query(self,
url,
method='GET',
extra_params=None,
extra_headers=None,
retry=3,
raw=False,
stream=False):
"""
Return a JSON object or raw session.
:param url: Arlo API URL
:param method... | [
"def",
"query",
"(",
"self",
",",
"url",
",",
"method",
"=",
"'GET'",
",",
"extra_params",
"=",
"None",
",",
"extra_headers",
"=",
"None",
",",
"retry",
"=",
"3",
",",
"raw",
"=",
"False",
",",
"stream",
"=",
"False",
")",
":",
"response",
"=",
"No... | 32.954545 | 0.004018 |
def set_level(level):
"""
Set the logging level of the root handler.
:param level: The logging level to filter on (an integer or string).
If no root handler exists yet this automatically calls :func:`install()`.
"""
handler, logger = find_handler(logging.getLogger(), match_stream_handler)
... | [
"def",
"set_level",
"(",
"level",
")",
":",
"handler",
",",
"logger",
"=",
"find_handler",
"(",
"logging",
".",
"getLogger",
"(",
")",
",",
"match_stream_handler",
")",
"if",
"handler",
"and",
"logger",
":",
"# Change the level of the existing handler.",
"handler"... | 35.647059 | 0.001608 |
def note_change(self, key, value):
"""
Updates change state to reflect a change to a field. Takes care of ignoring
no-ops, reversions and takes appropriate steps if the field was previously
deleted or added to ensure the change state purely reflects the diff since
last reset.
... | [
"def",
"note_change",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"# If we're changing the value and we haven't done so already, note it.",
"if",
"value",
"!=",
"self",
".",
"_instance",
"[",
"key",
"]",
"and",
"key",
"not",
"in",
"self",
".",
"_previous",
... | 52.785714 | 0.009309 |
def metadata_filter_as_dict(metadata_config):
"""Return the metadata filter represented as either None (no filter),
or a dictionary with at most two keys: 'additional' and 'excluded',
which contain either a list of metadata names, or the string 'all'"""
if metadata_config is None:
return {}
... | [
"def",
"metadata_filter_as_dict",
"(",
"metadata_config",
")",
":",
"if",
"metadata_config",
"is",
"None",
":",
"return",
"{",
"}",
"if",
"metadata_config",
"is",
"True",
":",
"return",
"{",
"'additional'",
":",
"'all'",
"}",
"if",
"metadata_config",
"is",
"Fa... | 33.184211 | 0.002311 |
def discovery_mdns(self):
"""
Installs the mDNS discovery bundles and instantiates components
"""
# Remove Zeroconf debug output
logging.getLogger("zeroconf").setLevel(logging.WARNING)
# Install the bundle
self.context.install_bundle("pelix.remote.discovery.mdns"... | [
"def",
"discovery_mdns",
"(",
"self",
")",
":",
"# Remove Zeroconf debug output",
"logging",
".",
"getLogger",
"(",
"\"zeroconf\"",
")",
".",
"setLevel",
"(",
"logging",
".",
"WARNING",
")",
"# Install the bundle",
"self",
".",
"context",
".",
"install_bundle",
"(... | 37.923077 | 0.005941 |
def apply_grad(fun, grad):
"""
Apply a function that takes a gradient matrix to a sequence of 2 or 3
dimensional gradients.
This is partucularly useful when the gradient of a basis concatenation
object is quite complex, eg.
>>> X = np.random.randn(100, 3)
>>> y = np.random.randn(100)
>... | [
"def",
"apply_grad",
"(",
"fun",
",",
"grad",
")",
":",
"if",
"issequence",
"(",
"grad",
")",
":",
"fgrad",
"=",
"[",
"apply_grad",
"(",
"fun",
",",
"g",
")",
"for",
"g",
"in",
"grad",
"]",
"return",
"fgrad",
"if",
"len",
"(",
"fgrad",
")",
"!=",... | 31.772727 | 0.000694 |
def lzwdecode(data):
"""
>>> lzwdecode(b'\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01')
'\x2d\x2d\x2d\x2d\x2d\x41\x2d\x2d\x2d\x42'
"""
fp = BytesIO(data)
return b''.join(LZWDecoder(fp).run()) | [
"def",
"lzwdecode",
"(",
"data",
")",
":",
"fp",
"=",
"BytesIO",
"(",
"data",
")",
"return",
"b''",
".",
"join",
"(",
"LZWDecoder",
"(",
"fp",
")",
".",
"run",
"(",
")",
")"
] | 28.714286 | 0.004831 |
def merge(self, config):
""" Load configuration from given configuration.
:param config: config to load. If config is a string type, then it's treated as .ini filename
:return: None
"""
if isinstance(config, ConfigParser) is True:
self.update(config)
elif isinstance(config, str):
self.read(config) | [
"def",
"merge",
"(",
"self",
",",
"config",
")",
":",
"if",
"isinstance",
"(",
"config",
",",
"ConfigParser",
")",
"is",
"True",
":",
"self",
".",
"update",
"(",
"config",
")",
"elif",
"isinstance",
"(",
"config",
",",
"str",
")",
":",
"self",
".",
... | 30.8 | 0.0347 |
def request_update(self):
"""Flags metadata for update, return Future()
Actual update must be handled separately. This method will only
change the reported ttl()
Returns:
kafka.future.Future (value will be the cluster object after update)
"""
with self._lock... | [
"def",
"request_update",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"_need_update",
"=",
"True",
"if",
"not",
"self",
".",
"_future",
"or",
"self",
".",
"_future",
".",
"is_done",
":",
"self",
".",
"_future",
"=",
"Future",
... | 33.714286 | 0.006186 |
def get_system_info(self, x=255, y=255):
"""Discover the integrity and resource availability of a whole
SpiNNaker system.
This command performs :py:meth:`.get_chip_info` on all working chips in
the system returning an enhanced :py:class:`dict`
(:py:class:`.SystemInfo`) containin... | [
"def",
"get_system_info",
"(",
"self",
",",
"x",
"=",
"255",
",",
"y",
"=",
"255",
")",
":",
"# A quick way of getting a list of working chips",
"p2p_tables",
"=",
"self",
".",
"get_p2p_routing_table",
"(",
"x",
",",
"y",
")",
"# Calculate the extent of the system",... | 41.933333 | 0.000777 |
def override_template(template, content_type=None):
'''
Call within a controller to override the template that is used in
your response.
:param template: a valid path to a template file, just as you would specify
in an ``@expose``.
:param content_type: a valid MIME type to use ... | [
"def",
"override_template",
"(",
"template",
",",
"content_type",
"=",
"None",
")",
":",
"request",
".",
"pecan",
"[",
"'override_template'",
"]",
"=",
"template",
"if",
"content_type",
":",
"request",
".",
"pecan",
"[",
"'override_content_type'",
"]",
"=",
"c... | 36.846154 | 0.002037 |
def create_environment(self, env_name, version_label=None,
solution_stack_name=None, cname_prefix=None, description=None,
option_settings=None, tier_name='WebServer', tier_type='Standard', tier_version='1.1'):
"""
Creates a new environment
""... | [
"def",
"create_environment",
"(",
"self",
",",
"env_name",
",",
"version_label",
"=",
"None",
",",
"solution_stack_name",
"=",
"None",
",",
"cname_prefix",
"=",
"None",
",",
"description",
"=",
"None",
",",
"option_settings",
"=",
"None",
",",
"tier_name",
"="... | 62.5625 | 0.00689 |
def get_labels(self):
"""
:calls: `GET /repos/:owner/:repo/issues/:number/labels <http://developer.github.com/v3/issues/labels>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Label.Label`
"""
return github.PaginatedList.PaginatedList(
github.L... | [
"def",
"get_labels",
"(",
"self",
")",
":",
"return",
"github",
".",
"PaginatedList",
".",
"PaginatedList",
"(",
"github",
".",
"Label",
".",
"Label",
",",
"self",
".",
"_requester",
",",
"self",
".",
"issue_url",
"+",
"\"/labels\"",
",",
"None",
")"
] | 37.909091 | 0.009368 |
def _doc_property(klass, prop):
"""Generate the docstring of a property."""
header = "{klass}.{name}".format(klass=klass.__name__,
name=_name(prop),
)
docstring = _doc(prop)
return _concat(header, docstring) | [
"def",
"_doc_property",
"(",
"klass",
",",
"prop",
")",
":",
"header",
"=",
"\"{klass}.{name}\"",
".",
"format",
"(",
"klass",
"=",
"klass",
".",
"__name__",
",",
"name",
"=",
"_name",
"(",
"prop",
")",
",",
")",
"docstring",
"=",
"_doc",
"(",
"prop",
... | 42.142857 | 0.009967 |
def _find_by_name(tree_data, name, is_dir, start_at):
"""return data entry matching the given name and tree mode
or None.
Before the item is returned, the respective data item is set
None in the tree_data list to mark it done"""
try:
item = tree_data[start_at]
if item and item[2] == ... | [
"def",
"_find_by_name",
"(",
"tree_data",
",",
"name",
",",
"is_dir",
",",
"start_at",
")",
":",
"try",
":",
"item",
"=",
"tree_data",
"[",
"start_at",
"]",
"if",
"item",
"and",
"item",
"[",
"2",
"]",
"==",
"name",
"and",
"S_ISDIR",
"(",
"item",
"[",... | 35.4 | 0.001376 |
def get_mdf_robot(self):
"""Builds and returns a :class:`MdfRobot` for analyzing the results in the MDF files."""
from abilab.robots import MdfRobot
robot = MdfRobot()
for task in self[2:]:
mdf_path = task.outdir.has_abiext(robot.EXT)
if mdf_path:
... | [
"def",
"get_mdf_robot",
"(",
"self",
")",
":",
"from",
"abilab",
".",
"robots",
"import",
"MdfRobot",
"robot",
"=",
"MdfRobot",
"(",
")",
"for",
"task",
"in",
"self",
"[",
"2",
":",
"]",
":",
"mdf_path",
"=",
"task",
".",
"outdir",
".",
"has_abiext",
... | 40.888889 | 0.007979 |
def similar(obj1, obj2):
"""Calculate similarity between two (Comparable) objects."""
Comparable.log(obj1, obj2, '%')
similarity = obj1.similarity(obj2)
Comparable.log(obj1, obj2, '%', result=similarity)
return similarity | [
"def",
"similar",
"(",
"obj1",
",",
"obj2",
")",
":",
"Comparable",
".",
"log",
"(",
"obj1",
",",
"obj2",
",",
"'%'",
")",
"similarity",
"=",
"obj1",
".",
"similarity",
"(",
"obj2",
")",
"Comparable",
".",
"log",
"(",
"obj1",
",",
"obj2",
",",
"'%'... | 39.333333 | 0.004149 |
def __period_remaining(self):
'''
Return the period remaining for the current rate limit window.
:return: The remaing period.
:rtype: float
'''
elapsed = self.clock() - self.last_reset
return self.period - elapsed | [
"def",
"__period_remaining",
"(",
"self",
")",
":",
"elapsed",
"=",
"self",
".",
"clock",
"(",
")",
"-",
"self",
".",
"last_reset",
"return",
"self",
".",
"period",
"-",
"elapsed"
] | 29.111111 | 0.007407 |
def run_count(bam_file, dexseq_gff, stranded, out_file, data):
"""
run dexseq_count on a BAM file
"""
assert file_exists(bam_file), "%s does not exist." % bam_file
sort_order = bam._get_sort_order(bam_file, {})
assert sort_order, "Cannot determine sort order of %s." % bam_file
strand_flag = ... | [
"def",
"run_count",
"(",
"bam_file",
",",
"dexseq_gff",
",",
"stranded",
",",
"out_file",
",",
"data",
")",
":",
"assert",
"file_exists",
"(",
"bam_file",
")",
",",
"\"%s does not exist.\"",
"%",
"bam_file",
"sort_order",
"=",
"bam",
".",
"_get_sort_order",
"(... | 40.948718 | 0.003058 |
def tag_labels(self):
"""Tag named entity labels in the ``words`` layer."""
if not self.is_tagged(ANALYSIS):
self.tag_analysis()
if self.__ner_tagger is None:
self.__ner_tagger = load_default_ner_tagger()
self.__ner_tagger.tag_document(self)
return self | [
"def",
"tag_labels",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"ANALYSIS",
")",
":",
"self",
".",
"tag_analysis",
"(",
")",
"if",
"self",
".",
"__ner_tagger",
"is",
"None",
":",
"self",
".",
"__ner_tagger",
"=",
"load_default_ner... | 38.75 | 0.006309 |
def validate(self, vat_deets):
"""Validates an existing VAT identification number against VIES."""
request = self._get('validation', vat_deets)
return self.responder(request) | [
"def",
"validate",
"(",
"self",
",",
"vat_deets",
")",
":",
"request",
"=",
"self",
".",
"_get",
"(",
"'validation'",
",",
"vat_deets",
")",
"return",
"self",
".",
"responder",
"(",
"request",
")"
] | 48.75 | 0.010101 |
def _serialize(self, entity, pb, prefix='', parent_repeated=False,
projection=None):
"""Internal helper to serialize this property to a protocol buffer.
Subclasses may override this method.
Args:
entity: The entity, a Model (subclass) instance.
pb: The protocol buffer, an Enti... | [
"def",
"_serialize",
"(",
"self",
",",
"entity",
",",
"pb",
",",
"prefix",
"=",
"''",
",",
"parent_repeated",
"=",
"False",
",",
"projection",
"=",
"None",
")",
":",
"values",
"=",
"self",
".",
"_get_base_value_unwrapped_as_list",
"(",
"entity",
")",
"name... | 36.921569 | 0.009312 |
def __write_divider(self, top=False, bot=False, nl=True):
"""
Write a divider line
:return none:
"""
if top:
self.noaa_txt += "\n#"
if nl:
self.noaa_txt += "\n"
self.noaa_txt += "#------------------\n"
if bot:
self.noaa_... | [
"def",
"__write_divider",
"(",
"self",
",",
"top",
"=",
"False",
",",
"bot",
"=",
"False",
",",
"nl",
"=",
"True",
")",
":",
"if",
"top",
":",
"self",
".",
"noaa_txt",
"+=",
"\"\\n#\"",
"if",
"nl",
":",
"self",
".",
"noaa_txt",
"+=",
"\"\\n\"",
"se... | 25.769231 | 0.005764 |
def run(self):
""" Called by the thread, it runs the process.
NEVER call this method directly. Instead call start() to start the thread.
To stop, call stop(), and then join()
"""
if self._live:
self._use_process = True
self._abort = False
campfire ... | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"_live",
":",
"self",
".",
"_use_process",
"=",
"True",
"self",
".",
"_abort",
"=",
"False",
"campfire",
"=",
"self",
".",
"_room",
".",
"get_campfire",
"(",
")",
"if",
"self",
".",
"_live",
"... | 31.650794 | 0.003405 |
def add_inspire_categories(self, subject_terms, source=None):
"""Add inspire categories.
:param subject_terms: user categories for the current document.
:type subject_terms: list
:param source: source for the given categories.
:type source: string
"""
for catego... | [
"def",
"add_inspire_categories",
"(",
"self",
",",
"subject_terms",
",",
"source",
"=",
"None",
")",
":",
"for",
"category",
"in",
"subject_terms",
":",
"category_dict",
"=",
"self",
".",
"_sourced_dict",
"(",
"source",
",",
"term",
"=",
"category",
",",
")"... | 33.866667 | 0.003831 |
def rpc(self, cmd, **kwargs):
"""Generic helper function to call an RPC method."""
func = getattr(self.client, cmd)
try:
if self.credentials is None:
return func(kwargs)
else:
return func(self.credentials, kwargs)
except socket.err... | [
"def",
"rpc",
"(",
"self",
",",
"cmd",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"getattr",
"(",
"self",
".",
"client",
",",
"cmd",
")",
"try",
":",
"if",
"self",
".",
"credentials",
"is",
"None",
":",
"return",
"func",
"(",
"kwargs",
")",
... | 36 | 0.003868 |
def extract_code_globals(cls, co):
"""
Find all globals names read or written to by codeblock co
"""
out_names = cls._extract_code_globals_cache.get(co)
if out_names is None:
try:
names = co.co_names
except AttributeError:
#... | [
"def",
"extract_code_globals",
"(",
"cls",
",",
"co",
")",
":",
"out_names",
"=",
"cls",
".",
"_extract_code_globals_cache",
".",
"get",
"(",
"co",
")",
"if",
"out_names",
"is",
"None",
":",
"try",
":",
"names",
"=",
"co",
".",
"co_names",
"except",
"Att... | 35.541667 | 0.003425 |
def load_tile(self, tile):
'''load a tile from cache or tile server'''
# see if its in the tile cache
key = tile.key()
if key in self._tile_cache:
img = self._tile_cache[key]
if np.array_equal(img, self._unavailable):
img = self.load_tile_lowres(t... | [
"def",
"load_tile",
"(",
"self",
",",
"tile",
")",
":",
"# see if its in the tile cache",
"key",
"=",
"tile",
".",
"key",
"(",
")",
"if",
"key",
"in",
"self",
".",
"_tile_cache",
":",
"img",
"=",
"self",
".",
"_tile_cache",
"[",
"key",
"]",
"if",
"np",... | 32.382979 | 0.003827 |
def registry_tags(self, query_string='{http://gis.harvard.edu/HHypermap/registry/0.1}property'):
"""
Get extra metadata tagged with a registry keyword.
For example:
<registry:property name="nomination/serviceOwner" value="True"/>
<registry:property name="nominator/name" v... | [
"def",
"registry_tags",
"(",
"self",
",",
"query_string",
"=",
"'{http://gis.harvard.edu/HHypermap/registry/0.1}property'",
")",
":",
"from",
"pycsw",
".",
"core",
".",
"etree",
"import",
"etree",
"parsed",
"=",
"etree",
".",
"fromstring",
"(",
"self",
".",
"xml",... | 60.121951 | 0.006387 |
def get_activity_lookup_session(self, proxy, *args, **kwargs):
"""Gets the ``OsidSession`` associated with the activity lookup service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: an ``ActivityLookupSession``
:rtype: ``osid.learning.ActivityLookupSession``
... | [
"def",
"get_activity_lookup_session",
"(",
"self",
",",
"proxy",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"supports_activity_lookup",
"(",
")",
":",
"raise",
"Unimplemented",
"(",
")",
"try",
":",
"from",
".",
"impor... | 40.538462 | 0.005561 |
def get_instance(self, payload):
"""
Build an instance of MemberInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.queue.member.MemberInstance
:rtype: twilio.rest.api.v2010.account.queue.member.MemberInstance
"""
... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"MemberInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"queue_sid",
"=",
"self",
".",
"_solu... | 32.8 | 0.003953 |
def charge_transfer_to_string(self):
"""returns shrage transfer as string"""
ch = self.charge_transfer
chts = ['\nCharge Transfer\n\nabsorbing atom']
for i in range(len(ch)):
for atom, v2 in ch[str(i)].items():
a = ['\n', atom, '\n', 's ', str(v2['s']), '\n'... | [
"def",
"charge_transfer_to_string",
"(",
"self",
")",
":",
"ch",
"=",
"self",
".",
"charge_transfer",
"chts",
"=",
"[",
"'\\nCharge Transfer\\n\\nabsorbing atom'",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"ch",
")",
")",
":",
"for",
"atom",
",",
"v... | 43.615385 | 0.003454 |
def find_bump(target, tag):
"""Identify the kind of release by comparing to existing ones."""
tmp = tag.split(".")
existing = [intify(basename(f)) for f in glob(join(target, "[0-9]*.md"))]
latest = max(existing)
if int(tmp[0]) > latest[0]:
return "major"
elif int(tmp[1]) > latest[1]:
... | [
"def",
"find_bump",
"(",
"target",
",",
"tag",
")",
":",
"tmp",
"=",
"tag",
".",
"split",
"(",
"\".\"",
")",
"existing",
"=",
"[",
"intify",
"(",
"basename",
"(",
"f",
")",
")",
"for",
"f",
"in",
"glob",
"(",
"join",
"(",
"target",
",",
"\"[0-9]*... | 32.909091 | 0.002688 |
def files_comments_add(self, *, comment: str, file: str, **kwargs) -> SlackResponse:
"""Add a comment to an existing file.
Args:
comment (str): The body of the comment.
e.g. 'Everyone should take a moment to read this file.'
file (str): The file id. e.g. 'F123446... | [
"def",
"files_comments_add",
"(",
"self",
",",
"*",
",",
"comment",
":",
"str",
",",
"file",
":",
"str",
",",
"*",
"*",
"kwargs",
")",
"->",
"SlackResponse",
":",
"kwargs",
".",
"update",
"(",
"{",
"\"comment\"",
":",
"comment",
",",
"\"file\"",
":",
... | 45 | 0.006536 |
def check_shutdown_flag(self):
"""Shutdown the server if the flag has been set"""
if self.shutdown_requested:
tornado.ioloop.IOLoop.instance().stop()
print("web server stopped.") | [
"def",
"check_shutdown_flag",
"(",
"self",
")",
":",
"if",
"self",
".",
"shutdown_requested",
":",
"tornado",
".",
"ioloop",
".",
"IOLoop",
".",
"instance",
"(",
")",
".",
"stop",
"(",
")",
"print",
"(",
"\"web server stopped.\"",
")"
] | 42.8 | 0.009174 |
def _parse(self):
""" Parse content of DCH file
"""
cur_ver = None
cur_line = None
for line in self.content:
m = re.match('[^ ]+ \(([0-9]+\.[0-9]+\.[0-9]+)-[0-9]+\) [^ ]+; urgency=[^ ]+', line)
if m:
cur_ver = m.group(1)
sel... | [
"def",
"_parse",
"(",
"self",
")",
":",
"cur_ver",
"=",
"None",
"cur_line",
"=",
"None",
"for",
"line",
"in",
"self",
".",
"content",
":",
"m",
"=",
"re",
".",
"match",
"(",
"'[^ ]+ \\(([0-9]+\\.[0-9]+\\.[0-9]+)-[0-9]+\\) [^ ]+; urgency=[^ ]+'",
",",
"line",
"... | 43.45 | 0.010135 |
def from_dict(cls, d):
"""
Decode from a dictionary as from :meth:`to_dict`.
"""
return cls(
d['id'],
d['start'],
d['end'],
Lnk.charspan(d['from'], d['to']) if 'from' in d else None,
# d.get('paths', [1]),
form=d['fo... | [
"def",
"from_dict",
"(",
"cls",
",",
"d",
")",
":",
"return",
"cls",
"(",
"d",
"[",
"'id'",
"]",
",",
"d",
"[",
"'start'",
"]",
",",
"d",
"[",
"'end'",
"]",
",",
"Lnk",
".",
"charspan",
"(",
"d",
"[",
"'from'",
"]",
",",
"d",
"[",
"'to'",
"... | 29.1875 | 0.004149 |
def mutate_stream (instream, outstream):
"""Python 3 compat note: we're assuming `stream` gives bytes not unicode."""
chunk = None
key = None
data = None
misclines = []
for fullline in instream:
line = fullline.split ('#', 1)[0]
m = sectionre.match (line)
if m is not N... | [
"def",
"mutate_stream",
"(",
"instream",
",",
"outstream",
")",
":",
"chunk",
"=",
"None",
"key",
"=",
"None",
"data",
"=",
"None",
"misclines",
"=",
"[",
"]",
"for",
"fullline",
"in",
"instream",
":",
"line",
"=",
"fullline",
".",
"split",
"(",
"'#'",... | 32.519481 | 0.019767 |
def _format_table(fmt, headers, rows, colwidths, colaligns):
"""Produce a plain-text representation of the table."""
lines = []
hidden = fmt.with_header_hide if (headers and fmt.with_header_hide) else []
pad = fmt.padding
headerrow = fmt.headerrow
padded_widths = [(w + 2*pad) for w in colwidths... | [
"def",
"_format_table",
"(",
"fmt",
",",
"headers",
",",
"rows",
",",
"colwidths",
",",
"colaligns",
")",
":",
"lines",
"=",
"[",
"]",
"hidden",
"=",
"fmt",
".",
"with_header_hide",
"if",
"(",
"headers",
"and",
"fmt",
".",
"with_header_hide",
")",
"else"... | 44.588235 | 0.004519 |
def format(collection, **params):
"""Truns a frozen sample into a TAR file."""
binary = io.BytesIO()
with tarfile.TarFile(fileobj=binary, mode='w') as tar:
mode = params.get('mode', 0o640)
now = calendar.timegm(datetime.datetime.utcnow().timetuple())
for filename, content in collecti... | [
"def",
"format",
"(",
"collection",
",",
"*",
"*",
"params",
")",
":",
"binary",
"=",
"io",
".",
"BytesIO",
"(",
")",
"with",
"tarfile",
".",
"TarFile",
"(",
"fileobj",
"=",
"binary",
",",
"mode",
"=",
"'w'",
")",
"as",
"tar",
":",
"mode",
"=",
"... | 46.555556 | 0.00117 |
def impute(self, column=-1, method="mean", combine_method="interpolate", by=None, group_by_frame=None, values=None):
"""
Impute missing values into the frame, modifying it in-place.
:param int column: Index of the column to impute, or -1 to impute the entire frame.
:param str method: Th... | [
"def",
"impute",
"(",
"self",
",",
"column",
"=",
"-",
"1",
",",
"method",
"=",
"\"mean\"",
",",
"combine_method",
"=",
"\"interpolate\"",
",",
"by",
"=",
"None",
",",
"group_by_frame",
"=",
"None",
",",
"values",
"=",
"None",
")",
":",
"if",
"is_type"... | 51.607843 | 0.008203 |
def draw_identity_line(ax=None, dynamic=True, **kwargs):
"""
Draws a 45 degree identity line such that y=x for all points within the
given axes x and y limits. This function also registeres a callback so
that as the figure is modified, the axes are updated and the line remains
drawn correctly.
... | [
"def",
"draw_identity_line",
"(",
"ax",
"=",
"None",
",",
"dynamic",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get the current working axes",
"ax",
"=",
"ax",
"or",
"plt",
".",
"gca",
"(",
")",
"# Define the standard line color",
"if",
"'c'",
"not",... | 28.550725 | 0.001472 |
def configure(self, options, conf):
"""Configure plugin.
"""
self.conf = conf
# Disable if explicitly disabled, or if logging is
# configured via logging config file
if not options.logcapture or conf.loggingConfig:
self.enabled = False
self.logformat =... | [
"def",
"configure",
"(",
"self",
",",
"options",
",",
"conf",
")",
":",
"self",
".",
"conf",
"=",
"conf",
"# Disable if explicitly disabled, or if logging is",
"# configured via logging config file",
"if",
"not",
"options",
".",
"logcapture",
"or",
"conf",
".",
"log... | 41.785714 | 0.003344 |
def modify(self, monitor_id, options):
"""Create a monitor using passed configuration."""
if not self._state:
raise InvalidState("State was not properly obtained from the app")
monitors = self.list() # Get the latest set of monitors
obj = None
for monitor in monitors... | [
"def",
"modify",
"(",
"self",
",",
"monitor_id",
",",
"options",
")",
":",
"if",
"not",
"self",
".",
"_state",
":",
"raise",
"InvalidState",
"(",
"\"State was not properly obtained from the app\"",
")",
"monitors",
"=",
"self",
".",
"list",
"(",
")",
"# Get th... | 45.958333 | 0.001776 |
def __build_sequence(parts):
"""Build a sequence object using the pre-tokenized parts from a MAF line.
s -- a sequence line; has 6 fields in addition to 's':
* source sequence,
* start coord. of seq., zero-based. If -'ve strand, rel to start of
rev. comp.
* ungapped length... | [
"def",
"__build_sequence",
"(",
"parts",
")",
":",
"strand",
"=",
"parts",
"[",
"4",
"]",
"seq_length",
"=",
"int",
"(",
"parts",
"[",
"3",
"]",
")",
"total_seq_len",
"=",
"int",
"(",
"parts",
"[",
"5",
"]",
")",
"start",
"=",
"(",
"int",
"(",
"p... | 37.2 | 0.011796 |
def plotConvergenceByColumnTopology(results, columnRange, featureRange, networkType, numTrials):
"""
Plots the convergence graph: iterations vs number of columns.
Each curve shows the convergence for a given number of unique features.
"""
#######################################################################... | [
"def",
"plotConvergenceByColumnTopology",
"(",
"results",
",",
"columnRange",
",",
"featureRange",
",",
"networkType",
",",
"numTrials",
")",
":",
"########################################################################",
"#",
"# Accumulate all the results per column in a convergenc... | 34.738462 | 0.022825 |
def get_scopes(self, vpnid='.*'):
"""Returns a list of all the scopes from CPNR server."""
request_url = self._build_url(['Scope'], vpn=vpnid)
return self._do_request('GET', request_url) | [
"def",
"get_scopes",
"(",
"self",
",",
"vpnid",
"=",
"'.*'",
")",
":",
"request_url",
"=",
"self",
".",
"_build_url",
"(",
"[",
"'Scope'",
"]",
",",
"vpn",
"=",
"vpnid",
")",
"return",
"self",
".",
"_do_request",
"(",
"'GET'",
",",
"request_url",
")"
] | 51.75 | 0.009524 |
def _format_row(headers, row):
"""Format a row."""
formatted_row = [' | '.join(field) for field in zip(headers, row)]
return '\n'.join(formatted_row) | [
"def",
"_format_row",
"(",
"headers",
",",
"row",
")",
":",
"formatted_row",
"=",
"[",
"' | '",
".",
"join",
"(",
"field",
")",
"for",
"field",
"in",
"zip",
"(",
"headers",
",",
"row",
")",
"]",
"return",
"'\\n'",
".",
"join",
"(",
"formatted_row",
"... | 39.5 | 0.006211 |
def filter(self, value):
""" Register function to filters. """
if self.env is None:
raise PluginException('The plugin must be installed to application.')
def wrapper(func):
name = func.__name__
if isinstance(value, str):
name = value
... | [
"def",
"filter",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"env",
"is",
"None",
":",
"raise",
"PluginException",
"(",
"'The plugin must be installed to application.'",
")",
"def",
"wrapper",
"(",
"func",
")",
":",
"name",
"=",
"func",
".",
"_... | 28.352941 | 0.006024 |
def _reduce_nbest_translations(nbest_translations_list: List[Translation]) -> Translation:
"""
Combines Translation objects that are nbest translations of the same sentence.
:param nbest_translations_list: A list of Translation objects, all of them translations of
the same source sentence.
:ret... | [
"def",
"_reduce_nbest_translations",
"(",
"nbest_translations_list",
":",
"List",
"[",
"Translation",
"]",
")",
"->",
"Translation",
":",
"best_translation",
"=",
"nbest_translations_list",
"[",
"0",
"]",
"sequences",
"=",
"[",
"translation",
".",
"target_ids",
"for... | 49.545455 | 0.006301 |
def _replace_missing_values_column(values, mv):
"""
Replace missing values in the values list where applicable
:param list values: Metadata (column values)
:return list values: Metadata (column values)
"""
for idx, v in enumerate(values):
try:
if v in EMPTY or v == mv:
... | [
"def",
"_replace_missing_values_column",
"(",
"values",
",",
"mv",
")",
":",
"for",
"idx",
",",
"v",
"in",
"enumerate",
"(",
"values",
")",
":",
"try",
":",
"if",
"v",
"in",
"EMPTY",
"or",
"v",
"==",
"mv",
":",
"values",
"[",
"idx",
"]",
"=",
"\"na... | 28.631579 | 0.001779 |
def grid(fitness_function, no_dimensions, step_size):
"""
Grid search using a fitness function over a given number of dimensions and a given step size between inclusive
limits of 0 and 1.
Parameters
----------
fitness_function: function
A function that takes a tuple of floats as an argu... | [
"def",
"grid",
"(",
"fitness_function",
",",
"no_dimensions",
",",
"step_size",
")",
":",
"best_fitness",
"=",
"float",
"(",
"\"-inf\"",
")",
"best_arguments",
"=",
"None",
"for",
"arguments",
"in",
"make_lists",
"(",
"no_dimensions",
",",
"step_size",
")",
":... | 30.172414 | 0.002215 |
def AddSignatureToRPMs(self, rpm_filenames):
"""Sign RPM with rpmsign."""
# The horrible second argument here is necessary to get a V3 signature to
# support CentOS 5 systems. See:
# http://ilostmynotes.blogspot.com/2016/03/the-horror-of-signing-rpms-that-support.html
args = [
"--define=%%_g... | [
"def",
"AddSignatureToRPMs",
"(",
"self",
",",
"rpm_filenames",
")",
":",
"# The horrible second argument here is necessary to get a V3 signature to",
"# support CentOS 5 systems. See:",
"# http://ilostmynotes.blogspot.com/2016/03/the-horror-of-signing-rpms-that-support.html",
"args",
"=",
... | 45.289474 | 0.00967 |
def clear_flag(flag):
"""
Clear / deactivate a flag.
:param str flag: Name of flag to set.
.. note:: **Changes to flags are reset when a handler crashes.** Changes to
flags happen immediately, but they are only persisted at the end of a
complete and successful run of the reactive framewo... | [
"def",
"clear_flag",
"(",
"flag",
")",
":",
"old_flags",
"=",
"get_flags",
"(",
")",
"unitdata",
".",
"kv",
"(",
")",
".",
"unset",
"(",
"'reactive.states.%s'",
"%",
"flag",
")",
"unitdata",
".",
"kv",
"(",
")",
".",
"set",
"(",
"'reactive.dispatch.remov... | 37 | 0.001198 |
def get_sites_in_sphere(self, pt, r):
"""
Find all sites within a sphere from a point.
Args:
pt (3x1 array): Cartesian coordinates of center of sphere.
r (float): Radius of sphere.
Returns:
[(site, dist) ...] since most of the time, subsequent proces... | [
"def",
"get_sites_in_sphere",
"(",
"self",
",",
"pt",
",",
"r",
")",
":",
"neighbors",
"=",
"[",
"]",
"for",
"site",
"in",
"self",
".",
"_sites",
":",
"dist",
"=",
"site",
".",
"distance_from_point",
"(",
"pt",
")",
"if",
"dist",
"<=",
"r",
":",
"n... | 30.888889 | 0.00349 |
def send_packet(self, packet, queue=True):
"""Sends a RTMP packet to the server.
:param packet: RTMPPacket, the packet to send to the server.
:param queue: bool, If True, queue up the packet in a internal queue rather
than sending it right away.
"""
if no... | [
"def",
"send_packet",
"(",
"self",
",",
"packet",
",",
"queue",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"packet",
",",
"RTMPPacket",
")",
":",
"raise",
"ValueError",
"(",
"\"A RTMPPacket argument is required\"",
")",
"return",
"librtmp",
".",
... | 37.357143 | 0.005597 |
def ListRecursivelyViaWalking(top):
"""Walks a directory tree, yielding (dir_path, file_paths) tuples.
For each of `top` and its subdirectories, yields a tuple containing the path
to the directory and the path to each of the contained files. Note that
unlike os.Walk()/tf.io.gfile.walk()/ListRecursivelyViaGlob... | [
"def",
"ListRecursivelyViaWalking",
"(",
"top",
")",
":",
"for",
"dir_path",
",",
"_",
",",
"filenames",
"in",
"tf",
".",
"io",
".",
"gfile",
".",
"walk",
"(",
"top",
",",
"topdown",
"=",
"True",
")",
":",
"yield",
"(",
"dir_path",
",",
"(",
"os",
... | 39.55 | 0.003704 |
def bootstrap_results(self, init_state):
"""Returns an object with the same type as returned by `one_step`.
Args:
init_state: `Tensor` or Python `list` of `Tensor`s representing the
initial state(s) of the Markov chain(s).
Returns:
kernel_results: A (possibly nested) `tuple`, `namedtup... | [
"def",
"bootstrap_results",
"(",
"self",
",",
"init_state",
")",
":",
"with",
"tf",
".",
"compat",
".",
"v1",
".",
"name_scope",
"(",
"name",
"=",
"mcmc_util",
".",
"make_name",
"(",
"self",
".",
"name",
",",
"'mh'",
",",
"'bootstrap_results'",
")",
",",... | 37 | 0.005098 |
def get_objective_form_for_create(self, objective_record_types=None):
"""Gets the objective form for creating new objectives.
A new form should be requested for each create transaction.
arg: objectiveRecordTypes (osid.type.Type): array of
objective record types
return:... | [
"def",
"get_objective_form_for_create",
"(",
"self",
",",
"objective_record_types",
"=",
"None",
")",
":",
"if",
"objective_record_types",
"is",
"None",
":",
"pass",
"# Still need to deal with the record_types argument",
"objective_form",
"=",
"objects",
".",
"ObjectiveForm... | 51 | 0.002026 |
def logging_syslog_facility_local(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logging = ET.SubElement(config, "logging", xmlns="urn:brocade.com:mgmt:brocade-ras")
syslog_facility = ET.SubElement(logging, "syslog-facility")
local = ET.SubEleme... | [
"def",
"logging_syslog_facility_local",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"logging",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"logging\"",
",",
"xmlns",
"=",
"\"urn:broca... | 42.727273 | 0.00625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.