text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def quarter(dt):
"""
Return start/stop datetime for the quarter as defined by dt.
"""
quarters = rrule.rrule(
rrule.MONTHLY,
bymonth = (1, 4, 7, 10),
bysetpos = -1,
dtstart = datetime(dt.year, 1, 1),
count = 8
)
first_day = quarters.before(dt, True)
last_da... | [
"def",
"quarter",
"(",
"dt",
")",
":",
"quarters",
"=",
"rrule",
".",
"rrule",
"(",
"rrule",
".",
"MONTHLY",
",",
"bymonth",
"=",
"(",
"1",
",",
"4",
",",
"7",
",",
"10",
")",
",",
"bysetpos",
"=",
"-",
"1",
",",
"dtstart",
"=",
"datetime",
"("... | 28.571429 | 0.021792 |
def find_completions_at_cursor(ast_tree, filename, line, col, root_env=gcl.default_env):
"""Find completions at the cursor.
Return a dict of { name => Completion } objects.
"""
q = gcl.SourceQuery(filename, line, col - 1)
rootpath = ast_tree.find_tokens(q)
if is_identifier_position(rootpath):
return f... | [
"def",
"find_completions_at_cursor",
"(",
"ast_tree",
",",
"filename",
",",
"line",
",",
"col",
",",
"root_env",
"=",
"gcl",
".",
"default_env",
")",
":",
"q",
"=",
"gcl",
".",
"SourceQuery",
"(",
"filename",
",",
"line",
",",
"col",
"-",
"1",
")",
"ro... | 34.722222 | 0.014019 |
def wait(objects, count=None, timeout=None):
"""Wait for one or more waitable objects.
This method waits until *count* elements from the sequence of waitable
objects *objects* have become ready. If *count* is ``None`` (the default),
then wait for all objects to become ready.
What "ready" is means ... | [
"def",
"wait",
"(",
"objects",
",",
"count",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"for",
"obj",
"in",
"objects",
":",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'add_done_callback'",
")",
":",
"raise",
"TypeError",
"(",
"'Expecting sequence... | 39.571429 | 0.001409 |
def load_yaml(fname):
"""Load a YAML file."""
yaml = YAML(typ="safe")
# Compat with HASS
yaml.allow_duplicate_keys = True
# Stub HASS constructors
HassSafeConstructor.name = fname
yaml.Constructor = HassSafeConstructor
with open(fname, encoding="utf-8") as conf_file:
# If config... | [
"def",
"load_yaml",
"(",
"fname",
")",
":",
"yaml",
"=",
"YAML",
"(",
"typ",
"=",
"\"safe\"",
")",
"# Compat with HASS",
"yaml",
".",
"allow_duplicate_keys",
"=",
"True",
"# Stub HASS constructors",
"HassSafeConstructor",
".",
"name",
"=",
"fname",
"yaml",
".",
... | 33.230769 | 0.002252 |
def _noise_dict_update(noise_dict):
"""
Update the noise dictionary parameters with default values, in case any
were missing
Parameters
----------
noise_dict : dict
A dictionary specifying the types of noise in this experiment. The
noise types interact in important ways. First,... | [
"def",
"_noise_dict_update",
"(",
"noise_dict",
")",
":",
"# Create the default dictionary",
"default_dict",
"=",
"{",
"'task_sigma'",
":",
"0",
",",
"'drift_sigma'",
":",
"0",
",",
"'auto_reg_sigma'",
":",
"1",
",",
"'auto_reg_rho'",
":",
"[",
"0.5",
"]",
",",
... | 41.292308 | 0.000364 |
def _add_sbi_id(self, sbi_id):
"""Add a SBI Identifier."""
sbi_ids = self.sbi_ids
sbi_ids.append(sbi_id)
DB.set_hash_value(self._key, 'sbi_ids', sbi_ids) | [
"def",
"_add_sbi_id",
"(",
"self",
",",
"sbi_id",
")",
":",
"sbi_ids",
"=",
"self",
".",
"sbi_ids",
"sbi_ids",
".",
"append",
"(",
"sbi_id",
")",
"DB",
".",
"set_hash_value",
"(",
"self",
".",
"_key",
",",
"'sbi_ids'",
",",
"sbi_ids",
")"
] | 36.2 | 0.010811 |
def get_strings(self):
"""
Yields all StringAnalysis for all unique Analysis objects
"""
seen = []
for digest, dx in self.analyzed_vms.items():
if dx in seen:
continue
seen.append(dx)
yield digest, self.analyzed_digest[digest], ... | [
"def",
"get_strings",
"(",
"self",
")",
":",
"seen",
"=",
"[",
"]",
"for",
"digest",
",",
"dx",
"in",
"self",
".",
"analyzed_vms",
".",
"items",
"(",
")",
":",
"if",
"dx",
"in",
"seen",
":",
"continue",
"seen",
".",
"append",
"(",
"dx",
")",
"yie... | 33.6 | 0.008696 |
def save_modules():
"""
Context in which imported modules are saved.
Translates exceptions internal to the context into the equivalent exception
outside the context.
"""
saved = sys.modules.copy()
with ExceptionSaver() as saved_exc:
yield saved
sys.modules.update(saved)
# r... | [
"def",
"save_modules",
"(",
")",
":",
"saved",
"=",
"sys",
".",
"modules",
".",
"copy",
"(",
")",
"with",
"ExceptionSaver",
"(",
")",
"as",
"saved_exc",
":",
"yield",
"saved",
"sys",
".",
"modules",
".",
"update",
"(",
"saved",
")",
"# remove any modules... | 26.863636 | 0.001634 |
def get_ruptures_within(dstore, bbox):
"""
Extract the ruptures within the given bounding box, a string
minlon,minlat,maxlon,maxlat.
Example:
http://127.0.0.1:8800/v1/calc/30/extract/ruptures_with/8,44,10,46
"""
minlon, minlat, maxlon, maxlat = map(float, bbox.split(','))
hypo = dstore['... | [
"def",
"get_ruptures_within",
"(",
"dstore",
",",
"bbox",
")",
":",
"minlon",
",",
"minlat",
",",
"maxlon",
",",
"maxlat",
"=",
"map",
"(",
"float",
",",
"bbox",
".",
"split",
"(",
"','",
")",
")",
"hypo",
"=",
"dstore",
"[",
"'ruptures'",
"]",
"[",
... | 41 | 0.001988 |
def flip(self, axis=HORIZONTAL):
"""Flips the layer, either HORIZONTAL or VERTICAL.
"""
if axis == HORIZONTAL:
self.img = self.img.transpose(Image.FLIP_LEFT_RIGHT)
if axis == VERTICAL:
self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM) | [
"def",
"flip",
"(",
"self",
",",
"axis",
"=",
"HORIZONTAL",
")",
":",
"if",
"axis",
"==",
"HORIZONTAL",
":",
"self",
".",
"img",
"=",
"self",
".",
"img",
".",
"transpose",
"(",
"Image",
".",
"FLIP_LEFT_RIGHT",
")",
"if",
"axis",
"==",
"VERTICAL",
":"... | 29.5 | 0.013158 |
def graph_memoized(func):
"""
Like memoized, but keep one cache per default graph.
"""
# TODO it keeps the graph alive
from ..compat import tfv1
GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'
@memoized
def func_with_graph_arg(*args, **kwargs):
kwargs.pop(GRAPH_ARG_NAME)
... | [
"def",
"graph_memoized",
"(",
"func",
")",
":",
"# TODO it keeps the graph alive",
"from",
".",
".",
"compat",
"import",
"tfv1",
"GRAPH_ARG_NAME",
"=",
"'__IMPOSSIBLE_NAME_FOR_YOU__'",
"@",
"memoized",
"def",
"func_with_graph_arg",
"(",
"*",
"args",
",",
"*",
"*",
... | 28.47619 | 0.001618 |
def to_raw_address(addr, section):
"""Converts the addr from a rva to a pointer to raw data in the file"""
return addr - section.header.VirtualAddress + section.header.PointerToRawData | [
"def",
"to_raw_address",
"(",
"addr",
",",
"section",
")",
":",
"return",
"addr",
"-",
"section",
".",
"header",
".",
"VirtualAddress",
"+",
"section",
".",
"header",
".",
"PointerToRawData"
] | 66 | 0.015 |
def create_epochs(self, epoch_length=30, first_second=None):
"""Create epochs in annotation file.
Parameters
----------
epoch_length : int
duration in seconds of each epoch
first_second : int, optional
Time, in seconds from record start, at which the epoch... | [
"def",
"create_epochs",
"(",
"self",
",",
"epoch_length",
"=",
"30",
",",
"first_second",
"=",
"None",
")",
":",
"lg",
".",
"info",
"(",
"'creating epochs of length '",
"+",
"str",
"(",
"epoch_length",
")",
")",
"if",
"first_second",
"is",
"None",
":",
"fi... | 37.166667 | 0.001748 |
def set( string, target_level, indent_string=" ", indent_empty_lines=False ):
""" Sets indentation of a single/multi-line string. """
lines = string.splitlines()
set_lines( lines, target_level, indent_string=indent_string, indent_empty_lines=indent_empty_lines )
result = "\n".join(lines)
r... | [
"def",
"set",
"(",
"string",
",",
"target_level",
",",
"indent_string",
"=",
"\" \"",
",",
"indent_empty_lines",
"=",
"False",
")",
":",
"lines",
"=",
"string",
".",
"splitlines",
"(",
")",
"set_lines",
"(",
"lines",
",",
"target_level",
",",
"indent_stri... | 46.571429 | 0.021084 |
def set_rd(self, vrf_name, rd):
""" Configures the VRF rd (route distinguisher)
Note: A valid RD has the following format admin_ID:local_assignment.
The admin_ID can be an AS number or globally assigned IPv4 address.
The local_assignment can be an integer between 0-65,535 if the... | [
"def",
"set_rd",
"(",
"self",
",",
"vrf_name",
",",
"rd",
")",
":",
"cmds",
"=",
"self",
".",
"command_builder",
"(",
"'rd'",
",",
"value",
"=",
"rd",
")",
"return",
"self",
".",
"configure_vrf",
"(",
"vrf_name",
",",
"cmds",
")"
] | 45.052632 | 0.002288 |
def edge_by_id(self, edge):
"""
Returns the edge that connects the head_id and tail_id nodes
"""
try:
head, tail, data = self.edges[edge]
except KeyError:
head, tail = None, None
raise GraphError('Invalid edge %s' % edge)
return (head... | [
"def",
"edge_by_id",
"(",
"self",
",",
"edge",
")",
":",
"try",
":",
"head",
",",
"tail",
",",
"data",
"=",
"self",
".",
"edges",
"[",
"edge",
"]",
"except",
"KeyError",
":",
"head",
",",
"tail",
"=",
"None",
",",
"None",
"raise",
"GraphError",
"("... | 28.818182 | 0.009174 |
def IV(abf,T1,T2,plotToo=True,color='b'):
"""
Given two time points (seconds) return IV data.
Optionally plots a fancy graph (with errorbars)
Returns [[AV],[SD]] for the given range.
"""
rangeData=abf.average_data([[T1,T2]]) #get the average data per sweep
AV,SD=rangeData[:,0,0],rangeData[:,... | [
"def",
"IV",
"(",
"abf",
",",
"T1",
",",
"T2",
",",
"plotToo",
"=",
"True",
",",
"color",
"=",
"'b'",
")",
":",
"rangeData",
"=",
"abf",
".",
"average_data",
"(",
"[",
"[",
"T1",
",",
"T2",
"]",
"]",
")",
"#get the average data per sweep",
"AV",
",... | 38.912281 | 0.03606 |
def random(args):
"""
%prog random fasta 100 > random100.fasta
Take number of records randomly from fasta
"""
from random import sample
p = OptionParser(random.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
fastafile, N = args
... | [
"def",
"random",
"(",
"args",
")",
":",
"from",
"random",
"import",
"sample",
"p",
"=",
"OptionParser",
"(",
"random",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2"... | 19.115385 | 0.001916 |
def header(self, name, data, data_type, **kwargs):
"""Serialize data intended for a request header.
:param data: The data to be serialized.
:param str data_type: The type to be serialized from.
:rtype: str
:raises: TypeError if serialization fails.
:raises: ValueError if... | [
"def",
"header",
"(",
"self",
",",
"name",
",",
"data",
",",
"data_type",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"client_side_validation",
":",
"data",
"=",
"self",
".",
"validate",
"(",
"data",
",",
"name",
",",
"required",
"=",
"True... | 38.727273 | 0.002291 |
def query_alternative_full_name():
"""
Returns list of alternative full name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative full name
default: 'Alzhe... | [
"def",
"query_alternative_full_name",
"(",
")",
":",
"args",
"=",
"get_args",
"(",
"request_args",
"=",
"request",
".",
"args",
",",
"allowed_str_args",
"=",
"[",
"'name'",
",",
"'entry_name'",
"]",
",",
"allowed_int_args",
"=",
"[",
"'limit'",
"]",
")",
"re... | 21.25641 | 0.001153 |
def addFilteringOptions(parser, samfileIsPositionalArg=False):
"""
Add options to an argument parser for filtering SAM/BAM.
@param samfileIsPositionalArg: If C{True} the SAM/BAM file must
be given as the final argument on the command line (without
being preceded by --sam... | [
"def",
"addFilteringOptions",
"(",
"parser",
",",
"samfileIsPositionalArg",
"=",
"False",
")",
":",
"parser",
".",
"add_argument",
"(",
"'%ssamfile'",
"%",
"(",
"''",
"if",
"samfileIsPositionalArg",
"else",
"'--'",
")",
",",
"required",
"=",
"True",
",",
"help... | 44.40678 | 0.000747 |
def to(self, unit):
"""Convert this distance to the given AstroPy unit."""
from astropy.units import au
return (self.au * au).to(unit) | [
"def",
"to",
"(",
"self",
",",
"unit",
")",
":",
"from",
"astropy",
".",
"units",
"import",
"au",
"return",
"(",
"self",
".",
"au",
"*",
"au",
")",
".",
"to",
"(",
"unit",
")"
] | 38.75 | 0.012658 |
def plot_turnover(returns, transactions, positions,
legend_loc='best', ax=None, **kwargs):
"""
Plots turnover vs. date.
Turnover is the number of shares traded for a period as a fraction
of total shares.
Displays daily total, daily average per month, and all-time daily
averag... | [
"def",
"plot_turnover",
"(",
"returns",
",",
"transactions",
",",
"positions",
",",
"legend_loc",
"=",
"'best'",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"y_ax... | 32.241935 | 0.000485 |
def managed(name, servers=None):
'''
Manage NTP servers
servers
A list of NTP servers
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': 'NTP servers already configured as specified'}
if not _check_servers(servers):
ret['result']... | [
"def",
"managed",
"(",
"name",
",",
"servers",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"'NTP servers already configured as specified'",
"}",
"if",
... | 29.27907 | 0.000769 |
def make_mesh( coor, ngroups, conns, mesh_in ):
"""Create a mesh reusing mat_ids and descs of mesh_in."""
mat_ids = []
for ii, conn in enumerate( conns ):
mat_id = nm.empty( (conn.shape[0],), dtype = nm.int32 )
mat_id.fill( mesh_in.mat_ids[ii][0] )
mat_ids.append( mat_id )
... | [
"def",
"make_mesh",
"(",
"coor",
",",
"ngroups",
",",
"conns",
",",
"mesh_in",
")",
":",
"mat_ids",
"=",
"[",
"]",
"for",
"ii",
",",
"conn",
"in",
"enumerate",
"(",
"conns",
")",
":",
"mat_id",
"=",
"nm",
".",
"empty",
"(",
"(",
"conn",
".",
"sha... | 41.090909 | 0.034632 |
def acquire_account(self, account=None, owner=None):
"""
Waits until an account becomes available, then locks and returns it.
If an account is not passed, the next available account is returned.
:type account: Account
:param account: The account to be acquired, or None.
... | [
"def",
"acquire_account",
"(",
"self",
",",
"account",
"=",
"None",
",",
"owner",
"=",
"None",
")",
":",
"with",
"self",
".",
"unlock_cond",
":",
"if",
"len",
"(",
"self",
".",
"accounts",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'account pool... | 39.424242 | 0.0015 |
def pop(self, option, default=None):
'''Just like `dict.pop`'''
val = self[option]
del self[option]
return (val is None and default) or val | [
"def",
"pop",
"(",
"self",
",",
"option",
",",
"default",
"=",
"None",
")",
":",
"val",
"=",
"self",
"[",
"option",
"]",
"del",
"self",
"[",
"option",
"]",
"return",
"(",
"val",
"is",
"None",
"and",
"default",
")",
"or",
"val"
] | 33.4 | 0.011696 |
def name(self):
"""
Return the person's name. If we have special titles, use them, otherwise,
don't include the title.
"""
if self.title in ["DR", "SIR", "LORD"]:
return "%s %s %s" % (self.get_title_display(), self.first_name, self.last_name)
else:
... | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"title",
"in",
"[",
"\"DR\"",
",",
"\"SIR\"",
",",
"\"LORD\"",
"]",
":",
"return",
"\"%s %s %s\"",
"%",
"(",
"self",
".",
"get_title_display",
"(",
")",
",",
"self",
".",
"first_name",
",",
"se... | 40.333333 | 0.010782 |
def check_days(text):
"""Suggest the preferred forms."""
err = "MAU102"
msg = "Days of the week should be capitalized. '{}' is the preferred form."
list = [
["Monday", ["monday"]],
["Tuesday", ["tuesday"]],
["Wednesday", ["wednesday"]],
["Thursday", ["... | [
"def",
"check_days",
"(",
"text",
")",
":",
"err",
"=",
"\"MAU102\"",
"msg",
"=",
"\"Days of the week should be capitalized. '{}' is the preferred form.\"",
"list",
"=",
"[",
"[",
"\"Monday\"",
",",
"[",
"\"monday\"",
"]",
"]",
",",
"[",
"\"Tuesday\"",
",",
"[",
... | 30.176471 | 0.00189 |
def fetch(self):
"""
Fetches the query and then tries to wrap the data in the model, joining
as needed, if applicable.
"""
returnResults = []
results = self._query.run()
for result in results:
if self._join:
# Because we can tell the m... | [
"def",
"fetch",
"(",
"self",
")",
":",
"returnResults",
"=",
"[",
"]",
"results",
"=",
"self",
".",
"_query",
".",
"run",
"(",
")",
"for",
"result",
"in",
"results",
":",
"if",
"self",
".",
"_join",
":",
"# Because we can tell the models to ignore certian fi... | 36.846154 | 0.002035 |
def delete(self):
"""
::
DELETE /:login/machines/:id
Initiate deletion of a stopped remote machine.
"""
j, r = self.datacenter.request('DELETE', self.path)
r.raise_for_status() | [
"def",
"delete",
"(",
"self",
")",
":",
"j",
",",
"r",
"=",
"self",
".",
"datacenter",
".",
"request",
"(",
"'DELETE'",
",",
"self",
".",
"path",
")",
"r",
".",
"raise_for_status",
"(",
")"
] | 24.5 | 0.015748 |
def mono_resolution(
grooves_per_mm, slit_width, focal_length, output_color, output_units="wn"
) -> float:
"""Calculate the resolution of a monochromator.
Parameters
----------
grooves_per_mm : number
Grooves per millimeter.
slit_width : number
Slit width in microns.
focal_l... | [
"def",
"mono_resolution",
"(",
"grooves_per_mm",
",",
"slit_width",
",",
"focal_length",
",",
"output_color",
",",
"output_units",
"=",
"\"wn\"",
")",
"->",
"float",
":",
"d_lambda",
"=",
"1e6",
"*",
"slit_width",
"/",
"(",
"grooves_per_mm",
"*",
"focal_length",... | 27.333333 | 0.001178 |
def load_config_dict(pipette_id: str) -> Dict:
""" Give updated config with overrides for a pipette. This will add
the default value for a mutable config before returning the modified
config value.
"""
override = load_overrides(pipette_id)
model = override['model']
config = copy.deepcopy(mod... | [
"def",
"load_config_dict",
"(",
"pipette_id",
":",
"str",
")",
"->",
"Dict",
":",
"override",
"=",
"load_overrides",
"(",
"pipette_id",
")",
"model",
"=",
"override",
"[",
"'model'",
"]",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"model_config",
"(",
")... | 33.125 | 0.001835 |
def delete(self, request, bot_id, id, format=None):
"""
Delete existing Telegram Bot
---
responseMessages:
- code: 401
message: Not authenticated
"""
return super(TelegramBotDetail, self).delete(request, bot_id, id, format) | [
"def",
"delete",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"TelegramBotDetail",
",",
"self",
")",
".",
"delete",
"(",
"request",
",",
"bot_id",
",",
"id",
",",
"format",
")"
] | 32.111111 | 0.010101 |
def addStreamingListener(self, streamingListener):
"""
Add a [[org.apache.spark.streaming.scheduler.StreamingListener]] object for
receiving system events related to streaming.
"""
self._jssc.addStreamingListener(self._jvm.JavaStreamingListenerWrapper(
self._jvm.Pytho... | [
"def",
"addStreamingListener",
"(",
"self",
",",
"streamingListener",
")",
":",
"self",
".",
"_jssc",
".",
"addStreamingListener",
"(",
"self",
".",
"_jvm",
".",
"JavaStreamingListenerWrapper",
"(",
"self",
".",
"_jvm",
".",
"PythonStreamingListenerWrapper",
"(",
... | 51.428571 | 0.008197 |
def get_full_import_name(import_from, name):
"""Get the full path of a name from a ``from x import y`` statement.
:param import_from: The astroid node to resolve the name of.
:type import_from: astroid.nodes.ImportFrom
:param name:
:type name: str
:returns: The full import path of the name.
... | [
"def",
"get_full_import_name",
"(",
"import_from",
",",
"name",
")",
":",
"partial_basename",
"=",
"resolve_import_alias",
"(",
"name",
",",
"import_from",
".",
"names",
")",
"module_name",
"=",
"import_from",
".",
"modname",
"if",
"import_from",
".",
"level",
"... | 33.045455 | 0.001337 |
def noise3(self, x, y, z, repeat, base=0.0):
"""Tileable 3D noise.
repeat specifies the integer interval in each dimension
when the noise pattern repeats.
base allows a different texture to be generated for
the same repeat interval.
"""
i = int(fmod(floor(x), repeat))
j = int(fmod(floor(y), repea... | [
"def",
"noise3",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
",",
"repeat",
",",
"base",
"=",
"0.0",
")",
":",
"i",
"=",
"int",
"(",
"fmod",
"(",
"floor",
"(",
"x",
")",
",",
"repeat",
")",
")",
"j",
"=",
"int",
"(",
"fmod",
"(",
"floor",
... | 30.35 | 0.047885 |
def make_index_for(package, index_dir, verbose=True):
"""
Create an 'index.html' for one package.
:param package: Package object to use.
:param index_dir: Where 'index.html' should be created.
"""
index_template = """\
<html>
<head><title>{title}</title></head>
<body>
<h1>{title}</h1>
<ul>
{p... | [
"def",
"make_index_for",
"(",
"package",
",",
"index_dir",
",",
"verbose",
"=",
"True",
")",
":",
"index_template",
"=",
"\"\"\"\\\n<html>\n<head><title>{title}</title></head>\n<body>\n<h1>{title}</h1>\n<ul>\n{packages}\n</ul>\n</body>\n</html>\n\"\"\"",
"item_template",
"=",
"'<li... | 29.90566 | 0.000611 |
def _validate_checksum(self):
"""Given a mnemonic word string, confirm seed checksum (last word) matches the computed checksum.
:rtype: bool
"""
phrase = self.phrase.split(" ")
if self.word_list.get_checksum(self.phrase) == phrase[-1]:
return True
raise Value... | [
"def",
"_validate_checksum",
"(",
"self",
")",
":",
"phrase",
"=",
"self",
".",
"phrase",
".",
"split",
"(",
"\" \"",
")",
"if",
"self",
".",
"word_list",
".",
"get_checksum",
"(",
"self",
".",
"phrase",
")",
"==",
"phrase",
"[",
"-",
"1",
"]",
":",
... | 37.444444 | 0.008696 |
def get_type_and_times(wxdata: [str]) -> ([str], str, str, str): # type: ignore
"""
Returns the report list and removed:
Report type string, start time string, end time string
"""
report_type, start_time, end_time = 'FROM', '', ''
if wxdata:
# TEMPO, BECMG, INTER
if wxdata[0] in... | [
"def",
"get_type_and_times",
"(",
"wxdata",
":",
"[",
"str",
"]",
")",
"->",
"(",
"[",
"str",
"]",
",",
"str",
",",
"str",
",",
"str",
")",
":",
"# type: ignore",
"report_type",
",",
"start_time",
",",
"end_time",
"=",
"'FROM'",
",",
"''",
",",
"''",... | 43.903226 | 0.001438 |
def log(ltype, method, page, user_agent):
"""Writes to the log a message in the following format::
"<datetime>: <exception> method <HTTP method> page <path> \
user agent <user_agent>"
"""
try:
f = open(settings.DJANGOSPAM_LOG, "a")
f.write("%s: %s method %s pag... | [
"def",
"log",
"(",
"ltype",
",",
"method",
",",
"page",
",",
"user_agent",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"settings",
".",
"DJANGOSPAM_LOG",
",",
"\"a\"",
")",
"f",
".",
"write",
"(",
"\"%s: %s method %s page %s user agent %s\\n\"",
"%",
"(",... | 34.117647 | 0.008389 |
def add_default(self, ext, content_type):
"""
Add a child ``<Default>`` element with attributes set to parameter
values.
"""
return self._add_default(extension=ext, contentType=content_type) | [
"def",
"add_default",
"(",
"self",
",",
"ext",
",",
"content_type",
")",
":",
"return",
"self",
".",
"_add_default",
"(",
"extension",
"=",
"ext",
",",
"contentType",
"=",
"content_type",
")"
] | 37.5 | 0.008696 |
def get_diagnostics(self):
"""
Reads diagnostic data from the sensor.
OCF (Offset Compensation Finished) - logic high indicates the finished Offset Compensation Algorithm. After power up the flag remains always to logic high.
COF (Cordic Overflow) - logic high indicates an out of range ... | [
"def",
"get_diagnostics",
"(",
"self",
")",
":",
"status",
"=",
"self",
".",
"bus",
".",
"read_byte_data",
"(",
"self",
".",
"address",
",",
"self",
".",
"diagnostics_reg",
")",
"bits_values",
"=",
"dict",
"(",
"[",
"(",
"'OCF'",
",",
"status",
"&",
"0... | 58.055556 | 0.010358 |
def _findAll(self, **kwargs):
"""Return a list of all children that match the specified criteria."""
result = []
for item in self._generateFind(**kwargs):
result.append(item)
return result | [
"def",
"_findAll",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"self",
".",
"_generateFind",
"(",
"*",
"*",
"kwargs",
")",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
] | 37.833333 | 0.008621 |
def main():
"""
Main function.
:return:
None.
"""
try:
# Get the `src` directory's absolute path
src_path = os.path.dirname(
# `aoiklivereload` directory's absolute path
os.path.dirname(
# `demo` directory's absolute path
... | [
"def",
"main",
"(",
")",
":",
"try",
":",
"# Get the `src` directory's absolute path",
"src_path",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"# `aoiklivereload` directory's absolute path",
"os",
".",
"path",
".",
"dirname",
"(",
"# `demo` directory's absolute path",
... | 23.814286 | 0.000576 |
def download_data_dictionary(request, dataset_id):
"""Generates and returns compiled data dictionary from database.
Returned as a CSV response.
"""
dataset = Dataset.objects.get(pk=dataset_id)
dataDict = dataset.data_dictionary
fields = DataDictionaryField.objects.filter(
parent_dict=da... | [
"def",
"download_data_dictionary",
"(",
"request",
",",
"dataset_id",
")",
":",
"dataset",
"=",
"Dataset",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"dataset_id",
")",
"dataDict",
"=",
"dataset",
".",
"data_dictionary",
"fields",
"=",
"DataDictionaryField",
... | 32.666667 | 0.000901 |
def _pre_process_line(line, comment_markers=_COMMENT_MARKERS):
"""
Preprocess a line in properties; strip comments, etc.
:param line:
A string not starting w/ any white spaces and ending w/ line breaks.
It may be empty. see also: :func:`load`.
:param comment_markers: Comment markers, e.... | [
"def",
"_pre_process_line",
"(",
"line",
",",
"comment_markers",
"=",
"_COMMENT_MARKERS",
")",
":",
"if",
"not",
"line",
":",
"return",
"None",
"if",
"any",
"(",
"c",
"in",
"line",
"for",
"c",
"in",
"comment_markers",
")",
":",
"if",
"line",
".",
"starts... | 30.037037 | 0.001195 |
def convert_dictionary_to_mysql_table(
log,
dictionary,
dbTableName,
uniqueKeyList=[],
dbConn=False,
createHelperTables=False,
dateModified=False,
returnInsertOnly=False,
replace=False,
batchInserts=True,
reDatetime=False,
s... | [
"def",
"convert_dictionary_to_mysql_table",
"(",
"log",
",",
"dictionary",
",",
"dbTableName",
",",
"uniqueKeyList",
"=",
"[",
"]",
",",
"dbConn",
"=",
"False",
",",
"createHelperTables",
"=",
"False",
",",
"dateModified",
"=",
"False",
",",
"returnInsertOnly",
... | 43.444906 | 0.002105 |
def create_api_vlan(self):
"""Get an instance of Api Vlan services facade."""
return ApiVlan(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | [
"def",
"create_api_vlan",
"(",
"self",
")",
":",
"return",
"ApiVlan",
"(",
"self",
".",
"networkapi_url",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"user_ldap",
")"
] | 30.571429 | 0.009091 |
def convert_to_node(instance, xml_node: XmlNode, node_globals: InheritedDict = None)\
-> InstanceNode:
'''Wraps passed instance with InstanceNode'''
return InstanceNode(instance, xml_node, node_globals) | [
"def",
"convert_to_node",
"(",
"instance",
",",
"xml_node",
":",
"XmlNode",
",",
"node_globals",
":",
"InheritedDict",
"=",
"None",
")",
"->",
"InstanceNode",
":",
"return",
"InstanceNode",
"(",
"instance",
",",
"xml_node",
",",
"node_globals",
")"
] | 52.75 | 0.014019 |
def flanking(args):
"""
%prog flanking SI.ids liftover.bed master.txt master-removed.txt
Extract flanking genes for given SI loci.
"""
p = OptionParser(flanking.__doc__)
p.add_option("-N", default=50, type="int",
help="How many genes on both directions")
opts, args = p.par... | [
"def",
"flanking",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"flanking",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"-N\"",
",",
"default",
"=",
"50",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"How many genes on both directions\... | 29.456522 | 0.001429 |
def rename(self, name=None, sourceNetwork=None, verbose=False):
"""
Rename an existing network. The SUID of the network is returned
:param name (string): Enter a new title for the network
:param sourceNetwork (string): Specifies a network by name, or by SUID
if the prefix SU... | [
"def",
"rename",
"(",
"self",
",",
"name",
"=",
"None",
",",
"sourceNetwork",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"sourceNetwork",
"=",
"check_network",
"(",
"self",
",",
"sourceNetwork",
",",
"verbose",
"=",
"verbose",
")",
"PARAMS",
"=... | 48.5 | 0.013906 |
def _getAuth(self):
"""
Main step in authorizing with Reader.
Sends request to Google ClientAuthMethod URL which returns an Auth token.
Returns Auth token or raises IOError on error.
"""
parameters = {
'service' : 'reader',
'Email' : sel... | [
"def",
"_getAuth",
"(",
"self",
")",
":",
"parameters",
"=",
"{",
"'service'",
":",
"'reader'",
",",
"'Email'",
":",
"self",
".",
"username",
",",
"'Passwd'",
":",
"self",
".",
"password",
",",
"'accountType'",
":",
"'GOOGLE'",
"}",
"req",
"=",
"requests... | 40.25 | 0.010922 |
def sklearn_segmentation(self, x, cluster_fn):
"""
Divide a univariate time-series, data_frame, into states contiguous segments, using sk-learn clustering algorithms on the peak prominences of the data.
:param x: The time series to assess freeze of gait on. This could be x, y, ... | [
"def",
"sklearn_segmentation",
"(",
"self",
",",
"x",
",",
"cluster_fn",
")",
":",
"peaks",
",",
"prominences",
"=",
"get_signal_peaks_and_prominences",
"(",
"x",
")",
"# sklearn fix: reshape to (-1, 1)",
"sklearn_idx",
"=",
"cluster_fn",
".",
"fit_predict",
"(",
"p... | 50.904762 | 0.008264 |
def relabel_non_zero(label_image, start = 1):
r"""
Relabel the regions of a label image.
Re-processes the labels to make them consecutively and starting from start.
Keeps all zero (0) labels, as they are considered background.
Parameters
----------
label_image : array_like
A nD... | [
"def",
"relabel_non_zero",
"(",
"label_image",
",",
"start",
"=",
"1",
")",
":",
"if",
"start",
"<=",
"0",
":",
"raise",
"ArgumentError",
"(",
"'The starting value can not be 0 or lower.'",
")",
"l",
"=",
"list",
"(",
"scipy",
".",
"unique",
"(",
"label_image"... | 26.53125 | 0.015909 |
def get(self, slug, xdata, ydatasets, label, opts, style, ctype):
"""
Returns html for a chart
"""
xdataset = self._format_list(xdata)
width = "100%"
height = "300px"
if opts is not None:
if "width" in opts:
width = str(opts["width"])
... | [
"def",
"get",
"(",
"self",
",",
"slug",
",",
"xdata",
",",
"ydatasets",
",",
"label",
",",
"opts",
",",
"style",
",",
"ctype",
")",
":",
"xdataset",
"=",
"self",
".",
"_format_list",
"(",
"xdata",
")",
"width",
"=",
"\"100%\"",
"height",
"=",
"\"300p... | 33.265625 | 0.000912 |
def _run_server_ops(state, host, progress=None):
'''
Run all ops for a single server.
'''
logger.debug('Running all ops on {0}'.format(host))
for op_hash in state.get_op_order():
op_meta = state.op_meta[op_hash]
logger.info('--> {0} {1} on {2}'.format(
click.style('-->... | [
"def",
"_run_server_ops",
"(",
"state",
",",
"host",
",",
"progress",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Running all ops on {0}'",
".",
"format",
"(",
"host",
")",
")",
"for",
"op_hash",
"in",
"state",
".",
"get_op_order",
"(",
")",
":... | 28.206897 | 0.001182 |
def localize_preserving_time_of_day(dt):
"""
Return the given datetime with the same time-of-day (hours and minutes) as
it *seems* to have, even if it has been adjusted by applying `timedelta`
additions that traverse daylight savings dates and would therefore
otherwise trigger changes to its apparen... | [
"def",
"localize_preserving_time_of_day",
"(",
"dt",
")",
":",
"# Remember the apparent time-of-day years, month, hours and minutes",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
"=",
"dt",
".",
"year",
",",
"dt",
".",
"month",
",",
"dt",
".",
"... | 49.388889 | 0.001104 |
def get(self, key):
"""
Returns the value for the specified key, or None if this map does not contain this key.
**Warning:
This method uses hashCode and equals of the binary form of the key, not the actual implementations of hashCode
and equals defined in the key's class.**
... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"check_not_none",
"(",
"key",
",",
"\"key can't be None\"",
")",
"key_data",
"=",
"self",
".",
"_to_data",
"(",
"key",
")",
"return",
"self",
".",
"_encode_invoke_on_key",
"(",
"replicated_map_get_codec",
",",
... | 45 | 0.009331 |
def filter_callbacks(cls, client, event_data):
"""Filter registered events and yield all of their callbacks."""
for event in cls.filter_events(client, event_data):
for cb in event.callbacks:
yield cb | [
"def",
"filter_callbacks",
"(",
"cls",
",",
"client",
",",
"event_data",
")",
":",
"for",
"event",
"in",
"cls",
".",
"filter_events",
"(",
"client",
",",
"event_data",
")",
":",
"for",
"cb",
"in",
"event",
".",
"callbacks",
":",
"yield",
"cb"
] | 39.833333 | 0.008197 |
def hdparms(disks, args=None):
'''
Retrieve all info's for all disks
parse 'em into a nice dict
(which, considering hdparms output, is quite a hassle)
.. versionadded:: 2016.3.0
CLI Example:
.. code-block:: bash
salt '*' disk.hdparms /dev/sda
'''
all_parms = 'aAbBcCdgHiJkM... | [
"def",
"hdparms",
"(",
"disks",
",",
"args",
"=",
"None",
")",
":",
"all_parms",
"=",
"'aAbBcCdgHiJkMmNnQrRuW'",
"if",
"args",
"is",
"None",
":",
"args",
"=",
"all_parms",
"elif",
"isinstance",
"(",
"args",
",",
"(",
"list",
",",
"tuple",
")",
")",
":"... | 30.486486 | 0.000429 |
def dim_upper_extent_dict(self):
""" Returns a mapping of dimension name to upper_extent """
return { d.name: d.upper_extent for d in self._dims.itervalues()} | [
"def",
"dim_upper_extent_dict",
"(",
"self",
")",
":",
"return",
"{",
"d",
".",
"name",
":",
"d",
".",
"upper_extent",
"for",
"d",
"in",
"self",
".",
"_dims",
".",
"itervalues",
"(",
")",
"}"
] | 57.333333 | 0.017241 |
def listen(self):
""" Handles listening requests from the client.
There are 4 types of requests:
1- Check space in the queue
2- Tests the socket
3- If there is a space, it sends data
4- after data is sent, puts it to queue for storing
"""
count = 0
... | [
"def",
"listen",
"(",
"self",
")",
":",
"count",
"=",
"0",
"self",
".",
"_start",
"(",
")",
"while",
"True",
":",
"result",
"=",
"self",
".",
"_socket",
".",
"recv_pyobj",
"(",
")",
"if",
"isinstance",
"(",
"result",
",",
"tuple",
")",
":",
"reques... | 30.533333 | 0.002116 |
def passthrough_repl(self, inputstring, **kwargs):
"""Add back passthroughs."""
out = []
index = None
for c in append_it(inputstring, None):
try:
if index is not None:
if c is not None and c in nums:
index += c
... | [
"def",
"passthrough_repl",
"(",
"self",
",",
"inputstring",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
"=",
"[",
"]",
"index",
"=",
"None",
"for",
"c",
"in",
"append_it",
"(",
"inputstring",
",",
"None",
")",
":",
"try",
":",
"if",
"index",
"is",
"n... | 33.666667 | 0.00175 |
def truncate_loc(self, character, location, branch, turn, tick):
"""Remove future data about a particular location
Return True if I deleted anything, False otherwise.
"""
r = False
branches_turns = self.branches[character, location][branch]
branches_turns.truncate(turn)... | [
"def",
"truncate_loc",
"(",
"self",
",",
"character",
",",
"location",
",",
"branch",
",",
"turn",
",",
"tick",
")",
":",
"r",
"=",
"False",
"branches_turns",
"=",
"self",
".",
"branches",
"[",
"character",
",",
"location",
"]",
"[",
"branch",
"]",
"br... | 43.5 | 0.002162 |
def plot_or_print(example_farm, example_cluster):
r"""
Plots or prints power output and power (coefficient) curves.
Parameters
----------
example_farm : WindFarm
WindFarm object.
example_farm_2 : WindFarm
WindFarm object constant wind farm efficiency and coordinates.
"""
... | [
"def",
"plot_or_print",
"(",
"example_farm",
",",
"example_cluster",
")",
":",
"# plot or print power output",
"if",
"plt",
":",
"example_cluster",
".",
"power_output",
".",
"plot",
"(",
"legend",
"=",
"True",
",",
"label",
"=",
"'example cluster'",
")",
"example_... | 29.095238 | 0.001585 |
def _get_samples(self, samples):
"""
Internal function. Prelude for each step() to read in perhaps
non empty list of samples to process. Input is a list of sample names,
output is a list of sample objects."""
## if samples not entered use all samples
if not samples:
samples = self.sample... | [
"def",
"_get_samples",
"(",
"self",
",",
"samples",
")",
":",
"## if samples not entered use all samples",
"if",
"not",
"samples",
":",
"samples",
"=",
"self",
".",
"samples",
".",
"keys",
"(",
")",
"## Be nice and allow user to pass in only one sample as a string,",
"#... | 38.416667 | 0.009873 |
def replace_word_tokens(string, language):
"""
Given a string and an ISO 639-2 language code,
return the string with the words replaced with
an operational equivalent.
"""
words = mathwords.word_groups_for_language(language)
# Replace operator words with numeric operators
operators = wo... | [
"def",
"replace_word_tokens",
"(",
"string",
",",
"language",
")",
":",
"words",
"=",
"mathwords",
".",
"word_groups_for_language",
"(",
"language",
")",
"# Replace operator words with numeric operators",
"operators",
"=",
"words",
"[",
"'binary_operators'",
"]",
".",
... | 32.140351 | 0.00053 |
def network_get_primary_address(binding):
'''
Deprecated since Juju 2.3; use network_get()
Retrieve the primary network address for a named binding
:param binding: string. The name of a relation of extra-binding
:return: string. The primary IP address for the named binding
:raise: NotImplement... | [
"def",
"network_get_primary_address",
"(",
"binding",
")",
":",
"cmd",
"=",
"[",
"'network-get'",
",",
"'--primary-address'",
",",
"binding",
"]",
"try",
":",
"response",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"subprocess",
"."... | 36.590909 | 0.001211 |
def get_elements(self, element, xmlns=None):
"""
Return a list of elements those match the searching condition.
If the XML input has namespaces, elements and attributes with prefixes
in the form prefix:sometag get expanded to {namespace}element where the
prefix is replaced by the... | [
"def",
"get_elements",
"(",
"self",
",",
"element",
",",
"xmlns",
"=",
"None",
")",
":",
"real_element",
"=",
"\"\"",
"real_xmlns",
"=",
"\"\"",
"if",
"xmlns",
"is",
"None",
":",
"real_xmlns",
"=",
"\"{\"",
"+",
"self",
".",
"xmlns",
"+",
"\"}\"",
"if"... | 47.046512 | 0.001937 |
def to_obj(self, ns_info=None):
"""Convert to a GenerateDS binding object.
Subclasses can override this function.
Returns:
An instance of this Entity's ``_binding_class`` with properties
set from this Entity.
"""
if ns_info:
ns_info.collect(s... | [
"def",
"to_obj",
"(",
"self",
",",
"ns_info",
"=",
"None",
")",
":",
"if",
"ns_info",
":",
"ns_info",
".",
"collect",
"(",
"self",
")",
"# null behavior for classes that inherit from Entity but do not",
"# have _binding_class",
"if",
"not",
"hasattr",
"(",
"self",
... | 30.971429 | 0.001789 |
def _handle_nopinyin_char(chars, errors='default'):
"""处理没有拼音的字符"""
if callable_check(errors):
return errors(chars)
if errors == 'default':
return chars
elif errors == 'ignore':
return None
elif errors == 'replace':
if len(chars) > 1:
return ''.join(text_... | [
"def",
"_handle_nopinyin_char",
"(",
"chars",
",",
"errors",
"=",
"'default'",
")",
":",
"if",
"callable_check",
"(",
"errors",
")",
":",
"return",
"errors",
"(",
"chars",
")",
"if",
"errors",
"==",
"'default'",
":",
"return",
"chars",
"elif",
"errors",
"=... | 28.857143 | 0.002398 |
def cree_ws_lecture(self, champs_ligne):
"""Alternative to create read only widgets. They should be set after."""
for c in champs_ligne:
label = ASSOCIATION[c][0]
w = ASSOCIATION[c][3](self.acces[c], False)
w.setObjectName("champ-lecture-seule-details")
se... | [
"def",
"cree_ws_lecture",
"(",
"self",
",",
"champs_ligne",
")",
":",
"for",
"c",
"in",
"champs_ligne",
":",
"label",
"=",
"ASSOCIATION",
"[",
"c",
"]",
"[",
"0",
"]",
"w",
"=",
"ASSOCIATION",
"[",
"c",
"]",
"[",
"3",
"]",
"(",
"self",
".",
"acces"... | 48.571429 | 0.008671 |
def in_venv():
"""
:return: True if in running from a virtualenv
Has to detect the case where the python binary is run
directly, so VIRTUAL_ENV may not be set
"""
global _in_venv
if _in_venv is not None:
return _in_venv
if not (os.path.isfile(ORIG_PREFIX_TXT) or os.path.isfile(... | [
"def",
"in_venv",
"(",
")",
":",
"global",
"_in_venv",
"if",
"_in_venv",
"is",
"not",
"None",
":",
"return",
"_in_venv",
"if",
"not",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"ORIG_PREFIX_TXT",
")",
"or",
"os",
".",
"path",
".",
"isfile",
"(",
"PY... | 34.030303 | 0.001732 |
def is_tagged(self, layer):
"""Is the given element tokenized/tagged?"""
# we have a number of special names that are not layers but instead
# attributes of "words" layer
if layer == ANALYSIS:
if WORDS in self and len(self[WORDS]) > 0:
return ANALYSIS in self[... | [
"def",
"is_tagged",
"(",
"self",
",",
"layer",
")",
":",
"# we have a number of special names that are not layers but instead",
"# attributes of \"words\" layer",
"if",
"layer",
"==",
"ANALYSIS",
":",
"if",
"WORDS",
"in",
"self",
"and",
"len",
"(",
"self",
"[",
"WORDS... | 47.038462 | 0.002404 |
def generate_component_id_namespace_overview(model, components):
"""
Tabulate which MIRIAM databases the component's identifier matches.
Parameters
----------
model : cobra.Model
A cobrapy metabolic model.
components : {"metabolites", "reactions", "genes"}
A string denoting `cob... | [
"def",
"generate_component_id_namespace_overview",
"(",
"model",
",",
"components",
")",
":",
"patterns",
"=",
"{",
"\"metabolites\"",
":",
"METABOLITE_ANNOTATIONS",
",",
"\"reactions\"",
":",
"REACTION_ANNOTATIONS",
",",
"\"genes\"",
":",
"GENE_PRODUCT_ANNOTATIONS",
"}",... | 39.244898 | 0.000507 |
def get_channel_max_user_count(channel=14, **kwargs):
'''
Get max users in channel
:param channel: number [1:7]
:param kwargs:
- api_host=127.0.0.1
- api_user=admin
- api_pass=example
- api_port=623
- api_kg=None
:return: int -- often 16
CLI Examples:
... | [
"def",
"get_channel_max_user_count",
"(",
"channel",
"=",
"14",
",",
"*",
"*",
"kwargs",
")",
":",
"access",
"=",
"get_user_access",
"(",
"channel",
"=",
"channel",
",",
"uid",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
"return",
"access",
"[",
"'channel_in... | 23.666667 | 0.001934 |
def exists(self, **kwargs):
"""Providing a partition is not necessary on topology; causes errors"""
kwargs.pop('partition', None)
kwargs['transform_name'] = True
return self._exists(**kwargs) | [
"def",
"exists",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"pop",
"(",
"'partition'",
",",
"None",
")",
"kwargs",
"[",
"'transform_name'",
"]",
"=",
"True",
"return",
"self",
".",
"_exists",
"(",
"*",
"*",
"kwargs",
")"
] | 43.8 | 0.008969 |
def _erc_weights_ccd(x0,
cov,
b,
maximum_iterations,
tolerance):
"""
Calculates the equal risk contribution / risk parity weights given
a DataFrame of returns.
Args:
* x0 (np.array): Starting asset weights.
... | [
"def",
"_erc_weights_ccd",
"(",
"x0",
",",
"cov",
",",
"b",
",",
"maximum_iterations",
",",
"tolerance",
")",
":",
"n",
"=",
"len",
"(",
"x0",
")",
"x",
"=",
"x0",
".",
"copy",
"(",
")",
"var",
"=",
"np",
".",
"diagonal",
"(",
"cov",
")",
"ctr",
... | 30.508475 | 0.000538 |
def autoresponds(self, matcher, *args, **kwargs):
"""Send a canned reply to all matching client requests.
``matcher`` is a `Matcher` or a command name, or an instance of
`OpInsert`, `OpQuery`, etc.
>>> s = MockupDB()
>>> port = s.run()
>>>
>>> from pymon... | [
"def",
"autoresponds",
"(",
"self",
",",
"matcher",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_insert_responder",
"(",
"\"top\"",
",",
"matcher",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 36.57732 | 0.001921 |
def get_log(db, job_id):
"""
Extract the logs as a big string
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_id: a job ID
"""
logs = db('SELECT * FROM log WHERE job_id=?x ORDER BY id', job_id)
out = []
for log in logs:
time = str(log.timestamp)[:-4] # strip... | [
"def",
"get_log",
"(",
"db",
",",
"job_id",
")",
":",
"logs",
"=",
"db",
"(",
"'SELECT * FROM log WHERE job_id=?x ORDER BY id'",
",",
"job_id",
")",
"out",
"=",
"[",
"]",
"for",
"log",
"in",
"logs",
":",
"time",
"=",
"str",
"(",
"log",
".",
"timestamp",
... | 31.538462 | 0.00237 |
def _dPdT_sat(cls, T):
"""Auxiliary equation for the dP/dT along saturation line
Parameters
----------
T : float
Temperature, [K]
Returns
-------
dPdT : float
dPdT, [MPa/K]
References
----------
IAPWS, Revised Sup... | [
"def",
"_dPdT_sat",
"(",
"cls",
",",
"T",
")",
":",
"Tita",
"=",
"1",
"-",
"T",
"/",
"cls",
".",
"Tc",
"suma1",
"=",
"0",
"suma2",
"=",
"0",
"for",
"n",
",",
"x",
"in",
"zip",
"(",
"cls",
".",
"_Pv",
"[",
"\"ao\"",
"]",
",",
"cls",
".",
"... | 27.75 | 0.002488 |
def aggr(self, group, *attributes, keep_all_rows=False, **named_attributes):
"""
Aggregation/projection operator
:param group: an entity set whose entities will be grouped per entity of `self`
:param attributes: attributes of self to include in the result
:param keep_all_rows: T... | [
"def",
"aggr",
"(",
"self",
",",
"group",
",",
"*",
"attributes",
",",
"keep_all_rows",
"=",
"False",
",",
"*",
"*",
"named_attributes",
")",
":",
"return",
"GroupBy",
".",
"create",
"(",
"self",
",",
"group",
",",
"keep_all_rows",
"=",
"keep_all_rows",
... | 67.083333 | 0.008578 |
def create_group(cls, prefix: str, name: str) -> ErrorGroup:
"""Create a new error group and return it."""
group = cls.ErrorGroup(prefix, name)
cls.groups.append(group)
return group | [
"def",
"create_group",
"(",
"cls",
",",
"prefix",
":",
"str",
",",
"name",
":",
"str",
")",
"->",
"ErrorGroup",
":",
"group",
"=",
"cls",
".",
"ErrorGroup",
"(",
"prefix",
",",
"name",
")",
"cls",
".",
"groups",
".",
"append",
"(",
"group",
")",
"r... | 41.8 | 0.00939 |
def is_rate_limited(self, namespace: str) -> bool:
"""
Checks if a namespace is already rate limited or not without making any additional attempts
:param namespace: Rate limiting namespace
:type namespace: str
:return: Returns true if attempt can go ahead under current rate... | [
"def",
"is_rate_limited",
"(",
"self",
",",
"namespace",
":",
"str",
")",
"->",
"bool",
":",
"return",
"not",
"self",
".",
"__can_attempt",
"(",
"namespace",
"=",
"namespace",
",",
"add_attempt",
"=",
"False",
")"
] | 43.3 | 0.00905 |
async def add_relation(self, relation1, relation2):
"""Add a relation between two applications.
:param str relation1: '<application>[:<relation_name>]'
:param str relation2: '<application>[:<relation_name>]'
"""
connection = self.connection()
app_facade = client.Applica... | [
"async",
"def",
"add_relation",
"(",
"self",
",",
"relation1",
",",
"relation2",
")",
":",
"connection",
"=",
"self",
".",
"connection",
"(",
")",
"app_facade",
"=",
"client",
".",
"ApplicationFacade",
".",
"from_connection",
"(",
"connection",
")",
"log",
"... | 35 | 0.001589 |
def _skip(options):
"""Return true if the task should be entirely skipped, and thus have no product requirements."""
values = [options.missing_direct_deps, options.unnecessary_deps]
return all(v == 'off' for v in values) | [
"def",
"_skip",
"(",
"options",
")",
":",
"values",
"=",
"[",
"options",
".",
"missing_direct_deps",
",",
"options",
".",
"unnecessary_deps",
"]",
"return",
"all",
"(",
"v",
"==",
"'off'",
"for",
"v",
"in",
"values",
")"
] | 57.25 | 0.008621 |
def is_locked(self):
"""
Returns whether model is locked
"""
if not self.__locked__:
return False
elif self.get_parent():
return self.get_parent().is_locked()
return True | [
"def",
"is_locked",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__locked__",
":",
"return",
"False",
"elif",
"self",
".",
"get_parent",
"(",
")",
":",
"return",
"self",
".",
"get_parent",
"(",
")",
".",
"is_locked",
"(",
")",
"return",
"True"
] | 23.4 | 0.00823 |
def leave_group(self, group_alias):
"""
退出小组
:param group_alias: 小组ID
:return:
"""
return self.api.req(API_GROUP_GROUP_HOME % group_alias, params={
'action': 'quit',
'ck': self.api.ck(),
}) | [
"def",
"leave_group",
"(",
"self",
",",
"group_alias",
")",
":",
"return",
"self",
".",
"api",
".",
"req",
"(",
"API_GROUP_GROUP_HOME",
"%",
"group_alias",
",",
"params",
"=",
"{",
"'action'",
":",
"'quit'",
",",
"'ck'",
":",
"self",
".",
"api",
".",
"... | 24.454545 | 0.014337 |
def get(self, timeout=None):
"""Get the value of the promise, waiting if necessary."""
self.wait(timeout)
if self._state==self.FULFILLED:
return self.value
else:
raise ValueError("Calculation didn't yield a value") | [
"def",
"get",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"wait",
"(",
"timeout",
")",
"if",
"self",
".",
"_state",
"==",
"self",
".",
"FULFILLED",
":",
"return",
"self",
".",
"value",
"else",
":",
"raise",
"ValueError",
"(",
"... | 37.714286 | 0.011111 |
def settimeout(self, timeout):
"""
Set the timeout to the websocket.
timeout: timeout time(second).
"""
self.sock_opt.timeout = timeout
if self.sock:
self.sock.settimeout(timeout) | [
"def",
"settimeout",
"(",
"self",
",",
"timeout",
")",
":",
"self",
".",
"sock_opt",
".",
"timeout",
"=",
"timeout",
"if",
"self",
".",
"sock",
":",
"self",
".",
"sock",
".",
"settimeout",
"(",
"timeout",
")"
] | 25.777778 | 0.008333 |
def _parseDirectories(self, dataDirectoryInstance, magic = consts.PE32):
"""
Parses all the directories in the L{PE} instance.
@type dataDirectoryInstance: L{DataDirectory}
@param dataDirectoryInstance: A L{DataDirectory} object with the directories data.
@type ... | [
"def",
"_parseDirectories",
"(",
"self",
",",
"dataDirectoryInstance",
",",
"magic",
"=",
"consts",
".",
"PE32",
")",
":",
"directories",
"=",
"[",
"(",
"consts",
".",
"EXPORT_DIRECTORY",
",",
"self",
".",
"_parseExportDirectory",
")",
",",
"(",
"consts",
".... | 61.862069 | 0.016465 |
def on_action(action):
"""Decorator for action handlers.
:param str action: explicit action name
This also decorates the method with `tornado.gen.coroutine` so that
`~tornado.concurrent.Future` can be yielded.
"""
@wrapt.decorator
@tornado.gen.coroutine
def _execute(wrapped, instance, ... | [
"def",
"on_action",
"(",
"action",
")",
":",
"@",
"wrapt",
".",
"decorator",
"@",
"tornado",
".",
"gen",
".",
"coroutine",
"def",
"_execute",
"(",
"wrapped",
",",
"instance",
",",
"args",
",",
"kwargs",
")",
":",
"return",
"wrapped",
"(",
"*",
"args",
... | 27.333333 | 0.002358 |
def decode(self, encoded, parentFieldName=""):
"""See the function description in base.py"""
if parentFieldName != "":
fieldName = "%s.%s" % (parentFieldName, self.name)
else:
fieldName = self.name
return ({fieldName: ([[0, 0]], "input")}, [fieldName]) | [
"def",
"decode",
"(",
"self",
",",
"encoded",
",",
"parentFieldName",
"=",
"\"\"",
")",
":",
"if",
"parentFieldName",
"!=",
"\"\"",
":",
"fieldName",
"=",
"\"%s.%s\"",
"%",
"(",
"parentFieldName",
",",
"self",
".",
"name",
")",
"else",
":",
"fieldName",
... | 30.444444 | 0.010638 |
def proximal_translation(prox_factory, y):
r"""Calculate the proximal of the translated function F(x - y).
Parameters
----------
prox_factory : callable
A factory function that, when called with a step size, returns the
proximal operator of ``F``.
y : Element in domain of ``F``.
... | [
"def",
"proximal_translation",
"(",
"prox_factory",
",",
"y",
")",
":",
"def",
"translation_prox_factory",
"(",
"sigma",
")",
":",
"\"\"\"Create proximal for the translation with a given sigma.\n\n Parameters\n ----------\n sigma : positive float\n Step si... | 29.5 | 0.000608 |
def multi_log_probs_from_logits_and_actions(policy_logits, actions):
"""Computes action log-probs from policy logits and actions.
In the notation used throughout documentation and comments, T refers to the
time dimension ranging from 0 to T-1. B refers to the batch size and
ACTION_SPACE refers to the list of... | [
"def",
"multi_log_probs_from_logits_and_actions",
"(",
"policy_logits",
",",
"actions",
")",
":",
"log_probs",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"policy_logits",
")",
")",
":",
"log_probs",
".",
"append",
"(",
"-",
"tf",
".",
"nn",... | 30.5 | 0.000836 |
def create_binary_buffer(init_or_size):
"""
ctypes.create_string_buffer variant which does not add a trailing null
when init_or_size is not a size.
"""
# As per ctypes.create_string_buffer, as of python 2.7.10 at least:
# - int or long is a length
# - str or unicode is an initialiser
# T... | [
"def",
"create_binary_buffer",
"(",
"init_or_size",
")",
":",
"# As per ctypes.create_string_buffer, as of python 2.7.10 at least:",
"# - int or long is a length",
"# - str or unicode is an initialiser",
"# Testing the latter confuses 2to3, so test the former.",
"if",
"isinstance",
"(",
"i... | 42.083333 | 0.001938 |
def load_woolyrnq(as_series=False):
"""Quarterly production of woollen yarn in Australia.
This time-series records the quarterly production (in tonnes) of woollen
yarn in Australia between Mar 1965 and Sep 1994.
Parameters
----------
as_series : bool, optional (default=False)
Whether t... | [
"def",
"load_woolyrnq",
"(",
"as_series",
"=",
"False",
")",
":",
"rslt",
"=",
"np",
".",
"array",
"(",
"[",
"6172",
",",
"6709",
",",
"6633",
",",
"6660",
",",
"6786",
",",
"6800",
",",
"6730",
",",
"6765",
",",
"6720",
",",
"7133",
",",
"6946",... | 33.702128 | 0.000307 |
def load_private_key(source, password=None):
"""
Loads a private key into a PrivateKey object
:param source:
A byte string of file contents, a unicode string filename or an
asn1crypto.keys.PrivateKeyInfo object
:param password:
A byte or unicode string to decrypt the private ke... | [
"def",
"load_private_key",
"(",
"source",
",",
"password",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"keys",
".",
"PrivateKeyInfo",
")",
":",
"private_object",
"=",
"source",
"else",
":",
"if",
"password",
"is",
"not",
"None",
":",
"... | 32.962963 | 0.001091 |
def load_cells(self, datum=None):
"""Load the row's data and initialize all the cells in the row.
It also set the appropriate row properties which require
the row's data to be determined.
The row's data is provided either at initialization or as an
argument to this function.
... | [
"def",
"load_cells",
"(",
"self",
",",
"datum",
"=",
"None",
")",
":",
"# Compile all the cells on instantiation.",
"table",
"=",
"self",
".",
"table",
"if",
"datum",
":",
"self",
".",
"datum",
"=",
"datum",
"else",
":",
"datum",
"=",
"self",
".",
"datum",... | 40.72549 | 0.00094 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.