Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
DatabaseAPI20Test._populate | (self) | Return a list of sql commands to setup the DB for the fetch
tests.
| Return a list of sql commands to setup the DB for the fetch
tests.
| def _populate(self):
''' Return a list of sql commands to setup the DB for the fetch
tests.
'''
populate = [
"insert into %sbooze values ('%s')" % (self.table_prefix,s)
for s in self.samples
]
return populate | [
"def",
"_populate",
"(",
"self",
")",
":",
"populate",
"=",
"[",
"\"insert into %sbooze values ('%s')\"",
"%",
"(",
"self",
".",
"table_prefix",
",",
"s",
")",
"for",
"s",
"in",
"self",
".",
"samples",
"]",
"return",
"populate"
] | [
548,
4
] | [
556,
23
] | python | en | ['en', 'en', 'en'] | True |
DatabaseAPI20Test.help_nextset_setUp | (self,cur) | Should create a procedure called deleteme
that returns two result sets, first the
number of rows in booze then "name from booze"
| Should create a procedure called deleteme
that returns two result sets, first the
number of rows in booze then "name from booze"
| def help_nextset_setUp(self,cur):
''' Should create a procedure called deleteme
that returns two result sets, first the
number of rows in booze then "name from booze"
'''
raise NotImplementedError('Helper not implemented') | [
"def",
"help_nextset_setUp",
"(",
"self",
",",
"cur",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Helper not implemented'",
")"
] | [
722,
4
] | [
727,
59
] | python | en | ['en', 'co', 'en'] | True |
DatabaseAPI20Test.help_nextset_tearDown | (self,cur) | If cleaning up is needed after nextSetTest | If cleaning up is needed after nextSetTest | def help_nextset_tearDown(self,cur):
'If cleaning up is needed after nextSetTest'
raise NotImplementedError('Helper not implemented') | [
"def",
"help_nextset_tearDown",
"(",
"self",
",",
"cur",
")",
":",
"raise",
"NotImplementedError",
"(",
"'Helper not implemented'",
")"
] | [
737,
4
] | [
739,
59
] | python | en | ['en', 'en', 'en'] | True |
f | (x) | Noise free objective. | Noise free objective. | def f(x):
"""Noise free objective."""
return np.sin(10 * x) * x * 100 | [
"def",
"f",
"(",
"x",
")",
":",
"return",
"np",
".",
"sin",
"(",
"10",
"*",
"x",
")",
"*",
"x",
"*",
"100"
] | [
23,
0
] | [
26,
35
] | python | en | ['en', 'en', 'en'] | True |
StatelessServer.run | (self) |
Runs the asyncio event loop with our handler loop.
|
Runs the asyncio event loop with our handler loop.
| def run(self):
"""
Runs the asyncio event loop with our handler loop.
"""
event_loop = asyncio.get_event_loop()
asyncio.ensure_future(self.application_checker())
try:
event_loop.run_until_complete(self.handle())
except KeyboardInterrupt:
lo... | [
"def",
"run",
"(",
"self",
")",
":",
"event_loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"application_checker",
"(",
")",
")",
"try",
":",
"event_loop",
".",
"run_until_complete",
"(",
"self",
"... | [
54,
4
] | [
63,
58
] | python | en | ['en', 'error', 'th'] | False |
StatelessServer.application_send | (self, scope, message) |
Receives outbound sends from applications and handles them.
|
Receives outbound sends from applications and handles them.
| async def application_send(self, scope, message):
"""
Receives outbound sends from applications and handles them.
"""
raise NotImplementedError("You must implement application_send()") | [
"async",
"def",
"application_send",
"(",
"self",
",",
"scope",
",",
"message",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"You must implement application_send()\"",
")"
] | [
68,
4
] | [
72,
74
] | python | en | ['en', 'error', 'th'] | False |
StatelessServer.get_or_create_application_instance | (self, scope_id, scope) |
Creates an application instance and returns its queue.
|
Creates an application instance and returns its queue.
| def get_or_create_application_instance(self, scope_id, scope):
"""
Creates an application instance and returns its queue.
"""
if scope_id in self.application_instances:
self.application_instances[scope_id]["last_used"] = time.time()
return self.application_instanc... | [
"def",
"get_or_create_application_instance",
"(",
"self",
",",
"scope_id",
",",
"scope",
")",
":",
"if",
"scope_id",
"in",
"self",
".",
"application_instances",
":",
"self",
".",
"application_instances",
"[",
"scope_id",
"]",
"[",
"\"last_used\"",
"]",
"=",
"tim... | [
76,
4
] | [
103,
26
] | python | en | ['en', 'error', 'th'] | False |
StatelessServer.delete_oldest_application_instance | (self) |
Finds and deletes the oldest application instance
|
Finds and deletes the oldest application instance
| def delete_oldest_application_instance(self):
"""
Finds and deletes the oldest application instance
"""
oldest_time = min(
details["last_used"] for details in self.application_instances.values()
)
for scope_id, details in self.application_instances.items():
... | [
"def",
"delete_oldest_application_instance",
"(",
"self",
")",
":",
"oldest_time",
"=",
"min",
"(",
"details",
"[",
"\"last_used\"",
"]",
"for",
"details",
"in",
"self",
".",
"application_instances",
".",
"values",
"(",
")",
")",
"for",
"scope_id",
",",
"detai... | [
105,
4
] | [
117,
22
] | python | en | ['en', 'error', 'th'] | False |
StatelessServer.delete_application_instance | (self, scope_id) |
Removes an application instance (makes sure its task is stopped,
then removes it from the current set)
|
Removes an application instance (makes sure its task is stopped,
then removes it from the current set)
| def delete_application_instance(self, scope_id):
"""
Removes an application instance (makes sure its task is stopped,
then removes it from the current set)
"""
details = self.application_instances[scope_id]
del self.application_instances[scope_id]
if not details["... | [
"def",
"delete_application_instance",
"(",
"self",
",",
"scope_id",
")",
":",
"details",
"=",
"self",
".",
"application_instances",
"[",
"scope_id",
"]",
"del",
"self",
".",
"application_instances",
"[",
"scope_id",
"]",
"if",
"not",
"details",
"[",
"\"future\""... | [
119,
4
] | [
127,
38
] | python | en | ['en', 'error', 'th'] | False |
StatelessServer.application_checker | (self) |
Goes through the set of current application instance Futures and cleans up
any that are done/prints exceptions for any that errored.
|
Goes through the set of current application instance Futures and cleans up
any that are done/prints exceptions for any that errored.
| async def application_checker(self):
"""
Goes through the set of current application instance Futures and cleans up
any that are done/prints exceptions for any that errored.
"""
while True:
await asyncio.sleep(self.application_checker_interval)
for scope_i... | [
"async",
"def",
"application_checker",
"(",
"self",
")",
":",
"while",
"True",
":",
"await",
"asyncio",
".",
"sleep",
"(",
"self",
".",
"application_checker_interval",
")",
"for",
"scope_id",
",",
"details",
"in",
"list",
"(",
"self",
".",
"application_instanc... | [
129,
4
] | [
145,
28
] | python | en | ['en', 'error', 'th'] | False |
StatelessServer.application_exception | (self, exception, application_details) |
Called whenever an application coroutine has an exception.
|
Called whenever an application coroutine has an exception.
| async def application_exception(self, exception, application_details):
"""
Called whenever an application coroutine has an exception.
"""
logging.error(
"Exception inside application: %s\n%s%s",
exception,
"".join(traceback.format_tb(exception.__traceb... | [
"async",
"def",
"application_exception",
"(",
"self",
",",
"exception",
",",
"application_details",
")",
":",
"logging",
".",
"error",
"(",
"\"Exception inside application: %s\\n%s%s\"",
",",
"exception",
",",
"\"\"",
".",
"join",
"(",
"traceback",
".",
"format_tb",... | [
147,
4
] | [
156,
9
] | python | en | ['en', 'error', 'th'] | False |
upath | (path) |
Always return a unicode path.
|
Always return a unicode path.
| def upath(path):
"""
Always return a unicode path.
"""
if six.PY2 and not isinstance(path, six.text_type):
return path.decode(fs_encoding)
return path | [
"def",
"upath",
"(",
"path",
")",
":",
"if",
"six",
".",
"PY2",
"and",
"not",
"isinstance",
"(",
"path",
",",
"six",
".",
"text_type",
")",
":",
"return",
"path",
".",
"decode",
"(",
"fs_encoding",
")",
"return",
"path"
] | [
34,
0
] | [
40,
15
] | python | en | ['en', 'error', 'th'] | False |
npath | (path) |
Always return a native path, that is unicode on Python 3 and bytestring on
Python 2.
|
Always return a native path, that is unicode on Python 3 and bytestring on
Python 2.
| def npath(path):
"""
Always return a native path, that is unicode on Python 3 and bytestring on
Python 2.
"""
if six.PY2 and not isinstance(path, bytes):
return path.encode(fs_encoding)
return path | [
"def",
"npath",
"(",
"path",
")",
":",
"if",
"six",
".",
"PY2",
"and",
"not",
"isinstance",
"(",
"path",
",",
"bytes",
")",
":",
"return",
"path",
".",
"encode",
"(",
"fs_encoding",
")",
"return",
"path"
] | [
43,
0
] | [
50,
15
] | python | en | ['en', 'error', 'th'] | False |
safe_join | (base, *paths) |
Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path.
The final path must be located inside of the base path component (otherwise
a ValueError is raised).
|
Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path. | def safe_join(base, *paths):
"""
Joins one or more path components to the base path component intelligently.
Returns a normalized, absolute version of the final path.
The final path must be located inside of the base path component (otherwise
a ValueError is raised).
"""
base = force_text(b... | [
"def",
"safe_join",
"(",
"base",
",",
"*",
"paths",
")",
":",
"base",
"=",
"force_text",
"(",
"base",
")",
"paths",
"=",
"[",
"force_text",
"(",
"p",
")",
"for",
"p",
"in",
"paths",
"]",
"final_path",
"=",
"abspathu",
"(",
"join",
"(",
"base",
",",... | [
53,
0
] | [
78,
21
] | python | en | ['en', 'error', 'th'] | False |
symlinks_supported | () |
A function to check if creating symlinks are supported in the
host platform and/or if they are allowed to be created (e.g.
on Windows it requires admin permissions).
|
A function to check if creating symlinks are supported in the
host platform and/or if they are allowed to be created (e.g.
on Windows it requires admin permissions).
| def symlinks_supported():
"""
A function to check if creating symlinks are supported in the
host platform and/or if they are allowed to be created (e.g.
on Windows it requires admin permissions).
"""
tmpdir = tempfile.mkdtemp()
original_path = os.path.join(tmpdir, 'original')
symlink_pat... | [
"def",
"symlinks_supported",
"(",
")",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"original_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmpdir",
",",
"'original'",
")",
"symlink_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"tmp... | [
81,
0
] | [
101,
24
] | python | en | ['en', 'error', 'th'] | False |
sorted_walk | (dir) | Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
| Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
| def sorted_walk(dir):
"""Do os.walk in a reproducible way,
independent of indeterministic filesystem readdir order
"""
for base, dirs, files in os.walk(dir):
dirs.sort()
files.sort()
yield base, dirs, files | [
"def",
"sorted_walk",
"(",
"dir",
")",
":",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dir",
")",
":",
"dirs",
".",
"sort",
"(",
")",
"files",
".",
"sort",
"(",
")",
"yield",
"base",
",",
"dirs",
",",
"files"
] | [
35,
0
] | [
42,
31
] | python | en | ['en', 'gl', 'en'] | True |
walk_egg | (egg_dir) | Walk an unpacked egg's contents, skipping the metadata directory | Walk an unpacked egg's contents, skipping the metadata directory | def walk_egg(egg_dir):
"""Walk an unpacked egg's contents, skipping the metadata directory"""
walker = sorted_walk(egg_dir)
base, dirs, files = next(walker)
if 'EGG-INFO' in dirs:
dirs.remove('EGG-INFO')
yield base, dirs, files
for bdf in walker:
yield bdf | [
"def",
"walk_egg",
"(",
"egg_dir",
")",
":",
"walker",
"=",
"sorted_walk",
"(",
"egg_dir",
")",
"base",
",",
"dirs",
",",
"files",
"=",
"next",
"(",
"walker",
")",
"if",
"'EGG-INFO'",
"in",
"dirs",
":",
"dirs",
".",
"remove",
"(",
"'EGG-INFO'",
")",
... | [
358,
0
] | [
366,
17
] | python | en | ['en', 'en', 'en'] | True |
scan_module | (egg_dir, base, name, stubs) | Check whether module possibly uses unsafe-for-zipfile stuff | Check whether module possibly uses unsafe-for-zipfile stuff | def scan_module(egg_dir, base, name, stubs):
"""Check whether module possibly uses unsafe-for-zipfile stuff"""
filename = os.path.join(base, name)
if filename[:-1] in stubs:
return True # Extension module
pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')
module = pkg + (pkg and '.' or '')... | [
"def",
"scan_module",
"(",
"egg_dir",
",",
"base",
",",
"name",
",",
"stubs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"name",
")",
"if",
"filename",
"[",
":",
"-",
"1",
"]",
"in",
"stubs",
":",
"return",
"True... | [
406,
0
] | [
437,
15
] | python | en | ['en', 'en', 'en'] | True |
iter_symbols | (code) | Yield names and strings used by `code` and its nested code objects | Yield names and strings used by `code` and its nested code objects | def iter_symbols(code):
"""Yield names and strings used by `code` and its nested code objects"""
for name in code.co_names:
yield name
for const in code.co_consts:
if isinstance(const, str):
yield const
elif isinstance(const, CodeType):
for name in iter_symbol... | [
"def",
"iter_symbols",
"(",
"code",
")",
":",
"for",
"name",
"in",
"code",
".",
"co_names",
":",
"yield",
"name",
"for",
"const",
"in",
"code",
".",
"co_consts",
":",
"if",
"isinstance",
"(",
"const",
",",
"str",
")",
":",
"yield",
"const",
"elif",
"... | [
440,
0
] | [
449,
26
] | python | en | ['en', 'en', 'en'] | True |
make_zipfile | (zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
mode='w') | Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecErro... | Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if installed
and found on the default search path). If neither tool is available,
raises DistutilsExecErro... | def make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,
mode='w'):
"""Create a zip file from all the files under 'base_dir'. The output
zip file will be named 'base_dir' + ".zip". Uses either the "zipfile"
Python module (if available) or the InfoZIP "zip" utility (if... | [
"def",
"make_zipfile",
"(",
"zip_filename",
",",
"base_dir",
",",
"verbose",
"=",
"0",
",",
"dry_run",
"=",
"0",
",",
"compress",
"=",
"True",
",",
"mode",
"=",
"'w'",
")",
":",
"import",
"zipfile",
"mkpath",
"(",
"os",
".",
"path",
".",
"dirname",
"... | [
469,
0
] | [
500,
23
] | python | en | ['en', 'en', 'en'] | True |
bdist_egg.call_command | (self, cmdname, **kw) | Invoke reinitialized command `cmdname` with keyword args | Invoke reinitialized command `cmdname` with keyword args | def call_command(self, cmdname, **kw):
"""Invoke reinitialized command `cmdname` with keyword args"""
for dirname in INSTALL_DIRECTORY_ATTRS:
kw.setdefault(dirname, self.bdist_dir)
kw.setdefault('skip_build', self.skip_build)
kw.setdefault('dry_run', self.dry_run)
cmd... | [
"def",
"call_command",
"(",
"self",
",",
"cmdname",
",",
"*",
"*",
"kw",
")",
":",
"for",
"dirname",
"in",
"INSTALL_DIRECTORY_ATTRS",
":",
"kw",
".",
"setdefault",
"(",
"dirname",
",",
"self",
".",
"bdist_dir",
")",
"kw",
".",
"setdefault",
"(",
"'skip_b... | [
145,
4
] | [
153,
18
] | python | en | ['en', 'en', 'en'] | True |
bdist_egg.copy_metadata_to | (self, target_dir) | Copy metadata (egg info) to the target_dir | Copy metadata (egg info) to the target_dir | def copy_metadata_to(self, target_dir):
"Copy metadata (egg info) to the target_dir"
# normalize the path (so that a forward-slash in egg_info will
# match using startswith below)
norm_egg_info = os.path.normpath(self.egg_info)
prefix = os.path.join(norm_egg_info, '')
for... | [
"def",
"copy_metadata_to",
"(",
"self",
",",
"target_dir",
")",
":",
"# normalize the path (so that a forward-slash in egg_info will",
"# match using startswith below)",
"norm_egg_info",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"self",
".",
"egg_info",
")",
"prefix",... | [
314,
4
] | [
324,
44
] | python | en | ['en', 'pt', 'en'] | True |
bdist_egg.get_ext_outputs | (self) | Get a list of relative paths to C extensions in the output distro | Get a list of relative paths to C extensions in the output distro | def get_ext_outputs(self):
"""Get a list of relative paths to C extensions in the output distro"""
all_outputs = []
ext_outputs = []
paths = {self.bdist_dir: ''}
for base, dirs, files in sorted_walk(self.bdist_dir):
for filename in files:
if os.path.... | [
"def",
"get_ext_outputs",
"(",
"self",
")",
":",
"all_outputs",
"=",
"[",
"]",
"ext_outputs",
"=",
"[",
"]",
"paths",
"=",
"{",
"self",
".",
"bdist_dir",
":",
"''",
"}",
"for",
"base",
",",
"dirs",
",",
"files",
"in",
"sorted_walk",
"(",
"self",
".",... | [
326,
4
] | [
352,
39
] | python | en | ['en', 'en', 'en'] | True |
main | () | Run administrative tasks. | Run administrative tasks. | def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DownloadApps.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's inst... | [
"def",
"main",
"(",
")",
":",
"os",
".",
"environ",
".",
"setdefault",
"(",
"'DJANGO_SETTINGS_MODULE'",
",",
"'DownloadApps.settings'",
")",
"try",
":",
"from",
"django",
".",
"core",
".",
"management",
"import",
"execute_from_command_line",
"except",
"ImportError... | [
6,
0
] | [
17,
39
] | python | en | ['lv', 'gd', 'en'] | False |
queries_captured | (
include_savepoints: bool = False, keep_cache_warm: bool = False
) |
Allow a user to capture just the queries executed during
the with statement.
|
Allow a user to capture just the queries executed during
the with statement.
| def queries_captured(
include_savepoints: bool = False, keep_cache_warm: bool = False
) -> Generator[List[Dict[str, Union[str, bytes]]], None, None]:
"""
Allow a user to capture just the queries executed during
the with statement.
"""
queries: List[Dict[str, Union[str, bytes]]] = []
def wr... | [
"def",
"queries_captured",
"(",
"include_savepoints",
":",
"bool",
"=",
"False",
",",
"keep_cache_warm",
":",
"bool",
"=",
"False",
")",
"->",
"Generator",
"[",
"List",
"[",
"Dict",
"[",
"str",
",",
"Union",
"[",
"str",
",",
"bytes",
"]",
"]",
"]",
","... | [
134,
0
] | [
180,
21
] | python | en | ['en', 'error', 'th'] | False |
stdout_suppressed | () | Redirect stdout to /dev/null. | Redirect stdout to /dev/null. | def stdout_suppressed() -> Iterator[IO[str]]:
"""Redirect stdout to /dev/null."""
with open(os.devnull, "a") as devnull:
stdout, sys.stdout = sys.stdout, devnull
yield stdout
sys.stdout = stdout | [
"def",
"stdout_suppressed",
"(",
")",
"->",
"Iterator",
"[",
"IO",
"[",
"str",
"]",
"]",
":",
"with",
"open",
"(",
"os",
".",
"devnull",
",",
"\"a\"",
")",
"as",
"devnull",
":",
"stdout",
",",
"sys",
".",
"stdout",
"=",
"sys",
".",
"stdout",
",",
... | [
184,
0
] | [
190,
27
] | python | en | ['en', 'en', 'it'] | True |
ConfigRunnerLogProb.__init__ | (self, exp_prefix, est_params, sim_params, observations, keys_of_interest, n_test_samples=10 ** 5,
n_seeds=5, use_gpu=True) | ---------- Either load or generate the configs ---------- | ---------- Either load or generate the configs ---------- | def __init__(self, exp_prefix, est_params, sim_params, observations, keys_of_interest, n_test_samples=10 ** 5,
n_seeds=5, use_gpu=True):
assert est_params and exp_prefix and sim_params and keys_of_interest
assert observations.all()
# convert to dicts to list of tuples
if isinstance(est_... | [
"def",
"__init__",
"(",
"self",
",",
"exp_prefix",
",",
"est_params",
",",
"sim_params",
",",
"observations",
",",
"keys_of_interest",
",",
"n_test_samples",
"=",
"10",
"**",
"5",
",",
"n_seeds",
"=",
"5",
",",
"use_gpu",
"=",
"True",
")",
":",
"assert",
... | [
62,
2
] | [
106,
75
] | python | en | ['en', 'en', 'en'] | True |
ConfigRunnerLogProb._generate_configuration_variants | (self, est_params, sim_params) |
Creates all possible combinations from the (configured) estimators and simulators.
Requires configured estimators and simulators in the constructor:
Args:
est_params: estimator parameters as dict with 2 levels
sim_params: density simulator parameters as dict with 2 levels
Returns:
... |
Creates all possible combinations from the (configured) estimators and simulators.
Requires configured estimators and simulators in the constructor: | def _generate_configuration_variants(self, est_params, sim_params):
"""
Creates all possible combinations from the (configured) estimators and simulators.
Requires configured estimators and simulators in the constructor:
Args:
est_params: estimator parameters as dict with 2 levels
sim_p... | [
"def",
"_generate_configuration_variants",
"(",
"self",
",",
"est_params",
",",
"sim_params",
")",
":",
"self",
".",
"est_configs",
"=",
"_create_configurations",
"(",
"est_params",
")",
"self",
".",
"sim_configs",
"=",
"_create_configurations",
"(",
"sim_params",
"... | [
108,
2
] | [
161,
18
] | python | en | ['en', 'error', 'th'] | False |
ConfigRunnerLogProb.run_configurations | (self, dump_models=False, multiprocessing=True, n_workers=None) |
Runs the given configurations, i.e.
1) fits the estimator to the simulation and
2) executes goodness-of-fit (currently: e.g. kl-divergence, wasserstein-distance etc.) tests
Every successful run yields a result object of type GoodnessOfFitResult which contains
information on both estimator, simulato... |
Runs the given configurations, i.e.
1) fits the estimator to the simulation and
2) executes goodness-of-fit (currently: e.g. kl-divergence, wasserstein-distance etc.) tests
Every successful run yields a result object of type GoodnessOfFitResult which contains
information on both estimator, simulato... | def run_configurations(self, dump_models=False, multiprocessing=True, n_workers=None):
"""
Runs the given configurations, i.e.
1) fits the estimator to the simulation and
2) executes goodness-of-fit (currently: e.g. kl-divergence, wasserstein-distance etc.) tests
Every successful run yields a result... | [
"def",
"run_configurations",
"(",
"self",
",",
"dump_models",
"=",
"False",
",",
"multiprocessing",
"=",
"True",
",",
"n_workers",
"=",
"None",
")",
":",
"self",
".",
"dump_models",
"=",
"dump_models",
"''' Asserts '''",
"assert",
"len",
"(",
"self",
".",
"c... | [
163,
2
] | [
208,
38
] | python | en | ['en', 'error', 'th'] | False |
ConfigRunnerLogProb._get_results_dataframe | (self, results) | retrieves the dataframe for one or more GoodnessOfFitResults result objects.
Args:
results: a list or single object of type GoodnessOfFitResults
Returns:
a pandas dataframe
| retrieves the dataframe for one or more GoodnessOfFitResults result objects. | def _get_results_dataframe(self, results):
""" retrieves the dataframe for one or more GoodnessOfFitResults result objects.
Args:
results: a list or single object of type GoodnessOfFitResults
Returns:
a pandas dataframe
"""
n_results = len(results)
assert n_results > 0, "... | [
"def",
"_get_results_dataframe",
"(",
"self",
",",
"results",
")",
":",
"n_results",
"=",
"len",
"(",
"results",
")",
"assert",
"n_results",
">",
"0",
",",
"\"no results given\"",
"results_dict",
"=",
"results",
".",
"report_dict",
"(",
"keys_of_interest",
"=",
... | [
291,
2
] | [
304,
52
] | python | en | ['en', 'en', 'en'] | True |
ConfigRunnerLogProb._export_results | (self, task, gof_result, file_handle_results) | write result to file | write result to file | def _export_results(self, task, gof_result, file_handle_results):
assert len(gof_result) > 0, "no results given"
""" write result to file"""
try:
gof_result_df = self._get_results_dataframe(results=gof_result)
gof_result.result_df = gof_result_df
io.append_result_to_csv(file_handle_result... | [
"def",
"_export_results",
"(",
"self",
",",
"task",
",",
"gof_result",
",",
"file_handle_results",
")",
":",
"assert",
"len",
"(",
"gof_result",
")",
">",
"0",
",",
"\"no results given\"",
"try",
":",
"gof_result_df",
"=",
"self",
".",
"_get_results_dataframe",
... | [
306,
2
] | [
317,
27
] | python | en | ['en', 'en', 'en'] | True |
point_inside_polygon | (x, y, poly) | Taken from http://www.ariel.com.au/a/python-point-int-poly.html
| Taken from http://www.ariel.com.au/a/python-point-int-poly.html
| def point_inside_polygon(x, y, poly):
'''Taken from http://www.ariel.com.au/a/python-point-int-poly.html
'''
n = len(poly)
inside = False
p1x = poly[0]
p1y = poly[1]
for i in range(0, n + 2, 2):
p2x = poly[i % n]
p2y = poly[(i + 1) % n]
if y > min(p1y, p2y):
... | [
"def",
"point_inside_polygon",
"(",
"x",
",",
"y",
",",
"poly",
")",
":",
"n",
"=",
"len",
"(",
"poly",
")",
"inside",
"=",
"False",
"p1x",
"=",
"poly",
"[",
"0",
"]",
"p1y",
"=",
"poly",
"[",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",... | [
47,
0
] | [
65,
17
] | python | en | ['en', 'en', 'en'] | True |
ExceptionAppend | (e, msg) | Append a message to the given exception's message. | Append a message to the given exception's message. | def ExceptionAppend(e, msg):
"""Append a message to the given exception's message."""
if not e.args:
e.args = (msg,)
elif len(e.args) == 1:
e.args = (str(e.args[0]) + " " + msg,)
else:
e.args = (str(e.args[0]) + " " + msg,) + e.args[1:] | [
"def",
"ExceptionAppend",
"(",
"e",
",",
"msg",
")",
":",
"if",
"not",
"e",
".",
"args",
":",
"e",
".",
"args",
"=",
"(",
"msg",
",",
")",
"elif",
"len",
"(",
"e",
".",
"args",
")",
"==",
"1",
":",
"e",
".",
"args",
"=",
"(",
"str",
"(",
... | [
44,
0
] | [
51,
59
] | python | en | ['en', 'en', 'en'] | True |
FindQualifiedTargets | (target, qualified_list) |
Given a list of qualified targets, return the qualified targets for the
specified |target|.
|
Given a list of qualified targets, return the qualified targets for the
specified |target|.
| def FindQualifiedTargets(target, qualified_list):
"""
Given a list of qualified targets, return the qualified targets for the
specified |target|.
"""
return [t for t in qualified_list if ParseQualifiedTarget(t)[1] == target] | [
"def",
"FindQualifiedTargets",
"(",
"target",
",",
"qualified_list",
")",
":",
"return",
"[",
"t",
"for",
"t",
"in",
"qualified_list",
"if",
"ParseQualifiedTarget",
"(",
"t",
")",
"[",
"1",
"]",
"==",
"target",
"]"
] | [
54,
0
] | [
59,
78
] | python | en | ['en', 'error', 'th'] | False |
GetEnvironFallback | (var_list, default) | Look up a key in the environment, with fallback to secondary keys
and finally falling back to a default value. | Look up a key in the environment, with fallback to secondary keys
and finally falling back to a default value. | def GetEnvironFallback(var_list, default):
"""Look up a key in the environment, with fallback to secondary keys
and finally falling back to a default value."""
for var in var_list:
if var in os.environ:
return os.environ[var]
return default | [
"def",
"GetEnvironFallback",
"(",
"var_list",
",",
"default",
")",
":",
"for",
"var",
"in",
"var_list",
":",
"if",
"var",
"in",
"os",
".",
"environ",
":",
"return",
"os",
".",
"environ",
"[",
"var",
"]",
"return",
"default"
] | [
121,
0
] | [
127,
18
] | python | en | ['en', 'en', 'en'] | True |
InvertRelativePath | (path, toplevel_dir=None) | Given a path like foo/bar that is relative to toplevel_dir, return
the inverse relative path back to the toplevel_dir.
E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path)))
should always produce the empty string, unless the path contains symlinks.
| Given a path like foo/bar that is relative to toplevel_dir, return
the inverse relative path back to the toplevel_dir. | def InvertRelativePath(path, toplevel_dir=None):
"""Given a path like foo/bar that is relative to toplevel_dir, return
the inverse relative path back to the toplevel_dir.
E.g. os.path.normpath(os.path.join(path, InvertRelativePath(path)))
should always produce the empty string, unless the path contains symli... | [
"def",
"InvertRelativePath",
"(",
"path",
",",
"toplevel_dir",
"=",
"None",
")",
":",
"if",
"not",
"path",
":",
"return",
"path",
"toplevel_dir",
"=",
"\".\"",
"if",
"toplevel_dir",
"is",
"None",
"else",
"toplevel_dir",
"return",
"RelativePath",
"(",
"toplevel... | [
188,
0
] | [
198,
71
] | python | en | ['en', 'en', 'en'] | True |
EncodePOSIXShellArgument | (argument) | Encodes |argument| suitably for consumption by POSIX shells.
argument may be quoted and escaped as necessary to ensure that POSIX shells
treat the returned value as a literal representing the argument passed to
this function. Parameter (variable) expansions beginning with $ are allowed
to remain intact withou... | Encodes |argument| suitably for consumption by POSIX shells. | def EncodePOSIXShellArgument(argument):
"""Encodes |argument| suitably for consumption by POSIX shells.
argument may be quoted and escaped as necessary to ensure that POSIX shells
treat the returned value as a literal representing the argument passed to
this function. Parameter (variable) expansions beginni... | [
"def",
"EncodePOSIXShellArgument",
"(",
"argument",
")",
":",
"if",
"not",
"isinstance",
"(",
"argument",
",",
"str",
")",
":",
"argument",
"=",
"str",
"(",
"argument",
")",
"if",
"_quote",
".",
"search",
"(",
"argument",
")",
":",
"quote",
"=",
"'\"'",
... | [
271,
0
] | [
291,
18
] | python | en | ['en', 'en', 'en'] | True |
EncodePOSIXShellList | (list) | Encodes |list| suitably for consumption by POSIX shells.
Returns EncodePOSIXShellArgument for each item in list, and joins them
together using the space character as an argument separator.
| Encodes |list| suitably for consumption by POSIX shells. | def EncodePOSIXShellList(list):
"""Encodes |list| suitably for consumption by POSIX shells.
Returns EncodePOSIXShellArgument for each item in list, and joins them
together using the space character as an argument separator.
"""
encoded_arguments = []
for argument in list:
encoded_arguments.a... | [
"def",
"EncodePOSIXShellList",
"(",
"list",
")",
":",
"encoded_arguments",
"=",
"[",
"]",
"for",
"argument",
"in",
"list",
":",
"encoded_arguments",
".",
"append",
"(",
"EncodePOSIXShellArgument",
"(",
"argument",
")",
")",
"return",
"\" \"",
".",
"join",
"(",... | [
294,
0
] | [
304,
38
] | python | en | ['en', 'en', 'en'] | True |
DeepDependencyTargets | (target_dicts, roots) | Returns the recursive list of target dependencies. | Returns the recursive list of target dependencies. | def DeepDependencyTargets(target_dicts, roots):
"""Returns the recursive list of target dependencies."""
dependencies = set()
pending = set(roots)
while pending:
# Pluck out one.
r = pending.pop()
# Skip if visited already.
if r in dependencies:
continue
... | [
"def",
"DeepDependencyTargets",
"(",
"target_dicts",
",",
"roots",
")",
":",
"dependencies",
"=",
"set",
"(",
")",
"pending",
"=",
"set",
"(",
"roots",
")",
"while",
"pending",
":",
"# Pluck out one.",
"r",
"=",
"pending",
".",
"pop",
"(",
")",
"# Skip if ... | [
307,
0
] | [
323,
42
] | python | en | ['en', 'nl', 'en'] | True |
BuildFileTargets | (target_list, build_file) | From a target_list, returns the subset from the specified build_file.
| From a target_list, returns the subset from the specified build_file.
| def BuildFileTargets(target_list, build_file):
"""From a target_list, returns the subset from the specified build_file.
"""
return [p for p in target_list if BuildFile(p) == build_file] | [
"def",
"BuildFileTargets",
"(",
"target_list",
",",
"build_file",
")",
":",
"return",
"[",
"p",
"for",
"p",
"in",
"target_list",
"if",
"BuildFile",
"(",
"p",
")",
"==",
"build_file",
"]"
] | [
326,
0
] | [
329,
65
] | python | en | ['en', 'en', 'en'] | True |
AllTargets | (target_list, target_dicts, build_file) | Returns all targets (direct and dependencies) for the specified build_file.
| Returns all targets (direct and dependencies) for the specified build_file.
| def AllTargets(target_list, target_dicts, build_file):
"""Returns all targets (direct and dependencies) for the specified build_file.
"""
bftargets = BuildFileTargets(target_list, build_file)
deptargets = DeepDependencyTargets(target_dicts, bftargets)
return bftargets + deptargets | [
"def",
"AllTargets",
"(",
"target_list",
",",
"target_dicts",
",",
"build_file",
")",
":",
"bftargets",
"=",
"BuildFileTargets",
"(",
"target_list",
",",
"build_file",
")",
"deptargets",
"=",
"DeepDependencyTargets",
"(",
"target_dicts",
",",
"bftargets",
")",
"re... | [
332,
0
] | [
337,
33
] | python | en | ['en', 'en', 'en'] | True |
WriteOnDiff | (filename) | Write to a file only if the new contents differ.
Arguments:
filename: name of the file to potentially write to.
Returns:
A file like object which will write to temporary file and only overwrite
the target if it differs (on close).
| Write to a file only if the new contents differ. | def WriteOnDiff(filename):
"""Write to a file only if the new contents differ.
Arguments:
filename: name of the file to potentially write to.
Returns:
A file like object which will write to temporary file and only overwrite
the target if it differs (on close).
"""
class Writer(object):
... | [
"def",
"WriteOnDiff",
"(",
"filename",
")",
":",
"class",
"Writer",
"(",
"object",
")",
":",
"\"\"\"Wrapper around file which only covers the target if it differs.\"\"\"",
"def",
"__init__",
"(",
"self",
")",
":",
"# On Cygwin remove the \"dir\" argument",
"# `C:` prefixed pa... | [
340,
0
] | [
426,
19
] | python | en | ['en', 'en', 'en'] | True |
EnsureDirExists | (path) | Make sure the directory for |path| exists. | Make sure the directory for |path| exists. | def EnsureDirExists(path):
"""Make sure the directory for |path| exists."""
try:
os.makedirs(os.path.dirname(path))
except OSError:
pass | [
"def",
"EnsureDirExists",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
"except",
"OSError",
":",
"pass"
] | [
429,
0
] | [
434,
12
] | python | en | ['en', 'en', 'en'] | True |
GetFlavor | (params) | Returns |params.flavor| if it's set, the system's default flavor else. | Returns |params.flavor| if it's set, the system's default flavor else. | def GetFlavor(params):
"""Returns |params.flavor| if it's set, the system's default flavor else."""
flavors = {
"cygwin": "win",
"win32": "win",
"darwin": "mac",
}
if "flavor" in params:
return params["flavor"]
if sys.platform in flavors:
return flavors[sys.p... | [
"def",
"GetFlavor",
"(",
"params",
")",
":",
"flavors",
"=",
"{",
"\"cygwin\"",
":",
"\"win\"",
",",
"\"win32\"",
":",
"\"win\"",
",",
"\"darwin\"",
":",
"\"mac\"",
",",
"}",
"if",
"\"flavor\"",
"in",
"params",
":",
"return",
"params",
"[",
"\"flavor\"",
... | [
437,
0
] | [
462,
18
] | python | en | ['en', 'fr', 'en'] | True |
CopyTool | (flavor, out_path, generator_flags={}) | Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
to |out_path|. | Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
to |out_path|. | def CopyTool(flavor, out_path, generator_flags={}):
"""Finds (flock|mac|win)_tool.gyp in the gyp directory and copies it
to |out_path|."""
# aix and solaris just need flock emulation. mac and win use more complicated
# support scripts.
prefix = {"aix": "flock", "solaris": "flock", "mac": "mac", "win":... | [
"def",
"CopyTool",
"(",
"flavor",
",",
"out_path",
",",
"generator_flags",
"=",
"{",
"}",
")",
":",
"# aix and solaris just need flock emulation. mac and win use more complicated",
"# support scripts.",
"prefix",
"=",
"{",
"\"aix\"",
":",
"\"flock\"",
",",
"\"solaris\"",
... | [
465,
0
] | [
495,
30
] | python | en | ['en', 'en', 'en'] | True |
TopologicallySorted | (graph, get_edges) | r"""Topologically sort based on a user provided edge definition.
Args:
graph: A list of node names.
get_edges: A function mapping from node name to a hashable collection
of node names which this node has outgoing edges to.
Returns:
A list containing all of the node in graph in topologica... | r"""Topologically sort based on a user provided edge definition. | def TopologicallySorted(graph, get_edges):
r"""Topologically sort based on a user provided edge definition.
Args:
graph: A list of node names.
get_edges: A function mapping from node name to a hashable collection
of node names which this node has outgoing edges to.
Returns:
A list co... | [
"def",
"TopologicallySorted",
"(",
"graph",
",",
"get_edges",
")",
":",
"get_edges",
"=",
"memoize",
"(",
"get_edges",
")",
"visited",
"=",
"set",
"(",
")",
"visiting",
"=",
"set",
"(",
")",
"ordered_nodes",
"=",
"[",
"]",
"def",
"Visit",
"(",
"node",
... | [
593,
0
] | [
633,
24
] | python | en | ['en', 'en', 'en'] | True |
ModelAccessPermission.check_permissions | (self, request, view, obj=None) |
Perform basic permissions checking before delegating to the appropriate
method based on the request method.
|
Perform basic permissions checking before delegating to the appropriate
method based on the request method.
| def check_permissions(self, request, view, obj=None):
"""
Perform basic permissions checking before delegating to the appropriate
method based on the request method.
"""
# Don't allow anonymous users. 401, not 403, hence no raised exception.
if not request.user or reques... | [
"def",
"check_permissions",
"(",
"self",
",",
"request",
",",
"view",
",",
"obj",
"=",
"None",
")",
":",
"# Don't allow anonymous users. 401, not 403, hence no raised exception.",
"if",
"not",
"request",
".",
"user",
"or",
"request",
".",
"user",
".",
"is_anonymous"... | [
95,
4
] | [
121,
21
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.__getitem__ | (self, key) |
Returns the last data value for this key, or [] if it's an empty list;
raises KeyError if not found.
|
Returns the last data value for this key, or [] if it's an empty list;
raises KeyError if not found.
| def __getitem__(self, key):
"""
Returns the last data value for this key, or [] if it's an empty list;
raises KeyError if not found.
"""
try:
list_ = super(MultiValueDict, self).__getitem__(key)
except KeyError:
raise MultiValueDictKeyError(repr(ke... | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"list_",
"=",
"super",
"(",
"MultiValueDict",
",",
"self",
")",
".",
"__getitem__",
"(",
"key",
")",
"except",
"KeyError",
":",
"raise",
"MultiValueDictKeyError",
"(",
"repr",
"(",
"key... | [
76,
4
] | [
88,
21
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.get | (self, key, default=None) |
Returns the last data value for the passed key. If key doesn't exist
or value is an empty list, then default is returned.
|
Returns the last data value for the passed key. If key doesn't exist
or value is an empty list, then default is returned.
| def get(self, key, default=None):
"""
Returns the last data value for the passed key. If key doesn't exist
or value is an empty list, then default is returned.
"""
try:
val = self[key]
except KeyError:
return default
if val == []:
... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"except",
"KeyError",
":",
"return",
"default",
"if",
"val",
"==",
"[",
"]",
":",
"return",
"default",
"return",
"val"
] | [
120,
4
] | [
131,
18
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict._getlist | (self, key, default=None, force_list=False) |
Return a list of values for the key.
Used internally to manipulate values list. If force_list is True,
return a new copy of values.
|
Return a list of values for the key. | def _getlist(self, key, default=None, force_list=False):
"""
Return a list of values for the key.
Used internally to manipulate values list. If force_list is True,
return a new copy of values.
"""
try:
values = super(MultiValueDict, self).__getitem__(key)
... | [
"def",
"_getlist",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"force_list",
"=",
"False",
")",
":",
"try",
":",
"values",
"=",
"super",
"(",
"MultiValueDict",
",",
"self",
")",
".",
"__getitem__",
"(",
"key",
")",
"except",
"KeyError",
... | [
133,
4
] | [
149,
25
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.getlist | (self, key, default=None) |
Return the list of values for the key. If key doesn't exist, return a
default value.
|
Return the list of values for the key. If key doesn't exist, return a
default value.
| def getlist(self, key, default=None):
"""
Return the list of values for the key. If key doesn't exist, return a
default value.
"""
return self._getlist(key, default, force_list=True) | [
"def",
"getlist",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getlist",
"(",
"key",
",",
"default",
",",
"force_list",
"=",
"True",
")"
] | [
151,
4
] | [
156,
59
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.appendlist | (self, key, value) | Appends an item to the internal list associated with key. | Appends an item to the internal list associated with key. | def appendlist(self, key, value):
"""Appends an item to the internal list associated with key."""
self.setlistdefault(key).append(value) | [
"def",
"appendlist",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"setlistdefault",
"(",
"key",
")",
".",
"append",
"(",
"value",
")"
] | [
177,
4
] | [
179,
46
] | python | en | ['en', 'en', 'en'] | True |
MultiValueDict._iteritems | (self) |
Yields (key, value) pairs, where value is the last item in the list
associated with the key.
|
Yields (key, value) pairs, where value is the last item in the list
associated with the key.
| def _iteritems(self):
"""
Yields (key, value) pairs, where value is the last item in the list
associated with the key.
"""
for key in self:
yield key, self[key] | [
"def",
"_iteritems",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
":",
"yield",
"key",
",",
"self",
"[",
"key",
"]"
] | [
181,
4
] | [
187,
32
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict._iterlists | (self) | Yields (key, list) pairs. | Yields (key, list) pairs. | def _iterlists(self):
"""Yields (key, list) pairs."""
return six.iteritems(super(MultiValueDict, self)) | [
"def",
"_iterlists",
"(",
"self",
")",
":",
"return",
"six",
".",
"iteritems",
"(",
"super",
"(",
"MultiValueDict",
",",
"self",
")",
")"
] | [
189,
4
] | [
191,
57
] | python | en | ['fr', 'hmn', 'en'] | False |
MultiValueDict._itervalues | (self) | Yield the last value on every key list. | Yield the last value on every key list. | def _itervalues(self):
"""Yield the last value on every key list."""
for key in self:
yield self[key] | [
"def",
"_itervalues",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
":",
"yield",
"self",
"[",
"key",
"]"
] | [
193,
4
] | [
196,
27
] | python | en | ['en', 'en', 'en'] | True |
MultiValueDict.copy | (self) | Returns a shallow copy of this object. | Returns a shallow copy of this object. | def copy(self):
"""Returns a shallow copy of this object."""
return copy.copy(self) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"copy",
".",
"copy",
"(",
"self",
")"
] | [
216,
4
] | [
218,
30
] | python | en | ['en', 'en', 'en'] | True |
MultiValueDict.update | (self, *args, **kwargs) |
update() extends rather than replaces existing key lists.
Also accepts keyword args.
|
update() extends rather than replaces existing key lists.
Also accepts keyword args.
| def update(self, *args, **kwargs):
"""
update() extends rather than replaces existing key lists.
Also accepts keyword args.
"""
if len(args) > 1:
raise TypeError("update expected at most 1 arguments, got %d" % len(args))
if args:
other_dict = args[... | [
"def",
"update",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"TypeError",
"(",
"\"update expected at most 1 arguments, got %d\"",
"%",
"len",
"(",
"args",
")",
")",
"if",
"arg... | [
220,
4
] | [
239,
50
] | python | en | ['en', 'error', 'th'] | False |
MultiValueDict.dict | (self) |
Returns current object as a dict with singular values.
|
Returns current object as a dict with singular values.
| def dict(self):
"""
Returns current object as a dict with singular values.
"""
return {key: self[key] for key in self} | [
"def",
"dict",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"self",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
"}"
] | [
241,
4
] | [
245,
47
] | python | en | ['en', 'error', 'th'] | False |
DictWrapper.__getitem__ | (self, key) |
Retrieves the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.
|
Retrieves the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.
| def __getitem__(self, key):
"""
Retrieves the real value after stripping the prefix string (if
present). If the prefix is present, pass the value through self.func
before returning, otherwise return the raw value.
"""
if key.startswith(self.prefix):
use_func =... | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"self",
".",
"prefix",
")",
":",
"use_func",
"=",
"True",
"key",
"=",
"key",
"[",
"len",
"(",
"self",
".",
"prefix",
")",
":",
"]",
"else",
":",
"use_fu... | [
307,
4
] | [
321,
20
] | python | en | ['en', 'error', 'th'] | False |
WagtailPageTests.assertCanCreateAt | (self, parent_model, child_model, msg=None) |
Assert a particular child Page type can be created under a parent
Page type. ``parent_model`` and ``child_model`` should be the Page
classes being tested.
|
Assert a particular child Page type can be created under a parent
Page type. ``parent_model`` and ``child_model`` should be the Page
classes being tested.
| def assertCanCreateAt(self, parent_model, child_model, msg=None):
"""
Assert a particular child Page type can be created under a parent
Page type. ``parent_model`` and ``child_model`` should be the Page
classes being tested.
"""
if not self._testCanCreateAt(parent_model, ... | [
"def",
"assertCanCreateAt",
"(",
"self",
",",
"parent_model",
",",
"child_model",
",",
"msg",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"_testCanCreateAt",
"(",
"parent_model",
",",
"child_model",
")",
":",
"msg",
"=",
"self",
".",
"_formatMessage",
... | [
18,
4
] | [
28,
44
] | python | en | ['en', 'error', 'th'] | False |
WagtailPageTests.assertCanNotCreateAt | (self, parent_model, child_model, msg=None) |
Assert a particular child Page type can not be created under a parent
Page type. ``parent_model`` and ``child_model`` should be the Page
classes being tested.
|
Assert a particular child Page type can not be created under a parent
Page type. ``parent_model`` and ``child_model`` should be the Page
classes being tested.
| def assertCanNotCreateAt(self, parent_model, child_model, msg=None):
"""
Assert a particular child Page type can not be created under a parent
Page type. ``parent_model`` and ``child_model`` should be the Page
classes being tested.
"""
if self._testCanCreateAt(parent_mode... | [
"def",
"assertCanNotCreateAt",
"(",
"self",
",",
"parent_model",
",",
"child_model",
",",
"msg",
"=",
"None",
")",
":",
"if",
"self",
".",
"_testCanCreateAt",
"(",
"parent_model",
",",
"child_model",
")",
":",
"msg",
"=",
"self",
".",
"_formatMessage",
"(",
... | [
30,
4
] | [
40,
44
] | python | en | ['en', 'error', 'th'] | False |
WagtailPageTests.assertCanCreate | (self, parent, child_model, data, msg=None) |
Assert that a child of the given Page type can be created under the
parent, using the supplied POST data.
``parent`` should be a Page instance, and ``child_model`` should be a
Page subclass. ``data`` should be a dict that will be POSTed at the
Wagtail admin Page creation method... |
Assert that a child of the given Page type can be created under the
parent, using the supplied POST data. | def assertCanCreate(self, parent, child_model, data, msg=None):
"""
Assert that a child of the given Page type can be created under the
parent, using the supplied POST data.
``parent`` should be a Page instance, and ``child_model`` should be a
Page subclass. ``data`` should be a... | [
"def",
"assertCanCreate",
"(",
"self",
",",
"parent",
",",
"child_model",
",",
"data",
",",
"msg",
"=",
"None",
")",
":",
"self",
".",
"assertCanCreateAt",
"(",
"parent",
".",
"specific_class",
",",
"child_model",
")",
"if",
"'slug'",
"not",
"in",
"data",
... | [
42,
4
] | [
86,
44
] | python | en | ['en', 'error', 'th'] | False |
WagtailPageTests.assertAllowedSubpageTypes | (self, parent_model, child_models, msg=None) |
Test that the only page types that can be created under
``parent_model`` are ``child_models``.
The list of allowed child models may differ from those set in
``Page.subpage_types``, if the child models have set
``Page.parent_page_types``.
|
Test that the only page types that can be created under
``parent_model`` are ``child_models``. | def assertAllowedSubpageTypes(self, parent_model, child_models, msg=None):
"""
Test that the only page types that can be created under
``parent_model`` are ``child_models``.
The list of allowed child models may differ from those set in
``Page.subpage_types``, if the child models... | [
"def",
"assertAllowedSubpageTypes",
"(",
"self",
",",
"parent_model",
",",
"child_models",
",",
"msg",
"=",
"None",
")",
":",
"self",
".",
"assertEqual",
"(",
"set",
"(",
"parent_model",
".",
"allowed_subpage_models",
"(",
")",
")",
",",
"set",
"(",
"child_m... | [
88,
4
] | [
100,
20
] | python | en | ['en', 'error', 'th'] | False |
WagtailPageTests.assertAllowedParentPageTypes | (self, child_model, parent_models, msg=None) |
Test that the only page types that ``child_model`` can be created under
are ``parent_models``.
The list of allowed parent models may differ from those set in
``Page.parent_page_types``, if the parent models have set
``Page.subpage_types``.
|
Test that the only page types that ``child_model`` can be created under
are ``parent_models``. | def assertAllowedParentPageTypes(self, child_model, parent_models, msg=None):
"""
Test that the only page types that ``child_model`` can be created under
are ``parent_models``.
The list of allowed parent models may differ from those set in
``Page.parent_page_types``, if the pare... | [
"def",
"assertAllowedParentPageTypes",
"(",
"self",
",",
"child_model",
",",
"parent_models",
",",
"msg",
"=",
"None",
")",
":",
"self",
".",
"assertEqual",
"(",
"set",
"(",
"child_model",
".",
"allowed_parent_page_models",
"(",
")",
")",
",",
"set",
"(",
"p... | [
102,
4
] | [
114,
20
] | python | en | ['en', 'error', 'th'] | False |
ScriptHelpers.__modify_trace | (self, replay, fps) | Adopt replay to the new framerate and add additional steps at the end. | Adopt replay to the new framerate and add additional steps at the end. | def __modify_trace(self, replay, fps):
"""Adopt replay to the new framerate and add additional steps at the end."""
trace = []
min_fps = replay[0]['debug']['config']['physics_steps_per_frame']
assert fps % min_fps == 0, (
'Trace has to be rendered in framerate being multiple of {}'.format(
... | [
"def",
"__modify_trace",
"(",
"self",
",",
"replay",
",",
"fps",
")",
":",
"trace",
"=",
"[",
"]",
"min_fps",
"=",
"replay",
"[",
"0",
"]",
"[",
"'debug'",
"]",
"[",
"'config'",
"]",
"[",
"'physics_steps_per_frame'",
"]",
"assert",
"fps",
"%",
"min_fps... | [
38,
2
] | [
57,
16
] | python | en | ['en', 'en', 'en'] | True |
std_call | (func) |
Returns the correct STDCALL function for certain OSR routines on Win32
platforms.
|
Returns the correct STDCALL function for certain OSR routines on Win32
platforms.
| def std_call(func):
"""
Returns the correct STDCALL function for certain OSR routines on Win32
platforms.
"""
if os.name == 'nt':
return lwingdal[func]
else:
return lgdal[func] | [
"def",
"std_call",
"(",
"func",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
":",
"return",
"lwingdal",
"[",
"func",
"]",
"else",
":",
"return",
"lgdal",
"[",
"func",
"]"
] | [
58,
0
] | [
66,
26
] | python | en | ['en', 'error', 'th'] | False |
gdal_version | () | Returns only the GDAL version number information. | Returns only the GDAL version number information. | def gdal_version():
"Returns only the GDAL version number information."
return _version_info(b'RELEASE_NAME') | [
"def",
"gdal_version",
"(",
")",
":",
"return",
"_version_info",
"(",
"b'RELEASE_NAME'",
")"
] | [
77,
0
] | [
79,
41
] | python | en | ['en', 'da', 'en'] | True |
gdal_full_version | () | Returns the full GDAL version information. | Returns the full GDAL version information. | def gdal_full_version():
"Returns the full GDAL version information."
return _version_info('') | [
"def",
"gdal_full_version",
"(",
")",
":",
"return",
"_version_info",
"(",
"''",
")"
] | [
82,
0
] | [
84,
28
] | python | en | ['en', 'no', 'en'] | True |
StatementSplitter._reset | (self) | Set the filter attributes to its default values | Set the filter attributes to its default values | def _reset(self):
"""Set the filter attributes to its default values"""
self._in_declare = False
self._is_create = False
self._begin_depth = 0
self.consume_ws = False
self.tokens = []
self.level = 0 | [
"def",
"_reset",
"(",
"self",
")",
":",
"self",
".",
"_in_declare",
"=",
"False",
"self",
".",
"_is_create",
"=",
"False",
"self",
".",
"_begin_depth",
"=",
"0",
"self",
".",
"consume_ws",
"=",
"False",
"self",
".",
"tokens",
"=",
"[",
"]",
"self",
"... | [
16,
4
] | [
24,
22
] | python | en | ['en', 'en', 'en'] | True |
StatementSplitter._change_splitlevel | (self, ttype, value) | Get the new split level (increase, decrease or remain equal) | Get the new split level (increase, decrease or remain equal) | def _change_splitlevel(self, ttype, value):
"""Get the new split level (increase, decrease or remain equal)"""
# parenthesis increase/decrease a level
if ttype is T.Punctuation and value == '(':
return 1
elif ttype is T.Punctuation and value == ')':
return -1
... | [
"def",
"_change_splitlevel",
"(",
"self",
",",
"ttype",
",",
"value",
")",
":",
"# parenthesis increase/decrease a level",
"if",
"ttype",
"is",
"T",
".",
"Punctuation",
"and",
"value",
"==",
"'('",
":",
"return",
"1",
"elif",
"ttype",
"is",
"T",
".",
"Punctu... | [
26,
4
] | [
76,
16
] | python | en | ['en', 'en', 'en'] | True |
StatementSplitter.process | (self, stream) | Process the stream | Process the stream | def process(self, stream):
"""Process the stream"""
EOS_TTYPE = T.Whitespace, T.Comment.Single
# Run over all stream tokens
for ttype, value in stream:
# Yield token if we finished a statement and there's no whitespaces
# It will count newline token as a non whit... | [
"def",
"process",
"(",
"self",
",",
"stream",
")",
":",
"EOS_TTYPE",
"=",
"T",
".",
"Whitespace",
",",
"T",
".",
"Comment",
".",
"Single",
"# Run over all stream tokens",
"for",
"ttype",
",",
"value",
"in",
"stream",
":",
"# Yield token if we finished a statemen... | [
78,
4
] | [
106,
44
] | python | en | ['en', 'zh', 'en'] | True |
RestProtocol.identify | (self) | Identifies the target product | Identifies the target product | def identify(self):
""" Identifies the target product """
wsm = RestRequest()
wsm.identify()
return self._communicate(wsm) | [
"def",
"identify",
"(",
"self",
")",
":",
"wsm",
"=",
"RestRequest",
"(",
")",
"wsm",
".",
"identify",
"(",
")",
"return",
"self",
".",
"_communicate",
"(",
"wsm",
")"
] | [
76,
4
] | [
80,
37
] | python | en | ['en', 'en', 'en'] | True |
get_input | (text) |
We take this out of verify() so we can mock it in the test.
|
We take this out of verify() so we can mock it in the test.
| def get_input(text):
"""
We take this out of verify() so we can mock it in the test.
"""
return raw_input(text) | [
"def",
"get_input",
"(",
"text",
")",
":",
"return",
"raw_input",
"(",
"text",
")"
] | [
21,
0
] | [
25,
26
] | python | en | ['en', 'error', 'th'] | False |
verify | (dbconfig) |
Verify with the user if he wants to continue with the given settings.
:param parsed: a argparse namespace
|
Verify with the user if he wants to continue with the given settings. | def verify(dbconfig):
"""
Verify with the user if he wants to continue with the given settings.
:param parsed: a argparse namespace
"""
print("\nThis script will populate a database with these settings:")
print("")
print("\tengine: " + (dbconfig['engine'] or ""))
print("\tdatabase: ... | [
"def",
"verify",
"(",
"dbconfig",
")",
":",
"print",
"(",
"\"\\nThis script will populate a database with these settings:\"",
")",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"\\tengine: \"",
"+",
"(",
"dbconfig",
"[",
"'engine'",
"]",
"or",
"\"\"",
")",
")",
... | [
28,
0
] | [
55,
19
] | python | en | ['en', 'error', 'th'] | False |
destroy_postgres | (connection) |
Destroys the content of a PostgreSQL database.
!! WARNING !! DESTROYS ALL CONTENTS OF THE DATABASE
args:
connection: A PostgresSQL DB connection
|
Destroys the content of a PostgreSQL database. | def destroy_postgres(connection):
"""
Destroys the content of a PostgreSQL database.
!! WARNING !! DESTROYS ALL CONTENTS OF THE DATABASE
args:
connection: A PostgresSQL DB connection
"""
# queries below generate a resultset with rows containing SQL queries
# which can be executed ... | [
"def",
"destroy_postgres",
"(",
"connection",
")",
":",
"# queries below generate a resultset with rows containing SQL queries",
"# which can be executed to drop the db content",
"postgres_gen_drop_tables",
"=",
"\"\"\"\nselect 'drop table if exists \"' || tablename || '\" cascade;'\n from pg_t... | [
59,
0
] | [
99,
27
] | python | en | ['en', 'error', 'th'] | False |
destroy | (dbconfig) |
Destroys the content of a database defined by settings in dbconfig dict.
!! WARNING !! DESTROYS ALL CONTENT
args:
dbconfig: a dict containing connection params for database
|
Destroys the content of a database defined by settings in dbconfig dict. | def destroy(dbconfig):
"""
Destroys the content of a database defined by settings in dbconfig dict.
!! WARNING !! DESTROYS ALL CONTENT
args:
dbconfig: a dict containing connection params for database
"""
assert(dbconfig['destroy'])
if dbconfig['engine'] == 'postgresql':
dat... | [
"def",
"destroy",
"(",
"dbconfig",
")",
":",
"assert",
"(",
"dbconfig",
"[",
"'destroy'",
"]",
")",
"if",
"dbconfig",
"[",
"'engine'",
"]",
"==",
"'postgresql'",
":",
"database",
"=",
"tkp",
".",
"db",
".",
"database",
".",
"Database",
"(",
")",
"destr... | [
102,
0
] | [
115,
56
] | python | en | ['en', 'error', 'th'] | False |
populate | (dbconfig) |
Populates a database with TRAP tables.
args:
dbconfig: a dict containing db connection settings
raises an exception when one of the tables already exists.
|
Populates a database with TRAP tables. | def populate(dbconfig):
"""
Populates a database with TRAP tables.
args:
dbconfig: a dict containing db connection settings
raises an exception when one of the tables already exists.
"""
if not dbconfig['yes']:
verify(dbconfig)
# configure the database before we do anytin... | [
"def",
"populate",
"(",
"dbconfig",
")",
":",
"if",
"not",
"dbconfig",
"[",
"'yes'",
"]",
":",
"verify",
"(",
"dbconfig",
")",
"# configure the database before we do anyting else",
"get_database_config",
"(",
"dbconfig",
",",
"apply",
"=",
"True",
")",
"database",... | [
118,
0
] | [
178,
24
] | python | en | ['en', 'error', 'th'] | False |
validate_block_body | (
constants: ConsensusConstants,
blocks: BlockchainInterface,
block_store: BlockStore,
coin_store: CoinStore,
peak: Optional[BlockRecord],
block: Union[FullBlock, UnfinishedBlock],
height: uint32,
npc_result: Optional[NPCResult],
fork_point_with_peak: Optional[uint32],
get_block_... |
This assumes the header block has been completely validated.
Validates the transactions and body of the block. Returns None for the first value if everything
validates correctly, or an Err if something does not validate. For the second value, returns a CostResult
only if validation succeeded, and there... |
This assumes the header block has been completely validated.
Validates the transactions and body of the block. Returns None for the first value if everything
validates correctly, or an Err if something does not validate. For the second value, returns a CostResult
only if validation succeeded, and there... | async def validate_block_body(
constants: ConsensusConstants,
blocks: BlockchainInterface,
block_store: BlockStore,
coin_store: CoinStore,
peak: Optional[BlockRecord],
block: Union[FullBlock, UnfinishedBlock],
height: uint32,
npc_result: Optional[NPCResult],
fork_point_with_peak: Opt... | [
"async",
"def",
"validate_block_body",
"(",
"constants",
":",
"ConsensusConstants",
",",
"blocks",
":",
"BlockchainInterface",
",",
"block_store",
":",
"BlockStore",
",",
"coin_store",
":",
"CoinStore",
",",
"peak",
":",
"Optional",
"[",
"BlockRecord",
"]",
",",
... | [
45,
0
] | [
479,
31
] | python | en | ['en', 'error', 'th'] | False |
TestBasics.test_submessage_event_sent_after_transaction_commits | (self) |
Tests that `send_event` is hooked to `transaction.on_commit`. This is important, because
we don't want to end up holding locks on message rows for too long if the event queue runs
into a problem.
|
Tests that `send_event` is hooked to `transaction.on_commit`. This is important, because
we don't want to end up holding locks on message rows for too long if the event queue runs
into a problem.
| def test_submessage_event_sent_after_transaction_commits(self) -> None:
"""
Tests that `send_event` is hooked to `transaction.on_commit`. This is important, because
we don't want to end up holding locks on message rows for too long if the event queue runs
into a problem.
"""
... | [
"def",
"test_submessage_event_sent_after_transaction_commits",
"(",
"self",
")",
"->",
"None",
":",
"hamlet",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"message_id",
"=",
"self",
".",
"send_stream_message",
"(",
"hamlet",
",",
"\"Scotland\"",
")",
... | [
188,
4
] | [
202,
94
] | python | en | ['en', 'error', 'th'] | False |
OffSysPathTests.test_distribution_at_pathlib | (self) | Demonstrate how to load metadata direct from a directory.
| Demonstrate how to load metadata direct from a directory.
| def test_distribution_at_pathlib(self):
"""Demonstrate how to load metadata direct from a directory.
"""
dist_info_path = self.site_dir / 'distinfo_pkg-1.0.0.dist-info'
dist = Distribution.at(dist_info_path)
assert dist.version == '1.0.0' | [
"def",
"test_distribution_at_pathlib",
"(",
"self",
")",
":",
"dist_info_path",
"=",
"self",
".",
"site_dir",
"/",
"'distinfo_pkg-1.0.0.dist-info'",
"dist",
"=",
"Distribution",
".",
"at",
"(",
"dist_info_path",
")",
"assert",
"dist",
".",
"version",
"==",
"'1.0.0... | [
165,
4
] | [
170,
38
] | python | en | ['en', 'en', 'en'] | True |
autoencoder.__init__ | (self, layers=[50, 25], activity_l1=[1e-7, 1e-7],
epochs=200, batch_size=100) |
Parameters
----------
layers : list
List of hidden layer sizes.
activity_l1 : list
List of activity regularizer l1 values.
epochs : int
Training epochs.
batch_size : int
Training batch sizes.
Return... |
Parameters
----------
layers : list
List of hidden layer sizes.
activity_l1 : list
List of activity regularizer l1 values.
epochs : int
Training epochs.
batch_size : int
Training batch sizes.
Return... | def __init__(self, layers=[50, 25], activity_l1=[1e-7, 1e-7],
epochs=200, batch_size=100):
"""
Parameters
----------
layers : list
List of hidden layer sizes.
activity_l1 : list
List of activity regularizer l1 values.
epoch... | [
"def",
"__init__",
"(",
"self",
",",
"layers",
"=",
"[",
"50",
",",
"25",
"]",
",",
"activity_l1",
"=",
"[",
"1e-7",
",",
"1e-7",
"]",
",",
"epochs",
"=",
"200",
",",
"batch_size",
"=",
"100",
")",
":",
"self",
".",
"layers",
"=",
"layers",
"self... | [
28,
4
] | [
50,
36
] | python | en | ['en', 'ja', 'th'] | False |
autoencoder.fit | (self, obj, random_state=0, test_size=0.1) | Train the autoencoder to reconstruct the reaction space.
Parameters
----------
obj : edbo.objective:
Initialized edbo.objective object.
random_state : int
Random seed for training/validation split.
test_size : float
Portion of data use... | Train the autoencoder to reconstruct the reaction space.
Parameters
----------
obj : edbo.objective:
Initialized edbo.objective object.
random_state : int
Random seed for training/validation split.
test_size : float
Portion of data use... | def fit(self, obj, random_state=0, test_size=0.1):
"""Train the autoencoder to reconstruct the reaction space.
Parameters
----------
obj : edbo.objective:
Initialized edbo.objective object.
random_state : int
Random seed for training/validation sp... | [
"def",
"fit",
"(",
"self",
",",
"obj",
",",
"random_state",
"=",
"0",
",",
"test_size",
"=",
"0.1",
")",
":",
"# Get data",
"X",
"=",
"obj",
".",
"domain",
"y",
"=",
"[",
"0",
"for",
"y",
"in",
"range",
"(",
"len",
"(",
"X",
")",
")",
"]",
"x... | [
52,
4
] | [
120,
32
] | python | en | ['en', 'en', 'en'] | True |
autoencoder.plot_loss | (self) | Plot the loss in reconstructing the validation set on each epoch.
Returns
----------
matplotlib.pyplot
Plot of validation loss.
| Plot the loss in reconstructing the validation set on each epoch.
Returns
----------
matplotlib.pyplot
Plot of validation loss.
| def plot_loss(self):
"""Plot the loss in reconstructing the validation set on each epoch.
Returns
----------
matplotlib.pyplot
Plot of validation loss.
"""
# Plot training & validation loss values
plt.plot(self.model.history.history['loss'])
... | [
"def",
"plot_loss",
"(",
"self",
")",
":",
"# Plot training & validation loss values",
"plt",
".",
"plot",
"(",
"self",
".",
"model",
".",
"history",
".",
"history",
"[",
"'loss'",
"]",
")",
"plt",
".",
"plot",
"(",
"self",
".",
"model",
".",
"history",
... | [
122,
4
] | [
137,
25
] | python | en | ['en', 'en', 'en'] | True |
autoencoder.transform | (self, obj) | Transform the encoded domain in edbo.objective object
Parameters
----------
obj : edbo.objective:
Initialized edbo.objective object.
Returns
----------
None
| Transform the encoded domain in edbo.objective object
Parameters
----------
obj : edbo.objective:
Initialized edbo.objective object.
Returns
----------
None
| def transform(self, obj):
"""Transform the encoded domain in edbo.objective object
Parameters
----------
obj : edbo.objective:
Initialized edbo.objective object.
Returns
----------
None
"""
get_layer_output = ... | [
"def",
"transform",
"(",
"self",
",",
"obj",
")",
":",
"get_layer_output",
"=",
"K",
".",
"function",
"(",
"[",
"self",
".",
"model",
".",
"layers",
"[",
"0",
"]",
".",
"input",
"]",
",",
"[",
"self",
".",
"model",
".",
"layers",
"[",
"len",
"(",... | [
139,
4
] | [
164,
44
] | python | en | ['en', 'en', 'en'] | True |
Filter.__init__ | (self,
source,
allowed_elements=allowed_elements,
allowed_attributes=allowed_attributes,
allowed_css_properties=allowed_css_properties,
allowed_css_keywords=allowed_css_keywords,
allowed_svg_properties=allowed_svg_prop... | Creates a Filter
:arg allowed_elements: set of elements to allow--everything else will
be escaped
:arg allowed_attributes: set of attributes to allow in
elements--everything else will be stripped
:arg allowed_css_properties: set of CSS properties to allow--everything
... | Creates a Filter | def __init__(self,
source,
allowed_elements=allowed_elements,
allowed_attributes=allowed_attributes,
allowed_css_properties=allowed_css_properties,
allowed_css_keywords=allowed_css_keywords,
allowed_svg_properties=allo... | [
"def",
"__init__",
"(",
"self",
",",
"source",
",",
"allowed_elements",
"=",
"allowed_elements",
",",
"allowed_attributes",
"=",
"allowed_attributes",
",",
"allowed_css_properties",
"=",
"allowed_css_properties",
",",
"allowed_css_keywords",
"=",
"allowed_css_keywords",
"... | [
725,
4
] | [
781,
56
] | python | en | ['en', 'gl', 'en'] | True |
generate_fake_var | (element) | Given a credential type field element, makes up something acceptable. | Given a credential type field element, makes up something acceptable. | def generate_fake_var(element):
"""Given a credential type field element, makes up something acceptable."""
if element['type'] == 'string':
if element.get('format', None) == 'ssh_private_key':
# this example came from the internet
return '\n'.join(
[
... | [
"def",
"generate_fake_var",
"(",
"element",
")",
":",
"if",
"element",
"[",
"'type'",
"]",
"==",
"'string'",
":",
"if",
"element",
".",
"get",
"(",
"'format'",
",",
"None",
")",
"==",
"'ssh_private_key'",
":",
"# this example came from the internet",
"return",
... | [
18,
0
] | [
43,
94
] | python | en | ['en', 'en', 'en'] | True |
credential_kind | (source) | Given the inventory source kind, return expected credential kind | Given the inventory source kind, return expected credential kind | def credential_kind(source):
"""Given the inventory source kind, return expected credential kind"""
return source.replace('ec2', 'aws') | [
"def",
"credential_kind",
"(",
"source",
")",
":",
"return",
"source",
".",
"replace",
"(",
"'ec2'",
",",
"'aws'",
")"
] | [
46,
0
] | [
48,
39
] | python | en | ['en', 'en', 'en'] | True |
read_content | (private_data_dir, raw_env, inventory_update) | Read the environmental data laid down by the task system
template out private and secret data so they will be readable and predictable
return a dictionary `content` with file contents, keyed off environment variable
that references the file
| Read the environmental data laid down by the task system
template out private and secret data so they will be readable and predictable
return a dictionary `content` with file contents, keyed off environment variable
that references the file
| def read_content(private_data_dir, raw_env, inventory_update):
"""Read the environmental data laid down by the task system
template out private and secret data so they will be readable and predictable
return a dictionary `content` with file contents, keyed off environment variable
that references th... | [
"def",
"read_content",
"(",
"private_data_dir",
",",
"raw_env",
",",
"inventory_update",
")",
":",
"# build dict env as a mapping of environment variables to file names",
"# Filter out environment variables which come from runtime environment",
"env",
"=",
"{",
"}",
"exclude_keys",
... | [
72,
0
] | [
163,
25
] | python | en | ['en', 'en', 'en'] | True |
Apollo.step | (self, closure: OptLossClosure = None) | r"""Performs a single optimization step.
Arguments:
closure: A closure that reevaluates the model and returns the loss.
| r"""Performs a single optimization step. | def step(self, closure: OptLossClosure = None) -> OptFloat:
r"""Performs a single optimization step.
Arguments:
closure: A closure that reevaluates the model and returns the loss.
"""
loss = None
if closure is not None:
with torch.enable_grad():
... | [
"def",
"step",
"(",
"self",
",",
"closure",
":",
"OptLossClosure",
"=",
"None",
")",
"->",
"OptFloat",
":",
"loss",
"=",
"None",
"if",
"closure",
"is",
"not",
"None",
":",
"with",
"torch",
".",
"enable_grad",
"(",
")",
":",
"loss",
"=",
"closure",
"(... | [
75,
4
] | [
158,
19
] | python | en | ['en', 'en', 'en'] | True |
topological_sort_as_sets | (dependency_graph) | Variation of Kahn's algorithm (1962) that returns sets.
Takes a dependency graph as a dictionary of node => dependencies.
Yields sets of items in topological order, where the first set contains
all nodes without dependencies, and each following set contains all
nodes that may depend on the nodes only ... | Variation of Kahn's algorithm (1962) that returns sets. | def topological_sort_as_sets(dependency_graph):
"""Variation of Kahn's algorithm (1962) that returns sets.
Takes a dependency graph as a dictionary of node => dependencies.
Yields sets of items in topological order, where the first set contains
all nodes without dependencies, and each following set co... | [
"def",
"topological_sort_as_sets",
"(",
"dependency_graph",
")",
":",
"todo",
"=",
"dependency_graph",
".",
"copy",
"(",
")",
"while",
"todo",
":",
"current",
"=",
"{",
"node",
"for",
"node",
",",
"deps",
"in",
"todo",
".",
"items",
"(",
")",
"if",
"len"... | [
0,
0
] | [
21,
52
] | python | en | ['en', 'da', 'en'] | True |
safe_dump | (x, safe_dict=None) |
Used to serialize an extra_vars dict to YAML
By default, extra vars are marked as `!unsafe` in the generated yaml
_unless_ they've been deemed "trusted" (meaning, they likely were set/added
by a user with a high level of privilege).
This function allows you to pass in a trusted `safe_dict` to all... |
Used to serialize an extra_vars dict to YAML | def safe_dump(x, safe_dict=None):
"""
Used to serialize an extra_vars dict to YAML
By default, extra vars are marked as `!unsafe` in the generated yaml
_unless_ they've been deemed "trusted" (meaning, they likely were set/added
by a user with a high level of privilege).
This function allows yo... | [
"def",
"safe_dump",
"(",
"x",
",",
"safe_dict",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"yamls",
"=",
"[",
"]",
"safe_dict",
"=",
"safe_dict",
"or",
"{",
"}",
"# Compare the top level keys so that we can find values that hav... | [
26,
0
] | [
67,
90
] | python | en | ['en', 'error', 'th'] | False |
sanitize_jinja | (arg) |
For some string, prevent usage of Jinja-like flags
|
For some string, prevent usage of Jinja-like flags
| def sanitize_jinja(arg):
"""
For some string, prevent usage of Jinja-like flags
"""
if isinstance(arg, str):
# If the argument looks like it contains Jinja expressions
# {{ x }} ...
if re.search(r'\{\{[^}]+}}', arg) is not None:
raise ValueError('Inline Jinja variable... | [
"def",
"sanitize_jinja",
"(",
"arg",
")",
":",
"if",
"isinstance",
"(",
"arg",
",",
"str",
")",
":",
"# If the argument looks like it contains Jinja expressions",
"# {{ x }} ...",
"if",
"re",
".",
"search",
"(",
"r'\\{\\{[^}]+}}'",
",",
"arg",
")",
"is",
"not",
... | [
70,
0
] | [
83,
14
] | python | en | ['en', 'error', 'th'] | False |
TestDataParser.__init__ | (self) |
Constructor
|
Constructor
| def __init__(self):
"""
Constructor
"""
self.tests = [] | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"tests",
"=",
"[",
"]"
] | [
54,
4
] | [
58,
23
] | python | en | ['en', 'error', 'th'] | False |
TestDataParser.parse | (self, data_file) |
Data file parser.
:param data_file: Data file path
|
Data file parser. | def parse(self, data_file):
"""
Data file parser.
:param data_file: Data file path
"""
with open(data_file, 'r') as data_f:
self.__parse(data_f) | [
"def",
"parse",
"(",
"self",
",",
"data_file",
")",
":",
"with",
"open",
"(",
"data_file",
",",
"'r'",
")",
"as",
"data_f",
":",
"self",
".",
"__parse",
"(",
"data_f",
")"
] | [
60,
4
] | [
67,
32
] | python | en | ['en', 'error', 'th'] | False |
TestDataParser.__escaped_split | (inp_str, split_char) |
Splits inp_str on split_char except when escaped.
:param inp_str: String to split
:param split_char: Split character
:return: List of splits
|
Splits inp_str on split_char except when escaped. | def __escaped_split(inp_str, split_char):
"""
Splits inp_str on split_char except when escaped.
:param inp_str: String to split
:param split_char: Split character
:return: List of splits
"""
split_colon_fn = lambda x: re.sub(r'\\' + split_char, split_char, x)
... | [
"def",
"__escaped_split",
"(",
"inp_str",
",",
"split_char",
")",
":",
"split_colon_fn",
"=",
"lambda",
"x",
":",
"re",
".",
"sub",
"(",
"r'\\\\'",
"+",
"split_char",
",",
"split_char",
",",
"x",
")",
"if",
"len",
"(",
"split_char",
")",
">",
"1",
":",... | [
70,
4
] | [
83,
18
] | python | en | ['en', 'error', 'th'] | False |
TestDataParser.__parse | (self, data_f) |
Parses data file using supplied file object.
:param data_f: Data file object
:return:
|
Parses data file using supplied file object. | def __parse(self, data_f):
"""
Parses data file using supplied file object.
:param data_f: Data file object
:return:
"""
for line in data_f:
line = line.strip()
if not line:
continue
# Read test name
name = ... | [
"def",
"__parse",
"(",
"self",
",",
"data_f",
")",
":",
"for",
"line",
"in",
"data_f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
":",
"continue",
"# Read test name",
"name",
"=",
"line",
"# Check dependencies",
"dependencies",
... | [
85,
4
] | [
119,
45
] | python | en | ['en', 'error', 'th'] | False |
TestDataParser.get_test_data | (self) |
Returns test data.
|
Returns test data.
| def get_test_data(self):
"""
Returns test data.
"""
return self.tests | [
"def",
"get_test_data",
"(",
"self",
")",
":",
"return",
"self",
".",
"tests"
] | [
121,
4
] | [
125,
25
] | python | en | ['en', 'error', 'th'] | False |
MbedTlsTest.__init__ | (self) |
Constructor initialises test index to 0.
|
Constructor initialises test index to 0.
| def __init__(self):
"""
Constructor initialises test index to 0.
"""
super(MbedTlsTest, self).__init__()
self.tests = []
self.test_index = -1
self.dep_index = 0
self.suite_passed = True
self.error_str = dict()
self.error_str[self.DEPENDENCY... | [
"def",
"__init__",
"(",
"self",
")",
":",
"super",
"(",
"MbedTlsTest",
",",
"self",
")",
".",
"__init__",
"(",
")",
"self",
".",
"tests",
"=",
"[",
"]",
"self",
".",
"test_index",
"=",
"-",
"1",
"self",
".",
"dep_index",
"=",
"0",
"self",
".",
"s... | [
157,
4
] | [
178,
40
] | python | en | ['en', 'error', 'th'] | False |
MbedTlsTest.setup | (self) |
Setup hook implementation. Reads test suite data file and parses out
tests.
|
Setup hook implementation. Reads test suite data file and parses out
tests.
| def setup(self):
"""
Setup hook implementation. Reads test suite data file and parses out
tests.
"""
binary_path = self.get_config_item('image_path')
script_dir = os.path.split(os.path.abspath(__file__))[0]
suite_name = os.path.splitext(os.path.basename(binary_pat... | [
"def",
"setup",
"(",
"self",
")",
":",
"binary_path",
"=",
"self",
".",
"get_config_item",
"(",
"'image_path'",
")",
"script_dir",
"=",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"[",
"0",
"]",... | [
180,
4
] | [
199,
39
] | python | en | ['en', 'error', 'th'] | False |
MbedTlsTest.print_test_info | (self) |
Prints test summary read by Greentea to detect test cases.
|
Prints test summary read by Greentea to detect test cases.
| def print_test_info(self):
"""
Prints test summary read by Greentea to detect test cases.
"""
self.log('{{__testcase_count;%d}}' % len(self.tests))
for name, _, _, _ in self.tests:
self.log('{{__testcase_name;%s}}' % name) | [
"def",
"print_test_info",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"'{{__testcase_count;%d}}'",
"%",
"len",
"(",
"self",
".",
"tests",
")",
")",
"for",
"name",
",",
"_",
",",
"_",
",",
"_",
"in",
"self",
".",
"tests",
":",
"self",
".",
"log"... | [
201,
4
] | [
207,
53
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.