text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def prepare_env(gdef='', gvars={}, extra_vars={}, host='localhost'):
'''clear current sos_dict, execute global_def (definitions and imports),
and inject global variables'''
env.sos_dict.clear()
if not gdef and not gvars:
# SoS Notebook calls prepare_env without global statement from a
#... | [
"def",
"prepare_env",
"(",
"gdef",
"=",
"''",
",",
"gvars",
"=",
"{",
"}",
",",
"extra_vars",
"=",
"{",
"}",
",",
"host",
"=",
"'localhost'",
")",
":",
"env",
".",
"sos_dict",
".",
"clear",
"(",
")",
"if",
"not",
"gdef",
"and",
"not",
"gvars",
":... | 45.711864 | 22.186441 |
def otsu(data, min_threshold=None, max_threshold=None,bins=256):
"""Compute a threshold using Otsu's method
data - an array of intensity values between zero and one
min_threshold - only consider thresholds above this minimum value
max_threshold - only consider thresholds below this maxi... | [
"def",
"otsu",
"(",
"data",
",",
"min_threshold",
"=",
"None",
",",
"max_threshold",
"=",
"None",
",",
"bins",
"=",
"256",
")",
":",
"assert",
"min_threshold",
"is",
"None",
"or",
"max_threshold",
"is",
"None",
"or",
"min_threshold",
"<",
"max_threshold",
... | 40.563636 | 18.4 |
def configure(obj, token):
"""Use this command to configure API tokens
"""
config = obj.get('config') or FileConfig(obj['profile'])
config.auth_token = token
config.save() | [
"def",
"configure",
"(",
"obj",
",",
"token",
")",
":",
"config",
"=",
"obj",
".",
"get",
"(",
"'config'",
")",
"or",
"FileConfig",
"(",
"obj",
"[",
"'profile'",
"]",
")",
"config",
".",
"auth_token",
"=",
"token",
"config",
".",
"save",
"(",
")"
] | 31 | 11.333333 |
def cartesian_cs(self):
"""The :class:`CartesianCS` which describes the coordinate axes."""
cs = self.element.find(GML_NS + 'cartesianCS')
href = cs.attrib[XLINK_NS + 'href']
return get(href) | [
"def",
"cartesian_cs",
"(",
"self",
")",
":",
"cs",
"=",
"self",
".",
"element",
".",
"find",
"(",
"GML_NS",
"+",
"'cartesianCS'",
")",
"href",
"=",
"cs",
".",
"attrib",
"[",
"XLINK_NS",
"+",
"'href'",
"]",
"return",
"get",
"(",
"href",
")"
] | 43.8 | 10 |
def save_file(self, title="Save As", initialDir="~", fileTypes="*|All Files", rememberAs=None, **kwargs):
"""
Show a Save As dialog
Usage: C{dialog.save_file(title="Save As", initialDir="~", fileTypes="*|All Files", rememberAs=None, **kwargs)}
@param title: window title... | [
"def",
"save_file",
"(",
"self",
",",
"title",
"=",
"\"Save As\"",
",",
"initialDir",
"=",
"\"~\"",
",",
"fileTypes",
"=",
"\"*|All Files\"",
",",
"rememberAs",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"rememberAs",
"is",
"not",
"None",
":",... | 54.705882 | 30.941176 |
def copy_location(new_node, old_node):
"""
Copy the source location hint (`lineno` and `col_offset`) from the
old to the new node if possible and return the new one.
"""
for attr in 'lineno', 'col_offset':
if attr in old_node._attributes and attr in new_node._attributes \
and hasa... | [
"def",
"copy_location",
"(",
"new_node",
",",
"old_node",
")",
":",
"for",
"attr",
"in",
"'lineno'",
",",
"'col_offset'",
":",
"if",
"attr",
"in",
"old_node",
".",
"_attributes",
"and",
"attr",
"in",
"new_node",
".",
"_attributes",
"and",
"hasattr",
"(",
"... | 41.2 | 12.8 |
def loop(self, timeout = 1):
"""Main loop."""
rlist = [self.sock]
wlist = []
if len(self.out_packet) > 0:
wlist.append(self.sock)
to_read, to_write, _ = select.select(rlist, wlist, [], timeout)
if len(to_read) > 0:
ret, _ = self.loop_read... | [
"def",
"loop",
"(",
"self",
",",
"timeout",
"=",
"1",
")",
":",
"rlist",
"=",
"[",
"self",
".",
"sock",
"]",
"wlist",
"=",
"[",
"]",
"if",
"len",
"(",
"self",
".",
"out_packet",
")",
">",
"0",
":",
"wlist",
".",
"append",
"(",
"self",
".",
"s... | 26.636364 | 15.454545 |
def create_eager_metrics_for_problem(problem, model_hparams):
"""See create_eager_metrics."""
metric_fns = problem.eval_metric_fns(model_hparams)
problem_hparams = problem.get_hparams(model_hparams)
target_modality = problem_hparams.modality["targets"]
weights_fn = model_hparams.weights_fn.get(
"targets... | [
"def",
"create_eager_metrics_for_problem",
"(",
"problem",
",",
"model_hparams",
")",
":",
"metric_fns",
"=",
"problem",
".",
"eval_metric_fns",
"(",
"model_hparams",
")",
"problem_hparams",
"=",
"problem",
".",
"get_hparams",
"(",
"model_hparams",
")",
"target_modali... | 48.666667 | 14.777778 |
def _draw_breakpoint_icon(self, top, painter, icon_name):
"""Draw the given breakpoint pixmap.
Args:
top (int): top of the line to draw the breakpoint icon.
painter (QPainter)
icon_name (srt): key of icon to draw (see: self.icons)
"""
rect = QRect(0, ... | [
"def",
"_draw_breakpoint_icon",
"(",
"self",
",",
"top",
",",
"painter",
",",
"icon_name",
")",
":",
"rect",
"=",
"QRect",
"(",
"0",
",",
"top",
",",
"self",
".",
"sizeHint",
"(",
")",
".",
"width",
"(",
")",
",",
"self",
".",
"sizeHint",
"(",
")",... | 36.6875 | 16.5 |
def jsonex_request(url, data, headers=None):
""" Make a request with JsonEx
:param url: URL
:type url: str
:param data: Data to POST
:type data: dict
:return: Response
:rtype: dict
:raises exc.ConnectionError: Connection error
:raises exc.ServerError: Remote server error (unknown)
... | [
"def",
"jsonex_request",
"(",
"url",
",",
"data",
",",
"headers",
"=",
"None",
")",
":",
"# Authentication?",
"url",
",",
"headers",
"=",
"_parse_authentication",
"(",
"url",
")",
"headers",
"[",
"'Content-Type'",
"]",
"=",
"'application/json'",
"# Request",
"... | 33.114286 | 19.142857 |
def from_table(fileobj=None, url='http://hgdownload.cse.ucsc.edu/goldenpath/hg19/database/knownGene.txt.gz',
parser=UCSCTable.KNOWN_GENE, mode='tx', decompress=None):
'''
UCSC Genome project provides several tables with gene coordinates (https://genome.ucsc.edu/cgi-bin/hgTables),
... | [
"def",
"from_table",
"(",
"fileobj",
"=",
"None",
",",
"url",
"=",
"'http://hgdownload.cse.ucsc.edu/goldenpath/hg19/database/knownGene.txt.gz'",
",",
"parser",
"=",
"UCSCTable",
".",
"KNOWN_GENE",
",",
"mode",
"=",
"'tx'",
",",
"decompress",
"=",
"None",
")",
":",
... | 55.917808 | 37.178082 |
def _args_for_remote(self):
"""
Generate arguments for 'terraform remote config'. Return None if
not present in configuration.
:return: list of args for 'terraform remote config' or None
:rtype: :std:term:`list`
"""
conf = self.config.get('terraform_remote_state'... | [
"def",
"_args_for_remote",
"(",
"self",
")",
":",
"conf",
"=",
"self",
".",
"config",
".",
"get",
"(",
"'terraform_remote_state'",
")",
"if",
"conf",
"is",
"None",
":",
"return",
"None",
"args",
"=",
"[",
"'-backend=%s'",
"%",
"conf",
"[",
"'backend'",
"... | 35.8 | 15.4 |
def run(self, quil_program, classical_addresses: List[int] = None,
trials=1):
"""
Run a Quil program multiple times, accumulating the values deposited in
a list of classical addresses.
:param Program quil_program: A Quil program.
:param classical_addresses: The class... | [
"def",
"run",
"(",
"self",
",",
"quil_program",
",",
"classical_addresses",
":",
"List",
"[",
"int",
"]",
"=",
"None",
",",
"trials",
"=",
"1",
")",
":",
"if",
"classical_addresses",
"is",
"None",
":",
"caddresses",
"=",
"get_classical_addresses_from_program",... | 45.121212 | 26.272727 |
def go_to_column(self, column):
"""
Moves the text cursor to given column.
:param column: Column to go to.
:type column: int
:return: Method success.
:rtype: bool
"""
cursor = self.textCursor()
cursor.setPosition(cursor.block().position() + colum... | [
"def",
"go_to_column",
"(",
"self",
",",
"column",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"cursor",
".",
"block",
"(",
")",
".",
"position",
"(",
")",
"+",
"column",
")",
"self",
".",
"setText... | 26 | 13.857143 |
def __validate(self, oid):
"""Validate and use the given id for this ObjectId.
Raises TypeError if id is not an instance of
(:class:`basestring` (:class:`str` or :class:`bytes`
in python 3), ObjectId) and InvalidId if it is not a
valid ObjectId.
:Parameters:
-... | [
"def",
"__validate",
"(",
"self",
",",
"oid",
")",
":",
"if",
"isinstance",
"(",
"oid",
",",
"ObjectId",
")",
":",
"self",
".",
"__id",
"=",
"oid",
".",
"binary",
"# bytes or unicode in python 2, str in python 3",
"elif",
"isinstance",
"(",
"oid",
",",
"stri... | 36.88 | 15.44 |
def initial_global_state(self) -> GlobalState:
"""Initialize the execution environment."""
environment = Environment(
self.callee_account,
self.caller,
self.call_data,
self.gas_price,
self.call_value,
self.origin,
code=s... | [
"def",
"initial_global_state",
"(",
"self",
")",
"->",
"GlobalState",
":",
"environment",
"=",
"Environment",
"(",
"self",
".",
"callee_account",
",",
"self",
".",
"caller",
",",
"self",
".",
"call_data",
",",
"self",
".",
"gas_price",
",",
"self",
".",
"c... | 34.142857 | 14.214286 |
def get_content_metadata(id, version, cursor):
"""Return metadata related to the content from the database."""
# Do the module lookup
args = dict(id=id, version=version)
# FIXME We are doing two queries here that can hopefully be
# condensed into one.
cursor.execute(SQL['get-module-metadat... | [
"def",
"get_content_metadata",
"(",
"id",
",",
"version",
",",
"cursor",
")",
":",
"# Do the module lookup",
"args",
"=",
"dict",
"(",
"id",
"=",
"id",
",",
"version",
"=",
"version",
")",
"# FIXME We are doing two queries here that can hopefully be",
"# condens... | 46.913043 | 20.695652 |
def compute(self):
"""
Compute a MaxSAT solution. First, the method checks whether or
not the set of hard clauses is satisfiable. If not, the method
returns ``False``. Otherwise, add soft clauses to the oracle and
call the MaxSAT algorithm (see :func:`_compute`).
... | [
"def",
"compute",
"(",
"self",
")",
":",
"if",
"self",
".",
"oracle",
".",
"solve",
"(",
")",
":",
"# hard part is satisfiable",
"# create selectors and a mapping from selectors to clause ids",
"self",
".",
"sels",
",",
"self",
".",
"vmap",
"=",
"[",
"]",
",",
... | 37.30303 | 20.636364 |
def macro_attachment_create(self, macro_id, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#create-macro-attachment"
api_path = "/api/v2/macros/{macro_id}/attachments.json"
api_path = api_path.format(macro_id=macro_id)
return self.call(api_path, method="POST", d... | [
"def",
"macro_attachment_create",
"(",
"self",
",",
"macro_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/macros/{macro_id}/attachments.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"macro_id",
"=",
"macro_id",
")",
... | 67 | 27 |
def add_to_fields(self):
'''Add this :class:`Field` to the fields of :attr:`model`.'''
meta = self.model._meta
meta.scalarfields.append(self)
if self.index:
meta.indices.append(self) | [
"def",
"add_to_fields",
"(",
"self",
")",
":",
"meta",
"=",
"self",
".",
"model",
".",
"_meta",
"meta",
".",
"scalarfields",
".",
"append",
"(",
"self",
")",
"if",
"self",
".",
"index",
":",
"meta",
".",
"indices",
".",
"append",
"(",
"self",
")"
] | 36.833333 | 12.833333 |
def create_project(self, project_name, project_des):
""" Create a project
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type project_des: string
:param project_des: the description of a proj... | [
"def",
"create_project",
"(",
"self",
",",
"project_name",
",",
"project_des",
")",
":",
"params",
"=",
"{",
"}",
"body",
"=",
"{",
"\"projectName\"",
":",
"project_name",
",",
"\"description\"",
":",
"project_des",
"}",
"body",
"=",
"six",
".",
"b",
"(",
... | 32.916667 | 22.291667 |
def open(self):
"""
Opens a WinDivert handle for the given filter.
Unless otherwise specified by flags, any packet that matches the filter will be diverted to the handle.
Diverted packets can be read by the application with receive().
The remapped function is WinDivertOpen::
... | [
"def",
"open",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_open",
":",
"raise",
"RuntimeError",
"(",
"\"WinDivert handle is already open.\"",
")",
"self",
".",
"_handle",
"=",
"windivert_dll",
".",
"WinDivertOpen",
"(",
"self",
".",
"_filter",
",",
"self",
... | 40.904762 | 23.190476 |
def declination_cooper69(dayofyear):
"""
Solar declination from Duffie & Beckman [1] and attributed to Cooper (1969)
.. warning::
Return units are radians, not degrees.
Declination can be expressed using either sine or cosine:
.. math::
\\delta = 23.45 \\sin \\left( \\frac{2 \\pi}... | [
"def",
"declination_cooper69",
"(",
"dayofyear",
")",
":",
"day_angle",
"=",
"_calculate_simple_day_angle",
"(",
"dayofyear",
")",
"dec",
"=",
"np",
".",
"deg2rad",
"(",
"23.45",
"*",
"np",
".",
"sin",
"(",
"day_angle",
"+",
"(",
"2.0",
"*",
"np",
".",
"... | 29.953488 | 26.325581 |
def shorten_string(string, max_width):
''' make limited length string in form:
"the string is very lo...(and 15 more)"
'''
string_len = len(string)
if string_len <= max_width:
return string
visible = max_width - 16 - int(log10(string_len))
# expected suffix len "...(and XXXXX more)... | [
"def",
"shorten_string",
"(",
"string",
",",
"max_width",
")",
":",
"string_len",
"=",
"len",
"(",
"string",
")",
"if",
"string_len",
"<=",
"max_width",
":",
"return",
"string",
"visible",
"=",
"max_width",
"-",
"16",
"-",
"int",
"(",
"log10",
"(",
"stri... | 37.533333 | 12.466667 |
def _connect(self):
"""
Connexion à la base XAIR
"""
try:
# On passe par Oracle Instant Client avec le TNS ORA_FULL
self.conn = cx_Oracle.connect(self._ORA_FULL)
self.cursor = self.conn.cursor()
print('XAIR: Connexion établie')
exc... | [
"def",
"_connect",
"(",
"self",
")",
":",
"try",
":",
"# On passe par Oracle Instant Client avec le TNS ORA_FULL",
"self",
".",
"conn",
"=",
"cx_Oracle",
".",
"connect",
"(",
"self",
".",
"_ORA_FULL",
")",
"self",
".",
"cursor",
"=",
"self",
".",
"conn",
".",
... | 32.846154 | 13.307692 |
def cross_goal(state):
"""
The goal function for cross solving search.
"""
centres, edges = state
for edge in edges:
if "D" not in edge.facings:
return False
if edge["D"] != centres["D"]["D"]:
return False
k = ""... | [
"def",
"cross_goal",
"(",
"state",
")",
":",
"centres",
",",
"edges",
"=",
"state",
"for",
"edge",
"in",
"edges",
":",
"if",
"\"D\"",
"not",
"in",
"edge",
".",
"facings",
":",
"return",
"False",
"if",
"edge",
"[",
"\"D\"",
"]",
"!=",
"centres",
"[",
... | 31.428571 | 9.857143 |
def query_row(stmt, args=(), factory=None):
"""
Execute a query. Returns the first row of the result set, or `None`.
"""
for row in query(stmt, args, factory):
return row
return None | [
"def",
"query_row",
"(",
"stmt",
",",
"args",
"=",
"(",
")",
",",
"factory",
"=",
"None",
")",
":",
"for",
"row",
"in",
"query",
"(",
"stmt",
",",
"args",
",",
"factory",
")",
":",
"return",
"row",
"return",
"None"
] | 29.142857 | 12 |
def is_reachable_host(entity_name):
'''
Returns a bool telling if the entity name is a reachable host (IPv4/IPv6/FQDN/etc).
:param hostname:
:return:
'''
try:
assert type(socket.getaddrinfo(entity_name, 0, 0, 0, 0)) == list
ret = True
except socket.gaierror:
ret = Fal... | [
"def",
"is_reachable_host",
"(",
"entity_name",
")",
":",
"try",
":",
"assert",
"type",
"(",
"socket",
".",
"getaddrinfo",
"(",
"entity_name",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
")",
"==",
"list",
"ret",
"=",
"True",
"except",
"socket",
"."... | 25.076923 | 27.076923 |
def prepare(self, rule):
"""
Parse and/or compile given rule into rule tree.
:param rule: Filtering grammar rule.
:return: Parsed and/or compiled rule.
"""
if self.parser:
rule = self.parser.parse(rule)
if self.compiler:
rule = self.compil... | [
"def",
"prepare",
"(",
"self",
",",
"rule",
")",
":",
"if",
"self",
".",
"parser",
":",
"rule",
"=",
"self",
".",
"parser",
".",
"parse",
"(",
"rule",
")",
"if",
"self",
".",
"compiler",
":",
"rule",
"=",
"self",
".",
"compiler",
".",
"compile",
... | 28.75 | 11.75 |
def load_plugins(self, args=None):
"""Load all plugins in the 'plugins' folder."""
for item in os.listdir(plugins_path):
if (item.startswith(self.header) and
item.endswith(".py") and
item != (self.header + "plugin.py")):
# Load the plug... | [
"def",
"load_plugins",
"(",
"self",
",",
"args",
"=",
"None",
")",
":",
"for",
"item",
"in",
"os",
".",
"listdir",
"(",
"plugins_path",
")",
":",
"if",
"(",
"item",
".",
"startswith",
"(",
"self",
".",
"header",
")",
"and",
"item",
".",
"endswith",
... | 45 | 14.916667 |
def delete_lambda(awsclient, function_name, events=None, delete_logs=False):
"""Delete a lambda function.
:param awsclient:
:param function_name:
:param events: list of events
:param delete_logs:
:return: exit_code
"""
if events is not None:
unwire(awsclient, events, function_na... | [
"def",
"delete_lambda",
"(",
"awsclient",
",",
"function_name",
",",
"events",
"=",
"None",
",",
"delete_logs",
"=",
"False",
")",
":",
"if",
"events",
"is",
"not",
"None",
":",
"unwire",
"(",
"awsclient",
",",
"events",
",",
"function_name",
",",
"alias_n... | 35.25 | 19.8 |
def element_to_objects(
element: etree.ElementTree, sender: str, sender_key_fetcher:Callable[[str], str]=None, user: UserType =None,
) -> List:
"""Transform an Element to a list of entities recursively.
Possible child entities are added to each entity ``_children`` list.
:param tree: Element
:... | [
"def",
"element_to_objects",
"(",
"element",
":",
"etree",
".",
"ElementTree",
",",
"sender",
":",
"str",
",",
"sender_key_fetcher",
":",
"Callable",
"[",
"[",
"str",
"]",
",",
"str",
"]",
"=",
"None",
",",
"user",
":",
"UserType",
"=",
"None",
",",
")... | 38.216667 | 20.466667 |
def predict_unseen(self, times, config):
"""
predict the loss of an unseen configuration
Parameters:
-----------
times: numpy array
times where to predict the loss
config: numpy array
the numerical representation of th... | [
"def",
"predict_unseen",
"(",
"self",
",",
"times",
",",
"config",
")",
":",
"assert",
"np",
".",
"all",
"(",
"times",
">",
"0",
")",
"and",
"np",
".",
"all",
"(",
"times",
"<=",
"self",
".",
"max_num_epochs",
")",
"x",
"=",
"np",
".",
"array",
"... | 26.758621 | 20.206897 |
def change_id(self, new_id_for_id):
""" Changes the id of the specified motors (each id must be unique on the bus). """
if len(set(new_id_for_id.values())) < len(new_id_for_id):
raise ValueError('each id must be unique.')
for new_id in new_id_for_id.itervalues():
if self... | [
"def",
"change_id",
"(",
"self",
",",
"new_id_for_id",
")",
":",
"if",
"len",
"(",
"set",
"(",
"new_id_for_id",
".",
"values",
"(",
")",
")",
")",
"<",
"len",
"(",
"new_id_for_id",
")",
":",
"raise",
"ValueError",
"(",
"'each id must be unique.'",
")",
"... | 45.722222 | 17.777778 |
def commitVCS(self, tag=None):
''' Commit the current working directory state (or do nothing if the
working directory is not version controlled)
'''
if not self.vcs:
return
self.vcs.commit(message='version %s' % tag, tag=tag) | [
"def",
"commitVCS",
"(",
"self",
",",
"tag",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"vcs",
":",
"return",
"self",
".",
"vcs",
".",
"commit",
"(",
"message",
"=",
"'version %s'",
"%",
"tag",
",",
"tag",
"=",
"tag",
")"
] | 39.285714 | 21.285714 |
def get_char_type(ch):
"""
0, 汉字
1, 英文字母
2. 数字
3. 其他
"""
if re.match(en_p, ch):
return 1
elif re.match("\d+", ch):
return 2
elif re.match(re_han, ch):
return 3
else:
return 4 | [
"def",
"get_char_type",
"(",
"ch",
")",
":",
"if",
"re",
".",
"match",
"(",
"en_p",
",",
"ch",
")",
":",
"return",
"1",
"elif",
"re",
".",
"match",
"(",
"\"\\d+\"",
",",
"ch",
")",
":",
"return",
"2",
"elif",
"re",
".",
"match",
"(",
"re_han",
... | 15.466667 | 20.133333 |
def get_decoded_jwt(request):
"""
Grab jwt from jwt cookie in request if possible.
Returns a decoded jwt dict if it can be found.
Returns None if the jwt is not found.
"""
jwt_cookie = request.COOKIES.get(jwt_cookie_name(), None)
if not jwt_cookie:
return None
return jwt_decode... | [
"def",
"get_decoded_jwt",
"(",
"request",
")",
":",
"jwt_cookie",
"=",
"request",
".",
"COOKIES",
".",
"get",
"(",
"jwt_cookie_name",
"(",
")",
",",
"None",
")",
"if",
"not",
"jwt_cookie",
":",
"return",
"None",
"return",
"jwt_decode_handler",
"(",
"jwt_cook... | 27.416667 | 14.583333 |
def quoted_insert(self, e): # (C-q or C-v)
u'''Add the next character typed to the line verbatim. This is how to
insert key sequences like C-q, for example.'''
e = self.console.getkeypress()
self.insert_text(e.char) | [
"def",
"quoted_insert",
"(",
"self",
",",
"e",
")",
":",
"# (C-q or C-v)\r",
"e",
"=",
"self",
".",
"console",
".",
"getkeypress",
"(",
")",
"self",
".",
"insert_text",
"(",
"e",
".",
"char",
")"
] | 49.4 | 13 |
def export_agg_losses(ekey, dstore):
"""
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
dskey = ekey[0]
oq = dstore['oqparam']
dt = oq.loss_dt()
name, value, tags = _get_data(dstore, dskey, oq.hazard_stats().items())
writer = writers.Csv... | [
"def",
"export_agg_losses",
"(",
"ekey",
",",
"dstore",
")",
":",
"dskey",
"=",
"ekey",
"[",
"0",
"]",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"dt",
"=",
"oq",
".",
"loss_dt",
"(",
")",
"name",
",",
"value",
",",
"tags",
"=",
"_get_data",
"(",
... | 40.884615 | 12.038462 |
def loads(cls, json_text, schema=None):
"""
:param str json_text: json text to be parse
:param voluptuous.Schema schema: JSON schema.
:return: Dictionary storing the parse results of JSON
:rtype: dictionary
:raises ImportError:
:raises RuntimeError:
:raise... | [
"def",
"loads",
"(",
"cls",
",",
"json_text",
",",
"schema",
"=",
"None",
")",
":",
"try",
":",
"json_text",
"=",
"json_text",
".",
"decode",
"(",
"\"ascii\"",
")",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"dict_json",
"=",
"json",
".",
"lo... | 29.428571 | 18.142857 |
def head_and_tail_print(self, n=5):
"""Display the first and last n elements of a DataFrame."""
from IPython import display
display.display(display.HTML(self._head_and_tail_table(n))) | [
"def",
"head_and_tail_print",
"(",
"self",
",",
"n",
"=",
"5",
")",
":",
"from",
"IPython",
"import",
"display",
"display",
".",
"display",
"(",
"display",
".",
"HTML",
"(",
"self",
".",
"_head_and_tail_table",
"(",
"n",
")",
")",
")"
] | 51 | 9.25 |
def execution_duration(self):
"""
Returns total BMDS execution time, in seconds.
"""
duration = None
if self.execution_start and self.execution_end:
delta = self.execution_end - self.execution_start
duration = delta.total_seconds()
return duration | [
"def",
"execution_duration",
"(",
"self",
")",
":",
"duration",
"=",
"None",
"if",
"self",
".",
"execution_start",
"and",
"self",
".",
"execution_end",
":",
"delta",
"=",
"self",
".",
"execution_end",
"-",
"self",
".",
"execution_start",
"duration",
"=",
"de... | 34.555556 | 11 |
def ask_overwrite(dest):
"""Check if file *dest* exists. If 'True', asks if the user wants
to overwrite it (just remove the file for later overwrite).
"""
msg = "File '{}' already exists. Overwrite file?".format(dest)
if os.path.exists(dest):
if yes_no_query(msg):
os.remove(dest... | [
"def",
"ask_overwrite",
"(",
"dest",
")",
":",
"msg",
"=",
"\"File '{}' already exists. Overwrite file?\"",
".",
"format",
"(",
"dest",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
":",
"if",
"yes_no_query",
"(",
"msg",
")",
":",
"os",
... | 33.909091 | 15.909091 |
def is_subfeature_of (parent_property, f):
""" Return true iff f is an ordinary subfeature of the parent_property's
feature, or if f is a subfeature of the parent_property's feature
specific to the parent_property's value.
"""
if __debug__:
from .property import Property
asse... | [
"def",
"is_subfeature_of",
"(",
"parent_property",
",",
"f",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"property",
"import",
"Property",
"assert",
"isinstance",
"(",
"parent_property",
",",
"Property",
")",
"assert",
"isinstance",
"(",
"f",
",",
"Feature"... | 25.814815 | 20.666667 |
def style(self, value):
"""
Setter for **self.__style** attribute.
:param value: Attribute value.
:type value: Style
"""
if value is not None:
assert type(value) is Style, "'{0}' attribute: '{1}' type is not 'Style'!".format("style", value)
style... | [
"def",
"style",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"assert",
"type",
"(",
"value",
")",
"is",
"Style",
",",
"\"'{0}' attribute: '{1}' type is not 'Style'!\"",
".",
"format",
"(",
"\"style\"",
",",
"value",
")",
"s... | 30.733333 | 17.266667 |
def pubmed(self, pubmedid=None, hgnc_symbol=None, hgnc_identifier=None, limit=None, as_df=False):
"""Method to query :class:`.models.PubMed` objects in database
:param pubmedid: alias symbol(s)
:type pubmedid: str or tuple(str) or None
:param hgnc_symbol: HGNC symbol(s)
:type h... | [
"def",
"pubmed",
"(",
"self",
",",
"pubmedid",
"=",
"None",
",",
"hgnc_symbol",
"=",
"None",
",",
"hgnc_identifier",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"as_df",
"=",
"False",
")",
":",
"q",
"=",
"self",
".",
"session",
".",
"query",
"(",
... | 39.025 | 24.7 |
def _isdst(dt):
"""Check if date is in dst.
"""
if type(dt) == datetime.date:
dt = datetime.datetime.combine(dt, datetime.datetime.min.time())
dtc = dt.replace(year=datetime.datetime.now().year)
if time.localtime(dtc.timestamp()).tm_isdst == 1:
return True
return False | [
"def",
"_isdst",
"(",
"dt",
")",
":",
"if",
"type",
"(",
"dt",
")",
"==",
"datetime",
".",
"date",
":",
"dt",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"dt",
",",
"datetime",
".",
"datetime",
".",
"min",
".",
"time",
"(",
")",
")",
... | 33.444444 | 15.222222 |
def process_row(cls, data, column_map):
"""Process the row data from Rekall"""
row = {}
for key,value in data.iteritems():
if not value:
value = '-'
elif isinstance(value, list):
value = value[1]
elif isinstance(... | [
"def",
"process_row",
"(",
"cls",
",",
"data",
",",
"column_map",
")",
":",
"row",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"data",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"value",
":",
"value",
"=",
"'-'",
"elif",
"isinstance",
"(",
... | 41.5 | 13.5 |
async def recv(self):
"""
Receive the next :class:`~av.audio.frame.AudioFrame`.
The base implementation just reads silence, subclass
:class:`AudioStreamTrack` to provide a useful implementation.
"""
if self.readyState != 'live':
raise MediaStreamError
... | [
"async",
"def",
"recv",
"(",
"self",
")",
":",
"if",
"self",
".",
"readyState",
"!=",
"'live'",
":",
"raise",
"MediaStreamError",
"sample_rate",
"=",
"8000",
"samples",
"=",
"int",
"(",
"AUDIO_PTIME",
"*",
"sample_rate",
")",
"if",
"hasattr",
"(",
"self",
... | 33.892857 | 16.178571 |
def refresh_styles(self):
"""Load all available styles"""
import matplotlib.pyplot as plt
self.colours = {}
for style in plt.style.available:
try:
style_colours = plt.style.library[style]['axes.prop_cycle']
self.colours[style] = [c['color'] fo... | [
"def",
"refresh_styles",
"(",
"self",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"self",
".",
"colours",
"=",
"{",
"}",
"for",
"style",
"in",
"plt",
".",
"style",
".",
"available",
":",
"try",
":",
"style_colours",
"=",
"plt",
".",
... | 34 | 19.9375 |
def det_optimal_snrsq(self, det):
"""Returns the opitmal SNR squared in the given detector.
Parameters
----------
det : str
The name of the detector.
Returns
-------
float :
The opimtal SNR squared.
"""
# try to get it fro... | [
"def",
"det_optimal_snrsq",
"(",
"self",
",",
"det",
")",
":",
"# try to get it from current stats",
"try",
":",
"return",
"getattr",
"(",
"self",
".",
"_current_stats",
",",
"'{}_optimal_snrsq'",
".",
"format",
"(",
"det",
")",
")",
"except",
"AttributeError",
... | 30.714286 | 18.714286 |
def set_dicts(self, word_dict, char_dict):
"""Set with custom dictionaries.
:param word_dict: The word dictionary.
:param char_dict: The character dictionary.
"""
self.word_dict = word_dict
self.char_dict = char_dict | [
"def",
"set_dicts",
"(",
"self",
",",
"word_dict",
",",
"char_dict",
")",
":",
"self",
".",
"word_dict",
"=",
"word_dict",
"self",
".",
"char_dict",
"=",
"char_dict"
] | 32.25 | 8.875 |
def interpolations_to_summary(sample_ind, interpolations, first_frame,
last_frame, hparams, decode_hp):
"""Converts interpolated frames into tf summaries.
The summaries consists of:
1. Image summary corresponding to the first frame.
2. Image summary corresponding to the last f... | [
"def",
"interpolations_to_summary",
"(",
"sample_ind",
",",
"interpolations",
",",
"first_frame",
",",
"last_frame",
",",
"hparams",
",",
"decode_hp",
")",
":",
"parent_tag",
"=",
"\"sample_%d\"",
"%",
"sample_ind",
"frame_shape",
"=",
"hparams",
".",
"problem",
"... | 40.410256 | 14.641026 |
def _parse_members(self, contents, module):
"""Extracts any module-level members from the code. They must appear before
any type declalations."""
#We need to get hold of the text before the module's main CONTAINS keyword
#so that we don't find variables from executables and claim them as... | [
"def",
"_parse_members",
"(",
"self",
",",
"contents",
",",
"module",
")",
":",
"#We need to get hold of the text before the module's main CONTAINS keyword",
"#so that we don't find variables from executables and claim them as",
"#belonging to the module.",
"icontains",
"=",
"module",
... | 47.829787 | 22.255319 |
def set(self, model, property_name, value):
"""
Set model property to value. Use setter if possible.
:param model: model object or dict
:param property_name: str, name on the model
:param value: mixed, a value to set
:return: None
"""
if type(model) is dic... | [
"def",
"set",
"(",
"self",
",",
"model",
",",
"property_name",
",",
"value",
")",
":",
"if",
"type",
"(",
"model",
")",
"is",
"dict",
":",
"model",
"[",
"property_name",
"]",
"=",
"value",
"elif",
"hasattr",
"(",
"model",
",",
"'set_'",
"+",
"propert... | 34.722222 | 11.277778 |
def filter(self, relation_id=None, duedate__lt=None, duedate__gte=None,
**kwargs):
"""
A common query would be duedate__lt=date(2015, 1, 1) to get all
Receivables that are due in 2014 and earlier.
"""
if relation_id is not None:
# Filter by (relation) a... | [
"def",
"filter",
"(",
"self",
",",
"relation_id",
"=",
"None",
",",
"duedate__lt",
"=",
"None",
",",
"duedate__gte",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"relation_id",
"is",
"not",
"None",
":",
"# Filter by (relation) account_id. There doesn'... | 43.896552 | 20.517241 |
def default_formatter(error):
"""Escape the error, and wrap it in a span with class ``error-message``"""
quoted = formencode.htmlfill.escape_formatter(error)
return u'<span class="error-message">{0}</span>'.format(quoted) | [
"def",
"default_formatter",
"(",
"error",
")",
":",
"quoted",
"=",
"formencode",
".",
"htmlfill",
".",
"escape_formatter",
"(",
"error",
")",
"return",
"u'<span class=\"error-message\">{0}</span>'",
".",
"format",
"(",
"quoted",
")"
] | 57.5 | 13.5 |
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3):
"""
Read the data encoding the ValidationInformation structure and decode
it into its constituent parts.
Args:
input_buffer (stream): A data stream containing encoded object
data, supporti... | [
"def",
"read",
"(",
"self",
",",
"input_buffer",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_3",
")",
":",
"if",
"kmip_version",
"<",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_3",
":",
"raise",
"exceptions",
".",
"VersionNotSupported",
... | 37.837989 | 20.206704 |
def clean_source_index(self):
"""
Cleanup broken symbolic links in the local source distribution index.
The purpose of this method requires some context to understand. Let me
preface this by stating that I realize I'm probably overcomplicating
things, but I like to preserve forw... | [
"def",
"clean_source_index",
"(",
"self",
")",
":",
"cleanup_timer",
"=",
"Timer",
"(",
")",
"cleanup_counter",
"=",
"0",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"config",
".",
"source_index",
")",
":",
"pathname",
"=",
"os",
".",
... | 57.571429 | 29.730159 |
def rename_motifs(motifs, stats=None):
"""Rename motifs to GimmeMotifs_1..GimmeMotifs_N.
If stats object is passed, stats will be copied."""
final_motifs = []
for i, motif in enumerate(motifs):
old = str(motif)
motif.id = "GimmeMotifs_{}".format(i + 1)
final_motifs.append(mo... | [
"def",
"rename_motifs",
"(",
"motifs",
",",
"stats",
"=",
"None",
")",
":",
"final_motifs",
"=",
"[",
"]",
"for",
"i",
",",
"motif",
"in",
"enumerate",
"(",
"motifs",
")",
":",
"old",
"=",
"str",
"(",
"motif",
")",
"motif",
".",
"id",
"=",
"\"Gimme... | 29.3125 | 14.6875 |
def as_labeller(x, default=label_value, multi_line=True):
"""
Coerse to labeller function
Parameters
----------
x : function | dict
Object to coerce
default : function | str
Default labeller. If it is a string,
it should be the name of one the labelling
functions... | [
"def",
"as_labeller",
"(",
"x",
",",
"default",
"=",
"label_value",
",",
"multi_line",
"=",
"True",
")",
":",
"if",
"x",
"is",
"None",
":",
"x",
"=",
"default",
"# One of the labelling functions as string",
"with",
"suppress",
"(",
"KeyError",
",",
"TypeError"... | 27.574074 | 15.907407 |
def set_version(self, version, force=True):
""" Sets the version name for the current state of repo """
if version in self.versions:
self._version = version
if 'working' in self.repo.branch().stdout:
if force:
logger.info('Found working branch... | [
"def",
"set_version",
"(",
"self",
",",
"version",
",",
"force",
"=",
"True",
")",
":",
"if",
"version",
"in",
"self",
".",
"versions",
":",
"self",
".",
"_version",
"=",
"version",
"if",
"'working'",
"in",
"self",
".",
"repo",
".",
"branch",
"(",
")... | 49.222222 | 25.944444 |
def _work(self, backend, package, ident='', log=True):
"""
Centralized task worker code. Used internally, see send_signal() and
work() for the external interfaces.
"""
num = self._sending_task(backend)
if log:
self.log(INFO, 'Starting %s backend task #%s (%s)... | [
"def",
"_work",
"(",
"self",
",",
"backend",
",",
"package",
",",
"ident",
"=",
"''",
",",
"log",
"=",
"True",
")",
":",
"num",
"=",
"self",
".",
"_sending_task",
"(",
"backend",
")",
"if",
"log",
":",
"self",
".",
"log",
"(",
"INFO",
",",
"'Star... | 35.4375 | 14.375 |
def sixteen_oscillator_two_stimulated_ensembles_grid():
"Not accurate false due to spikes are observed"
parameters = legion_parameters();
parameters.teta_x = -1.1;
template_dynamic_legion(16, 2000, 1500, conn_type = conn_type.GRID_FOUR, params = parameters, stimulus = [1, 1, 1, 0,
... | [
"def",
"sixteen_oscillator_two_stimulated_ensembles_grid",
"(",
")",
":",
"parameters",
"=",
"legion_parameters",
"(",
")",
"parameters",
".",
"teta_x",
"=",
"-",
"1.1",
"template_dynamic_legion",
"(",
"16",
",",
"2000",
",",
"1500",
",",
"conn_type",
"=",
"conn_t... | 83.5 | 46.5 |
def send_query(self, ID, methodname, *args, **kwargs):
"""将调用请求的ID,方法名,参数包装为请求数据后编码为字节串发送出去.
Parameters:
ID (str): - 任务ID
methodname (str): - 要调用的方法名
args (Any): - 要调用的方法的位置参数
kwargs (Any): - 要调用的方法的关键字参数
Return:
(bool): - 准确地说没有错误就会... | [
"def",
"send_query",
"(",
"self",
",",
"ID",
",",
"methodname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"self",
".",
"_make_query",
"(",
"ID",
",",
"methodname",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
"... | 25.941176 | 17.235294 |
def map(cls, x, palette, limits, na_value=None):
"""
Map values to a discrete palette
Parameters
----------
palette : callable ``f(x)``
palette to use
x : array_like
Continuous values to scale
na_value : object
Value to use for... | [
"def",
"map",
"(",
"cls",
",",
"x",
",",
"palette",
",",
"limits",
",",
"na_value",
"=",
"None",
")",
":",
"n",
"=",
"len",
"(",
"limits",
")",
"pal",
"=",
"palette",
"(",
"n",
")",
"[",
"match",
"(",
"x",
",",
"limits",
")",
"]",
"try",
":",... | 25.307692 | 15.692308 |
def start(name, call=None):
'''
Start a node
CLI Examples:
.. code-block:: bash
salt-cloud -a start myinstance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The stop action must be called with -a or --action.'
)
log.info('Starting node %s', name... | [
"def",
"start",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The stop action must be called with -a or --action.'",
")",
"log",
".",
"info",
"(",
"'Starting node %s'",
",",
"name",
"... | 19.75 | 22.833333 |
def download_structure(inputpdbid):
"""Given a PDB ID, downloads the corresponding PDB structure.
Checks for validity of ID and handles error while downloading.
Returns the path of the downloaded file."""
try:
if len(inputpdbid) != 4 or extract_pdbid(inputpdbid.lower()) == 'UnknownProtein':
... | [
"def",
"download_structure",
"(",
"inputpdbid",
")",
":",
"try",
":",
"if",
"len",
"(",
"inputpdbid",
")",
"!=",
"4",
"or",
"extract_pdbid",
"(",
"inputpdbid",
".",
"lower",
"(",
")",
")",
"==",
"'UnknownProtein'",
":",
"sysexit",
"(",
"3",
",",
"'Invali... | 49.647059 | 19.882353 |
def add(self, title, obj, **kwargs):
"""
Add a title
:param title: str: The title of the menu
:param obj: class or method
:param kwargs:
:return:
"""
is_class = inspect.isclass(obj)
self._push(title=title,
view=obj,
... | [
"def",
"add",
"(",
"self",
",",
"title",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"is_class",
"=",
"inspect",
".",
"isclass",
"(",
"obj",
")",
"self",
".",
"_push",
"(",
"title",
"=",
"title",
",",
"view",
"=",
"obj",
",",
"class_name",
"="... | 31.928571 | 11.642857 |
def transfer_and_wait(
self,
registry_address: PaymentNetworkID,
token_address: TokenAddress,
amount: TokenAmount,
target: Address,
identifier: PaymentID = None,
transfer_timeout: int = None,
secret: Secret = None,
... | [
"def",
"transfer_and_wait",
"(",
"self",
",",
"registry_address",
":",
"PaymentNetworkID",
",",
"token_address",
":",
"TokenAddress",
",",
"amount",
":",
"TokenAmount",
",",
"target",
":",
"Address",
",",
"identifier",
":",
"PaymentID",
"=",
"None",
",",
"transf... | 34.6 | 11.52 |
def smart_import(mpath):
"""Given a path smart_import will import the module and return the attr reffered to."""
try:
rest = __import__(mpath)
except ImportError:
split = mpath.split('.')
rest = smart_import('.'.join(split[:-1]))
rest = getattr(rest, split[-1])
return res... | [
"def",
"smart_import",
"(",
"mpath",
")",
":",
"try",
":",
"rest",
"=",
"__import__",
"(",
"mpath",
")",
"except",
"ImportError",
":",
"split",
"=",
"mpath",
".",
"split",
"(",
"'.'",
")",
"rest",
"=",
"smart_import",
"(",
"'.'",
".",
"join",
"(",
"s... | 34.777778 | 12.888889 |
def delete(self, order_id, data=None):
"""Cancel order and return the order object.
Deleting an order causes the order status to change to canceled.
The updated order object is returned.
"""
if not order_id or not order_id.startswith(self.RESOURCE_ID_PREFIX):
raise I... | [
"def",
"delete",
"(",
"self",
",",
"order_id",
",",
"data",
"=",
"None",
")",
":",
"if",
"not",
"order_id",
"or",
"not",
"order_id",
".",
"startswith",
"(",
"self",
".",
"RESOURCE_ID_PREFIX",
")",
":",
"raise",
"IdentifierError",
"(",
"\"Invalid order ID: '{... | 46.461538 | 19.307692 |
def most_frequent(self, k, inplace=False):
"""Only most frequent k words to be included in the embeddings."""
vocabulary = self.vocabulary.most_frequent(k)
vectors = np.asarray([self[w] for w in vocabulary])
if inplace:
self.vocabulary = vocabulary
self.vectors = vectors
return self
... | [
"def",
"most_frequent",
"(",
"self",
",",
"k",
",",
"inplace",
"=",
"False",
")",
":",
"vocabulary",
"=",
"self",
".",
"vocabulary",
".",
"most_frequent",
"(",
"k",
")",
"vectors",
"=",
"np",
".",
"asarray",
"(",
"[",
"self",
"[",
"w",
"]",
"for",
... | 41.111111 | 12.444444 |
def __deserialize_primitive(self, data, klass):
"""Deserializes string to primitive type.
:param data: str.
:param klass: class literal.
:return: int, long, float, str, bool.
"""
try:
return klass(data)
except UnicodeEncodeError:
return s... | [
"def",
"__deserialize_primitive",
"(",
"self",
",",
"data",
",",
"klass",
")",
":",
"try",
":",
"return",
"klass",
"(",
"data",
")",
"except",
"UnicodeEncodeError",
":",
"return",
"six",
".",
"text_type",
"(",
"data",
")",
"except",
"TypeError",
":",
"retu... | 26.785714 | 13.5 |
def histogram(self, key, **dims):
"""Adds histogram with dimensions to the registry"""
return super(MetricsRegistry, self).histogram(
self.metadata.register(key, **dims)) | [
"def",
"histogram",
"(",
"self",
",",
"key",
",",
"*",
"*",
"dims",
")",
":",
"return",
"super",
"(",
"MetricsRegistry",
",",
"self",
")",
".",
"histogram",
"(",
"self",
".",
"metadata",
".",
"register",
"(",
"key",
",",
"*",
"*",
"dims",
")",
")"
... | 48.75 | 7.25 |
def parse_single(str_):
"""
Very simple parser to parse expressions represent some single values.
:param str_: a string to parse
:return: Int | Bool | String
>>> parse_single(None)
''
>>> parse_single("0")
0
>>> parse_single("123")
123
>>> parse_single("True")
True
... | [
"def",
"parse_single",
"(",
"str_",
")",
":",
"if",
"str_",
"is",
"None",
":",
"return",
"''",
"str_",
"=",
"str_",
".",
"strip",
"(",
")",
"if",
"not",
"str_",
":",
"return",
"''",
"if",
"BOOL_PATTERN",
".",
"match",
"(",
"str_",
")",
"is",
"not",... | 20.613636 | 21.159091 |
def generate_tags_multiple_files_strings(input_files, ns, tag, ignore_tags):
"""
Creates stringified xml output of elements with certain tag.
"""
for el in generate_tags_multiple_files(input_files, tag, ignore_tags, ns):
yield formatting.string_and_clear(el, ns) | [
"def",
"generate_tags_multiple_files_strings",
"(",
"input_files",
",",
"ns",
",",
"tag",
",",
"ignore_tags",
")",
":",
"for",
"el",
"in",
"generate_tags_multiple_files",
"(",
"input_files",
",",
"tag",
",",
"ignore_tags",
",",
"ns",
")",
":",
"yield",
"formatti... | 46.833333 | 17.833333 |
def generate_session_id(secret_key=settings.secret_key_bytes(), signed=settings.sign_sessions()):
"""Generate a random session ID.
Typically, each browser tab connected to a Bokeh application
has its own session ID. In production deployments of a Bokeh
app, session IDs should be random and unguessable... | [
"def",
"generate_session_id",
"(",
"secret_key",
"=",
"settings",
".",
"secret_key_bytes",
"(",
")",
",",
"signed",
"=",
"settings",
".",
"sign_sessions",
"(",
")",
")",
":",
"secret_key",
"=",
"_ensure_bytes",
"(",
"secret_key",
")",
"if",
"signed",
":",
"#... | 47.724138 | 26.103448 |
def purge_queue(self, vhost, name):
"""
Purge all messages from a single queue. This is a convenience method
so you aren't forced to supply a list containing a single tuple to
the purge_queues method.
:param string vhost: The vhost of the queue being purged.
:param strin... | [
"def",
"purge_queue",
"(",
"self",
",",
"vhost",
",",
"name",
")",
":",
"vhost",
"=",
"quote",
"(",
"vhost",
",",
"''",
")",
"name",
"=",
"quote",
"(",
"name",
",",
"''",
")",
"path",
"=",
"Client",
".",
"urls",
"[",
"'purge_queue'",
"]",
"%",
"(... | 36.466667 | 17.8 |
def isoline_vmag(hemi, isolines=None, surface='midgray', min_length=2, **kw):
'''
isoline_vmag(hemi) calculates the visual magnification function f using the default set of
iso-lines (as returned by neuropythy.vision.visual_isolines()). The hemi argument may
alternately be a mesh object.
isoline... | [
"def",
"isoline_vmag",
"(",
"hemi",
",",
"isolines",
"=",
"None",
",",
"surface",
"=",
"'midgray'",
",",
"min_length",
"=",
"2",
",",
"*",
"*",
"kw",
")",
":",
"from",
"neuropythy",
".",
"util",
"import",
"(",
"curry",
",",
"zinv",
")",
"from",
"neur... | 63.5 | 29.62 |
def send(self, sock, msg):
"""Send ``msg`` to destination ``sock``."""
data = pickle.dumps(msg)
buf = struct.pack('>I', len(data)) + data
sock.sendall(buf) | [
"def",
"send",
"(",
"self",
",",
"sock",
",",
"msg",
")",
":",
"data",
"=",
"pickle",
".",
"dumps",
"(",
"msg",
")",
"buf",
"=",
"struct",
".",
"pack",
"(",
"'>I'",
",",
"len",
"(",
"data",
")",
")",
"+",
"data",
"sock",
".",
"sendall",
"(",
... | 33.4 | 10 |
def get_by_id(self, reply_id):
'''
Get the reply by id.
'''
reply = MReply.get_by_uid(reply_id)
logger.info('get_reply: {0}'.format(reply_id))
self.render('misc/reply/show_reply.html',
reply=reply,
username=reply.user_name,
... | [
"def",
"get_by_id",
"(",
"self",
",",
"reply_id",
")",
":",
"reply",
"=",
"MReply",
".",
"get_by_uid",
"(",
"reply_id",
")",
"logger",
".",
"info",
"(",
"'get_reply: {0}'",
".",
"format",
"(",
"reply_id",
")",
")",
"self",
".",
"render",
"(",
"'misc/repl... | 31.933333 | 12.6 |
def confirm(question: str, default: bool = True) -> bool:
"""
Requests confirmation of the specified question and returns that result
:param question:
The question to print to the console for the confirmation
:param default:
The default value if the user hits enter without entering a va... | [
"def",
"confirm",
"(",
"question",
":",
"str",
",",
"default",
":",
"bool",
"=",
"True",
")",
"->",
"bool",
":",
"result",
"=",
"input",
"(",
"'{question} [{yes}/{no}]:'",
".",
"format",
"(",
"question",
"=",
"question",
",",
"yes",
"=",
"'(Y)'",
"if",
... | 27.318182 | 21.227273 |
def CheckHost(host_data,
os_name=None,
cpe=None,
labels=None,
exclude_checks=None,
restrict_checks=None):
"""Perform all checks on a host using acquired artifacts.
Checks are selected based on the artifacts available and the host attributes
(e... | [
"def",
"CheckHost",
"(",
"host_data",
",",
"os_name",
"=",
"None",
",",
"cpe",
"=",
"None",
",",
"labels",
"=",
"None",
",",
"exclude_checks",
"=",
"None",
",",
"restrict_checks",
"=",
"None",
")",
":",
"# Get knowledgebase, os_name from hostdata",
"kb",
"=",
... | 33.288462 | 22.173077 |
def discard(self, pid=None):
"""Discard deposit changes.
#. The signal :data:`invenio_records.signals.before_record_update` is
sent before the edit execution.
#. It restores the last published version.
#. The following meta information are saved inside the deposit:
... | [
"def",
"discard",
"(",
"self",
",",
"pid",
"=",
"None",
")",
":",
"pid",
"=",
"pid",
"or",
"self",
".",
"pid",
"with",
"db",
".",
"session",
".",
"begin_nested",
"(",
")",
":",
"before_record_update",
".",
"send",
"(",
"current_app",
".",
"_get_current... | 32.275 | 21.475 |
def call(cmd_args, suppress_output=False):
""" Call an arbitary command and return the exit value, stdout, and stderr as a tuple
Command can be passed in as either a string or iterable
>>> result = call('hatchery', suppress_output=True)
>>> result.exitval
0
>>> result = call(['hatchery', 'notr... | [
"def",
"call",
"(",
"cmd_args",
",",
"suppress_output",
"=",
"False",
")",
":",
"if",
"not",
"funcy",
".",
"is_list",
"(",
"cmd_args",
")",
"and",
"not",
"funcy",
".",
"is_tuple",
"(",
"cmd_args",
")",
":",
"cmd_args",
"=",
"shlex",
".",
"split",
"(",
... | 38.85 | 20.15 |
def _StructPackDecoder(wire_type, format):
"""Return a constructor for a decoder for a fixed-width field.
Args:
wire_type: The field's wire type.
format: The format string to pass to struct.unpack().
"""
value_size = struct.calcsize(format)
local_unpack = struct.unpack
# Reusing _SimpleDeco... | [
"def",
"_StructPackDecoder",
"(",
"wire_type",
",",
"format",
")",
":",
"value_size",
"=",
"struct",
".",
"calcsize",
"(",
"format",
")",
"local_unpack",
"=",
"struct",
".",
"unpack",
"# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but",
"# not ... | 34.73913 | 19.217391 |
def confirm_project_avatar(self, project, cropping_properties):
"""Confirm the temporary avatar image previously uploaded with the specified cropping.
After a successful registry with :py:meth:`create_temp_project_avatar`, use this method to confirm the avatar
for use. The final avatar can be a... | [
"def",
"confirm_project_avatar",
"(",
"self",
",",
"project",
",",
"cropping_properties",
")",
":",
"data",
"=",
"cropping_properties",
"url",
"=",
"self",
".",
"_get_url",
"(",
"'project/'",
"+",
"project",
"+",
"'/avatar'",
")",
"r",
"=",
"self",
".",
"_se... | 52.470588 | 31.117647 |
def create_git_tag(self, tag, message, object, type, tagger=github.GithubObject.NotSet):
"""
:calls: `POST /repos/:owner/:repo/git/tags <http://developer.github.com/v3/git/tags>`_
:param tag: string
:param message: string
:param object: string
:param type: string
... | [
"def",
"create_git_tag",
"(",
"self",
",",
"tag",
",",
"message",
",",
"object",
",",
"type",
",",
"tagger",
"=",
"github",
".",
"GithubObject",
".",
"NotSet",
")",
":",
"assert",
"isinstance",
"(",
"tag",
",",
"(",
"str",
",",
"unicode",
")",
")",
"... | 42.896552 | 19.241379 |
def readInputFile(self, card_name, directory, session, spatial=False,
spatialReferenceID=None, **kwargs):
"""
Read specific input file for a GSSHA project to the database.
Args:
card_name(str): Name of GSSHA project card.
directory (str): Directory ... | [
"def",
"readInputFile",
"(",
"self",
",",
"card_name",
",",
"directory",
",",
"session",
",",
"spatial",
"=",
"False",
",",
"spatialReferenceID",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"project_directory",
"=",
"directory",
"with",
"t... | 56.961538 | 31.653846 |
def parse_hpo_genes(hpo_lines):
"""Parse HPO gene information
Args:
hpo_lines(iterable(str))
Returns:
diseases(dict): A dictionary with hgnc symbols as keys
"""
LOG.info("Parsing HPO genes ...")
genes = {}
for index, line in enumerate(hpo_lines):... | [
"def",
"parse_hpo_genes",
"(",
"hpo_lines",
")",
":",
"LOG",
".",
"info",
"(",
"\"Parsing HPO genes ...\"",
")",
"genes",
"=",
"{",
"}",
"for",
"index",
",",
"line",
"in",
"enumerate",
"(",
"hpo_lines",
")",
":",
"# First line is header",
"if",
"index",
"=="... | 32.555556 | 14.155556 |
def clean_up(self, dry_run=False, verbosity=1, last_n_days=0,
cleanup_path=None, storage=None):
"""
Iterate through sources. Delete database references to sources
not existing, including its corresponding thumbnails (files and
database references).
"""
if... | [
"def",
"clean_up",
"(",
"self",
",",
"dry_run",
"=",
"False",
",",
"verbosity",
"=",
"1",
",",
"last_n_days",
"=",
"0",
",",
"cleanup_path",
"=",
"None",
",",
"storage",
"=",
"None",
")",
":",
"if",
"dry_run",
":",
"print",
"(",
"\"Dry run...\"",
")",
... | 38.901961 | 20.470588 |
def pop(self):
"""
Removes the top process from the queue, and resumes its execution. For an empty queue, this method is a no-op.
This method may be invoked from anywhere (its use is not confined to processes, as method `join()` is).
"""
if not self.is_empty():
_, pro... | [
"def",
"pop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_empty",
"(",
")",
":",
"_",
",",
"process",
"=",
"heappop",
"(",
"self",
".",
"_waiting",
")",
"if",
"_logger",
"is",
"not",
"None",
":",
"self",
".",
"_log",
"(",
"INFO",
",",
... | 47.2 | 23.4 |
def detect_deprecation_in_expression(self, expression):
""" Detects if an expression makes use of any deprecated standards.
Returns:
list of tuple: (detecting_signature, original_text, recommended_text)"""
# Perform analysis on this expression
export = ExportValues(expressio... | [
"def",
"detect_deprecation_in_expression",
"(",
"self",
",",
"expression",
")",
":",
"# Perform analysis on this expression",
"export",
"=",
"ExportValues",
"(",
"expression",
")",
"export_values",
"=",
"export",
".",
"result",
"(",
")",
"# Define our results list",
"re... | 39.952381 | 18.190476 |
def rescale_around1(self, times):
"""
Suggests a rescaling factor and new physical time unit to balance the given time multiples around 1.
Parameters
----------
times : float array
array of times in multiple of the present elementary unit
"""
if self... | [
"def",
"rescale_around1",
"(",
"self",
",",
"times",
")",
":",
"if",
"self",
".",
"_unit",
"==",
"self",
".",
"_UNIT_STEP",
":",
"return",
"times",
",",
"'step'",
"# nothing to do",
"m",
"=",
"np",
".",
"mean",
"(",
"times",
")",
"mult",
"=",
"1.0",
... | 31.424242 | 20.878788 |
def fetch(self, recursive=1, fields=None, detail=None,
filters=None, parent_uuid=None, back_refs_uuid=None):
"""
Fetch collection from API server
:param recursive: level of recursion
:type recursive: int
:param fields: fetch only listed fields.
... | [
"def",
"fetch",
"(",
"self",
",",
"recursive",
"=",
"1",
",",
"fields",
"=",
"None",
",",
"detail",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"parent_uuid",
"=",
"None",
",",
"back_refs_uuid",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
... | 45.770833 | 20.229167 |
def _update_fields_with_objects(self):
""" Convert dict fields into objects, where appropriate """
# Update the cover with a photo object
if isinstance(self.cover, dict):
self.cover = Photo(self._client, self.cover)
# Update the photo list with photo objects
try:
... | [
"def",
"_update_fields_with_objects",
"(",
"self",
")",
":",
"# Update the cover with a photo object",
"if",
"isinstance",
"(",
"self",
".",
"cover",
",",
"dict",
")",
":",
"self",
".",
"cover",
"=",
"Photo",
"(",
"self",
".",
"_client",
",",
"self",
".",
"c... | 40.384615 | 12.769231 |
def security_rule_delete(security_rule, security_group, resource_group,
**kwargs):
'''
.. versionadded:: 2019.2.0
Delete a security rule within a specified security group.
:param name: The name of the security rule to delete.
:param security_group: The network security gr... | [
"def",
"security_rule_delete",
"(",
"security_rule",
",",
"security_group",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"False",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwar... | 28.861111 | 25.75 |
def parse_tables(self, markup):
""" Returns a list of tables in the markup.
A Wikipedia table looks like:
{| border="1"
|-
|Cell 1 (no modifier - not aligned)
|-
|align="right" |Cell 2 (right aligned)
|-
|}
"""
tables = ... | [
"def",
"parse_tables",
"(",
"self",
",",
"markup",
")",
":",
"tables",
"=",
"[",
"]",
"m",
"=",
"re",
".",
"findall",
"(",
"self",
".",
"re",
"[",
"\"table\"",
"]",
",",
"markup",
")",
"for",
"chunk",
"in",
"m",
":",
"table",
"=",
"WikipediaTable",... | 32.980392 | 15.294118 |
def union_with_variable(self, variable: str, replacement: VariableReplacement) -> 'Substitution':
"""Try to create a new substitution with the given variable added.
See :meth:`try_add_variable` for a version of this method that modifies the substitution
in place.
Args:
vari... | [
"def",
"union_with_variable",
"(",
"self",
",",
"variable",
":",
"str",
",",
"replacement",
":",
"VariableReplacement",
")",
"->",
"'Substitution'",
":",
"new_subst",
"=",
"Substitution",
"(",
"self",
")",
"new_subst",
".",
"try_add_variable",
"(",
"variable",
"... | 36.26087 | 24.217391 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.