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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
CacheRegion.invalidate | (self, hard=True) | Invalidate this :class:`.CacheRegion`.
The default invalidation system works by setting
a current timestamp (using ``time.time()``)
representing the "minimum creation time" for
a value. Any retrieved value whose creation
time is prior to this timestamp
is considered to ... | Invalidate this :class:`.CacheRegion`. | def invalidate(self, hard=True):
"""Invalidate this :class:`.CacheRegion`.
The default invalidation system works by setting
a current timestamp (using ``time.time()``)
representing the "minimum creation time" for
a value. Any retrieved value whose creation
time is prior... | [
"def",
"invalidate",
"(",
"self",
",",
"hard",
"=",
"True",
")",
":",
"self",
".",
"region_invalidator",
".",
"invalidate",
"(",
"hard",
")"
] | [
507,
4
] | [
555,
48
] | python | en | ['en', 'sn', 'en'] | True |
CacheRegion.configure_from_config | (self, config_dict, prefix) | Configure from a configuration dictionary
and a prefix.
Example::
local_region = make_region()
memcached_region = make_region()
# regions are ready to use for function
# decorators, but not yet for actual caching
# later, when config is ava... | Configure from a configuration dictionary
and a prefix. | def configure_from_config(self, config_dict, prefix):
"""Configure from a configuration dictionary
and a prefix.
Example::
local_region = make_region()
memcached_region = make_region()
# regions are ready to use for function
# decorators, but no... | [
"def",
"configure_from_config",
"(",
"self",
",",
"config_dict",
",",
"prefix",
")",
":",
"config_dict",
"=",
"coerce_string_conf",
"(",
"config_dict",
")",
"return",
"self",
".",
"configure",
"(",
"config_dict",
"[",
"\"%sbackend\"",
"%",
"prefix",
"]",
",",
... | [
557,
4
] | [
592,
9
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.is_configured | (self) | Return True if the backend has been configured via the
:meth:`.CacheRegion.configure` method already.
.. versionadded:: 0.5.1
| Return True if the backend has been configured via the
:meth:`.CacheRegion.configure` method already. | def is_configured(self):
"""Return True if the backend has been configured via the
:meth:`.CacheRegion.configure` method already.
.. versionadded:: 0.5.1
"""
return 'backend' in self.__dict__ | [
"def",
"is_configured",
"(",
"self",
")",
":",
"return",
"'backend'",
"in",
"self",
".",
"__dict__"
] | [
600,
4
] | [
607,
41
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.get | (self, key, expiration_time=None, ignore_expiration=False) | Return a value from the cache, based on the given key.
If the value is not present, the method returns the token
``NO_VALUE``. ``NO_VALUE`` evaluates to False, but is separate from
``None`` to distinguish between a cached value of ``None``.
By default, the configured expiration time of... | Return a value from the cache, based on the given key. | def get(self, key, expiration_time=None, ignore_expiration=False):
"""Return a value from the cache, based on the given key.
If the value is not present, the method returns the token
``NO_VALUE``. ``NO_VALUE`` evaluates to False, but is separate from
``None`` to distinguish between a ca... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"expiration_time",
"=",
"None",
",",
"ignore_expiration",
"=",
"False",
")",
":",
"if",
"self",
".",
"key_mangler",
":",
"key",
"=",
"self",
".",
"key_mangler",
"(",
"key",
")",
"value",
"=",
"self",
".",
"... | [
609,
4
] | [
687,
28
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.get_multi | (self, keys, expiration_time=None, ignore_expiration=False) | Return multiple values from the cache, based on the given keys.
Returns values as a list matching the keys given.
E.g.::
values = region.get_multi(["one", "two", "three"])
To convert values to a dictionary, use ``zip()``::
keys = ["one", "two", "three"]
v... | Return multiple values from the cache, based on the given keys. | def get_multi(self, keys, expiration_time=None, ignore_expiration=False):
"""Return multiple values from the cache, based on the given keys.
Returns values as a list matching the keys given.
E.g.::
values = region.get_multi(["one", "two", "three"])
To convert values to a ... | [
"def",
"get_multi",
"(",
"self",
",",
"keys",
",",
"expiration_time",
"=",
"None",
",",
"ignore_expiration",
"=",
"False",
")",
":",
"if",
"not",
"keys",
":",
"return",
"[",
"]",
"if",
"self",
".",
"key_mangler",
":",
"keys",
"=",
"list",
"(",
"map",
... | [
712,
4
] | [
761,
9
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.get_or_create | (
self, key, creator, expiration_time=None, should_cache_fn=None,
creator_args=None) | Return a cached value based on the given key.
If the value does not exist or is considered to be expired
based on its creation time, the given
creation function may or may not be used to recreate the value
and persist the newly generated value in the cache.
Whether or not the f... | Return a cached value based on the given key. | def get_or_create(
self, key, creator, expiration_time=None, should_cache_fn=None,
creator_args=None):
"""Return a cached value based on the given key.
If the value does not exist or is considered to be expired
based on its creation time, the given
creation funct... | [
"def",
"get_or_create",
"(",
"self",
",",
"key",
",",
"creator",
",",
"expiration_time",
"=",
"None",
",",
"should_cache_fn",
"=",
"None",
",",
"creator_args",
"=",
"None",
")",
":",
"orig_key",
"=",
"key",
"if",
"self",
".",
"key_mangler",
":",
"key",
"... | [
763,
4
] | [
906,
24
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.get_or_create_multi | (
self, keys, creator, expiration_time=None, should_cache_fn=None) | Return a sequence of cached values based on a sequence of keys.
The behavior for generation of values based on keys corresponds
to that of :meth:`.Region.get_or_create`, with the exception that
the ``creator()`` function may be asked to generate any subset of
the given keys. The list ... | Return a sequence of cached values based on a sequence of keys. | def get_or_create_multi(
self, keys, creator, expiration_time=None, should_cache_fn=None):
"""Return a sequence of cached values based on a sequence of keys.
The behavior for generation of values based on keys corresponds
to that of :meth:`.Region.get_or_create`, with the exception ... | [
"def",
"get_or_create_multi",
"(",
"self",
",",
"keys",
",",
"creator",
",",
"expiration_time",
"=",
"None",
",",
"should_cache_fn",
"=",
"None",
")",
":",
"def",
"get_value",
"(",
"key",
")",
":",
"value",
"=",
"values",
".",
"get",
"(",
"key",
",",
"... | [
908,
4
] | [
1040,
31
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion._value | (self, value) | Return a :class:`.CachedValue` given a value. | Return a :class:`.CachedValue` given a value. | def _value(self, value):
"""Return a :class:`.CachedValue` given a value."""
return CachedValue(
value,
{
"ct": time.time(),
"v": value_version
}) | [
"def",
"_value",
"(",
"self",
",",
"value",
")",
":",
"return",
"CachedValue",
"(",
"value",
",",
"{",
"\"ct\"",
":",
"time",
".",
"time",
"(",
")",
",",
"\"v\"",
":",
"value_version",
"}",
")"
] | [
1042,
4
] | [
1049,
14
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.set | (self, key, value) | Place a new value in the cache under the given key. | Place a new value in the cache under the given key. | def set(self, key, value):
"""Place a new value in the cache under the given key."""
if self.key_mangler:
key = self.key_mangler(key)
self.backend.set(key, self._value(value)) | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"if",
"self",
".",
"key_mangler",
":",
"key",
"=",
"self",
".",
"key_mangler",
"(",
"key",
")",
"self",
".",
"backend",
".",
"set",
"(",
"key",
",",
"self",
".",
"_value",
"(",
"value... | [
1051,
4
] | [
1056,
49
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.set_multi | (self, mapping) | Place new values in the cache under the given keys.
.. versionadded:: 0.5.0
| Place new values in the cache under the given keys. | def set_multi(self, mapping):
"""Place new values in the cache under the given keys.
.. versionadded:: 0.5.0
"""
if not mapping:
return
if self.key_mangler:
mapping = dict((
self.key_mangler(k), self._value(v))
for k, v i... | [
"def",
"set_multi",
"(",
"self",
",",
"mapping",
")",
":",
"if",
"not",
"mapping",
":",
"return",
"if",
"self",
".",
"key_mangler",
":",
"mapping",
"=",
"dict",
"(",
"(",
"self",
".",
"key_mangler",
"(",
"k",
")",
",",
"self",
".",
"_value",
"(",
"... | [
1058,
4
] | [
1073,
39
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.delete | (self, key) | Remove a value from the cache.
This operation is idempotent (can be called multiple times, or on a
non-existent key, safely)
| Remove a value from the cache. | def delete(self, key):
"""Remove a value from the cache.
This operation is idempotent (can be called multiple times, or on a
non-existent key, safely)
"""
if self.key_mangler:
key = self.key_mangler(key)
self.backend.delete(key) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"if",
"self",
".",
"key_mangler",
":",
"key",
"=",
"self",
".",
"key_mangler",
"(",
"key",
")",
"self",
".",
"backend",
".",
"delete",
"(",
"key",
")"
] | [
1075,
4
] | [
1085,
32
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.delete_multi | (self, keys) | Remove multiple values from the cache.
This operation is idempotent (can be called multiple times, or on a
non-existent key, safely)
.. versionadded:: 0.5.0
| Remove multiple values from the cache. | def delete_multi(self, keys):
"""Remove multiple values from the cache.
This operation is idempotent (can be called multiple times, or on a
non-existent key, safely)
.. versionadded:: 0.5.0
"""
if self.key_mangler:
keys = list(map(lambda key: self.key_mang... | [
"def",
"delete_multi",
"(",
"self",
",",
"keys",
")",
":",
"if",
"self",
".",
"key_mangler",
":",
"keys",
"=",
"list",
"(",
"map",
"(",
"lambda",
"key",
":",
"self",
".",
"key_mangler",
"(",
"key",
")",
",",
"keys",
")",
")",
"self",
".",
"backend"... | [
1087,
4
] | [
1100,
39
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.cache_on_arguments | (
self, namespace=None,
expiration_time=None,
should_cache_fn=None,
to_str=compat.string_type,
function_key_generator=None) | A function decorator that will cache the return
value of the function using a key derived from the
function itself and its arguments.
The decorator internally makes use of the
:meth:`.CacheRegion.get_or_create` method to access the
cache and conditionally call the function. See... | A function decorator that will cache the return
value of the function using a key derived from the
function itself and its arguments. | def cache_on_arguments(
self, namespace=None,
expiration_time=None,
should_cache_fn=None,
to_str=compat.string_type,
function_key_generator=None):
"""A function decorator that will cache the return
value of the function using a key derived from... | [
"def",
"cache_on_arguments",
"(",
"self",
",",
"namespace",
"=",
"None",
",",
"expiration_time",
"=",
"None",
",",
"should_cache_fn",
"=",
"None",
",",
"to_str",
"=",
"compat",
".",
"string_type",
",",
"function_key_generator",
"=",
"None",
")",
":",
"expirati... | [
1102,
4
] | [
1341,
30
] | python | en | ['en', 'en', 'en'] | True |
CacheRegion.cache_multi_on_arguments | (
self, namespace=None, expiration_time=None,
should_cache_fn=None,
asdict=False, to_str=compat.string_type,
function_multi_key_generator=None) | A function decorator that will cache multiple return
values from the function using a sequence of keys derived from the
function itself and the arguments passed to it.
This method is the "multiple key" analogue to the
:meth:`.CacheRegion.cache_on_arguments` method.
Example::
... | A function decorator that will cache multiple return
values from the function using a sequence of keys derived from the
function itself and the arguments passed to it. | def cache_multi_on_arguments(
self, namespace=None, expiration_time=None,
should_cache_fn=None,
asdict=False, to_str=compat.string_type,
function_multi_key_generator=None):
"""A function decorator that will cache multiple return
values from the function us... | [
"def",
"cache_multi_on_arguments",
"(",
"self",
",",
"namespace",
"=",
"None",
",",
"expiration_time",
"=",
"None",
",",
"should_cache_fn",
"=",
"None",
",",
"asdict",
"=",
"False",
",",
"to_str",
"=",
"compat",
".",
"string_type",
",",
"function_multi_key_gener... | [
1343,
4
] | [
1553,
30
] | python | en | ['en', 'en', 'en'] | True |
wiki | () |
Search Anything in wikipedia
|
Search Anything in wikipedia
| def wiki():
'''
Search Anything in wikipedia
'''
word = input("Wikipedia Search : ")
results = wk.search(word)
for i in enumerate(results):
print(i)
try:
key = int(input("Enter the number : "))
except AssertionError:
key = int(input("Please enter corresponding ar... | [
"def",
"wiki",
"(",
")",
":",
"word",
"=",
"input",
"(",
"\"Wikipedia Search : \"",
")",
"results",
"=",
"wk",
".",
"search",
"(",
"word",
")",
"for",
"i",
"in",
"enumerate",
"(",
"results",
")",
":",
"print",
"(",
"i",
")",
"try",
":",
"key",
"=",... | [
11,
0
] | [
43,
8
] | python | en | ['en', 'error', 'th'] | False |
randomWiki | () |
This function gives you a list of n number of random articles
Choose any article.
|
This function gives you a list of n number of random articles
Choose any article.
| def randomWiki():
'''
This function gives you a list of n number of random articles
Choose any article.
'''
number = input("No: of Random Pages : ")
lst = wk.random(number)
for i in enumerate(lst):
print(i)
try:
key = input("Enter the number : ")
assert key >= 0 a... | [
"def",
"randomWiki",
"(",
")",
":",
"number",
"=",
"input",
"(",
"\"No: of Random Pages : \"",
")",
"lst",
"=",
"wk",
".",
"random",
"(",
"number",
")",
"for",
"i",
"in",
"enumerate",
"(",
"lst",
")",
":",
"print",
"(",
"i",
")",
"try",
":",
"key",
... | [
51,
0
] | [
84,
8
] | python | en | ['en', 'error', 'th'] | False |
incr_error | (func) | Wrapper to count the number of errors | Wrapper to count the number of errors | def incr_error(func):
"""Wrapper to count the number of errors"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
global NUMBER_OF_ERRORS
NUMBER_OF_ERRORS += 1
return func(*args, **kwargs)
return wrapper | [
"def",
"incr_error",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"NUMBER_OF_ERRORS",
"NUMBER_OF_ERRORS",
"+=",
"1",
"return",
"func",
"(",
"*"... | [
30,
0
] | [
37,
18
] | python | en | ['en', 'en', 'en'] | True |
identify_template | (filepath) | Identify template
Given the path to a single file,
identify the appropriate template to use | Identify template | def identify_template(filepath):
"""Identify template
Given the path to a single file,
identify the appropriate template to use"""
for template_name, (validator, pattern) in LESSON_TEMPLATES.items():
if re.search(pattern, os.path.basename(filepath)):
return template_name
return... | [
"def",
"identify_template",
"(",
"filepath",
")",
":",
"for",
"template_name",
",",
"(",
"validator",
",",
"pattern",
")",
"in",
"LESSON_TEMPLATES",
".",
"items",
"(",
")",
":",
"if",
"re",
".",
"search",
"(",
"pattern",
",",
"os",
".",
"path",
".",
"b... | [
680,
0
] | [
689,
15
] | python | en | ['en', 'en', 'en'] | False |
validate_single | (filepath, template=None) | Validate a single Markdown file based on a specified template | Validate a single Markdown file based on a specified template | def validate_single(filepath, template=None):
"""Validate a single Markdown file based on a specified template"""
if os.path.basename(filepath) in SKIP_FILES:
# Silently pass certain non-lesson files without validating them
return True
template = template or identify_template(filepath)
... | [
"def",
"validate_single",
"(",
"filepath",
",",
"template",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"filepath",
")",
"in",
"SKIP_FILES",
":",
"# Silently pass certain non-lesson files without validating them",
"return",
"True",
"templat... | [
692,
0
] | [
720,
14
] | python | en | ['en', 'en', 'en'] | True |
validate_folder | (path, template=None) | Validate an entire folder of files | Validate an entire folder of files | def validate_folder(path, template=None):
"""Validate an entire folder of files"""
search_str = os.path.join(path, "*.md") # Find files based on extension
filename_list = glob.glob(search_str)
if not filename_list:
logging.error(
"No Markdown files were found "
"in spec... | [
"def",
"validate_folder",
"(",
"path",
",",
"template",
"=",
"None",
")",
":",
"search_str",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"\"*.md\"",
")",
"# Find files based on extension",
"filename_list",
"=",
"glob",
".",
"glob",
"(",
"search_st... | [
723,
0
] | [
738,
20
] | python | en | ['en', 'en', 'en'] | True |
start_logging | (level=logging.INFO) | Initialize logging and print messages to console. | Initialize logging and print messages to console. | def start_logging(level=logging.INFO):
"""Initialize logging and print messages to console."""
logging.basicConfig(stream=sys.stdout,
level=level,
format="%(levelname)s: %(message)s") | [
"def",
"start_logging",
"(",
"level",
"=",
"logging",
".",
"INFO",
")",
":",
"logging",
".",
"basicConfig",
"(",
"stream",
"=",
"sys",
".",
"stdout",
",",
"level",
"=",
"level",
",",
"format",
"=",
"\"%(levelname)s: %(message)s\"",
")"
] | [
741,
0
] | [
745,
60
] | python | en | ['en', 'en', 'en'] | True |
command_line | () | Handle arguments passed in via the command line | Handle arguments passed in via the command line | def command_line():
"""Handle arguments passed in via the command line"""
parser = argparse.ArgumentParser()
parser.add_argument("file_or_path",
nargs="*",
default=[os.getcwd()],
help="The individual pathname")
parser.add_argument(... | [
"def",
"command_line",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"file_or_path\"",
",",
"nargs",
"=",
"\"*\"",
",",
"default",
"=",
"[",
"os",
".",
"getcwd",
"(",
")",
"]",
",",
"he... | [
748,
0
] | [
765,
30
] | python | en | ['en', 'en', 'en'] | True |
check_required_files | (dir_to_validate) | Check if required files exists. | Check if required files exists. | def check_required_files(dir_to_validate):
"""Check if required files exists."""
REQUIRED_FILES = ["01-*.md",
"CONDUCT.md",
"CONTRIBUTING.md",
"discussion.md",
"index.md",
"instructors.md",
... | [
"def",
"check_required_files",
"(",
"dir_to_validate",
")",
":",
"REQUIRED_FILES",
"=",
"[",
"\"01-*.md\"",
",",
"\"CONDUCT.md\"",
",",
"\"CONTRIBUTING.md\"",
",",
"\"discussion.md\"",
",",
"\"index.md\"",
",",
"\"instructors.md\"",
",",
"\"LICENSE.md\"",
",",
"\"README... | [
768,
0
] | [
788,
16
] | python | en | ['en', 'en', 'en'] | True |
get_files_to_validate | (file_or_path) | Generate list of files to validate. | Generate list of files to validate. | def get_files_to_validate(file_or_path):
"""Generate list of files to validate."""
files_to_validate = []
dirs_to_validate = []
for fn in file_or_path:
if os.path.isdir(fn):
search_str = os.path.join(fn, "*.md")
files_to_validate.extend(glob.glob(search_str))
... | [
"def",
"get_files_to_validate",
"(",
"file_or_path",
")",
":",
"files_to_validate",
"=",
"[",
"]",
"dirs_to_validate",
"=",
"[",
"]",
"for",
"fn",
"in",
"file_or_path",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"fn",
")",
":",
"search_str",
"=",
"... | [
791,
0
] | [
808,
46
] | python | en | ['en', 'en', 'en'] | True |
MarkdownValidator.__init__ | (self, filename=None, markdown=None) | Perform validation on a Markdown document.
Validator accepts either the path to a file containing Markdown,
OR a valid Markdown string. The latter is useful for unit testing. | Perform validation on a Markdown document. | def __init__(self, filename=None, markdown=None):
"""Perform validation on a Markdown document.
Validator accepts either the path to a file containing Markdown,
OR a valid Markdown string. The latter is useful for unit testing."""
self.filename = filename
if filename:
... | [
"def",
"__init__",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"markdown",
"=",
"None",
")",
":",
"self",
".",
"filename",
"=",
"filename",
"if",
"filename",
":",
"# Expect Markdown files to be in same directory as the input file",
"self",
".",
"markdown_dir",
... | [
58,
4
] | [
83,
52
] | python | en | ['en', 'en', 'en'] | True |
MarkdownValidator._validate_no_fixme | (self) | Validate that the file contains no lines marked 'FIXME'
This will be based on the raw markdown, not the ast | Validate that the file contains no lines marked 'FIXME'
This will be based on the raw markdown, not the ast | def _validate_no_fixme(self):
"""Validate that the file contains no lines marked 'FIXME'
This will be based on the raw markdown, not the ast"""
valid = True
for i, line in enumerate(self.markdown.splitlines()):
if re.search("FIXME", line, re.IGNORECASE):
loggi... | [
"def",
"_validate_no_fixme",
"(",
"self",
")",
":",
"valid",
"=",
"True",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"self",
".",
"markdown",
".",
"splitlines",
"(",
")",
")",
":",
"if",
"re",
".",
"search",
"(",
"\"FIXME\"",
",",
"line",
",",
... | [
90,
4
] | [
101,
20
] | python | en | ['en', 'en', 'en'] | True |
MarkdownValidator._validate_hrs | (self) | Validate header
Verify that the header section at top of document
is bracketed by two horizontal rules | Validate header | def _validate_hrs(self):
"""Validate header
Verify that the header section at top of document
is bracketed by two horizontal rules"""
valid = True
try:
hr_nodes = [self.ast.children[0], self.ast.children[2]]
except IndexError:
logging.error(
... | [
"def",
"_validate_hrs",
"(",
"self",
")",
":",
"valid",
"=",
"True",
"try",
":",
"hr_nodes",
"=",
"[",
"self",
".",
"ast",
".",
"children",
"[",
"0",
"]",
",",
"self",
".",
"ast",
".",
"children",
"[",
"2",
"]",
"]",
"except",
"IndexError",
":",
... | [
103,
4
] | [
124,
20
] | python | en | ['en', 'et', 'en'] | False |
MarkdownValidator._validate_one_doc_header_row | (self, label, content) | Validate a single row of the document header section | Validate a single row of the document header section | def _validate_one_doc_header_row(self, label, content):
"""Validate a single row of the document header section"""
if label not in self.DOC_HEADERS:
logging.warning(
"In {0}: "
"Unrecognized label in header section: {1}".format(
self.filena... | [
"def",
"_validate_one_doc_header_row",
"(",
"self",
",",
"label",
",",
"content",
")",
":",
"if",
"label",
"not",
"in",
"self",
".",
"DOC_HEADERS",
":",
"logging",
".",
"warning",
"(",
"\"In {0}: \"",
"\"Unrecognized label in header section: {1}\"",
".",
"format",
... | [
126,
4
] | [
142,
30
] | python | en | ['en', 'en', 'en'] | True |
MarkdownValidator._validate_doc_headers | (self) | Validate the document header section.
Pass only if the header of the document contains the specified
sections with the expected contents | Validate the document header section. | def _validate_doc_headers(self):
"""Validate the document header section.
Pass only if the header of the document contains the specified
sections with the expected contents"""
# Test: Header section should be wrapped in hrs
has_hrs = self._validate_hrs()
header_nod... | [
"def",
"_validate_doc_headers",
"(",
"self",
")",
":",
"# Test: Header section should be wrapped in hrs",
"has_hrs",
"=",
"self",
".",
"_validate_hrs",
"(",
")",
"header_node",
"=",
"self",
".",
"ast",
".",
"children",
"[",
"1",
"]",
"header_text",
"=",
"'\\n'",
... | [
145,
4
] | [
181,
61
] | python | en | ['en', 'en', 'en'] | True |
MarkdownValidator._validate_section_heading_order | (self, ast_node=None, headings=None) | Verify that section headings appear, and in the order expected | Verify that section headings appear, and in the order expected | def _validate_section_heading_order(self, ast_node=None, headings=None):
"""Verify that section headings appear, and in the order expected"""
if ast_node is None:
ast_node = self.ast.data
headings = self.HEADINGS
heading_nodes = self.ast.get_section_headings(ast_node)
... | [
"def",
"_validate_section_heading_order",
"(",
"self",
",",
"ast_node",
"=",
"None",
",",
"headings",
"=",
"None",
")",
":",
"if",
"ast_node",
"is",
"None",
":",
"ast_node",
"=",
"self",
".",
"ast",
".",
"data",
"headings",
"=",
"self",
".",
"HEADINGS",
... | [
183,
4
] | [
238,
54
] | python | en | ['en', 'en', 'en'] | True |
MarkdownValidator._validate_one_callout | (self, callout_node) |
Logic to validate a single callout box (defined as a blockquoted
section that starts with a heading). Checks that:
* First child of callout box should be a lvl 2 header with
known title & CSS style
* Callout box must have at least one child after the heading
An addit... |
Logic to validate a single callout box (defined as a blockquoted
section that starts with a heading). Checks that: | def _validate_one_callout(self, callout_node):
"""
Logic to validate a single callout box (defined as a blockquoted
section that starts with a heading). Checks that:
* First child of callout box should be a lvl 2 header with
known title & CSS style
* Callout box must h... | [
"def",
"_validate_one_callout",
"(",
"self",
",",
"callout_node",
")",
":",
"heading_node",
"=",
"callout_node",
".",
"children",
"[",
"0",
"]",
"valid_head_lvl",
"=",
"self",
".",
"ast",
".",
"is_heading",
"(",
"heading_node",
",",
"heading_level",
"=",
"2",
... | [
240,
4
] | [
293,
18
] | python | en | ['en', 'error', 'th'] | False |
MarkdownValidator._validate_callouts | (self) |
Validate all sections that appear as callouts
The style is a better determinant of callout than the title
|
Validate all sections that appear as callouts | def _validate_callouts(self):
"""
Validate all sections that appear as callouts
The style is a better determinant of callout than the title
"""
callout_nodes = self.ast.get_callouts()
callouts_valid = True
# Validate all the callout nodes present
for n i... | [
"def",
"_validate_callouts",
"(",
"self",
")",
":",
"callout_nodes",
"=",
"self",
".",
"ast",
".",
"get_callouts",
"(",
")",
"callouts_valid",
"=",
"True",
"# Validate all the callout nodes present",
"for",
"n",
"in",
"callout_nodes",
":",
"res",
"=",
"self",
".... | [
295,
4
] | [
332,
70
] | python | en | ['en', 'error', 'th'] | False |
MarkdownValidator._validate_one_html_link | (self, link_node, check_text=False) |
Any local html file being linked was generated as part of the lesson.
Therefore, file links (.html) must have a Markdown file
in the expected folder.
The title of the linked Markdown document should match the link text.
|
Any local html file being linked was generated as part of the lesson.
Therefore, file links (.html) must have a Markdown file
in the expected folder. | def _validate_one_html_link(self, link_node, check_text=False):
"""
Any local html file being linked was generated as part of the lesson.
Therefore, file links (.html) must have a Markdown file
in the expected folder.
The title of the linked Markdown document should match th... | [
"def",
"_validate_one_html_link",
"(",
"self",
",",
"link_node",
",",
"check_text",
"=",
"False",
")",
":",
"dest",
",",
"link_text",
"=",
"self",
".",
"ast",
".",
"get_link_info",
"(",
"link_node",
")",
"# HTML files in same folder are made from Markdown; special tes... | [
335,
4
] | [
376,
19
] | python | en | ['en', 'error', 'th'] | False |
MarkdownValidator._validate_one_link | (self, link_node, check_text=False) | Logic to validate a single link to a file asset
Performs special checks for links to a local markdown file.
For links or images, just verify that a file exists.
| Logic to validate a single link to a file asset | def _validate_one_link(self, link_node, check_text=False):
"""Logic to validate a single link to a file asset
Performs special checks for links to a local markdown file.
For links or images, just verify that a file exists.
"""
dest, link_text = self.ast.get_link_info(link_node)... | [
"def",
"_validate_one_link",
"(",
"self",
",",
"link_node",
",",
"check_text",
"=",
"False",
")",
":",
"dest",
",",
"link_text",
"=",
"self",
".",
"ast",
".",
"get_link_info",
"(",
"link_node",
")",
"if",
"re",
".",
"match",
"(",
"r\"^[\\w,\\s-]+\\.(html?)\"... | [
378,
4
] | [
411,
19
] | python | en | ['en', 'en', 'en'] | True |
MarkdownValidator._partition_links | (self) | Fetch links in document. If this template has special requirements
for link text (eg only some links' text should match dest page title),
filter the list accordingly.
Default behavior: don't check the text of any links | Fetch links in document. If this template has special requirements
for link text (eg only some links' text should match dest page title),
filter the list accordingly. | def _partition_links(self):
"""Fetch links in document. If this template has special requirements
for link text (eg only some links' text should match dest page title),
filter the list accordingly.
Default behavior: don't check the text of any links"""
check_text = []
no... | [
"def",
"_partition_links",
"(",
"self",
")",
":",
"check_text",
"=",
"[",
"]",
"no_check_text",
"=",
"self",
".",
"ast",
".",
"find_external_links",
"(",
")",
"return",
"check_text",
",",
"no_check_text"
] | [
413,
4
] | [
422,
40
] | python | en | ['en', 'en', 'en'] | True |
MarkdownValidator._validate_links | (self) | Validate all references to external content
This includes links AND images: these are the two types of node that
CommonMark assigns a .destination property | Validate all references to external content | def _validate_links(self):
"""Validate all references to external content
This includes links AND images: these are the two types of node that
CommonMark assigns a .destination property"""
check_text, no_check_text = self._partition_links()
valid = True
for link_node in... | [
"def",
"_validate_links",
"(",
"self",
")",
":",
"check_text",
",",
"no_check_text",
"=",
"self",
".",
"_partition_links",
"(",
")",
"valid",
"=",
"True",
"for",
"link_node",
"in",
"check_text",
":",
"res",
"=",
"self",
".",
"_validate_one_link",
"(",
"link_... | [
424,
4
] | [
439,
20
] | python | en | ['en', 'en', 'en'] | True |
MarkdownValidator._run_tests | (self) |
Let user override the list of tests to be performed.
Error trapping is handled by the validate() wrapper method.
|
Let user override the list of tests to be performed. | def _run_tests(self):
"""
Let user override the list of tests to be performed.
Error trapping is handled by the validate() wrapper method.
"""
tests = [self._validate_no_fixme(),
self._validate_doc_headers(),
self._validate_section_heading_order... | [
"def",
"_run_tests",
"(",
"self",
")",
":",
"tests",
"=",
"[",
"self",
".",
"_validate_no_fixme",
"(",
")",
",",
"self",
".",
"_validate_doc_headers",
"(",
")",
",",
"self",
".",
"_validate_section_heading_order",
"(",
")",
",",
"self",
".",
"_validate_callo... | [
441,
4
] | [
453,
25
] | python | en | ['en', 'error', 'th'] | False |
MarkdownValidator.validate | (self) | Perform all required validations. Wrap in exception handler | Perform all required validations. Wrap in exception handler | def validate(self):
"""Perform all required validations. Wrap in exception handler"""
try:
return self._run_tests()
except IndexError:
logging.error("Document is missing critical sections")
return False | [
"def",
"validate",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_run_tests",
"(",
")",
"except",
"IndexError",
":",
"logging",
".",
"error",
"(",
"\"Document is missing critical sections\"",
")",
"return",
"False"
] | [
455,
4
] | [
461,
24
] | python | en | ['en', 'en', 'en'] | True |
IndexPageValidator._partition_links | (self) | Check the text of every link in index.md | Check the text of every link in index.md | def _partition_links(self):
"""Check the text of every link in index.md"""
external_links = self.ast.find_external_links()
check_text = []
no_check_text = []
for link in external_links:
if '#' in link.destination:
no_check_text.append(link)
... | [
"def",
"_partition_links",
"(",
"self",
")",
":",
"external_links",
"=",
"self",
".",
"ast",
".",
"find_external_links",
"(",
")",
"check_text",
"=",
"[",
"]",
"no_check_text",
"=",
"[",
"]",
"for",
"link",
"in",
"external_links",
":",
"if",
"'#'",
"in",
... | [
475,
4
] | [
488,
40
] | python | en | ['en', 'en', 'en'] | True |
IndexPageValidator._validate_intro_section | (self) | Validate the intro section
It must be a paragraph, followed by blockquoted list of prereqs | Validate the intro section | def _validate_intro_section(self):
"""Validate the intro section
It must be a paragraph, followed by blockquoted list of prereqs"""
intro_block = self.ast.children[3]
intro_section = self.ast.is_paragraph(intro_block)
if not intro_section:
logging.error(
... | [
"def",
"_validate_intro_section",
"(",
"self",
")",
":",
"intro_block",
"=",
"self",
".",
"ast",
".",
"children",
"[",
"3",
"]",
"intro_section",
"=",
"self",
".",
"ast",
".",
"is_paragraph",
"(",
"intro_block",
")",
"if",
"not",
"intro_section",
":",
"log... | [
490,
4
] | [
502,
28
] | python | en | ['en', 'en', 'en'] | True |
TopicPageValidator._validate_has_no_headings | (self) | Check headings
The top-level document has no headings indicating subtopics.
The only valid subheadings are nested in blockquote elements | Check headings | def _validate_has_no_headings(self):
"""Check headings
The top-level document has no headings indicating subtopics.
The only valid subheadings are nested in blockquote elements"""
heading_nodes = self.ast.get_section_headings()
if len(heading_nodes) != 0:
# Individua... | [
"def",
"_validate_has_no_headings",
"(",
"self",
")",
":",
"heading_nodes",
"=",
"self",
".",
"ast",
".",
"get_section_headings",
"(",
")",
"if",
"len",
"(",
"heading_nodes",
")",
"!=",
"0",
":",
"# Individual heading msgs are logged by validate_section_heading_order",
... | [
521,
4
] | [
536,
19
] | python | en | ['en', 'st', 'en'] | False |
ReferencePageValidator._partition_links | (self) | For reference.md, only check that text of link matches
dest page subtitle if the link is in a heading | For reference.md, only check that text of link matches
dest page subtitle if the link is in a heading | def _partition_links(self):
"""For reference.md, only check that text of link matches
dest page subtitle if the link is in a heading"""
all_links = self.ast.find_external_links()
check_text = self.ast.find_external_links(
parent_crit=self.ast.is_heading)
dont_check_te... | [
"def",
"_partition_links",
"(",
"self",
")",
":",
"all_links",
"=",
"self",
".",
"ast",
".",
"find_external_links",
"(",
")",
"check_text",
"=",
"self",
".",
"ast",
".",
"find_external_links",
"(",
"parent_crit",
"=",
"self",
".",
"ast",
".",
"is_heading",
... | [
553,
4
] | [
560,
42
] | python | en | ['en', 'en', 'en'] | True |
ReferencePageValidator._validate_glossary_entry | (self, glossary_entry) | Validate glossary entry
Glossary entry must be formatted in conformance with Pandoc's
```definition_lists``` extension.
That syntax isn't supported by the CommonMark parser, so we identify
terms manually. | Validate glossary entry | def _validate_glossary_entry(self, glossary_entry):
"""Validate glossary entry
Glossary entry must be formatted in conformance with Pandoc's
```definition_lists``` extension.
That syntax isn't supported by the CommonMark parser, so we identify
terms manually."""
glossar... | [
"def",
"_validate_glossary_entry",
"(",
"self",
",",
"glossary_entry",
")",
":",
"glossary_keyword",
"=",
"glossary_entry",
"[",
"0",
"]",
"if",
"len",
"(",
"glossary_entry",
")",
"<",
"2",
":",
"logging",
".",
"error",
"(",
"\"In {0}: \"",
"\"Glossary entry '{1... | [
562,
4
] | [
589,
29
] | python | en | ['en', 'en', 'en'] | True |
ReferencePageValidator._validate_glossary | (self) | Validate the glossary section.
Assumes that the glossary is at the end of the file:
everything after the header. (and there must be a glossary section)
Verifies that the only things in the glossary are definition items.
| Validate the glossary section. | def _validate_glossary(self):
"""Validate the glossary section.
Assumes that the glossary is at the end of the file:
everything after the header. (and there must be a glossary section)
Verifies that the only things in the glossary are definition items.
"""
is_glossa... | [
"def",
"_validate_glossary",
"(",
"self",
")",
":",
"is_glossary_valid",
"=",
"True",
"in_glossary",
"=",
"False",
"for",
"node",
"in",
"self",
".",
"ast",
".",
"children",
":",
"if",
"in_glossary",
":",
"is_glossary_valid",
"=",
"is_glossary_valid",
"and",
"s... | [
591,
4
] | [
608,
32
] | python | en | ['en', 'en', 'en'] | True |
InstructorPageValidator._partition_links | (self) | For instructors.md, only check that text of link matches
dest page subtitle if the link is in a heading | For instructors.md, only check that text of link matches
dest page subtitle if the link is in a heading | def _partition_links(self):
"""For instructors.md, only check that text of link matches
dest page subtitle if the link is in a heading"""
all_links = self.ast.find_external_links()
check_text = self.ast.find_external_links(
parent_crit=self.ast.is_heading)
dont_check_... | [
"def",
"_partition_links",
"(",
"self",
")",
":",
"all_links",
"=",
"self",
".",
"ast",
".",
"find_external_links",
"(",
")",
"check_text",
"=",
"self",
".",
"ast",
".",
"find_external_links",
"(",
"parent_crit",
"=",
"self",
".",
"ast",
".",
"is_heading",
... | [
625,
4
] | [
632,
42
] | python | en | ['en', 'en', 'en'] | True |
LicensePageValidator._run_tests | (self) | Skip the base tests; just check md5 hash | Skip the base tests; just check md5 hash | def _run_tests(self):
"""Skip the base tests; just check md5 hash"""
# TODO: This hash is specific to the license for english-language repo
expected_hash = '051a04b8ffe580ba6b7018fb4fd72a50'
m = hashlib.md5()
try:
m.update(self.markdown)
except TypeError:
... | [
"def",
"_run_tests",
"(",
"self",
")",
":",
"# TODO: This hash is specific to the license for english-language repo",
"expected_hash",
"=",
"'051a04b8ffe580ba6b7018fb4fd72a50'",
"m",
"=",
"hashlib",
".",
"md5",
"(",
")",
"try",
":",
"m",
".",
"update",
"(",
"self",
".... | [
637,
4
] | [
652,
24
] | python | en | ['en', 'en', 'en'] | True |
fliplr_joints | (joints_3d, joints_3d_visible, img_width, flip_pairs) | Flip human joints horizontally.
Note:
num_keypoints: K
Args:
joints_3d (np.ndarray([K, 3])): Coordinates of keypoints.
joints_3d_visible (np.ndarray([K, 1])): Visibility of keypoints.
img_width (int): Image width.
flip_pairs (list[tuple()]): Pairs of keypoints which are... | Flip human joints horizontally. | def fliplr_joints(joints_3d, joints_3d_visible, img_width, flip_pairs):
"""Flip human joints horizontally.
Note:
num_keypoints: K
Args:
joints_3d (np.ndarray([K, 3])): Coordinates of keypoints.
joints_3d_visible (np.ndarray([K, 1])): Visibility of keypoints.
img_width (int)... | [
"def",
"fliplr_joints",
"(",
"joints_3d",
",",
"joints_3d_visible",
",",
"img_width",
",",
"flip_pairs",
")",
":",
"assert",
"len",
"(",
"joints_3d",
")",
"==",
"len",
"(",
"joints_3d_visible",
")",
"assert",
"img_width",
">",
"0",
"joints_3d_flipped",
"=",
"j... | [
9,
0
] | [
47,
55
] | python | en | ['en', 'hu', 'en'] | True |
flip_back | (output_flipped, flip_pairs, target_type='GaussianHeatMap') | Flip the flipped heatmaps back to the original form.
Note:
batch_size: N
num_keypoints: K
heatmap height: H
heatmap width: W
Args:
output_flipped (np.ndarray[N, K, H, W]): The output heatmaps obtained
from the flipped images.
flip_pairs (list[tuple()... | Flip the flipped heatmaps back to the original form. | def flip_back(output_flipped, flip_pairs, target_type='GaussianHeatMap'):
"""Flip the flipped heatmaps back to the original form.
Note:
batch_size: N
num_keypoints: K
heatmap height: H
heatmap width: W
Args:
output_flipped (np.ndarray[N, K, H, W]): The output heatma... | [
"def",
"flip_back",
"(",
"output_flipped",
",",
"flip_pairs",
",",
"target_type",
"=",
"'GaussianHeatMap'",
")",
":",
"assert",
"output_flipped",
".",
"ndim",
"==",
"4",
",",
"'output_flipped should be [batch_size, num_keypoints, height, width]'",
"assert",
"target_type",
... | [
50,
0
] | [
88,
30
] | python | en | ['en', 'en', 'en'] | True |
transform_preds | (coords, center, scale, output_size, use_udp=False) | Get final keypoint predictions from heatmaps and transform them back to
the image.
First calculate the transformation matrix from `get_affine_transform()`,
then affine transform the predicted keypoint coordinates back
to the image.
Note:
num_keypoints: K
Args:
coords (np.ndarr... | Get final keypoint predictions from heatmaps and transform them back to
the image. | def transform_preds(coords, center, scale, output_size, use_udp=False):
"""Get final keypoint predictions from heatmaps and transform them back to
the image.
First calculate the transformation matrix from `get_affine_transform()`,
then affine transform the predicted keypoint coordinates back
to the... | [
"def",
"transform_preds",
"(",
"coords",
",",
"center",
",",
"scale",
",",
"output_size",
",",
"use_udp",
"=",
"False",
")",
":",
"assert",
"coords",
".",
"shape",
"[",
"1",
"]",
"in",
"(",
"2",
",",
"4",
",",
"5",
")",
"assert",
"len",
"(",
"cente... | [
91,
0
] | [
139,
24
] | python | en | ['en', 'en', 'en'] | True |
get_affine_transform | (center,
scale,
rot,
output_size,
shift=(0., 0.),
inv=False) | Get the affine transform matrix, given the center/scale/rot/output_size.
Args:
center (np.ndarray[2, ]): Center of the bounding box (x, y).
scale (np.ndarray[2, ]): Scale of the bounding box
wrt [width, height].
rot (float): Rotation angle (degree).
output_size (np.ndarr... | Get the affine transform matrix, given the center/scale/rot/output_size. | def get_affine_transform(center,
scale,
rot,
output_size,
shift=(0., 0.),
inv=False):
"""Get the affine transform matrix, given the center/scale/rot/output_size.
Args:
center (np... | [
"def",
"get_affine_transform",
"(",
"center",
",",
"scale",
",",
"rot",
",",
"output_size",
",",
"shift",
"=",
"(",
"0.",
",",
"0.",
")",
",",
"inv",
"=",
"False",
")",
":",
"assert",
"len",
"(",
"center",
")",
"==",
"2",
"assert",
"len",
"(",
"sca... | [
142,
0
] | [
196,
16
] | python | en | ['en', 'en', 'en'] | True |
affine_transform | (pt, trans_mat) | Apply an affine transformation to the points.
Args:
pt (np.ndarray): a 2 dimensional point to be transformed
trans_mat (np.ndarray): 2x3 matrix of an affine transform
Returns:
np.ndarray: Transformed points.
| Apply an affine transformation to the points. | def affine_transform(pt, trans_mat):
"""Apply an affine transformation to the points.
Args:
pt (np.ndarray): a 2 dimensional point to be transformed
trans_mat (np.ndarray): 2x3 matrix of an affine transform
Returns:
np.ndarray: Transformed points.
"""
assert len(pt) == 2
... | [
"def",
"affine_transform",
"(",
"pt",
",",
"trans_mat",
")",
":",
"assert",
"len",
"(",
"pt",
")",
"==",
"2",
"new_pt",
"=",
"np",
".",
"array",
"(",
"trans_mat",
")",
"@",
"np",
".",
"array",
"(",
"[",
"pt",
"[",
"0",
"]",
",",
"pt",
"[",
"1",... | [
199,
0
] | [
212,
17
] | python | en | ['en', 'en', 'en'] | True |
_get_3rd_point | (a, b) | To calculate the affine matrix, three pairs of points are required. This
function is used to get the 3rd point, given 2D points a & b.
The 3rd point is defined by rotating vector `a - b` by 90 degrees
anticlockwise, using b as the rotation center.
Args:
a (np.ndarray): point(x,y)
b (np... | To calculate the affine matrix, three pairs of points are required. This
function is used to get the 3rd point, given 2D points a & b. | def _get_3rd_point(a, b):
"""To calculate the affine matrix, three pairs of points are required. This
function is used to get the 3rd point, given 2D points a & b.
The 3rd point is defined by rotating vector `a - b` by 90 degrees
anticlockwise, using b as the rotation center.
Args:
a (np.n... | [
"def",
"_get_3rd_point",
"(",
"a",
",",
"b",
")",
":",
"assert",
"len",
"(",
"a",
")",
"==",
"2",
"assert",
"len",
"(",
"b",
")",
"==",
"2",
"direction",
"=",
"a",
"-",
"b",
"third_pt",
"=",
"b",
"+",
"np",
".",
"array",
"(",
"[",
"-",
"direc... | [
215,
0
] | [
234,
19
] | python | en | ['en', 'en', 'en'] | True |
rotate_point | (pt, angle_rad) | Rotate a point by an angle.
Args:
pt (list[float]): 2 dimensional point to be rotated
angle_rad (float): rotation angle by radian
Returns:
list[float]: Rotated point.
| Rotate a point by an angle. | def rotate_point(pt, angle_rad):
"""Rotate a point by an angle.
Args:
pt (list[float]): 2 dimensional point to be rotated
angle_rad (float): rotation angle by radian
Returns:
list[float]: Rotated point.
"""
assert len(pt) == 2
sn, cs = np.sin(angle_rad), np.cos(angle_ra... | [
"def",
"rotate_point",
"(",
"pt",
",",
"angle_rad",
")",
":",
"assert",
"len",
"(",
"pt",
")",
"==",
"2",
"sn",
",",
"cs",
"=",
"np",
".",
"sin",
"(",
"angle_rad",
")",
",",
"np",
".",
"cos",
"(",
"angle_rad",
")",
"new_x",
"=",
"pt",
"[",
"0",... | [
237,
0
] | [
253,
21
] | python | en | ['en', 'en', 'en'] | True |
test_empty_indexing | () | Regression test for ticket 1948. | Regression test for ticket 1948. | def test_empty_indexing():
"""Regression test for ticket 1948."""
# Check that indexing a chararray with an empty list/array returns an
# empty chararray instead of a chararray with a single empty string in it.
s = np.chararray((4,))
assert_(s[[]].size == 0) | [
"def",
"test_empty_indexing",
"(",
")",
":",
"# Check that indexing a chararray with an empty list/array returns an",
"# empty chararray instead of a chararray with a single empty string in it.",
"s",
"=",
"np",
".",
"chararray",
"(",
"(",
"4",
",",
")",
")",
"assert_",
"(",
... | [
686,
0
] | [
691,
28
] | python | en | ['en', 'en', 'en'] | True |
TestOperations.test_mod | (self) | Ticket #856 | Ticket #856 | def test_mod(self):
"""Ticket #856"""
F = np.array([['%d', '%f'], ['%s', '%r']]).view(np.chararray)
C = np.array([[3, 7], [19, 1]])
FC = np.array([['3', '7.000000'],
['19', '1']]).view(np.chararray)
assert_array_equal(FC, F % C)
A = np.array([['%.3... | [
"def",
"test_mod",
"(",
"self",
")",
":",
"F",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"'%d'",
",",
"'%f'",
"]",
",",
"[",
"'%s'",
",",
"'%r'",
"]",
"]",
")",
".",
"view",
"(",
"np",
".",
"chararray",
")",
"C",
"=",
"np",
".",
"array",
"(",... | [
644,
4
] | [
657,
54
] | python | de | ['en', 'de', 'ur'] | False |
TestOperations.test_slice | (self) | Regression test for https://github.com/numpy/numpy/issues/5982 | Regression test for https://github.com/numpy/numpy/issues/5982 | def test_slice(self):
"""Regression test for https://github.com/numpy/numpy/issues/5982"""
arr = np.array([['abc ', 'def '], ['geh ', 'ijk ']],
dtype='S4').view(np.chararray)
sl1 = arr[:]
assert_array_equal(sl1, arr)
assert_(sl1.base is arr)
assert... | [
"def",
"test_slice",
"(",
"self",
")",
":",
"arr",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"'abc '",
",",
"'def '",
"]",
",",
"[",
"'geh '",
",",
"'ijk '",
"]",
"]",
",",
"dtype",
"=",
"'S4'",
")",
".",
"view",
"(",
"np",
".",
"chararray",
")",... | [
668,
4
] | [
683,
36
] | python | en | ['en', 'en', 'en'] | True |
test_quantization | (tmpdir, observe, fuse) | Parity test for quant model | Parity test for quant model | def test_quantization(tmpdir, observe, fuse):
"""Parity test for quant model"""
seed_everything(42)
dm = RegressDataModule()
trainer_args = dict(
default_root_dir=tmpdir,
max_epochs=10,
gpus=1 if torch.cuda.is_available() else None,
)
model = RegressionModel()
qmodel ... | [
"def",
"test_quantization",
"(",
"tmpdir",
",",
"observe",
",",
"fuse",
")",
":",
"seed_everything",
"(",
"42",
")",
"dm",
"=",
"RegressDataModule",
"(",
")",
"trainer_args",
"=",
"dict",
"(",
"default_root_dir",
"=",
"tmpdir",
",",
"max_epochs",
"=",
"10",
... | [
32,
0
] | [
63,
60
] | python | en | ['en', 'fr', 'en'] | True |
test_quantize_torchscript | (tmpdir) | Test converting to torchscipt | Test converting to torchscipt | def test_quantize_torchscript(tmpdir):
"""Test converting to torchscipt """
dm = RegressDataModule()
qmodel = RegressionModel()
qcb = QuantizationAwareTraining(input_compatible=False)
trainer = Trainer(callbacks=[qcb], default_root_dir=tmpdir, max_epochs=1)
trainer.fit(qmodel, datamodule=dm)
... | [
"def",
"test_quantize_torchscript",
"(",
"tmpdir",
")",
":",
"dm",
"=",
"RegressDataModule",
"(",
")",
"qmodel",
"=",
"RegressionModel",
"(",
")",
"qcb",
"=",
"QuantizationAwareTraining",
"(",
"input_compatible",
"=",
"False",
")",
"trainer",
"=",
"Trainer",
"("... | [
67,
0
] | [
79,
36
] | python | en | ['en', 'en', 'en'] | True |
test_quantization_exceptions | (tmpdir) | Test wrong fuse layers | Test wrong fuse layers | def test_quantization_exceptions(tmpdir):
"""Test wrong fuse layers"""
with pytest.raises(MisconfigurationException, match='Unsupported qconfig'):
QuantizationAwareTraining(qconfig=['abc'])
with pytest.raises(MisconfigurationException, match='Unsupported observer type'):
QuantizationAwareTr... | [
"def",
"test_quantization_exceptions",
"(",
"tmpdir",
")",
":",
"with",
"pytest",
".",
"raises",
"(",
"MisconfigurationException",
",",
"match",
"=",
"'Unsupported qconfig'",
")",
":",
"QuantizationAwareTraining",
"(",
"qconfig",
"=",
"[",
"'abc'",
"]",
")",
"with... | [
83,
0
] | [
101,
70
] | python | en | ['en', 'en', 'en'] | True |
test_quantization_triggers | (tmpdir, trigger_fn, expected_count) | Test how many times the quant is called | Test how many times the quant is called | def test_quantization_triggers(tmpdir, trigger_fn, expected_count):
"""Test how many times the quant is called"""
dm = RegressDataModule()
qmodel = RegressionModel()
qcb = QuantizationAwareTraining(collect_quantization=trigger_fn)
trainer = Trainer(
callbacks=[qcb],
default_root_dir... | [
"def",
"test_quantization_triggers",
"(",
"tmpdir",
",",
"trigger_fn",
",",
"expected_count",
")",
":",
"dm",
"=",
"RegressDataModule",
"(",
")",
"qmodel",
"=",
"RegressionModel",
"(",
")",
"qcb",
"=",
"QuantizationAwareTraining",
"(",
"collect_quantization",
"=",
... | [
126,
0
] | [
140,
47
] | python | en | ['en', 'en', 'en'] | True |
iou | (
pred: torch.Tensor,
target: torch.Tensor,
ignore_index: Optional[int] = None,
absent_score: float = 0.0,
threshold: float = 0.5,
num_classes: Optional[int] = None,
reduction: str = 'elementwise_mean',
) | r"""
Computes `Intersection over union, or Jaccard index calculation <https://en.wikipedia.org/wiki/Jaccard_index>`_:
.. math:: J(A,B) = \frac{|A\cap B|}{|A\cup B|}
Where: :math:`A` and :math:`B` are both tensors of the same size,
containing integer class values. They may be subject to conversion from... | r"""
Computes `Intersection over union, or Jaccard index calculation <https://en.wikipedia.org/wiki/Jaccard_index>`_: | def iou(
pred: torch.Tensor,
target: torch.Tensor,
ignore_index: Optional[int] = None,
absent_score: float = 0.0,
threshold: float = 0.5,
num_classes: Optional[int] = None,
reduction: str = 'elementwise_mean',
) -> torch.Tensor:
r"""
Computes `Intersection over union, or Jaccard inde... | [
"def",
"iou",
"(",
"pred",
":",
"torch",
".",
"Tensor",
",",
"target",
":",
"torch",
".",
"Tensor",
",",
"ignore_index",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
"absent_score",
":",
"float",
"=",
"0.0",
",",
"threshold",
":",
"float",
"="... | [
44,
0
] | [
109,
89
] | python | cy | ['en', 'cy', 'hi'] | False |
paint | (str, color='r') | Utility func, for printing colorful logs in console...
@args:
--
str : String to be modified.
color : color code to which the string will be formed. default is 'r'=RED
@returns:
--
str : final modified string with foreground color as per parameters.
| Utility func, for printing colorful logs in console... | def paint(str, color='r'):
'''Utility func, for printing colorful logs in console...
@args:
--
str : String to be modified.
color : color code to which the string will be formed. default is 'r'=RED
@returns:
--
str : final modified string with foreground color as per parameters.
'... | [
"def",
"paint",
"(",
"str",
",",
"color",
"=",
"'r'",
")",
":",
"if",
"color",
"in",
"switcher",
":",
"str",
"=",
"switcher",
"[",
"color",
"]",
"+",
"str",
"+",
"Style",
".",
"RESET_ALL",
"return",
"str"
] | [
50,
0
] | [
65,
14
] | python | en | ['en', 'en', 'en'] | True |
find_tf_idf | (file_names=['./../test/testdata'], prev_file_path=None, dump_path=None) | Function to create a TF-IDF list of dictionaries for a corpus of docs.
If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding)
and also re-generate a new tfidf list which overrides over an old one by mentioning its path.
@Args:
--
... | Function to create a TF-IDF list of dictionaries for a corpus of docs.
If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding)
and also re-generate a new tfidf list which overrides over an old one by mentioning its path. | def find_tf_idf(file_names=['./../test/testdata'], prev_file_path=None, dump_path=None):
'''Function to create a TF-IDF list of dictionaries for a corpus of docs.
If you opt for dumping the data, you can provide a file_path with .tfidfpkl extension(standard made for better understanding)
and also re-generat... | [
"def",
"find_tf_idf",
"(",
"file_names",
"=",
"[",
"'./../test/testdata'",
"]",
",",
"prev_file_path",
"=",
"None",
",",
"dump_path",
"=",
"None",
")",
":",
"tf_idf",
"=",
"[",
"]",
"# will hold a dict of word_count for every doc(line in a doc in this case)",
"idf",
"... | [
71,
0
] | [
138,
22
] | python | en | ['en', 'en', 'en'] | True |
exc_iter | (*args) |
Iterate over Cartesian product of *args, and if an exception is raised,
add information of the current iterate.
|
Iterate over Cartesian product of *args, and if an exception is raised,
add information of the current iterate.
| def exc_iter(*args):
"""
Iterate over Cartesian product of *args, and if an exception is raised,
add information of the current iterate.
"""
value = [None]
def iterate():
for v in itertools.product(*args):
value[0] = v
yield v
try:
yield iterate()
... | [
"def",
"exc_iter",
"(",
"*",
"args",
")",
":",
"value",
"=",
"[",
"None",
"]",
"def",
"iterate",
"(",
")",
":",
"for",
"v",
"in",
"itertools",
".",
"product",
"(",
"*",
"args",
")",
":",
"value",
"[",
"0",
"]",
"=",
"v",
"yield",
"v",
"try",
... | [
45,
0
] | [
64,
33
] | python | en | ['en', 'error', 'th'] | False |
test_v1_4_0_deprecated_trainer_device_distrib | () | Test that Trainer attributes works fine. | Test that Trainer attributes works fine. | def test_v1_4_0_deprecated_trainer_device_distrib():
"""Test that Trainer attributes works fine."""
trainer = Trainer()
trainer.accelerator_connector._distrib_type = None
trainer.accelerator_connector._device_type = None
with pytest.deprecated_call(match='deprecated in v1.2 and will be removed in v... | [
"def",
"test_v1_4_0_deprecated_trainer_device_distrib",
"(",
")",
":",
"trainer",
"=",
"Trainer",
"(",
")",
"trainer",
".",
"accelerator_connector",
".",
"_distrib_type",
"=",
"None",
"trainer",
".",
"accelerator_connector",
".",
"_device_type",
"=",
"None",
"with",
... | [
64,
0
] | [
108,
34
] | python | en | ['en', 'de', 'en'] | True |
search4vowels | (phrase: str) | Return any vowels found in a supplied phrase. | Return any vowels found in a supplied phrase. | def search4vowels(phrase: str) -> set:
"""Return any vowels found in a supplied phrase."""
vowels = set('aeiou')
return vowels.intersection(set(phrase)) | [
"def",
"search4vowels",
"(",
"phrase",
":",
"str",
")",
"->",
"set",
":",
"vowels",
"=",
"set",
"(",
"'aeiou'",
")",
"return",
"vowels",
".",
"intersection",
"(",
"set",
"(",
"phrase",
")",
")"
] | [
1,
0
] | [
4,
43
] | python | en | ['en', 'en', 'en'] | True |
search4letters | (phrase: str, letters: str='aeiou') | Return a set of the 'letters' found in 'phrase'. | Return a set of the 'letters' found in 'phrase'. | def search4letters(phrase: str, letters: str='aeiou') -> set:
"""Return a set of the 'letters' found in 'phrase'."""
return set(letters).intersection(set(phrase)) | [
"def",
"search4letters",
"(",
"phrase",
":",
"str",
",",
"letters",
":",
"str",
"=",
"'aeiou'",
")",
"->",
"set",
":",
"return",
"set",
"(",
"letters",
")",
".",
"intersection",
"(",
"set",
"(",
"phrase",
")",
")"
] | [
7,
0
] | [
9,
49
] | python | en | ['en', 'en', 'en'] | True |
_demo_mm_inputs | (input_shape=(1, 3, 256, 256)) | Create a superset of inputs needed to run test or train batches.
Args:
input_shape (tuple):
input batch dimensions
| Create a superset of inputs needed to run test or train batches. | def _demo_mm_inputs(input_shape=(1, 3, 256, 256)):
"""Create a superset of inputs needed to run test or train batches.
Args:
input_shape (tuple):
input batch dimensions
"""
(N, C, H, W) = input_shape
rng = np.random.RandomState(0)
imgs = rng.rand(*input_shape)
target =... | [
"def",
"_demo_mm_inputs",
"(",
"input_shape",
"=",
"(",
"1",
",",
"3",
",",
"256",
",",
"256",
")",
")",
":",
"(",
"N",
",",
"C",
",",
"H",
",",
"W",
")",
"=",
"input_shape",
"rng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"0",
")",
... | [
83,
0
] | [
120,
20
] | python | en | ['en', 'en', 'en'] | True |
test_model_properties_resume_from_checkpoint | (tmpdir) |
Test that properties like `current_epoch` and `global_step`
in model and trainer are always the same.
|
Test that properties like `current_epoch` and `global_step`
in model and trainer are always the same.
| def test_model_properties_resume_from_checkpoint(tmpdir):
"""
Test that properties like `current_epoch` and `global_step`
in model and trainer are always the same.
"""
model = BoringModel()
checkpoint_callback = ModelCheckpoint(dirpath=tmpdir, monitor="val_loss", save_last=True)
trainer_args... | [
"def",
"test_model_properties_resume_from_checkpoint",
"(",
"tmpdir",
")",
":",
"model",
"=",
"BoringModel",
"(",
")",
"checkpoint_callback",
"=",
"ModelCheckpoint",
"(",
"dirpath",
"=",
"tmpdir",
",",
"monitor",
"=",
"\"val_loss\"",
",",
"save_last",
"=",
"True",
... | [
109,
0
] | [
129,
22
] | python | en | ['en', 'error', 'th'] | False |
test_try_resume_from_non_existing_checkpoint | (tmpdir) | Test that trying to resume from non-existing `resume_from_checkpoint` fail without error. | Test that trying to resume from non-existing `resume_from_checkpoint` fail without error. | def test_try_resume_from_non_existing_checkpoint(tmpdir):
""" Test that trying to resume from non-existing `resume_from_checkpoint` fail without error."""
dm = ClassifDataModule()
model = ClassificationModel()
checkpoint_cb = ModelCheckpoint(dirpath=tmpdir, monitor="val_loss", save_last=True)
traine... | [
"def",
"test_try_resume_from_non_existing_checkpoint",
"(",
"tmpdir",
")",
":",
"dm",
"=",
"ClassifDataModule",
"(",
")",
"model",
"=",
"ClassificationModel",
"(",
")",
"checkpoint_cb",
"=",
"ModelCheckpoint",
"(",
"dirpath",
"=",
"tmpdir",
",",
"monitor",
"=",
"\... | [
132,
0
] | [
149,
107
] | python | en | ['en', 'en', 'en'] | True |
test_callbacks_state_resume_from_checkpoint | (tmpdir) | Test that resuming from a checkpoint restores callbacks that persist state. | Test that resuming from a checkpoint restores callbacks that persist state. | def test_callbacks_state_resume_from_checkpoint(tmpdir):
""" Test that resuming from a checkpoint restores callbacks that persist state. """
dm = ClassifDataModule()
model = ClassificationModel()
callback_capture = CaptureCallbacksBeforeTraining()
def get_trainer_args():
checkpoint = ModelC... | [
"def",
"test_callbacks_state_resume_from_checkpoint",
"(",
"tmpdir",
")",
":",
"dm",
"=",
"ClassifDataModule",
"(",
")",
"model",
"=",
"ClassificationModel",
"(",
")",
"callback_capture",
"=",
"CaptureCallbacksBeforeTraining",
"(",
")",
"def",
"get_trainer_args",
"(",
... | [
159,
0
] | [
191,
68
] | python | en | ['en', 'en', 'en'] | True |
test_callbacks_references_resume_from_checkpoint | (tmpdir) | Test that resuming from a checkpoint sets references as expected. | Test that resuming from a checkpoint sets references as expected. | def test_callbacks_references_resume_from_checkpoint(tmpdir):
""" Test that resuming from a checkpoint sets references as expected. """
dm = ClassifDataModule()
model = ClassificationModel()
args = {'default_root_dir': tmpdir, 'max_steps': 1, 'logger': False}
# initial training
checkpoint = Mod... | [
"def",
"test_callbacks_references_resume_from_checkpoint",
"(",
"tmpdir",
")",
":",
"dm",
"=",
"ClassifDataModule",
"(",
")",
"model",
"=",
"ClassificationModel",
"(",
")",
"args",
"=",
"{",
"'default_root_dir'",
":",
"tmpdir",
",",
"'max_steps'",
":",
"1",
",",
... | [
194,
0
] | [
213,
37
] | python | en | ['en', 'en', 'en'] | True |
test_running_test_pretrained_model_distrib_dp | (tmpdir) | Verify `test()` on pretrained model. | Verify `test()` on pretrained model. | def test_running_test_pretrained_model_distrib_dp(tmpdir):
"""Verify `test()` on pretrained model."""
tutils.set_random_master_port()
dm = ClassifDataModule()
model = CustomClassificationModelDP(lr=0.1)
# exp file to get meta
logger = tutils.get_default_logger(tmpdir)
# exp file to get w... | [
"def",
"test_running_test_pretrained_model_distrib_dp",
"(",
"tmpdir",
")",
":",
"tutils",
".",
"set_random_master_port",
"(",
")",
"dm",
"=",
"ClassifDataModule",
"(",
")",
"model",
"=",
"CustomClassificationModelDP",
"(",
"lr",
"=",
"0.1",
")",
"# exp file to get me... | [
217,
0
] | [
261,
79
] | python | en | ['en', 'en', 'en'] | True |
test_running_test_pretrained_model_distrib_ddp_spawn | (tmpdir) | Verify `test()` on pretrained model. | Verify `test()` on pretrained model. | def test_running_test_pretrained_model_distrib_ddp_spawn(tmpdir):
"""Verify `test()` on pretrained model."""
tutils.set_random_master_port()
dm = ClassifDataModule()
model = ClassificationModel()
# exp file to get meta
logger = tutils.get_default_logger(tmpdir)
# exp file to get weights
... | [
"def",
"test_running_test_pretrained_model_distrib_ddp_spawn",
"(",
"tmpdir",
")",
":",
"tutils",
".",
"set_random_master_port",
"(",
")",
"dm",
"=",
"ClassifDataModule",
"(",
")",
"model",
"=",
"ClassificationModel",
"(",
")",
"# exp file to get meta",
"logger",
"=",
... | [
265,
0
] | [
309,
92
] | python | en | ['en', 'en', 'en'] | True |
test_running_test_pretrained_model_cpu | (tmpdir) | Verify test() on pretrained model. | Verify test() on pretrained model. | def test_running_test_pretrained_model_cpu(tmpdir):
"""Verify test() on pretrained model."""
tutils.reset_seed()
dm = ClassifDataModule()
model = ClassificationModel()
# logger file to get meta
logger = tutils.get_default_logger(tmpdir)
# logger file to get weights
checkpoint = tutils.... | [
"def",
"test_running_test_pretrained_model_cpu",
"(",
"tmpdir",
")",
":",
"tutils",
".",
"reset_seed",
"(",
")",
"dm",
"=",
"ClassifDataModule",
"(",
")",
"model",
"=",
"ClassificationModel",
"(",
")",
"# logger file to get meta",
"logger",
"=",
"tutils",
".",
"ge... | [
312,
0
] | [
347,
69
] | python | en | ['en', 'en', 'en'] | True |
test_load_model_from_checkpoint | (tmpdir, model_template) | Verify test() on pretrained model. | Verify test() on pretrained model. | def test_load_model_from_checkpoint(tmpdir, model_template):
"""Verify test() on pretrained model."""
tutils.reset_seed()
model = model_template()
trainer_options = dict(
progress_bar_refresh_rate=0,
max_epochs=2,
limit_train_batches=2,
limit_val_batches=2,
limit... | [
"def",
"test_load_model_from_checkpoint",
"(",
"tmpdir",
",",
"model_template",
")",
":",
"tutils",
".",
"reset_seed",
"(",
")",
"model",
"=",
"model_template",
"(",
")",
"trainer_options",
"=",
"dict",
"(",
"progress_bar_refresh_rate",
"=",
"0",
",",
"max_epochs"... | [
351,
0
] | [
394,
38
] | python | en | ['en', 'en', 'en'] | True |
test_dp_resume | (tmpdir) | Make sure DP continues training correctly. | Make sure DP continues training correctly. | def test_dp_resume(tmpdir):
"""Make sure DP continues training correctly."""
model = CustomClassificationModelDP(lr=0.1)
dm = ClassifDataModule()
trainer_options = dict(max_epochs=1, gpus=2, accelerator='dp', default_root_dir=tmpdir)
# get logger
logger = tutils.get_default_logger(tmpdir)
... | [
"def",
"test_dp_resume",
"(",
"tmpdir",
")",
":",
"model",
"=",
"CustomClassificationModelDP",
"(",
"lr",
"=",
"0.1",
")",
"dm",
"=",
"ClassifDataModule",
"(",
")",
"trainer_options",
"=",
"dict",
"(",
"max_epochs",
"=",
"1",
",",
"gpus",
"=",
"2",
",",
... | [
398,
0
] | [
469,
20
] | python | en | ['en', 'en', 'en'] | True |
test_model_saving_loading | (tmpdir) | Tests use case where trainer saves the model, and user loads it from tags independently. | Tests use case where trainer saves the model, and user loads it from tags independently. | def test_model_saving_loading(tmpdir):
"""Tests use case where trainer saves the model, and user loads it from tags independently."""
model = BoringModel()
# logger file to get meta
logger = tutils.get_default_logger(tmpdir)
# fit model
trainer = Trainer(
max_epochs=1,
limit_tr... | [
"def",
"test_model_saving_loading",
"(",
"tmpdir",
")",
":",
"model",
"=",
"BoringModel",
"(",
")",
"# logger file to get meta",
"logger",
"=",
"tutils",
".",
"get_default_logger",
"(",
"tmpdir",
")",
"# fit model",
"trainer",
"=",
"Trainer",
"(",
"max_epochs",
"=... | [
472,
0
] | [
520,
72
] | python | en | ['en', 'en', 'en'] | True |
test_strict_model_load_more_params | (monkeypatch, tmpdir, tmpdir_server, url_ckpt) | Tests use case where trainer saves the model, and user loads it from tags independently. | Tests use case where trainer saves the model, and user loads it from tags independently. | def test_strict_model_load_more_params(monkeypatch, tmpdir, tmpdir_server, url_ckpt):
"""Tests use case where trainer saves the model, and user loads it from tags independently."""
# set $TORCH_HOME, which determines torch hub's cache path, to tmpdir
monkeypatch.setenv('TORCH_HOME', tmpdir)
model = Bor... | [
"def",
"test_strict_model_load_more_params",
"(",
"monkeypatch",
",",
"tmpdir",
",",
"tmpdir_server",
",",
"url_ckpt",
")",
":",
"# set $TORCH_HOME, which determines torch hub's cache path, to tmpdir",
"monkeypatch",
".",
"setenv",
"(",
"'TORCH_HOME'",
",",
"tmpdir",
")",
"... | [
524,
0
] | [
570,
9
] | python | en | ['en', 'en', 'en'] | True |
test_strict_model_load_less_params | (monkeypatch, tmpdir, tmpdir_server, url_ckpt) | Tests use case where trainer saves the model, and user loads it from tags independently. | Tests use case where trainer saves the model, and user loads it from tags independently. | def test_strict_model_load_less_params(monkeypatch, tmpdir, tmpdir_server, url_ckpt):
"""Tests use case where trainer saves the model, and user loads it from tags independently."""
# set $TORCH_HOME, which determines torch hub's cache path, to tmpdir
monkeypatch.setenv('TORCH_HOME', tmpdir)
model = Bor... | [
"def",
"test_strict_model_load_less_params",
"(",
"monkeypatch",
",",
"tmpdir",
",",
"tmpdir_server",
",",
"url_ckpt",
")",
":",
"# set $TORCH_HOME, which determines torch hub's cache path, to tmpdir",
"monkeypatch",
".",
"setenv",
"(",
"'TORCH_HOME'",
",",
"tmpdir",
")",
"... | [
574,
0
] | [
624,
9
] | python | en | ['en', 'en', 'en'] | True |
generate_header_file | (input_path) | Generates a c++ header file containing the api_version variable with the
correct value.
Args:
input_path: the file containing the API version (API_VERSION).
Returns:
the header file contents.
| Generates a c++ header file containing the api_version variable with the
correct value. | def generate_header_file(input_path):
"""Generates a c++ header file containing the api_version variable with the
correct value.
Args:
input_path: the file containing the API version (API_VERSION).
Returns:
the header file contents.
"""
version = utils.get_api_version(input_pat... | [
"def",
"generate_header_file",
"(",
"input_path",
")",
":",
"version",
"=",
"utils",
".",
"get_api_version",
"(",
"input_path",
")",
"oldest_version",
"=",
"utils",
".",
"compute_oldest_api_version",
"(",
"version",
")",
"header_file_contents",
"=",
"FILE_TEMPLATE",
... | [
21,
0
] | [
42,
31
] | python | en | ['en', 'en', 'en'] | True |
test_multi_gpu_early_stop_dp | (tmpdir) | Make sure DDP works. with early stopping | Make sure DDP works. with early stopping | def test_multi_gpu_early_stop_dp(tmpdir):
"""Make sure DDP works. with early stopping"""
tutils.set_random_master_port()
dm = ClassifDataModule()
model = CustomClassificationModelDP()
trainer_options = dict(
default_root_dir=tmpdir,
callbacks=[EarlyStopping(monitor='val_acc')],
... | [
"def",
"test_multi_gpu_early_stop_dp",
"(",
"tmpdir",
")",
":",
"tutils",
".",
"set_random_master_port",
"(",
")",
"dm",
"=",
"ClassifDataModule",
"(",
")",
"model",
"=",
"CustomClassificationModelDP",
"(",
")",
"trainer_options",
"=",
"dict",
"(",
"default_root_dir... | [
58,
0
] | [
75,
53
] | python | en | ['en', 'en', 'en'] | True |
digit_to_character | (digit) |
Convert a digit to character.
|
Convert a digit to character.
| def digit_to_character(digit):
"""
Convert a digit to character.
"""
return chr(digit+48) | [
"def",
"digit_to_character",
"(",
"digit",
")",
":",
"return",
"chr",
"(",
"digit",
"+",
"48",
")"
] | [
6,
0
] | [
10,
24
] | python | en | ['en', 'ja', 'th'] | False |
int_to_str | (num) |
Convert an integer to string.
|
Convert an integer to string.
| def int_to_str(num):
"""
Convert an integer to string.
"""
string = ""
while True:
digit = int(str(num%10).split(".")[0]) # Converting Float to Integer.
string = digit_to_character(digit).__add__(string)
try:
num = int(str(num).strip()[:-1]) ... | [
"def",
"int_to_str",
"(",
"num",
")",
":",
"string",
"=",
"\"\"",
"while",
"True",
":",
"digit",
"=",
"int",
"(",
"str",
"(",
"num",
"%",
"10",
")",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
")",
"# Converting Float to Integer.\r",
"string",
"=... | [
12,
0
] | [
24,
17
] | python | en | ['en', 'ja', 'th'] | False |
to_string | (something) |
Will be used to map integer and strings from fbzlist so that they all are strings and can be used in join.
|
Will be used to map integer and strings from fbzlist so that they all are strings and can be used in join.
| def to_string(something):
"""
Will be used to map integer and strings from fbzlist so that they all are strings and can be used in join.
"""
try:
return int_to_str(something)
except TypeError:
return something | [
"def",
"to_string",
"(",
"something",
")",
":",
"try",
":",
"return",
"int_to_str",
"(",
"something",
")",
"except",
"TypeError",
":",
"return",
"something"
] | [
27,
0
] | [
34,
24
] | python | en | ['en', 'ja', 'th'] | False |
test_deletion | () | Test deletion methods | Test deletion methods | def test_deletion():
""" Test deletion methods """
base_ami = "ami-1234abcd"
parser = parse_args(
[
'--keep-previous', '0',
'--mapping-key', 'name',
'--mapping-values', 'test-ami']
)
ec2 = boto3.client('ec2')
reservation = ec2.run_instances(
... | [
"def",
"test_deletion",
"(",
")",
":",
"base_ami",
"=",
"\"ami-1234abcd\"",
"parser",
"=",
"parse_args",
"(",
"[",
"'--keep-previous'",
",",
"'0'",
",",
"'--mapping-key'",
",",
"'name'",
",",
"'--mapping-values'",
",",
"'test-ami'",
"]",
")",
"ec2",
"=",
"boto... | [
23,
0
] | [
65,
45
] | python | ca | ['ca', 'da', 'en'] | False |
test_deletion_ami_min_days | () | Test deletion methods | Test deletion methods | def test_deletion_ami_min_days():
""" Test deletion methods """
# creating tests objects
first_ami = AMI()
first_ami.name = "test-ami"
first_ami.id = 'ami-28c2b348'
first_ami.creation_date = "2017-11-04T01:35:31.000Z"
second_ami = AMI()
second_ami.name = "test-ami"
second_ami.id = ... | [
"def",
"test_deletion_ami_min_days",
"(",
")",
":",
"# creating tests objects",
"first_ami",
"=",
"AMI",
"(",
")",
"first_ami",
".",
"name",
"=",
"\"test-ami\"",
"first_ami",
".",
"id",
"=",
"'ami-28c2b348'",
"first_ami",
".",
"creation_date",
"=",
"\"2017-11-04T01:... | [
70,
0
] | [
116,
44
] | python | ca | ['ca', 'da', 'en'] | False |
DDPPlugin.pre_backward | (self, closure_loss: torch.Tensor, should_accumulate: bool, optimizer: Optimizer, opt_idx: int) | Run before precision plugin executes backward | Run before precision plugin executes backward | def pre_backward(self, closure_loss: torch.Tensor, should_accumulate: bool, optimizer: Optimizer, opt_idx: int):
"""Run before precision plugin executes backward"""
if not self.lightning_module.automatic_optimization and self.model.require_backward_grad_sync:
prepare_for_backward(self.model,... | [
"def",
"pre_backward",
"(",
"self",
",",
"closure_loss",
":",
"torch",
".",
"Tensor",
",",
"should_accumulate",
":",
"bool",
",",
"optimizer",
":",
"Optimizer",
",",
"opt_idx",
":",
"int",
")",
":",
"if",
"not",
"self",
".",
"lightning_module",
".",
"autom... | [
270,
4
] | [
273,
58
] | python | en | ['eu', 'gl', 'en'] | False |
DDPPlugin.reduce | (self, tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean") |
Reduces a tensor from several distributed processes to one aggregated tensor.
Args:
tensor: the tensor to sync and reduce
group: the process group to gather results from. Defaults to all processes (world)
reduce_op: the reduction operation. Defaults to 'mean'/'avg'.... |
Reduces a tensor from several distributed processes to one aggregated tensor. | def reduce(self, tensor, group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean"):
"""
Reduces a tensor from several distributed processes to one aggregated tensor.
Args:
tensor: the tensor to sync and reduce
group: the process group to gather res... | [
"def",
"reduce",
"(",
"self",
",",
"tensor",
",",
"group",
":",
"Optional",
"[",
"Any",
"]",
"=",
"None",
",",
"reduce_op",
":",
"Optional",
"[",
"Union",
"[",
"ReduceOp",
",",
"str",
"]",
"]",
"=",
"\"mean\"",
")",
":",
"if",
"isinstance",
"(",
"t... | [
280,
4
] | [
295,
21
] | python | en | ['en', 'error', 'th'] | False |
calculate_background | (bg_type, bg_bounds, energy, intensity) | Calculates a numpy array representing the background. | Calculates a numpy array representing the background. | def calculate_background(bg_type, bg_bounds, energy, intensity):
"""Calculates a numpy array representing the background."""
background = intensity.copy()
if bg_type is None:
return np.zeros_like(energy)
if not bg_bounds:
bg_bounds = [energy.min(), energy.max()]
for lower, upper in z... | [
"def",
"calculate_background",
"(",
"bg_type",
",",
"bg_bounds",
",",
"energy",
",",
"intensity",
")",
":",
"background",
"=",
"intensity",
".",
"copy",
"(",
")",
"if",
"bg_type",
"is",
"None",
":",
"return",
"np",
".",
"zeros_like",
"(",
"energy",
")",
... | [
19,
0
] | [
41,
21
] | python | en | ['en', 'en', 'en'] | True |
intensity_at_energy | (energy, intensity, energy_value) | Gives back the intensity value at energy_value. | Gives back the intensity value at energy_value. | def intensity_at_energy(energy, intensity, energy_value):
"""Gives back the intensity value at energy_value."""
idx = np.searchsorted(energy, energy_value)
return intensity[idx] | [
"def",
"intensity_at_energy",
"(",
"energy",
",",
"intensity",
",",
"energy_value",
")",
":",
"idx",
"=",
"np",
".",
"searchsorted",
"(",
"energy",
",",
"energy_value",
")",
"return",
"intensity",
"[",
"idx",
"]"
] | [
44,
0
] | [
47,
25
] | python | en | ['en', 'en', 'en'] | True |
shirley | (energy, intensity, tol=1e-5, maxit=50) | Calculates shirley background for given x, y values. | Calculates shirley background for given x, y values. | def shirley(energy, intensity, tol=1e-5, maxit=50):
"""Calculates shirley background for given x, y values."""
if energy[-1] < energy[0]:
raise ValueError("Energy not increasing.")
if not is_equidistant(energy):
raise ValueError("Energy not evenly spaced.")
energy = energy[::-1]
int... | [
"def",
"shirley",
"(",
"energy",
",",
"intensity",
",",
"tol",
"=",
"1e-5",
",",
"maxit",
"=",
"50",
")",
":",
"if",
"energy",
"[",
"-",
"1",
"]",
"<",
"energy",
"[",
"0",
"]",
":",
"raise",
"ValueError",
"(",
"\"Energy not increasing.\"",
")",
"if",... | [
50,
0
] | [
85,
27
] | python | en | ['en', 'en', 'en'] | True |
linear_bg | (energy, intensity) | Calculates linear background for given x, y values. | Calculates linear background for given x, y values. | def linear_bg(energy, intensity):
"""Calculates linear background for given x, y values."""
samples = len(energy)
background = np.linspace(intensity[0], intensity[-1], samples)
return background | [
"def",
"linear_bg",
"(",
"energy",
",",
"intensity",
")",
":",
"samples",
"=",
"len",
"(",
"energy",
")",
"background",
"=",
"np",
".",
"linspace",
"(",
"intensity",
"[",
"0",
"]",
",",
"intensity",
"[",
"-",
"1",
"]",
",",
"samples",
")",
"return",
... | [
87,
0
] | [
91,
21
] | python | en | ['en', 'en', 'en'] | True |
is_equidistant | (energy, tol=1e-08) | Returns True only when energy is equidistant. | Returns True only when energy is equidistant. | def is_equidistant(energy, tol=1e-08):
"""Returns True only when energy is equidistant."""
spacings = np.unique(np.diff(energy))
for spacing in spacings[1:]:
if not np.isclose(spacing, spacings[0], atol=tol):
return False
return True | [
"def",
"is_equidistant",
"(",
"energy",
",",
"tol",
"=",
"1e-08",
")",
":",
"spacings",
"=",
"np",
".",
"unique",
"(",
"np",
".",
"diff",
"(",
"energy",
")",
")",
"for",
"spacing",
"in",
"spacings",
"[",
"1",
":",
"]",
":",
"if",
"not",
"np",
"."... | [
93,
0
] | [
99,
15
] | python | en | ['en', 'en', 'en'] | True |
make_increasing | (energy, intensity) | Makes energy increasing and sorts intensity accordingly. | Makes energy increasing and sorts intensity accordingly. | def make_increasing(energy, intensity):
"""Makes energy increasing and sorts intensity accordingly."""
idxes = energy.argsort()
return energy[idxes], intensity[idxes] | [
"def",
"make_increasing",
"(",
"energy",
",",
"intensity",
")",
":",
"idxes",
"=",
"energy",
".",
"argsort",
"(",
")",
"return",
"energy",
"[",
"idxes",
"]",
",",
"intensity",
"[",
"idxes",
"]"
] | [
101,
0
] | [
104,
42
] | python | en | ['en', 'en', 'en'] | True |
make_equidistant | (energy, intensity) | Makes x, y pair so that x is equidistant. | Makes x, y pair so that x is equidistant. | def make_equidistant(energy, intensity):
"""Makes x, y pair so that x is equidistant."""
spacings = np.unique(np.diff(energy))
if all([np.isclose(spacing, spacings[0]) for spacing in spacings[1:]]):
return energy, intensity
# eliminate spacings that are too small
while np.isclose(0, spacings... | [
"def",
"make_equidistant",
"(",
"energy",
",",
"intensity",
")",
":",
"spacings",
"=",
"np",
".",
"unique",
"(",
"np",
".",
"diff",
"(",
"energy",
")",
")",
"if",
"all",
"(",
"[",
"np",
".",
"isclose",
"(",
"spacing",
",",
"spacings",
"[",
"0",
"]"... | [
106,
0
] | [
117,
42
] | python | en | ['en', 'en', 'en'] | True |
validate_fragment | (type_name, fragment) | Validate a dictionary representing a JSON/YAML fragment against an Envoy API proto3 type.
Throws Protobuf errors on parsing exceptions, successful validations produce
no result.
Args:
type_name: a string providing the type name, e.g.
envoy.config.bootstrap.v3.Bootstrap.
fragment:... | Validate a dictionary representing a JSON/YAML fragment against an Envoy API proto3 type. | def validate_fragment(type_name, fragment):
"""Validate a dictionary representing a JSON/YAML fragment against an Envoy API proto3 type.
Throws Protobuf errors on parsing exceptions, successful validations produce
no result.
Args:
type_name: a string providing the type name, e.g.
env... | [
"def",
"validate_fragment",
"(",
"type_name",
",",
"fragment",
")",
":",
"json_fragment",
"=",
"json",
".",
"dumps",
"(",
"fragment",
",",
"skipkeys",
"=",
"True",
")",
"r",
"=",
"runfiles",
".",
"Create",
"(",
")",
"all_protos_pb_text_path",
"=",
"r",
"."... | [
54,
0
] | [
82,
63
] | python | en | ['en', 'en', 'en'] | True |
package_list_from_file | (file) | List up package name (not containing version and extras) from a package list file
| List up package name (not containing version and extras) from a package list file
| def package_list_from_file(file):
"""List up package name (not containing version and extras) from a package list file
"""
mocked_packages = []
with open(file, 'r') as fp:
for ln in fp.readlines():
# Example: `tqdm>=4.41.0` => `tqdm`
# `[` is for package with extras
... | [
"def",
"package_list_from_file",
"(",
"file",
")",
":",
"mocked_packages",
"=",
"[",
"]",
"with",
"open",
"(",
"file",
",",
"'r'",
")",
"as",
"fp",
":",
"for",
"ln",
"in",
"fp",
".",
"readlines",
"(",
")",
":",
"# Example: `tqdm>=4.41.0` => `tqdm`",
"# `[`... | [
307,
0
] | [
319,
26
] | python | en | ['en', 'en', 'en'] | True |
log_request | (req: 'flask_request', res: str) | Log details of the web request and the results. | Log details of the web request and the results. | def log_request(req: 'flask_request', res: str) -> None:
"""Log details of the web request and the results."""
# raise Exception("Something awful just happened.")
sleep(15) # This makes log_request really slow...
with UseDatabase(app.config['dbconfig']) as cursor:
_SQL = """insert into l... | [
"def",
"log_request",
"(",
"req",
":",
"'flask_request'",
",",
"res",
":",
"str",
")",
"->",
"None",
":",
"# raise Exception(\"Something awful just happened.\")",
"sleep",
"(",
"15",
")",
"# This makes log_request really slow...",
"with",
"UseDatabase",
"(",
"app",
".... | [
29,
0
] | [
45,
37
] | python | en | ['en', 'en', 'en'] | True |
do_search | () | Extract the posted data; perform the search; return results. | Extract the posted data; perform the search; return results. | def do_search() -> 'html':
"""Extract the posted data; perform the search; return results."""
phrase = request.form['phrase']
letters = request.form['letters']
title = 'Here are your results:'
results = str(search4letters(phrase, letters))
try:
t = Thread(target=log_request, args=(reques... | [
"def",
"do_search",
"(",
")",
"->",
"'html'",
":",
"phrase",
"=",
"request",
".",
"form",
"[",
"'phrase'",
"]",
"letters",
"=",
"request",
".",
"form",
"[",
"'letters'",
"]",
"title",
"=",
"'Here are your results:'",
"results",
"=",
"str",
"(",
"search4let... | [
49,
0
] | [
64,
48
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.