text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def enable_virtual_terminal_processing():
"""As of Windows 10, the Windows console supports (some) ANSI escape
sequences, but it needs to be enabled using `SetConsoleMode` first.
More info on the escape sequences supported:
https://msdn.microsoft.com/en-us/library/windows/desktop/mt638032(v=vs.85).aspx
"""
stdout = GetStdHandle(STD_OUTPUT_HANDLE)
flags = GetConsoleMode(stdout)
SetConsoleMode(stdout, flags | ENABLE_VIRTUAL_TERMINAL_PROCESSING) | [
"def",
"enable_virtual_terminal_processing",
"(",
")",
":",
"stdout",
"=",
"GetStdHandle",
"(",
"STD_OUTPUT_HANDLE",
")",
"flags",
"=",
"GetConsoleMode",
"(",
"stdout",
")",
"SetConsoleMode",
"(",
"stdout",
",",
"flags",
"|",
"ENABLE_VIRTUAL_TERMINAL_PROCESSING",
")"
] | 47 | 16.3 |
def setColor(self, poiID, color):
"""setColor(string, (integer, integer, integer, integer)) -> None
Sets the rgba color of the poi.
"""
self._connection._beginMessage(
tc.CMD_SET_POI_VARIABLE, tc.VAR_COLOR, poiID, 1 + 1 + 1 + 1 + 1)
self._connection._string += struct.pack("!BBBBB", tc.TYPE_COLOR, int(
color[0]), int(color[1]), int(color[2]), int(color[3]))
self._connection._sendExact() | [
"def",
"setColor",
"(",
"self",
",",
"poiID",
",",
"color",
")",
":",
"self",
".",
"_connection",
".",
"_beginMessage",
"(",
"tc",
".",
"CMD_SET_POI_VARIABLE",
",",
"tc",
".",
"VAR_COLOR",
",",
"poiID",
",",
"1",
"+",
"1",
"+",
"1",
"+",
"1",
"+",
"1",
")",
"self",
".",
"_connection",
".",
"_string",
"+=",
"struct",
".",
"pack",
"(",
"\"!BBBBB\"",
",",
"tc",
".",
"TYPE_COLOR",
",",
"int",
"(",
"color",
"[",
"0",
"]",
")",
",",
"int",
"(",
"color",
"[",
"1",
"]",
")",
",",
"int",
"(",
"color",
"[",
"2",
"]",
")",
",",
"int",
"(",
"color",
"[",
"3",
"]",
")",
")",
"self",
".",
"_connection",
".",
"_sendExact",
"(",
")"
] | 45.2 | 15.2 |
def profile_name(org_vm, profile_inst, short=False):
"""
Return Org, Profile, Version as a string from the properties in the
profile instance. The returned form is the form Org:Name:Version or
Org:Name if the optional argument short is TRUE
"""
try:
name_tuple = get_profile_name(org_vm, profile_inst)
except Exception as ex: # pylint: disable=broad-except
print('GET_FULL_PROFILE_NAME exception %sm tuple=%r inst=%s' %
(ex, name_tuple, profile_inst))
return("UNKNOWN")
if short:
return "%s:%s" % (name_tuple[0], name_tuple[1])
return "%s:%s:%s" % (name_tuple[0], name_tuple[1], name_tuple[2]) | [
"def",
"profile_name",
"(",
"org_vm",
",",
"profile_inst",
",",
"short",
"=",
"False",
")",
":",
"try",
":",
"name_tuple",
"=",
"get_profile_name",
"(",
"org_vm",
",",
"profile_inst",
")",
"except",
"Exception",
"as",
"ex",
":",
"# pylint: disable=broad-except",
"print",
"(",
"'GET_FULL_PROFILE_NAME exception %sm tuple=%r inst=%s'",
"%",
"(",
"ex",
",",
"name_tuple",
",",
"profile_inst",
")",
")",
"return",
"(",
"\"UNKNOWN\"",
")",
"if",
"short",
":",
"return",
"\"%s:%s\"",
"%",
"(",
"name_tuple",
"[",
"0",
"]",
",",
"name_tuple",
"[",
"1",
"]",
")",
"return",
"\"%s:%s:%s\"",
"%",
"(",
"name_tuple",
"[",
"0",
"]",
",",
"name_tuple",
"[",
"1",
"]",
",",
"name_tuple",
"[",
"2",
"]",
")"
] | 41.4375 | 19.8125 |
def sec_project_community(self, project=None):
"""
Generate the data for the Communication section in a Project report
:return:
"""
def create_csv(metric1, csv_labels, file_label):
esfilters = None
csv_labels = csv_labels.replace("_", "") # LaTeX not supports "_"
if project != self.GLOBAL_PROJECT:
esfilters = {"project": project}
data_path = os.path.join(self.data_dir, "data")
file_name = os.path.join(data_path, file_label + "_" + project + ".csv")
logger.debug("CSV file %s generation in progress", file_name)
m1 = metric1(self.es_url, self.get_metric_index(metric1),
esfilters=esfilters, start=self.end_prev_month, end=self.end)
top = m1.get_list()
csv = csv_labels + '\n'
for i in range(0, len(top['value'])):
if i > self.TOP_MAX:
break
csv += top[metric1.FIELD_NAME][i] + "," + self.str_val(top['value'][i])
csv += "\n"
with open(file_name, "w") as f:
f.write(csv)
logger.debug("CSV file %s was generated", file_name)
logger.info("Community data for: %s", project)
author = self.config['project_community']['author_metrics'][0]
csv_labels = 'labels,' + author.id
file_label = author.ds.name + "_" + author.id
title_label = author.name + " per " + self.interval
self.__create_csv_eps(author, None, csv_labels, file_label, title_label,
project)
"""
Main developers
"""
metric = self.config['project_community']['people_top_metrics'][0]
# TODO: Commits must be extracted from metric
csv_labels = author.id + ",commits"
file_label = author.ds.name + "_top_" + author.id
create_csv(metric, csv_labels, file_label)
"""
Main organizations
"""
orgs = self.config['project_community']['orgs_top_metrics'][0]
# TODO: Commits must be extracted from metric
csv_labels = orgs.id + ",commits"
file_label = orgs.ds.name + "_top_" + orgs.id
create_csv(orgs, csv_labels, file_label) | [
"def",
"sec_project_community",
"(",
"self",
",",
"project",
"=",
"None",
")",
":",
"def",
"create_csv",
"(",
"metric1",
",",
"csv_labels",
",",
"file_label",
")",
":",
"esfilters",
"=",
"None",
"csv_labels",
"=",
"csv_labels",
".",
"replace",
"(",
"\"_\"",
",",
"\"\"",
")",
"# LaTeX not supports \"_\"",
"if",
"project",
"!=",
"self",
".",
"GLOBAL_PROJECT",
":",
"esfilters",
"=",
"{",
"\"project\"",
":",
"project",
"}",
"data_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"data_dir",
",",
"\"data\"",
")",
"file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_path",
",",
"file_label",
"+",
"\"_\"",
"+",
"project",
"+",
"\".csv\"",
")",
"logger",
".",
"debug",
"(",
"\"CSV file %s generation in progress\"",
",",
"file_name",
")",
"m1",
"=",
"metric1",
"(",
"self",
".",
"es_url",
",",
"self",
".",
"get_metric_index",
"(",
"metric1",
")",
",",
"esfilters",
"=",
"esfilters",
",",
"start",
"=",
"self",
".",
"end_prev_month",
",",
"end",
"=",
"self",
".",
"end",
")",
"top",
"=",
"m1",
".",
"get_list",
"(",
")",
"csv",
"=",
"csv_labels",
"+",
"'\\n'",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"top",
"[",
"'value'",
"]",
")",
")",
":",
"if",
"i",
">",
"self",
".",
"TOP_MAX",
":",
"break",
"csv",
"+=",
"top",
"[",
"metric1",
".",
"FIELD_NAME",
"]",
"[",
"i",
"]",
"+",
"\",\"",
"+",
"self",
".",
"str_val",
"(",
"top",
"[",
"'value'",
"]",
"[",
"i",
"]",
")",
"csv",
"+=",
"\"\\n\"",
"with",
"open",
"(",
"file_name",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"csv",
")",
"logger",
".",
"debug",
"(",
"\"CSV file %s was generated\"",
",",
"file_name",
")",
"logger",
".",
"info",
"(",
"\"Community data for: %s\"",
",",
"project",
")",
"author",
"=",
"self",
".",
"config",
"[",
"'project_community'",
"]",
"[",
"'author_metrics'",
"]",
"[",
"0",
"]",
"csv_labels",
"=",
"'labels,'",
"+",
"author",
".",
"id",
"file_label",
"=",
"author",
".",
"ds",
".",
"name",
"+",
"\"_\"",
"+",
"author",
".",
"id",
"title_label",
"=",
"author",
".",
"name",
"+",
"\" per \"",
"+",
"self",
".",
"interval",
"self",
".",
"__create_csv_eps",
"(",
"author",
",",
"None",
",",
"csv_labels",
",",
"file_label",
",",
"title_label",
",",
"project",
")",
"\"\"\"\n Main developers\n\n \"\"\"",
"metric",
"=",
"self",
".",
"config",
"[",
"'project_community'",
"]",
"[",
"'people_top_metrics'",
"]",
"[",
"0",
"]",
"# TODO: Commits must be extracted from metric",
"csv_labels",
"=",
"author",
".",
"id",
"+",
"\",commits\"",
"file_label",
"=",
"author",
".",
"ds",
".",
"name",
"+",
"\"_top_\"",
"+",
"author",
".",
"id",
"create_csv",
"(",
"metric",
",",
"csv_labels",
",",
"file_label",
")",
"\"\"\"\n Main organizations\n\n \"\"\"",
"orgs",
"=",
"self",
".",
"config",
"[",
"'project_community'",
"]",
"[",
"'orgs_top_metrics'",
"]",
"[",
"0",
"]",
"# TODO: Commits must be extracted from metric",
"csv_labels",
"=",
"orgs",
".",
"id",
"+",
"\",commits\"",
"file_label",
"=",
"orgs",
".",
"ds",
".",
"name",
"+",
"\"_top_\"",
"+",
"orgs",
".",
"id",
"create_csv",
"(",
"orgs",
",",
"csv_labels",
",",
"file_label",
")"
] | 36.754098 | 20.819672 |
def _get_species_taxon_ids(taxdump_file,
select_divisions=None, exclude_divisions=None):
"""Get a list of species taxon IDs (allow filtering by division)."""
if select_divisions and exclude_divisions:
raise ValueError('Cannot specify "select_divisions" and '
'"exclude_divisions" at the same time.')
select_division_ids = None
exclude_division_ids = None
divisions = None
if select_divisions or exclude_divisions:
divisions = _get_divisions(taxdump_file)
if select_divisions:
select_division_ids = set([divisions[d] for d in select_divisions])
elif exclude_divisions:
exclude_division_ids = set([divisions[d] for d in exclude_divisions])
with tarfile.open(taxdump_file) as tf:
with tf.extractfile('nodes.dmp') as fh:
df = pd.read_csv(fh, header=None, sep='|', encoding='ascii')
# select only tax_id, rank, and division id columns
df = df.iloc[:, [0, 2, 4]]
if select_division_ids:
# select only species from specified divisions
df = df.loc[df.iloc[:, 2].isin(select_division_ids)]
elif exclude_division_ids:
# exclude species from specified divisions
df = df.loc[~df.iloc[:, 2].isin(exclude_division_ids)]
# remove tab characters flanking each rank name
df.iloc[:, 1] = df.iloc[:, 1].str.strip('\t')
# get taxon IDs for all species
taxon_ids = df.iloc[:, 0].loc[df.iloc[:, 1] == 'species'].values
return taxon_ids | [
"def",
"_get_species_taxon_ids",
"(",
"taxdump_file",
",",
"select_divisions",
"=",
"None",
",",
"exclude_divisions",
"=",
"None",
")",
":",
"if",
"select_divisions",
"and",
"exclude_divisions",
":",
"raise",
"ValueError",
"(",
"'Cannot specify \"select_divisions\" and '",
"'\"exclude_divisions\" at the same time.'",
")",
"select_division_ids",
"=",
"None",
"exclude_division_ids",
"=",
"None",
"divisions",
"=",
"None",
"if",
"select_divisions",
"or",
"exclude_divisions",
":",
"divisions",
"=",
"_get_divisions",
"(",
"taxdump_file",
")",
"if",
"select_divisions",
":",
"select_division_ids",
"=",
"set",
"(",
"[",
"divisions",
"[",
"d",
"]",
"for",
"d",
"in",
"select_divisions",
"]",
")",
"elif",
"exclude_divisions",
":",
"exclude_division_ids",
"=",
"set",
"(",
"[",
"divisions",
"[",
"d",
"]",
"for",
"d",
"in",
"exclude_divisions",
"]",
")",
"with",
"tarfile",
".",
"open",
"(",
"taxdump_file",
")",
"as",
"tf",
":",
"with",
"tf",
".",
"extractfile",
"(",
"'nodes.dmp'",
")",
"as",
"fh",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"fh",
",",
"header",
"=",
"None",
",",
"sep",
"=",
"'|'",
",",
"encoding",
"=",
"'ascii'",
")",
"# select only tax_id, rank, and division id columns",
"df",
"=",
"df",
".",
"iloc",
"[",
":",
",",
"[",
"0",
",",
"2",
",",
"4",
"]",
"]",
"if",
"select_division_ids",
":",
"# select only species from specified divisions",
"df",
"=",
"df",
".",
"loc",
"[",
"df",
".",
"iloc",
"[",
":",
",",
"2",
"]",
".",
"isin",
"(",
"select_division_ids",
")",
"]",
"elif",
"exclude_division_ids",
":",
"# exclude species from specified divisions",
"df",
"=",
"df",
".",
"loc",
"[",
"~",
"df",
".",
"iloc",
"[",
":",
",",
"2",
"]",
".",
"isin",
"(",
"exclude_division_ids",
")",
"]",
"# remove tab characters flanking each rank name",
"df",
".",
"iloc",
"[",
":",
",",
"1",
"]",
"=",
"df",
".",
"iloc",
"[",
":",
",",
"1",
"]",
".",
"str",
".",
"strip",
"(",
"'\\t'",
")",
"# get taxon IDs for all species",
"taxon_ids",
"=",
"df",
".",
"iloc",
"[",
":",
",",
"0",
"]",
".",
"loc",
"[",
"df",
".",
"iloc",
"[",
":",
",",
"1",
"]",
"==",
"'species'",
"]",
".",
"values",
"return",
"taxon_ids"
] | 35.883721 | 21.093023 |
def zip(*args, **kwargs):
""" Returns a list of tuples, where the i-th tuple contains the i-th element
from each of the argument sequences or iterables (or default if too short).
"""
args = [list(iterable) for iterable in args]
n = max(map(len, args))
v = kwargs.get("default", None)
return _zip(*[i + [v] * (n - len(i)) for i in args]) | [
"def",
"zip",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"list",
"(",
"iterable",
")",
"for",
"iterable",
"in",
"args",
"]",
"n",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"args",
")",
")",
"v",
"=",
"kwargs",
".",
"get",
"(",
"\"default\"",
",",
"None",
")",
"return",
"_zip",
"(",
"*",
"[",
"i",
"+",
"[",
"v",
"]",
"*",
"(",
"n",
"-",
"len",
"(",
"i",
")",
")",
"for",
"i",
"in",
"args",
"]",
")"
] | 45.25 | 12.5 |
def generate_supremacy_circuit_google_v2_bristlecone(n_rows: int,
cz_depth: int, seed: int
) -> circuits.Circuit:
"""
Generates Google Random Circuits v2 in Bristlecone.
See also https://arxiv.org/abs/1807.10749
Args:
n_rows: number of rows in a Bristlecone lattice.
Note that we do not include single qubit corners.
cz_depth: number of layers with CZ gates.
seed: seed for the random instance.
Returns:
A circuit with given size and seed.
"""
def get_qubits(n_rows):
def count_neighbors(qubits, qubit):
"""Counts the qubits that the given qubit can interact with."""
possibles = [
devices.GridQubit(qubit.row + 1, qubit.col),
devices.GridQubit(qubit.row - 1, qubit.col),
devices.GridQubit(qubit.row, qubit.col + 1),
devices.GridQubit(qubit.row, qubit.col - 1),
]
return len(list(e for e in possibles if e in qubits))
assert 1 <= n_rows <= 11
max_row = n_rows - 1
dev = google.Bristlecone
# we need a consistent order of qubits
qubits = list(dev.qubits)
qubits.sort()
qubits = [q for q in qubits
if q.row <= max_row and q.row + q.col < n_rows + 6
and q.row - q.col < n_rows - 5]
qubits = [q for q in qubits if count_neighbors(qubits, q) > 1]
return qubits
qubits = get_qubits(n_rows)
return generate_supremacy_circuit_google_v2(qubits, cz_depth, seed) | [
"def",
"generate_supremacy_circuit_google_v2_bristlecone",
"(",
"n_rows",
":",
"int",
",",
"cz_depth",
":",
"int",
",",
"seed",
":",
"int",
")",
"->",
"circuits",
".",
"Circuit",
":",
"def",
"get_qubits",
"(",
"n_rows",
")",
":",
"def",
"count_neighbors",
"(",
"qubits",
",",
"qubit",
")",
":",
"\"\"\"Counts the qubits that the given qubit can interact with.\"\"\"",
"possibles",
"=",
"[",
"devices",
".",
"GridQubit",
"(",
"qubit",
".",
"row",
"+",
"1",
",",
"qubit",
".",
"col",
")",
",",
"devices",
".",
"GridQubit",
"(",
"qubit",
".",
"row",
"-",
"1",
",",
"qubit",
".",
"col",
")",
",",
"devices",
".",
"GridQubit",
"(",
"qubit",
".",
"row",
",",
"qubit",
".",
"col",
"+",
"1",
")",
",",
"devices",
".",
"GridQubit",
"(",
"qubit",
".",
"row",
",",
"qubit",
".",
"col",
"-",
"1",
")",
",",
"]",
"return",
"len",
"(",
"list",
"(",
"e",
"for",
"e",
"in",
"possibles",
"if",
"e",
"in",
"qubits",
")",
")",
"assert",
"1",
"<=",
"n_rows",
"<=",
"11",
"max_row",
"=",
"n_rows",
"-",
"1",
"dev",
"=",
"google",
".",
"Bristlecone",
"# we need a consistent order of qubits",
"qubits",
"=",
"list",
"(",
"dev",
".",
"qubits",
")",
"qubits",
".",
"sort",
"(",
")",
"qubits",
"=",
"[",
"q",
"for",
"q",
"in",
"qubits",
"if",
"q",
".",
"row",
"<=",
"max_row",
"and",
"q",
".",
"row",
"+",
"q",
".",
"col",
"<",
"n_rows",
"+",
"6",
"and",
"q",
".",
"row",
"-",
"q",
".",
"col",
"<",
"n_rows",
"-",
"5",
"]",
"qubits",
"=",
"[",
"q",
"for",
"q",
"in",
"qubits",
"if",
"count_neighbors",
"(",
"qubits",
",",
"q",
")",
">",
"1",
"]",
"return",
"qubits",
"qubits",
"=",
"get_qubits",
"(",
"n_rows",
")",
"return",
"generate_supremacy_circuit_google_v2",
"(",
"qubits",
",",
"cz_depth",
",",
"seed",
")"
] | 40.02439 | 18.195122 |
def is_right_model(instance, attribute, value):
"""Must include at least the ``source`` and ``license`` keys, but
not a ``rightsOf`` key (``source`` indicates that the Right is
derived from and allowed by a source Right; it cannot contain the
full rights to a Creation).
"""
for key in ['source', 'license']:
key_value = value.get(key)
if not isinstance(key_value, str):
instance_name = instance.__class__.__name__
raise ModelDataError(("'{key}' must be given as a string in "
"the '{attr}' parameter of a '{cls}'. Given "
"'{value}'").format(key=key,
attr=attribute.name,
cls=instance_name,
value=key_value)) | [
"def",
"is_right_model",
"(",
"instance",
",",
"attribute",
",",
"value",
")",
":",
"for",
"key",
"in",
"[",
"'source'",
",",
"'license'",
"]",
":",
"key_value",
"=",
"value",
".",
"get",
"(",
"key",
")",
"if",
"not",
"isinstance",
"(",
"key_value",
",",
"str",
")",
":",
"instance_name",
"=",
"instance",
".",
"__class__",
".",
"__name__",
"raise",
"ModelDataError",
"(",
"(",
"\"'{key}' must be given as a string in \"",
"\"the '{attr}' parameter of a '{cls}'. Given \"",
"\"'{value}'\"",
")",
".",
"format",
"(",
"key",
"=",
"key",
",",
"attr",
"=",
"attribute",
".",
"name",
",",
"cls",
"=",
"instance_name",
",",
"value",
"=",
"key_value",
")",
")"
] | 52.235294 | 19.294118 |
def _gen_uid(self):
'''
Generate the ID for post.
:return: the new ID.
'''
cur_uid = self.kind + tools.get_uu4d()
while MPost.get_by_uid(cur_uid):
cur_uid = self.kind + tools.get_uu4d()
return cur_uid | [
"def",
"_gen_uid",
"(",
"self",
")",
":",
"cur_uid",
"=",
"self",
".",
"kind",
"+",
"tools",
".",
"get_uu4d",
"(",
")",
"while",
"MPost",
".",
"get_by_uid",
"(",
"cur_uid",
")",
":",
"cur_uid",
"=",
"self",
".",
"kind",
"+",
"tools",
".",
"get_uu4d",
"(",
")",
"return",
"cur_uid"
] | 28.888889 | 14.666667 |
def _find_mocker(symbol: str, context: 'torment.contexts.TestContext') -> Callable[[], bool]:
'''Find method within the context that mocks symbol.
Given a symbol (i.e. ``tornado.httpclient.AsyncHTTPClient.fetch``), find
the shortest ``mock_`` method that resembles the symbol. Resembles means
the lowercased and periods replaced with underscores.
If no match is found, a dummy function (only returns False) is returned.
**Parameters**
:``symbol``: the symbol to be located
:``context``: the search context
**Return Value(s)**
The method used to mock the symbol.
**Examples**
Assuming the symbol is ``tornado.httpclient.AsyncHTTPClient.fetch``, the
first of the following methods would be returned:
* ``mock_tornado``
* ``mock_tornado_httpclient``
* ``mock_tornado_httpclient_asynchttpclient``
* ``mock_tornado_httpclient_asynchttpclient_fetch``
'''
components = []
method = None
for component in symbol.split('.'):
components.append(component.lower())
name = '_'.join([ 'mock' ] + components)
if hasattr(context, name):
method = getattr(context, name)
break
if method is None:
logger.warn('no mocker for %s', symbol)
def noop(*args, **kwargs):
return False
method = noop
return method | [
"def",
"_find_mocker",
"(",
"symbol",
":",
"str",
",",
"context",
":",
"'torment.contexts.TestContext'",
")",
"->",
"Callable",
"[",
"[",
"]",
",",
"bool",
"]",
":",
"components",
"=",
"[",
"]",
"method",
"=",
"None",
"for",
"component",
"in",
"symbol",
".",
"split",
"(",
"'.'",
")",
":",
"components",
".",
"append",
"(",
"component",
".",
"lower",
"(",
")",
")",
"name",
"=",
"'_'",
".",
"join",
"(",
"[",
"'mock'",
"]",
"+",
"components",
")",
"if",
"hasattr",
"(",
"context",
",",
"name",
")",
":",
"method",
"=",
"getattr",
"(",
"context",
",",
"name",
")",
"break",
"if",
"method",
"is",
"None",
":",
"logger",
".",
"warn",
"(",
"'no mocker for %s'",
",",
"symbol",
")",
"def",
"noop",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"False",
"method",
"=",
"noop",
"return",
"method"
] | 26.58 | 25.06 |
def set_inherited_traits(self, egg_donor, sperm_donor):
"""Accept either strings or Gods as inputs."""
if type(egg_donor) == str:
self.reproduce_asexually(egg_donor, sperm_donor)
else:
self.reproduce_sexually(egg_donor, sperm_donor) | [
"def",
"set_inherited_traits",
"(",
"self",
",",
"egg_donor",
",",
"sperm_donor",
")",
":",
"if",
"type",
"(",
"egg_donor",
")",
"==",
"str",
":",
"self",
".",
"reproduce_asexually",
"(",
"egg_donor",
",",
"sperm_donor",
")",
"else",
":",
"self",
".",
"reproduce_sexually",
"(",
"egg_donor",
",",
"sperm_donor",
")"
] | 45.833333 | 14.5 |
def removeTab(self, tab):
"""allows to remove a tab directly -not only by giving its index"""
if not isinstance(tab, int):
tab = self.indexOf(tab)
return super(FwTabWidget, self).removeTab(tab) | [
"def",
"removeTab",
"(",
"self",
",",
"tab",
")",
":",
"if",
"not",
"isinstance",
"(",
"tab",
",",
"int",
")",
":",
"tab",
"=",
"self",
".",
"indexOf",
"(",
"tab",
")",
"return",
"super",
"(",
"FwTabWidget",
",",
"self",
")",
".",
"removeTab",
"(",
"tab",
")"
] | 45 | 7.6 |
def _to_tuple(bbox):
""" Converts the input bbox representation (see the constructor docstring for a list of valid representations)
into a flat tuple
:param bbox: A bbox in one of 7 forms listed in the class description.
:return: A flat tuple of size
:raises: TypeError
"""
if isinstance(bbox, (list, tuple)):
return BBox._tuple_from_list_or_tuple(bbox)
if isinstance(bbox, str):
return BBox._tuple_from_str(bbox)
if isinstance(bbox, dict):
return BBox._tuple_from_dict(bbox)
if isinstance(bbox, BBox):
return BBox._tuple_from_bbox(bbox)
if isinstance(bbox, shapely.geometry.base.BaseGeometry):
return bbox.bounds
raise TypeError('Invalid bbox representation') | [
"def",
"_to_tuple",
"(",
"bbox",
")",
":",
"if",
"isinstance",
"(",
"bbox",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"BBox",
".",
"_tuple_from_list_or_tuple",
"(",
"bbox",
")",
"if",
"isinstance",
"(",
"bbox",
",",
"str",
")",
":",
"return",
"BBox",
".",
"_tuple_from_str",
"(",
"bbox",
")",
"if",
"isinstance",
"(",
"bbox",
",",
"dict",
")",
":",
"return",
"BBox",
".",
"_tuple_from_dict",
"(",
"bbox",
")",
"if",
"isinstance",
"(",
"bbox",
",",
"BBox",
")",
":",
"return",
"BBox",
".",
"_tuple_from_bbox",
"(",
"bbox",
")",
"if",
"isinstance",
"(",
"bbox",
",",
"shapely",
".",
"geometry",
".",
"base",
".",
"BaseGeometry",
")",
":",
"return",
"bbox",
".",
"bounds",
"raise",
"TypeError",
"(",
"'Invalid bbox representation'",
")"
] | 42.052632 | 12.210526 |
def checkValidNodeTypes(provisioner, nodeTypes):
"""
Raises if an invalid nodeType is specified for aws, azure, or gce.
:param str provisioner: 'aws', 'gce', or 'azure' to specify which cloud provisioner used.
:param nodeTypes: A list of node types. Example: ['t2.micro', 't2.medium']
:return: Nothing. Raises if invalid nodeType.
"""
if not nodeTypes:
return
if not isinstance(nodeTypes, list):
nodeTypes = [nodeTypes]
if not isinstance(nodeTypes[0], string_types):
return
# check if a valid node type for aws
from toil.lib.generatedEC2Lists import E2Instances, regionDict
if provisioner == 'aws':
from toil.provisioners.aws import getCurrentAWSZone
currentZone = getCurrentAWSZone()
if not currentZone:
currentZone = 'us-west-2'
else:
currentZone = currentZone[:-1] # adds something like 'a' or 'b' to the end
# check if instance type exists in this region
for nodeType in nodeTypes:
if nodeType and ':' in nodeType:
nodeType = nodeType.split(':')[0]
if nodeType not in regionDict[currentZone]:
# They probably misspelled it and can't tell.
close = get_close_matches(nodeType, regionDict[currentZone], 1)
if len(close) > 0:
helpText = ' Did you mean ' + close[0] + '?'
else:
helpText = ''
raise RuntimeError('Invalid nodeType (%s) specified for AWS in region: %s.%s'
'' % (nodeType, currentZone, helpText))
# Only checks if aws nodeType specified for gce/azure atm.
if provisioner == 'gce' or provisioner == 'azure':
for nodeType in nodeTypes:
if nodeType and ':' in nodeType:
nodeType = nodeType.split(':')[0]
try:
E2Instances[nodeType]
raise RuntimeError("It looks like you've specified an AWS nodeType with the "
"{} provisioner. Please specify an {} nodeType."
"".format(provisioner, provisioner))
except KeyError:
pass | [
"def",
"checkValidNodeTypes",
"(",
"provisioner",
",",
"nodeTypes",
")",
":",
"if",
"not",
"nodeTypes",
":",
"return",
"if",
"not",
"isinstance",
"(",
"nodeTypes",
",",
"list",
")",
":",
"nodeTypes",
"=",
"[",
"nodeTypes",
"]",
"if",
"not",
"isinstance",
"(",
"nodeTypes",
"[",
"0",
"]",
",",
"string_types",
")",
":",
"return",
"# check if a valid node type for aws",
"from",
"toil",
".",
"lib",
".",
"generatedEC2Lists",
"import",
"E2Instances",
",",
"regionDict",
"if",
"provisioner",
"==",
"'aws'",
":",
"from",
"toil",
".",
"provisioners",
".",
"aws",
"import",
"getCurrentAWSZone",
"currentZone",
"=",
"getCurrentAWSZone",
"(",
")",
"if",
"not",
"currentZone",
":",
"currentZone",
"=",
"'us-west-2'",
"else",
":",
"currentZone",
"=",
"currentZone",
"[",
":",
"-",
"1",
"]",
"# adds something like 'a' or 'b' to the end",
"# check if instance type exists in this region",
"for",
"nodeType",
"in",
"nodeTypes",
":",
"if",
"nodeType",
"and",
"':'",
"in",
"nodeType",
":",
"nodeType",
"=",
"nodeType",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"if",
"nodeType",
"not",
"in",
"regionDict",
"[",
"currentZone",
"]",
":",
"# They probably misspelled it and can't tell.",
"close",
"=",
"get_close_matches",
"(",
"nodeType",
",",
"regionDict",
"[",
"currentZone",
"]",
",",
"1",
")",
"if",
"len",
"(",
"close",
")",
">",
"0",
":",
"helpText",
"=",
"' Did you mean '",
"+",
"close",
"[",
"0",
"]",
"+",
"'?'",
"else",
":",
"helpText",
"=",
"''",
"raise",
"RuntimeError",
"(",
"'Invalid nodeType (%s) specified for AWS in region: %s.%s'",
"''",
"%",
"(",
"nodeType",
",",
"currentZone",
",",
"helpText",
")",
")",
"# Only checks if aws nodeType specified for gce/azure atm.",
"if",
"provisioner",
"==",
"'gce'",
"or",
"provisioner",
"==",
"'azure'",
":",
"for",
"nodeType",
"in",
"nodeTypes",
":",
"if",
"nodeType",
"and",
"':'",
"in",
"nodeType",
":",
"nodeType",
"=",
"nodeType",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
"try",
":",
"E2Instances",
"[",
"nodeType",
"]",
"raise",
"RuntimeError",
"(",
"\"It looks like you've specified an AWS nodeType with the \"",
"\"{} provisioner. Please specify an {} nodeType.\"",
"\"\"",
".",
"format",
"(",
"provisioner",
",",
"provisioner",
")",
")",
"except",
"KeyError",
":",
"pass"
] | 45.979167 | 18.979167 |
def locale(self) -> babel.core.Locale or None:
"""
Get user's locale
:return: :class:`babel.core.Locale`
"""
if not self.language_code:
return None
if not hasattr(self, '_locale'):
setattr(self, '_locale', babel.core.Locale.parse(self.language_code, sep='-'))
return getattr(self, '_locale') | [
"def",
"locale",
"(",
"self",
")",
"->",
"babel",
".",
"core",
".",
"Locale",
"or",
"None",
":",
"if",
"not",
"self",
".",
"language_code",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_locale'",
")",
":",
"setattr",
"(",
"self",
",",
"'_locale'",
",",
"babel",
".",
"core",
".",
"Locale",
".",
"parse",
"(",
"self",
".",
"language_code",
",",
"sep",
"=",
"'-'",
")",
")",
"return",
"getattr",
"(",
"self",
",",
"'_locale'",
")"
] | 32.909091 | 12.545455 |
def binary_report(self, sha256sum, apikey):
"""
retrieve report from file scan
"""
url = self.base_url + "file/report"
params = {"apikey": apikey, "resource": sha256sum}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = requests.post(url, data=params)
if response.status_code == self.HTTP_OK:
json_response = response.json()
response_code = json_response['response_code']
return json_response
elif response.status_code == self.HTTP_RATE_EXCEEDED:
time.sleep(20)
else:
self.logger.warning("retrieve report: %s, HTTP code: %d", os.path.basename(filename), response.status_code) | [
"def",
"binary_report",
"(",
"self",
",",
"sha256sum",
",",
"apikey",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"file/report\"",
"params",
"=",
"{",
"\"apikey\"",
":",
"apikey",
",",
"\"resource\"",
":",
"sha256sum",
"}",
"rate_limit_clear",
"=",
"self",
".",
"rate_limit",
"(",
")",
"if",
"rate_limit_clear",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"url",
",",
"data",
"=",
"params",
")",
"if",
"response",
".",
"status_code",
"==",
"self",
".",
"HTTP_OK",
":",
"json_response",
"=",
"response",
".",
"json",
"(",
")",
"response_code",
"=",
"json_response",
"[",
"'response_code'",
"]",
"return",
"json_response",
"elif",
"response",
".",
"status_code",
"==",
"self",
".",
"HTTP_RATE_EXCEEDED",
":",
"time",
".",
"sleep",
"(",
"20",
")",
"else",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"\"retrieve report: %s, HTTP code: %d\"",
",",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
",",
"response",
".",
"status_code",
")"
] | 40.105263 | 16.947368 |
def make_access_urls(self, catalog_url, all_services, metadata=None):
"""Make fully qualified urls for the access methods enabled on the dataset.
Parameters
----------
catalog_url : str
The top level server url
all_services : List[SimpleService]
list of :class:`SimpleService` objects associated with the dataset
metadata : dict
Metadata from the :class:`TDSCatalog`
"""
all_service_dict = CaseInsensitiveDict({})
for service in all_services:
all_service_dict[service.name] = service
if isinstance(service, CompoundService):
for subservice in service.services:
all_service_dict[subservice.name] = subservice
service_name = metadata.get('serviceName', None)
access_urls = CaseInsensitiveDict({})
server_url = _find_base_tds_url(catalog_url)
# process access urls for datasets that reference top
# level catalog services (individual or compound service
# types).
if service_name in all_service_dict:
service = all_service_dict[service_name]
if service.service_type != 'Resolver':
# if service is a CompoundService, create access url
# for each SimpleService
if isinstance(service, CompoundService):
for subservice in service.services:
server_base = urljoin(server_url, subservice.base)
access_urls[subservice.service_type] = urljoin(server_base,
self.url_path)
else:
server_base = urljoin(server_url, service.base)
access_urls[service.service_type] = urljoin(server_base, self.url_path)
# process access children of dataset elements
for service_type in self.access_element_info:
url_path = self.access_element_info[service_type]
if service_type in all_service_dict:
server_base = urljoin(server_url, all_service_dict[service_type].base)
access_urls[service_type] = urljoin(server_base, url_path)
self.access_urls = access_urls | [
"def",
"make_access_urls",
"(",
"self",
",",
"catalog_url",
",",
"all_services",
",",
"metadata",
"=",
"None",
")",
":",
"all_service_dict",
"=",
"CaseInsensitiveDict",
"(",
"{",
"}",
")",
"for",
"service",
"in",
"all_services",
":",
"all_service_dict",
"[",
"service",
".",
"name",
"]",
"=",
"service",
"if",
"isinstance",
"(",
"service",
",",
"CompoundService",
")",
":",
"for",
"subservice",
"in",
"service",
".",
"services",
":",
"all_service_dict",
"[",
"subservice",
".",
"name",
"]",
"=",
"subservice",
"service_name",
"=",
"metadata",
".",
"get",
"(",
"'serviceName'",
",",
"None",
")",
"access_urls",
"=",
"CaseInsensitiveDict",
"(",
"{",
"}",
")",
"server_url",
"=",
"_find_base_tds_url",
"(",
"catalog_url",
")",
"# process access urls for datasets that reference top",
"# level catalog services (individual or compound service",
"# types).",
"if",
"service_name",
"in",
"all_service_dict",
":",
"service",
"=",
"all_service_dict",
"[",
"service_name",
"]",
"if",
"service",
".",
"service_type",
"!=",
"'Resolver'",
":",
"# if service is a CompoundService, create access url",
"# for each SimpleService",
"if",
"isinstance",
"(",
"service",
",",
"CompoundService",
")",
":",
"for",
"subservice",
"in",
"service",
".",
"services",
":",
"server_base",
"=",
"urljoin",
"(",
"server_url",
",",
"subservice",
".",
"base",
")",
"access_urls",
"[",
"subservice",
".",
"service_type",
"]",
"=",
"urljoin",
"(",
"server_base",
",",
"self",
".",
"url_path",
")",
"else",
":",
"server_base",
"=",
"urljoin",
"(",
"server_url",
",",
"service",
".",
"base",
")",
"access_urls",
"[",
"service",
".",
"service_type",
"]",
"=",
"urljoin",
"(",
"server_base",
",",
"self",
".",
"url_path",
")",
"# process access children of dataset elements",
"for",
"service_type",
"in",
"self",
".",
"access_element_info",
":",
"url_path",
"=",
"self",
".",
"access_element_info",
"[",
"service_type",
"]",
"if",
"service_type",
"in",
"all_service_dict",
":",
"server_base",
"=",
"urljoin",
"(",
"server_url",
",",
"all_service_dict",
"[",
"service_type",
"]",
".",
"base",
")",
"access_urls",
"[",
"service_type",
"]",
"=",
"urljoin",
"(",
"server_base",
",",
"url_path",
")",
"self",
".",
"access_urls",
"=",
"access_urls"
] | 45.06 | 21.1 |
def sorted_key_list(self):
"""Returns list of keys sorted according to their absolute time."""
if not self.is_baked:
self.bake()
key_value_tuple = sorted(self.dct.items(),
key=lambda x: x[1]['__abs_time__'])
skl = [k[0] for k in key_value_tuple]
return skl | [
"def",
"sorted_key_list",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_baked",
":",
"self",
".",
"bake",
"(",
")",
"key_value_tuple",
"=",
"sorted",
"(",
"self",
".",
"dct",
".",
"items",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"1",
"]",
"[",
"'__abs_time__'",
"]",
")",
"skl",
"=",
"[",
"k",
"[",
"0",
"]",
"for",
"k",
"in",
"key_value_tuple",
"]",
"return",
"skl"
] | 41.75 | 13.375 |
def tnr(y, z):
"""True negative rate `tn / (tn + fp)`
"""
tp, tn, fp, fn = contingency_table(y, z)
return tn / (tn + fp) | [
"def",
"tnr",
"(",
"y",
",",
"z",
")",
":",
"tp",
",",
"tn",
",",
"fp",
",",
"fn",
"=",
"contingency_table",
"(",
"y",
",",
"z",
")",
"return",
"tn",
"/",
"(",
"tn",
"+",
"fp",
")"
] | 26.4 | 9 |
def search(term, category=Categories.ALL, pages=1, sort=None, order=None):
"""Return a search result for term in category. Can also be
sorted and span multiple pages."""
s = Search()
s.search(term=term, category=category, pages=pages, sort=sort, order=order)
return s | [
"def",
"search",
"(",
"term",
",",
"category",
"=",
"Categories",
".",
"ALL",
",",
"pages",
"=",
"1",
",",
"sort",
"=",
"None",
",",
"order",
"=",
"None",
")",
":",
"s",
"=",
"Search",
"(",
")",
"s",
".",
"search",
"(",
"term",
"=",
"term",
",",
"category",
"=",
"category",
",",
"pages",
"=",
"pages",
",",
"sort",
"=",
"sort",
",",
"order",
"=",
"order",
")",
"return",
"s"
] | 44.666667 | 21.333333 |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
compare
/katello/api/errata/compare
Otherwise, call ``super``.
"""
if which in ('compare',):
return '{0}/{1}'.format(super(Errata, self).path('base'), which)
return super(Errata, self).path(which) | [
"def",
"path",
"(",
"self",
",",
"which",
"=",
"None",
")",
":",
"if",
"which",
"in",
"(",
"'compare'",
",",
")",
":",
"return",
"'{0}/{1}'",
".",
"format",
"(",
"super",
"(",
"Errata",
",",
"self",
")",
".",
"path",
"(",
"'base'",
")",
",",
"which",
")",
"return",
"super",
"(",
"Errata",
",",
"self",
")",
".",
"path",
"(",
"which",
")"
] | 29.357143 | 20.571429 |
def sign(self, data):
"""
Create an URL-safe, signed token from ``data``.
"""
data = signing.b64_encode(data).decode()
return self.signer.sign(data) | [
"def",
"sign",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"signing",
".",
"b64_encode",
"(",
"data",
")",
".",
"decode",
"(",
")",
"return",
"self",
".",
"signer",
".",
"sign",
"(",
"data",
")"
] | 26.142857 | 12.142857 |
def hrlist(self, name_start, name_end, limit=10):
"""
Return a list of the top ``limit`` hash's name between ``name_start`` and
``name_end`` in descending order
.. note:: The range is (``name_start``, ``name_end``]. The ``name_start``
isn't in the range, but ``name_end`` is.
:param string name_start: The lower bound(not included) of hash names to
be returned, empty string ``''`` means +inf
:param string name_end: The upper bound(included) of hash names to be
returned, empty string ``''`` means -inf
:param int limit: number of elements will be returned.
:return: a list of hash's name
:rtype: list
>>> ssdb.hrlist('hash_ ', 'hash_z', 10)
['hash_2', 'hash_1']
>>> ssdb.hrlist('hash_ ', '', 3)
['hash_2', 'hash_1']
>>> ssdb.hrlist('', 'aaa_not_exist', 10)
[]
"""
limit = get_positive_integer('limit', limit)
return self.execute_command('hrlist', name_start, name_end, limit) | [
"def",
"hrlist",
"(",
"self",
",",
"name_start",
",",
"name_end",
",",
"limit",
"=",
"10",
")",
":",
"limit",
"=",
"get_positive_integer",
"(",
"'limit'",
",",
"limit",
")",
"return",
"self",
".",
"execute_command",
"(",
"'hrlist'",
",",
"name_start",
",",
"name_end",
",",
"limit",
")"
] | 42.12 | 18.84 |
def vlan_id(self):
"""
VLAN ID for this interface, if any
:return: VLAN identifier
:rtype: str
"""
nicids = self.nicid.split('-')
if nicids:
u = []
for vlan in nicids:
if vlan.split('.')[-1] not in u:
u.append(vlan.split('.')[-1])
return '-'.join(u) | [
"def",
"vlan_id",
"(",
"self",
")",
":",
"nicids",
"=",
"self",
".",
"nicid",
".",
"split",
"(",
"'-'",
")",
"if",
"nicids",
":",
"u",
"=",
"[",
"]",
"for",
"vlan",
"in",
"nicids",
":",
"if",
"vlan",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"not",
"in",
"u",
":",
"u",
".",
"append",
"(",
"vlan",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
")",
"return",
"'-'",
".",
"join",
"(",
"u",
")"
] | 26.642857 | 11.928571 |
def get_vm(self, name, path=""):
"""Get a VirtualMachine object"""
if path:
return self.get_obj([vim.VirtualMachine], name, path=path)
else:
return self.get_obj([vim.VirtualMachine], name) | [
"def",
"get_vm",
"(",
"self",
",",
"name",
",",
"path",
"=",
"\"\"",
")",
":",
"if",
"path",
":",
"return",
"self",
".",
"get_obj",
"(",
"[",
"vim",
".",
"VirtualMachine",
"]",
",",
"name",
",",
"path",
"=",
"path",
")",
"else",
":",
"return",
"self",
".",
"get_obj",
"(",
"[",
"vim",
".",
"VirtualMachine",
"]",
",",
"name",
")"
] | 38.5 | 18 |
def _parse_team_data(self, team_data):
"""
Parses a value for every attribute.
This function looks through every attribute and retrieves the value
according to the parsing scheme and index of the attribute from the
passed HTML data. Once the value is retrieved, the attribute's value is
updated with the returned result.
Note that this method is called directly once Team is invoked and does
not need to be called manually.
Parameters
----------
team_data : string
A string containing all of the rows of stats for a given team. If
multiple tables are being referenced, this will be comprised of
multiple rows in a single string.
"""
for field in self.__dict__:
if field == '_year' or \
field == '_team_conference':
continue
value = utils._parse_field(PARSING_SCHEME,
team_data,
# Remove the '_' from the name
str(field)[1:])
setattr(self, field, value) | [
"def",
"_parse_team_data",
"(",
"self",
",",
"team_data",
")",
":",
"for",
"field",
"in",
"self",
".",
"__dict__",
":",
"if",
"field",
"==",
"'_year'",
"or",
"field",
"==",
"'_team_conference'",
":",
"continue",
"value",
"=",
"utils",
".",
"_parse_field",
"(",
"PARSING_SCHEME",
",",
"team_data",
",",
"# Remove the '_' from the name",
"str",
"(",
"field",
")",
"[",
"1",
":",
"]",
")",
"setattr",
"(",
"self",
",",
"field",
",",
"value",
")"
] | 41.142857 | 18 |
def partition(args):
"""
%prog partition happy.txt synteny.graph
Select edges from another graph and merge it with the certain edges built
from the HAPPY mapping data.
"""
allowed_format = ("png", "ps")
p = OptionParser(partition.__doc__)
p.add_option("--prefix", help="Add prefix to the name [default: %default]")
p.add_option("--namestart", default=0, type="int",
help="Use a shorter name, starting index [default: %default]")
p.add_option("--format", default="png", choices=allowed_format,
help="Generate image of format [default: %default]")
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
happyfile, graphfile = args
bg = BiGraph()
bg.read(graphfile, color="red")
prefix = opts.prefix
fp = open(happyfile)
for i, row in enumerate(fp):
nns = happy_nodes(row, prefix=prefix)
nodes = set(nns)
edges = happy_edges(row, prefix=prefix)
small_graph = BiGraph()
for (a, b, oa, ob), is_uncertain in edges:
color = "gray" if is_uncertain else "black"
small_graph.add_edge(a, b, oa, ob, color=color)
for (u, v), e in bg.edges.items():
# Grab edge if both vertices are on the same line
if u in nodes and v in nodes:
uv = (str(u), str(v))
if uv in small_graph.edges:
e = small_graph.edges[uv]
e.color = "blue" # supported by both evidences
else:
small_graph.add_edge(e)
print(small_graph, file=sys.stderr)
pngfile = "A{0:02d}.{1}".format(i + 1, opts.format)
telomeres = (nns[0], nns[-1])
small_graph.draw(pngfile, namestart=opts.namestart,
nodehighlight=telomeres, dpi=72)
legend = ["Edge colors:"]
legend.append("[BLUE] Experimental + Synteny")
legend.append("[BLACK] Experimental certain")
legend.append("[GRAY] Experimental uncertain")
legend.append("[RED] Synteny only")
legend.append("Rectangle nodes are telomeres.")
print("\n".join(legend), file=sys.stderr) | [
"def",
"partition",
"(",
"args",
")",
":",
"allowed_format",
"=",
"(",
"\"png\"",
",",
"\"ps\"",
")",
"p",
"=",
"OptionParser",
"(",
"partition",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--prefix\"",
",",
"help",
"=",
"\"Add prefix to the name [default: %default]\"",
")",
"p",
".",
"add_option",
"(",
"\"--namestart\"",
",",
"default",
"=",
"0",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"Use a shorter name, starting index [default: %default]\"",
")",
"p",
".",
"add_option",
"(",
"\"--format\"",
",",
"default",
"=",
"\"png\"",
",",
"choices",
"=",
"allowed_format",
",",
"help",
"=",
"\"Generate image of format [default: %default]\"",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
"not",
"p",
".",
"print_help",
"(",
")",
")",
"happyfile",
",",
"graphfile",
"=",
"args",
"bg",
"=",
"BiGraph",
"(",
")",
"bg",
".",
"read",
"(",
"graphfile",
",",
"color",
"=",
"\"red\"",
")",
"prefix",
"=",
"opts",
".",
"prefix",
"fp",
"=",
"open",
"(",
"happyfile",
")",
"for",
"i",
",",
"row",
"in",
"enumerate",
"(",
"fp",
")",
":",
"nns",
"=",
"happy_nodes",
"(",
"row",
",",
"prefix",
"=",
"prefix",
")",
"nodes",
"=",
"set",
"(",
"nns",
")",
"edges",
"=",
"happy_edges",
"(",
"row",
",",
"prefix",
"=",
"prefix",
")",
"small_graph",
"=",
"BiGraph",
"(",
")",
"for",
"(",
"a",
",",
"b",
",",
"oa",
",",
"ob",
")",
",",
"is_uncertain",
"in",
"edges",
":",
"color",
"=",
"\"gray\"",
"if",
"is_uncertain",
"else",
"\"black\"",
"small_graph",
".",
"add_edge",
"(",
"a",
",",
"b",
",",
"oa",
",",
"ob",
",",
"color",
"=",
"color",
")",
"for",
"(",
"u",
",",
"v",
")",
",",
"e",
"in",
"bg",
".",
"edges",
".",
"items",
"(",
")",
":",
"# Grab edge if both vertices are on the same line",
"if",
"u",
"in",
"nodes",
"and",
"v",
"in",
"nodes",
":",
"uv",
"=",
"(",
"str",
"(",
"u",
")",
",",
"str",
"(",
"v",
")",
")",
"if",
"uv",
"in",
"small_graph",
".",
"edges",
":",
"e",
"=",
"small_graph",
".",
"edges",
"[",
"uv",
"]",
"e",
".",
"color",
"=",
"\"blue\"",
"# supported by both evidences",
"else",
":",
"small_graph",
".",
"add_edge",
"(",
"e",
")",
"print",
"(",
"small_graph",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"pngfile",
"=",
"\"A{0:02d}.{1}\"",
".",
"format",
"(",
"i",
"+",
"1",
",",
"opts",
".",
"format",
")",
"telomeres",
"=",
"(",
"nns",
"[",
"0",
"]",
",",
"nns",
"[",
"-",
"1",
"]",
")",
"small_graph",
".",
"draw",
"(",
"pngfile",
",",
"namestart",
"=",
"opts",
".",
"namestart",
",",
"nodehighlight",
"=",
"telomeres",
",",
"dpi",
"=",
"72",
")",
"legend",
"=",
"[",
"\"Edge colors:\"",
"]",
"legend",
".",
"append",
"(",
"\"[BLUE] Experimental + Synteny\"",
")",
"legend",
".",
"append",
"(",
"\"[BLACK] Experimental certain\"",
")",
"legend",
".",
"append",
"(",
"\"[GRAY] Experimental uncertain\"",
")",
"legend",
".",
"append",
"(",
"\"[RED] Synteny only\"",
")",
"legend",
".",
"append",
"(",
"\"Rectangle nodes are telomeres.\"",
")",
"print",
"(",
"\"\\n\"",
".",
"join",
"(",
"legend",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | 36.862069 | 15.931034 |
def install_json_schema(self):
"""Load install.json schema file."""
if self._install_json_schema is None and self.install_json_schema_file is not None:
# remove old schema file
if os.path.isfile('tcex_json_schema.json'):
# this file is now part of tcex.
os.remove('tcex_json_schema.json')
if os.path.isfile(self.install_json_schema_file):
with open(self.install_json_schema_file) as fh:
self._install_json_schema = json.load(fh)
return self._install_json_schema | [
"def",
"install_json_schema",
"(",
"self",
")",
":",
"if",
"self",
".",
"_install_json_schema",
"is",
"None",
"and",
"self",
".",
"install_json_schema_file",
"is",
"not",
"None",
":",
"# remove old schema file",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"'tcex_json_schema.json'",
")",
":",
"# this file is now part of tcex.",
"os",
".",
"remove",
"(",
"'tcex_json_schema.json'",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"install_json_schema_file",
")",
":",
"with",
"open",
"(",
"self",
".",
"install_json_schema_file",
")",
"as",
"fh",
":",
"self",
".",
"_install_json_schema",
"=",
"json",
".",
"load",
"(",
"fh",
")",
"return",
"self",
".",
"_install_json_schema"
] | 48.25 | 16.916667 |
def _check_guts_toc_mtime(attr, old, toc, last_build, pyc=0):
"""
rebuild is required if mtimes of files listed in old toc are newer
than ast_build
if pyc=1, check for .py files, too
"""
for (nm, fnm, typ) in old:
if mtime(fnm) > last_build:
logger.info("building because %s changed", fnm)
return True
elif pyc and mtime(fnm[:-1]) > last_build:
logger.info("building because %s changed", fnm[:-1])
return True
return False | [
"def",
"_check_guts_toc_mtime",
"(",
"attr",
",",
"old",
",",
"toc",
",",
"last_build",
",",
"pyc",
"=",
"0",
")",
":",
"for",
"(",
"nm",
",",
"fnm",
",",
"typ",
")",
"in",
"old",
":",
"if",
"mtime",
"(",
"fnm",
")",
">",
"last_build",
":",
"logger",
".",
"info",
"(",
"\"building because %s changed\"",
",",
"fnm",
")",
"return",
"True",
"elif",
"pyc",
"and",
"mtime",
"(",
"fnm",
"[",
":",
"-",
"1",
"]",
")",
">",
"last_build",
":",
"logger",
".",
"info",
"(",
"\"building because %s changed\"",
",",
"fnm",
"[",
":",
"-",
"1",
"]",
")",
"return",
"True",
"return",
"False"
] | 33.4 | 16.066667 |
def get_factors_iterative2(n):
"""[summary]
analog as above
Arguments:
n {[int]} -- [description]
Returns:
[list of lists] -- [all factors of n]
"""
ans, stack, x = [], [], 2
while True:
if x > n // x:
if not stack:
return ans
ans.append(stack + [n])
x = stack.pop()
n *= x
x += 1
elif n % x == 0:
stack.append(x)
n //= x
else:
x += 1 | [
"def",
"get_factors_iterative2",
"(",
"n",
")",
":",
"ans",
",",
"stack",
",",
"x",
"=",
"[",
"]",
",",
"[",
"]",
",",
"2",
"while",
"True",
":",
"if",
"x",
">",
"n",
"//",
"x",
":",
"if",
"not",
"stack",
":",
"return",
"ans",
"ans",
".",
"append",
"(",
"stack",
"+",
"[",
"n",
"]",
")",
"x",
"=",
"stack",
".",
"pop",
"(",
")",
"n",
"*=",
"x",
"x",
"+=",
"1",
"elif",
"n",
"%",
"x",
"==",
"0",
":",
"stack",
".",
"append",
"(",
"x",
")",
"n",
"//=",
"x",
"else",
":",
"x",
"+=",
"1"
] | 19.88 | 18.24 |
def low_connectivity_nodes(self, impedance, count, imp_name=None):
"""
Identify nodes that are connected to fewer than some threshold
of other nodes within a given distance.
Parameters
----------
impedance : float
Distance within which to search for other connected nodes. This
will usually be a distance unit in meters however if you have
customized the impedance this could be in other units such as
utility or time etc.
count : int
Threshold for connectivity. If a node is connected to fewer
than this many nodes within `impedance` it will be identified
as "low connectivity".
imp_name : string, optional
The impedance name to use for the aggregation on this network.
Must be one of the impedance names passed in the constructor of
this object. If not specified, there must be only one impedance
passed in the constructor, which will be used.
Returns
-------
node_ids : array
List of "low connectivity" node IDs.
"""
# set a counter variable on all nodes
self.set(self.node_ids.to_series(), name='counter')
# count nodes within impedance range
agg = self.aggregate(
impedance, type='count', imp_name=imp_name, name='counter')
return np.array(agg[agg < count].index) | [
"def",
"low_connectivity_nodes",
"(",
"self",
",",
"impedance",
",",
"count",
",",
"imp_name",
"=",
"None",
")",
":",
"# set a counter variable on all nodes",
"self",
".",
"set",
"(",
"self",
".",
"node_ids",
".",
"to_series",
"(",
")",
",",
"name",
"=",
"'counter'",
")",
"# count nodes within impedance range",
"agg",
"=",
"self",
".",
"aggregate",
"(",
"impedance",
",",
"type",
"=",
"'count'",
",",
"imp_name",
"=",
"imp_name",
",",
"name",
"=",
"'counter'",
")",
"return",
"np",
".",
"array",
"(",
"agg",
"[",
"agg",
"<",
"count",
"]",
".",
"index",
")"
] | 39.75 | 22.25 |
def get_context_for_image(self, zoom):
"""Creates a temporary cairo context for the image surface
:param zoom: The current scaling factor
:return: Cairo context to draw on
"""
cairo_context = Context(self.__image)
cairo_context.scale(zoom * self.multiplicator, zoom * self.multiplicator)
return cairo_context | [
"def",
"get_context_for_image",
"(",
"self",
",",
"zoom",
")",
":",
"cairo_context",
"=",
"Context",
"(",
"self",
".",
"__image",
")",
"cairo_context",
".",
"scale",
"(",
"zoom",
"*",
"self",
".",
"multiplicator",
",",
"zoom",
"*",
"self",
".",
"multiplicator",
")",
"return",
"cairo_context"
] | 39.666667 | 12 |
def gid(self):
"""Return the group id that the daemon will run with
:rtype: int
"""
if not self._gid:
if self.controller.config.daemon.group:
self._gid = grp.getgrnam(self.config.daemon.group).gr_gid
else:
self._gid = os.getgid()
return self._gid | [
"def",
"gid",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_gid",
":",
"if",
"self",
".",
"controller",
".",
"config",
".",
"daemon",
".",
"group",
":",
"self",
".",
"_gid",
"=",
"grp",
".",
"getgrnam",
"(",
"self",
".",
"config",
".",
"daemon",
".",
"group",
")",
".",
"gr_gid",
"else",
":",
"self",
".",
"_gid",
"=",
"os",
".",
"getgid",
"(",
")",
"return",
"self",
".",
"_gid"
] | 27.75 | 18.833333 |
def join(self, room):
"""Lets a user join a room on a specific Namespace."""
self.socket.rooms.add(self._get_room_name(room)) | [
"def",
"join",
"(",
"self",
",",
"room",
")",
":",
"self",
".",
"socket",
".",
"rooms",
".",
"add",
"(",
"self",
".",
"_get_room_name",
"(",
"room",
")",
")"
] | 46.333333 | 11.666667 |
def valid_checksum(file, hash_file):
"""
Summary:
Validate file checksum using md5 hash
Args:
file: file object to verify integrity
hash_file: md5 reference checksum file
Returns:
Valid (True) | False, TYPE: bool
"""
bits = 4096
# calc md5 hash
hash_md5 = hashlib.md5()
with open(file, "rb") as f:
for chunk in iter(lambda: f.read(bits), b""):
hash_md5.update(chunk)
# locate hash signature for file, validate
with open(hash_file) as c:
for line in c.readlines():
if line.strip():
check_list = line.split()
if file == check_list[1]:
if check_list[0] == hash_md5.hexdigest():
return True
return False | [
"def",
"valid_checksum",
"(",
"file",
",",
"hash_file",
")",
":",
"bits",
"=",
"4096",
"# calc md5 hash",
"hash_md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"open",
"(",
"file",
",",
"\"rb\"",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"bits",
")",
",",
"b\"\"",
")",
":",
"hash_md5",
".",
"update",
"(",
"chunk",
")",
"# locate hash signature for file, validate",
"with",
"open",
"(",
"hash_file",
")",
"as",
"c",
":",
"for",
"line",
"in",
"c",
".",
"readlines",
"(",
")",
":",
"if",
"line",
".",
"strip",
"(",
")",
":",
"check_list",
"=",
"line",
".",
"split",
"(",
")",
"if",
"file",
"==",
"check_list",
"[",
"1",
"]",
":",
"if",
"check_list",
"[",
"0",
"]",
"==",
"hash_md5",
".",
"hexdigest",
"(",
")",
":",
"return",
"True",
"return",
"False"
] | 30.88 | 11.2 |
def maybe_add_child(self, fcoord):
""" Adds child node for fcoord if it doesn't already exist, and returns it. """
if fcoord not in self.children:
new_position = self.position.play_move(
coords.from_flat(fcoord))
self.children[fcoord] = MCTSNode(
new_position, fmove=fcoord, parent=self)
return self.children[fcoord] | [
"def",
"maybe_add_child",
"(",
"self",
",",
"fcoord",
")",
":",
"if",
"fcoord",
"not",
"in",
"self",
".",
"children",
":",
"new_position",
"=",
"self",
".",
"position",
".",
"play_move",
"(",
"coords",
".",
"from_flat",
"(",
"fcoord",
")",
")",
"self",
".",
"children",
"[",
"fcoord",
"]",
"=",
"MCTSNode",
"(",
"new_position",
",",
"fmove",
"=",
"fcoord",
",",
"parent",
"=",
"self",
")",
"return",
"self",
".",
"children",
"[",
"fcoord",
"]"
] | 48.625 | 5.5 |
def input_to_phase(data, rate, data_type):
""" Take either phase or frequency as input and return phase
"""
if data_type == "phase":
return data
elif data_type == "freq":
return frequency2phase(data, rate)
else:
raise Exception("unknown data_type: " + data_type) | [
"def",
"input_to_phase",
"(",
"data",
",",
"rate",
",",
"data_type",
")",
":",
"if",
"data_type",
"==",
"\"phase\"",
":",
"return",
"data",
"elif",
"data_type",
"==",
"\"freq\"",
":",
"return",
"frequency2phase",
"(",
"data",
",",
"rate",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"unknown data_type: \"",
"+",
"data_type",
")"
] | 33.111111 | 10.777778 |
def to_tree(instance, *children):
"""
Generate tree structure of an instance, and its children. This method
yields its results, instead of returning them.
"""
# Yield representation of self
yield unicode(instance)
# Iterate trough each instance child collection
for i, child in enumerate(children):
lines = 0
yield "|"
yield "+---" + unicode(child)
if i != len(children) - 1:
a = "|"
else:
a = " "
# Iterate trough all values of collection of child
for j, item in enumerate(child.itervalues()):
if j != len(child) - 1:
b = "|"
else:
b = " "
if j == 0:
yield a + " |"
# Append prefix to each line
for k, line in enumerate(item.to_tree()):
lines += 1
if k == 0:
yield a + " +---" + line
else:
yield a + " " + b + " " + line
# Add extra space if required
if len(children) > 1 and i == len(children) - 1 and lines > 1:
yield a | [
"def",
"to_tree",
"(",
"instance",
",",
"*",
"children",
")",
":",
"# Yield representation of self",
"yield",
"unicode",
"(",
"instance",
")",
"# Iterate trough each instance child collection",
"for",
"i",
",",
"child",
"in",
"enumerate",
"(",
"children",
")",
":",
"lines",
"=",
"0",
"yield",
"\"|\"",
"yield",
"\"+---\"",
"+",
"unicode",
"(",
"child",
")",
"if",
"i",
"!=",
"len",
"(",
"children",
")",
"-",
"1",
":",
"a",
"=",
"\"|\"",
"else",
":",
"a",
"=",
"\" \"",
"# Iterate trough all values of collection of child",
"for",
"j",
",",
"item",
"in",
"enumerate",
"(",
"child",
".",
"itervalues",
"(",
")",
")",
":",
"if",
"j",
"!=",
"len",
"(",
"child",
")",
"-",
"1",
":",
"b",
"=",
"\"|\"",
"else",
":",
"b",
"=",
"\" \"",
"if",
"j",
"==",
"0",
":",
"yield",
"a",
"+",
"\" |\"",
"# Append prefix to each line",
"for",
"k",
",",
"line",
"in",
"enumerate",
"(",
"item",
".",
"to_tree",
"(",
")",
")",
":",
"lines",
"+=",
"1",
"if",
"k",
"==",
"0",
":",
"yield",
"a",
"+",
"\" +---\"",
"+",
"line",
"else",
":",
"yield",
"a",
"+",
"\" \"",
"+",
"b",
"+",
"\" \"",
"+",
"line",
"# Add extra space if required",
"if",
"len",
"(",
"children",
")",
">",
"1",
"and",
"i",
"==",
"len",
"(",
"children",
")",
"-",
"1",
"and",
"lines",
">",
"1",
":",
"yield",
"a"
] | 26.348837 | 19 |
def t_escaped_LINE_FEED_CHAR(self, t):
r'\x6E' # 'n'
t.lexer.pop_state()
t.value = unichr(0x000a)
return t | [
"def",
"t_escaped_LINE_FEED_CHAR",
"(",
"self",
",",
"t",
")",
":",
"# 'n'",
"t",
".",
"lexer",
".",
"pop_state",
"(",
")",
"t",
".",
"value",
"=",
"unichr",
"(",
"0x000a",
")",
"return",
"t"
] | 27 | 13 |
def is_on(self, channel):
"""
Check if a switch is turned on
:return: bool
"""
if channel in self._is_on:
return self._is_on[channel]
return False | [
"def",
"is_on",
"(",
"self",
",",
"channel",
")",
":",
"if",
"channel",
"in",
"self",
".",
"_is_on",
":",
"return",
"self",
".",
"_is_on",
"[",
"channel",
"]",
"return",
"False"
] | 22.111111 | 11.444444 |
def set_parallel_multiple(self, value):
"""
Setter for 'parallel_multiple' field.
:param value - a new value of 'parallel_multiple' field. Must be a boolean type. Does not accept None value.
"""
if value is None or not isinstance(value, bool):
raise TypeError("ParallelMultiple must be set to a bool")
else:
self.__parallel_multiple = value | [
"def",
"set_parallel_multiple",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"ParallelMultiple must be set to a bool\"",
")",
"else",
":",
"self",
".",
"__parallel_multiple",
"=",
"value"
] | 44.888889 | 17.555556 |
def precheck(context):
"""
calls a function named "precheck_<key>" where <key> is context_key with '-' changed to '_'
(e.g. "precheck_ami_id")
Checking function should return True if OK, or raise RuntimeError w/ message if not
Args:
context: a populated EFVersionContext object
Returns:
True if the precheck passed, or if there was no precheck function for context.key
Raises:
RuntimeError if precheck failed, with explanatory message
"""
if context.noprecheck:
return True
func_name = "precheck_" + context.key.replace("-", "_")
if func_name in globals() and isfunction(globals()[func_name]):
return globals()[func_name](context)
else:
return True | [
"def",
"precheck",
"(",
"context",
")",
":",
"if",
"context",
".",
"noprecheck",
":",
"return",
"True",
"func_name",
"=",
"\"precheck_\"",
"+",
"context",
".",
"key",
".",
"replace",
"(",
"\"-\"",
",",
"\"_\"",
")",
"if",
"func_name",
"in",
"globals",
"(",
")",
"and",
"isfunction",
"(",
"globals",
"(",
")",
"[",
"func_name",
"]",
")",
":",
"return",
"globals",
"(",
")",
"[",
"func_name",
"]",
"(",
"context",
")",
"else",
":",
"return",
"True"
] | 35.684211 | 23.052632 |
def _m2crypto_sign(message, ssldir=None, certname=None, **config):
""" Insert two new fields into the message dict and return it.
Those fields are:
- 'signature' - the computed RSA message digest of the JSON repr.
- 'certificate' - the base64 X509 certificate of the sending host.
"""
if ssldir is None or certname is None:
error = "You must set the ssldir and certname keyword arguments."
raise ValueError(error)
message['crypto'] = 'x509'
certificate = M2Crypto.X509.load_cert(
"%s/%s.crt" % (ssldir, certname)).as_pem()
# Opening this file requires elevated privileges in stg/prod.
rsa_private = M2Crypto.RSA.load_key(
"%s/%s.key" % (ssldir, certname))
digest = M2Crypto.EVP.MessageDigest('sha1')
digest.update(fedmsg.encoding.dumps(message))
signature = rsa_private.sign(digest.digest())
# Return a new dict containing the pairs in the original message as well
# as the new authn fields.
return dict(message.items() + [
('signature', signature.encode('base64').decode('ascii')),
('certificate', certificate.encode('base64').decode('ascii')),
]) | [
"def",
"_m2crypto_sign",
"(",
"message",
",",
"ssldir",
"=",
"None",
",",
"certname",
"=",
"None",
",",
"*",
"*",
"config",
")",
":",
"if",
"ssldir",
"is",
"None",
"or",
"certname",
"is",
"None",
":",
"error",
"=",
"\"You must set the ssldir and certname keyword arguments.\"",
"raise",
"ValueError",
"(",
"error",
")",
"message",
"[",
"'crypto'",
"]",
"=",
"'x509'",
"certificate",
"=",
"M2Crypto",
".",
"X509",
".",
"load_cert",
"(",
"\"%s/%s.crt\"",
"%",
"(",
"ssldir",
",",
"certname",
")",
")",
".",
"as_pem",
"(",
")",
"# Opening this file requires elevated privileges in stg/prod.",
"rsa_private",
"=",
"M2Crypto",
".",
"RSA",
".",
"load_key",
"(",
"\"%s/%s.key\"",
"%",
"(",
"ssldir",
",",
"certname",
")",
")",
"digest",
"=",
"M2Crypto",
".",
"EVP",
".",
"MessageDigest",
"(",
"'sha1'",
")",
"digest",
".",
"update",
"(",
"fedmsg",
".",
"encoding",
".",
"dumps",
"(",
"message",
")",
")",
"signature",
"=",
"rsa_private",
".",
"sign",
"(",
"digest",
".",
"digest",
"(",
")",
")",
"# Return a new dict containing the pairs in the original message as well",
"# as the new authn fields.",
"return",
"dict",
"(",
"message",
".",
"items",
"(",
")",
"+",
"[",
"(",
"'signature'",
",",
"signature",
".",
"encode",
"(",
"'base64'",
")",
".",
"decode",
"(",
"'ascii'",
")",
")",
",",
"(",
"'certificate'",
",",
"certificate",
".",
"encode",
"(",
"'base64'",
")",
".",
"decode",
"(",
"'ascii'",
")",
")",
",",
"]",
")"
] | 37.064516 | 20.967742 |
def factorization_machine_model(factor_size, num_features,
lr_mult_config, wd_mult_config, init_config):
""" builds factorization machine network with proper formulation:
y = w_0 \sum(x_i w_i) + 0.5(\sum\sum<v_i,v_j>x_ix_j - \sum<v_iv_i>x_i^2)
"""
x = mx.symbol.Variable("data", stype='csr')
# factor, linear and bias terms
v = mx.symbol.Variable("v", shape=(num_features, factor_size), stype='row_sparse',
init=init_config['v'], lr_mult=lr_mult_config['v'],
wd_mult=wd_mult_config['v'])
w = mx.symbol.Variable('w', shape=(num_features, 1), stype='row_sparse',
init=init_config['w'], lr_mult=lr_mult_config['w'],
wd_mult=wd_mult_config['w'])
w0 = mx.symbol.Variable('w0', shape=(1,), init=init_config['w0'],
lr_mult=lr_mult_config['w0'], wd_mult=wd_mult_config['w0'])
w1 = mx.symbol.broadcast_add(mx.symbol.dot(x, w), w0)
# squared terms for subtracting self interactions
v_s = mx.symbol._internal._square_sum(data=v, axis=1, keepdims=True)
x_s = x.square()
bd_sum = mx.sym.dot(x_s, v_s)
# interactions
w2 = mx.symbol.dot(x, v)
w2_squared = 0.5 * mx.symbol.square(data=w2)
# putting everything together
w_all = mx.symbol.Concat(w1, w2_squared, dim=1)
sum1 = w_all.sum(axis=1, keepdims=True)
sum2 = -0.5 * bd_sum
model = sum1 + sum2
y = mx.symbol.Variable("softmax_label")
model = mx.symbol.LogisticRegressionOutput(data=model, label=y)
return model | [
"def",
"factorization_machine_model",
"(",
"factor_size",
",",
"num_features",
",",
"lr_mult_config",
",",
"wd_mult_config",
",",
"init_config",
")",
":",
"x",
"=",
"mx",
".",
"symbol",
".",
"Variable",
"(",
"\"data\"",
",",
"stype",
"=",
"'csr'",
")",
"# factor, linear and bias terms",
"v",
"=",
"mx",
".",
"symbol",
".",
"Variable",
"(",
"\"v\"",
",",
"shape",
"=",
"(",
"num_features",
",",
"factor_size",
")",
",",
"stype",
"=",
"'row_sparse'",
",",
"init",
"=",
"init_config",
"[",
"'v'",
"]",
",",
"lr_mult",
"=",
"lr_mult_config",
"[",
"'v'",
"]",
",",
"wd_mult",
"=",
"wd_mult_config",
"[",
"'v'",
"]",
")",
"w",
"=",
"mx",
".",
"symbol",
".",
"Variable",
"(",
"'w'",
",",
"shape",
"=",
"(",
"num_features",
",",
"1",
")",
",",
"stype",
"=",
"'row_sparse'",
",",
"init",
"=",
"init_config",
"[",
"'w'",
"]",
",",
"lr_mult",
"=",
"lr_mult_config",
"[",
"'w'",
"]",
",",
"wd_mult",
"=",
"wd_mult_config",
"[",
"'w'",
"]",
")",
"w0",
"=",
"mx",
".",
"symbol",
".",
"Variable",
"(",
"'w0'",
",",
"shape",
"=",
"(",
"1",
",",
")",
",",
"init",
"=",
"init_config",
"[",
"'w0'",
"]",
",",
"lr_mult",
"=",
"lr_mult_config",
"[",
"'w0'",
"]",
",",
"wd_mult",
"=",
"wd_mult_config",
"[",
"'w0'",
"]",
")",
"w1",
"=",
"mx",
".",
"symbol",
".",
"broadcast_add",
"(",
"mx",
".",
"symbol",
".",
"dot",
"(",
"x",
",",
"w",
")",
",",
"w0",
")",
"# squared terms for subtracting self interactions",
"v_s",
"=",
"mx",
".",
"symbol",
".",
"_internal",
".",
"_square_sum",
"(",
"data",
"=",
"v",
",",
"axis",
"=",
"1",
",",
"keepdims",
"=",
"True",
")",
"x_s",
"=",
"x",
".",
"square",
"(",
")",
"bd_sum",
"=",
"mx",
".",
"sym",
".",
"dot",
"(",
"x_s",
",",
"v_s",
")",
"# interactions",
"w2",
"=",
"mx",
".",
"symbol",
".",
"dot",
"(",
"x",
",",
"v",
")",
"w2_squared",
"=",
"0.5",
"*",
"mx",
".",
"symbol",
".",
"square",
"(",
"data",
"=",
"w2",
")",
"# putting everything together",
"w_all",
"=",
"mx",
".",
"symbol",
".",
"Concat",
"(",
"w1",
",",
"w2_squared",
",",
"dim",
"=",
"1",
")",
"sum1",
"=",
"w_all",
".",
"sum",
"(",
"axis",
"=",
"1",
",",
"keepdims",
"=",
"True",
")",
"sum2",
"=",
"-",
"0.5",
"*",
"bd_sum",
"model",
"=",
"sum1",
"+",
"sum2",
"y",
"=",
"mx",
".",
"symbol",
".",
"Variable",
"(",
"\"softmax_label\"",
")",
"model",
"=",
"mx",
".",
"symbol",
".",
"LogisticRegressionOutput",
"(",
"data",
"=",
"model",
",",
"label",
"=",
"y",
")",
"return",
"model"
] | 44.771429 | 21.457143 |
def create_publication_assistant(self, **args):
'''
Create an assistant for a dataset that allows to make PID
requests for the dataset and all of its files.
:param drs_id: Mandatory. The dataset id of the dataset
to be published.
:param version_number: Mandatory. The version number of the
dataset to be published.
:param is_replica: Mandatory. Flag to indicate whether the
dataset is a replica.
.. note:: If the replica flag is set to False, the publication
may still be considered a replica by the consuming servlet,
namely if the dataset was already published at a different
host. For this, please refer to the consumer documentation.
:return: A publication assistant which provides all necessary
methods to publish a dataset and its files.
'''
# Check args
logdebug(LOGGER, 'Creating publication assistant..')
mandatory_args = ['drs_id', 'version_number', 'is_replica']
esgfpid.utils.check_presence_of_mandatory_args(args, mandatory_args)
# Check if service path is given
if self.__thredds_service_path is None:
msg = 'No thredds_service_path given (but it is mandatory for publication)'
logwarn(LOGGER, msg)
raise esgfpid.exceptions.ArgumentError(msg)
# Check if data node is given
if self.__data_node is None:
msg = 'No data_node given (but it is mandatory for publication)'
logwarn(LOGGER, msg)
raise esgfpid.exceptions.ArgumentError(msg)
# Check if solr has access:
if self.__coupler.is_solr_switched_off():
pass # solr access not mandatory anymore
# Create publication assistant
assistant = esgfpid.assistant.publish.DatasetPublicationAssistant(
drs_id=args['drs_id'],
version_number=args['version_number'],
thredds_service_path=self.__thredds_service_path,
data_node=self.__data_node,
prefix=self.prefix,
coupler=self.__coupler,
is_replica=args['is_replica'],
consumer_solr_url=self.__consumer_solr_url # may be None
)
logdebug(LOGGER, 'Creating publication assistant.. done')
return assistant | [
"def",
"create_publication_assistant",
"(",
"self",
",",
"*",
"*",
"args",
")",
":",
"# Check args",
"logdebug",
"(",
"LOGGER",
",",
"'Creating publication assistant..'",
")",
"mandatory_args",
"=",
"[",
"'drs_id'",
",",
"'version_number'",
",",
"'is_replica'",
"]",
"esgfpid",
".",
"utils",
".",
"check_presence_of_mandatory_args",
"(",
"args",
",",
"mandatory_args",
")",
"# Check if service path is given",
"if",
"self",
".",
"__thredds_service_path",
"is",
"None",
":",
"msg",
"=",
"'No thredds_service_path given (but it is mandatory for publication)'",
"logwarn",
"(",
"LOGGER",
",",
"msg",
")",
"raise",
"esgfpid",
".",
"exceptions",
".",
"ArgumentError",
"(",
"msg",
")",
"# Check if data node is given",
"if",
"self",
".",
"__data_node",
"is",
"None",
":",
"msg",
"=",
"'No data_node given (but it is mandatory for publication)'",
"logwarn",
"(",
"LOGGER",
",",
"msg",
")",
"raise",
"esgfpid",
".",
"exceptions",
".",
"ArgumentError",
"(",
"msg",
")",
"# Check if solr has access:",
"if",
"self",
".",
"__coupler",
".",
"is_solr_switched_off",
"(",
")",
":",
"pass",
"# solr access not mandatory anymore",
"# Create publication assistant",
"assistant",
"=",
"esgfpid",
".",
"assistant",
".",
"publish",
".",
"DatasetPublicationAssistant",
"(",
"drs_id",
"=",
"args",
"[",
"'drs_id'",
"]",
",",
"version_number",
"=",
"args",
"[",
"'version_number'",
"]",
",",
"thredds_service_path",
"=",
"self",
".",
"__thredds_service_path",
",",
"data_node",
"=",
"self",
".",
"__data_node",
",",
"prefix",
"=",
"self",
".",
"prefix",
",",
"coupler",
"=",
"self",
".",
"__coupler",
",",
"is_replica",
"=",
"args",
"[",
"'is_replica'",
"]",
",",
"consumer_solr_url",
"=",
"self",
".",
"__consumer_solr_url",
"# may be None",
")",
"logdebug",
"(",
"LOGGER",
",",
"'Creating publication assistant.. done'",
")",
"return",
"assistant"
] | 42.054545 | 20.927273 |
def write_shortstr(self, s):
"""Write a string up to 255 bytes long (after any encoding).
If passed a unicode string, encode with UTF-8.
"""
self._flushbits()
if isinstance(s, string):
s = s.encode('utf-8')
if len(s) > 255:
raise FrameSyntaxError(
'Shortstring overflow ({0} > 255)'.format(len(s)))
self.write_octet(len(s))
self.out.write(s) | [
"def",
"write_shortstr",
"(",
"self",
",",
"s",
")",
":",
"self",
".",
"_flushbits",
"(",
")",
"if",
"isinstance",
"(",
"s",
",",
"string",
")",
":",
"s",
"=",
"s",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"len",
"(",
"s",
")",
">",
"255",
":",
"raise",
"FrameSyntaxError",
"(",
"'Shortstring overflow ({0} > 255)'",
".",
"format",
"(",
"len",
"(",
"s",
")",
")",
")",
"self",
".",
"write_octet",
"(",
"len",
"(",
"s",
")",
")",
"self",
".",
"out",
".",
"write",
"(",
"s",
")"
] | 31 | 14.642857 |
def feed_parser(self, data):
"""Parse received message."""
assert isinstance(data, bytes)
self.controller.feed_parser(data) | [
"def",
"feed_parser",
"(",
"self",
",",
"data",
")",
":",
"assert",
"isinstance",
"(",
"data",
",",
"bytes",
")",
"self",
".",
"controller",
".",
"feed_parser",
"(",
"data",
")"
] | 36 | 3.75 |
def no_exception(on_exception, logger=None):
"""
处理函数抛出异常的装饰器, ATT: on_exception必填
:param on_exception: 遇到异常时函数返回什么内容
"""
def decorator(function):
def wrapper(*args, **kwargs):
try:
result = function(*args, **kwargs)
except Exception, e:
if hasattr(logger, 'exception'):
logger.exception(e)
else:
print traceback.format_exc()
result = on_exception
return result
return wrapper
return decorator | [
"def",
"no_exception",
"(",
"on_exception",
",",
"logger",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"result",
"=",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
",",
"e",
":",
"if",
"hasattr",
"(",
"logger",
",",
"'exception'",
")",
":",
"logger",
".",
"exception",
"(",
"e",
")",
"else",
":",
"print",
"traceback",
".",
"format_exc",
"(",
")",
"result",
"=",
"on_exception",
"return",
"result",
"return",
"wrapper",
"return",
"decorator"
] | 26.47619 | 13.238095 |
def _forgiving_issubclass(derived_class, base_class):
"""Forgiving version of ``issubclass``
Does not throw any exception when arguments are not of class type
"""
return (type(derived_class) is ClassType and \
type(base_class) is ClassType and \
issubclass(derived_class, base_class)) | [
"def",
"_forgiving_issubclass",
"(",
"derived_class",
",",
"base_class",
")",
":",
"return",
"(",
"type",
"(",
"derived_class",
")",
"is",
"ClassType",
"and",
"type",
"(",
"base_class",
")",
"is",
"ClassType",
"and",
"issubclass",
"(",
"derived_class",
",",
"base_class",
")",
")"
] | 39.75 | 13.625 |
def write_context_error_report(self,file,context_type):
"""Write a context error report relative to the target or query into the specified filename
:param file: The name of a file to write the report to
:param context_type: They type of profile, target or query based
:type file: string
:type context_type: string
"""
if context_type == 'target':
r = self.get_target_context_error_report()
elif context_type == 'query':
r = self.get_query_context_error_report()
else:
sys.stderr.write("ERROR invalid type must be target or query\n")
sys.exit()
of = open(file,'w')
of.write("\t".join(r['header'])+"\n")
for row in r['data']:
of.write("\t".join([str(x) for x in row])+"\n")
return | [
"def",
"write_context_error_report",
"(",
"self",
",",
"file",
",",
"context_type",
")",
":",
"if",
"context_type",
"==",
"'target'",
":",
"r",
"=",
"self",
".",
"get_target_context_error_report",
"(",
")",
"elif",
"context_type",
"==",
"'query'",
":",
"r",
"=",
"self",
".",
"get_query_context_error_report",
"(",
")",
"else",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"ERROR invalid type must be target or query\\n\"",
")",
"sys",
".",
"exit",
"(",
")",
"of",
"=",
"open",
"(",
"file",
",",
"'w'",
")",
"of",
".",
"write",
"(",
"\"\\t\"",
".",
"join",
"(",
"r",
"[",
"'header'",
"]",
")",
"+",
"\"\\n\"",
")",
"for",
"row",
"in",
"r",
"[",
"'data'",
"]",
":",
"of",
".",
"write",
"(",
"\"\\t\"",
".",
"join",
"(",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"row",
"]",
")",
"+",
"\"\\n\"",
")",
"return"
] | 35.333333 | 17.142857 |
def load_dict(self, dct):
"""Load a dictionary of configuration values."""
for k, v in dct.items():
setattr(self, k, v) | [
"def",
"load_dict",
"(",
"self",
",",
"dct",
")",
":",
"for",
"k",
",",
"v",
"in",
"dct",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")"
] | 36 | 8 |
def get_sample(self, md5):
"""Get the sample from the data store.
This method first fetches the data from datastore, then cleans it for serialization
and then updates it with 'raw_bytes' item.
Args:
md5: The md5 digest of the sample to be fetched from datastore.
Returns:
The sample dictionary or None
"""
# Support 'short' md5s but don't waste performance if the full md5 is provided
if len(md5) < 32:
md5 = self.get_full_md5(md5, self.sample_collection)
# Grab the sample
sample_info = self.database[self.sample_collection].find_one({'md5': md5})
if not sample_info:
return None
# Get the raw bytes from GridFS (note: this could fail)
try:
grid_fs_id = sample_info['__grid_fs']
sample_info = self.clean_for_serialization(sample_info)
sample_info.update({'raw_bytes':self.gridfs_handle.get(grid_fs_id).read()})
return sample_info
except gridfs.errors.CorruptGridFile:
# If we don't have the gridfs files, delete the entry from samples
self.database[self.sample_collection].update({'md5': md5}, {'md5': None})
return None | [
"def",
"get_sample",
"(",
"self",
",",
"md5",
")",
":",
"# Support 'short' md5s but don't waste performance if the full md5 is provided",
"if",
"len",
"(",
"md5",
")",
"<",
"32",
":",
"md5",
"=",
"self",
".",
"get_full_md5",
"(",
"md5",
",",
"self",
".",
"sample_collection",
")",
"# Grab the sample",
"sample_info",
"=",
"self",
".",
"database",
"[",
"self",
".",
"sample_collection",
"]",
".",
"find_one",
"(",
"{",
"'md5'",
":",
"md5",
"}",
")",
"if",
"not",
"sample_info",
":",
"return",
"None",
"# Get the raw bytes from GridFS (note: this could fail)",
"try",
":",
"grid_fs_id",
"=",
"sample_info",
"[",
"'__grid_fs'",
"]",
"sample_info",
"=",
"self",
".",
"clean_for_serialization",
"(",
"sample_info",
")",
"sample_info",
".",
"update",
"(",
"{",
"'raw_bytes'",
":",
"self",
".",
"gridfs_handle",
".",
"get",
"(",
"grid_fs_id",
")",
".",
"read",
"(",
")",
"}",
")",
"return",
"sample_info",
"except",
"gridfs",
".",
"errors",
".",
"CorruptGridFile",
":",
"# If we don't have the gridfs files, delete the entry from samples",
"self",
".",
"database",
"[",
"self",
".",
"sample_collection",
"]",
".",
"update",
"(",
"{",
"'md5'",
":",
"md5",
"}",
",",
"{",
"'md5'",
":",
"None",
"}",
")",
"return",
"None"
] | 39 | 25.46875 |
def inject_metadata_descriptions(self, term_dict):
'''
Inserts a set of descriptions of meta data terms. These will be displayed
below the scatter plot when a meta data term is clicked. All keys in the term dict
must occur as meta data.
Parameters
----------
term_dict: dict {metadataname: str: 'explanation to insert', ...}
Returns
-------
self: ScatterChart
'''
assert type(term_dict) == dict
if not self.term_doc_matrix.metadata_in_use():
raise TermDocMatrixHasNoMetadataException("No metadata is present in the term document matrix")
# This doesn't seem necessary. If a definition's not in the corpus, it just won't be shown.
# if set(term_dict.keys()) - set(self.term_doc_matrix.get_metadata()) != set():
# raise Exception('The following meta data terms are not present: '
# + ', '.join(list(set(term_dict.keys()) - set(self.term_doc_matrix.get_metadata()))))
if sys.version_info[0] == 2:
assert set([type(v) for v in term_dict.values()]) - set([str, unicode]) == set()
else:
assert set([type(v) for v in term_dict.values()]) - set([str]) == set()
self.metadata_descriptions = term_dict
return self | [
"def",
"inject_metadata_descriptions",
"(",
"self",
",",
"term_dict",
")",
":",
"assert",
"type",
"(",
"term_dict",
")",
"==",
"dict",
"if",
"not",
"self",
".",
"term_doc_matrix",
".",
"metadata_in_use",
"(",
")",
":",
"raise",
"TermDocMatrixHasNoMetadataException",
"(",
"\"No metadata is present in the term document matrix\"",
")",
"# This doesn't seem necessary. If a definition's not in the corpus, it just won't be shown.",
"# if set(term_dict.keys()) - set(self.term_doc_matrix.get_metadata()) != set():",
"# raise Exception('The following meta data terms are not present: '",
"# + ', '.join(list(set(term_dict.keys()) - set(self.term_doc_matrix.get_metadata()))))",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"assert",
"set",
"(",
"[",
"type",
"(",
"v",
")",
"for",
"v",
"in",
"term_dict",
".",
"values",
"(",
")",
"]",
")",
"-",
"set",
"(",
"[",
"str",
",",
"unicode",
"]",
")",
"==",
"set",
"(",
")",
"else",
":",
"assert",
"set",
"(",
"[",
"type",
"(",
"v",
")",
"for",
"v",
"in",
"term_dict",
".",
"values",
"(",
")",
"]",
")",
"-",
"set",
"(",
"[",
"str",
"]",
")",
"==",
"set",
"(",
")",
"self",
".",
"metadata_descriptions",
"=",
"term_dict",
"return",
"self"
] | 45.034483 | 31.793103 |
def get_null_or_blank_query(field=None):
"""
Query for null or blank field.
"""
if not field:
return field
null_q = get_null_query(field)
blank_q = get_blank_query(field)
return (null_q | blank_q) | [
"def",
"get_null_or_blank_query",
"(",
"field",
"=",
"None",
")",
":",
"if",
"not",
"field",
":",
"return",
"field",
"null_q",
"=",
"get_null_query",
"(",
"field",
")",
"blank_q",
"=",
"get_blank_query",
"(",
"field",
")",
"return",
"(",
"null_q",
"|",
"blank_q",
")"
] | 24.888889 | 7.777778 |
def updateUser(self, username, password, fullname, description, email):
""" Updates a user account in the user store
Input:
username - the name of the user. The name must be unique in
the user store.
password - the password for this user.
fullname - an optional full name for the user.
description - an optional field to add comments or description
for the user account.
email - an optional email for the user account.
"""
params = {
"f" : "json",
"username" : username
}
if password is not None:
params['password'] = password
if fullname is not None:
params['fullname'] = fullname
if description is not None:
params['description'] = description
if email is not None:
params['email'] = email
uURL = self._url + "/users/update"
return self._post(url=uURL, param_dict=params,
securityHandler=self._securityHandler,
proxy_url=self._proxy_url,
proxy_port=self._proxy_port) | [
"def",
"updateUser",
"(",
"self",
",",
"username",
",",
"password",
",",
"fullname",
",",
"description",
",",
"email",
")",
":",
"params",
"=",
"{",
"\"f\"",
":",
"\"json\"",
",",
"\"username\"",
":",
"username",
"}",
"if",
"password",
"is",
"not",
"None",
":",
"params",
"[",
"'password'",
"]",
"=",
"password",
"if",
"fullname",
"is",
"not",
"None",
":",
"params",
"[",
"'fullname'",
"]",
"=",
"fullname",
"if",
"description",
"is",
"not",
"None",
":",
"params",
"[",
"'description'",
"]",
"=",
"description",
"if",
"email",
"is",
"not",
"None",
":",
"params",
"[",
"'email'",
"]",
"=",
"email",
"uURL",
"=",
"self",
".",
"_url",
"+",
"\"/users/update\"",
"return",
"self",
".",
"_post",
"(",
"url",
"=",
"uURL",
",",
"param_dict",
"=",
"params",
",",
"securityHandler",
"=",
"self",
".",
"_securityHandler",
",",
"proxy_url",
"=",
"self",
".",
"_proxy_url",
",",
"proxy_port",
"=",
"self",
".",
"_proxy_port",
")"
] | 43.357143 | 13.607143 |
def wer(self, s1, s2):
"""
Computes the Word Error Rate, defined as the edit distance between the
two provided sentences after tokenizing to words.
Arguments:
s1 (string): space-separated sentence
s2 (string): space-separated sentence
"""
# build mapping of words to integers
b = set(s1.split() + s2.split())
word2char = dict(zip(b, range(len(b))))
# map the words to a char array (Levenshtein packages only accepts
# strings)
w1 = [chr(word2char[w]) for w in s1.split()]
w2 = [chr(word2char[w]) for w in s2.split()]
return Lev.distance(''.join(w1), ''.join(w2)) | [
"def",
"wer",
"(",
"self",
",",
"s1",
",",
"s2",
")",
":",
"# build mapping of words to integers",
"b",
"=",
"set",
"(",
"s1",
".",
"split",
"(",
")",
"+",
"s2",
".",
"split",
"(",
")",
")",
"word2char",
"=",
"dict",
"(",
"zip",
"(",
"b",
",",
"range",
"(",
"len",
"(",
"b",
")",
")",
")",
")",
"# map the words to a char array (Levenshtein packages only accepts",
"# strings)",
"w1",
"=",
"[",
"chr",
"(",
"word2char",
"[",
"w",
"]",
")",
"for",
"w",
"in",
"s1",
".",
"split",
"(",
")",
"]",
"w2",
"=",
"[",
"chr",
"(",
"word2char",
"[",
"w",
"]",
")",
"for",
"w",
"in",
"s2",
".",
"split",
"(",
")",
"]",
"return",
"Lev",
".",
"distance",
"(",
"''",
".",
"join",
"(",
"w1",
")",
",",
"''",
".",
"join",
"(",
"w2",
")",
")"
] | 35.526316 | 17.736842 |
def plot_fit(self,intervals=True,**kwargs):
""" Plots the fit of the model
Parameters
----------
intervals : Boolean
Whether to plot 95% confidence interval of states
Returns
----------
None (plots data and the fit)
"""
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
series_type = kwargs.get('series_type','Smoothed')
if self.latent_variables.estimated is False:
raise Exception("No latent variables estimated!")
else:
date_index = copy.deepcopy(self.index)
date_index = date_index[self.integ:self.data_original.shape[0]+1]
if series_type == 'Smoothed':
mu, V= self.smoothed_state(self.data,self.latent_variables.get_z_values())
elif series_type == 'Filtered':
mu, V, _, _, _ = self._model(self.data,self.latent_variables.get_z_values())
else:
mu, V = self.smoothed_state(self.data,self.latent_variables.get_z_values())
mu0 = mu[0][:-1]
mu1 = mu[1][:-1]
Vlev = V[0][0][:-1]
Vtrend = V[0][1][:-1]
plt.figure(figsize=figsize)
plt.subplot(2, 2, 1)
plt.title(self.data_name + " Raw and " + series_type)
if intervals == True:
alpha =[0.15*i/float(100) for i in range(50,12,-2)]
plt.fill_between(date_index[2:], mu0[2:] + 1.98*np.sqrt(Vlev[2:]), mu0[2:] - 1.98*np.sqrt(Vlev[2:]), alpha=0.15,label='95% C.I.')
plt.plot(date_index,self.data,label='Data')
plt.plot(date_index,mu0,label=series_type,c='black')
plt.legend(loc=2)
plt.subplot(2, 2, 2)
if intervals == True:
alpha =[0.15*i/float(100) for i in range(50,12,-2)]
plt.fill_between(date_index[2:], mu0[2:] + 1.98*np.sqrt(Vlev[2:]), mu0[2:] - 1.98*np.sqrt(Vlev[2:]), alpha=0.15,label='95% C.I.')
plt.title(self.data_name + " Local Level")
plt.plot(date_index,mu0,label='Local Level')
plt.legend(loc=2)
plt.subplot(2, 2, 3)
if intervals == True:
alpha =[0.15*i/float(100) for i in range(50,12,-2)]
plt.fill_between(date_index[2:], mu1[2:] + 1.98*np.sqrt(Vtrend[2:]), mu1[2:] - 1.98*np.sqrt(Vtrend[2:]), alpha=0.15,label='95% C.I.')
plt.title(self.data_name + " Trend")
plt.plot(date_index,mu1,label='Stochastic Trend')
plt.legend(loc=2)
plt.subplot(2, 2, 4)
plt.title("Measurement Noise")
plt.plot(date_index[1:self.data.shape[0]],self.data[1:self.data.shape[0]]-mu0[1:self.data.shape[0]],label='Irregular term')
plt.show() | [
"def",
"plot_fit",
"(",
"self",
",",
"intervals",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seaborn",
"as",
"sns",
"figsize",
"=",
"kwargs",
".",
"get",
"(",
"'figsize'",
",",
"(",
"10",
",",
"7",
")",
")",
"series_type",
"=",
"kwargs",
".",
"get",
"(",
"'series_type'",
",",
"'Smoothed'",
")",
"if",
"self",
".",
"latent_variables",
".",
"estimated",
"is",
"False",
":",
"raise",
"Exception",
"(",
"\"No latent variables estimated!\"",
")",
"else",
":",
"date_index",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"index",
")",
"date_index",
"=",
"date_index",
"[",
"self",
".",
"integ",
":",
"self",
".",
"data_original",
".",
"shape",
"[",
"0",
"]",
"+",
"1",
"]",
"if",
"series_type",
"==",
"'Smoothed'",
":",
"mu",
",",
"V",
"=",
"self",
".",
"smoothed_state",
"(",
"self",
".",
"data",
",",
"self",
".",
"latent_variables",
".",
"get_z_values",
"(",
")",
")",
"elif",
"series_type",
"==",
"'Filtered'",
":",
"mu",
",",
"V",
",",
"_",
",",
"_",
",",
"_",
"=",
"self",
".",
"_model",
"(",
"self",
".",
"data",
",",
"self",
".",
"latent_variables",
".",
"get_z_values",
"(",
")",
")",
"else",
":",
"mu",
",",
"V",
"=",
"self",
".",
"smoothed_state",
"(",
"self",
".",
"data",
",",
"self",
".",
"latent_variables",
".",
"get_z_values",
"(",
")",
")",
"mu0",
"=",
"mu",
"[",
"0",
"]",
"[",
":",
"-",
"1",
"]",
"mu1",
"=",
"mu",
"[",
"1",
"]",
"[",
":",
"-",
"1",
"]",
"Vlev",
"=",
"V",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
":",
"-",
"1",
"]",
"Vtrend",
"=",
"V",
"[",
"0",
"]",
"[",
"1",
"]",
"[",
":",
"-",
"1",
"]",
"plt",
".",
"figure",
"(",
"figsize",
"=",
"figsize",
")",
"plt",
".",
"subplot",
"(",
"2",
",",
"2",
",",
"1",
")",
"plt",
".",
"title",
"(",
"self",
".",
"data_name",
"+",
"\" Raw and \"",
"+",
"series_type",
")",
"if",
"intervals",
"==",
"True",
":",
"alpha",
"=",
"[",
"0.15",
"*",
"i",
"/",
"float",
"(",
"100",
")",
"for",
"i",
"in",
"range",
"(",
"50",
",",
"12",
",",
"-",
"2",
")",
"]",
"plt",
".",
"fill_between",
"(",
"date_index",
"[",
"2",
":",
"]",
",",
"mu0",
"[",
"2",
":",
"]",
"+",
"1.98",
"*",
"np",
".",
"sqrt",
"(",
"Vlev",
"[",
"2",
":",
"]",
")",
",",
"mu0",
"[",
"2",
":",
"]",
"-",
"1.98",
"*",
"np",
".",
"sqrt",
"(",
"Vlev",
"[",
"2",
":",
"]",
")",
",",
"alpha",
"=",
"0.15",
",",
"label",
"=",
"'95% C.I.'",
")",
"plt",
".",
"plot",
"(",
"date_index",
",",
"self",
".",
"data",
",",
"label",
"=",
"'Data'",
")",
"plt",
".",
"plot",
"(",
"date_index",
",",
"mu0",
",",
"label",
"=",
"series_type",
",",
"c",
"=",
"'black'",
")",
"plt",
".",
"legend",
"(",
"loc",
"=",
"2",
")",
"plt",
".",
"subplot",
"(",
"2",
",",
"2",
",",
"2",
")",
"if",
"intervals",
"==",
"True",
":",
"alpha",
"=",
"[",
"0.15",
"*",
"i",
"/",
"float",
"(",
"100",
")",
"for",
"i",
"in",
"range",
"(",
"50",
",",
"12",
",",
"-",
"2",
")",
"]",
"plt",
".",
"fill_between",
"(",
"date_index",
"[",
"2",
":",
"]",
",",
"mu0",
"[",
"2",
":",
"]",
"+",
"1.98",
"*",
"np",
".",
"sqrt",
"(",
"Vlev",
"[",
"2",
":",
"]",
")",
",",
"mu0",
"[",
"2",
":",
"]",
"-",
"1.98",
"*",
"np",
".",
"sqrt",
"(",
"Vlev",
"[",
"2",
":",
"]",
")",
",",
"alpha",
"=",
"0.15",
",",
"label",
"=",
"'95% C.I.'",
")",
"plt",
".",
"title",
"(",
"self",
".",
"data_name",
"+",
"\" Local Level\"",
")",
"plt",
".",
"plot",
"(",
"date_index",
",",
"mu0",
",",
"label",
"=",
"'Local Level'",
")",
"plt",
".",
"legend",
"(",
"loc",
"=",
"2",
")",
"plt",
".",
"subplot",
"(",
"2",
",",
"2",
",",
"3",
")",
"if",
"intervals",
"==",
"True",
":",
"alpha",
"=",
"[",
"0.15",
"*",
"i",
"/",
"float",
"(",
"100",
")",
"for",
"i",
"in",
"range",
"(",
"50",
",",
"12",
",",
"-",
"2",
")",
"]",
"plt",
".",
"fill_between",
"(",
"date_index",
"[",
"2",
":",
"]",
",",
"mu1",
"[",
"2",
":",
"]",
"+",
"1.98",
"*",
"np",
".",
"sqrt",
"(",
"Vtrend",
"[",
"2",
":",
"]",
")",
",",
"mu1",
"[",
"2",
":",
"]",
"-",
"1.98",
"*",
"np",
".",
"sqrt",
"(",
"Vtrend",
"[",
"2",
":",
"]",
")",
",",
"alpha",
"=",
"0.15",
",",
"label",
"=",
"'95% C.I.'",
")",
"plt",
".",
"title",
"(",
"self",
".",
"data_name",
"+",
"\" Trend\"",
")",
"plt",
".",
"plot",
"(",
"date_index",
",",
"mu1",
",",
"label",
"=",
"'Stochastic Trend'",
")",
"plt",
".",
"legend",
"(",
"loc",
"=",
"2",
")",
"plt",
".",
"subplot",
"(",
"2",
",",
"2",
",",
"4",
")",
"plt",
".",
"title",
"(",
"\"Measurement Noise\"",
")",
"plt",
".",
"plot",
"(",
"date_index",
"[",
"1",
":",
"self",
".",
"data",
".",
"shape",
"[",
"0",
"]",
"]",
",",
"self",
".",
"data",
"[",
"1",
":",
"self",
".",
"data",
".",
"shape",
"[",
"0",
"]",
"]",
"-",
"mu0",
"[",
"1",
":",
"self",
".",
"data",
".",
"shape",
"[",
"0",
"]",
"]",
",",
"label",
"=",
"'Irregular term'",
")",
"plt",
".",
"show",
"(",
")"
] | 39.178082 | 25.739726 |
def render_edge_with_node_label(self, name, edge, edge_settings):
"""
Render edge with label as separate node
"""
props_to_display = self.extract_props(edge.settings)
label = '<'
label += "|".join(self.get_label(prop, value) for prop, value in props_to_display.items())
label += '>'
edge_node_name = "{}-{}".format(name, edge.to)
self.gv_graph.node(edge_node_name, label=label, shape="record")
self.gv_graph.edge(self.get_path_from_name(name), edge_node_name, arrowhead="none", **edge_settings)
self.gv_graph.edge(edge_node_name, self.get_path_from_name(edge.to), **edge_settings) | [
"def",
"render_edge_with_node_label",
"(",
"self",
",",
"name",
",",
"edge",
",",
"edge_settings",
")",
":",
"props_to_display",
"=",
"self",
".",
"extract_props",
"(",
"edge",
".",
"settings",
")",
"label",
"=",
"'<'",
"label",
"+=",
"\"|\"",
".",
"join",
"(",
"self",
".",
"get_label",
"(",
"prop",
",",
"value",
")",
"for",
"prop",
",",
"value",
"in",
"props_to_display",
".",
"items",
"(",
")",
")",
"label",
"+=",
"'>'",
"edge_node_name",
"=",
"\"{}-{}\"",
".",
"format",
"(",
"name",
",",
"edge",
".",
"to",
")",
"self",
".",
"gv_graph",
".",
"node",
"(",
"edge_node_name",
",",
"label",
"=",
"label",
",",
"shape",
"=",
"\"record\"",
")",
"self",
".",
"gv_graph",
".",
"edge",
"(",
"self",
".",
"get_path_from_name",
"(",
"name",
")",
",",
"edge_node_name",
",",
"arrowhead",
"=",
"\"none\"",
",",
"*",
"*",
"edge_settings",
")",
"self",
".",
"gv_graph",
".",
"edge",
"(",
"edge_node_name",
",",
"self",
".",
"get_path_from_name",
"(",
"edge",
".",
"to",
")",
",",
"*",
"*",
"edge_settings",
")"
] | 41.125 | 29.875 |
def find_handfile(names=None):
"""
尝试定位 ``handfile`` 文件,明确指定或逐级搜索父路径
:param str names: 可选,待查找的文件名,主要用于调试,默认使用终端传入的配置
:return: ``handfile`` 文件所在的绝对路径,默认为 None
:rtype: str
"""
# 如果没有明确指定,则包含 env 中的值
names = names or [env.handfile]
# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾
if not names[0].endswith('.py'):
names += [names[0] + '.py']
# name 中是否包含路径元素
if os.path.dirname(names[0]):
# 若存在,则扩展 Home 路径标志,并测试是否存在
for name in names:
expanded = os.path.expanduser(name)
if os.path.exists(expanded):
if name.endswith('.py') or _is_package(expanded):
return os.path.abspath(expanded)
else:
# 否则,逐级向上搜索,直到根路径
path = '.'
# 在到系统根路径之前停止
while os.path.split(os.path.abspath(path))[1]:
for name in names:
joined = os.path.join(path, name)
if os.path.exists(joined):
if name.endswith('.py') or _is_package(joined):
return os.path.abspath(joined)
path = os.path.join('..', path)
return None | [
"def",
"find_handfile",
"(",
"names",
"=",
"None",
")",
":",
"# 如果没有明确指定,则包含 env 中的值",
"names",
"=",
"names",
"or",
"[",
"env",
".",
"handfile",
"]",
"# 若无 ``.py`` 扩展名,则作为待查询名称,追加到 names 末尾",
"if",
"not",
"names",
"[",
"0",
"]",
".",
"endswith",
"(",
"'.py'",
")",
":",
"names",
"+=",
"[",
"names",
"[",
"0",
"]",
"+",
"'.py'",
"]",
"# name 中是否包含路径元素",
"if",
"os",
".",
"path",
".",
"dirname",
"(",
"names",
"[",
"0",
"]",
")",
":",
"# 若存在,则扩展 Home 路径标志,并测试是否存在",
"for",
"name",
"in",
"names",
":",
"expanded",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"expanded",
")",
":",
"if",
"name",
".",
"endswith",
"(",
"'.py'",
")",
"or",
"_is_package",
"(",
"expanded",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"expanded",
")",
"else",
":",
"# 否则,逐级向上搜索,直到根路径",
"path",
"=",
"'.'",
"# 在到系统根路径之前停止",
"while",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
"[",
"1",
"]",
":",
"for",
"name",
"in",
"names",
":",
"joined",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"joined",
")",
":",
"if",
"name",
".",
"endswith",
"(",
"'.py'",
")",
"or",
"_is_package",
"(",
"joined",
")",
":",
"return",
"os",
".",
"path",
".",
"abspath",
"(",
"joined",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'..'",
",",
"path",
")",
"return",
"None"
] | 30 | 15.243243 |
def getTextualNode(self, textId, subreference=None, prevnext=False, metadata=False):
""" Retrieve a text node from the API
:param textId: CtsTextMetadata Identifier
:type textId: str
:param subreference: CapitainsCtsPassage CtsReference
:type subreference: str
:param prevnext: Retrieve graph representing previous and next passage
:type prevnext: boolean
:param metadata: Retrieve metadata about the passage and the text
:type metadata: boolean
:return: CapitainsCtsPassage
:rtype: CapitainsCtsPassage
"""
text, text_metadata = self.__getText__(textId)
if subreference is not None and not isinstance(subreference, CtsReference):
subreference = CtsReference(subreference)
passage = text.getTextualNode(subreference)
if metadata:
passage.set_metadata_from_collection(text_metadata)
return passage | [
"def",
"getTextualNode",
"(",
"self",
",",
"textId",
",",
"subreference",
"=",
"None",
",",
"prevnext",
"=",
"False",
",",
"metadata",
"=",
"False",
")",
":",
"text",
",",
"text_metadata",
"=",
"self",
".",
"__getText__",
"(",
"textId",
")",
"if",
"subreference",
"is",
"not",
"None",
"and",
"not",
"isinstance",
"(",
"subreference",
",",
"CtsReference",
")",
":",
"subreference",
"=",
"CtsReference",
"(",
"subreference",
")",
"passage",
"=",
"text",
".",
"getTextualNode",
"(",
"subreference",
")",
"if",
"metadata",
":",
"passage",
".",
"set_metadata_from_collection",
"(",
"text_metadata",
")",
"return",
"passage"
] | 44.571429 | 18 |
def __execute_stm(self, instr):
"""Execute STM instruction.
"""
assert instr.operands[0].size in [8, 16, 32, 64, 128, 256]
assert instr.operands[2].size == self.__mem.address_size
op0_val = self.read_operand(instr.operands[0]) # Data.
op2_val = self.read_operand(instr.operands[2]) # Memory address.
op0_size = instr.operands[0].size
self.write_memory(op2_val, op0_size // 8, op0_val)
return None | [
"def",
"__execute_stm",
"(",
"self",
",",
"instr",
")",
":",
"assert",
"instr",
".",
"operands",
"[",
"0",
"]",
".",
"size",
"in",
"[",
"8",
",",
"16",
",",
"32",
",",
"64",
",",
"128",
",",
"256",
"]",
"assert",
"instr",
".",
"operands",
"[",
"2",
"]",
".",
"size",
"==",
"self",
".",
"__mem",
".",
"address_size",
"op0_val",
"=",
"self",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"0",
"]",
")",
"# Data.",
"op2_val",
"=",
"self",
".",
"read_operand",
"(",
"instr",
".",
"operands",
"[",
"2",
"]",
")",
"# Memory address.",
"op0_size",
"=",
"instr",
".",
"operands",
"[",
"0",
"]",
".",
"size",
"self",
".",
"write_memory",
"(",
"op2_val",
",",
"op0_size",
"//",
"8",
",",
"op0_val",
")",
"return",
"None"
] | 32.928571 | 22.5 |
def autosave_all(self):
"""Autosave all opened files."""
for index in range(self.stack.get_stack_count()):
self.autosave(index) | [
"def",
"autosave_all",
"(",
"self",
")",
":",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"stack",
".",
"get_stack_count",
"(",
")",
")",
":",
"self",
".",
"autosave",
"(",
"index",
")"
] | 38 | 10.5 |
def address(self, street, city=None, state=None, zipcode=None, **kwargs):
'''Geocode an address.'''
fields = {
'street': street,
'city': city,
'state': state,
'zip': zipcode,
}
return self._fetch('address', fields, **kwargs) | [
"def",
"address",
"(",
"self",
",",
"street",
",",
"city",
"=",
"None",
",",
"state",
"=",
"None",
",",
"zipcode",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"fields",
"=",
"{",
"'street'",
":",
"street",
",",
"'city'",
":",
"city",
",",
"'state'",
":",
"state",
",",
"'zip'",
":",
"zipcode",
",",
"}",
"return",
"self",
".",
"_fetch",
"(",
"'address'",
",",
"fields",
",",
"*",
"*",
"kwargs",
")"
] | 29.6 | 20 |
def compile_dictionary(self, lang, wordlists, encoding, output):
"""Compile user dictionary."""
cmd = [
self.binary,
'--lang', lang,
'--encoding', codecs.lookup(filters.PYTHON_ENCODING_NAMES.get(encoding, encoding).lower()).name,
'create',
'master', output
]
wordlist = ''
try:
output_location = os.path.dirname(output)
if not os.path.exists(output_location):
os.makedirs(output_location)
if os.path.exists(output):
os.remove(output)
self.log("Compiling Dictionary...", 1)
# Read word lists and create a unique set of words
words = set()
for wordlist in wordlists:
with open(wordlist, 'rb') as src:
for word in src.read().split(b'\n'):
words.add(word.replace(b'\r', b''))
# Compile wordlist against language
util.call(
[
self.binary,
'--lang', lang,
'--encoding=utf-8',
'create',
'master', output
],
input_text=b'\n'.join(sorted(words)) + b'\n'
)
except Exception:
self.log(cmd, 0)
self.log("Current wordlist: '%s'" % wordlist, 0)
self.log("Problem compiling dictionary. Check the binary path and options.", 0)
raise | [
"def",
"compile_dictionary",
"(",
"self",
",",
"lang",
",",
"wordlists",
",",
"encoding",
",",
"output",
")",
":",
"cmd",
"=",
"[",
"self",
".",
"binary",
",",
"'--lang'",
",",
"lang",
",",
"'--encoding'",
",",
"codecs",
".",
"lookup",
"(",
"filters",
".",
"PYTHON_ENCODING_NAMES",
".",
"get",
"(",
"encoding",
",",
"encoding",
")",
".",
"lower",
"(",
")",
")",
".",
"name",
",",
"'create'",
",",
"'master'",
",",
"output",
"]",
"wordlist",
"=",
"''",
"try",
":",
"output_location",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"output_location",
")",
":",
"os",
".",
"makedirs",
"(",
"output_location",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"output",
")",
":",
"os",
".",
"remove",
"(",
"output",
")",
"self",
".",
"log",
"(",
"\"Compiling Dictionary...\"",
",",
"1",
")",
"# Read word lists and create a unique set of words",
"words",
"=",
"set",
"(",
")",
"for",
"wordlist",
"in",
"wordlists",
":",
"with",
"open",
"(",
"wordlist",
",",
"'rb'",
")",
"as",
"src",
":",
"for",
"word",
"in",
"src",
".",
"read",
"(",
")",
".",
"split",
"(",
"b'\\n'",
")",
":",
"words",
".",
"add",
"(",
"word",
".",
"replace",
"(",
"b'\\r'",
",",
"b''",
")",
")",
"# Compile wordlist against language",
"util",
".",
"call",
"(",
"[",
"self",
".",
"binary",
",",
"'--lang'",
",",
"lang",
",",
"'--encoding=utf-8'",
",",
"'create'",
",",
"'master'",
",",
"output",
"]",
",",
"input_text",
"=",
"b'\\n'",
".",
"join",
"(",
"sorted",
"(",
"words",
")",
")",
"+",
"b'\\n'",
")",
"except",
"Exception",
":",
"self",
".",
"log",
"(",
"cmd",
",",
"0",
")",
"self",
".",
"log",
"(",
"\"Current wordlist: '%s'\"",
"%",
"wordlist",
",",
"0",
")",
"self",
".",
"log",
"(",
"\"Problem compiling dictionary. Check the binary path and options.\"",
",",
"0",
")",
"raise"
] | 33.954545 | 19.363636 |
def log_player_plays_monopoly(self, player, resource):
"""
:param player: catan.game.Player
:param resource: catan.board.Terrain
"""
self._logln('{0} plays monopoly on {1}'.format(
player.color,
resource.value
)) | [
"def",
"log_player_plays_monopoly",
"(",
"self",
",",
"player",
",",
"resource",
")",
":",
"self",
".",
"_logln",
"(",
"'{0} plays monopoly on {1}'",
".",
"format",
"(",
"player",
".",
"color",
",",
"resource",
".",
"value",
")",
")"
] | 30.666667 | 10.222222 |
def _get_index(self,index):
"""Get the current block index, validating and checking status.
Returns None if the demo is finished"""
if index is None:
if self.finished:
print >>io.stdout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.'
return None
index = self.block_index
else:
self._validate_index(index)
return index | [
"def",
"_get_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"is",
"None",
":",
"if",
"self",
".",
"finished",
":",
"print",
">>",
"io",
".",
"stdout",
",",
"'Demo finished. Use <demo_name>.reset() if you want to rerun it.'",
"return",
"None",
"index",
"=",
"self",
".",
"block_index",
"else",
":",
"self",
".",
"_validate_index",
"(",
"index",
")",
"return",
"index"
] | 33.461538 | 18.846154 |
def perform_matched_selection(self, event):
"""
Performs matched selection.
:param event: QMouseEvent
"""
selected = TextHelper(self.editor).match_select()
if selected and event:
event.accept() | [
"def",
"perform_matched_selection",
"(",
"self",
",",
"event",
")",
":",
"selected",
"=",
"TextHelper",
"(",
"self",
".",
"editor",
")",
".",
"match_select",
"(",
")",
"if",
"selected",
"and",
"event",
":",
"event",
".",
"accept",
"(",
")"
] | 30.75 | 7 |
def hstrlen(self, name, key):
"""
Return the number of bytes stored in the value of ``key``
within hash ``name``
"""
with self.pipe as pipe:
return pipe.hstrlen(self.redis_key(name), key) | [
"def",
"hstrlen",
"(",
"self",
",",
"name",
",",
"key",
")",
":",
"with",
"self",
".",
"pipe",
"as",
"pipe",
":",
"return",
"pipe",
".",
"hstrlen",
"(",
"self",
".",
"redis_key",
"(",
"name",
")",
",",
"key",
")"
] | 33.285714 | 10.714286 |
def is_de_listed(self):
"""
判断合约是否过期
"""
instrument = Environment.get_instance().get_instrument(self._order_book_id)
current_date = Environment.get_instance().trading_dt
if instrument.de_listed_date is not None and current_date >= instrument.de_listed_date:
return True
return False | [
"def",
"is_de_listed",
"(",
"self",
")",
":",
"instrument",
"=",
"Environment",
".",
"get_instance",
"(",
")",
".",
"get_instrument",
"(",
"self",
".",
"_order_book_id",
")",
"current_date",
"=",
"Environment",
".",
"get_instance",
"(",
")",
".",
"trading_dt",
"if",
"instrument",
".",
"de_listed_date",
"is",
"not",
"None",
"and",
"current_date",
">=",
"instrument",
".",
"de_listed_date",
":",
"return",
"True",
"return",
"False"
] | 38 | 21.777778 |
def get_type_hierarchy(s):
"""Get the sequence of parents from `s` to Statement.
Parameters
----------
s : a class or instance of a child of Statement
For example the statement `Phosphorylation(MEK(), ERK())` or just the
class `Phosphorylation`.
Returns
-------
parent_list : list[types]
A list of the types leading up to Statement.
Examples
--------
>> s = Phosphorylation(MAPK1(), Elk1())
>> get_type_hierarchy(s)
[Phosphorylation, AddModification, Modification, Statement]
>> get_type_hierarchy(AddModification)
[AddModification, Modification, Statement]
"""
tp = type(s) if not isinstance(s, type) else s
p_list = [tp]
for p in tp.__bases__:
if p is not Statement:
p_list.extend(get_type_hierarchy(p))
else:
p_list.append(p)
return p_list | [
"def",
"get_type_hierarchy",
"(",
"s",
")",
":",
"tp",
"=",
"type",
"(",
"s",
")",
"if",
"not",
"isinstance",
"(",
"s",
",",
"type",
")",
"else",
"s",
"p_list",
"=",
"[",
"tp",
"]",
"for",
"p",
"in",
"tp",
".",
"__bases__",
":",
"if",
"p",
"is",
"not",
"Statement",
":",
"p_list",
".",
"extend",
"(",
"get_type_hierarchy",
"(",
"p",
")",
")",
"else",
":",
"p_list",
".",
"append",
"(",
"p",
")",
"return",
"p_list"
] | 29.2 | 18.8 |
def DeregisterHelper(cls, helper_class):
"""Deregisters a helper class.
The helper classes are identified based on their lower case name.
Args:
helper_class (type): class object of the argument helper.
Raises:
KeyError: if helper class is not set for the corresponding name.
"""
helper_name = helper_class.NAME.lower()
if helper_name not in cls._helper_classes:
raise KeyError('Helper class not set for name: {0:s}.'.format(
helper_class.NAME))
del cls._helper_classes[helper_name] | [
"def",
"DeregisterHelper",
"(",
"cls",
",",
"helper_class",
")",
":",
"helper_name",
"=",
"helper_class",
".",
"NAME",
".",
"lower",
"(",
")",
"if",
"helper_name",
"not",
"in",
"cls",
".",
"_helper_classes",
":",
"raise",
"KeyError",
"(",
"'Helper class not set for name: {0:s}.'",
".",
"format",
"(",
"helper_class",
".",
"NAME",
")",
")",
"del",
"cls",
".",
"_helper_classes",
"[",
"helper_name",
"]"
] | 31.117647 | 20.588235 |
def wait_for_subworkflows(self, workflow_results):
'''Wait for results from subworkflows'''
wf_ids = sum([x['pending_workflows'] for x in workflow_results], [])
for wf_id in wf_ids:
# here we did not check if workflow ids match
yield self.socket
res = self.socket.recv_pyobj()
if res is None:
sys.exit(0)
elif isinstance(res, Exception):
raise res | [
"def",
"wait_for_subworkflows",
"(",
"self",
",",
"workflow_results",
")",
":",
"wf_ids",
"=",
"sum",
"(",
"[",
"x",
"[",
"'pending_workflows'",
"]",
"for",
"x",
"in",
"workflow_results",
"]",
",",
"[",
"]",
")",
"for",
"wf_id",
"in",
"wf_ids",
":",
"# here we did not check if workflow ids match",
"yield",
"self",
".",
"socket",
"res",
"=",
"self",
".",
"socket",
".",
"recv_pyobj",
"(",
")",
"if",
"res",
"is",
"None",
":",
"sys",
".",
"exit",
"(",
"0",
")",
"elif",
"isinstance",
"(",
"res",
",",
"Exception",
")",
":",
"raise",
"res"
] | 41.181818 | 12.818182 |
def spectrogram(t_signal, frame_width=FRAME_WIDTH, overlap=FRAME_STRIDE):
"""
Calculate the magnitude spectrogram of a single-channel time-domain signal
from the real frequency components of the STFT with a hanning window
applied to each frame. The frame size and overlap between frames should
be specified in number of samples.
"""
frame_width = min(t_signal.shape[0], frame_width)
w = np.hanning(frame_width)
num_components = frame_width // 2 + 1
num_frames = 1 + (len(t_signal) - frame_width) // overlap
f_signal = np.empty([num_frames, num_components], dtype=np.complex_)
for i, t in enumerate(range(0, len(t_signal) - frame_width, overlap)):
# using rfft avoids computing negative frequency components
f_signal[i] = rfft(w * t_signal[t:t + frame_width])
# amplitude in decibels
return 20 * np.log10(1 + np.absolute(f_signal)) | [
"def",
"spectrogram",
"(",
"t_signal",
",",
"frame_width",
"=",
"FRAME_WIDTH",
",",
"overlap",
"=",
"FRAME_STRIDE",
")",
":",
"frame_width",
"=",
"min",
"(",
"t_signal",
".",
"shape",
"[",
"0",
"]",
",",
"frame_width",
")",
"w",
"=",
"np",
".",
"hanning",
"(",
"frame_width",
")",
"num_components",
"=",
"frame_width",
"//",
"2",
"+",
"1",
"num_frames",
"=",
"1",
"+",
"(",
"len",
"(",
"t_signal",
")",
"-",
"frame_width",
")",
"//",
"overlap",
"f_signal",
"=",
"np",
".",
"empty",
"(",
"[",
"num_frames",
",",
"num_components",
"]",
",",
"dtype",
"=",
"np",
".",
"complex_",
")",
"for",
"i",
",",
"t",
"in",
"enumerate",
"(",
"range",
"(",
"0",
",",
"len",
"(",
"t_signal",
")",
"-",
"frame_width",
",",
"overlap",
")",
")",
":",
"# using rfft avoids computing negative frequency components",
"f_signal",
"[",
"i",
"]",
"=",
"rfft",
"(",
"w",
"*",
"t_signal",
"[",
"t",
":",
"t",
"+",
"frame_width",
"]",
")",
"# amplitude in decibels",
"return",
"20",
"*",
"np",
".",
"log10",
"(",
"1",
"+",
"np",
".",
"absolute",
"(",
"f_signal",
")",
")"
] | 46.631579 | 21.052632 |
def switch_toggle(self, device):
"""Toggles the current state of the given device"""
state = self.get_state(device)
if(state == '1'):
return self.switch_off(device)
elif(state == '0'):
return self.switch_on(device)
else:
return state | [
"def",
"switch_toggle",
"(",
"self",
",",
"device",
")",
":",
"state",
"=",
"self",
".",
"get_state",
"(",
"device",
")",
"if",
"(",
"state",
"==",
"'1'",
")",
":",
"return",
"self",
".",
"switch_off",
"(",
"device",
")",
"elif",
"(",
"state",
"==",
"'0'",
")",
":",
"return",
"self",
".",
"switch_on",
"(",
"device",
")",
"else",
":",
"return",
"state"
] | 30.1 | 12.4 |
def parse_multiple_json(json_file, offset=None):
"""Parse multiple json records from the given file.
Seek to the offset as the start point before parsing
if offset set. return empty list if the json file does
not exists or exception occurs.
Args:
json_file (str): File path to be parsed.
offset (int): Initial seek position of the file.
Returns:
A dict of json info.
New offset after parsing.
"""
json_info_list = []
if not os.path.exists(json_file):
return json_info_list
try:
with open(json_file, "r") as f:
if offset:
f.seek(offset)
for line in f:
if line[-1] != "\n":
# Incomplete line
break
json_info = json.loads(line)
json_info_list.append(json_info)
offset += len(line)
except BaseException as e:
logging.error(e.message)
return json_info_list, offset | [
"def",
"parse_multiple_json",
"(",
"json_file",
",",
"offset",
"=",
"None",
")",
":",
"json_info_list",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"json_file",
")",
":",
"return",
"json_info_list",
"try",
":",
"with",
"open",
"(",
"json_file",
",",
"\"r\"",
")",
"as",
"f",
":",
"if",
"offset",
":",
"f",
".",
"seek",
"(",
"offset",
")",
"for",
"line",
"in",
"f",
":",
"if",
"line",
"[",
"-",
"1",
"]",
"!=",
"\"\\n\"",
":",
"# Incomplete line",
"break",
"json_info",
"=",
"json",
".",
"loads",
"(",
"line",
")",
"json_info_list",
".",
"append",
"(",
"json_info",
")",
"offset",
"+=",
"len",
"(",
"line",
")",
"except",
"BaseException",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"e",
".",
"message",
")",
"return",
"json_info_list",
",",
"offset"
] | 27.971429 | 15.971429 |
def create_cinder_volume(self, cinder, vol_name="demo-vol", vol_size=1,
img_id=None, src_vol_id=None, snap_id=None):
"""Create cinder volume, optionally from a glance image, OR
optionally as a clone of an existing volume, OR optionally
from a snapshot. Wait for the new volume status to reach
the expected status, validate and return a resource pointer.
:param vol_name: cinder volume display name
:param vol_size: size in gigabytes
:param img_id: optional glance image id
:param src_vol_id: optional source volume id to clone
:param snap_id: optional snapshot id to use
:returns: cinder volume pointer
"""
# Handle parameter input and avoid impossible combinations
if img_id and not src_vol_id and not snap_id:
# Create volume from image
self.log.debug('Creating cinder volume from glance image...')
bootable = 'true'
elif src_vol_id and not img_id and not snap_id:
# Clone an existing volume
self.log.debug('Cloning cinder volume...')
bootable = cinder.volumes.get(src_vol_id).bootable
elif snap_id and not src_vol_id and not img_id:
# Create volume from snapshot
self.log.debug('Creating cinder volume from snapshot...')
snap = cinder.volume_snapshots.find(id=snap_id)
vol_size = snap.size
snap_vol_id = cinder.volume_snapshots.get(snap_id).volume_id
bootable = cinder.volumes.get(snap_vol_id).bootable
elif not img_id and not src_vol_id and not snap_id:
# Create volume
self.log.debug('Creating cinder volume...')
bootable = 'false'
else:
# Impossible combination of parameters
msg = ('Invalid method use - name:{} size:{} img_id:{} '
'src_vol_id:{} snap_id:{}'.format(vol_name, vol_size,
img_id, src_vol_id,
snap_id))
amulet.raise_status(amulet.FAIL, msg=msg)
# Create new volume
try:
vol_new = cinder.volumes.create(display_name=vol_name,
imageRef=img_id,
size=vol_size,
source_volid=src_vol_id,
snapshot_id=snap_id)
vol_id = vol_new.id
except TypeError:
vol_new = cinder.volumes.create(name=vol_name,
imageRef=img_id,
size=vol_size,
source_volid=src_vol_id,
snapshot_id=snap_id)
vol_id = vol_new.id
except Exception as e:
msg = 'Failed to create volume: {}'.format(e)
amulet.raise_status(amulet.FAIL, msg=msg)
# Wait for volume to reach available status
ret = self.resource_reaches_status(cinder.volumes, vol_id,
expected_stat="available",
msg="Volume status wait")
if not ret:
msg = 'Cinder volume failed to reach expected state.'
amulet.raise_status(amulet.FAIL, msg=msg)
# Re-validate new volume
self.log.debug('Validating volume attributes...')
val_vol_name = self._get_cinder_obj_name(cinder.volumes.get(vol_id))
val_vol_boot = cinder.volumes.get(vol_id).bootable
val_vol_stat = cinder.volumes.get(vol_id).status
val_vol_size = cinder.volumes.get(vol_id).size
msg_attr = ('Volume attributes - name:{} id:{} stat:{} boot:'
'{} size:{}'.format(val_vol_name, vol_id,
val_vol_stat, val_vol_boot,
val_vol_size))
if val_vol_boot == bootable and val_vol_stat == 'available' \
and val_vol_name == vol_name and val_vol_size == vol_size:
self.log.debug(msg_attr)
else:
msg = ('Volume validation failed, {}'.format(msg_attr))
amulet.raise_status(amulet.FAIL, msg=msg)
return vol_new | [
"def",
"create_cinder_volume",
"(",
"self",
",",
"cinder",
",",
"vol_name",
"=",
"\"demo-vol\"",
",",
"vol_size",
"=",
"1",
",",
"img_id",
"=",
"None",
",",
"src_vol_id",
"=",
"None",
",",
"snap_id",
"=",
"None",
")",
":",
"# Handle parameter input and avoid impossible combinations",
"if",
"img_id",
"and",
"not",
"src_vol_id",
"and",
"not",
"snap_id",
":",
"# Create volume from image",
"self",
".",
"log",
".",
"debug",
"(",
"'Creating cinder volume from glance image...'",
")",
"bootable",
"=",
"'true'",
"elif",
"src_vol_id",
"and",
"not",
"img_id",
"and",
"not",
"snap_id",
":",
"# Clone an existing volume",
"self",
".",
"log",
".",
"debug",
"(",
"'Cloning cinder volume...'",
")",
"bootable",
"=",
"cinder",
".",
"volumes",
".",
"get",
"(",
"src_vol_id",
")",
".",
"bootable",
"elif",
"snap_id",
"and",
"not",
"src_vol_id",
"and",
"not",
"img_id",
":",
"# Create volume from snapshot",
"self",
".",
"log",
".",
"debug",
"(",
"'Creating cinder volume from snapshot...'",
")",
"snap",
"=",
"cinder",
".",
"volume_snapshots",
".",
"find",
"(",
"id",
"=",
"snap_id",
")",
"vol_size",
"=",
"snap",
".",
"size",
"snap_vol_id",
"=",
"cinder",
".",
"volume_snapshots",
".",
"get",
"(",
"snap_id",
")",
".",
"volume_id",
"bootable",
"=",
"cinder",
".",
"volumes",
".",
"get",
"(",
"snap_vol_id",
")",
".",
"bootable",
"elif",
"not",
"img_id",
"and",
"not",
"src_vol_id",
"and",
"not",
"snap_id",
":",
"# Create volume",
"self",
".",
"log",
".",
"debug",
"(",
"'Creating cinder volume...'",
")",
"bootable",
"=",
"'false'",
"else",
":",
"# Impossible combination of parameters",
"msg",
"=",
"(",
"'Invalid method use - name:{} size:{} img_id:{} '",
"'src_vol_id:{} snap_id:{}'",
".",
"format",
"(",
"vol_name",
",",
"vol_size",
",",
"img_id",
",",
"src_vol_id",
",",
"snap_id",
")",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"# Create new volume",
"try",
":",
"vol_new",
"=",
"cinder",
".",
"volumes",
".",
"create",
"(",
"display_name",
"=",
"vol_name",
",",
"imageRef",
"=",
"img_id",
",",
"size",
"=",
"vol_size",
",",
"source_volid",
"=",
"src_vol_id",
",",
"snapshot_id",
"=",
"snap_id",
")",
"vol_id",
"=",
"vol_new",
".",
"id",
"except",
"TypeError",
":",
"vol_new",
"=",
"cinder",
".",
"volumes",
".",
"create",
"(",
"name",
"=",
"vol_name",
",",
"imageRef",
"=",
"img_id",
",",
"size",
"=",
"vol_size",
",",
"source_volid",
"=",
"src_vol_id",
",",
"snapshot_id",
"=",
"snap_id",
")",
"vol_id",
"=",
"vol_new",
".",
"id",
"except",
"Exception",
"as",
"e",
":",
"msg",
"=",
"'Failed to create volume: {}'",
".",
"format",
"(",
"e",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"# Wait for volume to reach available status",
"ret",
"=",
"self",
".",
"resource_reaches_status",
"(",
"cinder",
".",
"volumes",
",",
"vol_id",
",",
"expected_stat",
"=",
"\"available\"",
",",
"msg",
"=",
"\"Volume status wait\"",
")",
"if",
"not",
"ret",
":",
"msg",
"=",
"'Cinder volume failed to reach expected state.'",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"# Re-validate new volume",
"self",
".",
"log",
".",
"debug",
"(",
"'Validating volume attributes...'",
")",
"val_vol_name",
"=",
"self",
".",
"_get_cinder_obj_name",
"(",
"cinder",
".",
"volumes",
".",
"get",
"(",
"vol_id",
")",
")",
"val_vol_boot",
"=",
"cinder",
".",
"volumes",
".",
"get",
"(",
"vol_id",
")",
".",
"bootable",
"val_vol_stat",
"=",
"cinder",
".",
"volumes",
".",
"get",
"(",
"vol_id",
")",
".",
"status",
"val_vol_size",
"=",
"cinder",
".",
"volumes",
".",
"get",
"(",
"vol_id",
")",
".",
"size",
"msg_attr",
"=",
"(",
"'Volume attributes - name:{} id:{} stat:{} boot:'",
"'{} size:{}'",
".",
"format",
"(",
"val_vol_name",
",",
"vol_id",
",",
"val_vol_stat",
",",
"val_vol_boot",
",",
"val_vol_size",
")",
")",
"if",
"val_vol_boot",
"==",
"bootable",
"and",
"val_vol_stat",
"==",
"'available'",
"and",
"val_vol_name",
"==",
"vol_name",
"and",
"val_vol_size",
"==",
"vol_size",
":",
"self",
".",
"log",
".",
"debug",
"(",
"msg_attr",
")",
"else",
":",
"msg",
"=",
"(",
"'Volume validation failed, {}'",
".",
"format",
"(",
"msg_attr",
")",
")",
"amulet",
".",
"raise_status",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"return",
"vol_new"
] | 49.215909 | 20.056818 |
def is_fringe(self, connections=None):
"""true if this edge has no incoming or no outgoing connections (except turnarounds)
If connections is given, only those connections are considered"""
if connections is None:
return self.is_fringe(self._incoming) or self.is_fringe(self._outgoing)
else:
cons = sum([c for c in connections.values()], [])
return len([c for c in cons if c._direction != Connection.LINKDIR_TURN]) == 0 | [
"def",
"is_fringe",
"(",
"self",
",",
"connections",
"=",
"None",
")",
":",
"if",
"connections",
"is",
"None",
":",
"return",
"self",
".",
"is_fringe",
"(",
"self",
".",
"_incoming",
")",
"or",
"self",
".",
"is_fringe",
"(",
"self",
".",
"_outgoing",
")",
"else",
":",
"cons",
"=",
"sum",
"(",
"[",
"c",
"for",
"c",
"in",
"connections",
".",
"values",
"(",
")",
"]",
",",
"[",
"]",
")",
"return",
"len",
"(",
"[",
"c",
"for",
"c",
"in",
"cons",
"if",
"c",
".",
"_direction",
"!=",
"Connection",
".",
"LINKDIR_TURN",
"]",
")",
"==",
"0"
] | 60.375 | 18.875 |
def make_send_to_address_tx(recipient_address, amount, private_key,
blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
change_address=None):
""" Builds and signs a "send to address" transaction.
"""
# get out the private key object, sending address, and inputs
private_key_obj, from_address, inputs = analyze_private_key(private_key,
blockchain_client)
# get the change address
if not change_address:
change_address = from_address
# create the outputs
outputs = make_pay_to_address_outputs(recipient_address, amount, inputs,
change_address, fee=fee)
# serialize the transaction
unsigned_tx = serialize_transaction(inputs, outputs)
# generate a scriptSig for each input
for i in xrange(0, len(inputs)):
signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex())
unsigned_tx = signed_tx
# return the signed tx
return signed_tx | [
"def",
"make_send_to_address_tx",
"(",
"recipient_address",
",",
"amount",
",",
"private_key",
",",
"blockchain_client",
"=",
"BlockchainInfoClient",
"(",
")",
",",
"fee",
"=",
"STANDARD_FEE",
",",
"change_address",
"=",
"None",
")",
":",
"# get out the private key object, sending address, and inputs",
"private_key_obj",
",",
"from_address",
",",
"inputs",
"=",
"analyze_private_key",
"(",
"private_key",
",",
"blockchain_client",
")",
"# get the change address",
"if",
"not",
"change_address",
":",
"change_address",
"=",
"from_address",
"# create the outputs",
"outputs",
"=",
"make_pay_to_address_outputs",
"(",
"recipient_address",
",",
"amount",
",",
"inputs",
",",
"change_address",
",",
"fee",
"=",
"fee",
")",
"# serialize the transaction",
"unsigned_tx",
"=",
"serialize_transaction",
"(",
"inputs",
",",
"outputs",
")",
"# generate a scriptSig for each input",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"inputs",
")",
")",
":",
"signed_tx",
"=",
"sign_transaction",
"(",
"unsigned_tx",
",",
"i",
",",
"private_key_obj",
".",
"to_hex",
"(",
")",
")",
"unsigned_tx",
"=",
"signed_tx",
"# return the signed tx",
"return",
"signed_tx"
] | 40.416667 | 18.25 |
def has_path(self, path, method=None):
"""
Returns True if this Swagger has the given path and optional method
:param string path: Path name
:param string method: HTTP method
:return: True, if this path/method is present in the document
"""
method = self._normalize_method_name(method)
path_dict = self.get_path(path)
path_dict_exists = path_dict is not None
if method:
return path_dict_exists and method in path_dict
return path_dict_exists | [
"def",
"has_path",
"(",
"self",
",",
"path",
",",
"method",
"=",
"None",
")",
":",
"method",
"=",
"self",
".",
"_normalize_method_name",
"(",
"method",
")",
"path_dict",
"=",
"self",
".",
"get_path",
"(",
"path",
")",
"path_dict_exists",
"=",
"path_dict",
"is",
"not",
"None",
"if",
"method",
":",
"return",
"path_dict_exists",
"and",
"method",
"in",
"path_dict",
"return",
"path_dict_exists"
] | 35.266667 | 14.733333 |
def version():
"""Wrapper for opj_version library routine."""
OPENJPEG.opj_version.restype = ctypes.c_char_p
library_version = OPENJPEG.opj_version()
if sys.hexversion >= 0x03000000:
return library_version.decode('utf-8')
else:
return library_version | [
"def",
"version",
"(",
")",
":",
"OPENJPEG",
".",
"opj_version",
".",
"restype",
"=",
"ctypes",
".",
"c_char_p",
"library_version",
"=",
"OPENJPEG",
".",
"opj_version",
"(",
")",
"if",
"sys",
".",
"hexversion",
">=",
"0x03000000",
":",
"return",
"library_version",
".",
"decode",
"(",
"'utf-8'",
")",
"else",
":",
"return",
"library_version"
] | 34.875 | 11.375 |
def changeKeybind(self,kbname,combo):
"""
Changes a keybind of a specific keybindname.
:param str kbname: Same as kbname of :py:meth:`add()`
:param str combo: New key combination
"""
for key,value in self.keybinds.items():
if kbname in value:
del value[value.index(kbname)]
break
if combo not in self.keybinds:
self.keybinds[combo]=[]
self.keybinds[combo].append(kbname)
self.peng.sendEvent("peng3d.keybind.change",{"peng":self.peng,"kbname":kbname,"combo":combo}) | [
"def",
"changeKeybind",
"(",
"self",
",",
"kbname",
",",
"combo",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"keybinds",
".",
"items",
"(",
")",
":",
"if",
"kbname",
"in",
"value",
":",
"del",
"value",
"[",
"value",
".",
"index",
"(",
"kbname",
")",
"]",
"break",
"if",
"combo",
"not",
"in",
"self",
".",
"keybinds",
":",
"self",
".",
"keybinds",
"[",
"combo",
"]",
"=",
"[",
"]",
"self",
".",
"keybinds",
"[",
"combo",
"]",
".",
"append",
"(",
"kbname",
")",
"self",
".",
"peng",
".",
"sendEvent",
"(",
"\"peng3d.keybind.change\"",
",",
"{",
"\"peng\"",
":",
"self",
".",
"peng",
",",
"\"kbname\"",
":",
"kbname",
",",
"\"combo\"",
":",
"combo",
"}",
")"
] | 39.133333 | 12.333333 |
def is_zero(pauli_object):
"""
Tests to see if a PauliTerm or PauliSum is zero.
:param pauli_object: Either a PauliTerm or PauliSum
:returns: True if PauliTerm is zero, False otherwise
:rtype: bool
"""
if isinstance(pauli_object, PauliTerm):
return np.isclose(pauli_object.coefficient, 0)
elif isinstance(pauli_object, PauliSum):
return len(pauli_object.terms) == 1 and np.isclose(pauli_object.terms[0].coefficient, 0)
else:
raise TypeError("is_zero only checks PauliTerms and PauliSum objects!") | [
"def",
"is_zero",
"(",
"pauli_object",
")",
":",
"if",
"isinstance",
"(",
"pauli_object",
",",
"PauliTerm",
")",
":",
"return",
"np",
".",
"isclose",
"(",
"pauli_object",
".",
"coefficient",
",",
"0",
")",
"elif",
"isinstance",
"(",
"pauli_object",
",",
"PauliSum",
")",
":",
"return",
"len",
"(",
"pauli_object",
".",
"terms",
")",
"==",
"1",
"and",
"np",
".",
"isclose",
"(",
"pauli_object",
".",
"terms",
"[",
"0",
"]",
".",
"coefficient",
",",
"0",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"is_zero only checks PauliTerms and PauliSum objects!\"",
")"
] | 38.857143 | 19.142857 |
def idle_task(self):
'''called on idle'''
if self.module('console') is not None and not self.menu_added_console:
self.menu_added_console = True
self.module('console').add_menu(self.menu)
if self.module('map') is not None and not self.menu_added_map:
self.menu_added_map = True
self.module('map').add_menu(self.menu) | [
"def",
"idle_task",
"(",
"self",
")",
":",
"if",
"self",
".",
"module",
"(",
"'console'",
")",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"menu_added_console",
":",
"self",
".",
"menu_added_console",
"=",
"True",
"self",
".",
"module",
"(",
"'console'",
")",
".",
"add_menu",
"(",
"self",
".",
"menu",
")",
"if",
"self",
".",
"module",
"(",
"'map'",
")",
"is",
"not",
"None",
"and",
"not",
"self",
".",
"menu_added_map",
":",
"self",
".",
"menu_added_map",
"=",
"True",
"self",
".",
"module",
"(",
"'map'",
")",
".",
"add_menu",
"(",
"self",
".",
"menu",
")"
] | 47.5 | 16 |
def save(self, filename, binary=True):
"""
Writes a structured grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vts" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# Use legacy writer if vtk is in filename
if '.vtk' in filename:
writer = vtk.vtkStructuredGridWriter()
if binary:
writer.SetFileTypeToBinary()
else:
writer.SetFileTypeToASCII()
elif '.vts' in filename:
writer = vtk.vtkXMLStructuredGridWriter()
if binary:
writer.SetDataModeToBinary()
else:
writer.SetDataModeToAscii()
else:
raise Exception('Extension should be either ".vts" (xml) or' +
'".vtk" (legacy)')
# Write
writer.SetFileName(filename)
writer.SetInputData(self)
writer.Write() | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"binary",
"=",
"True",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# Use legacy writer if vtk is in filename",
"if",
"'.vtk'",
"in",
"filename",
":",
"writer",
"=",
"vtk",
".",
"vtkStructuredGridWriter",
"(",
")",
"if",
"binary",
":",
"writer",
".",
"SetFileTypeToBinary",
"(",
")",
"else",
":",
"writer",
".",
"SetFileTypeToASCII",
"(",
")",
"elif",
"'.vts'",
"in",
"filename",
":",
"writer",
"=",
"vtk",
".",
"vtkXMLStructuredGridWriter",
"(",
")",
"if",
"binary",
":",
"writer",
".",
"SetDataModeToBinary",
"(",
")",
"else",
":",
"writer",
".",
"SetDataModeToAscii",
"(",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Extension should be either \".vts\" (xml) or'",
"+",
"'\".vtk\" (legacy)'",
")",
"# Write",
"writer",
".",
"SetFileName",
"(",
"filename",
")",
"writer",
".",
"SetInputData",
"(",
"self",
")",
"writer",
".",
"Write",
"(",
")"
] | 33.883721 | 19.046512 |
def get(self, item, cache=None):
"""Lookup a torrent info property.
If cache is True, check the cache first. If the cache is empty, then
fetch torrent info before returning it.
"""
if item not in self._keys:
raise KeyError(item)
if self._use_cache(cache) and (self._fetched or
item in self._attrs):
return self._attrs[item]
info = self.fetch(cache=cache)
return info[item] | [
"def",
"get",
"(",
"self",
",",
"item",
",",
"cache",
"=",
"None",
")",
":",
"if",
"item",
"not",
"in",
"self",
".",
"_keys",
":",
"raise",
"KeyError",
"(",
"item",
")",
"if",
"self",
".",
"_use_cache",
"(",
"cache",
")",
"and",
"(",
"self",
".",
"_fetched",
"or",
"item",
"in",
"self",
".",
"_attrs",
")",
":",
"return",
"self",
".",
"_attrs",
"[",
"item",
"]",
"info",
"=",
"self",
".",
"fetch",
"(",
"cache",
"=",
"cache",
")",
"return",
"info",
"[",
"item",
"]"
] | 33.214286 | 13.142857 |
def add_item(self, item_url, item_metadata):
""" Add the given item to the cache database, updating
the existing metadata if the item is already present
:type item_url: String or Item
:param item_url: the URL of the item, or an Item object
:type item_metadata: String
:param item_metadata: the item's metadata, as a JSON string
"""
c = self.conn.cursor()
c.execute("DELETE FROM items WHERE url=?", (str(item_url),))
self.conn.commit()
c.execute("INSERT INTO items VALUES (?, ?, ?)",
(str(item_url), item_metadata, self.__now_iso_8601()))
self.conn.commit()
c.close() | [
"def",
"add_item",
"(",
"self",
",",
"item_url",
",",
"item_metadata",
")",
":",
"c",
"=",
"self",
".",
"conn",
".",
"cursor",
"(",
")",
"c",
".",
"execute",
"(",
"\"DELETE FROM items WHERE url=?\"",
",",
"(",
"str",
"(",
"item_url",
")",
",",
")",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"c",
".",
"execute",
"(",
"\"INSERT INTO items VALUES (?, ?, ?)\"",
",",
"(",
"str",
"(",
"item_url",
")",
",",
"item_metadata",
",",
"self",
".",
"__now_iso_8601",
"(",
")",
")",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")",
"c",
".",
"close",
"(",
")"
] | 37.444444 | 18.722222 |
def sfs_scaled(dac, n=None):
"""Compute the site frequency spectrum scaled such that a constant value is
expected across the spectrum for neutral variation and constant
population size.
Parameters
----------
dac : array_like, int, shape (n_variants,)
Array of derived allele counts.
n : int, optional
The total number of chromosomes called.
Returns
-------
sfs_scaled : ndarray, int, shape (n_chromosomes,)
An array where the value of the kth element is the number of variants
with k derived alleles, multiplied by k.
"""
# compute site frequency spectrum
s = sfs(dac, n=n)
# apply scaling
s = scale_sfs(s)
return s | [
"def",
"sfs_scaled",
"(",
"dac",
",",
"n",
"=",
"None",
")",
":",
"# compute site frequency spectrum",
"s",
"=",
"sfs",
"(",
"dac",
",",
"n",
"=",
"n",
")",
"# apply scaling",
"s",
"=",
"scale_sfs",
"(",
"s",
")",
"return",
"s"
] | 25.592593 | 21.888889 |
def simple_interaction_kronecker(snps,phenos,covs=None,Acovs=None,Asnps1=None,Asnps0=None,K1r=None,K1c=None,K2r=None,K2c=None,covar_type='lowrank_diag',rank=1,NumIntervalsDelta0=100,NumIntervalsDeltaAlt=0,searchDelta=False):
"""
I-variate fixed effects interaction test for phenotype specific SNP effects
Args:
snps: [N x S] SP.array of S SNPs for N individuals (test SNPs)
phenos: [N x P] SP.array of P phenotypes for N individuals
covs: list of SP.arrays holding covariates. Each covs[i] has one corresponding Acovs[i]
Acovs: list of SP.arrays holding the phenotype design matrices for covariates.
Each covs[i] has one corresponding Acovs[i].
Asnps1: list of SP.arrays of I interaction variables to be tested for N
individuals. Note that it is assumed that Asnps0 is already included.
If not provided, the alternative model will be the independent model
Asnps0: single SP.array of I0 interaction variables to be included in the
background model when testing for interaction with Inters
K1r: [N x N] SP.array of LMM-covariance/kinship koefficients (optional)
If not provided, then linear regression analysis is performed
K1c: [P x P] SP.array of LMM-covariance/kinship koefficients (optional)
If not provided, then linear regression analysis is performed
K2r: [N x N] SP.array of LMM-covariance/kinship koefficients (optional)
If not provided, then linear regression analysis is performed
K2c: [P x P] SP.array of LMM-covariance/kinship koefficients (optional)
If not provided, then linear regression analysis is performed
covar_type: type of covaraince to use. Default 'freeform'. possible values are
'freeform': free form optimization,
'fixed': use a fixed matrix specified in covar_K0,
'diag': optimize a diagonal matrix,
'lowrank': optimize a low rank matrix. The rank of the lowrank part is specified in the variable rank,
'lowrank_id': optimize a low rank matrix plus the weight of a constant diagonal matrix. The rank of the lowrank part is specified in the variable rank,
'lowrank_diag': optimize a low rank matrix plus a free diagonal matrix. The rank of the lowrank part is specified in the variable rank,
'block': optimize the weight of a constant P x P block matrix of ones,
'block_id': optimize the weight of a constant P x P block matrix of ones plus the weight of a constant diagonal matrix,
'block_diag': optimize the weight of a constant P x P block matrix of ones plus a free diagonal matrix,
rank: rank of a possible lowrank component (default 1)
NumIntervalsDelta0: number of steps for delta optimization on the null model (100)
NumIntervalsDeltaAlt:number of steps for delta optimization on the alt. model (0 - no optimization)
searchDelta: Carry out delta optimization on the alternative model? if yes We use NumIntervalsDeltaAlt steps
Returns:
pv: P-values of the interaction test
pv0: P-values of the null model
pvAlt: P-values of the alternative model
"""
S=snps.shape[1]
#0. checks
N = phenos.shape[0]
P = phenos.shape[1]
if K1r==None:
K1r = SP.dot(snps,snps.T)
else:
assert K1r.shape[0]==N, 'K1r: dimensions dismatch'
assert K1r.shape[1]==N, 'K1r: dimensions dismatch'
if K2r==None:
K2r = SP.eye(N)
else:
assert K2r.shape[0]==N, 'K2r: dimensions dismatch'
assert K2r.shape[1]==N, 'K2r: dimensions dismatch'
covs,Acovs = updateKronCovs(covs,Acovs,N,P)
#Asnps can be several designs
if (Asnps0 is None):
Asnps0 = [SP.ones([1,P])]
if Asnps1 is None:
Asnps1 = [SP.eye([P])]
if (type(Asnps0)!=list):
Asnps0 = [Asnps0]
if (type(Asnps1)!=list):
Asnps1 = [Asnps1]
assert (len(Asnps0)==1) and (len(Asnps1)>0), "need at least one Snp design matrix for null and alt model"
#one row per column design matrix
pv = SP.zeros((len(Asnps1),snps.shape[1]))
lrt = SP.zeros((len(Asnps1),snps.shape[1]))
pvAlt = SP.zeros((len(Asnps1),snps.shape[1]))
lrtAlt = SP.zeros((len(Asnps1),snps.shape[1]))
#1. run GP model to infer suitable covariance structure
if K1c==None or K2c==None:
vc = estimateKronCovariances(phenos=phenos, K1r=K1r, K2r=K2r, K1c=K1c, K2c=K2c, covs=covs, Acovs=Acovs, covar_type=covar_type, rank=rank)
K1c = vc.getEstTraitCovar(0)
K2c = vc.getEstTraitCovar(1)
else:
assert K1c.shape[0]==P, 'K1c: dimensions dismatch'
assert K1c.shape[1]==P, 'K1c: dimensions dismatch'
assert K2c.shape[0]==P, 'K2c: dimensions dismatch'
assert K2c.shape[1]==P, 'K2c: dimensions dismatch'
#2. run kroneckerLMM for null model
lmm = limix.CKroneckerLMM()
lmm.setK1r(K1r)
lmm.setK1c(K1c)
lmm.setK2r(K2r)
lmm.setK2c(K2c)
lmm.setSNPs(snps)
#add covariates
for ic in range(len(Acovs)):
lmm.addCovariates(covs[ic],Acovs[ic])
lmm.setPheno(phenos)
#delta serch on alt. model?
if searchDelta:
lmm.setNumIntervalsAlt(NumIntervalsDeltaAlt)
lmm.setNumIntervals0_inter(NumIntervalsDeltaAlt)
else:
lmm.setNumIntervalsAlt(0)
lmm.setNumIntervals0_inter(0)
lmm.setNumIntervals0(NumIntervalsDelta0)
#add SNP design
lmm.setSNPcoldesign0_inter(Asnps0[0])
for iA in range(len(Asnps1)):
lmm.setSNPcoldesign(Asnps1[iA])
lmm.process()
pvAlt[iA,:] = lmm.getPv()[0]
pv[iA,:] = lmm.getPv()[1]
pv0 = lmm.getPv()[2]
return pv,pv0,pvAlt | [
"def",
"simple_interaction_kronecker",
"(",
"snps",
",",
"phenos",
",",
"covs",
"=",
"None",
",",
"Acovs",
"=",
"None",
",",
"Asnps1",
"=",
"None",
",",
"Asnps0",
"=",
"None",
",",
"K1r",
"=",
"None",
",",
"K1c",
"=",
"None",
",",
"K2r",
"=",
"None",
",",
"K2c",
"=",
"None",
",",
"covar_type",
"=",
"'lowrank_diag'",
",",
"rank",
"=",
"1",
",",
"NumIntervalsDelta0",
"=",
"100",
",",
"NumIntervalsDeltaAlt",
"=",
"0",
",",
"searchDelta",
"=",
"False",
")",
":",
"S",
"=",
"snps",
".",
"shape",
"[",
"1",
"]",
"#0. checks",
"N",
"=",
"phenos",
".",
"shape",
"[",
"0",
"]",
"P",
"=",
"phenos",
".",
"shape",
"[",
"1",
"]",
"if",
"K1r",
"==",
"None",
":",
"K1r",
"=",
"SP",
".",
"dot",
"(",
"snps",
",",
"snps",
".",
"T",
")",
"else",
":",
"assert",
"K1r",
".",
"shape",
"[",
"0",
"]",
"==",
"N",
",",
"'K1r: dimensions dismatch'",
"assert",
"K1r",
".",
"shape",
"[",
"1",
"]",
"==",
"N",
",",
"'K1r: dimensions dismatch'",
"if",
"K2r",
"==",
"None",
":",
"K2r",
"=",
"SP",
".",
"eye",
"(",
"N",
")",
"else",
":",
"assert",
"K2r",
".",
"shape",
"[",
"0",
"]",
"==",
"N",
",",
"'K2r: dimensions dismatch'",
"assert",
"K2r",
".",
"shape",
"[",
"1",
"]",
"==",
"N",
",",
"'K2r: dimensions dismatch'",
"covs",
",",
"Acovs",
"=",
"updateKronCovs",
"(",
"covs",
",",
"Acovs",
",",
"N",
",",
"P",
")",
"#Asnps can be several designs",
"if",
"(",
"Asnps0",
"is",
"None",
")",
":",
"Asnps0",
"=",
"[",
"SP",
".",
"ones",
"(",
"[",
"1",
",",
"P",
"]",
")",
"]",
"if",
"Asnps1",
"is",
"None",
":",
"Asnps1",
"=",
"[",
"SP",
".",
"eye",
"(",
"[",
"P",
"]",
")",
"]",
"if",
"(",
"type",
"(",
"Asnps0",
")",
"!=",
"list",
")",
":",
"Asnps0",
"=",
"[",
"Asnps0",
"]",
"if",
"(",
"type",
"(",
"Asnps1",
")",
"!=",
"list",
")",
":",
"Asnps1",
"=",
"[",
"Asnps1",
"]",
"assert",
"(",
"len",
"(",
"Asnps0",
")",
"==",
"1",
")",
"and",
"(",
"len",
"(",
"Asnps1",
")",
">",
"0",
")",
",",
"\"need at least one Snp design matrix for null and alt model\"",
"#one row per column design matrix",
"pv",
"=",
"SP",
".",
"zeros",
"(",
"(",
"len",
"(",
"Asnps1",
")",
",",
"snps",
".",
"shape",
"[",
"1",
"]",
")",
")",
"lrt",
"=",
"SP",
".",
"zeros",
"(",
"(",
"len",
"(",
"Asnps1",
")",
",",
"snps",
".",
"shape",
"[",
"1",
"]",
")",
")",
"pvAlt",
"=",
"SP",
".",
"zeros",
"(",
"(",
"len",
"(",
"Asnps1",
")",
",",
"snps",
".",
"shape",
"[",
"1",
"]",
")",
")",
"lrtAlt",
"=",
"SP",
".",
"zeros",
"(",
"(",
"len",
"(",
"Asnps1",
")",
",",
"snps",
".",
"shape",
"[",
"1",
"]",
")",
")",
"#1. run GP model to infer suitable covariance structure",
"if",
"K1c",
"==",
"None",
"or",
"K2c",
"==",
"None",
":",
"vc",
"=",
"estimateKronCovariances",
"(",
"phenos",
"=",
"phenos",
",",
"K1r",
"=",
"K1r",
",",
"K2r",
"=",
"K2r",
",",
"K1c",
"=",
"K1c",
",",
"K2c",
"=",
"K2c",
",",
"covs",
"=",
"covs",
",",
"Acovs",
"=",
"Acovs",
",",
"covar_type",
"=",
"covar_type",
",",
"rank",
"=",
"rank",
")",
"K1c",
"=",
"vc",
".",
"getEstTraitCovar",
"(",
"0",
")",
"K2c",
"=",
"vc",
".",
"getEstTraitCovar",
"(",
"1",
")",
"else",
":",
"assert",
"K1c",
".",
"shape",
"[",
"0",
"]",
"==",
"P",
",",
"'K1c: dimensions dismatch'",
"assert",
"K1c",
".",
"shape",
"[",
"1",
"]",
"==",
"P",
",",
"'K1c: dimensions dismatch'",
"assert",
"K2c",
".",
"shape",
"[",
"0",
"]",
"==",
"P",
",",
"'K2c: dimensions dismatch'",
"assert",
"K2c",
".",
"shape",
"[",
"1",
"]",
"==",
"P",
",",
"'K2c: dimensions dismatch'",
"#2. run kroneckerLMM for null model",
"lmm",
"=",
"limix",
".",
"CKroneckerLMM",
"(",
")",
"lmm",
".",
"setK1r",
"(",
"K1r",
")",
"lmm",
".",
"setK1c",
"(",
"K1c",
")",
"lmm",
".",
"setK2r",
"(",
"K2r",
")",
"lmm",
".",
"setK2c",
"(",
"K2c",
")",
"lmm",
".",
"setSNPs",
"(",
"snps",
")",
"#add covariates",
"for",
"ic",
"in",
"range",
"(",
"len",
"(",
"Acovs",
")",
")",
":",
"lmm",
".",
"addCovariates",
"(",
"covs",
"[",
"ic",
"]",
",",
"Acovs",
"[",
"ic",
"]",
")",
"lmm",
".",
"setPheno",
"(",
"phenos",
")",
"#delta serch on alt. model?",
"if",
"searchDelta",
":",
"lmm",
".",
"setNumIntervalsAlt",
"(",
"NumIntervalsDeltaAlt",
")",
"lmm",
".",
"setNumIntervals0_inter",
"(",
"NumIntervalsDeltaAlt",
")",
"else",
":",
"lmm",
".",
"setNumIntervalsAlt",
"(",
"0",
")",
"lmm",
".",
"setNumIntervals0_inter",
"(",
"0",
")",
"lmm",
".",
"setNumIntervals0",
"(",
"NumIntervalsDelta0",
")",
"#add SNP design",
"lmm",
".",
"setSNPcoldesign0_inter",
"(",
"Asnps0",
"[",
"0",
"]",
")",
"for",
"iA",
"in",
"range",
"(",
"len",
"(",
"Asnps1",
")",
")",
":",
"lmm",
".",
"setSNPcoldesign",
"(",
"Asnps1",
"[",
"iA",
"]",
")",
"lmm",
".",
"process",
"(",
")",
"pvAlt",
"[",
"iA",
",",
":",
"]",
"=",
"lmm",
".",
"getPv",
"(",
")",
"[",
"0",
"]",
"pv",
"[",
"iA",
",",
":",
"]",
"=",
"lmm",
".",
"getPv",
"(",
")",
"[",
"1",
"]",
"pv0",
"=",
"lmm",
".",
"getPv",
"(",
")",
"[",
"2",
"]",
"return",
"pv",
",",
"pv0",
",",
"pvAlt"
] | 49.024793 | 29.900826 |
def update_video(video_data):
"""
Called on to update Video objects in the database
update_video is used to update Video objects by the given edx_video_id in the video_data.
Args:
video_data (dict):
{
url: api url to the video
edx_video_id: ID of the video
duration: Length of video in seconds
client_video_id: client ID of video
encoded_video: a list of EncodedVideo dicts
url: url of the video
file_size: size of the video in bytes
profile: ID of the profile
courses: Courses associated with this video
}
Raises:
Raises ValVideoNotFoundError if the video cannot be retrieved.
Raises ValCannotUpdateError if the video cannot be updated.
Returns the successfully updated Video object
"""
try:
video = _get_video(video_data.get("edx_video_id"))
except Video.DoesNotExist:
error_message = u"Video not found when trying to update video with edx_video_id: {0}".format(video_data.get("edx_video_id"))
raise ValVideoNotFoundError(error_message)
serializer = VideoSerializer(video, data=video_data)
if serializer.is_valid():
serializer.save()
return video_data.get("edx_video_id")
else:
raise ValCannotUpdateError(serializer.errors) | [
"def",
"update_video",
"(",
"video_data",
")",
":",
"try",
":",
"video",
"=",
"_get_video",
"(",
"video_data",
".",
"get",
"(",
"\"edx_video_id\"",
")",
")",
"except",
"Video",
".",
"DoesNotExist",
":",
"error_message",
"=",
"u\"Video not found when trying to update video with edx_video_id: {0}\"",
".",
"format",
"(",
"video_data",
".",
"get",
"(",
"\"edx_video_id\"",
")",
")",
"raise",
"ValVideoNotFoundError",
"(",
"error_message",
")",
"serializer",
"=",
"VideoSerializer",
"(",
"video",
",",
"data",
"=",
"video_data",
")",
"if",
"serializer",
".",
"is_valid",
"(",
")",
":",
"serializer",
".",
"save",
"(",
")",
"return",
"video_data",
".",
"get",
"(",
"\"edx_video_id\"",
")",
"else",
":",
"raise",
"ValCannotUpdateError",
"(",
"serializer",
".",
"errors",
")"
] | 35.564103 | 22.076923 |
def has_errors(self, form):
"""
Find tab fields listed as invalid
"""
return any([fieldname_error for fieldname_error in form.errors.keys()
if fieldname_error in self]) | [
"def",
"has_errors",
"(",
"self",
",",
"form",
")",
":",
"return",
"any",
"(",
"[",
"fieldname_error",
"for",
"fieldname_error",
"in",
"form",
".",
"errors",
".",
"keys",
"(",
")",
"if",
"fieldname_error",
"in",
"self",
"]",
")"
] | 35.833333 | 9.833333 |
def delete(dataset):
"""Use this function to delete dataset by it's id."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
client.check_correct_host()
client.delete(dataset)
return ('Dataset {} has been deleted successfully'.format(dataset)) | [
"def",
"delete",
"(",
"dataset",
")",
":",
"config",
"=",
"ApiConfig",
"(",
")",
"client",
"=",
"ApiClient",
"(",
"config",
".",
"host",
",",
"config",
".",
"app_id",
",",
"config",
".",
"app_secret",
")",
"client",
".",
"check_correct_host",
"(",
")",
"client",
".",
"delete",
"(",
"dataset",
")",
"return",
"(",
"'Dataset {} has been deleted successfully'",
".",
"format",
"(",
"dataset",
")",
")"
] | 38.625 | 18.875 |
def _init_state(self, initial_state: Union[int, np.ndarray]):
"""Initializes a the shard wavefunction and sets the initial state."""
state = np.reshape(
sim.to_valid_state_vector(initial_state, self._num_qubits),
(self._num_shards, self._shard_size))
state_handle = mem_manager.SharedMemManager.create_array(
state.view(dtype=np.float32))
self._shared_mem_dict['state_handle'] = state_handle | [
"def",
"_init_state",
"(",
"self",
",",
"initial_state",
":",
"Union",
"[",
"int",
",",
"np",
".",
"ndarray",
"]",
")",
":",
"state",
"=",
"np",
".",
"reshape",
"(",
"sim",
".",
"to_valid_state_vector",
"(",
"initial_state",
",",
"self",
".",
"_num_qubits",
")",
",",
"(",
"self",
".",
"_num_shards",
",",
"self",
".",
"_shard_size",
")",
")",
"state_handle",
"=",
"mem_manager",
".",
"SharedMemManager",
".",
"create_array",
"(",
"state",
".",
"view",
"(",
"dtype",
"=",
"np",
".",
"float32",
")",
")",
"self",
".",
"_shared_mem_dict",
"[",
"'state_handle'",
"]",
"=",
"state_handle"
] | 56.5 | 15 |
def fqdns():
'''
Return all known FQDNs for the system by enumerating all interfaces and
then trying to reverse resolve them (excluding 'lo' interface).
'''
# Provides:
# fqdns
grains = {}
fqdns = set()
addresses = salt.utils.network.ip_addrs(include_loopback=False, interface_data=_get_interfaces())
addresses.extend(salt.utils.network.ip_addrs6(include_loopback=False, interface_data=_get_interfaces()))
err_message = 'Exception during resolving address: %s'
for ip in addresses:
try:
name, aliaslist, addresslist = socket.gethostbyaddr(ip)
fqdns.update([socket.getfqdn(name)] + [als for als in aliaslist if salt.utils.network.is_fqdn(als)])
except socket.herror as err:
if err.errno == 0:
# No FQDN for this IP address, so we don't need to know this all the time.
log.debug("Unable to resolve address %s: %s", ip, err)
else:
log.error(err_message, err)
except (socket.error, socket.gaierror, socket.timeout) as err:
log.error(err_message, err)
return {"fqdns": sorted(list(fqdns))} | [
"def",
"fqdns",
"(",
")",
":",
"# Provides:",
"# fqdns",
"grains",
"=",
"{",
"}",
"fqdns",
"=",
"set",
"(",
")",
"addresses",
"=",
"salt",
".",
"utils",
".",
"network",
".",
"ip_addrs",
"(",
"include_loopback",
"=",
"False",
",",
"interface_data",
"=",
"_get_interfaces",
"(",
")",
")",
"addresses",
".",
"extend",
"(",
"salt",
".",
"utils",
".",
"network",
".",
"ip_addrs6",
"(",
"include_loopback",
"=",
"False",
",",
"interface_data",
"=",
"_get_interfaces",
"(",
")",
")",
")",
"err_message",
"=",
"'Exception during resolving address: %s'",
"for",
"ip",
"in",
"addresses",
":",
"try",
":",
"name",
",",
"aliaslist",
",",
"addresslist",
"=",
"socket",
".",
"gethostbyaddr",
"(",
"ip",
")",
"fqdns",
".",
"update",
"(",
"[",
"socket",
".",
"getfqdn",
"(",
"name",
")",
"]",
"+",
"[",
"als",
"for",
"als",
"in",
"aliaslist",
"if",
"salt",
".",
"utils",
".",
"network",
".",
"is_fqdn",
"(",
"als",
")",
"]",
")",
"except",
"socket",
".",
"herror",
"as",
"err",
":",
"if",
"err",
".",
"errno",
"==",
"0",
":",
"# No FQDN for this IP address, so we don't need to know this all the time.",
"log",
".",
"debug",
"(",
"\"Unable to resolve address %s: %s\"",
",",
"ip",
",",
"err",
")",
"else",
":",
"log",
".",
"error",
"(",
"err_message",
",",
"err",
")",
"except",
"(",
"socket",
".",
"error",
",",
"socket",
".",
"gaierror",
",",
"socket",
".",
"timeout",
")",
"as",
"err",
":",
"log",
".",
"error",
"(",
"err_message",
",",
"err",
")",
"return",
"{",
"\"fqdns\"",
":",
"sorted",
"(",
"list",
"(",
"fqdns",
")",
")",
"}"
] | 40.857143 | 29.285714 |
def newest_file(file_iterable):
"""
Returns the name of the newest file given an iterable of file names.
"""
return max(file_iterable, key=lambda fname: os.path.getmtime(fname)) | [
"def",
"newest_file",
"(",
"file_iterable",
")",
":",
"return",
"max",
"(",
"file_iterable",
",",
"key",
"=",
"lambda",
"fname",
":",
"os",
".",
"path",
".",
"getmtime",
"(",
"fname",
")",
")"
] | 30.166667 | 18.166667 |
def _AsList(arg):
"""Encapsulates an argument in a list, if it's not already iterable."""
if (isinstance(arg, string_types) or
not isinstance(arg, collections.Iterable)):
return [arg]
else:
return list(arg) | [
"def",
"_AsList",
"(",
"arg",
")",
":",
"if",
"(",
"isinstance",
"(",
"arg",
",",
"string_types",
")",
"or",
"not",
"isinstance",
"(",
"arg",
",",
"collections",
".",
"Iterable",
")",
")",
":",
"return",
"[",
"arg",
"]",
"else",
":",
"return",
"list",
"(",
"arg",
")"
] | 33.142857 | 15 |
def re_tag(name, remote=False, commit=None):
"""Add a local tag with that name at that commit
If no commit is given, at current commit on cuurent branch
If remote is true, also push the tag to origin
If tag already exists, delete it, then re-make it
"""
if remote:
tags = run('ls-remote --tags', quiet=True).splitlines()
if name in tags:
hide(name)
if is_tag(name):
run('tag --delete %s' % name)
return tag(name, remote, commit) | [
"def",
"re_tag",
"(",
"name",
",",
"remote",
"=",
"False",
",",
"commit",
"=",
"None",
")",
":",
"if",
"remote",
":",
"tags",
"=",
"run",
"(",
"'ls-remote --tags'",
",",
"quiet",
"=",
"True",
")",
".",
"splitlines",
"(",
")",
"if",
"name",
"in",
"tags",
":",
"hide",
"(",
"name",
")",
"if",
"is_tag",
"(",
"name",
")",
":",
"run",
"(",
"'tag --delete %s'",
"%",
"name",
")",
"return",
"tag",
"(",
"name",
",",
"remote",
",",
"commit",
")"
] | 32.266667 | 15.933333 |
def validate_and_get_warnings(self):
"""
Validates/checks a given GTFS feed with respect to a number of different issues.
The set of warnings that are checked for, can be found in the gtfs_validator.ALL_WARNINGS
Returns
-------
warnings: WarningsContainer
"""
self.warnings_container.clear()
self._validate_stops_with_same_stop_time()
self._validate_speeds_and_trip_times()
self._validate_stop_spacings()
self._validate_stop_sequence()
self._validate_misplaced_stops()
return self.warnings_container | [
"def",
"validate_and_get_warnings",
"(",
"self",
")",
":",
"self",
".",
"warnings_container",
".",
"clear",
"(",
")",
"self",
".",
"_validate_stops_with_same_stop_time",
"(",
")",
"self",
".",
"_validate_speeds_and_trip_times",
"(",
")",
"self",
".",
"_validate_stop_spacings",
"(",
")",
"self",
".",
"_validate_stop_sequence",
"(",
")",
"self",
".",
"_validate_misplaced_stops",
"(",
")",
"return",
"self",
".",
"warnings_container"
] | 35.117647 | 15.705882 |
def unpatch(obj, name):
"""
Undo the effects of patch(func, obj, name)
"""
setattr(obj, name, getattr(obj, name).original) | [
"def",
"unpatch",
"(",
"obj",
",",
"name",
")",
":",
"setattr",
"(",
"obj",
",",
"name",
",",
"getattr",
"(",
"obj",
",",
"name",
")",
".",
"original",
")"
] | 26.8 | 6.8 |
def capture_snapshots(self, path_globs_and_roots):
"""Synchronously captures Snapshots for each matching PathGlobs rooted at a its root directory.
This is a blocking operation, and should be avoided where possible.
:param path_globs_and_roots tuple<PathGlobsAndRoot>: The PathGlobs to capture, and the root
directory relative to which each should be captured.
:returns: A tuple of Snapshots.
"""
result = self._native.lib.capture_snapshots(
self._scheduler,
self._to_value(_PathGlobsAndRootCollection(path_globs_and_roots)),
)
return self._raise_or_return(result) | [
"def",
"capture_snapshots",
"(",
"self",
",",
"path_globs_and_roots",
")",
":",
"result",
"=",
"self",
".",
"_native",
".",
"lib",
".",
"capture_snapshots",
"(",
"self",
".",
"_scheduler",
",",
"self",
".",
"_to_value",
"(",
"_PathGlobsAndRootCollection",
"(",
"path_globs_and_roots",
")",
")",
",",
")",
"return",
"self",
".",
"_raise_or_return",
"(",
"result",
")"
] | 43.357143 | 21.214286 |
def update_cname(name, data, **api_opts):
'''
Update CNAME. This is a helper call to update_object.
Find a CNAME ``_ref`` then call update_object with the record data.
CLI Example:
.. code-block:: bash
salt-call infoblox.update_cname name=example.example.com data="{
'canonical':'example-ha-0.example.com',
'use_ttl':true,
'ttl':200,
'comment':'Salt managed CNAME'}"
'''
o = get_cname(name=name, **api_opts)
if not o:
raise Exception('CNAME record not found')
return update_object(objref=o['_ref'], data=data, **api_opts) | [
"def",
"update_cname",
"(",
"name",
",",
"data",
",",
"*",
"*",
"api_opts",
")",
":",
"o",
"=",
"get_cname",
"(",
"name",
"=",
"name",
",",
"*",
"*",
"api_opts",
")",
"if",
"not",
"o",
":",
"raise",
"Exception",
"(",
"'CNAME record not found'",
")",
"return",
"update_object",
"(",
"objref",
"=",
"o",
"[",
"'_ref'",
"]",
",",
"data",
"=",
"data",
",",
"*",
"*",
"api_opts",
")"
] | 31.1 | 22.7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.