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
LinuxDistribution.__init__
(self, include_lsb=True, os_release_file='', distro_release_file='', include_uname=True)
The initialization method of this class gathers information from the available data sources, and stores that in private instance attributes. Subsequent access to the information items uses these private instance attributes, so that the data sources are read only once. Parameter...
The initialization method of this class gathers information from the available data sources, and stores that in private instance attributes. Subsequent access to the information items uses these private instance attributes, so that the data sources are read only once.
def __init__(self, include_lsb=True, os_release_file='', distro_release_file='', include_uname=True): """ The initialization method of this class gathers information from the available data sources, and stores that in private in...
[ "def", "__init__", "(", "self", ",", "include_lsb", "=", "True", ",", "os_release_file", "=", "''", ",", "distro_release_file", "=", "''", ",", "include_uname", "=", "True", ")", ":", "self", ".", "os_release_file", "=", "os_release_file", "or", "os", ".", ...
[ 577, 4 ]
[ 653, 42 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.__repr__
(self)
Return repr of all info
Return repr of all info
def __repr__(self): """Return repr of all info """ return \ "LinuxDistribution(" \ "os_release_file={self.os_release_file!r}, " \ "distro_release_file={self.distro_release_file!r}, " \ "include_lsb={self.include_lsb!r}, " \ "include_una...
[ "def", "__repr__", "(", "self", ")", ":", "return", "\"LinuxDistribution(\"", "\"os_release_file={self.os_release_file!r}, \"", "\"distro_release_file={self.distro_release_file!r}, \"", "\"include_lsb={self.include_lsb!r}, \"", "\"include_uname={self.include_uname!r}, \"", "\"_os_release_inf...
[ 655, 4 ]
[ 668, 26 ]
python
en
['en', 'no', 'en']
True
LinuxDistribution.linux_distribution
(self, full_distribution_name=True)
Return information about the OS distribution that is compatible with Python's :func:`platform.linux_distribution`, supporting a subset of its parameters. For details, see :func:`distro.linux_distribution`.
Return information about the OS distribution that is compatible with Python's :func:`platform.linux_distribution`, supporting a subset of its parameters.
def linux_distribution(self, full_distribution_name=True): """ Return information about the OS distribution that is compatible with Python's :func:`platform.linux_distribution`, supporting a subset of its parameters. For details, see :func:`distro.linux_distribution`. ""...
[ "def", "linux_distribution", "(", "self", ",", "full_distribution_name", "=", "True", ")", ":", "return", "(", "self", ".", "name", "(", ")", "if", "full_distribution_name", "else", "self", ".", "id", "(", ")", ",", "self", ".", "version", "(", ")", ",",...
[ 670, 4 ]
[ 682, 9 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.id
(self)
Return the distro ID of the OS distribution, as a string. For details, see :func:`distro.id`.
Return the distro ID of the OS distribution, as a string.
def id(self): """Return the distro ID of the OS distribution, as a string. For details, see :func:`distro.id`. """ def normalize(distro_id, table): distro_id = distro_id.lower().replace(' ', '_') return table.get(distro_id, distro_id) distro_id = self.os...
[ "def", "id", "(", "self", ")", ":", "def", "normalize", "(", "distro_id", ",", "table", ")", ":", "distro_id", "=", "distro_id", ".", "lower", "(", ")", ".", "replace", "(", "' '", ",", "'_'", ")", "return", "table", ".", "get", "(", "distro_id", "...
[ 684, 4 ]
[ 709, 17 ]
python
en
['en', 'en', 'en']
True
LinuxDistribution.name
(self, pretty=False)
Return the name of the OS distribution, as a string. For details, see :func:`distro.name`.
Return the name of the OS distribution, as a string.
def name(self, pretty=False): """ Return the name of the OS distribution, as a string. For details, see :func:`distro.name`. """ name = self.os_release_attr('name') \ or self.lsb_release_attr('distributor_id') \ or self.distro_release_attr('name') \ ...
[ "def", "name", "(", "self", ",", "pretty", "=", "False", ")", ":", "name", "=", "self", ".", "os_release_attr", "(", "'name'", ")", "or", "self", ".", "lsb_release_attr", "(", "'distributor_id'", ")", "or", "self", ".", "distro_release_attr", "(", "'name'"...
[ 711, 4 ]
[ 730, 25 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.version
(self, pretty=False, best=False)
Return the version of the OS distribution, as a string. For details, see :func:`distro.version`.
Return the version of the OS distribution, as a string.
def version(self, pretty=False, best=False): """ Return the version of the OS distribution, as a string. For details, see :func:`distro.version`. """ versions = [ self.os_release_attr('version_id'), self.lsb_release_attr('release'), self.distr...
[ "def", "version", "(", "self", ",", "pretty", "=", "False", ",", "best", "=", "False", ")", ":", "versions", "=", "[", "self", ".", "os_release_attr", "(", "'version_id'", ")", ",", "self", ".", "lsb_release_attr", "(", "'release'", ")", ",", "self", "...
[ 732, 4 ]
[ 764, 22 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.version_parts
(self, best=False)
Return the version of the OS distribution, as a tuple of version numbers. For details, see :func:`distro.version_parts`.
Return the version of the OS distribution, as a tuple of version numbers.
def version_parts(self, best=False): """ Return the version of the OS distribution, as a tuple of version numbers. For details, see :func:`distro.version_parts`. """ version_str = self.version(best=best) if version_str: version_regex = re.compile(r'(\...
[ "def", "version_parts", "(", "self", ",", "best", "=", "False", ")", ":", "version_str", "=", "self", ".", "version", "(", "best", "=", "best", ")", "if", "version_str", ":", "version_regex", "=", "re", ".", "compile", "(", "r'(\\d+)\\.?(\\d+)?\\.?(\\d+)?'",...
[ 766, 4 ]
[ 780, 25 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.major_version
(self, best=False)
Return the major version number of the current distribution. For details, see :func:`distro.major_version`.
Return the major version number of the current distribution.
def major_version(self, best=False): """ Return the major version number of the current distribution. For details, see :func:`distro.major_version`. """ return self.version_parts(best)[0]
[ "def", "major_version", "(", "self", ",", "best", "=", "False", ")", ":", "return", "self", ".", "version_parts", "(", "best", ")", "[", "0", "]" ]
[ 782, 4 ]
[ 788, 42 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.minor_version
(self, best=False)
Return the minor version number of the current distribution. For details, see :func:`distro.minor_version`.
Return the minor version number of the current distribution.
def minor_version(self, best=False): """ Return the minor version number of the current distribution. For details, see :func:`distro.minor_version`. """ return self.version_parts(best)[1]
[ "def", "minor_version", "(", "self", ",", "best", "=", "False", ")", ":", "return", "self", ".", "version_parts", "(", "best", ")", "[", "1", "]" ]
[ 790, 4 ]
[ 796, 42 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.build_number
(self, best=False)
Return the build number of the current distribution. For details, see :func:`distro.build_number`.
Return the build number of the current distribution.
def build_number(self, best=False): """ Return the build number of the current distribution. For details, see :func:`distro.build_number`. """ return self.version_parts(best)[2]
[ "def", "build_number", "(", "self", ",", "best", "=", "False", ")", ":", "return", "self", ".", "version_parts", "(", "best", ")", "[", "2", "]" ]
[ 798, 4 ]
[ 804, 42 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.like
(self)
Return the IDs of distributions that are like the OS distribution. For details, see :func:`distro.like`.
Return the IDs of distributions that are like the OS distribution.
def like(self): """ Return the IDs of distributions that are like the OS distribution. For details, see :func:`distro.like`. """ return self.os_release_attr('id_like') or ''
[ "def", "like", "(", "self", ")", ":", "return", "self", ".", "os_release_attr", "(", "'id_like'", ")", "or", "''" ]
[ 806, 4 ]
[ 812, 52 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.codename
(self)
Return the codename of the OS distribution. For details, see :func:`distro.codename`.
Return the codename of the OS distribution.
def codename(self): """ Return the codename of the OS distribution. For details, see :func:`distro.codename`. """ try: # Handle os_release specially since distros might purposefully set # this to empty string to have no codename return self._o...
[ "def", "codename", "(", "self", ")", ":", "try", ":", "# Handle os_release specially since distros might purposefully set", "# this to empty string to have no codename", "return", "self", ".", "_os_release_info", "[", "'codename'", "]", "except", "KeyError", ":", "return", ...
[ 814, 4 ]
[ 827, 21 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.info
(self, pretty=False, best=False)
Return certain machine-readable information about the OS distribution. For details, see :func:`distro.info`.
Return certain machine-readable information about the OS distribution.
def info(self, pretty=False, best=False): """ Return certain machine-readable information about the OS distribution. For details, see :func:`distro.info`. """ return dict( id=self.id(), version=self.version(pretty, best), version_parts...
[ "def", "info", "(", "self", ",", "pretty", "=", "False", ",", "best", "=", "False", ")", ":", "return", "dict", "(", "id", "=", "self", ".", "id", "(", ")", ",", "version", "=", "self", ".", "version", "(", "pretty", ",", "best", ")", ",", "ver...
[ 829, 4 ]
[ 846, 9 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.os_release_info
(self)
Return a dictionary containing key-value pairs for the information items from the os-release file data source of the OS distribution. For details, see :func:`distro.os_release_info`.
Return a dictionary containing key-value pairs for the information items from the os-release file data source of the OS distribution.
def os_release_info(self): """ Return a dictionary containing key-value pairs for the information items from the os-release file data source of the OS distribution. For details, see :func:`distro.os_release_info`. """ return self._os_release_info
[ "def", "os_release_info", "(", "self", ")", ":", "return", "self", ".", "_os_release_info" ]
[ 848, 4 ]
[ 855, 36 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.lsb_release_info
(self)
Return a dictionary containing key-value pairs for the information items from the lsb_release command data source of the OS distribution. For details, see :func:`distro.lsb_release_info`.
Return a dictionary containing key-value pairs for the information items from the lsb_release command data source of the OS distribution.
def lsb_release_info(self): """ Return a dictionary containing key-value pairs for the information items from the lsb_release command data source of the OS distribution. For details, see :func:`distro.lsb_release_info`. """ return self._lsb_release_info
[ "def", "lsb_release_info", "(", "self", ")", ":", "return", "self", ".", "_lsb_release_info" ]
[ 857, 4 ]
[ 865, 37 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.distro_release_info
(self)
Return a dictionary containing key-value pairs for the information items from the distro release file data source of the OS distribution. For details, see :func:`distro.distro_release_info`.
Return a dictionary containing key-value pairs for the information items from the distro release file data source of the OS distribution.
def distro_release_info(self): """ Return a dictionary containing key-value pairs for the information items from the distro release file data source of the OS distribution. For details, see :func:`distro.distro_release_info`. """ return self._distro_release_info
[ "def", "distro_release_info", "(", "self", ")", ":", "return", "self", ".", "_distro_release_info" ]
[ 867, 4 ]
[ 875, 40 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.uname_info
(self)
Return a dictionary containing key-value pairs for the information items from the uname command data source of the OS distribution. For details, see :func:`distro.uname_info`.
Return a dictionary containing key-value pairs for the information items from the uname command data source of the OS distribution.
def uname_info(self): """ Return a dictionary containing key-value pairs for the information items from the uname command data source of the OS distribution. For details, see :func:`distro.uname_info`. """ return self._uname_info
[ "def", "uname_info", "(", "self", ")", ":", "return", "self", ".", "_uname_info" ]
[ 877, 4 ]
[ 884, 31 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.os_release_attr
(self, attribute)
Return a single named information item from the os-release file data source of the OS distribution. For details, see :func:`distro.os_release_attr`.
Return a single named information item from the os-release file data source of the OS distribution.
def os_release_attr(self, attribute): """ Return a single named information item from the os-release file data source of the OS distribution. For details, see :func:`distro.os_release_attr`. """ return self._os_release_info.get(attribute, '')
[ "def", "os_release_attr", "(", "self", ",", "attribute", ")", ":", "return", "self", ".", "_os_release_info", ".", "get", "(", "attribute", ",", "''", ")" ]
[ 886, 4 ]
[ 893, 55 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.lsb_release_attr
(self, attribute)
Return a single named information item from the lsb_release command output data source of the OS distribution. For details, see :func:`distro.lsb_release_attr`.
Return a single named information item from the lsb_release command output data source of the OS distribution.
def lsb_release_attr(self, attribute): """ Return a single named information item from the lsb_release command output data source of the OS distribution. For details, see :func:`distro.lsb_release_attr`. """ return self._lsb_release_info.get(attribute, '')
[ "def", "lsb_release_attr", "(", "self", ",", "attribute", ")", ":", "return", "self", ".", "_lsb_release_info", ".", "get", "(", "attribute", ",", "''", ")" ]
[ 895, 4 ]
[ 902, 56 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.distro_release_attr
(self, attribute)
Return a single named information item from the distro release file data source of the OS distribution. For details, see :func:`distro.distro_release_attr`.
Return a single named information item from the distro release file data source of the OS distribution.
def distro_release_attr(self, attribute): """ Return a single named information item from the distro release file data source of the OS distribution. For details, see :func:`distro.distro_release_attr`. """ return self._distro_release_info.get(attribute, '')
[ "def", "distro_release_attr", "(", "self", ",", "attribute", ")", ":", "return", "self", ".", "_distro_release_info", ".", "get", "(", "attribute", ",", "''", ")" ]
[ 904, 4 ]
[ 911, 59 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution.uname_attr
(self, attribute)
Return a single named information item from the uname command output data source of the OS distribution. For details, see :func:`distro.uname_release_attr`.
Return a single named information item from the uname command output data source of the OS distribution.
def uname_attr(self, attribute): """ Return a single named information item from the uname command output data source of the OS distribution. For details, see :func:`distro.uname_release_attr`. """ return self._uname_info.get(attribute, '')
[ "def", "uname_attr", "(", "self", ",", "attribute", ")", ":", "return", "self", ".", "_uname_info", ".", "get", "(", "attribute", ",", "''", ")" ]
[ 913, 4 ]
[ 920, 50 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution._os_release_info
(self)
Get the information items from the specified os-release file. Returns: A dictionary containing all information items.
Get the information items from the specified os-release file.
def _os_release_info(self): """ Get the information items from the specified os-release file. Returns: A dictionary containing all information items. """ if os.path.isfile(self.os_release_file): with open(self.os_release_file) as release_file: ...
[ "def", "_os_release_info", "(", "self", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "os_release_file", ")", ":", "with", "open", "(", "self", ".", "os_release_file", ")", "as", "release_file", ":", "return", "self", ".", "_parse_o...
[ 923, 4 ]
[ 933, 17 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution._parse_os_release_content
(lines)
Parse the lines of an os-release file. Parameters: * lines: Iterable through the lines in the os-release file. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items. ...
Parse the lines of an os-release file.
def _parse_os_release_content(lines): """ Parse the lines of an os-release file. Parameters: * lines: Iterable through the lines in the os-release file. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: A ...
[ "def", "_parse_os_release_content", "(", "lines", ")", ":", "props", "=", "{", "}", "lexer", "=", "shlex", ".", "shlex", "(", "lines", ",", "posix", "=", "True", ")", "lexer", ".", "whitespace_split", "=", "True", "# The shlex module defines its `wordchars` vari...
[ 936, 4 ]
[ 998, 20 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution._lsb_release_info
(self)
Get the information items from the lsb_release command output. Returns: A dictionary containing all information items.
Get the information items from the lsb_release command output.
def _lsb_release_info(self): """ Get the information items from the lsb_release command output. Returns: A dictionary containing all information items. """ if not self.include_lsb: return {} with open(os.devnull, 'w') as devnull: try: ...
[ "def", "_lsb_release_info", "(", "self", ")", ":", "if", "not", "self", ".", "include_lsb", ":", "return", "{", "}", "with", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "as", "devnull", ":", "try", ":", "cmd", "=", "(", "'lsb_release'", ",", ...
[ 1001, 4 ]
[ 1017, 55 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution._parse_lsb_release_content
(lines)
Parse the output of the lsb_release command. Parameters: * lines: Iterable through the lines of the lsb_release output. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information it...
Parse the output of the lsb_release command.
def _parse_lsb_release_content(lines): """ Parse the output of the lsb_release command. Parameters: * lines: Iterable through the lines of the lsb_release output. Each line must be a unicode string or a UTF-8 encoded byte string. Returns: ...
[ "def", "_parse_lsb_release_content", "(", "lines", ")", ":", "props", "=", "{", "}", "for", "line", "in", "lines", ":", "kv", "=", "line", ".", "strip", "(", "'\\n'", ")", ".", "split", "(", "':'", ",", "1", ")", "if", "len", "(", "kv", ")", "!="...
[ 1020, 4 ]
[ 1041, 20 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution._distro_release_info
(self)
Get the information items from the specified distro release file. Returns: A dictionary containing all information items.
Get the information items from the specified distro release file.
def _distro_release_info(self): """ Get the information items from the specified distro release file. Returns: A dictionary containing all information items. """ if self.distro_release_file: # If it was specified, we use it and parse what we can, even if ...
[ "def", "_distro_release_info", "(", "self", ")", ":", "if", "self", ".", "distro_release_file", ":", "# If it was specified, we use it and parse what we can, even if", "# its file name or content does not match the expected pattern.", "distro_info", "=", "self", ".", "_parse_distro...
[ 1086, 4 ]
[ 1151, 21 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution._parse_distro_release_file
(self, filepath)
Parse a distro release file. Parameters: * filepath: Path name of the distro release file. Returns: A dictionary containing all information items.
Parse a distro release file.
def _parse_distro_release_file(self, filepath): """ Parse a distro release file. Parameters: * filepath: Path name of the distro release file. Returns: A dictionary containing all information items. """ try: with open(filepath) as fp: ...
[ "def", "_parse_distro_release_file", "(", "self", ",", "filepath", ")", ":", "try", ":", "with", "open", "(", "filepath", ")", "as", "fp", ":", "# Only parse the first line. For instance, on SLES there", "# are multiple lines. We don't want them...", "return", "self", "."...
[ 1153, 4 ]
[ 1173, 21 ]
python
en
['en', 'error', 'th']
False
LinuxDistribution._parse_distro_release_content
(line)
Parse a line from a distro release file. Parameters: * line: Line from the distro release file. Must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information items.
Parse a line from a distro release file.
def _parse_distro_release_content(line): """ Parse a line from a distro release file. Parameters: * line: Line from the distro release file. Must be a unicode string or a UTF-8 encoded byte string. Returns: A dictionary containing all information ite...
[ "def", "_parse_distro_release_content", "(", "line", ")", ":", "matches", "=", "_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN", ".", "match", "(", "line", ".", "strip", "(", ")", "[", ":", ":", "-", "1", "]", ")", "distro_info", "=", "{", "}", "if", "matches", ...
[ 1176, 4 ]
[ 1199, 26 ]
python
en
['en', 'error', 'th']
False
expand_longitude_slice_by_degrees
(min_lon, max_lon, include_prime_meridian, degrees)
Returns a tuple of expanded min and max longitude, whether the expanded area includes the prime meridian, and the final span of the expanded angle in degrees.
Returns a tuple of expanded min and max longitude, whether the expanded area includes the prime meridian, and the final span of the expanded angle in degrees.
def expand_longitude_slice_by_degrees(min_lon, max_lon, include_prime_meridian, degrees) \ -> (int, int, bool, int): """ Returns a tuple of expanded min and max longitude, whether the expanded area includes the prime meridian, and the final span of the expanded angle in degrees. """ if min_l...
[ "def", "expand_longitude_slice_by_degrees", "(", "min_lon", ",", "max_lon", ",", "include_prime_meridian", ",", "degrees", ")", "->", "(", "int", ",", "int", ",", "bool", ",", "int", ")", ":", "if", "min_lon", ">", "max_lon", ":", "# Swap min and max to simplify...
[ 56, 0 ]
[ 108, 84 ]
python
en
['en', 'error', 'th']
False
loadImageSeries
(filelist=None)
create a list of :py:class:`~PIL.Image.Image` objects for use in a montage
create a list of :py:class:`~PIL.Image.Image` objects for use in a montage
def loadImageSeries(filelist=None): """create a list of :py:class:`~PIL.Image.Image` objects for use in a montage""" if filelist is None or len(filelist) < 1: return imglist = [] for img in filelist: if not os.path.exists(img): print(f"unable to find {img}") cont...
[ "def", "loadImageSeries", "(", "filelist", "=", "None", ")", ":", "if", "filelist", "is", "None", "or", "len", "(", "filelist", ")", "<", "1", ":", "return", "imglist", "=", "[", "]", "for", "img", "in", "filelist", ":", "if", "not", "os", ".", "pa...
[ 207, 0 ]
[ 226, 18 ]
python
en
['en', 'en', 'en']
True
PostGISIntrospection.get_geometry_type
(self, table_name, description)
The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it's a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to determine the geometry type.
The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it's a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to determine the geometry type.
def get_geometry_type(self, table_name, description): """ The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it's a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to...
[ "def", "get_geometry_type", "(", "self", ",", "table_name", ",", "description", ")", ":", "with", "self", ".", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "cursor", ".", "execute", "(", "\"\"\"\n SELECT t.coord_dimension, t.srid, t.typ...
[ 28, 4 ]
[ 59, 39 ]
python
en
['en', 'error', 'th']
False
with_metaclass
(meta, *bases)
Create a base class with a metaclass.
Create a base class with a metaclass.
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a # dummy metaclass for one level of class instantiation that replaces # itself with the actual metaclass. class metaclass(type): def __new__(cls, nam...
[ "def", "with_metaclass", "(", "meta", ",", "*", "bases", ")", ":", "# This requires a bit of explanation: the basic idea is to make a", "# dummy metaclass for one level of class instantiation that replaces", "# itself with the actual metaclass.", "class", "metaclass", "(", "type", ")...
[ 55, 0 ]
[ 63, 61 ]
python
en
['en', 'en', 'en']
True
ETagRequestMixin.cache_control
(self)
A :class:`~werkzeug.datastructures.RequestCacheControl` object for the incoming cache control headers.
A :class:`~werkzeug.datastructures.RequestCacheControl` object for the incoming cache control headers.
def cache_control(self): """A :class:`~werkzeug.datastructures.RequestCacheControl` object for the incoming cache control headers. """ cache_control = self.environ.get("HTTP_CACHE_CONTROL") return parse_cache_control_header(cache_control, None, RequestCacheControl)
[ "def", "cache_control", "(", "self", ")", ":", "cache_control", "=", "self", ".", "environ", ".", "get", "(", "\"HTTP_CACHE_CONTROL\"", ")", "return", "parse_cache_control_header", "(", "cache_control", ",", "None", ",", "RequestCacheControl", ")" ]
[ 29, 4 ]
[ 34, 83 ]
python
de
['de', 'en', 'de']
True
ETagRequestMixin.if_match
(self)
An object containing all the etags in the `If-Match` header. :rtype: :class:`~werkzeug.datastructures.ETags`
An object containing all the etags in the `If-Match` header.
def if_match(self): """An object containing all the etags in the `If-Match` header. :rtype: :class:`~werkzeug.datastructures.ETags` """ return parse_etags(self.environ.get("HTTP_IF_MATCH"))
[ "def", "if_match", "(", "self", ")", ":", "return", "parse_etags", "(", "self", ".", "environ", ".", "get", "(", "\"HTTP_IF_MATCH\"", ")", ")" ]
[ 37, 4 ]
[ 42, 61 ]
python
en
['en', 'en', 'en']
True
ETagRequestMixin.if_none_match
(self)
An object containing all the etags in the `If-None-Match` header. :rtype: :class:`~werkzeug.datastructures.ETags`
An object containing all the etags in the `If-None-Match` header.
def if_none_match(self): """An object containing all the etags in the `If-None-Match` header. :rtype: :class:`~werkzeug.datastructures.ETags` """ return parse_etags(self.environ.get("HTTP_IF_NONE_MATCH"))
[ "def", "if_none_match", "(", "self", ")", ":", "return", "parse_etags", "(", "self", ".", "environ", ".", "get", "(", "\"HTTP_IF_NONE_MATCH\"", ")", ")" ]
[ 45, 4 ]
[ 50, 66 ]
python
en
['en', 'en', 'en']
True
ETagRequestMixin.if_modified_since
(self)
The parsed `If-Modified-Since` header as datetime object.
The parsed `If-Modified-Since` header as datetime object.
def if_modified_since(self): """The parsed `If-Modified-Since` header as datetime object.""" return parse_date(self.environ.get("HTTP_IF_MODIFIED_SINCE"))
[ "def", "if_modified_since", "(", "self", ")", ":", "return", "parse_date", "(", "self", ".", "environ", ".", "get", "(", "\"HTTP_IF_MODIFIED_SINCE\"", ")", ")" ]
[ 53, 4 ]
[ 55, 69 ]
python
en
['en', 'en', 'en']
True
ETagRequestMixin.if_unmodified_since
(self)
The parsed `If-Unmodified-Since` header as datetime object.
The parsed `If-Unmodified-Since` header as datetime object.
def if_unmodified_since(self): """The parsed `If-Unmodified-Since` header as datetime object.""" return parse_date(self.environ.get("HTTP_IF_UNMODIFIED_SINCE"))
[ "def", "if_unmodified_since", "(", "self", ")", ":", "return", "parse_date", "(", "self", ".", "environ", ".", "get", "(", "\"HTTP_IF_UNMODIFIED_SINCE\"", ")", ")" ]
[ 58, 4 ]
[ 60, 71 ]
python
en
['en', 'en', 'en']
True
ETagRequestMixin.if_range
(self)
The parsed `If-Range` header. .. versionadded:: 0.7 :rtype: :class:`~werkzeug.datastructures.IfRange`
The parsed `If-Range` header.
def if_range(self): """The parsed `If-Range` header. .. versionadded:: 0.7 :rtype: :class:`~werkzeug.datastructures.IfRange` """ return parse_if_range_header(self.environ.get("HTTP_IF_RANGE"))
[ "def", "if_range", "(", "self", ")", ":", "return", "parse_if_range_header", "(", "self", ".", "environ", ".", "get", "(", "\"HTTP_IF_RANGE\"", ")", ")" ]
[ 63, 4 ]
[ 70, 71 ]
python
en
['en', 'af', 'en']
True
ETagRequestMixin.range
(self)
The parsed `Range` header. .. versionadded:: 0.7 :rtype: :class:`~werkzeug.datastructures.Range`
The parsed `Range` header.
def range(self): """The parsed `Range` header. .. versionadded:: 0.7 :rtype: :class:`~werkzeug.datastructures.Range` """ return parse_range_header(self.environ.get("HTTP_RANGE"))
[ "def", "range", "(", "self", ")", ":", "return", "parse_range_header", "(", "self", ".", "environ", ".", "get", "(", "\"HTTP_RANGE\"", ")", ")" ]
[ 73, 4 ]
[ 80, 65 ]
python
en
['en', 'af', 'en']
True
ETagResponseMixin.cache_control
(self)
The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.
The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.
def cache_control(self): """The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain. """ def on_update(cache_control): if not cache_control and "cache-control" in self.headers...
[ "def", "cache_control", "(", "self", ")", ":", "def", "on_update", "(", "cache_control", ")", ":", "if", "not", "cache_control", "and", "\"cache-control\"", "in", "self", ".", "headers", ":", "del", "self", ".", "headers", "[", "\"cache-control\"", "]", "eli...
[ 95, 4 ]
[ 109, 9 ]
python
en
['en', 'en', 'en']
True
ETagResponseMixin._wrap_response
(self, start, length)
Wrap existing Response in case of Range Request context.
Wrap existing Response in case of Range Request context.
def _wrap_response(self, start, length): """Wrap existing Response in case of Range Request context.""" if self.status_code == 206: self.response = _RangeWrapper(self.response, start, length)
[ "def", "_wrap_response", "(", "self", ",", "start", ",", "length", ")", ":", "if", "self", ".", "status_code", "==", "206", ":", "self", ".", "response", "=", "_RangeWrapper", "(", "self", ".", "response", ",", "start", ",", "length", ")" ]
[ 111, 4 ]
[ 114, 71 ]
python
en
['en', 'en', 'en']
True
ETagResponseMixin._is_range_request_processable
(self, environ)
Return ``True`` if `Range` header is present and if underlying resource is considered unchanged when compared with `If-Range` header.
Return ``True`` if `Range` header is present and if underlying resource is considered unchanged when compared with `If-Range` header.
def _is_range_request_processable(self, environ): """Return ``True`` if `Range` header is present and if underlying resource is considered unchanged when compared with `If-Range` header. """ return ( "HTTP_IF_RANGE" not in environ or not is_resource_modified( ...
[ "def", "_is_range_request_processable", "(", "self", ",", "environ", ")", ":", "return", "(", "\"HTTP_IF_RANGE\"", "not", "in", "environ", "or", "not", "is_resource_modified", "(", "environ", ",", "self", ".", "headers", ".", "get", "(", "\"etag\"", ")", ",", ...
[ 116, 4 ]
[ 129, 37 ]
python
en
['en', 'en', 'en']
True
ETagResponseMixin._process_range_request
(self, environ, complete_length=None, accept_ranges=None)
Handle Range Request related headers (RFC7233). If `Accept-Ranges` header is valid, and Range Request is processable, we set the headers as described by the RFC, and wrap the underlying response in a RangeWrapper. Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise....
Handle Range Request related headers (RFC7233). If `Accept-Ranges` header is valid, and Range Request is processable, we set the headers as described by the RFC, and wrap the underlying response in a RangeWrapper.
def _process_range_request(self, environ, complete_length=None, accept_ranges=None): """Handle Range Request related headers (RFC7233). If `Accept-Ranges` header is valid, and Range Request is processable, we set the headers as described by the RFC, and wrap the underlying response in a ...
[ "def", "_process_range_request", "(", "self", ",", "environ", ",", "complete_length", "=", "None", ",", "accept_ranges", "=", "None", ")", ":", "from", ".", ".", "exceptions", "import", "RequestedRangeNotSatisfiable", "if", "accept_ranges", "is", "None", ":", "r...
[ 131, 4 ]
[ 165, 20 ]
python
en
['en', 'en', 'en']
True
ETagResponseMixin.make_conditional
( self, request_or_environ, accept_ranges=False, complete_length=None )
Make the response conditional to the request. This method works best if an etag was defined for the response already. The `add_etag` method can be used to do that. If called without etag just the date header is set. This does nothing if the request method in the request or environ is...
Make the response conditional to the request. This method works best if an etag was defined for the response already. The `add_etag` method can be used to do that. If called without etag just the date header is set.
def make_conditional( self, request_or_environ, accept_ranges=False, complete_length=None ): """Make the response conditional to the request. This method works best if an etag was defined for the response already. The `add_etag` method can be used to do that. If called without eta...
[ "def", "make_conditional", "(", "self", ",", "request_or_environ", ",", "accept_ranges", "=", "False", ",", "complete_length", "=", "None", ")", ":", "environ", "=", "_get_environ", "(", "request_or_environ", ")", "if", "environ", "[", "\"REQUEST_METHOD\"", "]", ...
[ 167, 4 ]
[ 233, 19 ]
python
en
['en', 'en', 'en']
True
ETagResponseMixin.add_etag
(self, overwrite=False, weak=False)
Add an etag for the current response if there is none yet.
Add an etag for the current response if there is none yet.
def add_etag(self, overwrite=False, weak=False): """Add an etag for the current response if there is none yet.""" if overwrite or "etag" not in self.headers: self.set_etag(generate_etag(self.get_data()), weak)
[ "def", "add_etag", "(", "self", ",", "overwrite", "=", "False", ",", "weak", "=", "False", ")", ":", "if", "overwrite", "or", "\"etag\"", "not", "in", "self", ".", "headers", ":", "self", ".", "set_etag", "(", "generate_etag", "(", "self", ".", "get_da...
[ 235, 4 ]
[ 238, 63 ]
python
en
['en', 'en', 'en']
True
ETagResponseMixin.set_etag
(self, etag, weak=False)
Set the etag, and override the old one if there was one.
Set the etag, and override the old one if there was one.
def set_etag(self, etag, weak=False): """Set the etag, and override the old one if there was one.""" self.headers["ETag"] = quote_etag(etag, weak)
[ "def", "set_etag", "(", "self", ",", "etag", ",", "weak", "=", "False", ")", ":", "self", ".", "headers", "[", "\"ETag\"", "]", "=", "quote_etag", "(", "etag", ",", "weak", ")" ]
[ 240, 4 ]
[ 242, 53 ]
python
en
['en', 'en', 'en']
True
ETagResponseMixin.get_etag
(self)
Return a tuple in the form ``(etag, is_weak)``. If there is no ETag the return value is ``(None, None)``.
Return a tuple in the form ``(etag, is_weak)``. If there is no ETag the return value is ``(None, None)``.
def get_etag(self): """Return a tuple in the form ``(etag, is_weak)``. If there is no ETag the return value is ``(None, None)``. """ return unquote_etag(self.headers.get("ETag"))
[ "def", "get_etag", "(", "self", ")", ":", "return", "unquote_etag", "(", "self", ".", "headers", ".", "get", "(", "\"ETag\"", ")", ")" ]
[ 244, 4 ]
[ 248, 53 ]
python
en
['en', 'en', 'en']
True
ETagResponseMixin.freeze
(self, no_etag=False)
Call this method if you want to make your response object ready for pickeling. This buffers the generator if there is one. This also sets the etag unless `no_etag` is set to `True`.
Call this method if you want to make your response object ready for pickeling. This buffers the generator if there is one. This also sets the etag unless `no_etag` is set to `True`.
def freeze(self, no_etag=False): """Call this method if you want to make your response object ready for pickeling. This buffers the generator if there is one. This also sets the etag unless `no_etag` is set to `True`. """ if not no_etag: self.add_etag() supe...
[ "def", "freeze", "(", "self", ",", "no_etag", "=", "False", ")", ":", "if", "not", "no_etag", ":", "self", ".", "add_etag", "(", ")", "super", "(", "ETagResponseMixin", ",", "self", ")", ".", "freeze", "(", ")" ]
[ 250, 4 ]
[ 257, 47 ]
python
en
['en', 'en', 'en']
True
extract_from_ast
(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True)
Extract localizable strings from the given template node. Per default this function returns matches in babel style that means non string parameters as well as keyword arguments are returned as `None`. This allows Babel to figure out what you really meant if you are using gettext functions that allow k...
Extract localizable strings from the given template node. Per default this function returns matches in babel style that means non string parameters as well as keyword arguments are returned as `None`. This allows Babel to figure out what you really meant if you are using gettext functions that allow k...
def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True): """Extract localizable strings from the given template node. Per default this function returns matches in babel style that means non string parameters as well as keyword arguments are returned as `None`....
[ "def", "extract_from_ast", "(", "node", ",", "gettext_functions", "=", "GETTEXT_FUNCTIONS", ",", "babel_style", "=", "True", ")", ":", "for", "node", "in", "node", ".", "find_all", "(", "nodes", ".", "Call", ")", ":", "if", "not", "isinstance", "(", "node"...
[ 436, 0 ]
[ 501, 50 ]
python
en
['en', 'en', 'en']
True
babel_extract
(fileobj, keywords, comment_tags, options)
Babel extraction method for Jinja templates. .. versionchanged:: 2.3 Basic support for translation comments was added. If `comment_tags` is now set to a list of keywords for extraction, the extractor will try to find the best preceeding comment that begins with one of the keywords. Fo...
Babel extraction method for Jinja templates.
def babel_extract(fileobj, keywords, comment_tags, options): """Babel extraction method for Jinja templates. .. versionchanged:: 2.3 Basic support for translation comments was added. If `comment_tags` is now set to a list of keywords for extraction, the extractor will try to find the best...
[ "def", "babel_extract", "(", "fileobj", ",", "keywords", ",", "comment_tags", ",", "options", ")", ":", "extensions", "=", "set", "(", ")", "for", "extension", "in", "options", ".", "get", "(", "'extensions'", ",", "''", ")", ".", "split", "(", "','", ...
[ 541, 0 ]
[ 618, 65 ]
python
en
['nb', 'en', 'en']
True
Extension.bind
(self, environment)
Create a copy of this extension bound to another environment.
Create a copy of this extension bound to another environment.
def bind(self, environment): """Create a copy of this extension bound to another environment.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.environment = environment return rv
[ "def", "bind", "(", "self", ",", "environment", ")", ":", "rv", "=", "object", ".", "__new__", "(", "self", ".", "__class__", ")", "rv", ".", "__dict__", ".", "update", "(", "self", ".", "__dict__", ")", "rv", ".", "environment", "=", "environment", ...
[ 74, 4 ]
[ 79, 17 ]
python
en
['en', 'en', 'en']
True
Extension.preprocess
(self, source, name, filename=None)
This method is called before the actual lexing and can be used to preprocess the source. The `filename` is optional. The return value must be the preprocessed source.
This method is called before the actual lexing and can be used to preprocess the source. The `filename` is optional. The return value must be the preprocessed source.
def preprocess(self, source, name, filename=None): """This method is called before the actual lexing and can be used to preprocess the source. The `filename` is optional. The return value must be the preprocessed source. """ return source
[ "def", "preprocess", "(", "self", ",", "source", ",", "name", ",", "filename", "=", "None", ")", ":", "return", "source" ]
[ 81, 4 ]
[ 86, 21 ]
python
en
['en', 'en', 'en']
True
Extension.filter_stream
(self, stream)
It's passed a :class:`~jinja2.lexer.TokenStream` that can be used to filter tokens returned. This method has to return an iterable of :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a :class:`~jinja2.lexer.TokenStream`. In the `ext` folder of the Jinja2 source distributi...
It's passed a :class:`~jinja2.lexer.TokenStream` that can be used to filter tokens returned. This method has to return an iterable of :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a :class:`~jinja2.lexer.TokenStream`.
def filter_stream(self, stream): """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used to filter tokens returned. This method has to return an iterable of :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a :class:`~jinja2.lexer.TokenStream`. In the ...
[ "def", "filter_stream", "(", "self", ",", "stream", ")", ":", "return", "stream" ]
[ 88, 4 ]
[ 98, 21 ]
python
en
['en', 'en', 'en']
True
Extension.parse
(self, parser)
If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes.
If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes.
def parse(self, parser): """If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes. """ raise NotImp...
[ "def", "parse", "(", "self", ",", "parser", ")", ":", "raise", "NotImplementedError", "(", ")" ]
[ 100, 4 ]
[ 106, 35 ]
python
en
['en', 'en', 'en']
True
Extension.attr
(self, name, lineno=None)
Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno)
Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code.
def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) """ return nodes.ExtensionAttribute(self.identifier, na...
[ "def", "attr", "(", "self", ",", "name", ",", "lineno", "=", "None", ")", ":", "return", "nodes", ".", "ExtensionAttribute", "(", "self", ".", "identifier", ",", "name", ",", "lineno", "=", "lineno", ")" ]
[ 108, 4 ]
[ 116, 77 ]
python
en
['en', 'en', 'en']
True
Extension.call_method
(self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None)
Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`.
Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`.
def call_method(self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None): """Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`. """ if args is None: args = [] if kwargs is None...
[ "def", "call_method", "(", "self", ",", "name", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "dyn_args", "=", "None", ",", "dyn_kwargs", "=", "None", ",", "lineno", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", ...
[ 118, 4 ]
[ 128, 62 ]
python
en
['en', 'en', 'en']
True
InternationalizationExtension.parse
(self, parser)
Parse a translatable tag.
Parse a translatable tag.
def parse(self, parser): """Parse a translatable tag.""" lineno = next(parser.stream).lineno num_called_num = False # find all the variables referenced. Additionally a variable can be # defined in the body of the trans block too, but this is checked at # a later state. ...
[ "def", "parse", "(", "self", ",", "parser", ")", ":", "lineno", "=", "next", "(", "parser", ".", "stream", ")", ".", "lineno", "num_called_num", "=", "False", "# find all the variables referenced. Additionally a variable can be", "# defined in the body of the trans block...
[ 216, 4 ]
[ 319, 23 ]
python
en
['en', 'en', 'it']
True
InternationalizationExtension._parse_block
(self, parser, allow_pluralize)
Parse until the next block tag with a given name.
Parse until the next block tag with a given name.
def _parse_block(self, parser, allow_pluralize): """Parse until the next block tag with a given name.""" referenced = [] buf = [] while 1: if parser.stream.current.type == 'data': buf.append(parser.stream.current.value.replace('%', '%%')) next(...
[ "def", "_parse_block", "(", "self", ",", "parser", ",", "allow_pluralize", ")", ":", "referenced", "=", "[", "]", "buf", "=", "[", "]", "while", "1", ":", "if", "parser", ".", "stream", ".", "current", ".", "type", "==", "'data'", ":", "buf", ".", ...
[ 324, 4 ]
[ 354, 38 ]
python
en
['en', 'en', 'en']
True
InternationalizationExtension._make_node
(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num)
Generates a useful node from the data provided.
Generates a useful node from the data provided.
def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num): """Generates a useful node from the data provided.""" # no variables referenced? no need to escape for old style # gettext invocations only if there are vars. if not vars_...
[ "def", "_make_node", "(", "self", ",", "singular", ",", "plural", ",", "variables", ",", "plural_expr", ",", "vars_referenced", ",", "num_called_num", ")", ":", "# no variables referenced? no need to escape for old style", "# gettext invocations only if there are vars.", "if...
[ 356, 4 ]
[ 402, 35 ]
python
en
['en', 'en', 'en']
True
hello_monkey
()
Respond and greet the caller by name.
Respond and greet the caller by name.
def hello_monkey(): """Respond and greet the caller by name.""" # Try adding your own number to this list! callers = { "+14158675308": "Curious George", "+12349013030": "Boots", "+12348134522": "Virgil", } from_number = request.values.get('From', None) message = callers[f...
[ "def", "hello_monkey", "(", ")", ":", "# Try adding your own number to this list!", "callers", "=", "{", "\"+14158675308\"", ":", "\"Curious George\"", ",", "\"+12349013030\"", ":", "\"Boots\"", ",", "\"+12348134522\"", ":", "\"Virgil\"", ",", "}", "from_number", "=", ...
[ 8, 0 ]
[ 22, 20 ]
python
en
['en', 'en', 'en']
True
bdist_wininst.reinitialize_command
(self, command, reinit_subcommands=0)
Supplement reinitialize_command to work around http://bugs.python.org/issue20819
Supplement reinitialize_command to work around http://bugs.python.org/issue20819
def reinitialize_command(self, command, reinit_subcommands=0): """ Supplement reinitialize_command to work around http://bugs.python.org/issue20819 """ cmd = self.distribution.reinitialize_command( command, reinit_subcommands) if command in ('install', 'instal...
[ "def", "reinitialize_command", "(", "self", ",", "command", ",", "reinit_subcommands", "=", "0", ")", ":", "cmd", "=", "self", ".", "distribution", ".", "reinitialize_command", "(", "command", ",", "reinit_subcommands", ")", "if", "command", "in", "(", "'insta...
[ 4, 4 ]
[ 13, 18 ]
python
en
['en', 'error', 'th']
False
find_best_app
(module)
Given a module instance this tries to find the best possible application in the module or raises an exception.
Given a module instance this tries to find the best possible application in the module or raises an exception.
def find_best_app(module): """Given a module instance this tries to find the best possible application in the module or raises an exception. """ from . import Flask # Search for the most common names first. for attr_name in 'app', 'application': app = getattr(module, attr_name, None) ...
[ "def", "find_best_app", "(", "module", ")", ":", "from", ".", "import", "Flask", "# Search for the most common names first.", "for", "attr_name", "in", "'app'", ",", "'application'", ":", "app", "=", "getattr", "(", "module", ",", "attr_name", ",", "None", ")", ...
[ 26, 0 ]
[ 47, 71 ]
python
en
['en', 'en', 'en']
True
prepare_exec_for_file
(filename)
Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected.
Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected.
def prepare_exec_for_file(filename): """Given a filename this will try to calculate the python path, add it to the search path and return the actual module name that is expected. """ module = [] # Chop off file extensions or package markers if os.path.split(filename)[1] == '__init__.py': ...
[ "def", "prepare_exec_for_file", "(", "filename", ")", ":", "module", "=", "[", "]", "# Chop off file extensions or package markers", "if", "os", ".", "path", ".", "split", "(", "filename", ")", "[", "1", "]", "==", "'__init__.py'", ":", "filename", "=", "os", ...
[ 50, 0 ]
[ 76, 33 ]
python
en
['en', 'en', 'en']
True
locate_app
(app_id)
Attempts to locate the application.
Attempts to locate the application.
def locate_app(app_id): """Attempts to locate the application.""" __traceback_hide__ = True if ':' in app_id: module, app_obj = app_id.split(':', 1) else: module = app_id app_obj = None try: __import__(module) except ImportError: # Reraise the ImportError...
[ "def", "locate_app", "(", "app_id", ")", ":", "__traceback_hide__", "=", "True", "if", "':'", "in", "app_id", ":", "module", ",", "app_obj", "=", "app_id", ".", "split", "(", "':'", ",", "1", ")", "else", ":", "module", "=", "app_id", "app_obj", "=", ...
[ 79, 0 ]
[ 110, 14 ]
python
en
['en', 'en', 'en']
True
with_appcontext
(f)
Wraps a callback so that it's guaranteed to be executed with the script's application context. If callbacks are registered directly to the ``app.cli`` object then they are wrapped with this function by default unless it's disabled.
Wraps a callback so that it's guaranteed to be executed with the script's application context. If callbacks are registered directly to the ``app.cli`` object then they are wrapped with this function by default unless it's disabled.
def with_appcontext(f): """Wraps a callback so that it's guaranteed to be executed with the script's application context. If callbacks are registered directly to the ``app.cli`` object then they are wrapped with this function by default unless it's disabled. """ @click.pass_context def deco...
[ "def", "with_appcontext", "(", "f", ")", ":", "@", "click", ".", "pass_context", "def", "decorator", "(", "__ctx", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "__ctx", ".", "ensure_object", "(", "ScriptInfo", ")", ".", "load_app", "(",...
[ 247, 0 ]
[ 257, 39 ]
python
en
['en', 'en', 'en']
True
run_command
(info, host, port, reload, debugger, eager_loading, with_threads)
Runs a local development server for the Flask application. This local server is recommended for development purposes only but it can also be used for simple intranet deployments. By default it will not support any sort of concurrency at all to simplify debugging. This can be changed with the --with-t...
Runs a local development server for the Flask application.
def run_command(info, host, port, reload, debugger, eager_loading, with_threads): """Runs a local development server for the Flask application. This local server is recommended for development purposes only but it can also be used for simple intranet deployments. By default it will not...
[ "def", "run_command", "(", "info", ",", "host", ",", "port", ",", "reload", ",", "debugger", ",", "eager_loading", ",", "with_threads", ")", ":", "from", "werkzeug", ".", "serving", "import", "run_simple", "debug", "=", "get_debug_flag", "(", ")", "if", "r...
[ 399, 0 ]
[ 437, 60 ]
python
en
['en', 'en', 'en']
True
shell_command
()
Runs an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to it's configuration. This is useful for executing small snippets of management code without having to manually configuring the application.
Runs an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to it's configuration.
def shell_command(): """Runs an interactive Python shell in the context of a given Flask application. The application will populate the default namespace of this shell according to it's configuration. This is useful for executing small snippets of management code without having to manually configu...
[ "def", "shell_command", "(", ")", ":", "import", "code", "from", "flask", ".", "globals", "import", "_app_ctx_stack", "app", "=", "_app_ctx_stack", ".", "top", ".", "app", "banner", "=", "'Python %s on %s\\nApp: %s%s\\nInstance: %s'", "%", "(", "sys", ".", "vers...
[ 442, 0 ]
[ 471, 43 ]
python
en
['en', 'en', 'en']
True
ScriptInfo.load_app
(self)
Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned.
Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned.
def load_app(self): """Loads the Flask app (if not yet loaded) and returns it. Calling this multiple times will just result in the already loaded app to be returned. """ __traceback_hide__ = True if self._loaded_app is not None: return self._loaded_app ...
[ "def", "load_app", "(", "self", ")", ":", "__traceback_hide__", "=", "True", "if", "self", ".", "_loaded_app", "is", "not", "None", ":", "return", "self", ".", "_loaded_app", "if", "self", ".", "create_app", "is", "not", "None", ":", "rv", "=", "self", ...
[ 219, 4 ]
[ 241, 17 ]
python
en
['en', 'en', 'en']
True
AppGroup.command
(self, *args, **kwargs)
This works exactly like the method of the same name on a regular :class:`click.Group` but it wraps callbacks in :func:`with_appcontext` unless it's disabled by passing ``with_appcontext=False``.
This works exactly like the method of the same name on a regular :class:`click.Group` but it wraps callbacks in :func:`with_appcontext` unless it's disabled by passing ``with_appcontext=False``.
def command(self, *args, **kwargs): """This works exactly like the method of the same name on a regular :class:`click.Group` but it wraps callbacks in :func:`with_appcontext` unless it's disabled by passing ``with_appcontext=False``. """ wrap_for_ctx = kwargs.pop('with_appcontext...
[ "def", "command", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "wrap_for_ctx", "=", "kwargs", ".", "pop", "(", "'with_appcontext'", ",", "True", ")", "def", "decorator", "(", "f", ")", ":", "if", "wrap_for_ctx", ":", "f", "=", ...
[ 268, 4 ]
[ 278, 24 ]
python
en
['en', 'en', 'en']
True
AppGroup.group
(self, *args, **kwargs)
This works exactly like the method of the same name on a regular :class:`click.Group` but it defaults the group class to :class:`AppGroup`.
This works exactly like the method of the same name on a regular :class:`click.Group` but it defaults the group class to :class:`AppGroup`.
def group(self, *args, **kwargs): """This works exactly like the method of the same name on a regular :class:`click.Group` but it defaults the group class to :class:`AppGroup`. """ kwargs.setdefault('cls', AppGroup) return click.Group.group(self, *args, **kwargs)
[ "def", "group", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'cls'", ",", "AppGroup", ")", "return", "click", ".", "Group", ".", "group", "(", "self", ",", "*", "args", ",", "*", "*", "kwarg...
[ 280, 4 ]
[ 286, 55 ]
python
en
['en', 'en', 'en']
True
make_breseq_folder
(folder: Path)
Mocks a breseq run for a single sample. .folder |---- output/ |----|---- index.html |---- data/ |----|---- output.vcf
Mocks a breseq run for a single sample. .folder |---- output/ |----|---- index.html |---- data/ |----|---- output.vcf
def make_breseq_folder(folder: Path) -> Dict[str, Path]: """ Mocks a breseq run for a single sample. .folder |---- output/ |----|---- index.html |---- data/ |----|---- output.vcf """ folder = checkdir(folder) folder_output = checkdir(folder / "output") folder_data = checkdir(folder / "data") folder_evidence...
[ "def", "make_breseq_folder", "(", "folder", ":", "Path", ")", "->", "Dict", "[", "str", ",", "Path", "]", ":", "folder", "=", "checkdir", "(", "folder", ")", "folder_output", "=", "checkdir", "(", "folder", "/", "\"output\"", ")", "folder_data", "=", "ch...
[ 31, 0 ]
[ 57, 14 ]
python
en
['en', 'error', 'th']
False
structure1
(tmp_path)
.parent |---- CeN0L1G5/ |----|---- data/ |----|---- output/ |---- CeN0L1G3/ |----|---- data/ |----|---- output/ |---- CeN0L1G29/ |----|---- data/ |----|---- output/
.parent |---- CeN0L1G5/ |----|---- data/ |----|---- output/ |---- CeN0L1G3/ |----|---- data/ |----|---- output/ |---- CeN0L1G29/ |----|---- data/ |----|---- output/
def structure1(tmp_path) -> BreseqFolder: """ .parent |---- CeN0L1G5/ |----|---- data/ |----|---- output/ |---- CeN0L1G3/ |----|---- data/ |----|---- output/ |---- CeN0L1G29/ |----|---- data/ |----|---- output/ """ parent_folder = checkdir(tmp_path / "cefepime") filenames_sample_1 = make_breseq_folder(p...
[ "def", "structure1", "(", "tmp_path", ")", "->", "BreseqFolder", ":", "parent_folder", "=", "checkdir", "(", "tmp_path", "/", "\"cefepime\"", ")", "filenames_sample_1", "=", "make_breseq_folder", "(", "parent_folder", "/", "\"CeN0L1G5\"", ")", "filenames_sample_2", ...
[ 61, 0 ]
[ 92, 14 ]
python
en
['en', 'error', 'th']
False
structure2
(tmp_path)
.parent |---- sample1/ |----|---- breseq |---- sample2/ |----|---- breseq |---- sample3/ |----|---- breseq
.parent |---- sample1/ |----|---- breseq |---- sample2/ |----|---- breseq |---- sample3/ |----|---- breseq
def structure2(tmp_path) -> BreseqFolder: """ .parent |---- sample1/ |----|---- breseq |---- sample2/ |----|---- breseq |---- sample3/ |----|---- breseq """ parent_folder = checkdir(tmp_path / "cefepime") folder_1 = checkdir(parent_folder / "CeN0L1G5") folder_2 = checkdir(parent_folder / "CeN0L1G3") folde...
[ "def", "structure2", "(", "tmp_path", ")", "->", "BreseqFolder", ":", "parent_folder", "=", "checkdir", "(", "tmp_path", "/", "\"cefepime\"", ")", "folder_1", "=", "checkdir", "(", "parent_folder", "/", "\"CeN0L1G5\"", ")", "folder_2", "=", "checkdir", "(", "p...
[ 96, 0 ]
[ 125, 14 ]
python
en
['en', 'error', 'th']
False
upload_docs._build_multipart
(cls, data)
Build up the MIME payload for the POST data
Build up the MIME payload for the POST data
def _build_multipart(cls, data): """ Build up the MIME payload for the POST data """ boundary = b'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254' sep_boundary = b'\n--' + boundary end_boundary = sep_boundary + b'--' end_items = end_boundary, b"\n", bu...
[ "def", "_build_multipart", "(", "cls", ",", "data", ")", ":", "boundary", "=", "b'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'", "sep_boundary", "=", "b'\\n--'", "+", "boundary", "end_boundary", "=", "sep_boundary", "+", "b'--'", "end_items", "=", "end_boundary"...
[ 125, 4 ]
[ 141, 49 ]
python
en
['en', 'error', 'th']
False
do_block
(parser, token)
Define a block that can be overridden by child templates.
Define a block that can be overridden by child templates.
def do_block(parser, token): """ Define a block that can be overridden by child templates. """ # token.split_contents() isn't useful here because this tag doesn't accept variable as arguments bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'%s' tag takes only ...
[ "def", "do_block", "(", "parser", ",", "token", ")", ":", "# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments", "bits", "=", "token", ".", "contents", ".", "split", "(", ")", "if", "len", "(", "bits", ")", "!=", "2", ":"...
[ 198, 0 ]
[ 223, 42 ]
python
en
['en', 'error', 'th']
False
construct_relative_path
(current_template_name, relative_name)
Convert a relative path (starting with './' or '../') to the full template name based on the current_template_name.
Convert a relative path (starting with './' or '../') to the full template name based on the current_template_name.
def construct_relative_path(current_template_name, relative_name): """ Convert a relative path (starting with './' or '../') to the full template name based on the current_template_name. """ has_quotes = ( (relative_name.startswith('"') and relative_name.endswith('"')) or (relative_n...
[ "def", "construct_relative_path", "(", "current_template_name", ",", "relative_name", ")", ":", "has_quotes", "=", "(", "(", "relative_name", ".", "startswith", "(", "'\"'", ")", "and", "relative_name", ".", "endswith", "(", "'\"'", ")", ")", "or", "(", "relat...
[ 226, 0 ]
[ 258, 54 ]
python
en
['en', 'error', 'th']
False
do_extends
(parser, token)
Signal that this template extends a parent template. This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses the literal value "base" as the name of the parent template to extend, or ``{% extends variable %}`` uses the value of ``variable`` as either the name of the parent te...
Signal that this template extends a parent template.
def do_extends(parser, token): """ Signal that this template extends a parent template. This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses the literal value "base" as the name of the parent template to extend, or ``{% extends variable %}`` uses the value of ``variable`` a...
[ "def", "do_extends", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "!=", "2", ":", "raise", "TemplateSyntaxError", "(", "\"'%s' takes one argument\"", "%", "bits", "[", "0", "...
[ 262, 0 ]
[ 280, 45 ]
python
en
['en', 'error', 'th']
False
do_include
(parser, token)
Load a template and render it with the current context. You can pass additional context using keyword arguments. Example:: {% include "foo/some_include" %} {% include "foo/some_include" with bar="BAZZ!" baz="BING!" %} Use the ``only`` argument to exclude the current context when rend...
Load a template and render it with the current context. You can pass additional context using keyword arguments.
def do_include(parser, token): """ Load a template and render it with the current context. You can pass additional context using keyword arguments. Example:: {% include "foo/some_include" %} {% include "foo/some_include" with bar="BAZZ!" baz="BING!" %} Use the ``only`` argument to...
[ "def", "do_include", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "<", "2", ":", "raise", "TemplateSyntaxError", "(", "\"%r tag takes at least one argument: the name of the template to...
[ 284, 0 ]
[ 328, 57 ]
python
en
['en', 'error', 'th']
False
ExtendsNode.find_template
(self, template_name, context)
This is a wrapper around engine.find_template(). A history is kept in the render_context attribute between successive extends calls and passed as the skip argument. This enables extends to work recursively without extending the same template twice.
This is a wrapper around engine.find_template(). A history is kept in the render_context attribute between successive extends calls and passed as the skip argument. This enables extends to work recursively without extending the same template twice.
def find_template(self, template_name, context): """ This is a wrapper around engine.find_template(). A history is kept in the render_context attribute between successive extends calls and passed as the skip argument. This enables extends to work recursively without extending the...
[ "def", "find_template", "(", "self", ",", "template_name", ",", "context", ")", ":", "history", "=", "context", ".", "render_context", ".", "setdefault", "(", "self", ".", "context_key", ",", "[", "self", ".", "origin", "]", ",", ")", "template", ",", "o...
[ 92, 4 ]
[ 106, 23 ]
python
en
['en', 'error', 'th']
False
IncludeNode.render
(self, context)
Render the specified template and context. Cache the template object in render_context to avoid reparsing and loading when used in a for loop.
Render the specified template and context. Cache the template object in render_context to avoid reparsing and loading when used in a for loop.
def render(self, context): """ Render the specified template and context. Cache the template object in render_context to avoid reparsing and loading when used in a for loop. """ template = self.template.resolve(context) # Does this quack like a Template? i...
[ "def", "render", "(", "self", ",", "context", ")", ":", "template", "=", "self", ".", "template", ".", "resolve", "(", "context", ")", "# Does this quack like a Template?", "if", "not", "callable", "(", "getattr", "(", "template", ",", "'render'", ",", "None...
[ 161, 4 ]
[ 194, 43 ]
python
en
['en', 'error', 'th']
False
save_agent
(output_dir, batch_id, model, optimizer, scheduler, keep_last=3)
Store agent to disk.
Store agent to disk.
def save_agent(output_dir, batch_id, model, optimizer, scheduler, keep_last=3): """Store agent to disk.""" fpath = os.path.join(output_dir, 'ckpt.%08d' % (batch_id)) logging.info('Saving: %s', fpath) torch.save( dict(model=model.state_dict(), optim=optimizer.state_dict(), ...
[ "def", "save_agent", "(", "output_dir", ",", "batch_id", ",", "model", ",", "optimizer", ",", "scheduler", ",", "keep_last", "=", "3", ")", ":", "fpath", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'ckpt.%08d'", "%", "(", "batch_id", ...
[ 47, 0 ]
[ 60, 24 ]
python
en
['en', 'en', 'en']
True
convert_to_video_vis
(vid, is_solved=None)
Generate a video visualization to go into tensorboard. Args: vid np.ndarray(BxTxHxW): Video in standard PHYRE style is_solved (int): Whether this video solves the task or not. Returns: vid_vis (BxTxHxWx3)
Generate a video visualization to go into tensorboard. Args: vid np.ndarray(BxTxHxW): Video in standard PHYRE style is_solved (int): Whether this video solves the task or not. Returns: vid_vis (BxTxHxWx3)
def convert_to_video_vis(vid, is_solved=None): """ Generate a video visualization to go into tensorboard. Args: vid np.ndarray(BxTxHxW): Video in standard PHYRE style is_solved (int): Whether this video solves the task or not. Returns: vid_vis (BxTxHxWx3) """ return np.st...
[ "def", "convert_to_video_vis", "(", "vid", ",", "is_solved", "=", "None", ")", ":", "return", "np", ".", "stack", "(", "[", "# The is_solved argument adds a little bar to the top for visualization", "# green if solved, red if not.", "np", ".", "stack", "(", "[", "phyre"...
[ 63, 0 ]
[ 79, 6 ]
python
en
['en', 'error', 'th']
False
get_num_workers
(num_workers, frames_per_clip)
Finetunes the nworkers if batch size/frames per clip too large, since otherwise jobs crash.
Finetunes the nworkers if batch size/frames per clip too large, since otherwise jobs crash.
def get_num_workers(num_workers, frames_per_clip): """Finetunes the nworkers if batch size/frames per clip too large, since otherwise jobs crash.""" del frames_per_clip return num_workers
[ "def", "get_num_workers", "(", "num_workers", ",", "frames_per_clip", ")", ":", "del", "frames_per_clip", "return", "num_workers" ]
[ 82, 0 ]
[ 86, 22 ]
python
en
['en', 'en', 'en']
True
gen_vis_vid_preds
(orig_vid, model, n_fwd_times=None, run_decode=True, n_hist_frames=3)
Generate a visualization of some training videos, along with model rollout (actual autoregressive rollout, so need to test again). Args: orig_vid: (B, T, Nobj, H, W) video batch model: the pytorch model for forward prediction Returns: RGB frames (B, T, 3, H, W) as torch tensor, ...
Generate a visualization of some training videos, along with model rollout (actual autoregressive rollout, so need to test again). Args: orig_vid: (B, T, Nobj, H, W) video batch model: the pytorch model for forward prediction Returns: RGB frames (B, T, 3, H, W) as torch tensor, ...
def gen_vis_vid_preds(orig_vid, model, n_fwd_times=None, run_decode=True, n_hist_frames=3): """ Generate a visualization of some training videos, along with model rollout (actual autoregressive rollout, so need to test a...
[ "def", "gen_vis_vid_preds", "(", "orig_vid", ",", "model", ",", "n_fwd_times", "=", "None", ",", "run_decode", "=", "True", ",", "n_hist_frames", "=", "3", ")", ":", "# Generate the predictions", "if", "n_fwd_times", "is", "None", ":", "n_fwd_times", "=", "ori...
[ 89, 0 ]
[ 128, 39 ]
python
en
['en', 'error', 'th']
False
phyre_batchvidresize
(t, shape)
Args: t: Input video tensor batch, Long dtype, BxTxHxW shape: Output shape required, (H', W')
Args: t: Input video tensor batch, Long dtype, BxTxHxW shape: Output shape required, (H', W')
def phyre_batchvidresize(t, shape): """ Args: t: Input video tensor batch, Long dtype, BxTxHxW shape: Output shape required, (H', W') """ return nn.functional.interpolate(t.to(torch.float), size=list(shape), mode='...
[ "def", "phyre_batchvidresize", "(", "t", ",", "shape", ")", ":", "return", "nn", ".", "functional", ".", "interpolate", "(", "t", ".", "to", "(", "torch", ".", "float", ")", ",", "size", "=", "list", "(", "shape", ")", ",", "mode", "=", "'nearest'", ...
[ 137, 0 ]
[ 145, 67 ]
python
en
['en', 'error', 'th']
False
overlay_pred_scores
(vid, scores, ch=1)
Args: vid (B, 1, H, W): PHYRE style video (torch.Tensor) scores (B,) Scores for each batch element to be overlayed in text on the frame ch: Which channel to overlay on. Returns: vid (B, H, W) with the score overlayed
Args: vid (B, 1, H, W): PHYRE style video (torch.Tensor) scores (B,) Scores for each batch element to be overlayed in text on the frame ch: Which channel to overlay on. Returns: vid (B, H, W) with the score overlayed
def overlay_pred_scores(vid, scores, ch=1): """ Args: vid (B, 1, H, W): PHYRE style video (torch.Tensor) scores (B,) Scores for each batch element to be overlayed in text on the frame ch: Which channel to overlay on. Returns: vid (B, H, W) with the score overlayed...
[ "def", "overlay_pred_scores", "(", "vid", ",", "scores", ",", "ch", "=", "1", ")", ":", "overlays", "=", "[", "]", "for", "batch_id", "in", "range", "(", "vid", ".", "shape", "[", "0", "]", ")", ":", "img", "=", "Image", ".", "new", "(", "'1'", ...
[ 148, 0 ]
[ 166, 14 ]
python
en
['en', 'error', 'th']
False
compute_pixel_accuracy
(gt, pred)
Args: gt torch.Tensor(B, T, H, W) pred torch.Tensor(B, T, H, W) Returns: acc torch.Tensor(B, phyre.NUM_COLORS)
Args: gt torch.Tensor(B, T, H, W) pred torch.Tensor(B, T, H, W) Returns: acc torch.Tensor(B, phyre.NUM_COLORS)
def compute_pixel_accuracy(gt, pred): """ Args: gt torch.Tensor(B, T, H, W) pred torch.Tensor(B, T, H, W) Returns: acc torch.Tensor(B, phyre.NUM_COLORS) """ match = (gt == pred) res = torch.zeros(( gt.shape[0], phyre.NUM_COLORS, )) for col in range...
[ "def", "compute_pixel_accuracy", "(", "gt", ",", "pred", ")", ":", "match", "=", "(", "gt", "==", "pred", ")", "res", "=", "torch", ".", "zeros", "(", "(", "gt", ".", "shape", "[", "0", "]", ",", "phyre", ".", "NUM_COLORS", ",", ")", ")", "for", ...
[ 169, 0 ]
[ 186, 14 ]
python
en
['en', 'error', 'th']
False
store_frames
(frames, task_ids, outdir, subdir, actions)
Args: frames: (B, T, H, W) outdir (path where to store all frames) actions: (B, 3)
Args: frames: (B, T, H, W) outdir (path where to store all frames) actions: (B, 3)
def store_frames(frames, task_ids, outdir, subdir, actions): """ Args: frames: (B, T, H, W) outdir (path where to store all frames) actions: (B, 3) """ assert frames.shape[0] == len(task_ids) assert frames.shape[0] == actions.shape[0] for i, task_id in enumerate(task_ids)...
[ "def", "store_frames", "(", "frames", ",", "task_ids", ",", "outdir", ",", "subdir", ",", "actions", ")", ":", "assert", "frames", ".", "shape", "[", "0", "]", "==", "len", "(", "task_ids", ")", "assert", "frames", ".", "shape", "[", "0", "]", "==", ...
[ 189, 0 ]
[ 216, 31 ]
python
en
['en', 'error', 'th']
False
ImgTrainer.load_agent_from_folder
(cls, model: NeuralModel, agent_folder: str, strict: bool = True)
This loader is used in the offline_agents code, to load at test time.
This loader is used in the offline_agents code, to load at test time.
def load_agent_from_folder(cls, model: NeuralModel, agent_folder: str, strict: bool = True) -> NeuralModel: """ This loader is used in the offline_agents code, to load at test time. """ last_chec...
[ "def", "load_agent_from_folder", "(", "cls", ",", "model", ":", "NeuralModel", ",", "agent_folder", ":", "str", ",", "strict", ":", "bool", "=", "True", ")", "->", "NeuralModel", ":", "last_checkpoint", "=", "get_latest_checkpoint", "(", "agent_folder", ")", "...
[ 221, 4 ]
[ 237, 20 ]
python
en
['en', 'error', 'th']
False
ImgTrainer.gen_model
(cls, cfg)
Generate the random init model.
Generate the random init model.
def gen_model(cls, cfg): """Generate the random init model.""" model = nets.Fwd(agent_cfg=cfg.agent) assert cfg.num_gpus <= torch.cuda.device_count() model = torch.nn.DataParallel(model, device_ids=list(range(cfg.num_gpus))) return model
[ "def", "gen_model", "(", "cls", ",", "cfg", ")", ":", "model", "=", "nets", ".", "Fwd", "(", "agent_cfg", "=", "cfg", ".", "agent", ")", "assert", "cfg", ".", "num_gpus", "<=", "torch", ".", "cuda", ".", "device_count", "(", ")", "model", "=", "tor...
[ 240, 4 ]
[ 246, 20 ]
python
en
['en', 'ms', 'en']
True
ImgTrainer.train
(cls, model, dataset, output_dir, summary_writer, full_eval_from_model, cfg)
Main train function.
Main train function.
def train(cls, model, dataset, output_dir, summary_writer, full_eval_from_model, cfg): """Main train function.""" updates = cfg.train.num_iter report_every = cfg.train.report_every save_checkpoints_every = cfg.train.save_checkpoints_every full_eval_every = cfg.train...
[ "def", "train", "(", "cls", ",", "model", ",", "dataset", ",", "output_dir", ",", "summary_writer", ",", "full_eval_from_model", ",", "cfg", ")", ":", "updates", "=", "cfg", ".", "train", ".", "num_iter", "report_every", "=", "cfg", ".", "train", ".", "r...
[ 249, 4 ]
[ 501, 26 ]
python
en
['en', 'ja', 'en']
True
ImgTrainer.eval_actions
(cls, model, dataset, nactionsXtasks, batch_size, cfg)
Evaluate likelihood of actions solving the task.
Evaluate likelihood of actions solving the task.
def eval_actions(cls, model, dataset, nactionsXtasks, batch_size, cfg): """Evaluate likelihood of actions solving the task.""" init_frames_to_sim = cfg.eval.init_frames_to_sim # Run it for these many n_hist_frames = cfg.eval.n_hist_frames n_fwd_times = cfg.eval.n_fwd_times store...
[ "def", "eval_actions", "(", "cls", ",", "model", ",", "dataset", ",", "nactionsXtasks", ",", "batch_size", ",", "cfg", ")", ":", "init_frames_to_sim", "=", "cfg", ".", "eval", ".", "init_frames_to_sim", "# Run it for these many", "n_hist_frames", "=", "cfg", "."...
[ 504, 4 ]
[ 666, 80 ]
python
en
['en', 'en', 'en']
True
ImgTrainer.vis_stacked_pred_gt
(cls, orig_vid_full, orig_vid, pred_vid_qnt, pred_solved=None, store_path=None)
Args: orig_vid_full: list of videos [T'x256x256] for each batch element in orig_vid, for even the frames that are going to be predicted orig_vid (BxTx256x256) pred_vid_qnt [(BxHxW)] (or None, if not available) (unprocessed; i.e. argmaxed from ...
Args: orig_vid_full: list of videos [T'x256x256] for each batch element in orig_vid, for even the frames that are going to be predicted orig_vid (BxTx256x256) pred_vid_qnt [(BxHxW)] (or None, if not available) (unprocessed; i.e. argmaxed from ...
def vis_stacked_pred_gt(cls, orig_vid_full, orig_vid, pred_vid_qnt, pred_solved=None, store_path=None): """ Args: orig_vid_full: list of videos [T'x256x...
[ "def", "vis_stacked_pred_gt", "(", "cls", ",", "orig_vid_full", ",", "orig_vid", ",", "pred_vid_qnt", ",", "pred_solved", "=", "None", ",", "store_path", "=", "None", ")", ":", "if", "pred_vid_qnt", "is", "None", ":", "return", "(", "orig_vid", ".", "cpu", ...
[ 669, 4 ]
[ 749, 61 ]
python
en
['en', 'error', 'th']
False
retry
(*dargs: t.Any, **dkw: t.Any)
Wrap a function with a new `Retrying` object. :param dargs: positional arguments passed to Retrying object :param dkw: keyword arguments passed to the Retrying object
Wrap a function with a new `Retrying` object.
def retry(*dargs: t.Any, **dkw: t.Any) -> t.Union[WrappedFn, t.Callable[[WrappedFn], WrappedFn]]: # noqa """Wrap a function with a new `Retrying` object. :param dargs: positional arguments passed to Retrying object :param dkw: keyword arguments passed to the Retrying object """ # support both @ret...
[ "def", "retry", "(", "*", "dargs", ":", "t", ".", "Any", ",", "*", "*", "dkw", ":", "t", ".", "Any", ")", "->", "t", ".", "Union", "[", "WrappedFn", ",", "t", ".", "Callable", "[", "[", "WrappedFn", "]", ",", "WrappedFn", "]", "]", ":", "# no...
[ 106, 0 ]
[ 132, 19 ]
python
en
['en', 'en', 'en']
True
BaseRetrying.copy
( self, sleep: t.Union[t.Callable[[t.Union[int, float]], None], object] = _unset, stop: t.Union["stop_base", object] = _unset, wait: t.Union["wait_base", object] = _unset, retry: t.Union[retry_base, object] = _unset, before: t.Union[t.Callable[["RetryCallState"], None], o...
Copy this object with some parameters changed if needed.
Copy this object with some parameters changed if needed.
def copy( self, sleep: t.Union[t.Callable[[t.Union[int, float]], None], object] = _unset, stop: t.Union["stop_base", object] = _unset, wait: t.Union["wait_base", object] = _unset, retry: t.Union[retry_base, object] = _unset, before: t.Union[t.Callable[["RetryCallState"], ...
[ "def", "copy", "(", "self", ",", "sleep", ":", "t", ".", "Union", "[", "t", ".", "Callable", "[", "[", "t", ".", "Union", "[", "int", ",", "float", "]", "]", ",", "None", "]", ",", "object", "]", "=", "_unset", ",", "stop", ":", "t", ".", "...
[ 251, 4 ]
[ 276, 9 ]
python
en
['en', 'en', 'en']
True
BaseRetrying.statistics
(self)
Return a dictionary of runtime statistics. This dictionary will be empty when the controller has never been ran. When it is running or has ran previously it should have (but may not) have useful and/or informational keys and values when running is underway and/or completed. .. ...
Return a dictionary of runtime statistics.
def statistics(self) -> t.Dict[str, t.Any]: """Return a dictionary of runtime statistics. This dictionary will be empty when the controller has never been ran. When it is running or has ran previously it should have (but may not) have useful and/or informational keys and values when ...
[ "def", "statistics", "(", "self", ")", "->", "t", ".", "Dict", "[", "str", ",", "t", ".", "Any", "]", ":", "try", ":", "return", "self", ".", "_local", ".", "statistics", "except", "AttributeError", ":", "self", ".", "_local", ".", "statistics", "=",...
[ 290, 4 ]
[ 315, 41 ]
python
en
['en', 'en', 'en']
True
BaseRetrying.wraps
(self, f: WrappedFn)
Wrap a function for retrying. :param f: A function to wraps for retrying.
Wrap a function for retrying.
def wraps(self, f: WrappedFn) -> WrappedFn: """Wrap a function for retrying. :param f: A function to wraps for retrying. """ @functools.wraps(f) def wrapped_f(*args: t.Any, **kw: t.Any) -> t.Any: return self(f, *args, **kw) def retry_with(*args: t.Any, **kw...
[ "def", "wraps", "(", "self", ",", "f", ":", "WrappedFn", ")", "->", "WrappedFn", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapped_f", "(", "*", "args", ":", "t", ".", "Any", ",", "*", "*", "kw", ":", "t", ".", "Any", ")", "...
[ 317, 4 ]
[ 333, 24 ]
python
en
['en', 'en', 'en']
True
Future.failed
(self)
Return whether a exception is being held in this future.
Return whether a exception is being held in this future.
def failed(self) -> bool: """Return whether a exception is being held in this future.""" return self.exception() is not None
[ "def", "failed", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "exception", "(", ")", "is", "not", "None" ]
[ 428, 4 ]
[ 430, 43 ]
python
en
['en', 'en', 'en']
True
Future.construct
(cls, attempt_number: int, value: t.Any, has_exception: bool)
Construct a new Future object.
Construct a new Future object.
def construct(cls, attempt_number: int, value: t.Any, has_exception: bool) -> "Future": """Construct a new Future object.""" fut = cls(attempt_number) if has_exception: fut.set_exception(value) else: fut.set_result(value) return fut
[ "def", "construct", "(", "cls", ",", "attempt_number", ":", "int", ",", "value", ":", "t", ".", "Any", ",", "has_exception", ":", "bool", ")", "->", "\"Future\"", ":", "fut", "=", "cls", "(", "attempt_number", ")", "if", "has_exception", ":", "fut", "....
[ 433, 4 ]
[ 440, 18 ]
python
en
['en', 'en', 'en']
True
SharedDataMiddleware.is_allowed
(self, filename)
Subclasses can override this method to disallow the access to certain files. However by providing `disallow` in the constructor this method is overwritten.
Subclasses can override this method to disallow the access to certain files. However by providing `disallow` in the constructor this method is overwritten.
def is_allowed(self, filename): """Subclasses can override this method to disallow the access to certain files. However by providing `disallow` in the constructor this method is overwritten. """ return True
[ "def", "is_allowed", "(", "self", ",", "filename", ")", ":", "return", "True" ]
[ 123, 4 ]
[ 128, 19 ]
python
en
['en', 'en', 'en']
True