text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def gpg_verify_key( key_id, key_data, config_dir=None ):
"""
Verify that a given serialized key, when imported, has the given key ID.
Return True on success
Return False on error
"""
key_data = str(key_data)
config_dir = get_config_dir( config_dir )
sanitized_key_id = "".join( key_id.u... | [
"def",
"gpg_verify_key",
"(",
"key_id",
",",
"key_data",
",",
"config_dir",
"=",
"None",
")",
":",
"key_data",
"=",
"str",
"(",
"key_data",
")",
"config_dir",
"=",
"get_config_dir",
"(",
"config_dir",
")",
"sanitized_key_id",
"=",
"\"\"",
".",
"join",
"(",
... | 29.888889 | 0.015606 |
def create_toolbar_tokens_func(get_is_refreshing, show_fish_help):
"""
Return a function that generates the toolbar tokens.
"""
token = Token.Toolbar
def get_toolbar_tokens(cli):
result = []
result.append((token, ' '))
if cli.buffers[DEFAULT_BUFFER].always_multiline:
... | [
"def",
"create_toolbar_tokens_func",
"(",
"get_is_refreshing",
",",
"show_fish_help",
")",
":",
"token",
"=",
"Token",
".",
"Toolbar",
"def",
"get_toolbar_tokens",
"(",
"cli",
")",
":",
"result",
"=",
"[",
"]",
"result",
".",
"append",
"(",
"(",
"token",
","... | 30.393939 | 0.001932 |
def flatten_all(list_of_list):
"""Flatten arbitrary depth of nesting. Good for unknown nesting structure
iterable object.
Usage::
>>> flatten_all([[0, 1], [2, 3, [4, 5], [6, 7, 8]], [9,]])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
"""
for i in list_of_list:
if hasattr(i, "__iter__"):
... | [
"def",
"flatten_all",
"(",
"list_of_list",
")",
":",
"for",
"i",
"in",
"list_of_list",
":",
"if",
"hasattr",
"(",
"i",
",",
"\"__iter__\"",
")",
":",
"for",
"j",
"in",
"flatten_all",
"(",
"i",
")",
":",
"yield",
"j",
"else",
":",
"yield",
"i"
] | 26.666667 | 0.002415 |
def remove_file_handlers(logger=None):
"""
Remove only file handlers from the specified logger. Will go through
and close each handler for safety.
:param logger: logging name or object to modify, defaults to root logger
"""
if not isinstance(logger, logging.Logger):
logger = logging.get... | [
"def",
"remove_file_handlers",
"(",
"logger",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"logger",
",",
"logging",
".",
"Logger",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"logger",
")",
"new_handlers",
"=",
"[",
"]",
"for",
... | 32.235294 | 0.001773 |
def _phi0(self, rho, T, x):
"""Ideal gas Helmholtz energy of binary mixtures and derivatives
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
x : float
Mole fraction of ammonia in mixture, [mol/mol]
... | [
"def",
"_phi0",
"(",
"self",
",",
"rho",
",",
"T",
",",
"x",
")",
":",
"# Define reducing parameters for mixture model",
"M",
"=",
"(",
"1",
"-",
"x",
")",
"*",
"IAPWS95",
".",
"M",
"+",
"x",
"*",
"NH3",
".",
"M",
"tau",
"=",
"500",
"/",
"T",
"de... | 33.344086 | 0.000626 |
def _constructClient(client_version, username, user_domain, password, project_name, project_domain,
auth_url):
"""Return a novaclient from the given args."""
loader = loading.get_plugin_loader('password')
# These only work with v3
if user_domain is not None or p... | [
"def",
"_constructClient",
"(",
"client_version",
",",
"username",
",",
"user_domain",
",",
"password",
",",
"project_name",
",",
"project_domain",
",",
"auth_url",
")",
":",
"loader",
"=",
"loading",
".",
"get_plugin_loader",
"(",
"'password'",
")",
"# These only... | 57.2 | 0.009174 |
def can_run_pconf(self, pconf):
"""True if the qadapter in principle is able to run the :class:`ParalConf` pconf"""
if not self.hint_cores >= pconf.num_cores >= self.min_cores: return False
if not self.hw.can_use_omp_threads(self.omp_threads): return False
if pconf.mem_per_proc > self.hw... | [
"def",
"can_run_pconf",
"(",
"self",
",",
"pconf",
")",
":",
"if",
"not",
"self",
".",
"hint_cores",
">=",
"pconf",
".",
"num_cores",
">=",
"self",
".",
"min_cores",
":",
"return",
"False",
"if",
"not",
"self",
".",
"hw",
".",
"can_use_omp_threads",
"(",... | 55.222222 | 0.015842 |
def save(self, *args, **kwargs):
"""
performs actions on create:
* ensure instance has usable password
* set default group
* keep in sync with email address model
"""
created = self.pk is None
sync_emailaddress = kwargs.pop('sync_emailaddress',... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"created",
"=",
"self",
".",
"pk",
"is",
"None",
"sync_emailaddress",
"=",
"kwargs",
".",
"pop",
"(",
"'sync_emailaddress'",
",",
"True",
")",
"# ensure usable password",
"i... | 43.107143 | 0.001621 |
def re_flags_str(flags, custom_flags):
"""Convert regexp flags to string.
Parameters
----------
flags : `int`
Flags.
custom_flags : `int`
Custom flags.
Returns
-------
`str`
Flag string.
"""
res = ''
for flag in RE_FLAGS:
if flags & getattr(r... | [
"def",
"re_flags_str",
"(",
"flags",
",",
"custom_flags",
")",
":",
"res",
"=",
"''",
"for",
"flag",
"in",
"RE_FLAGS",
":",
"if",
"flags",
"&",
"getattr",
"(",
"re",
",",
"flag",
")",
":",
"res",
"+=",
"flag",
"for",
"flag",
"in",
"RE_CUSTOM_FLAGS",
... | 19.695652 | 0.002105 |
def use(broker, debug=True, **kwargs):
"""用于生成特定的券商对象
:param broker:券商名支持 ['yh_client', '银河客户端'] ['ht_client', '华泰客户端']
:param debug: 控制 debug 日志的显示, 默认为 True
:param initial_assets: [雪球参数] 控制雪球初始资金,默认为一百万
:return the class of trader
Usage::
>>> import easytrader
>>> user = easy... | [
"def",
"use",
"(",
"broker",
",",
"debug",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"debug",
":",
"log",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"if",
"broker",
".",
"lower",
"(",
")",
"in",
"[",
"\"xq\"",
",",
"\... | 29.457143 | 0.000939 |
def replace_namespaced_replication_controller_scale(self, name, namespace, body, **kwargs): # noqa: E501
"""replace_namespaced_replication_controller_scale # noqa: E501
replace scale of the specified ReplicationController # noqa: E501
This method makes a synchronous HTTP request by default. ... | [
"def",
"replace_namespaced_replication_controller_scale",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
... | 64.8 | 0.001217 |
def parse(self, line: str, expand: bool = True) -> Statement:
"""
Tokenize the input and parse it into a Statement object, stripping
comments, expanding aliases and shortcuts, and extracting output
redirection directives.
:param line: the command line being parsed
:param... | [
"def",
"parse",
"(",
"self",
",",
"line",
":",
"str",
",",
"expand",
":",
"bool",
"=",
"True",
")",
"->",
"Statement",
":",
"# handle the special case/hardcoded terminator of a blank line",
"# we have to do this before we tokenize because tokenizing",
"# destroys all unquoted... | 40.241611 | 0.000977 |
def generate_py2k(config, py2k_dir=PY2K_DIR, run_tests=False):
"""Generate Python 2 code from Python 3 code."""
def copy(src, dst):
if (not os.path.isfile(dst) or
os.path.getmtime(src) > os.path.getmtime(dst)):
shutil.copy(src, dst)
return dst
return None
... | [
"def",
"generate_py2k",
"(",
"config",
",",
"py2k_dir",
"=",
"PY2K_DIR",
",",
"run_tests",
"=",
"False",
")",
":",
"def",
"copy",
"(",
"src",
",",
"dst",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"dst",
")",
"or",
"os",
"... | 37.413462 | 0.000501 |
def initialize(self, executor, secret):
'''
This handles initial setup of the `RequestHandler`.
'''
self.executor = executor
self.secret = secret | [
"def",
"initialize",
"(",
"self",
",",
"executor",
",",
"secret",
")",
":",
"self",
".",
"executor",
"=",
"executor",
"self",
".",
"secret",
"=",
"secret"
] | 22.5 | 0.010695 |
def diff(cwd,
item1=None,
item2=None,
opts='',
git_opts='',
user=None,
password=None,
no_index=False,
cached=False,
paths=None,
output_encoding=None):
'''
.. versionadded:: 2015.8.12,2016.3.3,2016.11.0
Interface to `g... | [
"def",
"diff",
"(",
"cwd",
",",
"item1",
"=",
"None",
",",
"item2",
"=",
"None",
",",
"opts",
"=",
"''",
",",
"git_opts",
"=",
"''",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"no_index",
"=",
"False",
",",
"cached",
"=",
"False... | 34.994118 | 0.00049 |
def __make_patch_storeable(self, patch):
"""Replace all dots with pipes in key names, mongo doesn't like to store keys with dots.
:param dict patch: The patch that needs to be made storeable and applied in the future
"""
new_patch = {}
for key in patch:
new_patch[key... | [
"def",
"__make_patch_storeable",
"(",
"self",
",",
"patch",
")",
":",
"new_patch",
"=",
"{",
"}",
"for",
"key",
"in",
"patch",
":",
"new_patch",
"[",
"key",
".",
"replace",
"(",
"\".\"",
",",
"\"|\"",
")",
"]",
"=",
"patch",
"[",
"key",
"]",
"return"... | 36.9 | 0.010582 |
def _on_connected(self, stream_future, connect_future):
"""Invoked when the socket stream has connected, setting up the
stream callbacks and invoking the on connect callback if set.
:param stream_future: The connection socket future
:type stream_future: :class:`~tornado.concurrent.Futur... | [
"def",
"_on_connected",
"(",
"self",
",",
"stream_future",
",",
"connect_future",
")",
":",
"if",
"stream_future",
".",
"exception",
"(",
")",
":",
"connect_future",
".",
"set_exception",
"(",
"exceptions",
".",
"ConnectError",
"(",
"stream_future",
".",
"except... | 44.684211 | 0.002307 |
def _replace_zeros(arr, default_min_value):
"""Substitute 0s in the list with a near-zero value.
Parameters
-----------
arr : numpy.array(float)
default_min_value : float
If the smallest non-zero element in `arr` is greater than the default,
use the default instead.
Returns
... | [
"def",
"_replace_zeros",
"(",
"arr",
",",
"default_min_value",
")",
":",
"min_nonzero_value",
"=",
"min",
"(",
"default_min_value",
",",
"np",
".",
"min",
"(",
"arr",
"[",
"arr",
">",
"0",
"]",
")",
")",
"closest_to_zero",
"=",
"np",
".",
"nextafter",
"(... | 30.166667 | 0.001786 |
def post_message(self, message, duration=None, pause=True, style="info"):
""" Post a message on the screen with Messenger.
Arguments:
message: The message to display.
duration: The time until the message vanishes. (Default: 2.55s)
pause: If True, the p... | [
"def",
"post_message",
"(",
"self",
",",
"message",
",",
"duration",
"=",
"None",
",",
"pause",
"=",
"True",
",",
"style",
"=",
"\"info\"",
")",
":",
"if",
"not",
"duration",
":",
"if",
"not",
"self",
".",
"message_duration",
":",
"duration",
"=",
"set... | 43.619048 | 0.002137 |
def access_cookie_valid(self, cookie, log_msg):
"""Check access cookie validity.
Returns true if the access cookie is valid. The set of allowed
access cookies is stored in self.access_cookies.
Uses log_msg as prefix to info level log message of accetance or
rejection.
"... | [
"def",
"access_cookie_valid",
"(",
"self",
",",
"cookie",
",",
"log_msg",
")",
":",
"if",
"(",
"cookie",
"in",
"self",
".",
"access_cookies",
")",
":",
"age",
"=",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"-",
"self",
".",
"access_cookies",
"[... | 43.407407 | 0.001669 |
def process(self, flightmode_selections, _flightmodes, block=True):
'''process and display graph'''
self.msg_types = set()
self.multiplier = []
self.field_types = []
self.xlim = None
self.flightmode_list = _flightmodes
# work out msg types we are interested in
... | [
"def",
"process",
"(",
"self",
",",
"flightmode_selections",
",",
"_flightmodes",
",",
"block",
"=",
"True",
")",
":",
"self",
".",
"msg_types",
"=",
"set",
"(",
")",
"self",
".",
"multiplier",
"=",
"[",
"]",
"self",
".",
"field_types",
"=",
"[",
"]",
... | 32.517241 | 0.00206 |
def dumps(dict_data, ensure_ascii=True, indent=None,
sort_keys=False, encoding='utf-8', **kwargs):
"""
返回json数据
:param encoding:
:param ensure_ascii:
:param sort_keys:
:param indent:
:param dict_data:
:return:
"""
return json.dumps(dict_data, default=json_default,
... | [
"def",
"dumps",
"(",
"dict_data",
",",
"ensure_ascii",
"=",
"True",
",",
"indent",
"=",
"None",
",",
"sort_keys",
"=",
"False",
",",
"encoding",
"=",
"'utf-8'",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"dict_data",
",",
... | 29.133333 | 0.002217 |
def erase_screen(self):
"""
Erase output screen.
"""
self.vt100_output.erase_screen()
self.vt100_output.cursor_goto(0, 0)
self.vt100_output.flush() | [
"def",
"erase_screen",
"(",
"self",
")",
":",
"self",
".",
"vt100_output",
".",
"erase_screen",
"(",
")",
"self",
".",
"vt100_output",
".",
"cursor_goto",
"(",
"0",
",",
"0",
")",
"self",
".",
"vt100_output",
".",
"flush",
"(",
")"
] | 27 | 0.010256 |
def saturation_equivalent_potential_temperature(pressure, temperature):
r"""Calculate saturation equivalent potential temperature.
This calculation must be given an air parcel's pressure and temperature.
The implementation uses the formula outlined in [Bolton1980]_ for the
equivalent potential temperat... | [
"def",
"saturation_equivalent_potential_temperature",
"(",
"pressure",
",",
"temperature",
")",
":",
"t",
"=",
"temperature",
".",
"to",
"(",
"'kelvin'",
")",
".",
"magnitude",
"p",
"=",
"pressure",
".",
"to",
"(",
"'hPa'",
")",
".",
"magnitude",
"e",
"=",
... | 32.016129 | 0.001466 |
def json(a):
"""
Output the json encoding of its argument.
This will escape all the HTML/XML special characters with their unicode
escapes, so it is safe to be output anywhere except for inside a tag
attribute.
If the output needs to be put in an attribute, entitize the output of this
filt... | [
"def",
"json",
"(",
"a",
")",
":",
"json_str",
"=",
"json_dumps",
"(",
"a",
")",
"# Escape all the XML/HTML special characters.",
"escapes",
"=",
"[",
"'<'",
",",
"'>'",
",",
"'&'",
"]",
"for",
"c",
"in",
"escapes",
":",
"json_str",
"=",
"json_str",
".",
... | 28.6 | 0.001692 |
def success(text):
'''Display a success message'''
print(' '.join((green('✔'), white(text))))
sys.stdout.flush() | [
"def",
"success",
"(",
"text",
")",
":",
"print",
"(",
"' '",
".",
"join",
"(",
"(",
"green",
"(",
"'✔'),",
" ",
"w",
"ite(t",
"e",
"xt))",
")",
")",
"",
"",
"sys",
".",
"stdout",
".",
"flush",
"(",
")"
] | 30.25 | 0.008065 |
def _is_image(self, var):
"""Return True if variable is a PIL.Image image"""
try:
from PIL import Image
return isinstance(var, Image.Image)
except:
return False | [
"def",
"_is_image",
"(",
"self",
",",
"var",
")",
":",
"try",
":",
"from",
"PIL",
"import",
"Image",
"return",
"isinstance",
"(",
"var",
",",
"Image",
".",
"Image",
")",
"except",
":",
"return",
"False"
] | 30.571429 | 0.013636 |
def read_request_from_str(data, **params):
"""
从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化
:param data:
:param params:
:return:
"""
method, uri = None, None
headers = {}
host = ''
try:
split_list = data.split('\n\n')
headers_text = split_list[0]
body = '\n\n'.join(sp... | [
"def",
"read_request_from_str",
"(",
"data",
",",
"*",
"*",
"params",
")",
":",
"method",
",",
"uri",
"=",
"None",
",",
"None",
"headers",
"=",
"{",
"}",
"host",
"=",
"''",
"try",
":",
"split_list",
"=",
"data",
".",
"split",
"(",
"'\\n\\n'",
")",
... | 25.777778 | 0.002492 |
def get_formset_class(self, **kwargs):
"""
Returns the formset for the queryset,
if a form class is available.
"""
form_class = self.get_formset_form_class()
if form_class:
kwargs['formfield_callback'] = self.formfield_for_dbfield
return model_form... | [
"def",
"get_formset_class",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"form_class",
"=",
"self",
".",
"get_formset_form_class",
"(",
")",
"if",
"form_class",
":",
"kwargs",
"[",
"'formfield_callback'",
"]",
"=",
"self",
".",
"formfield_for_dbfield",
"ret... | 40.909091 | 0.008696 |
def x(self, x):
"""Project x as y"""
if x is None:
return None
if self._force_vertical:
return super(HorizontalLogView, self).x(x)
return super(XLogView, self).y(x) | [
"def",
"x",
"(",
"self",
",",
"x",
")",
":",
"if",
"x",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"_force_vertical",
":",
"return",
"super",
"(",
"HorizontalLogView",
",",
"self",
")",
".",
"x",
"(",
"x",
")",
"return",
"super",
"(",
... | 30.571429 | 0.009091 |
def impact_table_pdf_extractor(impact_report, component_metadata):
"""Extracting impact summary of the impact layer.
For PDF generations
: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.Impac... | [
"def",
"impact_table_pdf_extractor",
"(",
"impact_report",
",",
"component_metadata",
")",
":",
"# QGIS Composer needed certain context to generate the output",
"# - Map Settings",
"# - Substitution maps",
"# - Element settings, such as icon for picture file or image source",
"context",
"=... | 32 | 0.000705 |
def scale(self, n):
""" Scale cluster to n workers
Parameters
----------
n: int
Target number of workers
Example
-------
>>> cluster.scale(10) # scale cluster to ten workers
See Also
--------
KubeCluster.scale_up
Kub... | [
"def",
"scale",
"(",
"self",
",",
"n",
")",
":",
"pods",
"=",
"self",
".",
"_cleanup_terminated_pods",
"(",
"self",
".",
"pods",
"(",
")",
")",
"if",
"n",
">=",
"len",
"(",
"pods",
")",
":",
"return",
"self",
".",
"scale_up",
"(",
"n",
",",
"pods... | 38.962963 | 0.000927 |
def generate_url_map(yaml_path=TOC_PATH) -> dict:
"""
Generates mapping from each URL to its previous and next URLs in the
textbook. The dictionary looks like:
{
'ch/10/some_page.html' : {
'prev': 'ch/09/foo.html',
'next': 'ch/10/bar.html',
},
...
}
... | [
"def",
"generate_url_map",
"(",
"yaml_path",
"=",
"TOC_PATH",
")",
"->",
"dict",
":",
"with",
"open",
"(",
"yaml_path",
")",
"as",
"f",
":",
"data",
"=",
"yaml",
".",
"load",
"(",
"f",
")",
"pipeline",
"=",
"[",
"t",
".",
"remove",
"(",
"_not_interna... | 24.625 | 0.001629 |
def pillar_format(ret, keys, value, expand_keys):
'''
Perform data formatting to be used as pillar data and
merge it with the current pillar data
'''
# if value is empty in Consul then it's None here - skip it
if value is None:
return ret
# If value is not None then it's a string
... | [
"def",
"pillar_format",
"(",
"ret",
",",
"keys",
",",
"value",
",",
"expand_keys",
")",
":",
"# if value is empty in Consul then it's None here - skip it",
"if",
"value",
"is",
"None",
":",
"return",
"ret",
"# If value is not None then it's a string",
"# YAML strips whitesp... | 28.625 | 0.001408 |
def create_signature(public_key, private_key, data, scheme):
"""
<Purpose>
Return a (signature, scheme) tuple, where the signature scheme is 'ed25519'
and is always generated by PyNaCl (i.e., 'nacl'). The signature returned
conforms to 'securesystemslib.formats.ED25519SIGNATURE_SCHEMA', and has the
... | [
"def",
"create_signature",
"(",
"public_key",
",",
"private_key",
",",
"data",
",",
"scheme",
")",
":",
"# Does 'public_key' have the correct format?",
"# This check will ensure 'public_key' conforms to",
"# 'securesystemslib.formats.ED25519PUBLIC_SCHEMA', which must have length 32",
"... | 35.326733 | 0.009542 |
def get_version(model_instance, version):
"""
try go load from the database one object with specific version
:param model_instance: instance in memory
:param version: version number
:return:
"""
version_field = get_version_fieldname(model_instance)
kwargs = {'pk': model_instance.pk,... | [
"def",
"get_version",
"(",
"model_instance",
",",
"version",
")",
":",
"version_field",
"=",
"get_version_fieldname",
"(",
"model_instance",
")",
"kwargs",
"=",
"{",
"'pk'",
":",
"model_instance",
".",
"pk",
",",
"version_field",
":",
"version",
"}",
"return",
... | 35.636364 | 0.002488 |
def derivative(self, point):
"""Return the derivative in ``point``.
The derivative of the gradient is often called the Hessian.
Parameters
----------
point : `domain` `element-like`
The point that the derivative should be taken in.
Returns
-------
... | [
"def",
"derivative",
"(",
"self",
",",
"point",
")",
":",
"return",
"NumericalDerivative",
"(",
"self",
",",
"point",
",",
"method",
"=",
"self",
".",
"method",
",",
"step",
"=",
"np",
".",
"sqrt",
"(",
"self",
".",
"step",
")",
")"
] | 33.361111 | 0.001618 |
def has_degradation_increases_activity(data: Dict) -> bool:
"""Check if the degradation of source causes activity of target."""
return part_has_modifier(data, SUBJECT, DEGRADATION) and part_has_modifier(data, OBJECT, ACTIVITY) | [
"def",
"has_degradation_increases_activity",
"(",
"data",
":",
"Dict",
")",
"->",
"bool",
":",
"return",
"part_has_modifier",
"(",
"data",
",",
"SUBJECT",
",",
"DEGRADATION",
")",
"and",
"part_has_modifier",
"(",
"data",
",",
"OBJECT",
",",
"ACTIVITY",
")"
] | 77.333333 | 0.008547 |
def get(self, id=None, project_id=None):
"""get."""
logs_limit = request.args.get('logs_limit', default=-1, type=int)
project = db.session.query(Project).filter_by(
id=project_id).first()
if project is None:
return jsonify({
'project': None,
... | [
"def",
"get",
"(",
"self",
",",
"id",
"=",
"None",
",",
"project_id",
"=",
"None",
")",
":",
"logs_limit",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'logs_limit'",
",",
"default",
"=",
"-",
"1",
",",
"type",
"=",
"int",
")",
"project",
"=",
... | 34.883333 | 0.000929 |
def visible_to_user(self, user):
"""Get a list of visible events for a given user (usually request.user).
These visible events will be those that either have no groups
assigned to them (and are therefore public) or those in which
the user is a member.
"""
return (Event... | [
"def",
"visible_to_user",
"(",
"self",
",",
"user",
")",
":",
"return",
"(",
"Event",
".",
"objects",
".",
"filter",
"(",
"approved",
"=",
"True",
")",
".",
"filter",
"(",
"Q",
"(",
"groups__in",
"=",
"user",
".",
"groups",
".",
"all",
"(",
")",
")... | 42.2 | 0.009281 |
def tokenize_middle_high_german_words(text):
"""Tokenizes MHG text"""
assert isinstance(text, str)
# As far as I know, hyphens were never used for compounds, so the tokenizer treats all hyphens as line-breaks
text = re.sub(r'-\n',r'-', text)
text = re.sub(r'\n', r' ', text)
text = re.sub(r'(?<=... | [
"def",
"tokenize_middle_high_german_words",
"(",
"text",
")",
":",
"assert",
"isinstance",
"(",
"text",
",",
"str",
")",
"# As far as I know, hyphens were never used for compounds, so the tokenizer treats all hyphens as line-breaks",
"text",
"=",
"re",
".",
"sub",
"(",
"r'-\\... | 38.153846 | 0.011811 |
def parse_info_frags(info_frags):
"""Import an info_frags.txt file and return a dictionary where each key
is a newly formed scaffold and each value is the list of bins and their
origin on the initial scaffolding.
"""
new_scaffolds = {}
with open(info_frags, "r") as info_frags_handle:
cu... | [
"def",
"parse_info_frags",
"(",
"info_frags",
")",
":",
"new_scaffolds",
"=",
"{",
"}",
"with",
"open",
"(",
"info_frags",
",",
"\"r\"",
")",
"as",
"info_frags_handle",
":",
"current_new_contig",
"=",
"None",
"for",
"line",
"in",
"info_frags_handle",
":",
"if"... | 37 | 0.000878 |
def progress(self, msg, onerror=None, sep='...', end='DONE', abrt='FAIL',
prog='.', excs=(Exception,), reraise=True):
""" Context manager for handling interactive prog indication
This context manager streamlines presenting banners and prog
indicators. To start the prog, pass ``... | [
"def",
"progress",
"(",
"self",
",",
"msg",
",",
"onerror",
"=",
"None",
",",
"sep",
"=",
"'...'",
",",
"end",
"=",
"'DONE'",
",",
"abrt",
"=",
"'FAIL'",
",",
"prog",
"=",
"'.'",
",",
"excs",
"=",
"(",
"Exception",
",",
")",
",",
"reraise",
"=",
... | 41.269841 | 0.001127 |
def task(ft):
"""
to create loading progress bar
"""
ft.pack(expand = True, fill = BOTH, side = TOP)
pb_hD = ttk.Progressbar(ft, orient = 'horizontal', mode = 'indeterminate')
pb_hD.pack(expand = True, fill = BOTH, side = TOP)
pb_hD.start(50)
ft.mainloop() | [
"def",
"task",
"(",
"ft",
")",
":",
"ft",
".",
"pack",
"(",
"expand",
"=",
"True",
",",
"fill",
"=",
"BOTH",
",",
"side",
"=",
"TOP",
")",
"pb_hD",
"=",
"ttk",
".",
"Progressbar",
"(",
"ft",
",",
"orient",
"=",
"'horizontal'",
",",
"mode",
"=",
... | 28.666667 | 0.093985 |
def newsDF(symbol, count=10, token='', version=''):
'''News about company
https://iexcloud.io/docs/api/#news
Continuous
Args:
symbol (string); Ticker to request
count (int): limit number of results
token (string); Access token
version (string); API version
Returns:... | [
"def",
"newsDF",
"(",
"symbol",
",",
"count",
"=",
"10",
",",
"token",
"=",
"''",
",",
"version",
"=",
"''",
")",
":",
"n",
"=",
"news",
"(",
"symbol",
",",
"count",
",",
"token",
",",
"version",
")",
"df",
"=",
"_newsToDF",
"(",
"n",
")",
"ret... | 23.166667 | 0.002304 |
def _assure_alert_policy(self, channel, destination):
"""Make sure an alert policy exists
Each policy will be a dict with the following keys:
-'index' - The policy index number
:returns: An iterable of currently configured alert policies
"""
# First we do a get PEF confi... | [
"def",
"_assure_alert_policy",
"(",
"self",
",",
"channel",
",",
"destination",
")",
":",
"# First we do a get PEF configuration parameters to get the count",
"# of entries. We have no guarantee that the meaningful data will",
"# be contiguous",
"rsp",
"=",
"self",
".",
"xraw_comm... | 46.441176 | 0.001241 |
def group_by(self, by):
"""
Return a new ``GroupBy`` object using this frame and the desired grouping columns.
The returned groups are sorted by the natural group-by column sort.
:param by: The columns to group on (either a single column name, or a list of column names, or
... | [
"def",
"group_by",
"(",
"self",
",",
"by",
")",
":",
"assert_is_type",
"(",
"by",
",",
"str",
",",
"int",
",",
"[",
"str",
",",
"int",
"]",
")",
"return",
"GroupBy",
"(",
"self",
",",
"by",
")"
] | 39.090909 | 0.009091 |
def point_stokes(self, context):
""" Return a stokes parameter array to montblanc """
stokes = np.empty(context.shape, context.dtype)
stokes[:,:,0] = 1
stokes[:,:,1:4] = 0
return stokes | [
"def",
"point_stokes",
"(",
"self",
",",
"context",
")",
":",
"stokes",
"=",
"np",
".",
"empty",
"(",
"context",
".",
"shape",
",",
"context",
".",
"dtype",
")",
"stokes",
"[",
":",
",",
":",
",",
"0",
"]",
"=",
"1",
"stokes",
"[",
":",
",",
":... | 36.666667 | 0.026667 |
def default_flaky_attributes(max_runs=None, min_passes=None, rerun_filter=None):
"""
Returns the default flaky attributes to set on a flaky test.
:param max_runs:
The value of the FlakyNames.MAX_RUNS attribute to use.
:type max_runs:
`int`
:param min_passes:
The value of the... | [
"def",
"default_flaky_attributes",
"(",
"max_runs",
"=",
"None",
",",
"min_passes",
"=",
"None",
",",
"rerun_filter",
"=",
"None",
")",
":",
"if",
"max_runs",
"is",
"None",
":",
"max_runs",
"=",
"2",
"if",
"min_passes",
"is",
"None",
":",
"min_passes",
"="... | 30.702703 | 0.001706 |
def collect_split_adjustments(self,
adjustments_for_sid,
requested_qtr_data,
dates,
sid,
sid_idx,
sid_estimates,
... | [
"def",
"collect_split_adjustments",
"(",
"self",
",",
"adjustments_for_sid",
",",
"requested_qtr_data",
",",
"dates",
",",
"sid",
",",
"sid_idx",
",",
"sid_estimates",
",",
"split_adjusted_asof_idx",
",",
"pre_adjustments",
",",
"post_adjustments",
",",
"requested_split... | 48.398438 | 0.001898 |
def chain_2(d2f_dg2, dg_dx, df_dg, d2g_dx2):
"""
Generic chaining function for second derivative
.. math::
\\frac{d^{2}(f . g)}{dx^{2}} = \\frac{d^{2}f}{dg^{2}}(\\frac{dg}{dx})^{2} + \\frac{df}{dg}\\frac{d^{2}g}{dx^{2}}
"""
if np.all(dg_dx==1.) and np.all(d2g_dx2 == 0):
return d2f_d... | [
"def",
"chain_2",
"(",
"d2f_dg2",
",",
"dg_dx",
",",
"df_dg",
",",
"d2g_dx2",
")",
":",
"if",
"np",
".",
"all",
"(",
"dg_dx",
"==",
"1.",
")",
"and",
"np",
".",
"all",
"(",
"d2g_dx2",
"==",
"0",
")",
":",
"return",
"d2f_dg2",
"dg_dx_2",
"=",
"np"... | 36.5 | 0.008909 |
def convert(input, output):
'''
Run dcm2niix on input file
'''
dirname = os.path.dirname(output)
if not os.path.exists(dirname):
os.makedirs(dirname)
basename = os.path.basename(output)
basename = re.sub('.nii(.gz)?', '', basename)
dcm2niix = commons.which('dcm2niix')
cmd = [... | [
"def",
"convert",
"(",
"input",
",",
"output",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"output",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"... | 23.380952 | 0.001957 |
def get_still_seg_belonged(dt_str, seg_duration, fmt='%Y-%m-%d %H:%M:%S'):
"""
获取该时刻所属的非滑动时间片
:param dt_str: datetime string, eg: 2016-10-31 12:22:11
:param seg_duration: 时间片长度, unit: minute
:param fmt: datetime string format
:return:
"""
dt = time_util.str_to_datetime(dt_str, fmt)
m... | [
"def",
"get_still_seg_belonged",
"(",
"dt_str",
",",
"seg_duration",
",",
"fmt",
"=",
"'%Y-%m-%d %H:%M:%S'",
")",
":",
"dt",
"=",
"time_util",
".",
"str_to_datetime",
"(",
"dt_str",
",",
"fmt",
")",
"minutes_of_day",
"=",
"time_util",
".",
"get_minutes_of_day",
... | 38.25 | 0.002128 |
def generate_altered_fields(self):
"""
Injecting point. This is quite awkward, and i'm looking forward Django for having the logic
divided into smaller methods/functions for easier enhancement and substitution.
So far we're doing all the SQL magic in this method.
"""
resu... | [
"def",
"generate_altered_fields",
"(",
"self",
")",
":",
"result",
"=",
"super",
"(",
"MigrationAutodetector",
",",
"self",
")",
".",
"generate_altered_fields",
"(",
")",
"self",
".",
"generate_sql_changes",
"(",
")",
"return",
"result"
] | 48.333333 | 0.009029 |
def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE,
send_amount=0, format='bin'):
""" Builds the outputs for an OP_RETURN transaction.
"""
return [
# main output
{ "script_hex": make_op_return_script(data, format=format), "value": send_amoun... | [
"def",
"make_op_return_outputs",
"(",
"data",
",",
"inputs",
",",
"change_address",
",",
"fee",
"=",
"OP_RETURN_FEE",
",",
"send_amount",
"=",
"0",
",",
"format",
"=",
"'bin'",
")",
":",
"return",
"[",
"# main output",
"{",
"\"script_hex\"",
":",
"make_op_retu... | 40.833333 | 0.011976 |
def to_int(self, *cols, **kwargs):
"""
Convert some column values to integers
:param \*cols: names of the colums
:type \*cols: str, at least one
:param \*\*kwargs: keyword arguments for ``pd.to_numeric``
:type \*\*kwargs: optional
:example: ``ds.to_int("mycol1",... | [
"def",
"to_int",
"(",
"self",
",",
"*",
"cols",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"for",
"col",
"in",
"cols",
":",
"self",
".",
"df",
"[",
"col",
"]",
"=",
"pd",
".",
"to_numeric",
"(",
"self",
".",
"df",
"[",
"col",
"]",
",",
... | 34.888889 | 0.012403 |
def last_commit_msg(self) -> str:
"""
:return: last commit message
:rtype: str
"""
last_msg: str = self.latest_commit().message.rstrip()
LOGGER.debug('last msg: %s', last_msg)
return last_msg | [
"def",
"last_commit_msg",
"(",
"self",
")",
"->",
"str",
":",
"last_msg",
":",
"str",
"=",
"self",
".",
"latest_commit",
"(",
")",
".",
"message",
".",
"rstrip",
"(",
")",
"LOGGER",
".",
"debug",
"(",
"'last msg: %s'",
",",
"last_msg",
")",
"return",
"... | 30 | 0.008097 |
def p_expression_Xor(self, p):
'expression : expression XOR expression'
p[0] = Xor(p[1], p[3], lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_expression_Xor",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"Xor",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",... | 41 | 0.011976 |
def seen_tasks(self):
"""Shows a list of seen task types."""
print('\n'.join(self._stub.seen_tasks(clearly_pb2.Empty()).task_types)) | [
"def",
"seen_tasks",
"(",
"self",
")",
":",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"self",
".",
"_stub",
".",
"seen_tasks",
"(",
"clearly_pb2",
".",
"Empty",
"(",
")",
")",
".",
"task_types",
")",
")"
] | 48.666667 | 0.013514 |
def convert_to_picos(sdp, duplicate_moment_matrix=False):
"""Convert an SDP relaxation to a PICOS problem such that the exported
.dat-s file is extremely sparse, there is not penalty imposed in terms of
SDP variables or number of constraints. This conversion can be used for
imposing extra constraints on... | [
"def",
"convert_to_picos",
"(",
"sdp",
",",
"duplicate_moment_matrix",
"=",
"False",
")",
":",
"import",
"picos",
"as",
"pic",
"import",
"cvxopt",
"as",
"cvx",
"P",
"=",
"pic",
".",
"Problem",
"(",
"verbose",
"=",
"sdp",
".",
"verbose",
")",
"block_size",
... | 42.303371 | 0.001298 |
def resources(self, type_=None, title=None, **kwargs):
"""Get all resources of this node or all resources of the specified
type. Additional arguments may also be specified that will be passed
to the query function.
"""
if type_ is None:
resources = self.__api.resource... | [
"def",
"resources",
"(",
"self",
",",
"type_",
"=",
"None",
",",
"title",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"type_",
"is",
"None",
":",
"resources",
"=",
"self",
".",
"__api",
".",
"resources",
"(",
"query",
"=",
"EqualsOperator",... | 39.571429 | 0.00235 |
def dump_cookie(key, value='', max_age=None, expires=None, path='/',
domain=None, secure=False, httponly=False,
charset='utf-8', sync_expires=True):
"""Creates a new Set-Cookie header without the ``Set-Cookie`` prefix
The parameters are the same as in the cookie Morsel object in ... | [
"def",
"dump_cookie",
"(",
"key",
",",
"value",
"=",
"''",
",",
"max_age",
"=",
"None",
",",
"expires",
"=",
"None",
",",
"path",
"=",
"'/'",
",",
"domain",
"=",
"None",
",",
"secure",
"=",
"False",
",",
"httponly",
"=",
"False",
",",
"charset",
"=... | 43.885057 | 0.000256 |
def main() -> None:
"""
Command-line handler for the ``pause_process_by_disk_space`` tool.
Use the ``--help`` option for help.
"""
parser = ArgumentParser(
description="Pauses and resumes a process by disk space; LINUX ONLY."
)
parser.add_argument(
"process_id", type=int,
... | [
"def",
"main",
"(",
")",
"->",
"None",
":",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"\"Pauses and resumes a process by disk space; LINUX ONLY.\"",
")",
"parser",
".",
"add_argument",
"(",
"\"process_id\"",
",",
"type",
"=",
"int",
",",
"help",
"=... | 35.642857 | 0.000325 |
def has_key(self, key):
"""Case insensitive test whether 'key' exists."""
k = self._lowerOrReturn(key)
return k in self.data | [
"def",
"has_key",
"(",
"self",
",",
"key",
")",
":",
"k",
"=",
"self",
".",
"_lowerOrReturn",
"(",
"key",
")",
"return",
"k",
"in",
"self",
".",
"data"
] | 36.25 | 0.013514 |
def init(log_level=ERROR):
'''
Enables explicit relative import in sub-modules when ran as __main__
:param log_level: module's inner logger level (equivalent to logging pkg)
'''
global _initialized
if _initialized:
return
else:
_initialized = True
# find caller's frame
... | [
"def",
"init",
"(",
"log_level",
"=",
"ERROR",
")",
":",
"global",
"_initialized",
"if",
"_initialized",
":",
"return",
"else",
":",
"_initialized",
"=",
"True",
"# find caller's frame",
"frame",
"=",
"currentframe",
"(",
")",
"# go 1 frame back to find who imported... | 28.6 | 0.002257 |
def update(ctx, opts, owner_repo_identifier, show_tokens, name, token):
"""
Update (set) a entitlement in a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
... | [
"def",
"update",
"(",
"ctx",
",",
"opts",
",",
"owner_repo_identifier",
",",
"show_tokens",
",",
"name",
",",
"token",
")",
":",
"owner",
",",
"repo",
",",
"identifier",
"=",
"owner_repo_identifier",
"# Use stderr for messages if the output is something else (e.g. # JS... | 32.2 | 0.00067 |
def step(self) -> None:
"""
Runs a single event of the simulation.
"""
event = heappop(self._events)
self._ts_now = event.timestamp or self._ts_now
event.execute(self) | [
"def",
"step",
"(",
"self",
")",
"->",
"None",
":",
"event",
"=",
"heappop",
"(",
"self",
".",
"_events",
")",
"self",
".",
"_ts_now",
"=",
"event",
".",
"timestamp",
"or",
"self",
".",
"_ts_now",
"event",
".",
"execute",
"(",
"self",
")"
] | 29.857143 | 0.009302 |
def get_attribute_mappings(self):
"""Get a dictionary of mappings between vertices and enumerated attributes.
:return: Dictionary of mappings between vertices and enumerated attributes.
"""
att_ind_start = len(self.graph.vs)
att_mappings = defaultdict(list)
att_ind_end =... | [
"def",
"get_attribute_mappings",
"(",
"self",
")",
":",
"att_ind_start",
"=",
"len",
"(",
"self",
".",
"graph",
".",
"vs",
")",
"att_mappings",
"=",
"defaultdict",
"(",
"list",
")",
"att_ind_end",
"=",
"self",
".",
"_add_differential_expression_attributes",
"(",... | 50.545455 | 0.008834 |
def with_deprecation_warning(fn, extra_message=''):
"""Wraps the function and prints a warn-once (per `extra_message`) warning."""
def new_fn(*args, **kwargs):
if extra_message not in _DONE_WARN:
tf.logging.warning(
'Sonnet nest is deprecated. Please use '
'tf.contrib.framework.nest in... | [
"def",
"with_deprecation_warning",
"(",
"fn",
",",
"extra_message",
"=",
"''",
")",
":",
"def",
"new_fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"extra_message",
"not",
"in",
"_DONE_WARN",
":",
"tf",
".",
"logging",
".",
"warning",
... | 36.416667 | 0.015625 |
def retrieve_github_cache(self, github_path, version, cache_dir, token):
'''
Retrieves a cache of the layouts git repo from GitHub
@param github_path: Location of the git repo on GitHub (e.g. hid-io/layouts)
@param version: git reference for the version to download (e.g. master)
... | [
"def",
"retrieve_github_cache",
"(",
"self",
",",
"github_path",
",",
"version",
",",
"cache_dir",
",",
"token",
")",
":",
"# Check for environment variable Github token",
"token",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'GITHUB_APIKEY'",
",",
"None",
")",
... | 41.483333 | 0.001962 |
def run(self):
"""Run this section and print out information."""
grouping = Grouping(group_by=lambda x: (x.namespace, x.operation,
x.pattern))
logfile = self.mloginfo.logfile
if logfile.start and logfile.end:
progress_start = s... | [
"def",
"run",
"(",
"self",
")",
":",
"grouping",
"=",
"Grouping",
"(",
"group_by",
"=",
"lambda",
"x",
":",
"(",
"x",
".",
"namespace",
",",
"x",
".",
"operation",
",",
"x",
".",
"pattern",
")",
")",
"logfile",
"=",
"self",
".",
"mloginfo",
".",
... | 40.172414 | 0.000559 |
def id(self, sort_ops=True):
"""
Returns an identifier string for the PauliTerm (ignoring the coefficient).
Don't use this to compare terms. This function will not work with qubits that
aren't sortable.
:param sort_ops: Whether to sort operations by qubit. This is True by defau... | [
"def",
"id",
"(",
"self",
",",
"sort_ops",
"=",
"True",
")",
":",
"if",
"len",
"(",
"self",
".",
"_ops",
")",
"==",
"0",
"and",
"not",
"sort_ops",
":",
"# This is nefariously backwards-compatibility breaking. There's potentially",
"# lots of code floating around that ... | 54.428571 | 0.009026 |
def single_feature_fit(self, feature):
"""Get the log2 bayes factor of the fit for each modality"""
if np.isfinite(feature).sum() == 0:
series = pd.Series(index=MODALITY_ORDER)
else:
logbf_one_param = pd.Series(
{k: v.logsumexp_logliks(feature) for
... | [
"def",
"single_feature_fit",
"(",
"self",
",",
"feature",
")",
":",
"if",
"np",
".",
"isfinite",
"(",
"feature",
")",
".",
"sum",
"(",
")",
"==",
"0",
":",
"series",
"=",
"pd",
".",
"Series",
"(",
"index",
"=",
"MODALITY_ORDER",
")",
"else",
":",
"... | 43.571429 | 0.002139 |
def _render(template=None, filepath=None, context=None, at_paths=None,
at_encoding=anytemplate.compat.ENCODING, at_engine=None,
at_ask_missing=False, at_cls_args=None, _at_usr_tmpl=None,
**kwargs):
"""
Compile and render given template string and return the result string.
... | [
"def",
"_render",
"(",
"template",
"=",
"None",
",",
"filepath",
"=",
"None",
",",
"context",
"=",
"None",
",",
"at_paths",
"=",
"None",
",",
"at_encoding",
"=",
"anytemplate",
".",
"compat",
".",
"ENCODING",
",",
"at_engine",
"=",
"None",
",",
"at_ask_m... | 43.775862 | 0.000385 |
def normalize(ctx, text):
"""
Normalize text or piped input.
Normalize text passed as an argument to this command using
the specified config (default values if --config option is
not used).
Pipes can be used along this command to process the output
of another cli. This is the default behav... | [
"def",
"normalize",
"(",
"ctx",
",",
"text",
")",
":",
"if",
"text",
":",
"click",
".",
"echo",
"(",
"ctx",
".",
"obj",
"[",
"'cucco'",
"]",
".",
"normalize",
"(",
"text",
")",
")",
"else",
":",
"for",
"line",
"in",
"sys",
".",
"stdin",
":",
"c... | 29.941176 | 0.001905 |
def socketio(request):
"""
Socket.IO handler - maintains the lifecycle of a Socket.IO
request, sending the each of the events. Also handles
adding/removing request/socket pairs to the CLIENTS dict
which is used for sending on_finish events when the server
stops.
"""
context = {}
sock... | [
"def",
"socketio",
"(",
"request",
")",
":",
"context",
"=",
"{",
"}",
"socket",
"=",
"SocketIOChannelProxy",
"(",
"request",
".",
"environ",
"[",
"\"socketio\"",
"]",
")",
"client_start",
"(",
"request",
",",
"socket",
",",
"context",
")",
"try",
":",
"... | 46.264151 | 0.000799 |
def sub_tag(self, path, follow=True):
"""Returns direct sub-record with given tag name or None.
Path can be a simple tag name, in which case the first direct
sub-record of this record with the matching tag is returned. Path
can also consist of several tags separated by slashes, in that ... | [
"def",
"sub_tag",
"(",
"self",
",",
"path",
",",
"follow",
"=",
"True",
")",
":",
"tags",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"rec",
"=",
"self",
"for",
"tag",
"in",
"tags",
":",
"recs",
"=",
"[",
"x",
"for",
"x",
"in",
"(",
"rec",
".... | 40.592593 | 0.001783 |
def get_metric_group_definitions(self):
"""
Get the faked metric group definitions for this context object
that are to be returned from its create operation.
If a 'metric-groups' property had been specified for this context,
only those faked metric group definitions of its manag... | [
"def",
"get_metric_group_definitions",
"(",
"self",
")",
":",
"group_names",
"=",
"self",
".",
"properties",
".",
"get",
"(",
"'metric-groups'",
",",
"None",
")",
"if",
"not",
"group_names",
":",
"group_names",
"=",
"self",
".",
"manager",
".",
"get_metric_gro... | 43.230769 | 0.001741 |
def _load_json_url(self, url):
'''dict: Return the JSON at the local path or URL as a dict.'''
res = requests.get(url)
res.raise_for_status()
return res.json() | [
"def",
"_load_json_url",
"(",
"self",
",",
"url",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"res",
".",
"raise_for_status",
"(",
")",
"return",
"res",
".",
"json",
"(",
")"
] | 31.166667 | 0.010417 |
def kwargs_warn_until(kwargs,
version,
category=DeprecationWarning,
stacklevel=None,
_version_info_=None,
_dont_call_warnings=False):
'''
Helper function to raise a warning (by default, a ``DeprecationW... | [
"def",
"kwargs_warn_until",
"(",
"kwargs",
",",
"version",
",",
"category",
"=",
"DeprecationWarning",
",",
"stacklevel",
"=",
"None",
",",
"_version_info_",
"=",
"None",
",",
"_dont_call_warnings",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"vers... | 48.926471 | 0.000589 |
def map_return(self):
"""Perform a function on every item and return a list of yield values."""
with Pool(self.cpu_count) as pool:
vals = pool.map(self._func, self._iterable)
pool.close()
return vals | [
"def",
"map_return",
"(",
"self",
")",
":",
"with",
"Pool",
"(",
"self",
".",
"cpu_count",
")",
"as",
"pool",
":",
"vals",
"=",
"pool",
".",
"map",
"(",
"self",
".",
"_func",
",",
"self",
".",
"_iterable",
")",
"pool",
".",
"close",
"(",
")",
"re... | 41 | 0.011952 |
def run_toy_SGLD(gpu_id=None):
"""Run SGLD on toy dataset"""
X, Y, X_test, Y_test = load_toy()
minibatch_size = 1
teacher_noise_precision = 1.0 / 9.0
net = get_toy_sym(True, teacher_noise_precision)
data_shape = (minibatch_size,) + X.shape[1::]
data_inputs = {'data': nd.zeros(data_shape, ctx... | [
"def",
"run_toy_SGLD",
"(",
"gpu_id",
"=",
"None",
")",
":",
"X",
",",
"Y",
",",
"X_test",
",",
"Y_test",
"=",
"load_toy",
"(",
")",
"minibatch_size",
"=",
"1",
"teacher_noise_precision",
"=",
"1.0",
"/",
"9.0",
"net",
"=",
"get_toy_sym",
"(",
"True",
... | 45.653846 | 0.002475 |
def _start_collective_solver(self, state):
'''
Determines who from all the monitors monitoring this agent should
resolve the issue.
'''
own_address = state.agent.get_own_address()
monitors = [IRecipient(x) for x in state.descriptor.partners
if x.role =... | [
"def",
"_start_collective_solver",
"(",
"self",
",",
"state",
")",
":",
"own_address",
"=",
"state",
".",
"agent",
".",
"get_own_address",
"(",
")",
"monitors",
"=",
"[",
"IRecipient",
"(",
"x",
")",
"for",
"x",
"in",
"state",
".",
"descriptor",
".",
"pa... | 46.176471 | 0.002497 |
def find_local_peaks(sig, radius):
"""
Find all local peaks in a signal. A sample is a local peak if it is
the largest value within the <radius> samples on its left and right.
In cases where it shares the max value with nearby samples, the
middle sample is classified as the local peak.
Paramet... | [
"def",
"find_local_peaks",
"(",
"sig",
",",
"radius",
")",
":",
"# TODO: Fix flat mountain scenarios.",
"if",
"np",
".",
"min",
"(",
"sig",
")",
"==",
"np",
".",
"max",
"(",
"sig",
")",
":",
"return",
"np",
".",
"empty",
"(",
"0",
")",
"peak_inds",
"="... | 24.4 | 0.000876 |
def precmd(self, line):
"""Parse the command on the given line.
:param line: The raw input line
:type line: str
"""
line = line.lower()
if line == 'exit' or line == 'help':
return line
try:
parts = stmt.p... | [
"def",
"precmd",
"(",
"self",
",",
"line",
")",
":",
"line",
"=",
"line",
".",
"lower",
"(",
")",
"if",
"line",
"==",
"'exit'",
"or",
"line",
"==",
"'help'",
":",
"return",
"line",
"try",
":",
"parts",
"=",
"stmt",
".",
"parseString",
"(",
"line",
... | 23.217391 | 0.01259 |
def _validateParamsFor_validateChoice(choices, blank=False, strip=None, allowlistRegexes=None, blocklistRegexes=None,
numbered=False, lettered=False, caseSensitive=False, excMsg=None):
"""Raises PySimpleValidateException if the arguments are invalid. This is called by
the validateChoice() fun... | [
"def",
"_validateParamsFor_validateChoice",
"(",
"choices",
",",
"blank",
"=",
"False",
",",
"strip",
"=",
"None",
",",
"allowlistRegexes",
"=",
"None",
",",
"blocklistRegexes",
"=",
"None",
",",
"numbered",
"=",
"False",
",",
"lettered",
"=",
"False",
",",
... | 51.972222 | 0.009444 |
def numexp_action(self, text, loc, num):
"""Code executed after recognising a numexp expression (something +|- something)"""
exshared.setpos(loc, text)
if DEBUG > 0:
print("NUM_EXP:",num)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
... | [
"def",
"numexp_action",
"(",
"self",
",",
"text",
",",
"loc",
",",
"num",
")",
":",
"exshared",
".",
"setpos",
"(",
"loc",
",",
"text",
")",
"if",
"DEBUG",
">",
"0",
":",
"print",
"(",
"\"NUM_EXP:\"",
",",
"num",
")",
"if",
"DEBUG",
"==",
"2",
":... | 44.125 | 0.012483 |
def get_bg(self, key=None, ret_attrs=False):
"""Get the background data
Parameters
----------
key: None or str
A user-defined key that identifies the background data.
Examples are "data" for experimental data, or "fit"
for an estimated background corr... | [
"def",
"get_bg",
"(",
"self",
",",
"key",
"=",
"None",
",",
"ret_attrs",
"=",
"False",
")",
":",
"if",
"key",
"is",
"None",
":",
"if",
"ret_attrs",
":",
"raise",
"ValueError",
"(",
"\"No attributes for combined background!\"",
")",
"return",
"self",
".",
"... | 40.771429 | 0.001369 |
def get_system_users():
"""Return currently connected users as a list of namedtuples."""
retlist = []
rawlist = _psutil_linux.get_system_users()
for item in rawlist:
user, tty, hostname, tstamp, user_process = item
# XXX the underlying C function includes entries about
# system b... | [
"def",
"get_system_users",
"(",
")",
":",
"retlist",
"=",
"[",
"]",
"rawlist",
"=",
"_psutil_linux",
".",
"get_system_users",
"(",
")",
"for",
"item",
"in",
"rawlist",
":",
"user",
",",
"tty",
",",
"hostname",
",",
"tstamp",
",",
"user_process",
"=",
"it... | 37.6875 | 0.001618 |
def iter_encode(self, boundary, blocksize=4096):
"""Yields the encoding of this parameter
If self.fileobj is set, then blocks of ``blocksize`` bytes are read and
yielded."""
total = self.get_size(boundary)
current = 0
if self.value is not None:
block = self.en... | [
"def",
"iter_encode",
"(",
"self",
",",
"boundary",
",",
"blocksize",
"=",
"4096",
")",
":",
"total",
"=",
"self",
".",
"get_size",
"(",
"boundary",
")",
"current",
"=",
"0",
"if",
"self",
".",
"value",
"is",
"not",
"None",
":",
"block",
"=",
"self",... | 39 | 0.001317 |
def dlogpdf_dlink(self, link_f, y, Y_metadata=None):
"""
derivative of logpdf wrt link_f param
.. math::
:param link_f: latent variables link(f)
:type link_f: Nx1 array
:param y: data
:type y: Nx1 array
:param Y_metadata: includes censoring information in... | [
"def",
"dlogpdf_dlink",
"(",
"self",
",",
"link_f",
",",
"y",
",",
"Y_metadata",
"=",
"None",
")",
":",
"assert",
"np",
".",
"atleast_1d",
"(",
"link_f",
")",
".",
"shape",
"==",
"np",
".",
"atleast_1d",
"(",
"y",
")",
".",
"shape",
"c",
"=",
"np",... | 42.928571 | 0.008137 |
def dump_crl(type, crl):
"""
Dump a certificate revocation list to a buffer.
:param type: The file type (one of ``FILETYPE_PEM``, ``FILETYPE_ASN1``, or
``FILETYPE_TEXT``).
:param CRL crl: The CRL to dump.
:return: The buffer with the CRL.
:rtype: bytes
"""
bio = _new_mem_buf()
... | [
"def",
"dump_crl",
"(",
"type",
",",
"crl",
")",
":",
"bio",
"=",
"_new_mem_buf",
"(",
")",
"if",
"type",
"==",
"FILETYPE_PEM",
":",
"ret",
"=",
"_lib",
".",
"PEM_write_bio_X509_CRL",
"(",
"bio",
",",
"crl",
".",
"_crl",
")",
"elif",
"type",
"==",
"F... | 28.115385 | 0.001323 |
def _connect_to_gateway(self):
"""
Open connection to SSH gateway
- First try with all keys loaded from an SSH agent (if allowed)
- Then with those passed directly or read from ~/.ssh/config
- As last resort, try with a provided password
"""
for key in self.ssh... | [
"def",
"_connect_to_gateway",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"ssh_pkeys",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Trying to log in with key: {0}'",
".",
"format",
"(",
"hexlify",
"(",
"key",
".",
"get_fingerprint",
"(",
")",... | 46.722222 | 0.001165 |
def _add(self, other):
"""Add a interval to the underlying IntervalSet data store. This does not perform any tests as we assume that
any requirements have already been checked and that this function is being called by an internal function such
as union(), intersection() or add().
:param ... | [
"def",
"_add",
"(",
"self",
",",
"other",
")",
":",
"if",
"len",
"(",
"[",
"interval",
"for",
"interval",
"in",
"self",
"if",
"other",
"in",
"interval",
"]",
")",
">",
"0",
":",
"# if other is already represented",
"return",
"# remove any intervals which are f... | 60.5 | 0.008141 |
def cub200_iterator(data_path, batch_k, batch_size, data_shape):
"""Return training and testing iterator for the CUB200-2011 dataset."""
return (CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=True),
CUB200Iter(data_path, batch_k, batch_size, data_shape, is_train=False)) | [
"def",
"cub200_iterator",
"(",
"data_path",
",",
"batch_k",
",",
"batch_size",
",",
"data_shape",
")",
":",
"return",
"(",
"CUB200Iter",
"(",
"data_path",
",",
"batch_k",
",",
"batch_size",
",",
"data_shape",
",",
"is_train",
"=",
"True",
")",
",",
"CUB200It... | 76 | 0.009772 |
def local_attention_2d(q,
k,
v,
query_shape=(8, 16),
memory_flange=(8, 16),
name=None):
"""Strided block local self-attention.
The 2-D sequence is divided into 2-D blocks of shape query_shape. Attenti... | [
"def",
"local_attention_2d",
"(",
"q",
",",
"k",
",",
"v",
",",
"query_shape",
"=",
"(",
"8",
",",
"16",
")",
",",
"memory_flange",
"=",
"(",
"8",
",",
"16",
")",
",",
"name",
"=",
"None",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"name... | 38.695652 | 0.001826 |
def setup_components(self, builder, configuration):
"""Apply component level configuration defaults to the global config and run setup methods on the components
registering and setting up any child components generated in the process.
Parameters
----------
builder:
I... | [
"def",
"setup_components",
"(",
"self",
",",
"builder",
",",
"configuration",
")",
":",
"self",
".",
"_managers",
"=",
"_setup_components",
"(",
"builder",
",",
"self",
".",
"_managers",
",",
"configuration",
")",
"self",
".",
"_components",
"=",
"_setup_compo... | 46.076923 | 0.00982 |
def set_nodes_vlan(site, nodes, interface, vlan_id):
"""Set the interface of the nodes in a specific vlan.
It is assumed that the same interface name is available on the node.
Args:
site(str): site to consider
nodes(list): nodes to consider
interface(str): the network interface to ... | [
"def",
"set_nodes_vlan",
"(",
"site",
",",
"nodes",
",",
"interface",
",",
"vlan_id",
")",
":",
"def",
"_to_network_address",
"(",
"host",
")",
":",
"\"\"\"Translate a host to a network address\n e.g:\n paranoia-20.rennes.grid5000.fr -> paranoia-20-eth2.rennes.grid5... | 36.391304 | 0.001164 |
def from_json(cls, input_json: str) -> 'NistBeaconValue':
"""
Convert a string of JSON which represents a NIST randomness beacon
value into a 'NistBeaconValue' object.
:param input_json: JSON to build a 'Nist RandomnessBeaconValue' from
:return: A 'NistBeaconValue' object, 'None... | [
"def",
"from_json",
"(",
"cls",
",",
"input_json",
":",
"str",
")",
"->",
"'NistBeaconValue'",
":",
"try",
":",
"data_dict",
"=",
"json",
".",
"loads",
"(",
"input_json",
")",
"except",
"ValueError",
":",
"return",
"None",
"# Our required values are \"must haves... | 37.875 | 0.001072 |
def load_texture(self, file_path):
"""Generate our sprite's surface by loading the specified image from disk.
Note that this automatically centers the origin."""
self.image = pygame.image.load(file_path)
self.apply_texture(self.image) | [
"def",
"load_texture",
"(",
"self",
",",
"file_path",
")",
":",
"self",
".",
"image",
"=",
"pygame",
".",
"image",
".",
"load",
"(",
"file_path",
")",
"self",
".",
"apply_texture",
"(",
"self",
".",
"image",
")"
] | 52.6 | 0.011236 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.