text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def metadata_add_endpoints(self):
""" Metadata: add endpoint to the group """
metadata = load_mpe_service_metadata(self.args.metadata_file)
group_name = metadata.get_group_name_nonetrick(self.args.group_name)
for endpoint in self.args.endpoints:
metadata.add_endpoint(group_na... | [
"def",
"metadata_add_endpoints",
"(",
"self",
")",
":",
"metadata",
"=",
"load_mpe_service_metadata",
"(",
"self",
".",
"args",
".",
"metadata_file",
")",
"group_name",
"=",
"metadata",
".",
"get_group_name_nonetrick",
"(",
"self",
".",
"args",
".",
"group_name",
... | 54.428571 | 14.857143 |
def prepare_request(node):
"""
Prepare request to node's API route
:param Node node: the RAML node object
"""
if node.resource.method not in AVAILABLE_METHODS:
raise UnsupportedHTTPMethodError(node.resource.method)
def request(data=None, json=None, **kwargs):
"""
... | [
"def",
"prepare_request",
"(",
"node",
")",
":",
"if",
"node",
".",
"resource",
".",
"method",
"not",
"in",
"AVAILABLE_METHODS",
":",
"raise",
"UnsupportedHTTPMethodError",
"(",
"node",
".",
"resource",
".",
"method",
")",
"def",
"request",
"(",
"data",
"=",... | 39 | 20.285714 |
def calc_filemap(atlas_properties, subject, atlas_version_tags, worklog,
output_path=None, overwrite=False, output_format='mgz', create_directory=False):
'''
calc_filemap is a calculator that converts the atlas properties nested-map into a single-depth
map whose keys are filenames and whose... | [
"def",
"calc_filemap",
"(",
"atlas_properties",
",",
"subject",
",",
"atlas_version_tags",
",",
"worklog",
",",
"output_path",
"=",
"None",
",",
"overwrite",
"=",
"False",
",",
"output_format",
"=",
"'mgz'",
",",
"create_directory",
"=",
"False",
")",
":",
"if... | 47.38806 | 24.850746 |
def get_initkwargs(cls, form_list, initial_dict=None,
instance_dict=None, condition_dict=None, *args, **kwargs):
"""
Creates a dict with all needed parameters for the form wizard instances.
* `form_list` - is a list of forms. The list entries can be single form
classes or tupl... | [
"def",
"get_initkwargs",
"(",
"cls",
",",
"form_list",
",",
"initial_dict",
"=",
"None",
",",
"instance_dict",
"=",
"None",
",",
"condition_dict",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'in... | 49.534483 | 22.637931 |
def echo_html_fenye_str(rec_num, fenye_num):
'''
生成分页的导航
'''
pagination_num = int(math.ceil(rec_num * 1.0 / 10))
if pagination_num == 1 or pagination_num == 0:
fenye_str = ''
elif pagination_num > 1:
pager_mid, pager_pre, pager_next, pager_last, pager_home = '', '', '', '', ''... | [
"def",
"echo_html_fenye_str",
"(",
"rec_num",
",",
"fenye_num",
")",
":",
"pagination_num",
"=",
"int",
"(",
"math",
".",
"ceil",
"(",
"rec_num",
"*",
"1.0",
"/",
"10",
")",
")",
"if",
"pagination_num",
"==",
"1",
"or",
"pagination_num",
"==",
"0",
":",
... | 32.907407 | 26.092593 |
def _ConvertMapFieldValue(self, value, message, field):
"""Convert map field value for a message map field.
Args:
value: A JSON object to convert the map field value.
message: A protocol message to record the converted data.
field: The descriptor of the map field to be converted.
Raises:... | [
"def",
"_ConvertMapFieldValue",
"(",
"self",
",",
"value",
",",
"message",
",",
"field",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"raise",
"ParseError",
"(",
"'Map field {0} must be in a dict which is {1}.'",
".",
"format",
"(",
... | 40.48 | 18.88 |
def buffer_to_value(self, obj, buffer, offset, default_endianness=DEFAULT_ENDIANNESS):
"""
Converts the bytes in ``buffer`` at ``offset`` to a native Python value. Returns that value and the number of
bytes consumed to create it.
:param obj: The parent :class:`.PebblePacket` of this fie... | [
"def",
"buffer_to_value",
"(",
"self",
",",
"obj",
",",
"buffer",
",",
"offset",
",",
"default_endianness",
"=",
"DEFAULT_ENDIANNESS",
")",
":",
"try",
":",
"value",
",",
"length",
"=",
"struct",
".",
"unpack_from",
"(",
"str",
"(",
"self",
".",
"endiannes... | 48.931034 | 23.068966 |
def append_func(self, func, *args, **kwargs):
'''
append func with given arguments and keywords.
'''
wraped_func = partial(func, *args, **kwargs)
self.append(wraped_func) | [
"def",
"append_func",
"(",
"self",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"wraped_func",
"=",
"partial",
"(",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"append",
"(",
"wraped_func",
")"
] | 34.166667 | 16.166667 |
def cloudshell_model_name(self):
"""Return the name of the CloudShell model"""
if self.shell_name:
return "{shell_name}.{resource_model}".format(shell_name=self.shell_name,
resource_model=self.RESOURCE_MODEL.replace(" ", ""))
... | [
"def",
"cloudshell_model_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"shell_name",
":",
"return",
"\"{shell_name}.{resource_model}\"",
".",
"format",
"(",
"shell_name",
"=",
"self",
".",
"shell_name",
",",
"resource_model",
"=",
"self",
".",
"RESOURCE_MODEL",... | 51.142857 | 23.571429 |
def b_fit_score(self, x, y):
""" Computes the cds statistic from variable 1 to variable 2
Args:
a (numpy.ndarray): Variable 1
b (numpy.ndarray): Variable 2
Returns:
float: BF fit score
"""
x = np.reshape(scale(x), (-1, 1))
y = np.resh... | [
"def",
"b_fit_score",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"x",
"=",
"np",
".",
"reshape",
"(",
"scale",
"(",
"x",
")",
",",
"(",
"-",
"1",
",",
"1",
")",
")",
"y",
"=",
"np",
".",
"reshape",
"(",
"scale",
"(",
"y",
")",
",",
"(",
... | 28.294118 | 14.117647 |
def linkify_hostgroups_hosts(self, hosts):
"""We just search for each hostgroup the id of the hosts
and replace the names by the found identifiers
:param hosts: object Hosts
:type hosts: alignak.objects.host.Hosts
:return: None
"""
for hostgroup in self:
... | [
"def",
"linkify_hostgroups_hosts",
"(",
"self",
",",
"hosts",
")",
":",
"for",
"hostgroup",
"in",
"self",
":",
"members",
"=",
"hostgroup",
".",
"get_hosts",
"(",
")",
"# The new members identifiers list",
"new_members",
"=",
"[",
"]",
"for",
"member",
"in",
"... | 38 | 13.8 |
def get_request_data(self, var_name, full_data=False):
"""
:param var_name:
:param full_data: If you want `.to_array()` with this data, ready to be sent.
:return: A tuple of `to_array()` dict and the files (:py:func:`InputFile.get_request_files()`).
Files can be None, if... | [
"def",
"get_request_data",
"(",
"self",
",",
"var_name",
",",
"full_data",
"=",
"False",
")",
":",
"if",
"not",
"full_data",
":",
"raise",
"ArithmeticError",
"(",
"'we have a thumbnail, please use `full_data=True`.'",
")",
"# end if",
"file",
"=",
"{",
"}",
"data"... | 51.428571 | 30.928571 |
def logo(symbol, token='', version=''):
'''This is a helper function, but the google APIs url is standardized.
https://iexcloud.io/docs/api/#logo
8am UTC daily
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
... | [
"def",
"logo",
"(",
"symbol",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"_raiseIfNotStr",
"(",
"symbol",
")",
"return",
"_getJson",
"(",
"'stock/'",
"+",
"symbol",
"+",
"'/logo'",
",",
"token",
",",
"version",
")"
] | 26.3125 | 21.1875 |
def _to_kraus(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Kraus representation."""
if rep == 'Kraus':
return data
if rep == 'Stinespring':
return _stinespring_to_kraus(data, input_dim, output_dim)
if rep == 'Operator':
return _from_operator('Kraus', da... | [
"def",
"_to_kraus",
"(",
"rep",
",",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"if",
"rep",
"==",
"'Kraus'",
":",
"return",
"data",
"if",
"rep",
"==",
"'Stinespring'",
":",
"return",
"_stinespring_to_kraus",
"(",
"data",
",",
"input_dim",
",",... | 41.916667 | 15.333333 |
def logit_px(self)->LogitTensorImage:
"Get logit(image.px)."
if self._logit_px is None: self._logit_px = logit_(self.px)
return self._logit_px | [
"def",
"logit_px",
"(",
"self",
")",
"->",
"LogitTensorImage",
":",
"if",
"self",
".",
"_logit_px",
"is",
"None",
":",
"self",
".",
"_logit_px",
"=",
"logit_",
"(",
"self",
".",
"px",
")",
"return",
"self",
".",
"_logit_px"
] | 40.75 | 12.75 |
def _parse(args):
"""Parse passed arguments from shell."""
ordered = []
opt_full = dict()
opt_abbrev = dict()
args = args + [''] # Avoid out of range
i = 0
while i < len(args) - 1:
arg = args[i]
arg_next = args[i+1]
if arg.startswith('--'):
if arg_next... | [
"def",
"_parse",
"(",
"args",
")",
":",
"ordered",
"=",
"[",
"]",
"opt_full",
"=",
"dict",
"(",
")",
"opt_abbrev",
"=",
"dict",
"(",
")",
"args",
"=",
"args",
"+",
"[",
"''",
"]",
"# Avoid out of range",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"... | 26.466667 | 17.533333 |
def artist(self):
"""
:class:`Artist` object of album's artist
"""
if not self._artist:
self._artist = Artist(self._artist_id, self._artist_name, self._connection)
return self._artist | [
"def",
"artist",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_artist",
":",
"self",
".",
"_artist",
"=",
"Artist",
"(",
"self",
".",
"_artist_id",
",",
"self",
".",
"_artist_name",
",",
"self",
".",
"_connection",
")",
"return",
"self",
".",
"_... | 32.714286 | 14.714286 |
def fmt_text(text):
""" convert characters that aren't printable to hex format
"""
PRINTABLE_CHAR = set(
list(range(ord(' '), ord('~') + 1)) + [ord('\r'), ord('\n')])
newtext = ("\\x{:02X}".format(
c) if c not in PRINTABLE_CHAR else chr(c) for c in text)
textlines = "\r\n".join(l.str... | [
"def",
"fmt_text",
"(",
"text",
")",
":",
"PRINTABLE_CHAR",
"=",
"set",
"(",
"list",
"(",
"range",
"(",
"ord",
"(",
"' '",
")",
",",
"ord",
"(",
"'~'",
")",
"+",
"1",
")",
")",
"+",
"[",
"ord",
"(",
"'\\r'",
")",
",",
"ord",
"(",
"'\\n'",
")"... | 40.7 | 14.2 |
def extract(args):
"""
%prog extract idsfile sizesfile
Extract the lines containing only the given IDs.
"""
p = OptionParser(extract.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
idsfile, sizesfile = args
sizes = Sizes(sizesfile).... | [
"def",
"extract",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"extract",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
... | 24.210526 | 15.052632 |
def execute_notebook(self, name):
"""Loads and then runs a notebook file."""
warnings.filterwarnings("ignore", category=DeprecationWarning)
nb,f = self.load_notebook(name)
self.run_notebook(nb,f)
self.assertTrue(True) | [
"def",
"execute_notebook",
"(",
"self",
",",
"name",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"\"ignore\"",
",",
"category",
"=",
"DeprecationWarning",
")",
"nb",
",",
"f",
"=",
"self",
".",
"load_notebook",
"(",
"name",
")",
"self",
".",
"run_not... | 36 | 14 |
def async_command(self, command, raw=False, timeout_ms=None):
"""See shell_service.ShellService.async_command()."""
return self.shell_service.async_command(
str(command), raw=raw, timeout_ms=timeout_ms) | [
"def",
"async_command",
"(",
"self",
",",
"command",
",",
"raw",
"=",
"False",
",",
"timeout_ms",
"=",
"None",
")",
":",
"return",
"self",
".",
"shell_service",
".",
"async_command",
"(",
"str",
"(",
"command",
")",
",",
"raw",
"=",
"raw",
",",
"timeou... | 53.75 | 9.5 |
def update_dashboards(modules, horizon_config, installed_apps):
"""Imports dashboard and panel configuration from modules and applies it.
The submodules from specified modules are imported, and the configuration
for the specific dashboards is merged, with the later modules overriding
settings from the ... | [
"def",
"update_dashboards",
"(",
"modules",
",",
"horizon_config",
",",
"installed_apps",
")",
":",
"config_dashboards",
"=",
"horizon_config",
".",
"get",
"(",
"'dashboards'",
",",
"[",
"]",
")",
"if",
"config_dashboards",
"or",
"horizon_config",
".",
"get",
"(... | 46.661538 | 21.538462 |
def anonymous_login(services):
"""Initialize services without authenticating to Globus Auth.
Note:
Clients may have reduced functionality without authentication.
Arguments:
services (str or list of str): The services to initialize clients for.
Returns:
dict: The clients reques... | [
"def",
"anonymous_login",
"(",
"services",
")",
":",
"if",
"isinstance",
"(",
"services",
",",
"str",
")",
":",
"services",
"=",
"[",
"services",
"]",
"clients",
"=",
"{",
"}",
"# Initialize valid services",
"for",
"serv",
"in",
"services",
":",
"try",
":"... | 33.148148 | 23.888889 |
def Message(msg, id=260, ok=None):
"""Original doc: Display a MESSAGE string.
Return when the user clicks the OK button or presses Return.
The MESSAGE string can be at most 255 characters long.
"""
return psidialogs.message(message=msg, ok=ok) | [
"def",
"Message",
"(",
"msg",
",",
"id",
"=",
"260",
",",
"ok",
"=",
"None",
")",
":",
"return",
"psidialogs",
".",
"message",
"(",
"message",
"=",
"msg",
",",
"ok",
"=",
"ok",
")"
] | 32.25 | 17.125 |
def do_state_tomography(preparation_program, nsamples, cxn, qubits=None, use_run=False):
"""
Method to perform both a QPU and QVM state tomography, and use the latter as
as reference to calculate the fidelity of the former.
:param Program preparation_program: Program to execute.
:param int nsamples... | [
"def",
"do_state_tomography",
"(",
"preparation_program",
",",
"nsamples",
",",
"cxn",
",",
"qubits",
"=",
"None",
",",
"use_run",
"=",
"False",
")",
":",
"return",
"tomography",
".",
"_do_tomography",
"(",
"preparation_program",
",",
"nsamples",
",",
"cxn",
"... | 55.263158 | 25.368421 |
def finalize(self) -> None:
''' split statement and task by last directive '''
self.wrap_script()
if not self.statements:
self.task = ''
return
# handle tasks
input_directive = [
idx for idx, statement in enumerate(self.statements)
... | [
"def",
"finalize",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"wrap_script",
"(",
")",
"if",
"not",
"self",
".",
"statements",
":",
"self",
".",
"task",
"=",
"''",
"return",
"# handle tasks",
"input_directive",
"=",
"[",
"idx",
"for",
"idx",
","... | 47 | 19.269231 |
def get_witness(self, work, siglum, text_class=WitnessText):
"""Returns a `WitnessText` representing the file associated with
`work` and `siglum`.
Combined, `work` and `siglum` form the basis of a filename for
retrieving the text.
:param work: name of work
:type work: `... | [
"def",
"get_witness",
"(",
"self",
",",
"work",
",",
"siglum",
",",
"text_class",
"=",
"WitnessText",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work",
",",
"siglum",
"+",
"'.txt'",
")",
"self",
".",
"_logger",
".",
"debug",
"("... | 36.285714 | 18.52381 |
def get_resource_ids(self):
"""
Get resource ids as a list.
:return: List of resource id:s or "unknown"
"""
resids = []
if self.dutinformations:
for info in self.dutinformations:
resids.append(info.resource_id)
return resids
... | [
"def",
"get_resource_ids",
"(",
"self",
")",
":",
"resids",
"=",
"[",
"]",
"if",
"self",
".",
"dutinformations",
":",
"for",
"info",
"in",
"self",
".",
"dutinformations",
":",
"resids",
".",
"append",
"(",
"info",
".",
"resource_id",
")",
"return",
"resi... | 27.25 | 11.75 |
def plot_covariance(
mean, cov=None, variance=1.0, std=None, interval=None,
ellipse=None, title=None, axis_equal=True,
show_semiaxis=False, show_center=True,
facecolor=None, edgecolor=None,
fc='none', ec='#004080',
alpha=1.0, xlim=None, ylim=None,
ls='solid'):
... | [
"def",
"plot_covariance",
"(",
"mean",
",",
"cov",
"=",
"None",
",",
"variance",
"=",
"1.0",
",",
"std",
"=",
"None",
",",
"interval",
"=",
"None",
",",
"ellipse",
"=",
"None",
",",
"title",
"=",
"None",
",",
"axis_equal",
"=",
"True",
",",
"show_sem... | 30.479167 | 21.868056 |
def abspath(cur_file, parent=0) -> str:
"""
Absolute path
Args:
cur_file: __file__ or file or path str
parent: level of parent to look for
Returns:
str
"""
file_path = os.path.abspath(cur_file).replace('\\', '/')
if os.path.isdir(file_path) and parent == 0: return f... | [
"def",
"abspath",
"(",
"cur_file",
",",
"parent",
"=",
"0",
")",
"->",
"str",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"cur_file",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"... | 27.533333 | 17.8 |
def inverted(values, input_min=0, input_max=1):
"""
Returns the inversion of the supplied values (*input_min* becomes
*input_max*, *input_max* becomes *input_min*, `input_min + 0.1` becomes
`input_max - 0.1`, etc.). All items in *values* are assumed to be between
*input_min* and *input_max* (which d... | [
"def",
"inverted",
"(",
"values",
",",
"input_min",
"=",
"0",
",",
"input_max",
"=",
"1",
")",
":",
"values",
"=",
"_normalize",
"(",
"values",
")",
"if",
"input_min",
">=",
"input_max",
":",
"raise",
"ValueError",
"(",
"'input_min must be smaller than input_m... | 34.333333 | 19.083333 |
def export_avg_losses(ekey, dstore):
"""
:param ekey: export key, i.e. a pair (datastore key, fmt)
:param dstore: datastore object
"""
dskey = ekey[0]
oq = dstore['oqparam']
dt = oq.loss_dt()
name, value, tags = _get_data(dstore, dskey, oq.hazard_stats().items())
writer = writers.Csv... | [
"def",
"export_avg_losses",
"(",
"ekey",
",",
"dstore",
")",
":",
"dskey",
"=",
"ekey",
"[",
"0",
"]",
"oq",
"=",
"dstore",
"[",
"'oqparam'",
"]",
"dt",
"=",
"oq",
".",
"loss_dt",
"(",
")",
"name",
",",
"value",
",",
"tags",
"=",
"_get_data",
"(",
... | 38.166667 | 11.611111 |
def str(password,
opslimit=OPSLIMIT_INTERACTIVE,
memlimit=MEMLIMIT_INTERACTIVE):
"""
Hashes a password with a random salt, using the memory-hard
argon2i construct and returning an ascii string that has all
the needed info to check against a future password
The default settings for ... | [
"def",
"str",
"(",
"password",
",",
"opslimit",
"=",
"OPSLIMIT_INTERACTIVE",
",",
"memlimit",
"=",
"MEMLIMIT_INTERACTIVE",
")",
":",
"return",
"nacl",
".",
"bindings",
".",
"crypto_pwhash_str_alg",
"(",
"password",
",",
"opslimit",
",",
"memlimit",
",",
"ALG",
... | 32.130435 | 18.478261 |
def _inputcooker_store(self, char):
"""Put the cooked data in the correct queue"""
if self.sb:
self.sbdataq = self.sbdataq + char
else:
self.inputcooker_store_queue(char) | [
"def",
"_inputcooker_store",
"(",
"self",
",",
"char",
")",
":",
"if",
"self",
".",
"sb",
":",
"self",
".",
"sbdataq",
"=",
"self",
".",
"sbdataq",
"+",
"char",
"else",
":",
"self",
".",
"inputcooker_store_queue",
"(",
"char",
")"
] | 35.5 | 10.833333 |
def gemini_writer(self, f_handle):
"""
Write out a GEMINI formated OT ephemeris. This is just a hack of SSD Horizons output.
"""
f_handle.write(GEMINI_HEADER)
# Date__(UT)__HR:MN Date_________JDUT R.A.___(ICRF/J2000.0)___DEC dRA*cosD d(DEC)/dt
# 1 2 ... | [
"def",
"gemini_writer",
"(",
"self",
",",
"f_handle",
")",
":",
"f_handle",
".",
"write",
"(",
"GEMINI_HEADER",
")",
"# Date__(UT)__HR:MN Date_________JDUT R.A.___(ICRF/J2000.0)___DEC dRA*cosD d(DEC)/dt",
"# 1 2 3 4 5 6 7 ... | 70.521739 | 40.869565 |
def _get_object_as_soft(self):
"""Return object as SOFT formatted string."""
soft = []
if self.database is not None:
soft.append(self.database._get_object_as_soft())
soft += ["^%s = %s" % (self.geotype, self.name),
self._get_metadata_as_string()]
for ... | [
"def",
"_get_object_as_soft",
"(",
"self",
")",
":",
"soft",
"=",
"[",
"]",
"if",
"self",
".",
"database",
"is",
"not",
"None",
":",
"soft",
".",
"append",
"(",
"self",
".",
"database",
".",
"_get_object_as_soft",
"(",
")",
")",
"soft",
"+=",
"[",
"\... | 44.307692 | 10.384615 |
def __load_project(path):
'''
Load a docker-compose project from path
:param path:
:return:
'''
file_path = __get_docker_file_path(path)
if file_path is None:
msg = 'Could not find docker-compose file at {0}'.format(path)
return __standardize_result(False,
... | [
"def",
"__load_project",
"(",
"path",
")",
":",
"file_path",
"=",
"__get_docker_file_path",
"(",
"path",
")",
"if",
"file_path",
"is",
"None",
":",
"msg",
"=",
"'Could not find docker-compose file at {0}'",
".",
"format",
"(",
"path",
")",
"return",
"__standardize... | 30.642857 | 17.5 |
def get_unique_families(hkls):
"""
Returns unique families of Miller indices. Families must be permutations
of each other.
Args:
hkls ([h, k, l]): List of Miller indices.
Returns:
{hkl: multiplicity}: A dict with unique hkl and multiplicity.
"""
# TODO: Definitely can be sp... | [
"def",
"get_unique_families",
"(",
"hkls",
")",
":",
"# TODO: Definitely can be sped up.",
"def",
"is_perm",
"(",
"hkl1",
",",
"hkl2",
")",
":",
"h1",
"=",
"np",
".",
"abs",
"(",
"hkl1",
")",
"h2",
"=",
"np",
".",
"abs",
"(",
"hkl2",
")",
"return",
"al... | 26.787879 | 17.878788 |
def to_cartesian(r, theta, theta_units="radians"):
"""
Converts polar r, theta to cartesian x, y.
"""
assert theta_units in ['radians', 'degrees'],\
"kwarg theta_units must specified in radians or degrees"
# Convert to radians
if theta_units == "degrees":
theta = to_radians(thet... | [
"def",
"to_cartesian",
"(",
"r",
",",
"theta",
",",
"theta_units",
"=",
"\"radians\"",
")",
":",
"assert",
"theta_units",
"in",
"[",
"'radians'",
",",
"'degrees'",
"]",
",",
"\"kwarg theta_units must specified in radians or degrees\"",
"# Convert to radians",
"if",
"t... | 25.5 | 16.625 |
def vms(message, level=1):
"""Writes the specified message *only* if verbose output is enabled."""
if verbose is not None and verbose != False:
if isinstance(verbose, bool) or (isinstance(verbose, int) and level <= verbose):
std(message) | [
"def",
"vms",
"(",
"message",
",",
"level",
"=",
"1",
")",
":",
"if",
"verbose",
"is",
"not",
"None",
"and",
"verbose",
"!=",
"False",
":",
"if",
"isinstance",
"(",
"verbose",
",",
"bool",
")",
"or",
"(",
"isinstance",
"(",
"verbose",
",",
"int",
"... | 52.2 | 17.2 |
def search(geo_coords, mode=2, verbose=True):
"""
Function to query for a list of coordinates
"""
if not isinstance(geo_coords, tuple) and not isinstance(geo_coords, list):
raise TypeError('Expecting a tuple or a tuple/list of tuples')
elif not isinstance(geo_coords[0], tuple):
geo_c... | [
"def",
"search",
"(",
"geo_coords",
",",
"mode",
"=",
"2",
",",
"verbose",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"geo_coords",
",",
"tuple",
")",
"and",
"not",
"isinstance",
"(",
"geo_coords",
",",
"list",
")",
":",
"raise",
"TypeError... | 37.454545 | 13.454545 |
def handle_error(self, failure):
"""
Provides basic error information for bad requests.
If the error was an HttpError or DNSLookupError, it
prints more specific information.
"""
self.logger.error(repr(failure))
if failure.check(HttpError):
response = ... | [
"def",
"handle_error",
"(",
"self",
",",
"failure",
")",
":",
"self",
".",
"logger",
".",
"error",
"(",
"repr",
"(",
"failure",
")",
")",
"if",
"failure",
".",
"check",
"(",
"HttpError",
")",
":",
"response",
"=",
"failure",
".",
"value",
".",
"respo... | 43.571429 | 14.333333 |
def hlen(key, host=None, port=None, db=None, password=None):
'''
Returns number of fields of a hash.
.. versionadded:: 2017.7.0
CLI Example:
.. code-block:: bash
salt '*' redis.hlen foo_hash
'''
server = _connect(host, port, db, password)
return server.hlen(key) | [
"def",
"hlen",
"(",
"key",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"db",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"server",
"=",
"_connect",
"(",
"host",
",",
"port",
",",
"db",
",",
"password",
")",
"return",
"server... | 20.928571 | 22.928571 |
def aboveAt(self, offset=0):
""" Returns point in the center of the region's top side (offset to the top
by negative ``offset``) """
return Location(self.getX() + (self.getW() / 2), self.getY() + offset) | [
"def",
"aboveAt",
"(",
"self",
",",
"offset",
"=",
"0",
")",
":",
"return",
"Location",
"(",
"self",
".",
"getX",
"(",
")",
"+",
"(",
"self",
".",
"getW",
"(",
")",
"/",
"2",
")",
",",
"self",
".",
"getY",
"(",
")",
"+",
"offset",
")"
] | 56 | 12.5 |
def create_apply_graph(self, signature, input_tensors, name):
"""See `ModuleImpl.create_apply_graph`."""
signature_def = self._meta_graph.signature_def.get(signature)
meta_graph = meta_graph_pb2.MetaGraphDef()
meta_graph.CopyFrom(self._meta_graph)
apply_graph = tf_v1.get_default_graph()
infeed_m... | [
"def",
"create_apply_graph",
"(",
"self",
",",
"signature",
",",
"input_tensors",
",",
"name",
")",
":",
"signature_def",
"=",
"self",
".",
"_meta_graph",
".",
"signature_def",
".",
"get",
"(",
"signature",
")",
"meta_graph",
"=",
"meta_graph_pb2",
".",
"MetaG... | 46.755556 | 22.377778 |
def expose_event(self, widget, event):
"""When an area of the window is exposed, we just copy out of the
server-side, off-screen surface to that area.
"""
x, y, width, height = event.area
self.logger.debug("surface is %s" % self.surface)
if self.surface is not None:
... | [
"def",
"expose_event",
"(",
"self",
",",
"widget",
",",
"event",
")",
":",
"x",
",",
"y",
",",
"width",
",",
"height",
"=",
"event",
".",
"area",
"self",
".",
"logger",
".",
"debug",
"(",
"\"surface is %s\"",
"%",
"self",
".",
"surface",
")",
"if",
... | 34 | 12.9 |
def _GetVSSStoreIdentifiers(self, scan_node):
"""Determines the VSS store identifiers.
Args:
scan_node (SourceScanNode): scan node.
Returns:
list[str]: VSS store identifiers.
Raises:
ScannerError: if the format the scan node is invalid or no mediator
is provided and VSS st... | [
"def",
"_GetVSSStoreIdentifiers",
"(",
"self",
",",
"scan_node",
")",
":",
"if",
"not",
"scan_node",
"or",
"not",
"scan_node",
".",
"path_spec",
":",
"raise",
"errors",
".",
"ScannerError",
"(",
"'Invalid scan node.'",
")",
"volume_system",
"=",
"vshadow_volume_sy... | 30.948718 | 20.923077 |
def repeat_nd(a, repeats):
"""Return read-only view into input array with elements repeated.
Zoom nD image by integer factors using nearest neighbor interpolation
(box filter).
Parameters
----------
a : array_like
Input array.
repeats : sequence of int
The number of repetit... | [
"def",
"repeat_nd",
"(",
"a",
",",
"repeats",
")",
":",
"a",
"=",
"numpy",
".",
"asarray",
"(",
"a",
")",
"reshape",
"=",
"[",
"]",
"shape",
"=",
"[",
"]",
"strides",
"=",
"[",
"]",
"for",
"i",
",",
"j",
",",
"k",
"in",
"zip",
"(",
"a",
"."... | 26.40625 | 20.53125 |
def oauth2(self):
"""
returns the oauth2 class
"""
if self._url.endswith("/oauth2"):
url = self._url
else:
url = self._url + "/oauth2"
return _oauth2.oauth2(oauth_url=url,
securityHandler=self._securityHandler,
... | [
"def",
"oauth2",
"(",
"self",
")",
":",
"if",
"self",
".",
"_url",
".",
"endswith",
"(",
"\"/oauth2\"",
")",
":",
"url",
"=",
"self",
".",
"_url",
"else",
":",
"url",
"=",
"self",
".",
"_url",
"+",
"\"/oauth2\"",
"return",
"_oauth2",
".",
"oauth2",
... | 34.75 | 11.583333 |
def _format_list(self, extracted_list):
"""Format a list of traceback entry tuples for printing.
Given a list of tuples as returned by extract_tb() or
extract_stack(), return a list of strings ready for printing.
Each string in the resulting list corresponds to the item with the
... | [
"def",
"_format_list",
"(",
"self",
",",
"extracted_list",
")",
":",
"Colors",
"=",
"self",
".",
"Colors",
"list",
"=",
"[",
"]",
"for",
"filename",
",",
"lineno",
",",
"name",
",",
"line",
"in",
"extracted_list",
"[",
":",
"-",
"1",
"]",
":",
"item"... | 44.621622 | 19.297297 |
def delete_db_instance(self, dbid):
''' Delete DB '''
if not self.connect_to_aws_rds():
return False
try:
database = self.rdsc.delete_dbinstance(dbid,
skip_final_snapshot=True)
print database
except:
... | [
"def",
"delete_db_instance",
"(",
"self",
",",
"dbid",
")",
":",
"if",
"not",
"self",
".",
"connect_to_aws_rds",
"(",
")",
":",
"return",
"False",
"try",
":",
"database",
"=",
"self",
".",
"rdsc",
".",
"delete_dbinstance",
"(",
"dbid",
",",
"skip_final_sna... | 30.833333 | 18 |
def is_bridge(self):
"""bool: Is this zone a bridge?"""
# Since this does not change over time (?) check whether we already
# know the answer. If so, there is no need to go further
if self._is_bridge is not None:
return self._is_bridge
# if not, we have to get it from... | [
"def",
"is_bridge",
"(",
"self",
")",
":",
"# Since this does not change over time (?) check whether we already",
"# know the answer. If so, there is no need to go further",
"if",
"self",
".",
"_is_bridge",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_is_bridge",
"# if ... | 45.909091 | 17.363636 |
def register_column(self,
column,
expr,
deltas=None,
checkpoints=None,
odo_kwargs=None):
"""Explicitly map a single bound column to a collection of blaze
expressions. The expressions n... | [
"def",
"register_column",
"(",
"self",
",",
"column",
",",
"expr",
",",
"deltas",
"=",
"None",
",",
"checkpoints",
"=",
"None",
",",
"odo_kwargs",
"=",
"None",
")",
":",
"self",
".",
"_table_expressions",
"[",
"column",
"]",
"=",
"ExprData",
"(",
"expr",... | 32 | 16.515152 |
async def _redirect(self, response_obj):
'''
Calls the _check_redirect method of the supplied response object
in order to determine if the http status code indicates a redirect.
Returns:
Response: May or may not be the result of recursive calls due
to redirects!
... | [
"async",
"def",
"_redirect",
"(",
"self",
",",
"response_obj",
")",
":",
"redirect",
",",
"force_get",
",",
"location",
"=",
"False",
",",
"None",
",",
"None",
"if",
"300",
"<=",
"response_obj",
".",
"status_code",
"<",
"400",
":",
"if",
"response_obj",
... | 39.492063 | 19.238095 |
def reread(self):
"""
Read and parse credentials file.
If something goes wrong, log exception and continue.
"""
logger.debug("Loading credentials from %s",
os.path.abspath(self.creds_filename))
creds = {}
try:
with self.open_creds(... | [
"def",
"reread",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Loading credentials from %s\"",
",",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"creds_filename",
")",
")",
"creds",
"=",
"{",
"}",
"try",
":",
"with",
"self",
".",
"open... | 34.2 | 14.2 |
def fullversion():
'''
Return all server information from catalina.sh version
CLI Example:
.. code-block:: bash
salt '*' tomcat.fullversion
'''
cmd = __catalina_home() + '/bin/catalina.sh version'
ret = {}
out = __salt__['cmd.run'](cmd).splitlines()
for line in out:
... | [
"def",
"fullversion",
"(",
")",
":",
"cmd",
"=",
"__catalina_home",
"(",
")",
"+",
"'/bin/catalina.sh version'",
"ret",
"=",
"{",
"}",
"out",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
".",
"splitlines",
"(",
")",
"for",
"line",
"in",
"ou... | 22.95 | 21.65 |
def serialize(obj):
"""JSON serializer that accepts datetime & date"""
from datetime import datetime, date, time
if isinstance(obj, date) and not isinstance(obj, datetime):
obj = datetime.combine(obj, time.min)
if isinstance(obj, datetime):
return obj.isoformat() | [
"def",
"serialize",
"(",
"obj",
")",
":",
"from",
"datetime",
"import",
"datetime",
",",
"date",
",",
"time",
"if",
"isinstance",
"(",
"obj",
",",
"date",
")",
"and",
"not",
"isinstance",
"(",
"obj",
",",
"datetime",
")",
":",
"obj",
"=",
"datetime",
... | 41.285714 | 10.142857 |
def formatter_help(cls):
""" Return a list of format specifiers and their documentation.
"""
result = [("raw", "Switch off the default field formatter.")]
for name, method in globals().items():
if name.startswith("fmt_"):
result.append((name[4:], method.__doc... | [
"def",
"formatter_help",
"(",
"cls",
")",
":",
"result",
"=",
"[",
"(",
"\"raw\"",
",",
"\"Switch off the default field formatter.\"",
")",
"]",
"for",
"name",
",",
"method",
"in",
"globals",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"name",
".",
"sta... | 34.6 | 17.6 |
def illumg(method, target, ilusrc, et, fixref, abcorr, obsrvr, spoint):
"""
Find the illumination angles (phase, incidence, and
emission) at a specified surface point of a target body.
The surface of the target body may be represented by a triaxial
ellipsoid or by topographic data provided by D... | [
"def",
"illumg",
"(",
"method",
",",
"target",
",",
"ilusrc",
",",
"et",
",",
"fixref",
",",
"abcorr",
",",
"obsrvr",
",",
"spoint",
")",
":",
"method",
"=",
"stypes",
".",
"stringToCharP",
"(",
"method",
")",
"target",
"=",
"stypes",
".",
"stringToCha... | 41.176471 | 16.392157 |
def _get_model_parameters_estimations(self, error_model):
"""
Infer model estimation method from the 'error_model'. Return an object
of type ModelParametersEstimation.
"""
if error_model.dependance == NIDM_INDEPEDENT_ERROR:
if error_model.variance_homo:
... | [
"def",
"_get_model_parameters_estimations",
"(",
"self",
",",
"error_model",
")",
":",
"if",
"error_model",
".",
"dependance",
"==",
"NIDM_INDEPEDENT_ERROR",
":",
"if",
"error_model",
".",
"variance_homo",
":",
"estimation_method",
"=",
"STATO_OLS",
"else",
":",
"es... | 34.625 | 17.25 |
def _process_flux_param(self, pval, wave):
"""Process individual model parameter representing flux."""
if isinstance(pval, u.Quantity):
self._validate_flux_unit(pval.unit)
outval = units.convert_flux(self._redshift_model(wave), pval,
self._... | [
"def",
"_process_flux_param",
"(",
"self",
",",
"pval",
",",
"wave",
")",
":",
"if",
"isinstance",
"(",
"pval",
",",
"u",
".",
"Quantity",
")",
":",
"self",
".",
"_validate_flux_unit",
"(",
"pval",
".",
"unit",
")",
"outval",
"=",
"units",
".",
"conver... | 48.222222 | 12.777778 |
def str_append_hash(*args):
""" Convert each argument to a lower case string, appended, then hash """
ret_hash = ""
for i in args:
ret_hash += str(i).lower()
return hash(ret_hash) | [
"def",
"str_append_hash",
"(",
"*",
"args",
")",
":",
"ret_hash",
"=",
"\"\"",
"for",
"i",
"in",
"args",
":",
"ret_hash",
"+=",
"str",
"(",
"i",
")",
".",
"lower",
"(",
")",
"return",
"hash",
"(",
"ret_hash",
")"
] | 28.285714 | 17 |
def new_method_call(celf, destination, path, iface, method) :
"creates a new DBUS.MESSAGE_TYPE_METHOD_CALL message."
result = dbus.dbus_message_new_method_call \
(
(lambda : None, lambda : destination.encode())[destination != None](),
path.encode(),
(lambda ... | [
"def",
"new_method_call",
"(",
"celf",
",",
"destination",
",",
"path",
",",
"iface",
",",
"method",
")",
":",
"result",
"=",
"dbus",
".",
"dbus_message_new_method_call",
"(",
"(",
"lambda",
":",
"None",
",",
"lambda",
":",
"destination",
".",
"encode",
"(... | 38.928571 | 22.071429 |
def _path_to_objs(path, include=['*', '.*'], exclude=['.*', '_*']):
"""Turn path with opt. globbing into valid list of files respecting
include and exclude patterns.
Parameters
----------
path : str
Path to process. Can be location of a file, folder or glob.
Can be in uri-notati... | [
"def",
"_path_to_objs",
"(",
"path",
",",
"include",
"=",
"[",
"'*'",
",",
"'.*'",
"]",
",",
"exclude",
"=",
"[",
"'.*'",
",",
"'_*'",
"]",
")",
":",
"if",
"'://'",
"in",
"path",
":",
"# don't modify when path is in uri-notation, except for local files",
"if",... | 34.223529 | 24.270588 |
def create(self, model):
""" Given a model object instance create it """
signals.pre_create.send(model.__class__, model=model)
signals.pre_save.send(model.__class__, model=model)
param = self.to_pg(model)
query = """
INSERT INTO {table} ({dirty_cols})
... | [
"def",
"create",
"(",
"self",
",",
"model",
")",
":",
"signals",
".",
"pre_create",
".",
"send",
"(",
"model",
".",
"__class__",
",",
"model",
"=",
"model",
")",
"signals",
".",
"pre_save",
".",
"send",
"(",
"model",
".",
"__class__",
",",
"model",
"... | 31.076923 | 17.115385 |
def _pretrained_initializer(varname, weight_file, embedding_weight_file=None):
"""
We'll stub out all the initializers in the pretrained LM with
a function that loads the weights from the file
"""
weight_name_map = {}
for i in range(2):
for j in range(8): # if we decide to add more laye... | [
"def",
"_pretrained_initializer",
"(",
"varname",
",",
"weight_file",
",",
"embedding_weight_file",
"=",
"None",
")",
":",
"weight_name_map",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"2",
")",
":",
"for",
"j",
"in",
"range",
"(",
"8",
")",
":",
"... | 40.070175 | 17.22807 |
def post(self, request, *args, **kwargs):
"""
Returns a token identifying the user in Centrifugo.
"""
current_timestamp = "%.0f" % time.time()
user_id_str = u"{0}".format(request.user.id)
token = generate_token(settings.CENTRIFUGE_SECRET, user_id_str, "{0}".format(curren... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"current_timestamp",
"=",
"\"%.0f\"",
"%",
"time",
".",
"time",
"(",
")",
"user_id_str",
"=",
"u\"{0}\"",
".",
"format",
"(",
"request",
".",
"user",
"."... | 43.235294 | 27.588235 |
def execute(args):
"""
Executes the *index* subprogram with parsed commandline *args*.
"""
index_file = Config.instance().get_expanded("core", "index_file")
# just print the file location?
if args.location:
print(index_file)
return
# just remove the index file?
if args.... | [
"def",
"execute",
"(",
"args",
")",
":",
"index_file",
"=",
"Config",
".",
"instance",
"(",
")",
".",
"get_expanded",
"(",
"\"core\"",
",",
"\"index_file\"",
")",
"# just print the file location?",
"if",
"args",
".",
"location",
":",
"print",
"(",
"index_file"... | 31.452991 | 21.367521 |
def compute_pointwise_distances(self, other, default=None):
"""
Compute the minimal distance between each point on self and other.
Parameters
----------
other : tuple of number \
or imgaug.augmentables.kps.Keypoint \
or imgaug.augmentables.LineStr... | [
"def",
"compute_pointwise_distances",
"(",
"self",
",",
"other",
",",
"default",
"=",
"None",
")",
":",
"import",
"shapely",
".",
"geometry",
"from",
".",
"kps",
"import",
"Keypoint",
"if",
"isinstance",
"(",
"other",
",",
"Keypoint",
")",
":",
"other",
"=... | 34.214286 | 18.595238 |
def get_alerts_summary(self, **kwargs): # noqa: E501
"""Count alerts of various statuses for a customer # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_al... | [
"def",
"get_alerts_summary",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"get_alerts_summary_with_... | 42.35 | 18.7 |
def _events(self, using_url, filters=None, limit=None):
""" A long-polling method that queries Syncthing for events..
Args:
using_url (str): REST HTTP endpoint
filters (List[str]): Creates an "event group" in Syncthing to
only receive events that ... | [
"def",
"_events",
"(",
"self",
",",
"using_url",
",",
"filters",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"# coerce",
"if",
"not",
"isinstance",
"(",
"limit",
",",
"(",
"int",
",",
"NoneType",
")",
")",
":",
"limit",
"=",
"None",
"# coerce",... | 33.909091 | 20.781818 |
def item(self, infohash, prefetch=None, cache=False):
""" Fetch a single item by its info hash.
"""
return next(self.items(infohash, prefetch, cache)) | [
"def",
"item",
"(",
"self",
",",
"infohash",
",",
"prefetch",
"=",
"None",
",",
"cache",
"=",
"False",
")",
":",
"return",
"next",
"(",
"self",
".",
"items",
"(",
"infohash",
",",
"prefetch",
",",
"cache",
")",
")"
] | 42.75 | 7.75 |
def end(self) -> "GameNode":
"""Follows the main variation to the end and returns the last node."""
node = self
while node.variations:
node = node.variations[0]
return node | [
"def",
"end",
"(",
"self",
")",
"->",
"\"GameNode\"",
":",
"node",
"=",
"self",
"while",
"node",
".",
"variations",
":",
"node",
"=",
"node",
".",
"variations",
"[",
"0",
"]",
"return",
"node"
] | 26.375 | 18.375 |
def json2value(json_string, params=Null, flexible=False, leaves=False):
"""
:param json_string: THE JSON
:param params: STANDARD JSON PARAMS
:param flexible: REMOVE COMMENTS
:param leaves: ASSUME JSON KEYS ARE DOT-DELIMITED
:return: Python value
"""
if not is_text(json_string):
L... | [
"def",
"json2value",
"(",
"json_string",
",",
"params",
"=",
"Null",
",",
"flexible",
"=",
"False",
",",
"leaves",
"=",
"False",
")",
":",
"if",
"not",
"is_text",
"(",
"json_string",
")",
":",
"Log",
".",
"error",
"(",
"\"only unicode json accepted\"",
")"... | 38.971014 | 24.710145 |
def global_closeness_centrality(g, node=None, normalize=True):
"""
Calculates global closeness centrality for one or all nodes in the network.
See :func:`.node_global_closeness_centrality` for more information.
Parameters
----------
g : networkx.Graph
normalize : boolean
If True, n... | [
"def",
"global_closeness_centrality",
"(",
"g",
",",
"node",
"=",
"None",
",",
"normalize",
"=",
"True",
")",
":",
"if",
"not",
"node",
":",
"C",
"=",
"{",
"}",
"for",
"node",
"in",
"g",
".",
"nodes",
"(",
")",
":",
"C",
"[",
"node",
"]",
"=",
... | 28.648649 | 25.621622 |
def terminate(self, include_watchman=True):
"""Terminates pantsd and watchman.
N.B. This should always be called under care of the `lifecycle_lock`.
"""
super(PantsDaemon, self).terminate()
if include_watchman:
self.watchman_launcher.terminate() | [
"def",
"terminate",
"(",
"self",
",",
"include_watchman",
"=",
"True",
")",
":",
"super",
"(",
"PantsDaemon",
",",
"self",
")",
".",
"terminate",
"(",
")",
"if",
"include_watchman",
":",
"self",
".",
"watchman_launcher",
".",
"terminate",
"(",
")"
] | 33.125 | 11.5 |
def get_queryset(self):
"""
Optionally restricts the queryset by filtering against
query parameters in the URL.
"""
query_params = self.request.query_params
url_params = self.kwargs
# get queryset_filters from FilterMixin
queryset_filters = self.get_db_f... | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"query_params",
"=",
"self",
".",
"request",
".",
"query_params",
"url_params",
"=",
"self",
".",
"kwargs",
"# get queryset_filters from FilterMixin",
"queryset_filters",
"=",
"self",
".",
"get_db_filters",
"(",
"url_par... | 32.565217 | 22.304348 |
def start_api_and_rpc_workers(self):
"""Initializes eventlet and starts wait for workers to exit.
Spawns the workers returned from serve_rpc
"""
pool = eventlet.GreenPool()
quark_rpc = self.serve_rpc()
pool.spawn(quark_rpc.wait)
pool.waitall() | [
"def",
"start_api_and_rpc_workers",
"(",
"self",
")",
":",
"pool",
"=",
"eventlet",
".",
"GreenPool",
"(",
")",
"quark_rpc",
"=",
"self",
".",
"serve_rpc",
"(",
")",
"pool",
".",
"spawn",
"(",
"quark_rpc",
".",
"wait",
")",
"pool",
".",
"waitall",
"(",
... | 26.545455 | 15.181818 |
def error(msg, exit_code):
"""
Print `msg` error and exit with status `exit_code`
"""
sys.stderr.write("%s\ntry 'mongotail --help' for more information\n" % msg)
sys.stderr.flush()
exit(exit_code) | [
"def",
"error",
"(",
"msg",
",",
"exit_code",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"%s\\ntry 'mongotail --help' for more information\\n\"",
"%",
"msg",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")",
"exit",
"(",
"exit_code",
")"
] | 30.571429 | 15.142857 |
def predict(self, x):
"""
This function make forward pass through MLP (no update).
**Args:**
* `x` : input vector (1-dimensional array)
**Returns:**
* `y` : output of MLP (float or 1-diemnsional array).
Size depends on number of MLP outputs.
... | [
"def",
"predict",
"(",
"self",
",",
"x",
")",
":",
"# forward pass to hidden layers",
"for",
"l",
"in",
"self",
".",
"layers",
":",
"x",
"=",
"l",
".",
"predict",
"(",
"x",
")",
"self",
".",
"x",
"[",
"1",
":",
"]",
"=",
"x",
"# forward pass to outpu... | 26.583333 | 17.5 |
def fetch_weighted_complexity(self, recalculate_metrics=False):
"""
Calculates indicator value according to metrics weights
Uses metrics in database
args:
recalculate_metrics: If true metrics values are updated before
using weights
"""... | [
"def",
"fetch_weighted_complexity",
"(",
"self",
",",
"recalculate_metrics",
"=",
"False",
")",
":",
"# TODO: implment metrics recalculation",
"max_total",
"=",
"sum",
"(",
"[",
"self",
".",
"metrics_weights",
"[",
"metric_name",
"]",
"for",
"metric_name",
"in",
"se... | 35.575758 | 16.848485 |
def encode_arg(arg):
"""
Encode argument to be sent in a valid GuacamoleInstruction.
example:
>> arg = encode_arg('size')
>> arg == '4.size'
>> True
:param arg: arg string.
:return: str
"""
arg_utf8 = utf8(arg)
return ELEM_SEP.j... | [
"def",
"encode_arg",
"(",
"arg",
")",
":",
"arg_utf8",
"=",
"utf8",
"(",
"arg",
")",
"return",
"ELEM_SEP",
".",
"join",
"(",
"[",
"str",
"(",
"len",
"(",
"str",
"(",
"arg_utf8",
")",
")",
")",
",",
"str",
"(",
"arg_utf8",
")",
"]",
")"
] | 21.875 | 21.625 |
def iteration(self, node_status=True):
"""
Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status)
"""
self.clean_initial_status(self.available_statuses.values())
actual_status = {node: nstatus for node, nstatus in future... | [
"def",
"iteration",
"(",
"self",
",",
"node_status",
"=",
"True",
")",
":",
"self",
".",
"clean_initial_status",
"(",
"self",
".",
"available_statuses",
".",
"values",
"(",
")",
")",
"actual_status",
"=",
"{",
"node",
":",
"nstatus",
"for",
"node",
",",
... | 42.253333 | 23.8 |
def saveAs( self, filename = '' ):
"""
Saves the current document to the inputed filename. If no filename \
is supplied, then the user will be prompted to supply a filename.
:param filename | <str>
:return <bool> | success
"""
if ( not ... | [
"def",
"saveAs",
"(",
"self",
",",
"filename",
"=",
"''",
")",
":",
"if",
"(",
"not",
"(",
"filename",
"and",
"isinstance",
"(",
"filename",
",",
"basestring",
")",
")",
")",
":",
"langTypes",
"=",
"XLanguage",
".",
"pluginFileTypes",
"(",
")",
"filena... | 35.095238 | 17.761905 |
def do_pot(self):
"""
Sync the template with the python code.
"""
files_to_translate = []
log.debug("Collecting python sources for pot ...")
for source_path in self._source_paths:
for source_path in self._iter_suffix(path=source_path, suffix=".py"):
... | [
"def",
"do_pot",
"(",
"self",
")",
":",
"files_to_translate",
"=",
"[",
"]",
"log",
".",
"debug",
"(",
"\"Collecting python sources for pot ...\"",
")",
"for",
"source_path",
"in",
"self",
".",
"_source_paths",
":",
"for",
"source_path",
"in",
"self",
".",
"_i... | 53.791667 | 23.291667 |
def get_upstream_paths(self, port):
"""Retrieve a dictionary containing the full URLs of the upstream apps
:param int port: The port used by the replay and cdx servers
:return: A dictionary containing the upstream paths (replay, cdx-server, record [if enabled])
:rtype: dict[str, str]
... | [
"def",
"get_upstream_paths",
"(",
"self",
",",
"port",
")",
":",
"base_paths",
"=",
"{",
"'replay'",
":",
"self",
".",
"REPLAY_API",
"%",
"port",
",",
"'cdx-server'",
":",
"self",
".",
"CDX_API",
"%",
"port",
",",
"}",
"if",
"self",
".",
"recorder_path",... | 35.5 | 20.1875 |
def top_directory(self):
"""Return the name of the archive topmost directory."""
if self.handle:
return os.path.commonprefix(self.handle.getnames()).rstrip('/') | [
"def",
"top_directory",
"(",
"self",
")",
":",
"if",
"self",
".",
"handle",
":",
"return",
"os",
".",
"path",
".",
"commonprefix",
"(",
"self",
".",
"handle",
".",
"getnames",
"(",
")",
")",
".",
"rstrip",
"(",
"'/'",
")"
] | 46.25 | 17 |
def _new_conn(self):
"""
Return a fresh :class:`HTTPConnection`.
"""
self.num_connections += 1
log.debug("Starting new HTTP connection (%d): %s",
self.num_connections, self.host)
conn = self.ConnectionCls(host=self.host, port=self.port,
... | [
"def",
"_new_conn",
"(",
"self",
")",
":",
"self",
".",
"num_connections",
"+=",
"1",
"log",
".",
"debug",
"(",
"\"Starting new HTTP connection (%d): %s\"",
",",
"self",
".",
"num_connections",
",",
"self",
".",
"host",
")",
"conn",
"=",
"self",
".",
"Connec... | 37.833333 | 17.333333 |
def schedule_contact_downtime(self, contact, start_time, end_time, author, comment):
"""Schedule contact downtime
Format of the line that triggers function call::
SCHEDULE_CONTACT_DOWNTIME;<contact_name>;<start_time>;<end_time>;<author>;<comment>
:param contact: contact to put in downt... | [
"def",
"schedule_contact_downtime",
"(",
"self",
",",
"contact",
",",
"start_time",
",",
"end_time",
",",
"author",
",",
"comment",
")",
":",
"data",
"=",
"{",
"'ref'",
":",
"contact",
".",
"uuid",
",",
"'start_time'",
":",
"start_time",
",",
"'end_time'",
... | 40.826087 | 17.043478 |
def common(self, other):
"""
Return two objects with the same dimensions if they lie in the same orthogonal plane.
::
>>> l = Location(pop=1, snap=2)
>>> m = Location(crackle=1, snap=3)
>>> l.common(m)
(<Location snap:2 >, <Location snap:3 >)
... | [
"def",
"common",
"(",
"self",
",",
"other",
")",
":",
"selfDim",
"=",
"set",
"(",
"self",
".",
"keys",
"(",
")",
")",
"otherDim",
"=",
"set",
"(",
"other",
".",
"keys",
"(",
")",
")",
"dims",
"=",
"selfDim",
"|",
"otherDim",
"newSelf",
"=",
"None... | 34.419355 | 11.709677 |
def extend(self, tasks):
'''Add tasks to this particular shovel'''
self._tasks.extend(tasks)
for task in tasks:
# We'll now go through all of our tasks and group them into
# sub-shovels
current = self.map
modules = task.fullname.split('.')
... | [
"def",
"extend",
"(",
"self",
",",
"tasks",
")",
":",
"self",
".",
"_tasks",
".",
"extend",
"(",
"tasks",
")",
"for",
"task",
"in",
"tasks",
":",
"# We'll now go through all of our tasks and group them into",
"# sub-shovels",
"current",
"=",
"self",
".",
"map",
... | 41.875 | 12.958333 |
def set(self, client_id, code, request, *args, **kwargs):
"""Creates Grant object with the given params
:param client_id: ID of the client
:param code:
:param request: OAuthlib request object
"""
expires = datetime.utcnow() + timedelta(seconds=100)
grant = self.m... | [
"def",
"set",
"(",
"self",
",",
"client_id",
",",
"code",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"expires",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"100",
")",
"grant",
"=",
"... | 32.421053 | 13.263158 |
def runGenomeSGE(bfile, freqFile, nbJob, outPrefix, options):
"""Runs the genome command from plink, on SGE.
:param bfile: the prefix of the input file.
:param freqFile: the name of the frequency file (from Plink).
:param nbJob: the number of jobs to launch.
:param outPrefix: the prefix of all the ... | [
"def",
"runGenomeSGE",
"(",
"bfile",
",",
"freqFile",
",",
"nbJob",
",",
"outPrefix",
",",
"options",
")",
":",
"# Add the environment variable for DRMAA package",
"if",
"\"DRMAA_LIBRARY_PATH\"",
"not",
"in",
"os",
".",
"environ",
":",
"msg",
"=",
"\"could not load ... | 33.819277 | 18.819277 |
def get_all_context(self):
"""
Retrieves Plan and Pricing for current order creation
"""
self.plan_pricing = get_object_or_404(PlanPricing.objects.all().select_related('plan', 'pricing'),
Q(pk=self.kwargs['pk']) & Q(plan__available=True) & (
... | [
"def",
"get_all_context",
"(",
"self",
")",
":",
"self",
".",
"plan_pricing",
"=",
"get_object_or_404",
"(",
"PlanPricing",
".",
"objects",
".",
"all",
"(",
")",
".",
"select_related",
"(",
"'plan'",
",",
"'pricing'",
")",
",",
"Q",
"(",
"pk",
"=",
"self... | 51.352941 | 32.294118 |
def is_downloadable(self, response):
'''
Checks whether the response object is a html page
or a likely downloadable file.
Intended to detect error pages or prompts
such as kaggle's competition rules acceptance prompt.
Returns True if the response is a html page. False ot... | [
"def",
"is_downloadable",
"(",
"self",
",",
"response",
")",
":",
"content_type",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"'Content-Type'",
",",
"''",
")",
"content_disp",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"'Content-Disposition'",
"... | 38.578947 | 21.842105 |
def fourier_ratios(phase_shifted_coeffs):
r"""
Returns the :math:`R_{j1}` and :math:`\phi_{j1}` values for the given
phase-shifted coefficients.
.. math::
R_{j1} = A_j / A_1
.. math::
\phi_{j1} = \phi_j - j \phi_1
**Parameters**
phase... | [
"def",
"fourier_ratios",
"(",
"phase_shifted_coeffs",
")",
":",
"n_coeff",
"=",
"phase_shifted_coeffs",
".",
"size",
"# n_coeff = 2*degree + 1 => degree = (n_coeff-1)/2",
"degree",
"=",
"(",
"n_coeff",
"-",
"1",
")",
"/",
"2",
"amplitudes",
"=",
"phase_shifted_coeffs",
... | 29.867925 | 20.075472 |
def extend_back(self, dag, edge_map=None):
"""Add `dag` at the end of `self`, using `edge_map`.
"""
edge_map = edge_map or {}
for qreg in dag.qregs.values():
if qreg.name not in self.qregs:
self.add_qreg(QuantumRegister(qreg.size, qreg.name))
edge_... | [
"def",
"extend_back",
"(",
"self",
",",
"dag",
",",
"edge_map",
"=",
"None",
")",
":",
"edge_map",
"=",
"edge_map",
"or",
"{",
"}",
"for",
"qreg",
"in",
"dag",
".",
"qregs",
".",
"values",
"(",
")",
":",
"if",
"qreg",
".",
"name",
"not",
"in",
"s... | 43.733333 | 16.2 |
def from_ordered_sequence(cls, iseq):
"""
Return the root of a balanced binary search tree populated with the
values in iterable *iseq*.
"""
seq = list(iseq)
# optimize for usually all fits by making longest first
bst = cls(seq.pop())
bst._insert_from_orde... | [
"def",
"from_ordered_sequence",
"(",
"cls",
",",
"iseq",
")",
":",
"seq",
"=",
"list",
"(",
"iseq",
")",
"# optimize for usually all fits by making longest first",
"bst",
"=",
"cls",
"(",
"seq",
".",
"pop",
"(",
")",
")",
"bst",
".",
"_insert_from_ordered_sequen... | 34.7 | 12.3 |
def set_unicode(self, quoted_text=False):
"""Converts the context's ``value`` to a sequence of unicode code points for holding text tokens, indicating
whether the text is quoted.
"""
if isinstance(self.value, CodePointArray):
assert self.quoted_text == quoted_text
... | [
"def",
"set_unicode",
"(",
"self",
",",
"quoted_text",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"value",
",",
"CodePointArray",
")",
":",
"assert",
"self",
".",
"quoted_text",
"==",
"quoted_text",
"return",
"self",
"self",
".",
"value"... | 42.090909 | 7.272727 |
def ppj(json_data):
"""ppj
:param json_data: dictionary to print
"""
return str(json.dumps(
json_data,
sort_keys=True,
indent=4,
separators=(',', ': '))) | [
"def",
"ppj",
"(",
"json_data",
")",
":",
"return",
"str",
"(",
"json",
".",
"dumps",
"(",
"json_data",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
")"
] | 22.5 | 11.4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.