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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
localtime | (value) |
Convert a datetime to local time in the active time zone.
This only makes sense within a {% localtime off %} block.
|
Convert a datetime to local time in the active time zone. | def localtime(value):
"""
Convert a datetime to local time in the active time zone.
This only makes sense within a {% localtime off %} block.
"""
return do_timezone(value, timezone.get_current_timezone()) | [
"def",
"localtime",
"(",
"value",
")",
":",
"return",
"do_timezone",
"(",
"value",
",",
"timezone",
".",
"get_current_timezone",
"(",
")",
")"
] | [
19,
0
] | [
25,
62
] | python | en | ['en', 'error', 'th'] | False |
utc | (value) |
Convert a datetime to UTC.
|
Convert a datetime to UTC.
| def utc(value):
"""
Convert a datetime to UTC.
"""
return do_timezone(value, timezone.utc) | [
"def",
"utc",
"(",
"value",
")",
":",
"return",
"do_timezone",
"(",
"value",
",",
"timezone",
".",
"utc",
")"
] | [
29,
0
] | [
33,
43
] | python | en | ['en', 'error', 'th'] | False |
do_timezone | (value, arg) |
Convert a datetime to local time in a given time zone.
The argument must be an instance of a tzinfo subclass or a time zone name.
Naive datetimes are assumed to be in local time in the default time zone.
|
Convert a datetime to local time in a given time zone. | def do_timezone(value, arg):
"""
Convert a datetime to local time in a given time zone.
The argument must be an instance of a tzinfo subclass or a time zone name.
Naive datetimes are assumed to be in local time in the default time zone.
"""
if not isinstance(value, datetime):
return ''... | [
"def",
"do_timezone",
"(",
"value",
",",
"arg",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"datetime",
")",
":",
"return",
"''",
"# Obtain a timezone-aware datetime",
"try",
":",
"if",
"timezone",
".",
"is_naive",
"(",
"value",
")",
":",
"defa... | [
37,
0
] | [
77,
17
] | python | en | ['en', 'error', 'th'] | False |
localtime_tag | (parser, token) |
Force or prevent conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
|
Force or prevent conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``. | def localtime_tag(parser, token):
"""
Force or prevent conversion of datetime objects to local time,
regardless of the value of ``settings.USE_TZ``.
Sample usage::
{% localtime off %}{{ value_in_utc }}{% endlocaltime %}
"""
bits = token.split_contents()
if len(bits) == 1:
u... | [
"def",
"localtime_tag",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"==",
"1",
":",
"use_tz",
"=",
"True",
"elif",
"len",
"(",
"bits",
")",
">",
"2",
"or",
"bits",
"... | [
125,
0
] | [
144,
42
] | python | en | ['en', 'error', 'th'] | False |
timezone_tag | (parser, token) |
Enable a given time zone just for this block.
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
time zone name, or ``None``. If it is ``None``, the default time zone is
used within the block.
Sample usage::
{% timezone "Europe/Paris" %}
It is {{ now }}... |
Enable a given time zone just for this block. | def timezone_tag(parser, token):
"""
Enable a given time zone just for this block.
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
time zone name, or ``None``. If it is ``None``, the default time zone is
used within the block.
Sample usage::
{% timezone "Euro... | [
"def",
"timezone_tag",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"!=",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"'%s' takes one argument (timezone)\"",
"%",
"bits",
"[... | [
148,
0
] | [
169,
37
] | python | en | ['en', 'error', 'th'] | False |
get_current_timezone_tag | (parser, token) |
Store the name of the current time zone in the context.
Usage::
{% get_current_timezone as TIME_ZONE %}
This will fetch the currently active time zone and put its name
into the ``TIME_ZONE`` context variable.
|
Store the name of the current time zone in the context. | def get_current_timezone_tag(parser, token):
"""
Store the name of the current time zone in the context.
Usage::
{% get_current_timezone as TIME_ZONE %}
This will fetch the currently active time zone and put its name
into the ``TIME_ZONE`` context variable.
"""
# token.split_conte... | [
"def",
"get_current_timezone_tag",
"(",
"parser",
",",
"token",
")",
":",
"# token.split_contents() isn't useful here because this tag doesn't accept variable as arguments",
"args",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
"len",
"(",
"args",
")",
"!... | [
173,
0
] | [
189,
42
] | python | en | ['en', 'error', 'th'] | False |
openapi_param_value_generator | (
endpoints: List[str],
) | This decorator is used to register OpenAPI param value genarator functions
with endpoints. Example usage:
@openapi_param_value_generator(["/messages/render:post"])
def ...
| This decorator is used to register OpenAPI param value genarator functions
with endpoints. Example usage: | def openapi_param_value_generator(
endpoints: List[str],
) -> Callable[[Callable[[], Dict[str, object]]], Callable[[], Dict[str, object]]]:
"""This decorator is used to register OpenAPI param value genarator functions
with endpoints. Example usage:
@openapi_param_value_generator(["/messages/render:post... | [
"def",
"openapi_param_value_generator",
"(",
"endpoints",
":",
"List",
"[",
"str",
"]",
",",
")",
"->",
"Callable",
"[",
"[",
"Callable",
"[",
"[",
"]",
",",
"Dict",
"[",
"str",
",",
"object",
"]",
"]",
"]",
",",
"Callable",
"[",
"[",
"]",
",",
"Di... | [
32,
0
] | [
54,
18
] | python | en | ['en', 'en', 'en'] | True |
PackageDependencySource.fetch | (self) | Fetch package contents into memory.
Returns:
bytes: Package archive contents.
| Fetch package contents into memory. | def fetch(self) -> bytes:
"""Fetch package contents into memory.
Returns:
bytes: Package archive contents.
"""
self.log.debug(f"fetching package: {self.file_name}")
desc = self.format_desc(self.file_name)
content = utils.stream_download(self.source_url, desc... | [
"def",
"fetch",
"(",
"self",
")",
"->",
"bytes",
":",
"self",
".",
"log",
".",
"debug",
"(",
"f\"fetching package: {self.file_name}\"",
")",
"desc",
"=",
"self",
".",
"format_desc",
"(",
"self",
".",
"file_name",
")",
"content",
"=",
"utils",
".",
"stream_... | [
51,
4
] | [
61,
22
] | python | en | ['en', 'en', 'en'] | True |
PackageDependencySource.__enter__ | (self) | Prepare Pypi package for installation.
Extracts the package into a temporary directory then
generates stubs for type hinting.
This helps with intellisense.
If the dependency is a module, a list
of tuples with the file and stub path, respectively,
will be returned. Other... | Prepare Pypi package for installation. | def __enter__(self) -> Union[Path, List[Tuple[Path, Path]]]:
"""Prepare Pypi package for installation.
Extracts the package into a temporary directory then
generates stubs for type hinting.
This helps with intellisense.
If the dependency is a module, a list
of tuples wi... | [
"def",
"__enter__",
"(",
"self",
")",
"->",
"Union",
"[",
"Path",
",",
"List",
"[",
"Tuple",
"[",
"Path",
",",
"Path",
"]",
"]",
"]",
":",
"self",
".",
"tmp_path",
"=",
"Path",
"(",
"mkdtemp",
"(",
")",
")",
"with",
"self",
".",
"handle_cleanup",
... | [
63,
4
] | [
84,
32
] | python | en | ['en', 'en', 'en'] | True |
VCSDependencySource.fetch | (self, dest_path: Path) | Clones VCS repository to a given directory.
Args:
dest_path: Path to clone directory too.
Returns:
Path to clone repository.
| Clones VCS repository to a given directory. | def fetch(self, dest_path: Path) -> Path:
"""Clones VCS repository to a given directory.
Args:
dest_path: Path to clone directory too.
Returns:
Path to clone repository.
"""
self.log.debug(f"fetching vcs package: ${self.file_name} @ ${self.repo_url}")
... | [
"def",
"fetch",
"(",
"self",
",",
"dest_path",
":",
"Path",
")",
"->",
"Path",
":",
"self",
".",
"log",
".",
"debug",
"(",
"f\"fetching vcs package: ${self.file_name} @ ${self.repo_url}\"",
")",
"self",
".",
"format_desc",
"(",
"self",
".",
"file_name",
")",
"... | [
121,
4
] | [
134,
24
] | python | en | ['en', 'en', 'en'] | True |
VCSDependencySource.__enter__ | (self) | Prepare VCS repository for installation.
See PackageDependencySource.__enter__
Returns:
Root package path or list of files.
| Prepare VCS repository for installation. | def __enter__(self) -> Union[Path, List[Tuple[Path, Path]]]:
"""Prepare VCS repository for installation.
See PackageDependencySource.__enter__
Returns:
Root package path or list of files.
"""
self.tmp_path = Path(mkdtemp())
with self.handle_cleanup():
... | [
"def",
"__enter__",
"(",
"self",
")",
"->",
"Union",
"[",
"Path",
",",
"List",
"[",
"Tuple",
"[",
"Path",
",",
"Path",
"]",
"]",
"]",
":",
"self",
".",
"tmp_path",
"=",
"Path",
"(",
"mkdtemp",
"(",
")",
")",
"with",
"self",
".",
"handle_cleanup",
... | [
136,
4
] | [
150,
32
] | python | en | ['en', 'it', 'en'] | True |
parse_extras | (requirements_path: str) | Parse over the requirements.txt file to find extras requested.
Args:
requirements_path: The filepath for the requirements.txt file to parse.
Returns:
A dictionary mapping the requirement name to a set of extras requested.
| Parse over the requirements.txt file to find extras requested. | def parse_extras(requirements_path: str) -> Dict[str, Set[str]]:
"""Parse over the requirements.txt file to find extras requested.
Args:
requirements_path: The filepath for the requirements.txt file to parse.
Returns:
A dictionary mapping the requirement name to a set of extras requested.... | [
"def",
"parse_extras",
"(",
"requirements_path",
":",
"str",
")",
"->",
"Dict",
"[",
"str",
",",
"Set",
"[",
"str",
"]",
"]",
":",
"extras_requested",
"=",
"{",
"}",
"with",
"open",
"(",
"requirements_path",
",",
"\"r\"",
")",
"as",
"requirements",
":",
... | [
4,
0
] | [
22,
27
] | python | en | ['en', 'en', 'en'] | True |
_parse_requirement_for_extra | (
requirement: str,
) | Given a requirement string, returns the requirement name and set of extras, if extras specified.
Else, returns (None, None)
| Given a requirement string, returns the requirement name and set of extras, if extras specified.
Else, returns (None, None)
| def _parse_requirement_for_extra(
requirement: str,
) -> Tuple[Optional[str], Optional[Set[str]]]:
"""Given a requirement string, returns the requirement name and set of extras, if extras specified.
Else, returns (None, None)
"""
# https://www.python.org/dev/peps/pep-0508/#grammar
extras_patter... | [
"def",
"_parse_requirement_for_extra",
"(",
"requirement",
":",
"str",
",",
")",
"->",
"Tuple",
"[",
"Optional",
"[",
"str",
"]",
",",
"Optional",
"[",
"Set",
"[",
"str",
"]",
"]",
"]",
":",
"# https://www.python.org/dev/peps/pep-0508/#grammar",
"extras_pattern",
... | [
25,
0
] | [
44,
21
] | python | en | ['en', 'en', 'en'] | True |
get_srid_info | (srid, connection) |
Returns the units, unit name, and spheroid WKT associated with the
given SRID from the `spatial_ref_sys` (or equivalent) spatial database
table for the given database connection. These results are cached.
|
Returns the units, unit name, and spheroid WKT associated with the
given SRID from the `spatial_ref_sys` (or equivalent) spatial database
table for the given database connection. These results are cached.
| def get_srid_info(srid, connection):
"""
Returns the units, unit name, and spheroid WKT associated with the
given SRID from the `spatial_ref_sys` (or equivalent) spatial database
table for the given database connection. These results are cached.
"""
global _srid_cache
try:
# The Sp... | [
"def",
"get_srid_info",
"(",
"srid",
",",
"connection",
")",
":",
"global",
"_srid_cache",
"try",
":",
"# The SpatialRefSys model for the spatial backend.",
"SpatialRefSys",
"=",
"connection",
".",
"ops",
".",
"spatial_ref_sys",
"(",
")",
"except",
"NotImplementedError"... | [
15,
0
] | [
41,
46
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.__init__ | (self, verbose_name=None, srid=4326, spatial_index=True, dim=2,
geography=False, **kwargs) |
The initialization function for geometry fields. Takes the following
as keyword arguments:
srid:
The spatial reference system identifier, an OGC standard.
Defaults to 4326 (WGS84).
spatial_index:
Indicates whether to create a spatial index. Defaults to Tru... |
The initialization function for geometry fields. Takes the following
as keyword arguments: | def __init__(self, verbose_name=None, srid=4326, spatial_index=True, dim=2,
geography=False, **kwargs):
"""
The initialization function for geometry fields. Takes the following
as keyword arguments:
srid:
The spatial reference system identifier, an OGC standar... | [
"def",
"__init__",
"(",
"self",
",",
"verbose_name",
"=",
"None",
",",
"srid",
"=",
"4326",
",",
"spatial_index",
"=",
"True",
",",
"dim",
"=",
"2",
",",
"geography",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"# Setting the index flag with the value... | [
56,
4
] | [
106,
53
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.geodetic | (self, connection) |
Returns true if this field's SRID corresponds with a coordinate
system that uses non-projected units (e.g., latitude/longitude).
|
Returns true if this field's SRID corresponds with a coordinate
system that uses non-projected units (e.g., latitude/longitude).
| def geodetic(self, connection):
"""
Returns true if this field's SRID corresponds with a coordinate
system that uses non-projected units (e.g., latitude/longitude).
"""
return self.units_name(connection).lower() in self.geodetic_units | [
"def",
"geodetic",
"(",
"self",
",",
"connection",
")",
":",
"return",
"self",
".",
"units_name",
"(",
"connection",
")",
".",
"lower",
"(",
")",
"in",
"self",
".",
"geodetic_units"
] | [
143,
4
] | [
148,
73
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.get_distance | (self, value, lookup_type, connection) |
Returns a distance number in units of the field. For example, if
`D(km=1)` was passed in and the units of the field were in meters,
then 1000 would be returned.
|
Returns a distance number in units of the field. For example, if
`D(km=1)` was passed in and the units of the field were in meters,
then 1000 would be returned.
| def get_distance(self, value, lookup_type, connection):
"""
Returns a distance number in units of the field. For example, if
`D(km=1)` was passed in and the units of the field were in meters,
then 1000 would be returned.
"""
return connection.ops.get_distance(self, value... | [
"def",
"get_distance",
"(",
"self",
",",
"value",
",",
"lookup_type",
",",
"connection",
")",
":",
"return",
"connection",
".",
"ops",
".",
"get_distance",
"(",
"self",
",",
"value",
",",
"lookup_type",
")"
] | [
150,
4
] | [
156,
68
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.get_prep_value | (self, value) |
Spatial lookup values are either a parameter that is (or may be
converted to) a geometry, or a sequence of lookup values that
begins with a geometry. This routine will setup the geometry
value properly, and preserve any other lookup parameters before
returning to the caller.
... |
Spatial lookup values are either a parameter that is (or may be
converted to) a geometry, or a sequence of lookup values that
begins with a geometry. This routine will setup the geometry
value properly, and preserve any other lookup parameters before
returning to the caller.
... | def get_prep_value(self, value):
"""
Spatial lookup values are either a parameter that is (or may be
converted to) a geometry, or a sequence of lookup values that
begins with a geometry. This routine will setup the geometry
value properly, and preserve any other lookup parameter... | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
"GeometryField",
",",
"self",
")",
".",
"get_prep_value",
"(",
"value",
")",
"if",
"isinstance",
"(",
"value",
",",
"SQLEvaluator",
")",
":",
"return",
"value",
"el... | [
158,
4
] | [
196,
23
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.get_srid | (self, geom) |
Returns the default SRID for the given geometry, taking into account
the SRID set for the field. For example, if the input geometry
has no SRID, then that of the field will be returned.
|
Returns the default SRID for the given geometry, taking into account
the SRID set for the field. For example, if the input geometry
has no SRID, then that of the field will be returned.
| def get_srid(self, geom):
"""
Returns the default SRID for the given geometry, taking into account
the SRID set for the field. For example, if the input geometry
has no SRID, then that of the field will be returned.
"""
gsrid = geom.srid # SRID of given geometry.
... | [
"def",
"get_srid",
"(",
"self",
",",
"geom",
")",
":",
"gsrid",
"=",
"geom",
".",
"srid",
"# SRID of given geometry.",
"if",
"gsrid",
"is",
"None",
"or",
"self",
".",
"srid",
"==",
"-",
"1",
"or",
"(",
"gsrid",
"==",
"-",
"1",
"and",
"self",
".",
"... | [
203,
4
] | [
213,
24
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.get_db_prep_lookup | (self, lookup_type, value, connection, prepared=False) |
Prepare for the database lookup, and return any spatial parameters
necessary for the query. This includes wrapping any geometry
parameters with a backend-specific adapter and formatting any distance
parameters into the correct units for the coordinate system of the
field.
... |
Prepare for the database lookup, and return any spatial parameters
necessary for the query. This includes wrapping any geometry
parameters with a backend-specific adapter and formatting any distance
parameters into the correct units for the coordinate system of the
field.
... | def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
"""
Prepare for the database lookup, and return any spatial parameters
necessary for the query. This includes wrapping any geometry
parameters with a backend-specific adapter and formatting any distance
... | [
"def",
"get_db_prep_lookup",
"(",
"self",
",",
"lookup_type",
",",
"value",
",",
"connection",
",",
"prepared",
"=",
"False",
")",
":",
"# special case for isnull lookup",
"if",
"lookup_type",
"==",
"'isnull'",
":",
"return",
"[",
"]",
"elif",
"lookup_type",
"in... | [
236,
4
] | [
269,
68
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.get_db_prep_save | (self, value, connection) | Prepares the value for saving in the database. | Prepares the value for saving in the database. | def get_db_prep_save(self, value, connection):
"Prepares the value for saving in the database."
if value is None:
return None
else:
return connection.ops.Adapter(self.get_prep_value(value)) | [
"def",
"get_db_prep_save",
"(",
"self",
",",
"value",
",",
"connection",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"connection",
".",
"ops",
".",
"Adapter",
"(",
"self",
".",
"get_prep_value",
"(",
"value",
")",... | [
277,
4
] | [
282,
69
] | python | en | ['en', 'en', 'en'] | True |
GeometryField.get_placeholder | (self, value, connection) |
Returns the placeholder for the geometry column for the
given value.
|
Returns the placeholder for the geometry column for the
given value.
| def get_placeholder(self, value, connection):
"""
Returns the placeholder for the geometry column for the
given value.
"""
return connection.ops.get_geom_placeholder(self, value) | [
"def",
"get_placeholder",
"(",
"self",
",",
"value",
",",
"connection",
")",
":",
"return",
"connection",
".",
"ops",
".",
"get_geom_placeholder",
"(",
"self",
",",
"value",
")"
] | [
284,
4
] | [
289,
63
] | python | en | ['en', 'error', 'th'] | False |
KMLSitemap._build_kml_sources | (self, sources) |
Go through the given sources and return a 3-tuple of the application
label, module name, and field name of every GeometryField encountered
in the sources.
If no sources are provided, then all models.
|
Go through the given sources and return a 3-tuple of the application
label, module name, and field name of every GeometryField encountered
in the sources. | def _build_kml_sources(self, sources):
"""
Go through the given sources and return a 3-tuple of the application
label, module name, and field name of every GeometryField encountered
in the sources.
If no sources are provided, then all models.
"""
kml_sources = []... | [
"def",
"_build_kml_sources",
"(",
"self",
",",
"sources",
")",
":",
"kml_sources",
"=",
"[",
"]",
"if",
"sources",
"is",
"None",
":",
"sources",
"=",
"apps",
".",
"get_models",
"(",
")",
"for",
"source",
"in",
"sources",
":",
"if",
"isinstance",
"(",
"... | [
18,
4
] | [
42,
26
] | python | en | ['en', 'error', 'th'] | False |
KMLSitemap.get_urls | (self, page=1, site=None, protocol=None) |
This method is overridden so the appropriate `geo_format` attribute
is placed on each URL element.
|
This method is overridden so the appropriate `geo_format` attribute
is placed on each URL element.
| def get_urls(self, page=1, site=None, protocol=None):
"""
This method is overridden so the appropriate `geo_format` attribute
is placed on each URL element.
"""
urls = Sitemap.get_urls(self, page=page, site=site, protocol=protocol)
for url in urls:
url['geo_fo... | [
"def",
"get_urls",
"(",
"self",
",",
"page",
"=",
"1",
",",
"site",
"=",
"None",
",",
"protocol",
"=",
"None",
")",
":",
"urls",
"=",
"Sitemap",
".",
"get_urls",
"(",
"self",
",",
"page",
"=",
"page",
",",
"site",
"=",
"site",
",",
"protocol",
"=... | [
44,
4
] | [
52,
19
] | python | en | ['en', 'error', 'th'] | False |
_default_key_normalizer | (key_class, request_context) |
Create a pool key out of a request context dictionary.
According to RFC 3986, both the scheme and host are case-insensitive.
Therefore, this function normalizes both before constructing the pool
key for an HTTPS request. If you wish to change this behaviour, provide
alternate callables to ``key_fn... |
Create a pool key out of a request context dictionary. | def _default_key_normalizer(key_class, request_context):
"""
Create a pool key out of a request context dictionary.
According to RFC 3986, both the scheme and host are case-insensitive.
Therefore, this function normalizes both before constructing the pool
key for an HTTPS request. If you wish to ch... | [
"def",
"_default_key_normalizer",
"(",
"key_class",
",",
"request_context",
")",
":",
"# Since we mutate the dictionary, make a copy first",
"context",
"=",
"request_context",
".",
"copy",
"(",
")",
"context",
"[",
"\"scheme\"",
"]",
"=",
"context",
"[",
"\"scheme\"",
... | [
73,
0
] | [
119,
31
] | python | en | ['en', 'error', 'th'] | False |
PoolManager._new_pool | (self, scheme, host, port, request_context=None) |
Create a new :class:`ConnectionPool` based on host, port, scheme, and
any additional pool keyword arguments.
If ``request_context`` is provided, it is provided as keyword arguments
to the pool class used. This method is used to actually create the
connection pools handed out by... |
Create a new :class:`ConnectionPool` based on host, port, scheme, and
any additional pool keyword arguments. | def _new_pool(self, scheme, host, port, request_context=None):
"""
Create a new :class:`ConnectionPool` based on host, port, scheme, and
any additional pool keyword arguments.
If ``request_context`` is provided, it is provided as keyword arguments
to the pool class used. This me... | [
"def",
"_new_pool",
"(",
"self",
",",
"scheme",
",",
"host",
",",
"port",
",",
"request_context",
"=",
"None",
")",
":",
"pool_cls",
"=",
"self",
".",
"pool_classes_by_scheme",
"[",
"scheme",
"]",
"if",
"request_context",
"is",
"None",
":",
"request_context"... | [
182,
4
] | [
207,
54
] | python | en | ['en', 'error', 'th'] | False |
PoolManager.clear | (self) |
Empty our store of pools and direct them all to close.
This will not affect in-flight connections, but they will not be
re-used after completion.
|
Empty our store of pools and direct them all to close. | def clear(self):
"""
Empty our store of pools and direct them all to close.
This will not affect in-flight connections, but they will not be
re-used after completion.
"""
self.pools.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"pools",
".",
"clear",
"(",
")"
] | [
209,
4
] | [
216,
26
] | python | en | ['en', 'error', 'th'] | False |
PoolManager.connection_from_host | (self, host, port=None, scheme="http", pool_kwargs=None) |
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is
provided, it is merged with the instance's ``connection_pool_kw``
variable a... |
Get a :class:`ConnectionPool` based on the host, port, and scheme. | def connection_from_host(self, host, port=None, scheme="http", pool_kwargs=None):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is... | [
"def",
"connection_from_host",
"(",
"self",
",",
"host",
",",
"port",
"=",
"None",
",",
"scheme",
"=",
"\"http\"",
",",
"pool_kwargs",
"=",
"None",
")",
":",
"if",
"not",
"host",
":",
"raise",
"LocationValueError",
"(",
"\"No host specified.\"",
")",
"reques... | [
218,
4
] | [
239,
60
] | python | en | ['en', 'error', 'th'] | False |
PoolManager.connection_from_context | (self, request_context) |
Get a :class:`ConnectionPool` based on the request context.
``request_context`` must at least contain the ``scheme`` key and its
value must be a key in ``key_fn_by_scheme`` instance variable.
|
Get a :class:`ConnectionPool` based on the request context. | def connection_from_context(self, request_context):
"""
Get a :class:`ConnectionPool` based on the request context.
``request_context`` must at least contain the ``scheme`` key and its
value must be a key in ``key_fn_by_scheme`` instance variable.
"""
scheme = request_co... | [
"def",
"connection_from_context",
"(",
"self",
",",
"request_context",
")",
":",
"scheme",
"=",
"request_context",
"[",
"\"scheme\"",
"]",
".",
"lower",
"(",
")",
"pool_key_constructor",
"=",
"self",
".",
"key_fn_by_scheme",
"[",
"scheme",
"]",
"pool_key",
"=",
... | [
241,
4
] | [
252,
87
] | python | en | ['en', 'error', 'th'] | False |
PoolManager.connection_from_pool_key | (self, pool_key, request_context=None) |
Get a :class:`ConnectionPool` based on the provided pool key.
``pool_key`` should be a namedtuple that only contains immutable
objects. At a minimum it must have the ``scheme``, ``host``, and
``port`` fields.
|
Get a :class:`ConnectionPool` based on the provided pool key. | def connection_from_pool_key(self, pool_key, request_context=None):
"""
Get a :class:`ConnectionPool` based on the provided pool key.
``pool_key`` should be a namedtuple that only contains immutable
objects. At a minimum it must have the ``scheme``, ``host``, and
``port`` fields... | [
"def",
"connection_from_pool_key",
"(",
"self",
",",
"pool_key",
",",
"request_context",
"=",
"None",
")",
":",
"with",
"self",
".",
"pools",
".",
"lock",
":",
"# If the scheme, host, or port doesn't match existing open",
"# connections, open a new ConnectionPool.",
"pool",... | [
254,
4
] | [
276,
19
] | python | en | ['en', 'error', 'th'] | False |
PoolManager.connection_from_url | (self, url, pool_kwargs=None) |
Similar to :func:`urllib3.connectionpool.connection_from_url`.
If ``pool_kwargs`` is not provided and a new pool needs to be
constructed, ``self.connection_pool_kw`` is used to initialize
the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``
is provided, it is ... |
Similar to :func:`urllib3.connectionpool.connection_from_url`. | def connection_from_url(self, url, pool_kwargs=None):
"""
Similar to :func:`urllib3.connectionpool.connection_from_url`.
If ``pool_kwargs`` is not provided and a new pool needs to be
constructed, ``self.connection_pool_kw`` is used to initialize
the :class:`urllib3.connectionpoo... | [
"def",
"connection_from_url",
"(",
"self",
",",
"url",
",",
"pool_kwargs",
"=",
"None",
")",
":",
"u",
"=",
"parse_url",
"(",
"url",
")",
"return",
"self",
".",
"connection_from_host",
"(",
"u",
".",
"host",
",",
"port",
"=",
"u",
".",
"port",
",",
"... | [
278,
4
] | [
292,
9
] | python | en | ['en', 'error', 'th'] | False |
PoolManager._merge_pool_kwargs | (self, override) |
Merge a dictionary of override values for self.connection_pool_kw.
This does not modify self.connection_pool_kw and returns a new dict.
Any keys in the override dictionary with a value of ``None`` are
removed from the merged dictionary.
|
Merge a dictionary of override values for self.connection_pool_kw. | def _merge_pool_kwargs(self, override):
"""
Merge a dictionary of override values for self.connection_pool_kw.
This does not modify self.connection_pool_kw and returns a new dict.
Any keys in the override dictionary with a value of ``None`` are
removed from the merged dictionary... | [
"def",
"_merge_pool_kwargs",
"(",
"self",
",",
"override",
")",
":",
"base_pool_kwargs",
"=",
"self",
".",
"connection_pool_kw",
".",
"copy",
"(",
")",
"if",
"override",
":",
"for",
"key",
",",
"value",
"in",
"override",
".",
"items",
"(",
")",
":",
"if"... | [
294,
4
] | [
312,
31
] | python | en | ['en', 'error', 'th'] | False |
PoolManager.urlopen | (self, method, url, redirect=True, **kw) |
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appropriate
:class:`urllib3.connectionpool.ConnectionPool` c... |
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``. | def urlopen(self, method, url, redirect=True, **kw):
"""
Same as :meth:`urllib3.connectionpool.HTTPConnectionPool.urlopen`
with custom cross-host redirect logic and only sends the request-uri
portion of the ``url``.
The given ``url`` parameter must be absolute, such that an appr... | [
"def",
"urlopen",
"(",
"self",
",",
"method",
",",
"url",
",",
"redirect",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"u",
"=",
"parse_url",
"(",
"url",
")",
"conn",
"=",
"self",
".",
"connection_from_host",
"(",
"u",
".",
"host",
",",
"port",
"... | [
314,
4
] | [
377,
60
] | python | en | ['en', 'error', 'th'] | False |
ProxyManager._set_proxy_headers | (self, url, headers=None) |
Sets headers needed by proxies: specifically, the Accept and Host
headers. Only sets headers not provided by the user.
|
Sets headers needed by proxies: specifically, the Accept and Host
headers. Only sets headers not provided by the user.
| def _set_proxy_headers(self, url, headers=None):
"""
Sets headers needed by proxies: specifically, the Accept and Host
headers. Only sets headers not provided by the user.
"""
headers_ = {"Accept": "*/*"}
netloc = parse_url(url).netloc
if netloc:
head... | [
"def",
"_set_proxy_headers",
"(",
"self",
",",
"url",
",",
"headers",
"=",
"None",
")",
":",
"headers_",
"=",
"{",
"\"Accept\"",
":",
"\"*/*\"",
"}",
"netloc",
"=",
"parse_url",
"(",
"url",
")",
".",
"netloc",
"if",
"netloc",
":",
"headers_",
"[",
"\"H... | [
448,
4
] | [
461,
23
] | python | en | ['en', 'error', 'th'] | False |
ProxyManager.urlopen | (self, method, url, redirect=True, **kw) | Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute. | Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute. | def urlopen(self, method, url, redirect=True, **kw):
"Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute."
u = parse_url(url)
self._validate_proxy_scheme_url_selection(u.scheme)
if u.scheme == "http":
# For proxied HTTPS requests, httplib sets the necessary head... | [
"def",
"urlopen",
"(",
"self",
",",
"method",
",",
"url",
",",
"redirect",
"=",
"True",
",",
"*",
"*",
"kw",
")",
":",
"u",
"=",
"parse_url",
"(",
"url",
")",
"self",
".",
"_validate_proxy_scheme_url_selection",
"(",
"u",
".",
"scheme",
")",
"if",
"u... | [
475,
4
] | [
487,
86
] | python | en | ['en', 'en', 'nl'] | True |
dictConfig | (config) | Configure logging using a dictionary. | Configure logging using a dictionary. | def dictConfig(config):
"""Configure logging using a dictionary."""
dictConfigClass(config).configure() | [
"def",
"dictConfig",
"(",
"config",
")",
":",
"dictConfigClass",
"(",
"config",
")",
".",
"configure",
"(",
")"
] | [
566,
0
] | [
568,
39
] | python | en | ['it', 'pt', 'en'] | False |
BaseConfigurator.resolve | (self, s) |
Resolve strings to objects using standard import and attribute
syntax.
|
Resolve strings to objects using standard import and attribute
syntax.
| def resolve(self, s):
"""
Resolve strings to objects using standard import and attribute
syntax.
"""
name = s.split('.')
used = name.pop(0)
try:
found = self.importer(used)
for frag in name:
used += '.' + frag
... | [
"def",
"resolve",
"(",
"self",
",",
"s",
")",
":",
"name",
"=",
"s",
".",
"split",
"(",
"'.'",
")",
"used",
"=",
"name",
".",
"pop",
"(",
"0",
")",
"try",
":",
"found",
"=",
"self",
".",
"importer",
"(",
"used",
")",
"for",
"frag",
"in",
"nam... | [
170,
4
] | [
191,
19
] | python | en | ['en', 'error', 'th'] | False |
BaseConfigurator.ext_convert | (self, value) | Default converter for the ext:// protocol. | Default converter for the ext:// protocol. | def ext_convert(self, value):
"""Default converter for the ext:// protocol."""
return self.resolve(value) | [
"def",
"ext_convert",
"(",
"self",
",",
"value",
")",
":",
"return",
"self",
".",
"resolve",
"(",
"value",
")"
] | [
193,
4
] | [
195,
34
] | python | en | ['en', 'en', 'en'] | True |
BaseConfigurator.cfg_convert | (self, value) | Default converter for the cfg:// protocol. | Default converter for the cfg:// protocol. | def cfg_convert(self, value):
"""Default converter for the cfg:// protocol."""
rest = value
m = self.WORD_PATTERN.match(rest)
if m is None:
raise ValueError("Unable to convert %r" % value)
else:
rest = rest[m.end():]
d = self.config[m.groups()[... | [
"def",
"cfg_convert",
"(",
"self",
",",
"value",
")",
":",
"rest",
"=",
"value",
"m",
"=",
"self",
".",
"WORD_PATTERN",
".",
"match",
"(",
"rest",
")",
"if",
"m",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Unable to convert %r\"",
"%",
"value",
... | [
197,
4
] | [
229,
16
] | python | en | ['en', 'en', 'en'] | True |
BaseConfigurator.convert | (self, value) |
Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.
|
Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.
| def convert(self, value):
"""
Convert values to an appropriate type. dicts, lists and tuples are
replaced by their converting alternatives. Strings are checked to
see if they have a conversion format and are converted if they do.
"""
if not isinstance(value, ConvertingDic... | [
"def",
"convert",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"ConvertingDict",
")",
"and",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"value",
"=",
"ConvertingDict",
"(",
"value",
")",
"value",
".",
"conf... | [
231,
4
] | [
257,
20
] | python | en | ['en', 'error', 'th'] | False |
BaseConfigurator.configure_custom | (self, config) | Configure an object with a user-supplied factory. | Configure an object with a user-supplied factory. | def configure_custom(self, config):
"""Configure an object with a user-supplied factory."""
c = config.pop('()')
if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType:
c = self.resolve(c)
props = config.pop('.', None)
# Check for... | [
"def",
"configure_custom",
"(",
"self",
",",
"config",
")",
":",
"c",
"=",
"config",
".",
"pop",
"(",
"'()'",
")",
"if",
"not",
"hasattr",
"(",
"c",
",",
"'__call__'",
")",
"and",
"hasattr",
"(",
"types",
",",
"'ClassType'",
")",
"and",
"type",
"(",
... | [
259,
4
] | [
271,
21
] | python | en | ['en', 'en', 'en'] | True |
BaseConfigurator.as_tuple | (self, value) | Utility function which converts lists to tuples. | Utility function which converts lists to tuples. | def as_tuple(self, value):
"""Utility function which converts lists to tuples."""
if isinstance(value, list):
value = tuple(value)
return value | [
"def",
"as_tuple",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"tuple",
"(",
"value",
")",
"return",
"value"
] | [
273,
4
] | [
277,
20
] | python | en | ['en', 'en', 'en'] | True |
DictConfigurator.configure | (self) | Do the configuration. | Do the configuration. | def configure(self):
"""Do the configuration."""
config = self.config
if 'version' not in config:
raise ValueError("dictionary doesn't specify a version")
if config['version'] != 1:
raise ValueError("Unsupported version: %s" % config['version'])
increment... | [
"def",
"configure",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"config",
"if",
"'version'",
"not",
"in",
"config",
":",
"raise",
"ValueError",
"(",
"\"dictionary doesn't specify a version\"",
")",
"if",
"config",
"[",
"'version'",
"]",
"!=",
"1",
":"... | [
286,
4
] | [
430,
34
] | python | en | ['en', 'en', 'en'] | True |
DictConfigurator.configure_formatter | (self, config) | Configure a formatter from a dictionary. | Configure a formatter from a dictionary. | def configure_formatter(self, config):
"""Configure a formatter from a dictionary."""
if '()' in config:
factory = config['()'] # for use in exception handler
try:
result = self.configure_custom(config)
except TypeError as te:
if "'for... | [
"def",
"configure_formatter",
"(",
"self",
",",
"config",
")",
":",
"if",
"'()'",
"in",
"config",
":",
"factory",
"=",
"config",
"[",
"'()'",
"]",
"# for use in exception handler",
"try",
":",
"result",
"=",
"self",
".",
"configure_custom",
"(",
"config",
")... | [
432,
4
] | [
452,
21
] | python | en | ['en', 'en', 'en'] | True |
DictConfigurator.configure_filter | (self, config) | Configure a filter from a dictionary. | Configure a filter from a dictionary. | def configure_filter(self, config):
"""Configure a filter from a dictionary."""
if '()' in config:
result = self.configure_custom(config)
else:
name = config.get('name', '')
result = logging.Filter(name)
return result | [
"def",
"configure_filter",
"(",
"self",
",",
"config",
")",
":",
"if",
"'()'",
"in",
"config",
":",
"result",
"=",
"self",
".",
"configure_custom",
"(",
"config",
")",
"else",
":",
"name",
"=",
"config",
".",
"get",
"(",
"'name'",
",",
"''",
")",
"re... | [
454,
4
] | [
461,
21
] | python | en | ['en', 'en', 'en'] | True |
DictConfigurator.add_filters | (self, filterer, filters) | Add filters to a filterer from a list of names. | Add filters to a filterer from a list of names. | def add_filters(self, filterer, filters):
"""Add filters to a filterer from a list of names."""
for f in filters:
try:
filterer.addFilter(self.config['filters'][f])
except StandardError as e:
raise ValueError('Unable to add filter %r: %s' % (f, e)) | [
"def",
"add_filters",
"(",
"self",
",",
"filterer",
",",
"filters",
")",
":",
"for",
"f",
"in",
"filters",
":",
"try",
":",
"filterer",
".",
"addFilter",
"(",
"self",
".",
"config",
"[",
"'filters'",
"]",
"[",
"f",
"]",
")",
"except",
"StandardError",
... | [
463,
4
] | [
469,
72
] | python | en | ['en', 'en', 'en'] | True |
DictConfigurator.configure_handler | (self, config) | Configure a handler from a dictionary. | Configure a handler from a dictionary. | def configure_handler(self, config):
"""Configure a handler from a dictionary."""
formatter = config.pop('formatter', None)
if formatter:
try:
formatter = self.config['formatters'][formatter]
except StandardError as e:
raise ValueError('Una... | [
"def",
"configure_handler",
"(",
"self",
",",
"config",
")",
":",
"formatter",
"=",
"config",
".",
"pop",
"(",
"'formatter'",
",",
"None",
")",
"if",
"formatter",
":",
"try",
":",
"formatter",
"=",
"self",
".",
"config",
"[",
"'formatters'",
"]",
"[",
... | [
471,
4
] | [
522,
21
] | python | en | ['en', 'en', 'en'] | True |
DictConfigurator.add_handlers | (self, logger, handlers) | Add handlers to a logger from a list of names. | Add handlers to a logger from a list of names. | def add_handlers(self, logger, handlers):
"""Add handlers to a logger from a list of names."""
for h in handlers:
try:
logger.addHandler(self.config['handlers'][h])
except StandardError as e:
raise ValueError('Unable to add handler %r: %s' % (h, e)... | [
"def",
"add_handlers",
"(",
"self",
",",
"logger",
",",
"handlers",
")",
":",
"for",
"h",
"in",
"handlers",
":",
"try",
":",
"logger",
".",
"addHandler",
"(",
"self",
".",
"config",
"[",
"'handlers'",
"]",
"[",
"h",
"]",
")",
"except",
"StandardError",... | [
524,
4
] | [
530,
73
] | python | en | ['en', 'en', 'en'] | True |
DictConfigurator.common_logger_config | (self, logger, config, incremental=False) |
Perform configuration which is common to root and non-root loggers.
|
Perform configuration which is common to root and non-root loggers.
| def common_logger_config(self, logger, config, incremental=False):
"""
Perform configuration which is common to root and non-root loggers.
"""
level = config.get('level', None)
if level is not None:
logger.setLevel(_checkLevel(level))
if not incremental:
... | [
"def",
"common_logger_config",
"(",
"self",
",",
"logger",
",",
"config",
",",
"incremental",
"=",
"False",
")",
":",
"level",
"=",
"config",
".",
"get",
"(",
"'level'",
",",
"None",
")",
"if",
"level",
"is",
"not",
"None",
":",
"logger",
".",
"setLeve... | [
532,
4
] | [
548,
49
] | python | en | ['en', 'error', 'th'] | False |
DictConfigurator.configure_logger | (self, name, config, incremental=False) | Configure a non-root logger from a dictionary. | Configure a non-root logger from a dictionary. | def configure_logger(self, name, config, incremental=False):
"""Configure a non-root logger from a dictionary."""
logger = logging.getLogger(name)
self.common_logger_config(logger, config, incremental)
propagate = config.get('propagate', None)
if propagate is not None:
... | [
"def",
"configure_logger",
"(",
"self",
",",
"name",
",",
"config",
",",
"incremental",
"=",
"False",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"self",
".",
"common_logger_config",
"(",
"logger",
",",
"config",
",",
"increment... | [
550,
4
] | [
556,
40
] | python | en | ['en', 'en', 'en'] | True |
DictConfigurator.configure_root | (self, config, incremental=False) | Configure a root logger from a dictionary. | Configure a root logger from a dictionary. | def configure_root(self, config, incremental=False):
"""Configure a root logger from a dictionary."""
root = logging.getLogger()
self.common_logger_config(root, config, incremental) | [
"def",
"configure_root",
"(",
"self",
",",
"config",
",",
"incremental",
"=",
"False",
")",
":",
"root",
"=",
"logging",
".",
"getLogger",
"(",
")",
"self",
".",
"common_logger_config",
"(",
"root",
",",
"config",
",",
"incremental",
")"
] | [
558,
4
] | [
561,
60
] | python | en | ['en', 'en', 'en'] | True |
_match_vcs_scheme | (url) | Look for VCS schemes in the URL.
Returns the matched VCS scheme, or None if there's no match.
| Look for VCS schemes in the URL. | def _match_vcs_scheme(url):
# type: (str) -> Optional[str]
"""Look for VCS schemes in the URL.
Returns the matched VCS scheme, or None if there's no match.
"""
for scheme in vcs.schemes:
if url.lower().startswith(scheme) and url[len(scheme)] in '+:':
return scheme
return Non... | [
"def",
"_match_vcs_scheme",
"(",
"url",
")",
":",
"# type: (str) -> Optional[str]",
"for",
"scheme",
"in",
"vcs",
".",
"schemes",
":",
"if",
"url",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"scheme",
")",
"and",
"url",
"[",
"len",
"(",
"scheme",
")... | [
66,
0
] | [
75,
15
] | python | en | ['en', 'en', 'en'] | True |
_is_url_like_archive | (url) | Return whether the URL looks like an archive.
| Return whether the URL looks like an archive.
| def _is_url_like_archive(url):
# type: (str) -> bool
"""Return whether the URL looks like an archive.
"""
filename = Link(url).filename
for bad_ext in ARCHIVE_EXTENSIONS:
if filename.endswith(bad_ext):
return True
return False | [
"def",
"_is_url_like_archive",
"(",
"url",
")",
":",
"# type: (str) -> bool",
"filename",
"=",
"Link",
"(",
"url",
")",
".",
"filename",
"for",
"bad_ext",
"in",
"ARCHIVE_EXTENSIONS",
":",
"if",
"filename",
".",
"endswith",
"(",
"bad_ext",
")",
":",
"return",
... | [
78,
0
] | [
86,
16
] | python | en | ['en', 'en', 'en'] | True |
_ensure_html_header | (response) | Check the Content-Type header to ensure the response contains HTML.
Raises `_NotHTML` if the content type is not text/html.
| Check the Content-Type header to ensure the response contains HTML. | def _ensure_html_header(response):
# type: (Response) -> None
"""Check the Content-Type header to ensure the response contains HTML.
Raises `_NotHTML` if the content type is not text/html.
"""
content_type = response.headers.get("Content-Type", "")
if not content_type.lower().startswith("text/h... | [
"def",
"_ensure_html_header",
"(",
"response",
")",
":",
"# type: (Response) -> None",
"content_type",
"=",
"response",
".",
"headers",
".",
"get",
"(",
"\"Content-Type\"",
",",
"\"\"",
")",
"if",
"not",
"content_type",
".",
"lower",
"(",
")",
".",
"startswith",... | [
97,
0
] | [
105,
61
] | python | en | ['en', 'en', 'en'] | True |
_ensure_html_response | (url, session) | Send a HEAD request to the URL, and ensure the response contains HTML.
Raises `_NotHTTP` if the URL is not available for a HEAD request, or
`_NotHTML` if the content type is not text/html.
| Send a HEAD request to the URL, and ensure the response contains HTML. | def _ensure_html_response(url, session):
# type: (str, PipSession) -> None
"""Send a HEAD request to the URL, and ensure the response contains HTML.
Raises `_NotHTTP` if the URL is not available for a HEAD request, or
`_NotHTML` if the content type is not text/html.
"""
scheme, netloc, path, qu... | [
"def",
"_ensure_html_response",
"(",
"url",
",",
"session",
")",
":",
"# type: (str, PipSession) -> None",
"scheme",
",",
"netloc",
",",
"path",
",",
"query",
",",
"fragment",
"=",
"urllib_parse",
".",
"urlsplit",
"(",
"url",
")",
"if",
"scheme",
"not",
"in",
... | [
112,
0
] | [
126,
29
] | python | en | ['en', 'en', 'en'] | True |
_get_html_response | (url, session) | Access an HTML page with GET, and return the response.
This consists of three parts:
1. If the URL looks suspiciously like an archive, send a HEAD first to
check the Content-Type is HTML, to avoid downloading a large file.
Raise `_NotHTTP` if the content type cannot be determined, or
`_No... | Access an HTML page with GET, and return the response. | def _get_html_response(url, session):
# type: (str, PipSession) -> Response
"""Access an HTML page with GET, and return the response.
This consists of three parts:
1. If the URL looks suspiciously like an archive, send a HEAD first to
check the Content-Type is HTML, to avoid downloading a large... | [
"def",
"_get_html_response",
"(",
"url",
",",
"session",
")",
":",
"# type: (str, PipSession) -> Response",
"if",
"_is_url_like_archive",
"(",
"url",
")",
":",
"_ensure_html_response",
"(",
"url",
",",
"session",
"=",
"session",
")",
"logger",
".",
"debug",
"(",
... | [
129,
0
] | [
177,
15
] | python | en | ['en', 'en', 'en'] | True |
_get_encoding_from_headers | (headers) | Determine if we have any encoding information in our headers.
| Determine if we have any encoding information in our headers.
| def _get_encoding_from_headers(headers):
# type: (ResponseHeaders) -> Optional[str]
"""Determine if we have any encoding information in our headers.
"""
if headers and "Content-Type" in headers:
content_type, params = cgi.parse_header(headers["Content-Type"])
if "charset" in params:
... | [
"def",
"_get_encoding_from_headers",
"(",
"headers",
")",
":",
"# type: (ResponseHeaders) -> Optional[str]",
"if",
"headers",
"and",
"\"Content-Type\"",
"in",
"headers",
":",
"content_type",
",",
"params",
"=",
"cgi",
".",
"parse_header",
"(",
"headers",
"[",
"\"Conte... | [
180,
0
] | [
188,
15
] | python | en | ['en', 'en', 'en'] | True |
_determine_base_url | (document, page_url) | Determine the HTML document's base URL.
This looks for a ``<base>`` tag in the HTML document. If present, its href
attribute denotes the base URL of anchor tags in the document. If there is
no such tag (or if it does not have a valid href attribute), the HTML
file's URL is used as the base URL.
:p... | Determine the HTML document's base URL. | def _determine_base_url(document, page_url):
# type: (HTMLElement, str) -> str
"""Determine the HTML document's base URL.
This looks for a ``<base>`` tag in the HTML document. If present, its href
attribute denotes the base URL of anchor tags in the document. If there is
no such tag (or if it does ... | [
"def",
"_determine_base_url",
"(",
"document",
",",
"page_url",
")",
":",
"# type: (HTMLElement, str) -> str",
"for",
"base",
"in",
"document",
".",
"findall",
"(",
"\".//base\"",
")",
":",
"href",
"=",
"base",
".",
"get",
"(",
"\"href\"",
")",
"if",
"href",
... | [
191,
0
] | [
208,
19
] | python | en | ['en', 'no', 'en'] | True |
_clean_url_path_part | (part) |
Clean a "part" of a URL path (i.e. after splitting on "@" characters).
|
Clean a "part" of a URL path (i.e. after splitting on " | def _clean_url_path_part(part):
# type: (str) -> str
"""
Clean a "part" of a URL path (i.e. after splitting on "@" characters).
"""
# We unquote prior to quoting to make sure nothing is double quoted.
return urllib_parse.quote(urllib_parse.unquote(part)) | [
"def",
"_clean_url_path_part",
"(",
"part",
")",
":",
"# type: (str) -> str",
"# We unquote prior to quoting to make sure nothing is double quoted.",
"return",
"urllib_parse",
".",
"quote",
"(",
"urllib_parse",
".",
"unquote",
"(",
"part",
")",
")"
] | [
211,
0
] | [
217,
57
] | python | en | ['en', 'error', 'th'] | False |
_clean_file_url_path | (part) |
Clean the first part of a URL path that corresponds to a local
filesystem path (i.e. the first part after splitting on "@" characters).
|
Clean the first part of a URL path that corresponds to a local
filesystem path (i.e. the first part after splitting on " | def _clean_file_url_path(part):
# type: (str) -> str
"""
Clean the first part of a URL path that corresponds to a local
filesystem path (i.e. the first part after splitting on "@" characters).
"""
# We unquote prior to quoting to make sure nothing is double quoted.
# Also, on Windows the pat... | [
"def",
"_clean_file_url_path",
"(",
"part",
")",
":",
"# type: (str) -> str",
"# We unquote prior to quoting to make sure nothing is double quoted.",
"# Also, on Windows the path part might contain a drive letter which",
"# should not be quoted. On Linux where drive letters do not",
"# exist, th... | [
220,
0
] | [
231,
73
] | python | en | ['en', 'error', 'th'] | False |
_clean_url_path | (path, is_local_path) |
Clean the path portion of a URL.
|
Clean the path portion of a URL.
| def _clean_url_path(path, is_local_path):
# type: (str, bool) -> str
"""
Clean the path portion of a URL.
"""
if is_local_path:
clean_func = _clean_file_url_path
else:
clean_func = _clean_url_path_part
# Split on the reserved characters prior to cleaning so that
# revisi... | [
"def",
"_clean_url_path",
"(",
"path",
",",
"is_local_path",
")",
":",
"# type: (str, bool) -> str",
"if",
"is_local_path",
":",
"clean_func",
"=",
"_clean_file_url_path",
"else",
":",
"clean_func",
"=",
"_clean_url_path_part",
"# Split on the reserved characters prior to cle... | [
238,
0
] | [
258,
33
] | python | en | ['en', 'error', 'th'] | False |
_clean_link | (url) |
Make sure a link is fully quoted.
For example, if ' ' occurs in the URL, it will be replaced with "%20",
and without double-quoting other characters.
|
Make sure a link is fully quoted.
For example, if ' ' occurs in the URL, it will be replaced with "%20",
and without double-quoting other characters.
| def _clean_link(url):
# type: (str) -> str
"""
Make sure a link is fully quoted.
For example, if ' ' occurs in the URL, it will be replaced with "%20",
and without double-quoting other characters.
"""
# Split the URL into parts according to the general structure
# `scheme://netloc/path;p... | [
"def",
"_clean_link",
"(",
"url",
")",
":",
"# type: (str) -> str",
"# Split the URL into parts according to the general structure",
"# `scheme://netloc/path;parameters?query#fragment`.",
"result",
"=",
"urllib_parse",
".",
"urlparse",
"(",
"url",
")",
"# If the netloc is empty, th... | [
261,
0
] | [
274,
62
] | python | en | ['en', 'error', 'th'] | False |
_create_link_from_element | (
anchor, # type: HTMLElement
page_url, # type: str
base_url, # type: str
) |
Convert an anchor element in a simple repository page to a Link.
|
Convert an anchor element in a simple repository page to a Link.
| def _create_link_from_element(
anchor, # type: HTMLElement
page_url, # type: str
base_url, # type: str
):
# type: (...) -> Optional[Link]
"""
Convert an anchor element in a simple repository page to a Link.
"""
href = anchor.get("href")
if not href:
return None
url ... | [
"def",
"_create_link_from_element",
"(",
"anchor",
",",
"# type: HTMLElement",
"page_url",
",",
"# type: str",
"base_url",
",",
"# type: str",
")",
":",
"# type: (...) -> Optional[Link]",
"href",
"=",
"anchor",
".",
"get",
"(",
"\"href\"",
")",
"if",
"not",
"href",
... | [
277,
0
] | [
306,
15
] | python | en | ['en', 'error', 'th'] | False |
with_cached_html_pages | (
fn, # type: Callable[[HTMLPage], Iterable[Link]]
) |
Given a function that parses an Iterable[Link] from an HTMLPage, cache the
function's result (keyed by CacheablePageContent), unless the HTMLPage
`page` has `page.cache_link_parsing == False`.
|
Given a function that parses an Iterable[Link] from an HTMLPage, cache the
function's result (keyed by CacheablePageContent), unless the HTMLPage
`page` has `page.cache_link_parsing == False`.
| def with_cached_html_pages(
fn, # type: Callable[[HTMLPage], Iterable[Link]]
):
# type: (...) -> Callable[[HTMLPage], List[Link]]
"""
Given a function that parses an Iterable[Link] from an HTMLPage, cache the
function's result (keyed by CacheablePageContent), unless the HTMLPage
`page` has `p... | [
"def",
"with_cached_html_pages",
"(",
"fn",
",",
"# type: Callable[[HTMLPage], Iterable[Link]]",
")",
":",
"# type: (...) -> Callable[[HTMLPage], List[Link]]",
"@",
"_lru_cache",
"(",
"maxsize",
"=",
"None",
")",
"def",
"wrapper",
"(",
"cacheable_page",
")",
":",
"# type:... | [
325,
0
] | [
347,
26
] | python | en | ['en', 'error', 'th'] | False |
parse_links | (page) |
Parse an HTML document, and yield its anchor elements as Link objects.
|
Parse an HTML document, and yield its anchor elements as Link objects.
| def parse_links(page):
# type: (HTMLPage) -> Iterable[Link]
"""
Parse an HTML document, and yield its anchor elements as Link objects.
"""
document = html5lib.parse(
page.content,
transport_encoding=page.encoding,
namespaceHTMLElements=False,
)
url = page.url
bas... | [
"def",
"parse_links",
"(",
"page",
")",
":",
"# type: (HTMLPage) -> Iterable[Link]",
"document",
"=",
"html5lib",
".",
"parse",
"(",
"page",
".",
"content",
",",
"transport_encoding",
"=",
"page",
".",
"encoding",
",",
"namespaceHTMLElements",
"=",
"False",
",",
... | [
351,
0
] | [
372,
18
] | python | en | ['en', 'error', 'th'] | False |
_remove_duplicate_links | (links) |
Return a list of links, with duplicates removed and ordering preserved.
|
Return a list of links, with duplicates removed and ordering preserved.
| def _remove_duplicate_links(links):
# type: (Iterable[Link]) -> List[Link]
"""
Return a list of links, with duplicates removed and ordering preserved.
"""
# We preserve the ordering when removing duplicates because we can.
return list(OrderedDict.fromkeys(links)) | [
"def",
"_remove_duplicate_links",
"(",
"links",
")",
":",
"# type: (Iterable[Link]) -> List[Link]",
"# We preserve the ordering when removing duplicates because we can.",
"return",
"list",
"(",
"OrderedDict",
".",
"fromkeys",
"(",
"links",
")",
")"
] | [
479,
0
] | [
485,
44
] | python | en | ['en', 'error', 'th'] | False |
group_locations | (locations, expand_dir=False) |
Divide a list of locations into two groups: "files" (archives) and "urls."
:return: A pair of lists (files, urls).
|
Divide a list of locations into two groups: "files" (archives) and "urls." | def group_locations(locations, expand_dir=False):
# type: (Sequence[str], bool) -> Tuple[List[str], List[str]]
"""
Divide a list of locations into two groups: "files" (archives) and "urls."
:return: A pair of lists (files, urls).
"""
files = []
urls = []
# puts the url for the given fi... | [
"def",
"group_locations",
"(",
"locations",
",",
"expand_dir",
"=",
"False",
")",
":",
"# type: (Sequence[str], bool) -> Tuple[List[str], List[str]]",
"files",
"=",
"[",
"]",
"urls",
"=",
"[",
"]",
"# puts the url for the given file path into the appropriate list",
"def",
"... | [
488,
0
] | [
545,
22
] | python | en | ['en', 'error', 'th'] | False |
HTMLPage.__init__ | (
self,
content, # type: bytes
encoding, # type: Optional[str]
url, # type: str
cache_link_parsing=True, # type: bool
) |
:param encoding: the encoding to decode the given content.
:param url: the URL from which the HTML was downloaded.
:param cache_link_parsing: whether links parsed from this page's url
should be cached. PyPI index urls should
... |
:param encoding: the encoding to decode the given content.
:param url: the URL from which the HTML was downloaded.
:param cache_link_parsing: whether links parsed from this page's url
should be cached. PyPI index urls should
... | def __init__(
self,
content, # type: bytes
encoding, # type: Optional[str]
url, # type: str
cache_link_parsing=True, # type: bool
):
# type: (...) -> None
"""
:param encoding: the encoding to decod... | [
"def",
"__init__",
"(",
"self",
",",
"content",
",",
"# type: bytes",
"encoding",
",",
"# type: Optional[str]",
"url",
",",
"# type: str",
"cache_link_parsing",
"=",
"True",
",",
"# type: bool",
")",
":",
"# type: (...) -> None",
"self",
".",
"content",
"=",
"cont... | [
378,
4
] | [
396,
52
] | python | en | ['en', 'error', 'th'] | False |
CollectedLinks.__init__ | (
self,
files, # type: List[Link]
find_links, # type: List[Link]
project_urls, # type: List[Link]
) |
:param files: Links from file locations.
:param find_links: Links from find_links.
:param project_urls: URLs to HTML project pages, as described by
the PEP 503 simple repository API.
|
:param files: Links from file locations.
:param find_links: Links from find_links.
:param project_urls: URLs to HTML project pages, as described by
the PEP 503 simple repository API.
| def __init__(
self,
files, # type: List[Link]
find_links, # type: List[Link]
project_urls, # type: List[Link]
):
# type: (...) -> None
"""
:param files: Links from file locations.
:param find_links: Links from find_links.
:param pro... | [
"def",
"__init__",
"(",
"self",
",",
"files",
",",
"# type: List[Link]",
"find_links",
",",
"# type: List[Link]",
"project_urls",
",",
"# type: List[Link]",
")",
":",
"# type: (...) -> None",
"self",
".",
"files",
"=",
"files",
"self",
".",
"find_links",
"=",
"fin... | [
565,
4
] | [
580,
40
] | python | en | ['en', 'error', 'th'] | False |
LinkCollector.fetch_page | (self, location) |
Fetch an HTML page containing package links.
|
Fetch an HTML page containing package links.
| def fetch_page(self, location):
# type: (Link) -> Optional[HTMLPage]
"""
Fetch an HTML page containing package links.
"""
return _get_html_page(location, session=self.session) | [
"def",
"fetch_page",
"(",
"self",
",",
"location",
")",
":",
"# type: (Link) -> Optional[HTMLPage]",
"return",
"_get_html_page",
"(",
"location",
",",
"session",
"=",
"self",
".",
"session",
")"
] | [
606,
4
] | [
611,
61
] | python | en | ['en', 'error', 'th'] | False |
LinkCollector.collect_links | (self, project_name) | Find all available links for the given project name.
:return: All the Link objects (unfiltered), as a CollectedLinks object.
| Find all available links for the given project name. | def collect_links(self, project_name):
# type: (str) -> CollectedLinks
"""Find all available links for the given project name.
:return: All the Link objects (unfiltered), as a CollectedLinks object.
"""
search_scope = self.search_scope
index_locations = search_scope.get_... | [
"def",
"collect_links",
"(",
"self",
",",
"project_name",
")",
":",
"# type: (str) -> CollectedLinks",
"search_scope",
"=",
"self",
".",
"search_scope",
"index_locations",
"=",
"search_scope",
".",
"get_index_urls_locations",
"(",
"project_name",
")",
"index_file_loc",
... | [
613,
4
] | [
660,
9
] | python | en | ['en', 'en', 'en'] | True |
refs_aggregate | (lookup_parts, aggregates) |
A little helper method to check if the lookup_parts contains references
to the given aggregates set. Because the LOOKUP_SEP is contained in the
default annotation names we must check each prefix of the lookup_parts
for match.
|
A little helper method to check if the lookup_parts contains references
to the given aggregates set. Because the LOOKUP_SEP is contained in the
default annotation names we must check each prefix of the lookup_parts
for match.
| def refs_aggregate(lookup_parts, aggregates):
"""
A little helper method to check if the lookup_parts contains references
to the given aggregates set. Because the LOOKUP_SEP is contained in the
default annotation names we must check each prefix of the lookup_parts
for match.
"""
for n in ran... | [
"def",
"refs_aggregate",
"(",
"lookup_parts",
",",
"aggregates",
")",
":",
"for",
"n",
"in",
"range",
"(",
"len",
"(",
"lookup_parts",
")",
"+",
"1",
")",
":",
"level_n_lookup",
"=",
"LOOKUP_SEP",
".",
"join",
"(",
"lookup_parts",
"[",
"0",
":",
"n",
"... | [
10,
0
] | [
21,
20
] | python | en | ['en', 'error', 'th'] | False |
Aggregate.__init__ | (self, lookup, **extra) | Instantiate a new aggregate.
* lookup is the field on which the aggregate operates.
* extra is a dictionary of additional data to provide for the
aggregate definition
Also utilizes the class variables:
* name, the identifier for this aggregate function.
| Instantiate a new aggregate. | def __init__(self, lookup, **extra):
"""Instantiate a new aggregate.
* lookup is the field on which the aggregate operates.
* extra is a dictionary of additional data to provide for the
aggregate definition
Also utilizes the class variables:
* name, the identifier... | [
"def",
"__init__",
"(",
"self",
",",
"lookup",
",",
"*",
"*",
"extra",
")",
":",
"self",
".",
"lookup",
"=",
"lookup",
"self",
".",
"extra",
"=",
"extra"
] | [
28,
4
] | [
39,
26
] | python | en | ['it', 'en', 'en'] | True |
Aggregate.add_to_query | (self, query, alias, col, source, is_summary) | Add the aggregate to the nominated query.
This method is used to convert the generic Aggregate definition into a
backend-specific definition.
* query is the backend-specific query instance to which the aggregate
is to be added.
* col is a column reference describing the su... | Add the aggregate to the nominated query. | def add_to_query(self, query, alias, col, source, is_summary):
"""Add the aggregate to the nominated query.
This method is used to convert the generic Aggregate definition into a
backend-specific definition.
* query is the backend-specific query instance to which the aggregate
... | [
"def",
"add_to_query",
"(",
"self",
",",
"query",
",",
"alias",
",",
"col",
",",
"source",
",",
"is_summary",
")",
":",
"klass",
"=",
"getattr",
"(",
"query",
".",
"aggregates_module",
",",
"self",
".",
"name",
")",
"aggregate",
"=",
"klass",
"(",
"col... | [
45,
4
] | [
65,
43
] | python | en | ['en', 'en', 'en'] | True |
parse_distutils_args | (args) | Parse provided arguments, returning an object that has the
matched arguments.
Any unknown arguments are ignored.
| Parse provided arguments, returning an object that has the
matched arguments. | def parse_distutils_args(args):
# type: (List[str]) -> Dict[str, str]
"""Parse provided arguments, returning an object that has the
matched arguments.
Any unknown arguments are ignored.
"""
result = {}
for arg in args:
try:
_, match = _distutils_getopt.getopt(args=[arg])... | [
"def",
"parse_distutils_args",
"(",
"args",
")",
":",
"# type: (List[str]) -> Dict[str, str]",
"result",
"=",
"{",
"}",
"for",
"arg",
"in",
"args",
":",
"try",
":",
"_",
",",
"match",
"=",
"_distutils_getopt",
".",
"getopt",
"(",
"args",
"=",
"[",
"arg",
"... | [
29,
0
] | [
47,
17
] | python | en | ['en', 'en', 'en'] | True |
get_static_prefix | (parser, token) |
Populates a template variable with the static prefix,
``settings.STATIC_URL``.
Usage::
{% get_static_prefix [as varname] %}
Examples::
{% get_static_prefix %}
{% get_static_prefix as static_prefix %}
|
Populates a template variable with the static prefix,
``settings.STATIC_URL``. | def get_static_prefix(parser, token):
"""
Populates a template variable with the static prefix,
``settings.STATIC_URL``.
Usage::
{% get_static_prefix [as varname] %}
Examples::
{% get_static_prefix %}
{% get_static_prefix as static_prefix %}
"""
return PrefixNode... | [
"def",
"get_static_prefix",
"(",
"parser",
",",
"token",
")",
":",
"return",
"PrefixNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
",",
"\"STATIC_URL\"",
")"
] | [
55,
0
] | [
70,
63
] | python | en | ['en', 'error', 'th'] | False |
get_media_prefix | (parser, token) |
Populates a template variable with the media prefix,
``settings.MEDIA_URL``.
Usage::
{% get_media_prefix [as varname] %}
Examples::
{% get_media_prefix %}
{% get_media_prefix as media_prefix %}
|
Populates a template variable with the media prefix,
``settings.MEDIA_URL``. | def get_media_prefix(parser, token):
"""
Populates a template variable with the media prefix,
``settings.MEDIA_URL``.
Usage::
{% get_media_prefix [as varname] %}
Examples::
{% get_media_prefix %}
{% get_media_prefix as media_prefix %}
"""
return PrefixNode.handle... | [
"def",
"get_media_prefix",
"(",
"parser",
",",
"token",
")",
":",
"return",
"PrefixNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
",",
"\"MEDIA_URL\"",
")"
] | [
74,
0
] | [
89,
62
] | python | en | ['en', 'error', 'th'] | False |
do_static | (parser, token) |
Joins the given path with the STATIC_URL setting.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% static variable_with_path as varname %}
... |
Joins the given path with the STATIC_URL setting. | def do_static(parser, token):
"""
Joins the given path with the STATIC_URL setting.
Usage::
{% static path [as varname] %}
Examples::
{% static "myapp/css/base.css" %}
{% static variable_with_path %}
{% static "myapp/css/base.css" as admin_base_css %}
{% stati... | [
"def",
"do_static",
"(",
"parser",
",",
"token",
")",
":",
"return",
"StaticNode",
".",
"handle_token",
"(",
"parser",
",",
"token",
")"
] | [
137,
0
] | [
153,
49
] | python | en | ['en', 'error', 'th'] | False |
PrefixNode.handle_token | (cls, parser, token, name) |
Class method to parse prefix node and return a Node.
|
Class method to parse prefix node and return a Node.
| def handle_token(cls, parser, token, name):
"""
Class method to parse prefix node and return a Node.
"""
# token.split_contents() isn't useful here because tags using this method don't accept variable as arguments
tokens = token.contents.split()
if len(tokens) > 1 and tok... | [
"def",
"handle_token",
"(",
"cls",
",",
"parser",
",",
"token",
",",
"name",
")",
":",
"# token.split_contents() isn't useful here because tags using this method don't accept variable as arguments",
"tokens",
"=",
"token",
".",
"contents",
".",
"split",
"(",
")",
"if",
... | [
21,
4
] | [
34,
33
] | python | en | ['en', 'error', 'th'] | False |
StaticNode.handle_token | (cls, parser, token) |
Class method to parse prefix node and return a Node.
|
Class method to parse prefix node and return a Node.
| def handle_token(cls, parser, token):
"""
Class method to parse prefix node and return a Node.
"""
bits = token.split_contents()
if len(bits) < 2:
raise template.TemplateSyntaxError(
"'%s' takes at least one argument (path to file)" % bits[0])
... | [
"def",
"handle_token",
"(",
"cls",
",",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"raise",
"template",
".",
"TemplateSyntaxError",
"(",
"\"'%s' takes at least one ... | [
116,
4
] | [
133,
33
] | python | en | ['en', 'error', 'th'] | False |
arg_type | (arg_names, kwargs) |
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently supported: numpy darray or som... |
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
Currently supported: numpy darray or som... | def arg_type(arg_names, kwargs):
"""
Returns a hashable summary of the types of arg_names within kwargs.
:param arg_names: tuple containing names of relevant arguments
:param kwargs: dict mapping string argument names to values.
These must be values for which we can create a tf placeholder.
... | [
"def",
"arg_type",
"(",
"arg_names",
",",
"kwargs",
")",
":",
"assert",
"isinstance",
"(",
"arg_names",
",",
"tuple",
")",
"passed",
"=",
"tuple",
"(",
"name",
"in",
"kwargs",
"for",
"name",
"in",
"arg_names",
")",
"passed_and_not_none",
"=",
"[",
"]",
"... | [
319,
0
] | [
362,
48
] | python | en | ['en', 'error', 'th'] | False |
Attack.__init__ | (self, model, sess=None, dtypestr="float32", **kwargs) |
:param model: An instance of the cleverhans.model.Model class.
:param sess: The (possibly optional) tf.Session to run graphs in.
:param dtypestr: Floating point precision to use (change to float64
to avoid numerical instabilities).
:param back: (deprecated and w... |
:param model: An instance of the cleverhans.model.Model class.
:param sess: The (possibly optional) tf.Session to run graphs in.
:param dtypestr: Floating point precision to use (change to float64
to avoid numerical instabilities).
:param back: (deprecated and w... | def __init__(self, model, sess=None, dtypestr="float32", **kwargs):
"""
:param model: An instance of the cleverhans.model.Model class.
:param sess: The (possibly optional) tf.Session to run graphs in.
:param dtypestr: Floating point precision to use (change to float64
... | [
"def",
"__init__",
"(",
"self",
",",
"model",
",",
"sess",
"=",
"None",
",",
"dtypestr",
"=",
"\"float32\"",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"\"back\"",
"in",
"kwargs",
":",
"if",
"kwargs",
"[",
"\"back\"",
"]",
"==",
"\"tf\"",
":",
"warning... | [
25,
4
] | [
84,
35
] | python | en | ['en', 'error', 'th'] | False |
Attack.generate | (self, x, **kwargs) |
Generate the attack's symbolic graph for adversarial examples. This
method should be overriden in any child class that implements an
attack that is expressable symbolically. Otherwise, it will wrap the
numerical implementation as a symbolic operator.
:param x: The model's symbo... |
Generate the attack's symbolic graph for adversarial examples. This
method should be overriden in any child class that implements an
attack that is expressable symbolically. Otherwise, it will wrap the
numerical implementation as a symbolic operator. | def generate(self, x, **kwargs):
"""
Generate the attack's symbolic graph for adversarial examples. This
method should be overriden in any child class that implements an
attack that is expressable symbolically. Otherwise, it will wrap the
numerical implementation as a symbolic op... | [
"def",
"generate",
"(",
"self",
",",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"error",
"=",
"\"Sub-classes must implement generate.\"",
"raise",
"NotImplementedError",
"(",
"error",
")",
"# Include an unused return so pylint understands the method signature",
"return",
"x"... | [
86,
4
] | [
118,
16
] | python | en | ['en', 'error', 'th'] | False |
Attack.construct_graph | (self, fixed, feedable, x_val, hash_key) |
Construct the graph required to run the attack through generate_np.
:param fixed: Structural elements that require defining a new graph.
:param feedable: Arguments that can be fed to the same graph when
they take different values.
:param x_val: symbolic adversa... |
Construct the graph required to run the attack through generate_np. | def construct_graph(self, fixed, feedable, x_val, hash_key):
"""
Construct the graph required to run the attack through generate_np.
:param fixed: Structural elements that require defining a new graph.
:param feedable: Arguments that can be fed to the same graph when
... | [
"def",
"construct_graph",
"(",
"self",
",",
"fixed",
",",
"feedable",
",",
"x_val",
",",
"hash_key",
")",
":",
"# try our very best to create a TF placeholder for each of the",
"# feedable keyword arguments, and check the types are one of",
"# the allowed types",
"class_name",
"=... | [
120,
4
] | [
175,
13
] | python | en | ['en', 'error', 'th'] | False |
Attack.generate_np | (self, x_val, **kwargs) |
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param **kwargs: optional parameters used by child classe... |
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments. | def generate_np(self, x_val, **kwargs):
"""
Generate adversarial examples and return them as a NumPy array.
Sub-classes *should not* implement this method unless they must
perform special handling of arguments.
:param x_val: A NumPy array with the original inputs.
:param... | [
"def",
"generate_np",
"(",
"self",
",",
"x_val",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"sess",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Cannot use `generate_np` when no `sess` was\"",
"\" provided\"",
")",
"packed",
"=",
"self",
".",
... | [
177,
4
] | [
209,
46
] | python | en | ['en', 'error', 'th'] | False |
Attack.construct_variables | (self, kwargs) |
Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return:
Structural arguments
Feedable arguments
Output of `arg_type` describing feedable arguments
A unique key
|
Construct the inputs to the attack graph to be used by generate_np. | def construct_variables(self, kwargs):
"""
Construct the inputs to the attack graph to be used by generate_np.
:param kwargs: Keyword arguments to generate_np.
:return:
Structural arguments
Feedable arguments
Output of `arg_type` describing feedable argumen... | [
"def",
"construct_variables",
"(",
"self",
",",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"feedable_kwargs",
",",
"dict",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Using a dict for `feedable_kwargs is deprecated.\"",
"\"Switch to using a tuple.\"",
"\... | [
211,
4
] | [
272,
55
] | python | en | ['en', 'error', 'th'] | False |
Attack.get_or_guess_labels | (self, x, kwargs) |
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
... |
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is in kwargs and is not none, then assume it's a
... | def get_or_guess_labels(self, x, kwargs):
"""
Get the label to use in generating an adversarial example for x.
The kwargs are fed directly from the kwargs of the attack.
If 'y' is in kwargs, then assume it's an untargeted attack and
use that as the label.
If 'y_target' is... | [
"def",
"get_or_guess_labels",
"(",
"self",
",",
"x",
",",
"kwargs",
")",
":",
"if",
"\"y\"",
"in",
"kwargs",
"and",
"\"y_target\"",
"in",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"Can not set both 'y' and 'y_target'.\"",
")",
"elif",
"\"y\"",
"in",
"kwargs",... | [
274,
4
] | [
301,
33
] | python | en | ['en', 'error', 'th'] | False |
Attack.parse_params | (self, params=None) |
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
:param params: a dictionary of attack-specific parameters
:return: True when parsing was successful
|
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes. | def parse_params(self, params=None):
"""
Take in a dictionary of parameters and applies attack-specific checks
before saving them as attributes.
:param params: a dictionary of attack-specific parameters
:return: True when parsing was successful
"""
if params is ... | [
"def",
"parse_params",
"(",
"self",
",",
"params",
"=",
"None",
")",
":",
"if",
"params",
"is",
"not",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"`params` is unused and will be removed \"",
"\" on or after 2019-04-26.\"",
")",
"return",
"True"
] | [
303,
4
] | [
316,
19
] | python | en | ['en', 'error', 'th'] | False |
mnist_tutorial | (
train_start=0,
train_end=60000,
test_start=0,
test_end=10000,
nb_epochs=NB_EPOCHS,
batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE,
testing=False,
label_smoothing=0.1,
) |
MNIST CleverHans tutorial
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:param nb_epochs: number of epochs to train model
:param ... |
MNIST CleverHans tutorial
:param train_start: index of first training set example
:param train_end: index of last training set example
:param test_start: index of first test set example
:param test_end: index of last test set example
:param nb_epochs: number of epochs to train model
:param ... | def mnist_tutorial(
train_start=0,
train_end=60000,
test_start=0,
test_end=10000,
nb_epochs=NB_EPOCHS,
batch_size=BATCH_SIZE,
learning_rate=LEARNING_RATE,
testing=False,
label_smoothing=0.1,
):
"""
MNIST CleverHans tutorial
:param train_start: index of first training set ... | [
"def",
"mnist_tutorial",
"(",
"train_start",
"=",
"0",
",",
"train_end",
"=",
"60000",
",",
"test_start",
"=",
"0",
",",
"test_end",
"=",
"10000",
",",
"nb_epochs",
"=",
"NB_EPOCHS",
",",
"batch_size",
"=",
"BATCH_SIZE",
",",
"learning_rate",
"=",
"LEARNING_... | [
29,
0
] | [
188,
17
] | python | en | ['en', 'error', 'th'] | False |
log_response | (message, *args, response=None, request=None, logger=request_logger, level=None, exc_info=None) |
Log errors based on HttpResponse status.
Log 5xx responses as errors and 4xx responses as warnings (unless a level
is given as a keyword argument). The HttpResponse status_code and the
request are passed to the logger's extra parameter.
|
Log errors based on HttpResponse status. | def log_response(message, *args, response=None, request=None, logger=request_logger, level=None, exc_info=None):
"""
Log errors based on HttpResponse status.
Log 5xx responses as errors and 4xx responses as warnings (unless a level
is given as a keyword argument). The HttpResponse status_code and the
... | [
"def",
"log_response",
"(",
"message",
",",
"*",
"args",
",",
"response",
"=",
"None",
",",
"request",
"=",
"None",
",",
"logger",
"=",
"request_logger",
",",
"level",
"=",
"None",
",",
"exc_info",
"=",
"None",
")",
":",
"# Check if the response has already ... | [
198,
0
] | [
229,
36
] | python | en | ['en', 'error', 'th'] | False |
AdminEmailHandler.format_subject | (self, subject) |
Escape CR and LF characters.
|
Escape CR and LF characters.
| def format_subject(self, subject):
"""
Escape CR and LF characters.
"""
return subject.replace('\n', '\\n').replace('\r', '\\r') | [
"def",
"format_subject",
"(",
"self",
",",
"subject",
")",
":",
"return",
"subject",
".",
"replace",
"(",
"'\\n'",
",",
"'\\\\n'",
")",
".",
"replace",
"(",
"'\\r'",
",",
"'\\\\r'",
")"
] | [
129,
4
] | [
133,
64
] | python | en | ['en', 'error', 'th'] | False |
update_realmauditlog_values | (apps: StateApps, schema_editor: DatabaseSchemaEditor) |
This migration fixes two issues with the RealmAuditLog format for certain event types:
* The notifications_stream and signup_notifications_stream fields had the
Stream objects passed into `ujson.dumps()` and thus marshalled as a giant
JSON object, when the intent was to store the stream ID.
* T... |
This migration fixes two issues with the RealmAuditLog format for certain event types:
* The notifications_stream and signup_notifications_stream fields had the
Stream objects passed into `ujson.dumps()` and thus marshalled as a giant
JSON object, when the intent was to store the stream ID.
* T... | def update_realmauditlog_values(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
"""
This migration fixes two issues with the RealmAuditLog format for certain event types:
* The notifications_stream and signup_notifications_stream fields had the
Stream objects passed into `ujson.dumps()`... | [
"def",
"update_realmauditlog_values",
"(",
"apps",
":",
"StateApps",
",",
"schema_editor",
":",
"DatabaseSchemaEditor",
")",
"->",
"None",
":",
"RealmAuditLog",
"=",
"apps",
".",
"get_model",
"(",
"\"zerver\"",
",",
"\"RealmAuditLog\"",
")",
"# Constants from models.p... | [
9,
0
] | [
105,
45
] | python | en | ['en', 'error', 'th'] | False |
SimplerXMLGenerator.addQuickElement | (self, name, contents=None, attrs=None) | Convenience method for adding an element with no children | Convenience method for adding an element with no children | def addQuickElement(self, name, contents=None, attrs=None):
"Convenience method for adding an element with no children"
if attrs is None:
attrs = {}
self.startElement(name, attrs)
if contents is not None:
self.characters(contents)
self.endElement(name) | [
"def",
"addQuickElement",
"(",
"self",
",",
"name",
",",
"contents",
"=",
"None",
",",
"attrs",
"=",
"None",
")",
":",
"if",
"attrs",
"is",
"None",
":",
"attrs",
"=",
"{",
"}",
"self",
".",
"startElement",
"(",
"name",
",",
"attrs",
")",
"if",
"con... | [
13,
4
] | [
20,
29
] | python | en | ['en', 'en', 'en'] | True |
ugettext_noop | (message) |
A legacy compatibility wrapper for Unicode handling on Python 2.
Alias of gettext_noop() since Django 2.0.
|
A legacy compatibility wrapper for Unicode handling on Python 2.
Alias of gettext_noop() since Django 2.0.
| def ugettext_noop(message):
"""
A legacy compatibility wrapper for Unicode handling on Python 2.
Alias of gettext_noop() since Django 2.0.
"""
warnings.warn(
'django.utils.translation.ugettext_noop() is deprecated in favor of '
'django.utils.translation.gettext_noop().',
Remo... | [
"def",
"ugettext_noop",
"(",
"message",
")",
":",
"warnings",
".",
"warn",
"(",
"'django.utils.translation.ugettext_noop() is deprecated in favor of '",
"'django.utils.translation.gettext_noop().'",
",",
"RemovedInDjango40Warning",
",",
"stacklevel",
"=",
"2",
",",
")",
"retu... | [
77,
0
] | [
87,
32
] | python | en | ['en', 'error', 'th'] | False |
ugettext | (message) |
A legacy compatibility wrapper for Unicode handling on Python 2.
Alias of gettext() since Django 2.0.
|
A legacy compatibility wrapper for Unicode handling on Python 2.
Alias of gettext() since Django 2.0.
| def ugettext(message):
"""
A legacy compatibility wrapper for Unicode handling on Python 2.
Alias of gettext() since Django 2.0.
"""
warnings.warn(
'django.utils.translation.ugettext() is deprecated in favor of '
'django.utils.translation.gettext().',
RemovedInDjango40Warning... | [
"def",
"ugettext",
"(",
"message",
")",
":",
"warnings",
".",
"warn",
"(",
"'django.utils.translation.ugettext() is deprecated in favor of '",
"'django.utils.translation.gettext().'",
",",
"RemovedInDjango40Warning",
",",
"stacklevel",
"=",
"2",
",",
")",
"return",
"gettext... | [
94,
0
] | [
104,
27
] | python | en | ['en', 'error', 'th'] | False |
ungettext | (singular, plural, number) |
A legacy compatibility wrapper for Unicode handling on Python 2.
Alias of ngettext() since Django 2.0.
|
A legacy compatibility wrapper for Unicode handling on Python 2.
Alias of ngettext() since Django 2.0.
| def ungettext(singular, plural, number):
"""
A legacy compatibility wrapper for Unicode handling on Python 2.
Alias of ngettext() since Django 2.0.
"""
warnings.warn(
'django.utils.translation.ungettext() is deprecated in favor of '
'django.utils.translation.ngettext().',
Rem... | [
"def",
"ungettext",
"(",
"singular",
",",
"plural",
",",
"number",
")",
":",
"warnings",
".",
"warn",
"(",
"'django.utils.translation.ungettext() is deprecated in favor of '",
"'django.utils.translation.ngettext().'",
",",
"RemovedInDjango40Warning",
",",
"stacklevel",
"=",
... | [
111,
0
] | [
121,
45
] | python | en | ['en', 'error', 'th'] | False |
ugettext_lazy | (message) |
A legacy compatibility wrapper for Unicode handling on Python 2. Has been
Alias of gettext_lazy since Django 2.0.
|
A legacy compatibility wrapper for Unicode handling on Python 2. Has been
Alias of gettext_lazy since Django 2.0.
| def ugettext_lazy(message):
"""
A legacy compatibility wrapper for Unicode handling on Python 2. Has been
Alias of gettext_lazy since Django 2.0.
"""
warnings.warn(
'django.utils.translation.ugettext_lazy() is deprecated in favor of '
'django.utils.translation.gettext_lazy().',
... | [
"def",
"ugettext_lazy",
"(",
"message",
")",
":",
"warnings",
".",
"warn",
"(",
"'django.utils.translation.ugettext_lazy() is deprecated in favor of '",
"'django.utils.translation.gettext_lazy().'",
",",
"RemovedInDjango40Warning",
",",
"stacklevel",
"=",
"2",
",",
")",
"retu... | [
136,
0
] | [
146,
32
] | python | en | ['en', 'error', 'th'] | False |
ungettext_lazy | (singular, plural, number=None) |
A legacy compatibility wrapper for Unicode handling on Python 2.
An alias of ungettext_lazy() since Django 2.0.
|
A legacy compatibility wrapper for Unicode handling on Python 2.
An alias of ungettext_lazy() since Django 2.0.
| def ungettext_lazy(singular, plural, number=None):
"""
A legacy compatibility wrapper for Unicode handling on Python 2.
An alias of ungettext_lazy() since Django 2.0.
"""
warnings.warn(
'django.utils.translation.ungettext_lazy() is deprecated in favor of '
'django.utils.translation.n... | [
"def",
"ungettext_lazy",
"(",
"singular",
",",
"plural",
",",
"number",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"'django.utils.translation.ungettext_lazy() is deprecated in favor of '",
"'django.utils.translation.ngettext_lazy().'",
",",
"RemovedInDjango40Warning",... | [
204,
0
] | [
214,
50
] | python | en | ['en', 'error', 'th'] | False |
to_language | (locale) | Turn a locale name (en_US) into a language name (en-us). | Turn a locale name (en_US) into a language name (en-us). | def to_language(locale):
"""Turn a locale name (en_US) into a language name (en-us)."""
p = locale.find('_')
if p >= 0:
return locale[:p].lower() + '-' + locale[p + 1:].lower()
else:
return locale.lower() | [
"def",
"to_language",
"(",
"locale",
")",
":",
"p",
"=",
"locale",
".",
"find",
"(",
"'_'",
")",
"if",
"p",
">=",
"0",
":",
"return",
"locale",
"[",
":",
"p",
"]",
".",
"lower",
"(",
")",
"+",
"'-'",
"+",
"locale",
"[",
"p",
"+",
"1",
":",
... | [
262,
0
] | [
268,
29
] | python | en | ['es', 'en', 'en'] | True |
to_locale | (language) | Turn a language name (en-us) into a locale name (en_US). | Turn a language name (en-us) into a locale name (en_US). | def to_locale(language):
"""Turn a language name (en-us) into a locale name (en_US)."""
language, _, country = language.lower().partition('-')
if not country:
return language
# A language with > 2 characters after the dash only has its first
# character after the dash capitalized; e.g. sr-la... | [
"def",
"to_locale",
"(",
"language",
")",
":",
"language",
",",
"_",
",",
"country",
"=",
"language",
".",
"lower",
"(",
")",
".",
"partition",
"(",
"'-'",
")",
"if",
"not",
"country",
":",
"return",
"language",
"# A language with > 2 characters after the dash... | [
271,
0
] | [
284,
35
] | python | en | ['es', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.