text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def setup_fake_forward_run(pst,new_pst_name,org_cwd='.',bak_suffix="._bak",new_cwd='.'):
"""setup a fake forward run for a pst. The fake
forward run simply copies existing backup versions of
model output files to the outfiles pest(pp) is looking
for. This is really a development option for debugging
... | [
"def",
"setup_fake_forward_run",
"(",
"pst",
",",
"new_pst_name",
",",
"org_cwd",
"=",
"'.'",
",",
"bak_suffix",
"=",
"\"._bak\"",
",",
"new_cwd",
"=",
"'.'",
")",
":",
"if",
"new_cwd",
"!=",
"org_cwd",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"("... | 32.686047 | 0.008287 |
def cmd(tgt,
fun,
arg=(),
timeout=None,
tgt_type='glob',
ret='',
kwarg=None,
ssh=False,
**kwargs):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``... | [
"def",
"cmd",
"(",
"tgt",
",",
"fun",
",",
"arg",
"=",
"(",
")",
",",
"timeout",
"=",
"None",
",",
"tgt_type",
"=",
"'glob'",
",",
"ret",
"=",
"''",
",",
"kwarg",
"=",
"None",
",",
"ssh",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"cfgf... | 29.854167 | 0.001351 |
def role_delete(role_id=None, name=None, profile=None,
**connection_args):
'''
Delete a role (keystone role-delete)
CLI Examples:
.. code-block:: bash
salt '*' keystone.role_delete c965f79c4f864eaaa9c3b41904e67082
salt '*' keystone.role_delete role_id=c965f79c4f864eaa... | [
"def",
"role_delete",
"(",
"role_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"*",
"*",
"connection_args",
")",
":",
"kstone",
"=",
"auth",
"(",
"profile",
",",
"*",
"*",
"connection_args",
")",
"if",
"name",
":",
"fo... | 26.129032 | 0.00119 |
def jstemplate(parser, token):
"""Templatetag to handle any of the Mustache-based templates.
Replaces ``[[[`` and ``]]]`` with ``{{{`` and ``}}}``,
``[[`` and ``]]`` with ``{{`` and ``}}`` and
``[%`` and ``%]`` with ``{%`` and ``%}`` to avoid conflicts
with Django's template engine when using any ... | [
"def",
"jstemplate",
"(",
"parser",
",",
"token",
")",
":",
"nodelist",
"=",
"parser",
".",
"parse",
"(",
"(",
"'endjstemplate'",
",",
")",
")",
"parser",
".",
"delete_first_token",
"(",
")",
"return",
"JSTemplateNode",
"(",
"nodelist",
")"
] | 40 | 0.002037 |
def cursor_up(self, stats):
"""Set the cursor to position N-1 in the list."""
if 0 <= self.cursor_position - 1:
self.cursor_position -= 1
else:
if self._current_page - 1 < 0 :
self._current_page = self._page_max - 1
self.cursor_position = (... | [
"def",
"cursor_up",
"(",
"self",
",",
"stats",
")",
":",
"if",
"0",
"<=",
"self",
".",
"cursor_position",
"-",
"1",
":",
"self",
".",
"cursor_position",
"-=",
"1",
"else",
":",
"if",
"self",
".",
"_current_page",
"-",
"1",
"<",
"0",
":",
"self",
".... | 42.818182 | 0.008316 |
def beautify_date(inasafe_time, feature, parent):
"""Given an InaSAFE analysis time, it will convert it to a date with
year-month-date format.
For instance:
* beautify_date( @start_datetime ) -> will convert datetime provided by
qgis_variable.
"""
_ = feature, parent # NOQA
datet... | [
"def",
"beautify_date",
"(",
"inasafe_time",
",",
"feature",
",",
"parent",
")",
":",
"_",
"=",
"feature",
",",
"parent",
"# NOQA",
"datetime_object",
"=",
"parse",
"(",
"inasafe_time",
")",
"date",
"=",
"datetime_object",
".",
"strftime",
"(",
"'%Y-%m-%d'",
... | 33.75 | 0.002404 |
def _read_range(self, start, end=0):
"""
Read a range of bytes in stream.
Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.
Returns:
bytes: number of bytes read
"""
if star... | [
"def",
"_read_range",
"(",
"self",
",",
"start",
",",
"end",
"=",
"0",
")",
":",
"if",
"start",
">=",
"self",
".",
"_size",
":",
"# EOF. Do not detect using 416 (Out of range) error, 200 returned.",
"return",
"bytes",
"(",
")",
"# Get object bytes range",
"with",
... | 31.52 | 0.002463 |
def run(self) -> None:
"""
Read lines and put them on the queue.
"""
fd = self._fd
encoding = self._encoding
line_terminators = self._line_terminators
queue = self._queue
buf = ""
while True:
try:
c = fd.read(1).decode(e... | [
"def",
"run",
"(",
"self",
")",
"->",
"None",
":",
"fd",
"=",
"self",
".",
"_fd",
"encoding",
"=",
"self",
".",
"_encoding",
"line_terminators",
"=",
"self",
".",
"_line_terminators",
"queue",
"=",
"self",
".",
"_queue",
"buf",
"=",
"\"\"",
"while",
"T... | 34.090909 | 0.001729 |
def request_timestamp(self):
"""
The timestamp of the request in ISO8601 YYYYMMDD'T'HHMMSS'Z' format.
If this is not available in the query parameters or headers, or the
value is not a valid format for AWS SigV4, an AttributeError exception
is raised.
"""
amz_dat... | [
"def",
"request_timestamp",
"(",
"self",
")",
":",
"amz_date",
"=",
"self",
".",
"query_parameters",
".",
"get",
"(",
"_x_amz_date",
")",
"if",
"amz_date",
"is",
"not",
"None",
":",
"amz_date",
"=",
"amz_date",
"[",
"0",
"]",
"else",
":",
"amz_date",
"="... | 42.741935 | 0.002214 |
def _translate_limit(self, len_, start, num):
"""
Translate limit to valid bounds.
"""
if start > len_ or num <= 0:
return 0, 0
return min(start, len_), num | [
"def",
"_translate_limit",
"(",
"self",
",",
"len_",
",",
"start",
",",
"num",
")",
":",
"if",
"start",
">",
"len_",
"or",
"num",
"<=",
"0",
":",
"return",
"0",
",",
"0",
"return",
"min",
"(",
"start",
",",
"len_",
")",
",",
"num"
] | 28.857143 | 0.009615 |
def _backup_file(path):
"""
Backup a file but never overwrite an existing backup file
"""
backup_base = '/var/local/woven-backup'
backup_path = ''.join([backup_base,path])
if not exists(backup_path):
directory = ''.join([backup_base,os.path.split(path)[0]])
sudo('mkdir -p %s'% di... | [
"def",
"_backup_file",
"(",
"path",
")",
":",
"backup_base",
"=",
"'/var/local/woven-backup'",
"backup_path",
"=",
"''",
".",
"join",
"(",
"[",
"backup_base",
",",
"path",
"]",
")",
"if",
"not",
"exists",
"(",
"backup_path",
")",
":",
"directory",
"=",
"''... | 36.4 | 0.016086 |
def hash_data(data, hasher=NoParam, base=NoParam, types=False,
hashlen=NoParam, convert=False):
"""
Get a unique hash depending on the state of the data.
Args:
data (object):
Any sort of loosely organized data
hasher (str or HASHER):
Hash algorithm fro... | [
"def",
"hash_data",
"(",
"data",
",",
"hasher",
"=",
"NoParam",
",",
"base",
"=",
"NoParam",
",",
"types",
"=",
"False",
",",
"hashlen",
"=",
"NoParam",
",",
"convert",
"=",
"False",
")",
":",
"if",
"convert",
"and",
"isinstance",
"(",
"data",
",",
"... | 35.737705 | 0.001339 |
def transformFromNative(obj):
"""
Replace the Name in obj.value with a string.
"""
obj.isNative = False
obj.value = serializeFields(obj.value, NAME_ORDER)
return obj | [
"def",
"transformFromNative",
"(",
"obj",
")",
":",
"obj",
".",
"isNative",
"=",
"False",
"obj",
".",
"value",
"=",
"serializeFields",
"(",
"obj",
".",
"value",
",",
"NAME_ORDER",
")",
"return",
"obj"
] | 29.571429 | 0.00939 |
def set_dict_options(self, options):
"""for dictionary-like inputs (as object in Javascript)
options must be in python dictionary format
"""
if isinstance(options, dict):
for key, option_data in options.items():
self.set_options(key, option_data)
else:... | [
"def",
"set_dict_options",
"(",
"self",
",",
"options",
")",
":",
"if",
"isinstance",
"(",
"options",
",",
"dict",
")",
":",
"for",
"key",
",",
"option_data",
"in",
"options",
".",
"items",
"(",
")",
":",
"self",
".",
"set_options",
"(",
"key",
",",
... | 46.333333 | 0.009412 |
def get_return_code(self, stderr=STDOUT):
"""Executes a simple external command and return its exit status
:param stderr: where to put stderr
:return: return code of command
"""
args = shlex.split(self.cmd)
return call(args, stdout=PIPE, stderr=stderr) | [
"def",
"get_return_code",
"(",
"self",
",",
"stderr",
"=",
"STDOUT",
")",
":",
"args",
"=",
"shlex",
".",
"split",
"(",
"self",
".",
"cmd",
")",
"return",
"call",
"(",
"args",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"stderr",
")"
] | 37.75 | 0.009709 |
def write_ensemble(ensemble, options):
"""
Prints out the ensemble composition at each size
"""
# set output file name
size = len(ensemble)
filename = '%s_%s_queries.csv' % (options.outname, size)
file = os.path.join(os.getcwd(), filename)
f = open(file, 'w')
out = ', '.join(ensemble)
... | [
"def",
"write_ensemble",
"(",
"ensemble",
",",
"options",
")",
":",
"# set output file name",
"size",
"=",
"len",
"(",
"ensemble",
")",
"filename",
"=",
"'%s_%s_queries.csv'",
"%",
"(",
"options",
".",
"outname",
",",
"size",
")",
"file",
"=",
"os",
".",
"... | 19.705882 | 0.014245 |
def get_safari_navigation_bar_height(self):
"""Get the height of Safari navigation bar
:returns: height of navigation bar
"""
status_bar_height = 0
if self.driver_wrapper.is_ios_test() and self.driver_wrapper.is_web_test():
# ios 7.1, 8.3
status_bar_heigh... | [
"def",
"get_safari_navigation_bar_height",
"(",
"self",
")",
":",
"status_bar_height",
"=",
"0",
"if",
"self",
".",
"driver_wrapper",
".",
"is_ios_test",
"(",
")",
"and",
"self",
".",
"driver_wrapper",
".",
"is_web_test",
"(",
")",
":",
"# ios 7.1, 8.3",
"status... | 35 | 0.008357 |
def main(in_base, out_base, compiled_files, source_files, outfile=None,
showasm=None, showast=False, do_verify=False,
showgrammar=False, raise_on_error=False,
do_linemaps=False, do_fragments=False):
"""
in_base base directory for input files
out_base base directory for output file... | [
"def",
"main",
"(",
"in_base",
",",
"out_base",
",",
"compiled_files",
",",
"source_files",
",",
"outfile",
"=",
"None",
",",
"showasm",
"=",
"None",
",",
"showast",
"=",
"False",
",",
"do_verify",
"=",
"False",
",",
"showgrammar",
"=",
"False",
",",
"ra... | 41.189944 | 0.001722 |
def _get_args_and_errors(self, minuit=None, args=None, errors=None):
"""
consistent algorithm to get argument and errors
1) get it from minuit if minuit is available
2) if not get it from args and errors
2.1) if args is dict parse it.
3) if all else fail get it from self.last_arg
"""
ret... | [
"def",
"_get_args_and_errors",
"(",
"self",
",",
"minuit",
"=",
"None",
",",
"args",
"=",
"None",
",",
"errors",
"=",
"None",
")",
":",
"ret_arg",
"=",
"None",
"ret_error",
"=",
"None",
"if",
"minuit",
"is",
"not",
"None",
":",
"# case 1",
"ret_arg",
"... | 28.214286 | 0.001224 |
def increase_index_ordered_list(header_type_count: dict,
header_type_prev: int,
header_type_curr: int,
parser: str = 'github'):
r"""Compute the current index for ordered list table of contents.
:parameter header_typ... | [
"def",
"increase_index_ordered_list",
"(",
"header_type_count",
":",
"dict",
",",
"header_type_prev",
":",
"int",
",",
"header_type_curr",
":",
"int",
",",
"parser",
":",
"str",
"=",
"'github'",
")",
":",
"# header_type_prev might be 0 while header_type_curr can't.",
"a... | 42.459459 | 0.000622 |
def euclidean(a, b):
"Returns euclidean distance between a and b"
return np.linalg.norm(np.subtract(a, b)) | [
"def",
"euclidean",
"(",
"a",
",",
"b",
")",
":",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"np",
".",
"subtract",
"(",
"a",
",",
"b",
")",
")"
] | 37.333333 | 0.008772 |
def _dump_multipolygon(obj, decimals):
"""
Dump a GeoJSON-like MultiPolygon object to WKT.
Input parameters and return value are the MULTIPOLYGON equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
mp = 'MULTIPOLYGON (%s)'
polys = (
# join the polygons in the mul... | [
"def",
"_dump_multipolygon",
"(",
"obj",
",",
"decimals",
")",
":",
"coords",
"=",
"obj",
"[",
"'coordinates'",
"]",
"mp",
"=",
"'MULTIPOLYGON (%s)'",
"polys",
"=",
"(",
"# join the polygons in the multipolygon",
"', '",
".",
"join",
"(",
"# join the rings in a poly... | 30.111111 | 0.001192 |
def make_desktop_entry(d):
"""
Create a desktop entry that conforms to the format of the Desktop Entry
Specification by freedesktop.org. See:
http://freedesktop.org/Standards/desktop-entry-spec
These should work for both KDE and Gnome2
An entry is a .desktop file that includes the appl... | [
"def",
"make_desktop_entry",
"(",
"d",
")",
":",
"assert",
"d",
"[",
"'path'",
"]",
".",
"endswith",
"(",
"'.desktop'",
")",
"# default values",
"d",
".",
"setdefault",
"(",
"'comment'",
",",
"''",
")",
"d",
".",
"setdefault",
"(",
"'icon'",
",",
"''",
... | 25.488372 | 0.000879 |
def _get_package_data():
"""Iterate over the `init` dir for directories and returns
all files within them.
Only files within `binaries` and `templates` will be added.
"""
from os import listdir as ls
from os.path import join as jn
x = 'init'
b = jn('serv', x)
dr = ['binaries', 'tem... | [
"def",
"_get_package_data",
"(",
")",
":",
"from",
"os",
"import",
"listdir",
"as",
"ls",
"from",
"os",
".",
"path",
"import",
"join",
"as",
"jn",
"x",
"=",
"'init'",
"b",
"=",
"jn",
"(",
"'serv'",
",",
"x",
")",
"dr",
"=",
"[",
"'binaries'",
",",
... | 29.923077 | 0.002494 |
def stop(self):
"""Stop the sensor.
"""
if not self._running:
return
self._weight_subscriber.unregister()
self._running = False | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_running",
":",
"return",
"self",
".",
"_weight_subscriber",
".",
"unregister",
"(",
")",
"self",
".",
"_running",
"=",
"False"
] | 24.714286 | 0.011173 |
def engine(self):
"""Return Render Engine."""
return self.backend({
'APP_DIRS': True,
'DIRS': [str(ROOT / self.backend.app_dirname)],
'NAME': 'djangoforms',
'OPTIONS': {},
}) | [
"def",
"engine",
"(",
"self",
")",
":",
"return",
"self",
".",
"backend",
"(",
"{",
"'APP_DIRS'",
":",
"True",
",",
"'DIRS'",
":",
"[",
"str",
"(",
"ROOT",
"/",
"self",
".",
"backend",
".",
"app_dirname",
")",
"]",
",",
"'NAME'",
":",
"'djangoforms'"... | 29.875 | 0.00813 |
def update(self, session, title=None, bulletin=None, desc=None):
'''taobao.shop.remainshowcase.get 获取卖家店铺剩余橱窗数量
目前只支持标题、公告和描述的更新'''
request = TOPRequest('taobao.shop.remainshowcase.get')
if title!=None: request['title'] = title
if bulletin!=None: request['bulletin'] = bu... | [
"def",
"update",
"(",
"self",
",",
"session",
",",
"title",
"=",
"None",
",",
"bulletin",
"=",
"None",
",",
"desc",
"=",
"None",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.shop.remainshowcase.get'",
")",
"if",
"title",
"!=",
"None",
":",
"requ... | 44.3 | 0.026549 |
def is_device_mounted(device):
'''Given a device path, return True if that device is mounted, and False
if it isn't.
:param device: str: Full path of the device to check.
:returns: boolean: True if the path represents a mounted device, False if
it doesn't.
'''
try:
out = check_o... | [
"def",
"is_device_mounted",
"(",
"device",
")",
":",
"try",
":",
"out",
"=",
"check_output",
"(",
"[",
"'lsblk'",
",",
"'-P'",
",",
"device",
"]",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
"except",
"Exception",
":",
"return",
"False",
"return",
"bool",
... | 34.538462 | 0.002169 |
def read_int(self):
"""Reads an integer from the packet"""
format = '!I'
length = struct.calcsize(format)
info = struct.unpack(format,
self.data[self.offset:self.offset + length])
self.offset += length
return info[0] | [
"def",
"read_int",
"(",
"self",
")",
":",
"format",
"=",
"'!I'",
"length",
"=",
"struct",
".",
"calcsize",
"(",
"format",
")",
"info",
"=",
"struct",
".",
"unpack",
"(",
"format",
",",
"self",
".",
"data",
"[",
"self",
".",
"offset",
":",
"self",
"... | 34.125 | 0.010714 |
def calc_acceleration_bca(jackknife_replicates):
"""
Calculate the acceleration constant for the Bias Corrected and Accelerated
(BCa) bootstrap confidence intervals.
Parameters
----------
jackknife_replicates : 2D ndarray.
Each row should correspond to a different jackknife parameter sa... | [
"def",
"calc_acceleration_bca",
"(",
"jackknife_replicates",
")",
":",
"# Get the mean of the bootstrapped statistics.",
"jackknife_mean",
"=",
"jackknife_replicates",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"[",
"None",
",",
":",
"]",
"# Calculate the differences betwee... | 41.25641 | 0.000607 |
def getRaDecs(self, mods):
"""Internal function converting cartesian coords to
ra dec"""
raDecOut = np.empty( (len(mods), 5))
raDecOut[:,0:3] = mods[:,0:3]
for i, row in enumerate(mods):
raDecOut[i, 3:5] = r.raDecFromVec(row[3:6])
return raDecOut | [
"def",
"getRaDecs",
"(",
"self",
",",
"mods",
")",
":",
"raDecOut",
"=",
"np",
".",
"empty",
"(",
"(",
"len",
"(",
"mods",
")",
",",
"5",
")",
")",
"raDecOut",
"[",
":",
",",
"0",
":",
"3",
"]",
"=",
"mods",
"[",
":",
",",
"0",
":",
"3",
... | 33.222222 | 0.016287 |
def camel_case(arg, capitalize=None):
"""Converts given text with whitespaces between words
into equivalent camel-cased one.
:param capitalize: Whether result will have first letter upper case (True),
lower case (False), or left as is (None, default).
:return: String turned into... | [
"def",
"camel_case",
"(",
"arg",
",",
"capitalize",
"=",
"None",
")",
":",
"ensure_string",
"(",
"arg",
")",
"if",
"not",
"arg",
":",
"return",
"arg",
"words",
"=",
"split",
"(",
"arg",
")",
"first_word",
"=",
"words",
"[",
"0",
"]",
"if",
"len",
"... | 31.8 | 0.001221 |
def parse_options():
"""
parse_options() -> opts, args
Parse any command-line options given returning both
the parsed options and arguments.
"""
parser = optparse.OptionParser(usage=USAGE, version=VERSION)
parser.add_option("-o", "--ontology",
action="store", type="string", default="", dest="ontology",
... | [
"def",
"parse_options",
"(",
")",
":",
"parser",
"=",
"optparse",
".",
"OptionParser",
"(",
"usage",
"=",
"USAGE",
",",
"version",
"=",
"VERSION",
")",
"parser",
".",
"add_option",
"(",
"\"-o\"",
",",
"\"--ontology\"",
",",
"action",
"=",
"\"store\"",
",",... | 23.190476 | 0.033531 |
def edit(parent, profile):
"""
Edits the given profile.
:param parent | <QWidget>
profile | <projexui.widgets.xviewwidget.XViewProfile>
:return <bool>
"""
dlg = XViewProfileDialog(parent)
dlg.setProfile(pro... | [
"def",
"edit",
"(",
"parent",
",",
"profile",
")",
":",
"dlg",
"=",
"XViewProfileDialog",
"(",
"parent",
")",
"dlg",
".",
"setProfile",
"(",
"profile",
")",
"if",
"(",
"dlg",
".",
"exec_",
"(",
")",
")",
":",
"return",
"True",
"return",
"False"
] | 27.714286 | 0.014963 |
def key_dict( from_dict ):
"""Returns dict from_dict['unicode_save_field'] = 'original key with unicode' """
new_dict = {}
old2new = {}
new2old = {}
for key in from_dict:
k = normalizeUnicode(key,'identifier')
if k != key:
i = ''
while new_dict.has_key("%s%s" % (k,i) ):
if not i:
i = 1
else:... | [
"def",
"key_dict",
"(",
"from_dict",
")",
":",
"new_dict",
"=",
"{",
"}",
"old2new",
"=",
"{",
"}",
"new2old",
"=",
"{",
"}",
"for",
"key",
"in",
"from_dict",
":",
"k",
"=",
"normalizeUnicode",
"(",
"key",
",",
"'identifier'",
")",
"if",
"k",
"!=",
... | 24.263158 | 0.056367 |
def availability_set_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get a dictionary representing an availability set's properties.
:param name: The availability set to get.
:param resource_group: The resource group name assigned to the
availability set.
CLI Exam... | [
"def",
"availability_set_get",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"compconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'compute'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"av_set",
"=",
"compconn",
".... | 26.645161 | 0.001168 |
def pipe_rename(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that renames or copies fields in the input source.
Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipe2py.modules pipe like object (iterable of items)
conf : {
'RULE': [
... | [
"def",
"pipe_rename",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"splits",
"=",
"get_splits",
"(",
"_INPUT",
",",
"conf",
"[",
"'RULE'",
"]",
",",
"*",
"*",
"cdicts",
"(",
... | 27.888889 | 0.001284 |
def get_client(self):
"""Get cache client.
"""
backend_class = import_string(current_app.config.get('CACHE_BACKEND'))
backend = backend_class(**current_app.config.get('CACHE_BACKEND_OPTIONS'))
return backend | [
"def",
"get_client",
"(",
"self",
")",
":",
"backend_class",
"=",
"import_string",
"(",
"current_app",
".",
"config",
".",
"get",
"(",
"'CACHE_BACKEND'",
")",
")",
"backend",
"=",
"backend_class",
"(",
"*",
"*",
"current_app",
".",
"config",
".",
"get",
"(... | 40.333333 | 0.012146 |
def get_top_pathologies(graph, n: Optional[int] = 15) -> List[Tuple[BaseEntity, int]]:
"""Get the top highest relationship-having edges in the graph by BEL.
:param pybel.BELGraph graph: A BEL graph
:param n: The number of top connected pathologies to return. If None, returns all nodes
"""
return co... | [
"def",
"get_top_pathologies",
"(",
"graph",
",",
"n",
":",
"Optional",
"[",
"int",
"]",
"=",
"15",
")",
"->",
"List",
"[",
"Tuple",
"[",
"BaseEntity",
",",
"int",
"]",
"]",
":",
"return",
"count_pathologies",
"(",
"graph",
")",
".",
"most_common",
"(",... | 50.142857 | 0.008403 |
def transactional(ignore_redirects=True):
'''
If utilizing the :mod:`pecan.hooks` ``TransactionHook``, allows you
to flag a controller method or class as being wrapped in a transaction,
regardless of HTTP method.
:param ignore_redirects: Indicates if the hook should ignore redirects
... | [
"def",
"transactional",
"(",
"ignore_redirects",
"=",
"True",
")",
":",
"def",
"deco",
"(",
"f",
")",
":",
"if",
"isclass",
"(",
"f",
")",
":",
"for",
"meth",
"in",
"[",
"m",
"[",
"1",
"]",
"for",
"m",
"in",
"getmembers",
"(",
"f",
")",
"if",
"... | 36.241379 | 0.000927 |
def get_addon_module_name(addonxml_filename):
'''Attempts to extract a module name for the given addon's addon.xml file.
Looks for the 'xbmc.python.pluginsource' extension node and returns the
addon's filename without the .py suffix.
'''
try:
xml = ET.parse(addonxml_filename).getroot()
e... | [
"def",
"get_addon_module_name",
"(",
"addonxml_filename",
")",
":",
"try",
":",
"xml",
"=",
"ET",
".",
"parse",
"(",
"addonxml_filename",
")",
".",
"getroot",
"(",
")",
"except",
"IOError",
":",
"sys",
".",
"exit",
"(",
"'Cannot find an addon.xml file in the cur... | 41.842105 | 0.00123 |
def get_table_fields(self, db_table):
"""
Gets table fields from schema.
"""
db_table_desc = self.introspection.get_table_description(self.cursor, db_table)
return [t[0] for t in db_table_desc] | [
"def",
"get_table_fields",
"(",
"self",
",",
"db_table",
")",
":",
"db_table_desc",
"=",
"self",
".",
"introspection",
".",
"get_table_description",
"(",
"self",
".",
"cursor",
",",
"db_table",
")",
"return",
"[",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"d... | 38 | 0.012876 |
def get_file_contents(path):
"""
Get the contents of a file.
"""
with open(path, 'rb') as fp:
# mitogen.core.Blob() is a bytes subclass with a repr() that returns a
# summary of the blob, rather than the raw blob data. This makes
# logging output *much* nicer. Unlike most custom ... | [
"def",
"get_file_contents",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"fp",
":",
"# mitogen.core.Blob() is a bytes subclass with a repr() that returns a",
"# summary of the blob, rather than the raw blob data. This makes",
"# logging output *much... | 39.6 | 0.002469 |
def get_device_info_for_agent(self, context, hosting_device_db):
"""Returns information about <hosting_device> needed by config agent.
Convenience function that service plugins can use to populate
their resources with information about the device hosting their
logical resource.... | [
"def",
"get_device_info_for_agent",
"(",
"self",
",",
"context",
",",
"hosting_device_db",
")",
":",
"template",
"=",
"hosting_device_db",
".",
"template",
"mgmt_port",
"=",
"hosting_device_db",
".",
"management_port",
"mgmt_ip",
"=",
"(",
"mgmt_port",
"[",
"'fixed_... | 52.041667 | 0.001572 |
def parse_individual(self, individual):
"""Converts a deap individual into a full list of parameters.
Parameters
----------
individual: deap individual from optimization
Details vary according to type of optimization, but
parameters within deap individual are alwa... | [
"def",
"parse_individual",
"(",
"self",
",",
"individual",
")",
":",
"scaled_ind",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"_params",
"[",
"'value_means'",
"]",
")",
")",
":",
"scaled_ind",
".",
"append",
"(",
"self",
... | 42.32 | 0.001848 |
def mmGetMetricStabilityConfusion(self):
"""
For each iteration that doesn't follow a reset, looks at every other
iteration for the same world that doesn't follow a reset, and computes the
number of bits that show up in one or the other set of active cells for
that iteration, but not both. This metr... | [
"def",
"mmGetMetricStabilityConfusion",
"(",
"self",
")",
":",
"self",
".",
"_mmComputeSequenceRepresentationData",
"(",
")",
"numbers",
"=",
"self",
".",
"_mmData",
"[",
"\"stabilityConfusion\"",
"]",
"return",
"Metric",
"(",
"self",
",",
"\"stability confusion\"",
... | 43.615385 | 0.001727 |
def _get_stdout(stderr=False):
"""
This utility function contains the logic to determine what streams to use
by default for standard out/err.
Typically this will just return `sys.stdout`, but it contains additional
logic for use in IPython on Windows to determine the correct stream to use
(usua... | [
"def",
"_get_stdout",
"(",
"stderr",
"=",
"False",
")",
":",
"if",
"stderr",
":",
"stream",
"=",
"'stderr'",
"else",
":",
"stream",
"=",
"'stdout'",
"sys_stream",
"=",
"getattr",
"(",
"sys",
",",
"stream",
")",
"if",
"IPythonIOStream",
"is",
"None",
":",... | 29.551724 | 0.00113 |
def list_tab(user):
'''
Return the contents of the specified user's incrontab
CLI Example:
.. code-block:: bash
salt '*' incron.list_tab root
'''
if user == 'system':
data = raw_system_incron()
else:
data = raw_incron(user)
log.debug('incron user data %s', ... | [
"def",
"list_tab",
"(",
"user",
")",
":",
"if",
"user",
"==",
"'system'",
":",
"data",
"=",
"raw_system_incron",
"(",
")",
"else",
":",
"data",
"=",
"raw_incron",
"(",
"user",
")",
"log",
".",
"debug",
"(",
"'incron user data %s'",
",",
"data",
")",
"r... | 26.794872 | 0.000923 |
def convert_models_for_lang(language):
"""Convert old SingleByteCharSetModels for the given language"""
# Validate language
language = language.title()
lang_metadata = LANGUAGES.get(language)
if not lang_metadata:
raise ValueError('Unknown language: {}. If you are adding a model for a'
... | [
"def",
"convert_models_for_lang",
"(",
"language",
")",
":",
"# Validate language",
"language",
"=",
"language",
".",
"title",
"(",
")",
"lang_metadata",
"=",
"LANGUAGES",
".",
"get",
"(",
"language",
")",
"if",
"not",
"lang_metadata",
":",
"raise",
"ValueError"... | 47.292453 | 0.001758 |
def build_java_docs(app):
"""build java docs and then move the outdir"""
java_path = app.builder.srcdir + '/../scala-package'
java_doc_sources = 'find . -type f -name "*.scala" | egrep \"\.\/core|\.\/infer\" | egrep \"\/javaapi\" | egrep -v \"Suite\"'
java_doc_classpath = ':'.join([
'`find nativ... | [
"def",
"build_java_docs",
"(",
"app",
")",
":",
"java_path",
"=",
"app",
".",
"builder",
".",
"srcdir",
"+",
"'/../scala-package'",
"java_doc_sources",
"=",
"'find . -type f -name \"*.scala\" | egrep \\\"\\.\\/core|\\.\\/infer\\\" | egrep \\\"\\/javaapi\\\" | egrep -v \\\"Suite\\\"... | 55.611111 | 0.008841 |
def _options(self, **kwargs):
"""
Formats search parameters/values for use with API
:param \*\*kwargs: search parameters/values
"""
def _format_fq(d):
for k,v in d.items():
if isinstance(v, list):
d[k] = ' '.join(m... | [
"def",
"_options",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_format_fq",
"(",
"d",
")",
":",
"for",
"k",
",",
"v",
"in",
"d",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"d",
"[",
"k",
"]... | 29.727273 | 0.012833 |
def summary_gradient_updates(grads, opt, lr):
"""get summary ops for the magnitude of gradient updates"""
# strategy:
# make a dict of variable name -> [variable, grad, adagrad slot]
vars_grads = {}
for v in tf.trainable_variables():
vars_grads[v.name] = [v, None, None]
for g, v in grad... | [
"def",
"summary_gradient_updates",
"(",
"grads",
",",
"opt",
",",
"lr",
")",
":",
"# strategy:",
"# make a dict of variable name -> [variable, grad, adagrad slot]",
"vars_grads",
"=",
"{",
"}",
"for",
"v",
"in",
"tf",
".",
"trainable_variables",
"(",
")",
":",
"vars... | 32.970588 | 0.001733 |
def run_module_async(kwargs, job_id, timeout_secs, started_sender, econtext):
"""
Execute a module with its run status and result written to a file,
terminating on the process on completion. This function must run in a child
forked using :func:`create_fork_child`.
@param mitogen.core.Sender started... | [
"def",
"run_module_async",
"(",
"kwargs",
",",
"job_id",
",",
"timeout_secs",
",",
"started_sender",
",",
"econtext",
")",
":",
"arunner",
"=",
"AsyncRunner",
"(",
"job_id",
",",
"timeout_secs",
",",
"started_sender",
",",
"econtext",
",",
"kwargs",
")",
"arun... | 40.190476 | 0.001157 |
def jtosparse(j):
"""
Generate sparse matrix coordinates from 3-D Jacobian.
"""
data = j.flatten().tolist()
nobs, nf, nargs = j.shape
indices = zip(*[(r, c) for n in xrange(nobs)
for r in xrange(n * nf, (n + 1) * nf)
for c in xrange(n * nargs, (n +... | [
"def",
"jtosparse",
"(",
"j",
")",
":",
"data",
"=",
"j",
".",
"flatten",
"(",
")",
".",
"tolist",
"(",
")",
"nobs",
",",
"nf",
",",
"nargs",
"=",
"j",
".",
"shape",
"indices",
"=",
"zip",
"(",
"*",
"[",
"(",
"r",
",",
"c",
")",
"for",
"n",... | 39.8 | 0.002457 |
def _apply_pipeline_and_get_build_instance(self,
X_factory,
mX_factory,
category_idx_store,
df,
pars... | [
"def",
"_apply_pipeline_and_get_build_instance",
"(",
"self",
",",
"X_factory",
",",
"mX_factory",
",",
"category_idx_store",
",",
"df",
",",
"parse_pipeline",
",",
"term_idx_store",
",",
"metadata_idx_store",
",",
"y",
")",
":",
"df",
".",
"apply",
"(",
"parse_pi... | 27.638889 | 0.057282 |
def __write_view_tmpl(tag_key, tag_list):
'''
Generate the HTML file for viewing.
:param tag_key: key of the tags.
:param tag_list: list of the tags.
:return: None
'''
view_file = os.path.join(OUT_DIR, 'view', 'view_' + tag_key.split('_')[1] + '.html')
view_widget_arr = []
for sig in... | [
"def",
"__write_view_tmpl",
"(",
"tag_key",
",",
"tag_list",
")",
":",
"view_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"OUT_DIR",
",",
"'view'",
",",
"'view_'",
"+",
"tag_key",
".",
"split",
"(",
"'_'",
")",
"[",
"1",
"]",
"+",
"'.html'",
")",... | 35.645833 | 0.001706 |
def get_placement_group_dict():
"""Returns dictionary of {placement_group_name: (state, strategy)}"""
client = get_ec2_client()
response = client.describe_placement_groups()
assert is_good_response(response)
result = OrderedDict()
ec2 = get_ec2_resource()
for placement_group_response in response['Placem... | [
"def",
"get_placement_group_dict",
"(",
")",
":",
"client",
"=",
"get_ec2_client",
"(",
")",
"response",
"=",
"client",
".",
"describe_placement_groups",
"(",
")",
"assert",
"is_good_response",
"(",
"response",
")",
"result",
"=",
"OrderedDict",
"(",
")",
"ec2",... | 32.941176 | 0.019097 |
def list_data(
self, previous_data=False, prompt=False, console_row=False,
console_row_to_cursor=False, console_row_from_cursor=False
):
""" Return list of strings. Where each string is fitted to windows width. Parameters are the same as
they are in :meth:`.WConsoleWindow.data` method
:return: list of str
... | [
"def",
"list_data",
"(",
"self",
",",
"previous_data",
"=",
"False",
",",
"prompt",
"=",
"False",
",",
"console_row",
"=",
"False",
",",
"console_row_to_cursor",
"=",
"False",
",",
"console_row_from_cursor",
"=",
"False",
")",
":",
"return",
"self",
".",
"sp... | 36.25 | 0.03139 |
def diff(arr, n, axis=0):
"""
difference of n between self,
analogous to s-s.shift(n)
Parameters
----------
arr : ndarray
n : int
number of periods
axis : int
axis to shift on
Returns
-------
shifted
"""
n = int(n)
na = np.nan
dtype = arr.d... | [
"def",
"diff",
"(",
"arr",
",",
"n",
",",
"axis",
"=",
"0",
")",
":",
"n",
"=",
"int",
"(",
"n",
")",
"na",
"=",
"np",
".",
"nan",
"dtype",
"=",
"arr",
".",
"dtype",
"is_timedelta",
"=",
"False",
"if",
"needs_i8_conversion",
"(",
"arr",
")",
":... | 26.0125 | 0.000463 |
def CloseHandle(self):
'''Releases a handle acquired with VMGuestLib_OpenHandle'''
if hasattr(self, 'handle'):
ret = vmGuestLib.VMGuestLib_CloseHandle(self.handle.value)
if ret != VMGUESTLIB_ERROR_SUCCESS: raise VMGuestLibException(ret)
del(self.handle) | [
"def",
"CloseHandle",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'handle'",
")",
":",
"ret",
"=",
"vmGuestLib",
".",
"VMGuestLib_CloseHandle",
"(",
"self",
".",
"handle",
".",
"value",
")",
"if",
"ret",
"!=",
"VMGUESTLIB_ERROR_SUCCESS",
":"... | 50 | 0.009836 |
def traverse_levelorder(self, leaves=True, internal=True):
'''Perform a levelorder traversal starting at this ``Node`` object
Args:
``leaves`` (``bool``): ``True`` to include leaves, otherwise ``False``
``internal`` (``bool``): ``True`` to include internal nodes, otherwise ``Fa... | [
"def",
"traverse_levelorder",
"(",
"self",
",",
"leaves",
"=",
"True",
",",
"internal",
"=",
"True",
")",
":",
"q",
"=",
"deque",
"(",
")",
"q",
".",
"append",
"(",
"self",
")",
"while",
"len",
"(",
"q",
")",
"!=",
"0",
":",
"n",
"=",
"q",
".",... | 39.071429 | 0.008929 |
def decrease_posts_count_after_post_deletion(sender, instance, **kwargs):
""" Decreases the member's post count after a post deletion.
This receiver handles the deletion of a forum post: the posts count related to the post's
author is decreased.
"""
if not instance.approved:
# If a post has... | [
"def",
"decrease_posts_count_after_post_deletion",
"(",
"sender",
",",
"instance",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"instance",
".",
"approved",
":",
"# If a post has not been approved, it has not been counted.",
"# So do not decrement count",
"return",
"try"... | 37.851852 | 0.001908 |
def unique_field(self, field_name):
"""set a unique field to be selected, this is automatically called when you do unique_FIELDNAME(...)"""
self.fields_set.options["unique"] = True
return self.select_field(field_name) | [
"def",
"unique_field",
"(",
"self",
",",
"field_name",
")",
":",
"self",
".",
"fields_set",
".",
"options",
"[",
"\"unique\"",
"]",
"=",
"True",
"return",
"self",
".",
"select_field",
"(",
"field_name",
")"
] | 59.5 | 0.012448 |
def turn_off(self, device_id, name):
"""Create the message to turn light or switch off."""
msg = "!%sF0|Turn Off|%s" % (device_id, name)
self._send_message(msg) | [
"def",
"turn_off",
"(",
"self",
",",
"device_id",
",",
"name",
")",
":",
"msg",
"=",
"\"!%sF0|Turn Off|%s\"",
"%",
"(",
"device_id",
",",
"name",
")",
"self",
".",
"_send_message",
"(",
"msg",
")"
] | 45.25 | 0.01087 |
def emit_toi_stats(toi_set, peripherals):
"""
Calculates new TOI stats and emits them via statsd.
"""
count_by_zoom = defaultdict(int)
total = 0
for coord_int in toi_set:
coord = coord_unmarshall_int(coord_int)
count_by_zoom[coord.zoom] += 1
total += 1
peripherals.s... | [
"def",
"emit_toi_stats",
"(",
"toi_set",
",",
"peripherals",
")",
":",
"count_by_zoom",
"=",
"defaultdict",
"(",
"int",
")",
"total",
"=",
"0",
"for",
"coord_int",
"in",
"toi_set",
":",
"coord",
"=",
"coord_unmarshall_int",
"(",
"coord_int",
")",
"count_by_zoo... | 28.666667 | 0.001876 |
def _asdict(self):
"""Return a dictionary representation of the current prompt."""
with self._cond:
if self._prompt is None:
return
return {'id': self._prompt.id,
'message': self._prompt.message,
'text-input': self._prompt.text_input} | [
"def",
"_asdict",
"(",
"self",
")",
":",
"with",
"self",
".",
"_cond",
":",
"if",
"self",
".",
"_prompt",
"is",
"None",
":",
"return",
"return",
"{",
"'id'",
":",
"self",
".",
"_prompt",
".",
"id",
",",
"'message'",
":",
"self",
".",
"_prompt",
"."... | 35.375 | 0.010345 |
def _create_attachment(self, filename, content, mimetype=None):
"""Convert the filename, content, mimetype triple to attachment."""
if mimetype is None:
mimetype, _ = mimetypes.guess_type(filename)
if mimetype is None:
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
... | [
"def",
"_create_attachment",
"(",
"self",
",",
"filename",
",",
"content",
",",
"mimetype",
"=",
"None",
")",
":",
"if",
"mimetype",
"is",
"None",
":",
"mimetype",
",",
"_",
"=",
"mimetypes",
".",
"guess_type",
"(",
"filename",
")",
"if",
"mimetype",
"is... | 42.857143 | 0.002174 |
def _phase_kuramoto(self, teta, t, argv):
"""!
@brief Overrided method for calculation of oscillator phase.
@param[in] teta (double): Current value of phase.
@param[in] t (double): Time (can be ignored).
@param[in] argv (uint): Index of oscillator whose phase repre... | [
"def",
"_phase_kuramoto",
"(",
"self",
",",
"teta",
",",
"t",
",",
"argv",
")",
":",
"index",
"=",
"argv",
"# index of oscillator\r",
"phase",
"=",
"0.0",
"# phase of a specified oscillator that will calculated in line with current env. states.\r",
"neighbors",
"=",
"self... | 39.5 | 0.021183 |
def query(botcust2, message):
"""Sends a message to Mitsuku and retrieves the reply
Args:
botcust2 (str): The botcust2 identifier
message (str): The message to send to Mitsuku
Returns:
reply (str): The message Mitsuku sent back
"""
logger.debug("Getting Mitsuku reply")
... | [
"def",
"query",
"(",
"botcust2",
",",
"message",
")",
":",
"logger",
".",
"debug",
"(",
"\"Getting Mitsuku reply\"",
")",
"# Set up http request packages",
"params",
"=",
"{",
"'botid'",
":",
"'f6a012073e345a08'",
",",
"'amp;skin'",
":",
"'chat'",
"}",
"headers",
... | 30.898305 | 0.001063 |
def Emulation_setNavigatorOverrides(self, platform):
"""
Function path: Emulation.setNavigatorOverrides
Domain: Emulation
Method name: setNavigatorOverrides
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'platform' (type: string) -> The platform navigator... | [
"def",
"Emulation_setNavigatorOverrides",
"(",
"self",
",",
"platform",
")",
":",
"assert",
"isinstance",
"(",
"platform",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'platform' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"platform",
")",... | 33 | 0.044881 |
def get_provider(cls, scm_name: str, conf) -> SourceControl:
"""Load and return named SCM provider instance.
:param conf: A yabt.config.Config object used to initialize the SCM
provider instance.
:raises KeyError: If no SCM provider with name `scm_name` registered.
... | [
"def",
"get_provider",
"(",
"cls",
",",
"scm_name",
":",
"str",
",",
"conf",
")",
"->",
"SourceControl",
":",
"for",
"entry_point",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'yabt.scm'",
",",
"scm_name",
")",
":",
"entry_point",
".",
"load",
"("... | 49.764706 | 0.00232 |
def device_uuid(self):
"""Return device UUID."""
if self._device:
return self._device
return GEN_ID_FORMAT.format(self.src_ip) | [
"def",
"device_uuid",
"(",
"self",
")",
":",
"if",
"self",
".",
"_device",
":",
"return",
"self",
".",
"_device",
"return",
"GEN_ID_FORMAT",
".",
"format",
"(",
"self",
".",
"src_ip",
")"
] | 31.6 | 0.012346 |
def delete(self, hdfs_path, recursive=False):
"""Delete a file located at `hdfs_path`."""
return self.client.delete(hdfs_path, recursive=recursive) | [
"def",
"delete",
"(",
"self",
",",
"hdfs_path",
",",
"recursive",
"=",
"False",
")",
":",
"return",
"self",
".",
"client",
".",
"delete",
"(",
"hdfs_path",
",",
"recursive",
"=",
"recursive",
")"
] | 53.666667 | 0.01227 |
def list_menu(self, options, title="Choose a value", message="Choose a value", default=None, **kwargs):
"""
Show a single-selection list menu
Usage: C{dialog.list_menu(options, title="Choose a value", message="Choose a value", default=None, **kwargs)}
@param options: li... | [
"def",
"list_menu",
"(",
"self",
",",
"options",
",",
"title",
"=",
"\"Choose a value\"",
",",
"message",
"=",
"\"Choose a value\"",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"choices",
"=",
"[",
"]",
"optionNum",
"=",
"0",
"for",
... | 38.931034 | 0.008643 |
def create(gandi, datacenter, memory, cores, ip_version, bandwidth, login,
password, hostname, image, run, background, sshkey, size, vlan, ip,
script, script_args, ssh, gen_password):
"""Create a new virtual machine.
you can specify a configuration entry named 'sshkey' containing
path... | [
"def",
"create",
"(",
"gandi",
",",
"datacenter",
",",
"memory",
",",
"cores",
",",
"ip_version",
",",
"bandwidth",
",",
"login",
",",
"password",
",",
"hostname",
",",
"image",
",",
"run",
",",
"background",
",",
"sshkey",
",",
"size",
",",
"vlan",
",... | 33.782051 | 0.001106 |
def fit(self, X, y=None, **kwargs):
"""
The fit method is the primary drawing input for the
visualization since it has both the X and y data required for the
viz and the transform method does not.
Parameters
----------
X : ndarray or DataFrame of shape n x m
... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Convert from pandas data types",
"if",
"is_dataframe",
"(",
"X",
")",
":",
"# Get column names before reverting to an np.ndarray",
"if",
"self",
".",
"features_",
... | 34.919355 | 0.001797 |
def close(self, **kwargs):
"""
close websocket connection.
"""
self.keep_running = False
if self.sock:
self.sock.close(**kwargs)
self.sock = None | [
"def",
"close",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"keep_running",
"=",
"False",
"if",
"self",
".",
"sock",
":",
"self",
".",
"sock",
".",
"close",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"sock",
"=",
"None"
] | 25.25 | 0.009569 |
def build_report(self, msg=''):
"""Resposible for constructing a report to be output as part of the build.
Returns report as a string.
"""
shutit_global.shutit_global_object.yield_to_draw()
s = '\n'
s += '################################################################################\n'
s += '# COMMAND H... | [
"def",
"build_report",
"(",
"self",
",",
"msg",
"=",
"''",
")",
":",
"shutit_global",
".",
"shutit_global_object",
".",
"yield_to_draw",
"(",
")",
"s",
"=",
"'\\n'",
"s",
"+=",
"'################################################################################\\n'",
"s",... | 49.035714 | 0.027143 |
def bitcount(self, key, start=None, end=None):
"""Count the number of set bits (population counting) in a string.
By default all the bytes contained in the string are examined. It is
possible to specify the counting operation only in an interval passing
the additional arguments start an... | [
"def",
"bitcount",
"(",
"self",
",",
"key",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"command",
"=",
"[",
"b'BITCOUNT'",
",",
"key",
"]",
"if",
"start",
"is",
"not",
"None",
"and",
"end",
"is",
"None",
":",
"raise",
"ValueError... | 42.142857 | 0.001325 |
def get_bin_index(self, value):
"""Used to get the index of the bin to place a particular value."""
if value == self.max_value:
return self.num_bins - 1
return int(self.C * log(value / self.min_value)) | [
"def",
"get_bin_index",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"max_value",
":",
"return",
"self",
".",
"num_bins",
"-",
"1",
"return",
"int",
"(",
"self",
".",
"C",
"*",
"log",
"(",
"value",
"/",
"self",
".",
"min_v... | 38.833333 | 0.008403 |
def from_dict(dic):
"""
recursive dict to dictobj 컨버트
:param dic:
:return:
"""
return ODict((k, ODict.convert_ifdic(v)) for k, v in dic.items()) | [
"def",
"from_dict",
"(",
"dic",
")",
":",
"return",
"ODict",
"(",
"(",
"k",
",",
"ODict",
".",
"convert_ifdic",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"dic",
".",
"items",
"(",
")",
")"
] | 26.571429 | 0.010417 |
def _parse_image_multilogs_string(config, ret, repo):
'''
Parse image log strings into grokable data
'''
image_logs, infos = [], None
if ret and ret.strip().startswith('{') and ret.strip().endswith('}'):
pushd = 0
buf = ''
for char in ret:
buf += char
... | [
"def",
"_parse_image_multilogs_string",
"(",
"config",
",",
"ret",
",",
"repo",
")",
":",
"image_logs",
",",
"infos",
"=",
"[",
"]",
",",
"None",
"if",
"ret",
"and",
"ret",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'{'",
")",
"and",
"ret",
"."... | 31.758621 | 0.002107 |
def _decode_signed_user(encoded_sig, encoded_data):
""" Decodes the ``POST``ed signed data
"""
decoded_sig = _decode(encoded_sig)
decoded_data = loads(_decode(encoded_data))
if decoded_sig != hmac.new(app.config['CANVAS_CLIENT_SECRET'],
encoded_data, sha256).digest():
raise ValueEr... | [
"def",
"_decode_signed_user",
"(",
"encoded_sig",
",",
"encoded_data",
")",
":",
"decoded_sig",
"=",
"_decode",
"(",
"encoded_sig",
")",
"decoded_data",
"=",
"loads",
"(",
"_decode",
"(",
"encoded_data",
")",
")",
"if",
"decoded_sig",
"!=",
"hmac",
".",
"new",... | 34.272727 | 0.010336 |
def migrate_to_blob(context, portal_type, query={}, remove_old_value=True):
"""Migrates FileFields fields to blob ones for a given portal_type.
The wueries are done against 'portal_catalog', 'uid_catalog' and
'reference_catalog'
:param context: portal root object as context
:param query: an express... | [
"def",
"migrate_to_blob",
"(",
"context",
",",
"portal_type",
",",
"query",
"=",
"{",
"}",
",",
"remove_old_value",
"=",
"True",
")",
":",
"migrator",
"=",
"makeMigrator",
"(",
"context",
",",
"portal_type",
",",
"remove_old_value",
"=",
"remove_old_value",
")... | 43.625 | 0.001403 |
def aggregation_result_extractor(impact_report, component_metadata):
"""Extracting aggregation result of breakdown from the impact layer.
:param impact_report: the impact report that acts as a proxy to fetch
all the data that extractor needed
:type impact_report: safe.report.impact_report.ImpactRep... | [
"def",
"aggregation_result_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"context",
"=",
"{",
"}",
"\"\"\"Initializations.\"\"\"",
"extra_args",
"=",
"component_metadata",
".",
"extra_args",
"# Find out aggregation report type",
"analysis_layer",
"=",... | 36.586777 | 0.00011 |
def my_protocol_parser(out, buf):
"""Parser is used with StreamParser for incremental protocol parsing.
Parser is a generator function, but it is not a coroutine. Usually
parsers are implemented as a state machine.
more details in asyncio/parsers.py
existing parsers:
* HTTP protocol parsers a... | [
"def",
"my_protocol_parser",
"(",
"out",
",",
"buf",
")",
":",
"while",
"True",
":",
"tp",
"=",
"yield",
"from",
"buf",
".",
"read",
"(",
"5",
")",
"if",
"tp",
"in",
"(",
"MSG_PING",
",",
"MSG_PONG",
")",
":",
"# skip line",
"yield",
"from",
"buf",
... | 37.708333 | 0.001078 |
def prodmix(I,K,a,p,epsilon,LB):
"""prodmix: robust production planning using soco
Parameters:
I - set of materials
K - set of components
a[i][k] - coef. matrix
p[i] - price of material i
LB[k] - amount needed for k
Returns a model, ready to be solved.
"""
... | [
"def",
"prodmix",
"(",
"I",
",",
"K",
",",
"a",
",",
"p",
",",
"epsilon",
",",
"LB",
")",
":",
"model",
"=",
"Model",
"(",
"\"robust product mix\"",
")",
"x",
",",
"rhs",
"=",
"{",
"}",
",",
"{",
"}",
"for",
"i",
"in",
"I",
":",
"x",
"[",
"... | 29.678571 | 0.018648 |
def _separable_series3(h, N=1, verbose=False):
""" finds separable approximations to the 3d kernel h
returns res = (hx,hy,hz)[N]
s.t. h \approx sum_i einsum("i,j,k",res[i,0],res[i,1],res[i,2])
FIXME: This is just a naive and slow first try!
"""
hx, hy, hz = [], [], []
res = h.copy()
fo... | [
"def",
"_separable_series3",
"(",
"h",
",",
"N",
"=",
"1",
",",
"verbose",
"=",
"False",
")",
":",
"hx",
",",
"hy",
",",
"hz",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"res",
"=",
"h",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
... | 30 | 0.001901 |
def get_staking_leaderboard(self, round_num=0, tournament=1):
"""Retrieves the leaderboard of the staking competition for the given
round.
Args:
round_num (int, optional): The round you are interested in,
defaults to current round.
tournament (int, option... | [
"def",
"get_staking_leaderboard",
"(",
"self",
",",
"round_num",
"=",
"0",
",",
"tournament",
"=",
"1",
")",
":",
"msg",
"=",
"\"getting stakes for tournament {} round {}\"",
"self",
".",
"logger",
".",
"info",
"(",
"msg",
".",
"format",
"(",
"tournament",
","... | 38.240964 | 0.001229 |
async def setup_hostname() -> str:
"""
Intended to be run when the server starts. Sets the machine hostname.
The machine hostname is set from the systemd-generated machine-id, which
changes at every boot.
Once the hostname is set, we restart avahi.
This is a separate task from establishing an... | [
"async",
"def",
"setup_hostname",
"(",
")",
"->",
"str",
":",
"machine_id",
"=",
"open",
"(",
"'/etc/machine-id'",
")",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"hostname",
"=",
"machine_id",
"[",
":",
"6",
"]",
"with",
"open",
"(",
"'/etc/hostna... | 37.44898 | 0.000531 |
def get_key_pair(self, alias_name):
"""
Retrieves the public and private key pair associated with the specified alias name.
Args:
alias_name: Key pair associated with the RabbitMQ
Returns:
dict: RabbitMQ certificate
"""
uri = self.URI + "/keypair... | [
"def",
"get_key_pair",
"(",
"self",
",",
"alias_name",
")",
":",
"uri",
"=",
"self",
".",
"URI",
"+",
"\"/keypair/\"",
"+",
"alias_name",
"return",
"self",
".",
"_client",
".",
"get",
"(",
"uri",
")"
] | 30.083333 | 0.008065 |
def from_bytes(cls, bitstream):
'''
Parse the given packet and update properties accordingly
'''
packet = cls()
# Convert to ConstBitStream (if not already provided)
if not isinstance(bitstream, ConstBitStream):
if isinstance(bitstream, Bits):
... | [
"def",
"from_bytes",
"(",
"cls",
",",
"bitstream",
")",
":",
"packet",
"=",
"cls",
"(",
")",
"# Convert to ConstBitStream (if not already provided)",
"if",
"not",
"isinstance",
"(",
"bitstream",
",",
"ConstBitStream",
")",
":",
"if",
"isinstance",
"(",
"bitstream"... | 32.897959 | 0.001205 |
def scanf(format, s=None, collapseWhitespace=True):
"""
scanf supports the following formats:
%c One character
%5c 5 characters
%d, %i int value
%7d, %7i int value with length 7
%f float value
%o octal value
%X, %x hex value
%s ... | [
"def",
"scanf",
"(",
"format",
",",
"s",
"=",
"None",
",",
"collapseWhitespace",
"=",
"True",
")",
":",
"if",
"s",
"is",
"None",
":",
"s",
"=",
"sys",
".",
"stdin",
"if",
"hasattr",
"(",
"s",
",",
"\"readline\"",
")",
":",
"s",
"=",
"s",
".",
"... | 26.8 | 0.002058 |
def asDictionary(self):
""" returns object as dictionary """
template = {
"type" : "esriSFS",
"style" : self._style,
"color" : self._color,
"outline" : self._outline
}
return template | [
"def",
"asDictionary",
"(",
"self",
")",
":",
"template",
"=",
"{",
"\"type\"",
":",
"\"esriSFS\"",
",",
"\"style\"",
":",
"self",
".",
"_style",
",",
"\"color\"",
":",
"self",
".",
"_color",
",",
"\"outline\"",
":",
"self",
".",
"_outline",
"}",
"return... | 28.333333 | 0.022814 |
def create_hdf5(output_filename, feature_count, data):
"""
Create a HDF5 feature files.
Parameters
----------
output_filename : string
name of the HDF5 file that will be created
feature_count : int
dimension of all features combined
data : list of tuples
list of (x, ... | [
"def",
"create_hdf5",
"(",
"output_filename",
",",
"feature_count",
",",
"data",
")",
":",
"import",
"h5py",
"logging",
".",
"info",
"(",
"\"Start creating of %s hdf file\"",
",",
"output_filename",
")",
"x",
"=",
"[",
"]",
"y",
"=",
"[",
"]",
"for",
"featur... | 32.785714 | 0.001058 |
def configparser_to_backend_config(cp_instance):
"""
Return a config dict generated from a configparser instance.
This functions main purpose is to ensure config dict values are properly typed.
Note:
This can be used with any ``ConfigParser`` backend instance not just the default one
i... | [
"def",
"configparser_to_backend_config",
"(",
"cp_instance",
")",
":",
"def",
"get_store",
"(",
")",
":",
"# [TODO]",
"# This should be deligated to a dedicated validation function!",
"store",
"=",
"cp_instance",
".",
"get",
"(",
"'Backend'",
",",
"'store'",
")",
"if",
... | 32.597222 | 0.002068 |
def random_histogram(counts, nbins, seed):
"""
Distribute a total number of counts on a set of bins homogenously.
>>> random_histogram(1, 2, 42)
array([1, 0])
>>> random_histogram(100, 5, 42)
array([28, 18, 17, 19, 18])
>>> random_histogram(10000, 5, 42)
array([2043, 2015, 2050, 1930, 1... | [
"def",
"random_histogram",
"(",
"counts",
",",
"nbins",
",",
"seed",
")",
":",
"numpy",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"return",
"numpy",
".",
"histogram",
"(",
"numpy",
".",
"random",
".",
"random",
"(",
"counts",
")",
",",
"nbins",
"... | 32.538462 | 0.002299 |
def ensure(cond, *args, **kwds):
"""
Return if a condition is true, otherwise raise a caller-configurable
:py:class:`Exception`
:param bool cond: the condition to be checked
:param sequence args: the arguments to be passed to the exception's
constructor
The only accepte... | [
"def",
"ensure",
"(",
"cond",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"_CHK_UNEXP",
"=",
"'check_condition() got an unexpected keyword argument {0}'",
"raising",
"=",
"kwds",
".",
"pop",
"(",
"'raising'",
",",
"AssertionError",
")",
"if",
"kwds",
":... | 35.947368 | 0.001427 |
def create(self, ospf_process_id, vrf=None):
"""Creates a OSPF process in the specified VRF or the default VRF.
Args:
ospf_process_id (str): The OSPF process Id value
vrf (str): The VRF to apply this OSPF process to
Returns:
bool: True if th... | [
"def",
"create",
"(",
"self",
",",
"ospf_process_id",
",",
"vrf",
"=",
"None",
")",
":",
"value",
"=",
"int",
"(",
"ospf_process_id",
")",
"if",
"not",
"0",
"<",
"value",
"<",
"65536",
":",
"raise",
"ValueError",
"(",
"'ospf as must be between 1 and 65535'",... | 41.210526 | 0.002497 |
def url(self, host):
"""Generate url for coap client."""
path = '/'.join(str(v) for v in self._path)
return 'coaps://{}:5684/{}'.format(host, path) | [
"def",
"url",
"(",
"self",
",",
"host",
")",
":",
"path",
"=",
"'/'",
".",
"join",
"(",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"self",
".",
"_path",
")",
"return",
"'coaps://{}:5684/{}'",
".",
"format",
"(",
"host",
",",
"path",
")"
] | 42 | 0.011696 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.