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
apply_subs_map
(line, map)
Do string replacements on line indicated by map
Do string replacements on line indicated by map
def apply_subs_map(line, map): """ Do string replacements on line indicated by map """ for key, val in map.items(): line = line.replace(key, val) return line
[ "def", "apply_subs_map", "(", "line", ",", "map", ")", ":", "for", "key", ",", "val", "in", "map", ".", "items", "(", ")", ":", "line", "=", "line", ".", "replace", "(", "key", ",", "val", ")", "return", "line" ]
[ 17, 0 ]
[ 23, 15 ]
python
en
['en', 'error', 'th']
False
copy_template
(template_dir, filename, dest_dir, map)
Copy template to file dest_name with indicated string substitutions Remove first level of template_dir to form subdirectory for dest
Copy template to file dest_name with indicated string substitutions
def copy_template(template_dir, filename, dest_dir, map): """ Copy template to file dest_name with indicated string substitutions Remove first level of template_dir to form subdirectory for dest """ if VERBOSE: print("create: %s + %s => %s" % (template_dir, filename, dest_dir)) with op...
[ "def", "copy_template", "(", "template_dir", ",", "filename", ",", "dest_dir", ",", "map", ")", ":", "if", "VERBOSE", ":", "print", "(", "\"create: %s + %s => %s\"", "%", "(", "template_dir", ",", "filename", ",", "dest_dir", ")", ")", "with", "open", "(", ...
[ 25, 0 ]
[ 44, 46 ]
python
en
['en', 'error', 'th']
False
create_files
(template_dir, dest_dir, proj_name)
Generate the files needed for the new target @param template_dir Where templates and dir structure are @param p4_source The file or directory holding P4 source code The directory 'template_dir' is scanned and a new version of each file there is created in the target directory. If template_dir...
Generate the files needed for the new target @param template_dir Where templates and dir structure are @param p4_source The file or directory holding P4 source code
def create_files(template_dir, dest_dir, proj_name): """ Generate the files needed for the new target @param template_dir Where templates and dir structure are @param p4_source The file or directory holding P4 source code The directory 'template_dir' is scanned and a new version of each file th...
[ "def", "create_files", "(", "template_dir", ",", "dest_dir", ",", "proj_name", ")", ":", "# The map of string replacements", "repl_map", "=", "{", "\"__PROJECT_NAME__\"", ":", "proj_name", "}", "if", "os", ".", "path", ".", "isdir", "(", "template_dir", ")", ":"...
[ 46, 0 ]
[ 76, 63 ]
python
en
['en', 'error', 'th']
False
DatabaseFeatures.supports_stddev
(self)
Confirm support for STDDEV and related stats functions SQLite supports STDDEV as an extension package; so connection.ops.check_expression_support() can't unilaterally rule out support for STDDEV. We need to manually check whether the call works.
Confirm support for STDDEV and related stats functions
def supports_stddev(self): """Confirm support for STDDEV and related stats functions SQLite supports STDDEV as an extension package; so connection.ops.check_expression_support() can't unilaterally rule out support for STDDEV. We need to manually check whether the call works. ...
[ "def", "supports_stddev", "(", "self", ")", ":", "with", "self", ".", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "'CREATE TABLE STDDEV_TEST (X INT)'", ")", "try", ":", "cursor", ".", "execute", "(", "'SELECT ST...
[ 58, 4 ]
[ 74, 26 ]
python
en
['en', 'en', 'en']
True
normalize_version_info
(py_version_info)
Convert a tuple of ints representing a Python version to one of length three. :param py_version_info: a tuple of ints representing a Python version, or None to specify no version. The tuple can have any length. :return: a tuple of length three if `py_version_info` is non-None. Otherwi...
Convert a tuple of ints representing a Python version to one of length three.
def normalize_version_info(py_version_info): # type: (Tuple[int, ...]) -> Tuple[int, int, int] """ Convert a tuple of ints representing a Python version to one of length three. :param py_version_info: a tuple of ints representing a Python version, or None to specify no version. The tuple ca...
[ "def", "normalize_version_info", "(", "py_version_info", ")", ":", "# type: (Tuple[int, ...]) -> Tuple[int, int, int]", "if", "len", "(", "py_version_info", ")", "<", "3", ":", "py_version_info", "+=", "(", "3", "-", "len", "(", "py_version_info", ")", ")", "*", "...
[ 92, 0 ]
[ 109, 47 ]
python
en
['en', 'error', 'th']
False
ensure_dir
(path)
os.path.makedirs without EEXIST.
os.path.makedirs without EEXIST.
def ensure_dir(path): # type: (AnyStr) -> None """os.path.makedirs without EEXIST.""" try: os.makedirs(path) except OSError as e: # Windows can raise spurious ENOTEMPTY errors. See #6426. if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY: raise
[ "def", "ensure_dir", "(", "path", ")", ":", "# type: (AnyStr) -> None", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", "OSError", "as", "e", ":", "# Windows can raise spurious ENOTEMPTY errors. See #6426.", "if", "e", ".", "errno", "!=", "errno", ...
[ 112, 0 ]
[ 120, 17 ]
python
en
['en', 'en', 'en']
True
rmtree_errorhandler
(func, path, exc_info)
On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.
On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.
def rmtree_errorhandler(func, path, exc_info): """On Windows, the files in .svn are read-only, so when rmtree() tries to remove them, an exception is thrown. We catch that here, remove the read-only attribute, and hopefully continue without problems.""" try: has_attr_readonly = not (os.stat(pat...
[ "def", "rmtree_errorhandler", "(", "func", ",", "path", ",", "exc_info", ")", ":", "try", ":", "has_attr_readonly", "=", "not", "(", "os", ".", "stat", "(", "path", ")", ".", "st_mode", "&", "stat", ".", "S_IWRITE", ")", "except", "(", "IOError", ",", ...
[ 144, 0 ]
[ 161, 13 ]
python
en
['en', 'en', 'en']
True
path_to_display
(path)
Convert a bytes (or text) path to text (unicode in Python 2) for display and logging purposes. This function should never error out. Also, this function is mainly needed for Python 2 since in Python 3 str paths are already text.
Convert a bytes (or text) path to text (unicode in Python 2) for display and logging purposes.
def path_to_display(path): # type: (Optional[Union[str, Text]]) -> Optional[Text] """ Convert a bytes (or text) path to text (unicode in Python 2) for display and logging purposes. This function should never error out. Also, this function is mainly needed for Python 2 since in Python 3 str path...
[ "def", "path_to_display", "(", "path", ")", ":", "# type: (Optional[Union[str, Text]]) -> Optional[Text]", "if", "path", "is", "None", ":", "return", "None", "if", "isinstance", "(", "path", ",", "text_type", ")", ":", "return", "path", "# Otherwise, path is a bytes o...
[ 164, 0 ]
[ 195, 23 ]
python
en
['en', 'error', 'th']
False
display_path
(path)
Gives the display value for a given path, making it relative to cwd if possible.
Gives the display value for a given path, making it relative to cwd if possible.
def display_path(path): # type: (Union[str, Text]) -> str """Gives the display value for a given path, making it relative to cwd if possible.""" path = os.path.normcase(os.path.abspath(path)) if sys.version_info[0] == 2: path = path.decode(sys.getfilesystemencoding(), 'replace') path...
[ "def", "display_path", "(", "path", ")", ":", "# type: (Union[str, Text]) -> str", "path", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ")", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2...
[ 198, 0 ]
[ 208, 15 ]
python
en
['en', 'en', 'en']
True
backup_dir
(dir, ext='.bak')
Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc)
Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc)
def backup_dir(dir, ext='.bak'): # type: (str, str) -> str """Figure out the name of a directory to back up the given dir to (adding .bak, .bak2, etc)""" n = 1 extension = ext while os.path.exists(dir + extension): n += 1 extension = ext + str(n) return dir + extension
[ "def", "backup_dir", "(", "dir", ",", "ext", "=", "'.bak'", ")", ":", "# type: (str, str) -> str", "n", "=", "1", "extension", "=", "ext", "while", "os", ".", "path", ".", "exists", "(", "dir", "+", "extension", ")", ":", "n", "+=", "1", "extension", ...
[ 211, 0 ]
[ 220, 26 ]
python
en
['en', 'en', 'en']
True
_check_no_input
(message)
Raise an error if no input is allowed.
Raise an error if no input is allowed.
def _check_no_input(message): # type: (str) -> None """Raise an error if no input is allowed.""" if os.environ.get('PIP_NO_INPUT'): raise Exception( 'No input was expected ($PIP_NO_INPUT set); question: {}'.format( message) )
[ "def", "_check_no_input", "(", "message", ")", ":", "# type: (str) -> None", "if", "os", ".", "environ", ".", "get", "(", "'PIP_NO_INPUT'", ")", ":", "raise", "Exception", "(", "'No input was expected ($PIP_NO_INPUT set); question: {}'", ".", "format", "(", "message",...
[ 231, 0 ]
[ 238, 9 ]
python
en
['en', 'lb', 'en']
True
ask
(message, options)
Ask the message interactively, with the given possible responses
Ask the message interactively, with the given possible responses
def ask(message, options): # type: (str, Iterable[str]) -> str """Ask the message interactively, with the given possible responses""" while 1: _check_no_input(message) response = input(message) response = response.strip().lower() if response not in options: print(...
[ "def", "ask", "(", "message", ",", "options", ")", ":", "# type: (str, Iterable[str]) -> str", "while", "1", ":", "_check_no_input", "(", "message", ")", "response", "=", "input", "(", "message", ")", "response", "=", "response", ".", "strip", "(", ")", ".",...
[ 241, 0 ]
[ 254, 27 ]
python
en
['en', 'en', 'en']
True
ask_input
(message)
Ask for input interactively.
Ask for input interactively.
def ask_input(message): # type: (str) -> str """Ask for input interactively.""" _check_no_input(message) return input(message)
[ "def", "ask_input", "(", "message", ")", ":", "# type: (str) -> str", "_check_no_input", "(", "message", ")", "return", "input", "(", "message", ")" ]
[ 257, 0 ]
[ 261, 25 ]
python
en
['en', 'en', 'en']
True
ask_password
(message)
Ask for a password interactively.
Ask for a password interactively.
def ask_password(message): # type: (str) -> str """Ask for a password interactively.""" _check_no_input(message) return getpass.getpass(message)
[ "def", "ask_password", "(", "message", ")", ":", "# type: (str) -> str", "_check_no_input", "(", "message", ")", "return", "getpass", ".", "getpass", "(", "message", ")" ]
[ 264, 0 ]
[ 268, 35 ]
python
en
['en', 'en', 'en']
True
tabulate
(rows)
Return a list of formatted rows and a list of column sizes. For example:: >>> tabulate([['foobar', 2000], [0xdeadbeef]]) (['foobar 2000', '3735928559'], [10, 4])
Return a list of formatted rows and a list of column sizes.
def tabulate(rows): # type: (Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]] """Return a list of formatted rows and a list of column sizes. For example:: >>> tabulate([['foobar', 2000], [0xdeadbeef]]) (['foobar 2000', '3735928559'], [10, 4]) """ rows = [tuple(map(str, row)) for...
[ "def", "tabulate", "(", "rows", ")", ":", "# type: (Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]", "rows", "=", "[", "tuple", "(", "map", "(", "str", ",", "row", ")", ")", "for", "row", "in", "rows", "]", "sizes", "=", "[", "max", "(", "map", "(...
[ 283, 0 ]
[ 295, 23 ]
python
en
['en', 'en', 'en']
True
is_installable_dir
(path)
Is path is a directory containing setup.py or pyproject.toml?
Is path is a directory containing setup.py or pyproject.toml?
def is_installable_dir(path): # type: (str) -> bool """Is path is a directory containing setup.py or pyproject.toml? """ if not os.path.isdir(path): return False setup_py = os.path.join(path, 'setup.py') if os.path.isfile(setup_py): return True pyproject_toml = os.path.join(p...
[ "def", "is_installable_dir", "(", "path", ")", ":", "# type: (str) -> bool", "if", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "False", "setup_py", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'setup.py'", ")", "...
[ 298, 0 ]
[ 310, 16 ]
python
en
['en', 'en', 'en']
True
read_chunks
(file, size=io.DEFAULT_BUFFER_SIZE)
Yield pieces of data from a file-like object until EOF.
Yield pieces of data from a file-like object until EOF.
def read_chunks(file, size=io.DEFAULT_BUFFER_SIZE): """Yield pieces of data from a file-like object until EOF.""" while True: chunk = file.read(size) if not chunk: break yield chunk
[ "def", "read_chunks", "(", "file", ",", "size", "=", "io", ".", "DEFAULT_BUFFER_SIZE", ")", ":", "while", "True", ":", "chunk", "=", "file", ".", "read", "(", "size", ")", "if", "not", "chunk", ":", "break", "yield", "chunk" ]
[ 313, 0 ]
[ 319, 19 ]
python
en
['en', 'en', 'en']
True
normalize_path
(path, resolve_symlinks=True)
Convert a path to its canonical, case-normalized, absolute version.
Convert a path to its canonical, case-normalized, absolute version.
def normalize_path(path, resolve_symlinks=True): # type: (str, bool) -> str """ Convert a path to its canonical, case-normalized, absolute version. """ path = expanduser(path) if resolve_symlinks: path = os.path.realpath(path) else: path = os.path.abspath(path) return os...
[ "def", "normalize_path", "(", "path", ",", "resolve_symlinks", "=", "True", ")", ":", "# type: (str, bool) -> str", "path", "=", "expanduser", "(", "path", ")", "if", "resolve_symlinks", ":", "path", "=", "os", ".", "path", ".", "realpath", "(", "path", ")",...
[ 322, 0 ]
[ 333, 33 ]
python
en
['en', 'error', 'th']
False
splitext
(path)
Like os.path.splitext, but take off .tar too
Like os.path.splitext, but take off .tar too
def splitext(path): # type: (str) -> Tuple[str, str] """Like os.path.splitext, but take off .tar too""" base, ext = posixpath.splitext(path) if base.lower().endswith('.tar'): ext = base[-4:] + ext base = base[:-4] return base, ext
[ "def", "splitext", "(", "path", ")", ":", "# type: (str) -> Tuple[str, str]", "base", ",", "ext", "=", "posixpath", ".", "splitext", "(", "path", ")", "if", "base", ".", "lower", "(", ")", ".", "endswith", "(", "'.tar'", ")", ":", "ext", "=", "base", "...
[ 336, 0 ]
[ 343, 20 ]
python
en
['en', 'en', 'en']
True
renames
(old, new)
Like os.renames(), but handles renaming across devices.
Like os.renames(), but handles renaming across devices.
def renames(old, new): # type: (str, str) -> None """Like os.renames(), but handles renaming across devices.""" # Implementation borrowed from os.renames(). head, tail = os.path.split(new) if head and tail and not os.path.exists(head): os.makedirs(head) shutil.move(old, new) head, ...
[ "def", "renames", "(", "old", ",", "new", ")", ":", "# type: (str, str) -> None", "# Implementation borrowed from os.renames().", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "new", ")", "if", "head", "and", "tail", "and", "not", "os", "."...
[ 346, 0 ]
[ 361, 16 ]
python
en
['en', 'en', 'en']
True
is_local
(path)
Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." Caution: this function assumes the head of path has been normalized with normalize_path.
Return True if path is within sys.prefix, if we're running in a virtualenv.
def is_local(path): # type: (str) -> bool """ Return True if path is within sys.prefix, if we're running in a virtualenv. If we're not in a virtualenv, all paths are considered "local." Caution: this function assumes the head of path has been normalized with normalize_path. """ if not ...
[ "def", "is_local", "(", "path", ")", ":", "# type: (str) -> bool", "if", "not", "running_under_virtualenv", "(", ")", ":", "return", "True", "return", "path", ".", "startswith", "(", "normalize_path", "(", "sys", ".", "prefix", ")", ")" ]
[ 364, 0 ]
[ 376, 54 ]
python
en
['en', 'error', 'th']
False
dist_is_local
(dist)
Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv.
Return True if given Distribution object is installed locally (i.e. within current virtualenv).
def dist_is_local(dist): # type: (Distribution) -> bool """ Return True if given Distribution object is installed locally (i.e. within current virtualenv). Always True if we're not in a virtualenv. """ return is_local(dist_location(dist))
[ "def", "dist_is_local", "(", "dist", ")", ":", "# type: (Distribution) -> bool", "return", "is_local", "(", "dist_location", "(", "dist", ")", ")" ]
[ 379, 0 ]
[ 388, 40 ]
python
en
['en', 'error', 'th']
False
dist_in_usersite
(dist)
Return True if given Distribution is installed in user site.
Return True if given Distribution is installed in user site.
def dist_in_usersite(dist): # type: (Distribution) -> bool """ Return True if given Distribution is installed in user site. """ return dist_location(dist).startswith(normalize_path(user_site))
[ "def", "dist_in_usersite", "(", "dist", ")", ":", "# type: (Distribution) -> bool", "return", "dist_location", "(", "dist", ")", ".", "startswith", "(", "normalize_path", "(", "user_site", ")", ")" ]
[ 391, 0 ]
[ 396, 68 ]
python
en
['en', 'error', 'th']
False
dist_in_site_packages
(dist)
Return True if given Distribution is installed in sysconfig.get_python_lib().
Return True if given Distribution is installed in sysconfig.get_python_lib().
def dist_in_site_packages(dist): # type: (Distribution) -> bool """ Return True if given Distribution is installed in sysconfig.get_python_lib(). """ return dist_location(dist).startswith(normalize_path(site_packages))
[ "def", "dist_in_site_packages", "(", "dist", ")", ":", "# type: (Distribution) -> bool", "return", "dist_location", "(", "dist", ")", ".", "startswith", "(", "normalize_path", "(", "site_packages", ")", ")" ]
[ 399, 0 ]
[ 405, 72 ]
python
en
['en', 'error', 'th']
False
dist_is_editable
(dist)
Return True if given Distribution is an editable install.
Return True if given Distribution is an editable install.
def dist_is_editable(dist): # type: (Distribution) -> bool """ Return True if given Distribution is an editable install. """ for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + '.egg-link') if os.path.isfile(egg_link): return True return ...
[ "def", "dist_is_editable", "(", "dist", ")", ":", "# type: (Distribution) -> bool", "for", "path_item", "in", "sys", ".", "path", ":", "egg_link", "=", "os", ".", "path", ".", "join", "(", "path_item", ",", "dist", ".", "project_name", "+", "'.egg-link'", ")...
[ 408, 0 ]
[ 417, 16 ]
python
en
['en', 'error', 'th']
False
get_installed_distributions
( local_only=True, # type: bool skip=stdlib_pkgs, # type: Container[str] include_editables=True, # type: bool editables_only=False, # type: bool user_only=False, # type: bool paths=None # type: Optional[List[str]] )
Return a list of installed Distribution objects. If ``local_only`` is True (default), only return installations local to the current virtualenv, if in a virtualenv. ``skip`` argument is an iterable of lower-case project names to ignore; defaults to stdlib_pkgs If ``include_editables`` is Fal...
Return a list of installed Distribution objects.
def get_installed_distributions( local_only=True, # type: bool skip=stdlib_pkgs, # type: Container[str] include_editables=True, # type: bool editables_only=False, # type: bool user_only=False, # type: bool paths=None # type: Optional[List[str]] ): # type: (...) ...
[ "def", "get_installed_distributions", "(", "local_only", "=", "True", ",", "# type: bool", "skip", "=", "stdlib_pkgs", ",", "# type: Container[str]", "include_editables", "=", "True", ",", "# type: bool", "editables_only", "=", "False", ",", "# type: bool", "user_only",...
[ 420, 0 ]
[ 485, 13 ]
python
en
['en', 'error', 'th']
False
_search_distribution
(req_name)
Find a distribution matching the ``req_name`` in the environment. This searches from *all* distributions available in the environment, to match the behavior of ``pkg_resources.get_distribution()``.
Find a distribution matching the ``req_name`` in the environment.
def _search_distribution(req_name): # type: (str) -> Optional[Distribution] """Find a distribution matching the ``req_name`` in the environment. This searches from *all* distributions available in the environment, to match the behavior of ``pkg_resources.get_distribution()``. """ # Canonicalize...
[ "def", "_search_distribution", "(", "req_name", ")", ":", "# type: (str) -> Optional[Distribution]", "# Canonicalize the name before searching in the list of", "# installed distributions and also while creating the package", "# dictionary to get the Distribution object", "req_name", "=", "ca...
[ 488, 0 ]
[ 508, 33 ]
python
en
['en', 'en', 'en']
True
get_distribution
(req_name)
Given a requirement name, return the installed Distribution object. This searches from *all* distributions available in the environment, to match the behavior of ``pkg_resources.get_distribution()``.
Given a requirement name, return the installed Distribution object.
def get_distribution(req_name): # type: (str) -> Optional[Distribution] """Given a requirement name, return the installed Distribution object. This searches from *all* distributions available in the environment, to match the behavior of ``pkg_resources.get_distribution()``. """ # Search the di...
[ "def", "get_distribution", "(", "req_name", ")", ":", "# type: (str) -> Optional[Distribution]", "# Search the distribution by looking through the working set", "dist", "=", "_search_distribution", "(", "req_name", ")", "# If distribution could not be found, call working_set.require", ...
[ 511, 0 ]
[ 536, 41 ]
python
en
['en', 'en', 'en']
True
egg_link_path
(dist)
Return the path for the .egg-link file if it exists, otherwise, None. There's 3 scenarios: 1) not in a virtualenv try to find in site.USER_SITE, then site_packages 2) in a no-global virtualenv try to find in site_packages 3) in a yes-global virtualenv try to find in site_packa...
Return the path for the .egg-link file if it exists, otherwise, None.
def egg_link_path(dist): # type: (Distribution) -> Optional[str] """ Return the path for the .egg-link file if it exists, otherwise, None. There's 3 scenarios: 1) not in a virtualenv try to find in site.USER_SITE, then site_packages 2) in a no-global virtualenv try to find in site...
[ "def", "egg_link_path", "(", "dist", ")", ":", "# type: (Distribution) -> Optional[str]", "sites", "=", "[", "]", "if", "running_under_virtualenv", "(", ")", ":", "sites", ".", "append", "(", "site_packages", ")", "if", "not", "virtualenv_no_global", "(", ")", "...
[ 539, 0 ]
[ 572, 15 ]
python
en
['en', 'error', 'th']
False
dist_location
(dist)
Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. The returned location is normalized (in particular, with symlinks...
Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is.
def dist_location(dist): # type: (Distribution) -> str """ Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. ...
[ "def", "dist_location", "(", "dist", ")", ":", "# type: (Distribution) -> str", "egg_link", "=", "egg_link_path", "(", "dist", ")", "if", "egg_link", ":", "return", "normalize_path", "(", "egg_link", ")", "return", "normalize_path", "(", "dist", ".", "location", ...
[ 575, 0 ]
[ 588, 40 ]
python
en
['en', 'error', 'th']
False
captured_output
(stream_name)
Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Taken from Lib/support/__init__.py in the CPython repo.
Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO.
def captured_output(stream_name): """Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Taken from Lib/support/__init__.py in the CPython repo. """ orig_stdout = getattr(sys, stream_name) setattr(sys, stream_name...
[ "def", "captured_output", "(", "stream_name", ")", ":", "orig_stdout", "=", "getattr", "(", "sys", ",", "stream_name", ")", "setattr", "(", "sys", ",", "stream_name", ",", "StreamWrapper", ".", "from_stream", "(", "orig_stdout", ")", ")", "try", ":", "yield"...
[ 626, 0 ]
[ 637, 46 ]
python
en
['en', 'en', 'en']
True
captured_stdout
()
Capture the output of sys.stdout: with captured_stdout() as stdout: print('hello') self.assertEqual(stdout.getvalue(), 'hello\n') Taken from Lib/support/__init__.py in the CPython repo.
Capture the output of sys.stdout:
def captured_stdout(): """Capture the output of sys.stdout: with captured_stdout() as stdout: print('hello') self.assertEqual(stdout.getvalue(), 'hello\n') Taken from Lib/support/__init__.py in the CPython repo. """ return captured_output('stdout')
[ "def", "captured_stdout", "(", ")", ":", "return", "captured_output", "(", "'stdout'", ")" ]
[ 640, 0 ]
[ 649, 36 ]
python
en
['en', 'en', 'en']
True
captured_stderr
()
See captured_stdout().
See captured_stdout().
def captured_stderr(): """ See captured_stdout(). """ return captured_output('stderr')
[ "def", "captured_stderr", "(", ")", ":", "return", "captured_output", "(", "'stderr'", ")" ]
[ 652, 0 ]
[ 656, 36 ]
python
en
['en', 'error', 'th']
False
get_installed_version
(dist_name, working_set=None)
Get the installed version of dist_name avoiding pkg_resources cache
Get the installed version of dist_name avoiding pkg_resources cache
def get_installed_version(dist_name, working_set=None): """Get the installed version of dist_name avoiding pkg_resources cache""" # Create a requirement that we'll look for inside of setuptools. req = pkg_resources.Requirement.parse(dist_name) if working_set is None: # We want to avoid having t...
[ "def", "get_installed_version", "(", "dist_name", ",", "working_set", "=", "None", ")", ":", "# Create a requirement that we'll look for inside of setuptools.", "req", "=", "pkg_resources", ".", "Requirement", ".", "parse", "(", "dist_name", ")", "if", "working_set", "i...
[ 659, 0 ]
[ 674, 41 ]
python
en
['en', 'en', 'en']
True
consume
(iterator)
Consume an iterable at C speed.
Consume an iterable at C speed.
def consume(iterator): """Consume an iterable at C speed.""" deque(iterator, maxlen=0)
[ "def", "consume", "(", "iterator", ")", ":", "deque", "(", "iterator", ",", "maxlen", "=", "0", ")" ]
[ 677, 0 ]
[ 679, 29 ]
python
en
['en', 'en', 'en']
True
build_netloc
(host, port)
Build a netloc from a host-port pair
Build a netloc from a host-port pair
def build_netloc(host, port): # type: (str, Optional[int]) -> str """ Build a netloc from a host-port pair """ if port is None: return host if ':' in host: # Only wrap host with square brackets when it is IPv6 host = '[{}]'.format(host) return '{}:{}'.format(host, por...
[ "def", "build_netloc", "(", "host", ",", "port", ")", ":", "# type: (str, Optional[int]) -> str", "if", "port", "is", "None", ":", "return", "host", "if", "':'", "in", "host", ":", "# Only wrap host with square brackets when it is IPv6", "host", "=", "'[{}]'", ".", ...
[ 690, 0 ]
[ 700, 37 ]
python
en
['en', 'error', 'th']
False
build_url_from_netloc
(netloc, scheme='https')
Build a full URL from a netloc.
Build a full URL from a netloc.
def build_url_from_netloc(netloc, scheme='https'): # type: (str, str) -> str """ Build a full URL from a netloc. """ if netloc.count(':') >= 2 and '@' not in netloc and '[' not in netloc: # It must be a bare IPv6 address, so wrap it with brackets. netloc = '[{}]'.format(netloc) r...
[ "def", "build_url_from_netloc", "(", "netloc", ",", "scheme", "=", "'https'", ")", ":", "# type: (str, str) -> str", "if", "netloc", ".", "count", "(", "':'", ")", ">=", "2", "and", "'@'", "not", "in", "netloc", "and", "'['", "not", "in", "netloc", ":", ...
[ 703, 0 ]
[ 711, 43 ]
python
en
['en', 'error', 'th']
False
parse_netloc
(netloc)
Return the host-port pair from a netloc.
Return the host-port pair from a netloc.
def parse_netloc(netloc): # type: (str) -> Tuple[str, Optional[int]] """ Return the host-port pair from a netloc. """ url = build_url_from_netloc(netloc) parsed = urllib_parse.urlparse(url) return parsed.hostname, parsed.port
[ "def", "parse_netloc", "(", "netloc", ")", ":", "# type: (str) -> Tuple[str, Optional[int]]", "url", "=", "build_url_from_netloc", "(", "netloc", ")", "parsed", "=", "urllib_parse", ".", "urlparse", "(", "url", ")", "return", "parsed", ".", "hostname", ",", "parse...
[ 714, 0 ]
[ 721, 39 ]
python
en
['en', 'error', 'th']
False
split_auth_from_netloc
(netloc)
Parse out and remove the auth information from a netloc. Returns: (netloc, (username, password)).
Parse out and remove the auth information from a netloc.
def split_auth_from_netloc(netloc): """ Parse out and remove the auth information from a netloc. Returns: (netloc, (username, password)). """ if '@' not in netloc: return netloc, (None, None) # Split from the right because that's how urllib.parse.urlsplit() # behaves if more than o...
[ "def", "split_auth_from_netloc", "(", "netloc", ")", ":", "if", "'@'", "not", "in", "netloc", ":", "return", "netloc", ",", "(", "None", ",", "None", ")", "# Split from the right because that's how urllib.parse.urlsplit()", "# behaves if more than one @ is present (which ca...
[ 724, 0 ]
[ 749, 28 ]
python
en
['en', 'error', 'th']
False
redact_netloc
(netloc)
Replace the sensitive data in a netloc with "****", if it exists. For example: - "user:pass@example.com" returns "user:****@example.com" - "accesstoken@example.com" returns "****@example.com"
Replace the sensitive data in a netloc with "****", if it exists.
def redact_netloc(netloc): # type: (str) -> str """ Replace the sensitive data in a netloc with "****", if it exists. For example: - "user:pass@example.com" returns "user:****@example.com" - "accesstoken@example.com" returns "****@example.com" """ netloc, (user, password) = spli...
[ "def", "redact_netloc", "(", "netloc", ")", ":", "# type: (str) -> str", "netloc", ",", "(", "user", ",", "password", ")", "=", "split_auth_from_netloc", "(", "netloc", ")", "if", "user", "is", "None", ":", "return", "netloc", "if", "password", "is", "None",...
[ 752, 0 ]
[ 772, 60 ]
python
en
['en', 'error', 'th']
False
_transform_url
(url, transform_netloc)
Transform and replace netloc in a url. transform_netloc is a function taking the netloc and returning a tuple. The first element of this tuple is the new netloc. The entire tuple is returned. Returns a tuple containing the transformed url as item 0 and the original tuple returned by transform_netl...
Transform and replace netloc in a url.
def _transform_url(url, transform_netloc): """Transform and replace netloc in a url. transform_netloc is a function taking the netloc and returning a tuple. The first element of this tuple is the new netloc. The entire tuple is returned. Returns a tuple containing the transformed url as item 0 and...
[ "def", "_transform_url", "(", "url", ",", "transform_netloc", ")", ":", "purl", "=", "urllib_parse", ".", "urlsplit", "(", "url", ")", "netloc_tuple", "=", "transform_netloc", "(", "purl", ".", "netloc", ")", "# stripped url", "url_pieces", "=", "(", "purl", ...
[ 775, 0 ]
[ 792, 29 ]
python
en
['en', 'en', 'en']
True
split_auth_netloc_from_url
(url)
Parse a url into separate netloc, auth, and url with no auth. Returns: (url_without_auth, netloc, (username, password))
Parse a url into separate netloc, auth, and url with no auth.
def split_auth_netloc_from_url(url): # type: (str) -> Tuple[str, str, Tuple[str, str]] """ Parse a url into separate netloc, auth, and url with no auth. Returns: (url_without_auth, netloc, (username, password)) """ url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc) return u...
[ "def", "split_auth_netloc_from_url", "(", "url", ")", ":", "# type: (str) -> Tuple[str, str, Tuple[str, str]]", "url_without_auth", ",", "(", "netloc", ",", "auth", ")", "=", "_transform_url", "(", "url", ",", "_get_netloc", ")", "return", "url_without_auth", ",", "ne...
[ 803, 0 ]
[ 811, 41 ]
python
en
['en', 'error', 'th']
False
remove_auth_from_url
(url)
Return a copy of url with 'username:password@' removed.
Return a copy of url with 'username:password
def remove_auth_from_url(url): # type: (str) -> str """Return a copy of url with 'username:password@' removed.""" # username/pass params are passed to subversion through flags # and are not recognized in the url. return _transform_url(url, _get_netloc)[0]
[ "def", "remove_auth_from_url", "(", "url", ")", ":", "# type: (str) -> str", "# username/pass params are passed to subversion through flags", "# and are not recognized in the url.", "return", "_transform_url", "(", "url", ",", "_get_netloc", ")", "[", "0", "]" ]
[ 814, 0 ]
[ 819, 46 ]
python
en
['en', 'en', 'en']
True
redact_auth_from_url
(url)
Replace the password in a given url with ****.
Replace the password in a given url with ****.
def redact_auth_from_url(url): # type: (str) -> str """Replace the password in a given url with ****.""" return _transform_url(url, _redact_netloc)[0]
[ "def", "redact_auth_from_url", "(", "url", ")", ":", "# type: (str) -> str", "return", "_transform_url", "(", "url", ",", "_redact_netloc", ")", "[", "0", "]" ]
[ 822, 0 ]
[ 825, 49 ]
python
en
['en', 'en', 'en']
True
protect_pip_from_modification_on_windows
(modifying_pip)
Protection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ...
Protection of pip.exe from modification on Windows
def protect_pip_from_modification_on_windows(modifying_pip): # type: (bool) -> None """Protection of pip.exe from modification on Windows On Windows, any operation modifying pip should be run as: python -m pip ... """ pip_names = [ "pip.exe", "pip{}.exe".format(sys.version_i...
[ "def", "protect_pip_from_modification_on_windows", "(", "modifying_pip", ")", ":", "# type: (bool) -> None", "pip_names", "=", "[", "\"pip.exe\"", ",", "\"pip{}.exe\"", ".", "format", "(", "sys", ".", "version_info", "[", "0", "]", ")", ",", "\"pip{}.{}.exe\"", ".",...
[ 874, 0 ]
[ 901, 9 ]
python
en
['en', 'en', 'en']
True
is_console_interactive
()
Is this console interactive?
Is this console interactive?
def is_console_interactive(): # type: () -> bool """Is this console interactive? """ return sys.stdin is not None and sys.stdin.isatty()
[ "def", "is_console_interactive", "(", ")", ":", "# type: () -> bool", "return", "sys", ".", "stdin", "is", "not", "None", "and", "sys", ".", "stdin", ".", "isatty", "(", ")" ]
[ 904, 0 ]
[ 908, 55 ]
python
en
['en', 'en', 'en']
True
hash_file
(path, blocksize=1 << 20)
Return (hash, length) for path using hashlib.sha256()
Return (hash, length) for path using hashlib.sha256()
def hash_file(path, blocksize=1 << 20): # type: (Text, int) -> Tuple[Any, int] """Return (hash, length) for path using hashlib.sha256() """ h = hashlib.sha256() length = 0 with open(path, 'rb') as f: for block in read_chunks(f, size=blocksize): length += len(block) ...
[ "def", "hash_file", "(", "path", ",", "blocksize", "=", "1", "<<", "20", ")", ":", "# type: (Text, int) -> Tuple[Any, int]", "h", "=", "hashlib", ".", "sha256", "(", ")", "length", "=", "0", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":"...
[ 911, 0 ]
[ 922, 20 ]
python
en
['en', 'hi-Latn', 'en']
True
is_wheel_installed
()
Return whether the wheel package is installed.
Return whether the wheel package is installed.
def is_wheel_installed(): """ Return whether the wheel package is installed. """ try: import wheel # noqa: F401 except ImportError: return False return True
[ "def", "is_wheel_installed", "(", ")", ":", "try", ":", "import", "wheel", "# noqa: F401", "except", "ImportError", ":", "return", "False", "return", "True" ]
[ 925, 0 ]
[ 934, 15 ]
python
en
['en', 'error', 'th']
False
pairwise
(iterable)
Return paired elements. For example: s -> (s0, s1), (s2, s3), (s4, s5), ...
Return paired elements.
def pairwise(iterable): # type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]] """ Return paired elements. For example: s -> (s0, s1), (s2, s3), (s4, s5), ... """ iterable = iter(iterable) return zip_longest(iterable, iterable)
[ "def", "pairwise", "(", "iterable", ")", ":", "# type: (Iterable[Any]) -> Iterator[Tuple[Any, Any]]", "iterable", "=", "iter", "(", "iterable", ")", "return", "zip_longest", "(", "iterable", ",", "iterable", ")" ]
[ 937, 0 ]
[ 946, 42 ]
python
en
['en', 'error', 'th']
False
partition
( pred, # type: Callable[[T], bool] iterable, # type: Iterable[T] )
Use a predicate to partition entries into false entries and true entries, like partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
Use a predicate to partition entries into false entries and true entries, like
def partition( pred, # type: Callable[[T], bool] iterable, # type: Iterable[T] ): # type: (...) -> Tuple[Iterable[T], Iterable[T]] """ Use a predicate to partition entries into false entries and true entries, like partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 """ ...
[ "def", "partition", "(", "pred", ",", "# type: Callable[[T], bool]", "iterable", ",", "# type: Iterable[T]", ")", ":", "# type: (...) -> Tuple[Iterable[T], Iterable[T]]", "t1", ",", "t2", "=", "tee", "(", "iterable", ")", "return", "filterfalse", "(", "pred", ",", "...
[ 949, 0 ]
[ 961, 50 ]
python
en
['en', 'error', 'th']
False
validate_password
(password, user=None, password_validators=None)
Validate whether the password meets all validator requirements. If the password is valid, return ``None``. If the password is invalid, raise ValidationError with all error messages.
Validate whether the password meets all validator requirements.
def validate_password(password, user=None, password_validators=None): """ Validate whether the password meets all validator requirements. If the password is valid, return ``None``. If the password is invalid, raise ValidationError with all error messages. """ errors = [] if password_validat...
[ "def", "validate_password", "(", "password", ",", "user", "=", "None", ",", "password_validators", "=", "None", ")", ":", "errors", "=", "[", "]", "if", "password_validators", "is", "None", ":", "password_validators", "=", "get_default_password_validators", "(", ...
[ 39, 0 ]
[ 55, 37 ]
python
en
['en', 'error', 'th']
False
password_changed
(password, user=None, password_validators=None)
Inform all validators that have implemented a password_changed() method that the password has been changed.
Inform all validators that have implemented a password_changed() method that the password has been changed.
def password_changed(password, user=None, password_validators=None): """ Inform all validators that have implemented a password_changed() method that the password has been changed. """ if password_validators is None: password_validators = get_default_password_validators() for validator i...
[ "def", "password_changed", "(", "password", ",", "user", "=", "None", ",", "password_validators", "=", "None", ")", ":", "if", "password_validators", "is", "None", ":", "password_validators", "=", "get_default_password_validators", "(", ")", "for", "validator", "i...
[ 58, 0 ]
[ 67, 40 ]
python
en
['en', 'error', 'th']
False
password_validators_help_texts
(password_validators=None)
Return a list of all help texts of all configured validators.
Return a list of all help texts of all configured validators.
def password_validators_help_texts(password_validators=None): """ Return a list of all help texts of all configured validators. """ help_texts = [] if password_validators is None: password_validators = get_default_password_validators() for validator in password_validators: help_t...
[ "def", "password_validators_help_texts", "(", "password_validators", "=", "None", ")", ":", "help_texts", "=", "[", "]", "if", "password_validators", "is", "None", ":", "password_validators", "=", "get_default_password_validators", "(", ")", "for", "validator", "in", ...
[ 70, 0 ]
[ 79, 21 ]
python
en
['en', 'error', 'th']
False
_password_validators_help_text_html
(password_validators=None)
Return an HTML string with all help texts of all configured validators in an <ul>.
Return an HTML string with all help texts of all configured validators in an <ul>.
def _password_validators_help_text_html(password_validators=None): """ Return an HTML string with all help texts of all configured validators in an <ul>. """ help_texts = password_validators_help_texts(password_validators) help_items = [format_html('<li>{}</li>', help_text) for help_text in help...
[ "def", "_password_validators_help_text_html", "(", "password_validators", "=", "None", ")", ":", "help_texts", "=", "password_validators_help_texts", "(", "password_validators", ")", "help_items", "=", "[", "format_html", "(", "'<li>{}</li>'", ",", "help_text", ")", "fo...
[ 82, 0 ]
[ 89, 68 ]
python
en
['en', 'error', 'th']
False
BasicTests.test_package_not_found_mentions_metadata
(self)
When a package is not found, that could indicate that the packgae is not installed or that it is installed without metadata. Ensure the exception mentions metadata to help guide users toward the cause. See #124.
When a package is not found, that could indicate that the packgae is not installed or that it is installed without metadata. Ensure the exception mentions metadata to help guide users toward the cause. See #124.
def test_package_not_found_mentions_metadata(self): """ When a package is not found, that could indicate that the packgae is not installed or that it is installed without metadata. Ensure the exception mentions metadata to help guide users toward the cause. See #124. """ ...
[ "def", "test_package_not_found_mentions_metadata", "(", "self", ")", ":", "with", "self", ".", "assertRaises", "(", "PackageNotFoundError", ")", "as", "ctx", ":", "Distribution", ".", "from_name", "(", "'does-not-exist'", ")", "assert", "\"metadata\"", "in", "str", ...
[ 37, 4 ]
[ 47, 47 ]
python
en
['en', 'error', 'th']
False
NameNormalizationTests.pkg_with_dashes
(site_dir)
Create minimal metadata for a package with dashes in the name (and thus underscores in the filename).
Create minimal metadata for a package with dashes in the name (and thus underscores in the filename).
def pkg_with_dashes(site_dir): """ Create minimal metadata for a package with dashes in the name (and thus underscores in the filename). """ metadata_dir = site_dir / 'my_pkg.dist-info' metadata_dir.mkdir() metadata = metadata_dir / 'METADATA' with metadat...
[ "def", "pkg_with_dashes", "(", "site_dir", ")", ":", "metadata_dir", "=", "site_dir", "/", "'my_pkg.dist-info'", "metadata_dir", ".", "mkdir", "(", ")", "metadata", "=", "metadata_dir", "/", "'METADATA'", "with", "metadata", ".", "open", "(", "'w'", ")", "as",...
[ 83, 4 ]
[ 93, 23 ]
python
en
['en', 'error', 'th']
False
NameNormalizationTests.test_dashes_in_dist_name_found_as_underscores
(self)
For a package with a dash in the name, the dist-info metadata uses underscores in the name. Ensure the metadata loads.
For a package with a dash in the name, the dist-info metadata uses underscores in the name. Ensure the metadata loads.
def test_dashes_in_dist_name_found_as_underscores(self): """ For a package with a dash in the name, the dist-info metadata uses underscores in the name. Ensure the metadata loads. """ pkg_name = self.pkg_with_dashes(self.site_dir) assert version(pkg_name) == '1.0'
[ "def", "test_dashes_in_dist_name_found_as_underscores", "(", "self", ")", ":", "pkg_name", "=", "self", ".", "pkg_with_dashes", "(", "self", ".", "site_dir", ")", "assert", "version", "(", "pkg_name", ")", "==", "'1.0'" ]
[ 95, 4 ]
[ 101, 41 ]
python
en
['en', 'error', 'th']
False
NameNormalizationTests.pkg_with_mixed_case
(site_dir)
Create minimal metadata for a package with mixed case in the name.
Create minimal metadata for a package with mixed case in the name.
def pkg_with_mixed_case(site_dir): """ Create minimal metadata for a package with mixed case in the name. """ metadata_dir = site_dir / 'CherryPy.dist-info' metadata_dir.mkdir() metadata = metadata_dir / 'METADATA' with metadata.open('w') as strm: ...
[ "def", "pkg_with_mixed_case", "(", "site_dir", ")", ":", "metadata_dir", "=", "site_dir", "/", "'CherryPy.dist-info'", "metadata_dir", ".", "mkdir", "(", ")", "metadata", "=", "metadata_dir", "/", "'METADATA'", "with", "metadata", ".", "open", "(", "'w'", ")", ...
[ 104, 4 ]
[ 114, 25 ]
python
en
['en', 'error', 'th']
False
NameNormalizationTests.test_dist_name_found_as_any_case
(self)
Ensure the metadata loads when queried with any case.
Ensure the metadata loads when queried with any case.
def test_dist_name_found_as_any_case(self): """ Ensure the metadata loads when queried with any case. """ pkg_name = self.pkg_with_mixed_case(self.site_dir) assert version(pkg_name) == '1.0' assert version(pkg_name.lower()) == '1.0' assert version(pkg_name.upper()...
[ "def", "test_dist_name_found_as_any_case", "(", "self", ")", ":", "pkg_name", "=", "self", ".", "pkg_with_mixed_case", "(", "self", ".", "site_dir", ")", "assert", "version", "(", "pkg_name", ")", "==", "'1.0'", "assert", "version", "(", "pkg_name", ".", "lowe...
[ 116, 4 ]
[ 123, 49 ]
python
en
['en', 'error', 'th']
False
NonASCIITests.pkg_with_non_ascii_description
(site_dir)
Create minimal metadata for a package with non-ASCII in the description.
Create minimal metadata for a package with non-ASCII in the description.
def pkg_with_non_ascii_description(site_dir): """ Create minimal metadata for a package with non-ASCII in the description. """ metadata_dir = site_dir / 'portend.dist-info' metadata_dir.mkdir() metadata = metadata_dir / 'METADATA' with metadata.open('w', e...
[ "def", "pkg_with_non_ascii_description", "(", "site_dir", ")", ":", "metadata_dir", "=", "site_dir", "/", "'portend.dist-info'", "metadata_dir", ".", "mkdir", "(", ")", "metadata", "=", "metadata_dir", "/", "'METADATA'", "with", "metadata", ".", "open", "(", "'w'"...
[ 128, 4 ]
[ 138, 24 ]
python
en
['en', 'error', 'th']
False
NonASCIITests.pkg_with_non_ascii_description_egg_info
(site_dir)
Create minimal metadata for an egg-info package with non-ASCII in the description.
Create minimal metadata for an egg-info package with non-ASCII in the description.
def pkg_with_non_ascii_description_egg_info(site_dir): """ Create minimal metadata for an egg-info package with non-ASCII in the description. """ metadata_dir = site_dir / 'portend.dist-info' metadata_dir.mkdir() metadata = metadata_dir / 'METADATA' with m...
[ "def", "pkg_with_non_ascii_description_egg_info", "(", "site_dir", ")", ":", "metadata_dir", "=", "site_dir", "/", "'portend.dist-info'", "metadata_dir", ".", "mkdir", "(", ")", "metadata", "=", "metadata_dir", "/", "'METADATA'", "with", "metadata", ".", "open", "("...
[ 141, 4 ]
[ 155, 24 ]
python
en
['en', 'error', 'th']
False
MissingSysPath.test_discovery
(self)
Discovering distributions should succeed even if there is an invalid path on sys.path.
Discovering distributions should succeed even if there is an invalid path on sys.path.
def test_discovery(self): """ Discovering distributions should succeed even if there is an invalid path on sys.path. """ importlib_metadata.distributions()
[ "def", "test_discovery", "(", "self", ")", ":", "importlib_metadata", ".", "distributions", "(", ")" ]
[ 211, 4 ]
[ 216, 42 ]
python
en
['en', 'error', 'th']
False
InaccessibleSysPath.test_discovery
(self)
Discovering distributions should succeed even if there is an invalid path on sys.path.
Discovering distributions should succeed even if there is an invalid path on sys.path.
def test_discovery(self): """ Discovering distributions should succeed even if there is an invalid path on sys.path. """ list(importlib_metadata.distributions())
[ "def", "test_discovery", "(", "self", ")", ":", "list", "(", "importlib_metadata", ".", "distributions", "(", ")", ")" ]
[ 227, 4 ]
[ 232, 48 ]
python
en
['en', 'error', 'th']
False
TestEntryPoints.test_immutable
(self)
EntryPoints should be immutable
EntryPoints should be immutable
def test_immutable(self): """EntryPoints should be immutable""" with self.assertRaises(AttributeError): self.ep.name = 'badactor'
[ "def", "test_immutable", "(", "self", ")", ":", "with", "self", ".", "assertRaises", "(", "AttributeError", ")", ":", "self", ".", "ep", ".", "name", "=", "'badactor'" ]
[ 244, 4 ]
[ 247, 37 ]
python
en
['en', 'en', 'en']
True
TestEntryPoints.test_hashable
(self)
EntryPoints should be hashable
EntryPoints should be hashable
def test_hashable(self): """EntryPoints should be hashable""" hash(self.ep)
[ "def", "test_hashable", "(", "self", ")", ":", "hash", "(", "self", ".", "ep", ")" ]
[ 254, 4 ]
[ 256, 21 ]
python
en
['en', 'en', 'en']
True
TestEntryPoints.test_json_dump
(self)
json should not expect to be able to dump an EntryPoint
json should not expect to be able to dump an EntryPoint
def test_json_dump(self): """ json should not expect to be able to dump an EntryPoint """ with self.assertRaises(Exception): json.dumps(self.ep)
[ "def", "test_json_dump", "(", "self", ")", ":", "with", "self", ".", "assertRaises", "(", "Exception", ")", ":", "json", ".", "dumps", "(", "self", ".", "ep", ")" ]
[ 258, 4 ]
[ 263, 31 ]
python
en
['en', 'error', 'th']
False
FileSystem.test_unicode_dir_on_sys_path
(self)
Ensure a Unicode subdirectory of a directory on sys.path does not crash.
Ensure a Unicode subdirectory of a directory on sys.path does not crash.
def test_unicode_dir_on_sys_path(self): """ Ensure a Unicode subdirectory of a directory on sys.path does not crash. """ fixtures.build_files( {self.unicode_filename(): {}}, prefix=self.site_dir, ) list(distributions())
[ "def", "test_unicode_dir_on_sys_path", "(", "self", ")", ":", "fixtures", ".", "build_files", "(", "{", "self", ".", "unicode_filename", "(", ")", ":", "{", "}", "}", ",", "prefix", "=", "self", ".", "site_dir", ",", ")", "list", "(", "distributions", "(...
[ 275, 4 ]
[ 284, 29 ]
python
en
['en', 'error', 'th']
False
remove_manual_inventory_sources
(apps, schema_editor)
Previously we would automatically create inventory sources after Group creation and we would use the parent Group as our interface for the user. During that process we would create InventorySource that had a source of "manual".
Previously we would automatically create inventory sources after Group creation and we would use the parent Group as our interface for the user. During that process we would create InventorySource that had a source of "manual".
def remove_manual_inventory_sources(apps, schema_editor): """Previously we would automatically create inventory sources after Group creation and we would use the parent Group as our interface for the user. During that process we would create InventorySource that had a source of "manual". """ Invento...
[ "def", "remove_manual_inventory_sources", "(", "apps", ",", "schema_editor", ")", ":", "InventoryUpdate", "=", "apps", ".", "get_model", "(", "'main'", ",", "'InventoryUpdate'", ")", "InventoryUpdate", ".", "objects", ".", "filter", "(", "source", "=", "''", ")"...
[ 5, 0 ]
[ 13, 54 ]
python
en
['en', 'en', 'en']
True
SkewNormal.pdf
(self, X, Y)
Conditional probability density function p(y|x) of the underlying probability model ( Args: X: x to be conditioned on - numpy array of shape (n_points, ndim_x) Y: y target values for witch the pdf shall be evaluated - numpy array of shape (n_points, ndim_y) Returns: p(X|Y) conditional densit...
Conditional probability density function p(y|x) of the underlying probability model ( Args: X: x to be conditioned on - numpy array of shape (n_points, ndim_x) Y: y target values for witch the pdf shall be evaluated - numpy array of shape (n_points, ndim_y)
def pdf(self, X, Y): """ Conditional probability density function p(y|x) of the underlying probability model ( Args: X: x to be conditioned on - numpy array of shape (n_points, ndim_x) Y: y target values for witch the pdf shall be evaluated - numpy array of shape (n_points, ndim_y) Returns: ...
[ "def", "pdf", "(", "self", ",", "X", ",", "Y", ")", ":", "X", ",", "Y", "=", "self", ".", "_handle_input_dimensionality", "(", "X", ",", "Y", ")", "locs", ",", "scales", ",", "skews", "=", "self", ".", "_loc_scale_skew_mapping", "(", "X", ")", "P",...
[ 49, 2 ]
[ 66, 12 ]
python
en
['en', 'en', 'en']
True
SkewNormal.cdf
(self, X, Y)
Conditional cumulated probability density function P(Y < y | x) of the underlying probability model Args: X: x to be conditioned on - numpy array of shape (n_points, ndim_x) Y: y target values for witch the cdf shall be evaluated - numpy array of shape (n_points, ndim_y) Returns: ...
Conditional cumulated probability density function P(Y < y | x) of the underlying probability model
def cdf(self, X, Y): """ Conditional cumulated probability density function P(Y < y | x) of the underlying probability model Args: X: x to be conditioned on - numpy array of shape (n_points, ndim_x) Y: y target values for witch the cdf shall be evaluated - numpy array of shape (n_points...
[ "def", "cdf", "(", "self", ",", "X", ",", "Y", ")", ":", "X", ",", "Y", "=", "self", ".", "_handle_input_dimensionality", "(", "X", ",", "Y", ")", "locs", ",", "scales", ",", "skews", "=", "self", ".", "_loc_scale_skew_mapping", "(", "X", ")", "P",...
[ 68, 2 ]
[ 85, 12 ]
python
en
['en', 'en', 'en']
True
SkewNormal.simulate_conditional
(self, X)
Draws random samples from the conditional distribution Args: X: x to be conditioned on when drawing a sample from y ~ p(y|x) - numpy array of shape (n_samples, ndim_x) Returns: Conditional random samples y drawn from p(y|x) - numpy array of shape (n_samples, ndim_y)
Draws random samples from the conditional distribution
def simulate_conditional(self, X): """ Draws random samples from the conditional distribution Args: X: x to be conditioned on when drawing a sample from y ~ p(y|x) - numpy array of shape (n_samples, ndim_x) Returns: Conditional random samples y drawn from p(y|x) - numpy array of shape (n_sampl...
[ "def", "simulate_conditional", "(", "self", ",", "X", ")", ":", "X", "=", "self", ".", "_handle_input_dimensionality", "(", "X", ")", "locs", ",", "scales", ",", "skews", "=", "self", ".", "_loc_scale_skew_mapping", "(", "X", ")", "rvs", "=", "np", ".", ...
[ 87, 2 ]
[ 105, 14 ]
python
en
['en', 'en', 'en']
True
SkewNormal.simulate
(self, n_samples=1000)
Draws random samples from the unconditional distribution p(x,y) Args: n_samples: (int) number of samples to be drawn from the conditional distribution Returns: (X,Y) - random samples drawn from p(x,y) - numpy arrays of shape (n_samples, ndim_x) and (n_samples, ndim_y)
Draws random samples from the unconditional distribution p(x,y)
def simulate(self, n_samples=1000): """ Draws random samples from the unconditional distribution p(x,y) Args: n_samples: (int) number of samples to be drawn from the conditional distribution Returns: (X,Y) - random samples drawn from p(x,y) - numpy arrays of shape (n_samples, ndim_...
[ "def", "simulate", "(", "self", ",", "n_samples", "=", "1000", ")", ":", "X", "=", "self", ".", "_sample_x", "(", "n_samples", ")", "assert", "X", ".", "shape", "==", "(", "n_samples", ",", "self", ".", "ndim_x", ")", "return", "X", ",", "self", "....
[ 107, 2 ]
[ 119, 42 ]
python
en
['en', 'en', 'en']
True
SkewNormal.mean_
(self, x_cond, n_samples=None)
Conditional mean of the distribution Args: x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x) Returns: Means E[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y)
Conditional mean of the distribution Args: x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x)
def mean_(self, x_cond, n_samples=None): """ Conditional mean of the distribution Args: x_cond: different x values to condition on - numpy array of shape (n_values, ndim_x) Returns: Means E[y|x] corresponding to x_cond - numpy array of shape (n_values, ndim_y) """ x = self._handle_input...
[ "def", "mean_", "(", "self", ",", "x_cond", ",", "n_samples", "=", "None", ")", ":", "x", "=", "self", ".", "_handle_input_dimensionality", "(", "x_cond", ")", "locs", ",", "_", ",", "_", "=", "self", ".", "_loc_scale_skew_mapping", "(", "x", ")", "ass...
[ 121, 2 ]
[ 132, 15 ]
python
en
['en', 'en', 'en']
True
AbiChecker.__init__
(self, old_version, new_version, configuration)
Instantiate the API/ABI checker. old_version: RepoVersion containing details to compare against new_version: RepoVersion containing details to check configuration.report_dir: directory for output files configuration.keep_all_reports: if false, delete old reports configuration.br...
Instantiate the API/ABI checker.
def __init__(self, old_version, new_version, configuration): """Instantiate the API/ABI checker. old_version: RepoVersion containing details to compare against new_version: RepoVersion containing details to check configuration.report_dir: directory for output files configuration...
[ "def", "__init__", "(", "self", ",", "old_version", ",", "new_version", ",", "configuration", ")", ":", "self", ".", "repo_path", "=", "\".\"", "self", ".", "log", "=", "None", "self", ".", "verbose", "=", "configuration", ".", "verbose", "self", ".", "_...
[ 34, 4 ]
[ 57, 34 ]
python
en
['en', 'pt', 'en']
True
AbiChecker._get_clean_worktree_for_git_revision
(self, version)
Make a separate worktree with version.revision checked out. Do not modify the current worktree.
Make a separate worktree with version.revision checked out. Do not modify the current worktree.
def _get_clean_worktree_for_git_revision(self, version): """Make a separate worktree with version.revision checked out. Do not modify the current worktree.""" git_worktree_path = tempfile.mkdtemp() if version.repository: self.log.debug( "Checking out git workt...
[ "def", "_get_clean_worktree_for_git_revision", "(", "self", ",", "version", ")", ":", "git_worktree_path", "=", "tempfile", ".", "mkdtemp", "(", ")", "if", "version", ".", "repository", ":", "self", ".", "log", ".", "debug", "(", "\"Checking out git worktree for r...
[ 80, 4 ]
[ 110, 32 ]
python
en
['en', 'en', 'en']
True
AbiChecker._update_git_submodules
(self, git_worktree_path, version)
If the crypto submodule is present, initialize it. if version.crypto_revision exists, update it to that revision, otherwise update it to the default revision
If the crypto submodule is present, initialize it. if version.crypto_revision exists, update it to that revision, otherwise update it to the default revision
def _update_git_submodules(self, git_worktree_path, version): """If the crypto submodule is present, initialize it. if version.crypto_revision exists, update it to that revision, otherwise update it to the default revision""" update_output = subprocess.check_output( [self.git...
[ "def", "_update_git_submodules", "(", "self", ",", "git_worktree_path", ",", "version", ")", ":", "update_output", "=", "subprocess", ".", "check_output", "(", "[", "self", ".", "git_command", ",", "\"submodule\"", ",", "\"update\"", ",", "\"--init\"", ",", "'--...
[ 112, 4 ]
[ 143, 55 ]
python
en
['en', 'en', 'en']
True
AbiChecker._build_shared_libraries
(self, git_worktree_path, version)
Build the shared libraries in the specified worktree.
Build the shared libraries in the specified worktree.
def _build_shared_libraries(self, git_worktree_path, version): """Build the shared libraries in the specified worktree.""" my_environment = os.environ.copy() my_environment["CFLAGS"] = "-g -Og" my_environment["SHARED"] = "1" if os.path.exists(os.path.join(git_worktree_path, "cryp...
[ "def", "_build_shared_libraries", "(", "self", ",", "git_worktree_path", ",", "version", ")", ":", "my_environment", "=", "os", ".", "environ", ".", "copy", "(", ")", "my_environment", "[", "\"CFLAGS\"", "]", "=", "\"-g -Og\"", "my_environment", "[", "\"SHARED\"...
[ 145, 4 ]
[ 163, 17 ]
python
en
['en', 'en', 'en']
True
AbiChecker._get_abi_dumps_from_shared_libraries
(self, version)
Generate the ABI dumps for the specified git revision. The shared libraries must have been built and the module paths present in version.modules.
Generate the ABI dumps for the specified git revision. The shared libraries must have been built and the module paths present in version.modules.
def _get_abi_dumps_from_shared_libraries(self, version): """Generate the ABI dumps for the specified git revision. The shared libraries must have been built and the module paths present in version.modules.""" for mbed_module, module_path in version.modules.items(): output_pat...
[ "def", "_get_abi_dumps_from_shared_libraries", "(", "self", ",", "version", ")", ":", "for", "mbed_module", ",", "module_path", "in", "version", ".", "modules", ".", "items", "(", ")", ":", "output_path", "=", "os", ".", "path", ".", "join", "(", "self", "...
[ 165, 4 ]
[ 186, 56 ]
python
en
['en', 'en', 'en']
True
AbiChecker._cleanup_worktree
(self, git_worktree_path)
Remove the specified git worktree.
Remove the specified git worktree.
def _cleanup_worktree(self, git_worktree_path): """Remove the specified git worktree.""" shutil.rmtree(git_worktree_path) worktree_output = subprocess.check_output( [self.git_command, "worktree", "prune"], cwd=self.repo_path, stderr=subprocess.STDOUT )...
[ "def", "_cleanup_worktree", "(", "self", ",", "git_worktree_path", ")", ":", "shutil", ".", "rmtree", "(", "git_worktree_path", ")", "worktree_output", "=", "subprocess", ".", "check_output", "(", "[", "self", ".", "git_command", ",", "\"worktree\"", ",", "\"pru...
[ 188, 4 ]
[ 196, 55 ]
python
en
['en', 'en', 'en']
True
AbiChecker._get_abi_dump_for_ref
(self, version)
Generate the ABI dumps for the specified git revision.
Generate the ABI dumps for the specified git revision.
def _get_abi_dump_for_ref(self, version): """Generate the ABI dumps for the specified git revision.""" git_worktree_path = self._get_clean_worktree_for_git_revision(version) self._update_git_submodules(git_worktree_path, version) self._build_shared_libraries(git_worktree_path, version) ...
[ "def", "_get_abi_dump_for_ref", "(", "self", ",", "version", ")", ":", "git_worktree_path", "=", "self", ".", "_get_clean_worktree_for_git_revision", "(", "version", ")", "self", ".", "_update_git_submodules", "(", "git_worktree_path", ",", "version", ")", "self", "...
[ 198, 4 ]
[ 204, 49 ]
python
en
['en', 'en', 'en']
True
AbiChecker.get_abi_compatibility_report
(self)
Generate a report of the differences between the reference ABI and the new ABI. ABI dumps from self.old_version and self.new_version must be available.
Generate a report of the differences between the reference ABI and the new ABI. ABI dumps from self.old_version and self.new_version must be available.
def get_abi_compatibility_report(self): """Generate a report of the differences between the reference ABI and the new ABI. ABI dumps from self.old_version and self.new_version must be available.""" compatibility_report = "" compliance_return_code = 0 shared_modules = list...
[ "def", "get_abi_compatibility_report", "(", "self", ")", ":", "compatibility_report", "=", "\"\"", "compliance_return_code", "=", "0", "shared_modules", "=", "list", "(", "set", "(", "self", ".", "old_version", ".", "modules", ".", "keys", "(", ")", ")", "&", ...
[ 224, 4 ]
[ 288, 37 ]
python
en
['en', 'en', 'en']
True
AbiChecker.check_for_abi_changes
(self)
Generate a report of ABI differences between self.old_rev and self.new_rev.
Generate a report of ABI differences between self.old_rev and self.new_rev.
def check_for_abi_changes(self): """Generate a report of ABI differences between self.old_rev and self.new_rev.""" self.check_repo_path() self.check_abi_tools_are_installed() self._get_abi_dump_for_ref(self.old_version) self._get_abi_dump_for_ref(self.new_version) ...
[ "def", "check_for_abi_changes", "(", "self", ")", ":", "self", ".", "check_repo_path", "(", ")", "self", ".", "check_abi_tools_are_installed", "(", ")", "self", ".", "_get_abi_dump_for_ref", "(", "self", ".", "old_version", ")", "self", ".", "_get_abi_dump_for_ref...
[ 290, 4 ]
[ 297, 50 ]
python
en
['en', 'en', 'en']
True
Command.write_migration_files
(self, changes)
Takes a changes dict and writes them out as migration files.
Takes a changes dict and writes them out as migration files.
def write_migration_files(self, changes): """ Takes a changes dict and writes them out as migration files. """ directory_created = {} for app_label, app_migrations in changes.items(): if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING...
[ "def", "write_migration_files", "(", "self", ",", "changes", ")", ":", "directory_created", "=", "{", "}", "for", "app_label", ",", "app_migrations", "in", "changes", ".", "items", "(", ")", ":", "if", "self", ".", "verbosity", ">=", "1", ":", "self", "....
[ 196, 4 ]
[ 240, 66 ]
python
en
['en', 'error', 'th']
False
Command.handle_merge
(self, loader, conflicts)
Handles merging together conflicted migrations interactively, if it's safe; otherwise, advises on how to fix it.
Handles merging together conflicted migrations interactively, if it's safe; otherwise, advises on how to fix it.
def handle_merge(self, loader, conflicts): """ Handles merging together conflicted migrations interactively, if it's safe; otherwise, advises on how to fix it. """ if self.interactive: questioner = InteractiveMigrationQuestioner() else: questioner ...
[ "def", "handle_merge", "(", "self", ",", "loader", ",", "conflicts", ")", ":", "if", "self", ".", "interactive", ":", "questioner", "=", "InteractiveMigrationQuestioner", "(", ")", "else", ":", "questioner", "=", "MigrationQuestioner", "(", "defaults", "=", "{...
[ 242, 4 ]
[ 321, 66 ]
python
en
['en', 'error', 'th']
False
setup_realm_internal_bots
(realm: Realm)
Create this realm's internal bots. This function is idempotent; it does nothing for a bot that already exists.
Create this realm's internal bots.
def setup_realm_internal_bots(realm: Realm) -> None: """Create this realm's internal bots. This function is idempotent; it does nothing for a bot that already exists. """ internal_bots = [ (bot["name"], bot["email_template"] % (settings.INTERNAL_BOT_DOMAIN,)) for bot in settings.REA...
[ "def", "setup_realm_internal_bots", "(", "realm", ":", "Realm", ")", "->", "None", ":", "internal_bots", "=", "[", "(", "bot", "[", "\"name\"", "]", ",", "bot", "[", "\"email_template\"", "]", "%", "(", "settings", ".", "INTERNAL_BOT_DOMAIN", ",", ")", ")"...
[ 31, 0 ]
[ 49, 18 ]
python
en
['en', 'en', 'en']
True
create_if_missing_realm_internal_bots
()
This checks if there is any realm internal bot missing. If that is the case, it creates the missing realm internal bots.
This checks if there is any realm internal bot missing.
def create_if_missing_realm_internal_bots() -> None: """This checks if there is any realm internal bot missing. If that is the case, it creates the missing realm internal bots. """ if missing_any_realm_internal_bots(): for realm in Realm.objects.all(): setup_realm_internal_bots(real...
[ "def", "create_if_missing_realm_internal_bots", "(", ")", "->", "None", ":", "if", "missing_any_realm_internal_bots", "(", ")", ":", "for", "realm", "in", "Realm", ".", "objects", ".", "all", "(", ")", ":", "setup_realm_internal_bots", "(", "realm", ")" ]
[ 52, 0 ]
[ 59, 44 ]
python
en
['en', 'en', 'en']
True
create_foliage
( constants: ConsensusConstants, reward_block_unfinished: RewardChainBlockUnfinished, block_generator: Optional[BlockGenerator], aggregate_sig: G2Element, additions: List[Coin], removals: List[Coin], prev_block: Optional[BlockRecord], blocks: BlockchainInterface, total_iters_sp: uint...
Creates a foliage for a given reward chain block. This may or may not be a tx block. In the case of a tx block, the return values are not None. This is called at the signage point, so some of this information may be tweaked at the infusion point. Args: constants: consensus constants being used...
Creates a foliage for a given reward chain block. This may or may not be a tx block. In the case of a tx block, the return values are not None. This is called at the signage point, so some of this information may be tweaked at the infusion point.
def create_foliage( constants: ConsensusConstants, reward_block_unfinished: RewardChainBlockUnfinished, block_generator: Optional[BlockGenerator], aggregate_sig: G2Element, additions: List[Coin], removals: List[Coin], prev_block: Optional[BlockRecord], blocks: BlockchainInterface, to...
[ "def", "create_foliage", "(", "constants", ":", "ConsensusConstants", ",", "reward_block_unfinished", ":", "RewardChainBlockUnfinished", ",", "block_generator", ":", "Optional", "[", "BlockGenerator", "]", ",", "aggregate_sig", ":", "G2Element", ",", "additions", ":", ...
[ 37, 0 ]
[ 272, 64 ]
python
en
['en', 'error', 'th']
False
create_unfinished_block
( constants: ConsensusConstants, sub_slot_start_total_iters: uint128, sub_slot_iters: uint64, signage_point_index: uint8, sp_iters: uint64, ip_iters: uint64, proof_of_space: ProofOfSpace, slot_cc_challenge: bytes32, farmer_reward_puzzle_hash: bytes32, pool_target: PoolTarget, ...
Creates a new unfinished block using all the information available at the signage point. This will have to be modified using information from the infusion point. Args: constants: consensus constants being used for this chain sub_slot_start_total_iters: the starting sub-slot iters at the si...
Creates a new unfinished block using all the information available at the signage point. This will have to be modified using information from the infusion point.
def create_unfinished_block( constants: ConsensusConstants, sub_slot_start_total_iters: uint128, sub_slot_iters: uint64, signage_point_index: uint8, sp_iters: uint64, ip_iters: uint64, proof_of_space: ProofOfSpace, slot_cc_challenge: bytes32, farmer_reward_puzzle_hash: bytes32, p...
[ "def", "create_unfinished_block", "(", "constants", ":", "ConsensusConstants", ",", "sub_slot_start_total_iters", ":", "uint128", ",", "sub_slot_iters", ":", "uint64", ",", "signage_point_index", ":", "uint8", ",", "sp_iters", ":", "uint64", ",", "ip_iters", ":", "u...
[ 275, 0 ]
[ 412, 5 ]
python
en
['en', 'error', 'th']
False
unfinished_block_to_full_block
( unfinished_block: UnfinishedBlock, cc_ip_vdf: VDFInfo, cc_ip_proof: VDFProof, rc_ip_vdf: VDFInfo, rc_ip_proof: VDFProof, icc_ip_vdf: Optional[VDFInfo], icc_ip_proof: Optional[VDFProof], finished_sub_slots: List[EndOfSubSlotBundle], prev_block: Optional[BlockRecord], blocks: Blo...
Converts an unfinished block to a finished block. Includes all the infusion point VDFs as well as tweaking other properties (height, weight, sub-slots, etc) Args: unfinished_block: the unfinished block to finish cc_ip_vdf: the challenge chain vdf info at the infusion point cc_ip_pr...
Converts an unfinished block to a finished block. Includes all the infusion point VDFs as well as tweaking other properties (height, weight, sub-slots, etc)
def unfinished_block_to_full_block( unfinished_block: UnfinishedBlock, cc_ip_vdf: VDFInfo, cc_ip_proof: VDFProof, rc_ip_vdf: VDFInfo, rc_ip_proof: VDFProof, icc_ip_vdf: Optional[VDFInfo], icc_ip_proof: Optional[VDFProof], finished_sub_slots: List[EndOfSubSlotBundle], prev_block: Opti...
[ "def", "unfinished_block_to_full_block", "(", "unfinished_block", ":", "UnfinishedBlock", ",", "cc_ip_vdf", ":", "VDFInfo", ",", "cc_ip_proof", ":", "VDFProof", ",", "rc_ip_vdf", ":", "VDFInfo", ",", "rc_ip_proof", ":", "VDFProof", ",", "icc_ip_vdf", ":", "Optional"...
[ 415, 0 ]
[ 516, 5 ]
python
en
['en', 'error', 'th']
False
color_format
(use_color, fmt_str, *args, **kwargs)
Return the result of 'fmt_str.format(*args, **kwargs)' after transforming 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' is False then all color codes in 'args' and 'kwargs' are replaced with the empty string.
Return the result of 'fmt_str.format(*args, **kwargs)' after transforming 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' is False then all color codes in 'args' and 'kwargs' are replaced with the empty string.
def color_format(use_color, fmt_str, *args, **kwargs): """ Return the result of 'fmt_str.format(*args, **kwargs)' after transforming 'args' and 'kwargs' according to the value of 'use_color'. If 'use_color' is False then all color codes in 'args' and 'kwargs' are replaced with the empty string. ...
[ "def", "color_format", "(", "use_color", ",", "fmt_str", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "use_color", "is", "True", "or", "use_color", "is", "False", "if", "not", "use_color", ":", "args", "=", "[", "arg", "if", "not", ...
[ 42, 0 ]
[ 55, 42 ]
python
en
['en', 'error', 'th']
False
find_longest_name
(benchmark_list)
Return the length of the longest benchmark name in a given list of benchmark JSON objects
Return the length of the longest benchmark name in a given list of benchmark JSON objects
def find_longest_name(benchmark_list): """ Return the length of the longest benchmark name in a given list of benchmark JSON objects """ longest_name = 1 for bc in benchmark_list: if len(bc['name']) > longest_name: longest_name = len(bc['name']) return longest_name
[ "def", "find_longest_name", "(", "benchmark_list", ")", ":", "longest_name", "=", "1", "for", "bc", "in", "benchmark_list", ":", "if", "len", "(", "bc", "[", "'name'", "]", ")", ">", "longest_name", ":", "longest_name", "=", "len", "(", "bc", "[", "'name...
[ 58, 0 ]
[ 67, 23 ]
python
en
['en', 'error', 'th']
False
calculate_change
(old_val, new_val)
Return a float representing the decimal change between old_val and new_val.
Return a float representing the decimal change between old_val and new_val.
def calculate_change(old_val, new_val): """ Return a float representing the decimal change between old_val and new_val. """ if old_val == 0 and new_val == 0: return 0.0 if old_val == 0: return float(new_val - old_val) / (float(old_val + new_val) / 2) return float(new_val - old_va...
[ "def", "calculate_change", "(", "old_val", ",", "new_val", ")", ":", "if", "old_val", "==", "0", "and", "new_val", "==", "0", ":", "return", "0.0", "if", "old_val", "==", "0", ":", "return", "float", "(", "new_val", "-", "old_val", ")", "/", "(", "fl...
[ 70, 0 ]
[ 78, 50 ]
python
en
['en', 'error', 'th']
False
filter_benchmark
(json_orig, family, replacement="")
Apply a filter to the json, and only leave the 'family' of benchmarks.
Apply a filter to the json, and only leave the 'family' of benchmarks.
def filter_benchmark(json_orig, family, replacement=""): """ Apply a filter to the json, and only leave the 'family' of benchmarks. """ regex = re.compile(family) filtered = {} filtered['benchmarks'] = [] for be in json_orig['benchmarks']: if not regex.search(be['name']): ...
[ "def", "filter_benchmark", "(", "json_orig", ",", "family", ",", "replacement", "=", "\"\"", ")", ":", "regex", "=", "re", ".", "compile", "(", "family", ")", "filtered", "=", "{", "}", "filtered", "[", "'benchmarks'", "]", "=", "[", "]", "for", "be", ...
[ 81, 0 ]
[ 94, 19 ]
python
en
['en', 'error', 'th']
False
get_unique_benchmark_names
(json)
While *keeping* the order, give all the unique 'names' used for benchmarks.
While *keeping* the order, give all the unique 'names' used for benchmarks.
def get_unique_benchmark_names(json): """ While *keeping* the order, give all the unique 'names' used for benchmarks. """ seen = set() uniqued = [x['name'] for x in json['benchmarks'] if x['name'] not in seen and (seen.add(x['name']) or True)] return uniqued
[ "def", "get_unique_benchmark_names", "(", "json", ")", ":", "seen", "=", "set", "(", ")", "uniqued", "=", "[", "x", "[", "'name'", "]", "for", "x", "in", "json", "[", "'benchmarks'", "]", "if", "x", "[", "'name'", "]", "not", "in", "seen", "and", "...
[ 97, 0 ]
[ 105, 18 ]
python
en
['en', 'error', 'th']
False
intersect
(list1, list2)
Given two lists, get a new list consisting of the elements only contained in *both of the input lists*, while preserving the ordering.
Given two lists, get a new list consisting of the elements only contained in *both of the input lists*, while preserving the ordering.
def intersect(list1, list2): """ Given two lists, get a new list consisting of the elements only contained in *both of the input lists*, while preserving the ordering. """ return [x for x in list1 if x in list2]
[ "def", "intersect", "(", "list1", ",", "list2", ")", ":", "return", "[", "x", "for", "x", "in", "list1", "if", "x", "in", "list2", "]" ]
[ 108, 0 ]
[ 113, 43 ]
python
en
['en', 'error', 'th']
False
partition_benchmarks
(json1, json2)
While preserving the ordering, find benchmarks with the same names in both of the inputs, and group them. (i.e. partition/filter into groups with common name)
While preserving the ordering, find benchmarks with the same names in both of the inputs, and group them. (i.e. partition/filter into groups with common name)
def partition_benchmarks(json1, json2): """ While preserving the ordering, find benchmarks with the same names in both of the inputs, and group them. (i.e. partition/filter into groups with common name) """ json1_unique_names = get_unique_benchmark_names(json1) json2_unique_names = get_uniqu...
[ "def", "partition_benchmarks", "(", "json1", ",", "json2", ")", ":", "json1_unique_names", "=", "get_unique_benchmark_names", "(", "json1", ")", "json2_unique_names", "=", "get_unique_benchmark_names", "(", "json2", ")", "names", "=", "intersect", "(", "json1_unique_n...
[ 116, 0 ]
[ 136, 21 ]
python
en
['en', 'error', 'th']
False
generate_difference_report
( json1, json2, display_aggregates_only=False, utest=False, utest_alpha=0.05, use_color=True)
Calculate and report the difference between each test of two benchmarks runs specified as 'json1' and 'json2'.
Calculate and report the difference between each test of two benchmarks runs specified as 'json1' and 'json2'.
def generate_difference_report( json1, json2, display_aggregates_only=False, utest=False, utest_alpha=0.05, use_color=True): """ Calculate and report the difference between each test of two benchmarks runs specified as 'json1' and 'json2'. """ assert u...
[ "def", "generate_difference_report", "(", "json1", ",", "json2", ",", "display_aggregates_only", "=", "False", ",", "utest", "=", "False", ",", "utest_alpha", "=", "0.05", ",", "use_color", "=", "True", ")", ":", "assert", "utest", "is", "True", "or", "utest...
[ 190, 0 ]
[ 266, 22 ]
python
en
['en', 'error', 'th']
False
Chat.__init__
(self, channel: str, nickname: str, oauth: str, helix: Optional['twitch.Helix'] = None)
:param channel: Channel name :param nickname: User nickname :param oauth: Twitch OAuth :param helix: Optional Helix API
:param channel: Channel name :param nickname: User nickname :param oauth: Twitch OAuth :param helix: Optional Helix API
def __init__(self, channel: str, nickname: str, oauth: str, helix: Optional['twitch.Helix'] = None): """ :param channel: Channel name :param nickname: User nickname :param oauth: Twitch OAuth :param helix: Optional Helix API """ super().__init__() self.hel...
[ "def", "__init__", "(", "self", ",", "channel", ":", "str", ",", "nickname", ":", "str", ",", "oauth", ":", "str", ",", "helix", ":", "Optional", "[", "'twitch.Helix'", "]", "=", "None", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self...
[ 11, 4 ]
[ 26, 33 ]
python
en
['en', 'error', 'th']
False
get_image_model_string
()
Get the dotted ``app.Model`` name for the image model as a string. Useful for developers making Wagtail plugins that need to refer to the image model, such as in foreign keys, but the model itself is not required.
Get the dotted ``app.Model`` name for the image model as a string. Useful for developers making Wagtail plugins that need to refer to the image model, such as in foreign keys, but the model itself is not required.
def get_image_model_string(): """ Get the dotted ``app.Model`` name for the image model as a string. Useful for developers making Wagtail plugins that need to refer to the image model, such as in foreign keys, but the model itself is not required. """ return getattr(settings, 'WAGTAILIMAGES_IMAG...
[ "def", "get_image_model_string", "(", ")", ":", "return", "getattr", "(", "settings", ",", "'WAGTAILIMAGES_IMAGE_MODEL'", ",", "'wagtailimages.Image'", ")" ]
[ 7, 0 ]
[ 13, 80 ]
python
en
['en', 'error', 'th']
False
get_image_model
()
Get the image model from the ``WAGTAILIMAGES_IMAGE_MODEL`` setting. Useful for developers making Wagtail plugins that need the image model. Defaults to the standard :class:`~wagtail.images.models.Image` model if no custom model is defined.
Get the image model from the ``WAGTAILIMAGES_IMAGE_MODEL`` setting. Useful for developers making Wagtail plugins that need the image model. Defaults to the standard :class:`~wagtail.images.models.Image` model if no custom model is defined.
def get_image_model(): """ Get the image model from the ``WAGTAILIMAGES_IMAGE_MODEL`` setting. Useful for developers making Wagtail plugins that need the image model. Defaults to the standard :class:`~wagtail.images.models.Image` model if no custom model is defined. """ from django.apps impo...
[ "def", "get_image_model", "(", ")", ":", "from", "django", ".", "apps", "import", "apps", "model_string", "=", "get_image_model_string", "(", ")", "try", ":", "return", "apps", ".", "get_model", "(", "model_string", ")", "except", "ValueError", ":", "raise", ...
[ 16, 0 ]
[ 32, 9 ]
python
en
['en', 'error', 'th']
False