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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
_get_encoding_from_headers | (headers: ResponseHeaders) | 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: 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:
retur... | [
"def",
"_get_encoding_from_headers",
"(",
"headers",
":",
"ResponseHeaders",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"headers",
"and",
"\"Content-Type\"",
"in",
"headers",
":",
"content_type",
",",
"params",
"=",
"cgi",
".",
"parse_header",
"(",
"he... | [
146,
0
] | [
153,
15
] | python | en | ['en', 'en', 'en'] | True |
_determine_base_url | (document: HTMLElement, page_url: 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 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: HTMLElement, page_url: 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 not have a va... | [
"def",
"_determine_base_url",
"(",
"document",
":",
"HTMLElement",
",",
"page_url",
":",
"str",
")",
"->",
"str",
":",
"for",
"base",
"in",
"document",
".",
"findall",
"(",
"\".//base\"",
")",
":",
"href",
"=",
"base",
".",
"get",
"(",
"\"href\"",
")",
... | [
156,
0
] | [
172,
19
] | python | en | ['en', 'no', 'en'] | True |
_clean_url_path_part | (part: str) |
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: 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",
":",
"str",
")",
"->",
"str",
":",
"# We unquote prior to quoting to make sure nothing is double quoted.",
"return",
"urllib",
".",
"parse",
".",
"quote",
"(",
"urllib",
".",
"parse",
".",
"unquote",
"(",
"part",
")",
")... | [
175,
0
] | [
180,
57
] | python | en | ['en', 'error', 'th'] | False |
_clean_file_url_path | (part: 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).
|
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: 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 path part might ... | [
"def",
"_clean_file_url_path",
"(",
"part",
":",
"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",
"# ex... | [
183,
0
] | [
193,
73
] | python | en | ['en', 'error', 'th'] | False |
_clean_url_path | (path: str, is_local_path: bool) |
Clean the path portion of a URL.
|
Clean the path portion of a URL.
| def _clean_url_path(path: str, is_local_path: 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
# revision strings in... | [
"def",
"_clean_url_path",
"(",
"path",
":",
"str",
",",
"is_local_path",
":",
"bool",
")",
"->",
"str",
":",
"if",
"is_local_path",
":",
"clean_func",
"=",
"_clean_file_url_path",
"else",
":",
"clean_func",
"=",
"_clean_url_path_part",
"# Split on the reserved chara... | [
200,
0
] | [
219,
33
] | python | en | ['en', 'error', 'th'] | False |
_clean_link | (url: 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.
|
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: 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;parameters?que... | [
"def",
"_clean_link",
"(",
"url",
":",
"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 ... | [
222,
0
] | [
234,
62
] | python | en | ['en', 'error', 'th'] | False |
_create_link_from_element | (
anchor: HTMLElement,
page_url: str,
base_url: 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: HTMLElement,
page_url: str,
base_url: str,
) -> Optional[Link]:
"""
Convert an anchor element in a simple repository page to a Link.
"""
href = anchor.get("href")
if not href:
return None
url = _clean_link(urllib.parse.urljoin(base_url,... | [
"def",
"_create_link_from_element",
"(",
"anchor",
":",
"HTMLElement",
",",
"page_url",
":",
"str",
",",
"base_url",
":",
"str",
",",
")",
"->",
"Optional",
"[",
"Link",
"]",
":",
"href",
"=",
"anchor",
".",
"get",
"(",
"\"href\"",
")",
"if",
"not",
"h... | [
237,
0
] | [
264,
15
] | python | en | ['en', 'error', 'th'] | False |
with_cached_html_pages | (
fn: 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: Callable[["HTMLPage"], Iterable[Link]],
) -> 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 `page.cache_link_parsing =... | [
"def",
"with_cached_html_pages",
"(",
"fn",
":",
"Callable",
"[",
"[",
"\"HTMLPage\"",
"]",
",",
"Iterable",
"[",
"Link",
"]",
"]",
",",
")",
"->",
"Callable",
"[",
"[",
"\"HTMLPage\"",
"]",
",",
"List",
"[",
"Link",
"]",
"]",
":",
"@",
"functools",
... | [
280,
0
] | [
299,
26
] | python | en | ['en', 'error', 'th'] | False |
parse_links | (page: "HTMLPage") |
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: "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
base_url = _de... | [
"def",
"parse_links",
"(",
"page",
":",
"\"HTMLPage\"",
")",
"->",
"Iterable",
"[",
"Link",
"]",
":",
"document",
"=",
"html5lib",
".",
"parse",
"(",
"page",
".",
"content",
",",
"transport_encoding",
"=",
"page",
".",
"encoding",
",",
"namespaceHTMLElements... | [
303,
0
] | [
323,
18
] | python | en | ['en', 'error', 'th'] | False |
HTMLPage.__init__ | (
self,
content: bytes,
encoding: Optional[str],
url: str,
cache_link_parsing: bool = True,
) |
: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: bytes,
encoding: Optional[str],
url: str,
cache_link_parsing: bool = True,
) -> None:
"""
:param encoding: the encoding to decode the given content.
:param url: the URL from which the HTML was downloaded.
:param cac... | [
"def",
"__init__",
"(",
"self",
",",
"content",
":",
"bytes",
",",
"encoding",
":",
"Optional",
"[",
"str",
"]",
",",
"url",
":",
"str",
",",
"cache_link_parsing",
":",
"bool",
"=",
"True",
",",
")",
"->",
"None",
":",
"self",
".",
"content",
"=",
... | [
329,
4
] | [
346,
52
] | python | en | ['en', 'error', 'th'] | False |
LinkCollector.create | (
cls, session: PipSession,
options: Values,
suppress_no_index: bool = False
) |
:param session: The Session to use to make requests.
:param suppress_no_index: Whether to ignore the --no-index option
when constructing the SearchScope object.
|
:param session: The Session to use to make requests.
:param suppress_no_index: Whether to ignore the --no-index option
when constructing the SearchScope object.
| def create(
cls, session: PipSession,
options: Values,
suppress_no_index: bool = False
) -> "LinkCollector":
"""
:param session: The Session to use to make requests.
:param suppress_no_index: Whether to ignore the --no-index option
when constructing the Se... | [
"def",
"create",
"(",
"cls",
",",
"session",
":",
"PipSession",
",",
"options",
":",
"Values",
",",
"suppress_no_index",
":",
"bool",
"=",
"False",
")",
"->",
"\"LinkCollector\"",
":",
"index_urls",
"=",
"[",
"options",
".",
"index_url",
"]",
"+",
"options... | [
452,
4
] | [
479,
29
] | python | en | ['en', 'error', 'th'] | False |
LinkCollector.fetch_page | (self, location: Link) |
Fetch an HTML page containing package links.
|
Fetch an HTML page containing package links.
| def fetch_page(self, location: Link) -> Optional[HTMLPage]:
"""
Fetch an HTML page containing package links.
"""
return _get_html_page(location, session=self.session) | [
"def",
"fetch_page",
"(",
"self",
",",
"location",
":",
"Link",
")",
"->",
"Optional",
"[",
"HTMLPage",
"]",
":",
"return",
"_get_html_page",
"(",
"location",
",",
"session",
"=",
"self",
".",
"session",
")"
] | [
485,
4
] | [
489,
61
] | python | en | ['en', 'error', 'th'] | False |
WKBReader.read | (self, wkb) | Return a GEOSGeometry for the given WKB buffer. | Return a GEOSGeometry for the given WKB buffer. | def read(self, wkb):
"Return a GEOSGeometry for the given WKB buffer."
return GEOSGeometry(super().read(wkb)) | [
"def",
"read",
"(",
"self",
",",
"wkb",
")",
":",
"return",
"GEOSGeometry",
"(",
"super",
"(",
")",
".",
"read",
"(",
"wkb",
")",
")"
] | [
15,
4
] | [
17,
46
] | python | en | ['en', 'en', 'en'] | True |
WKTReader.read | (self, wkt) | Return a GEOSGeometry for the given WKT string. | Return a GEOSGeometry for the given WKT string. | def read(self, wkt):
"Return a GEOSGeometry for the given WKT string."
return GEOSGeometry(super().read(wkt)) | [
"def",
"read",
"(",
"self",
",",
"wkt",
")",
":",
"return",
"GEOSGeometry",
"(",
"super",
"(",
")",
".",
"read",
"(",
"wkt",
")",
")"
] | [
21,
4
] | [
23,
46
] | python | en | ['en', 'en', 'en'] | True |
_wrapper | (args: Optional[List[str]] = None) | Central wrapper for all old entrypoints.
Historically pip has had several entrypoints defined. Because of issues
arising from PATH, sys.path, multiple Pythons, their interactions, and most
of them having a pip installed, users suffer every time an entrypoint gets
moved.
To alleviate this pain, and... | Central wrapper for all old entrypoints. | def _wrapper(args: Optional[List[str]] = None) -> int:
"""Central wrapper for all old entrypoints.
Historically pip has had several entrypoints defined. Because of issues
arising from PATH, sys.path, multiple Pythons, their interactions, and most
of them having a pip installed, users suffer every time ... | [
"def",
"_wrapper",
"(",
"args",
":",
"Optional",
"[",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"int",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"WARNING: pip is being invoked by an old script wrapper. This will \"",
"\"fail in a future version of ... | [
6,
0
] | [
26,
21
] | python | en | ['en', 'en', 'en'] | True |
_validate_clientsecrets | (clientsecrets_dict) | Validate parsed client secrets from a file.
Args:
clientsecrets_dict: dict, a dictionary holding the client secrets.
Returns:
tuple, a string of the client type and the information parsed
from the file.
| Validate parsed client secrets from a file. | def _validate_clientsecrets(clientsecrets_dict):
"""Validate parsed client secrets from a file.
Args:
clientsecrets_dict: dict, a dictionary holding the client secrets.
Returns:
tuple, a string of the client type and the information parsed
from the file.
"""
_INVALID_FILE_F... | [
"def",
"_validate_clientsecrets",
"(",
"clientsecrets_dict",
")",
":",
"_INVALID_FILE_FORMAT_MSG",
"=",
"(",
"'Invalid file format. See '",
"'https://developers.google.com/api-client-library/'",
"'python/guide/aaa_client_secrets'",
")",
"if",
"clientsecrets_dict",
"is",
"None",
":"... | [
67,
0
] | [
105,
35
] | python | en | ['en', 'en', 'en'] | True |
loadfile | (filename, cache=None) | Loading of client_secrets JSON file, optionally backed by a cache.
Typical cache storage would be App Engine memcache service,
but you can pass in any other cache client that implements
these methods:
* ``get(key, namespace=ns)``
* ``set(key, value, namespace=ns)``
Usage::
# without ... | Loading of client_secrets JSON file, optionally backed by a cache. | def loadfile(filename, cache=None):
"""Loading of client_secrets JSON file, optionally backed by a cache.
Typical cache storage would be App Engine memcache service,
but you can pass in any other cache client that implements
these methods:
* ``get(key, namespace=ns)``
* ``set(key, value, names... | [
"def",
"loadfile",
"(",
"filename",
",",
"cache",
"=",
"None",
")",
":",
"_SECRET_NAMESPACE",
"=",
"'oauth2client:secrets#ns'",
"if",
"not",
"cache",
":",
"return",
"_loadfile",
"(",
"filename",
")",
"obj",
"=",
"cache",
".",
"get",
"(",
"filename",
",",
"... | [
128,
0
] | [
172,
35
] | python | en | ['en', 'en', 'en'] | True |
_check_lazy_references | (apps, ignore=None) |
Ensure all lazy (i.e. string) model references have been resolved.
Lazy references are used in various places throughout Django, primarily in
related fields and model signals. Identify those common cases and provide
more helpful error messages for them.
The ignore parameter is used by StateApps t... |
Ensure all lazy (i.e. string) model references have been resolved. | def _check_lazy_references(apps, ignore=None):
"""
Ensure all lazy (i.e. string) model references have been resolved.
Lazy references are used in various places throughout Django, primarily in
related fields and model signals. Identify those common cases and provide
more helpful error messages for ... | [
"def",
"_check_lazy_references",
"(",
"apps",
",",
"ignore",
"=",
"None",
")",
":",
"pending_models",
"=",
"set",
"(",
"apps",
".",
"_pending_operations",
")",
"-",
"(",
"ignore",
"or",
"set",
"(",
")",
")",
"# Short circuit if there aren't any errors.",
"if",
... | [
88,
0
] | [
204,
36
] | python | en | ['en', 'error', 'th'] | False |
install_scripts.write_script | (self, script_name, contents, mode="t", *ignored) | Write an executable file to the scripts directory | Write an executable file to the scripts directory | def write_script(self, script_name, contents, mode="t", *ignored):
"""Write an executable file to the scripts directory"""
from setuptools.command.easy_install import chmod, current_umask
log.info("Installing %s script to %s", script_name, self.install_dir)
target = os.path.join(self.in... | [
"def",
"write_script",
"(",
"self",
",",
"script_name",
",",
"contents",
",",
"mode",
"=",
"\"t\"",
",",
"*",
"ignored",
")",
":",
"from",
"setuptools",
".",
"command",
".",
"easy_install",
"import",
"chmod",
",",
"current_umask",
"log",
".",
"info",
"(",
... | [
50,
4
] | [
64,
39
] | python | en | ['en', 'en', 'en'] | True |
StandardizedFeature.fit | (self, blocks, y=None) |
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
Returns:
:class:`StandardizedFeature`: an instance of this class with the
``self.scaler`` attribute fit to the ``bloc... |
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency. | def fit(self, blocks, y=None):
"""
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
Returns:
:class:`StandardizedFeature`: an instance of this class with the
`... | [
"def",
"fit",
"(",
"self",
",",
"blocks",
",",
"y",
"=",
"None",
")",
":",
"feature_array",
"=",
"self",
".",
"feature",
".",
"fit_transform",
"(",
"blocks",
")",
"self",
".",
"scaler",
"=",
"self",
".",
"scaler",
".",
"fit",
"(",
"feature_array",
")... | [
23,
4
] | [
44,
19
] | python | en | ['en', 'error', 'th'] | False |
StandardizedFeature.transform | (self, blocks, y=None) |
Transform an ordered sequence of blocks into a 2D features matrix with
shape (num blocks, num features) and standardized feature values.
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This isn't used, it's only here for API consistency.
... |
Transform an ordered sequence of blocks into a 2D features matrix with
shape (num blocks, num features) and standardized feature values. | def transform(self, blocks, y=None):
"""
Transform an ordered sequence of blocks into a 2D features matrix with
shape (num blocks, num features) and standardized feature values.
Args:
blocks (List[Block]): as output by :class:`Blockifier.blockify`
y (None): This ... | [
"def",
"transform",
"(",
"self",
",",
"blocks",
",",
"y",
"=",
"None",
")",
":",
"return",
"self",
".",
"scaler",
".",
"transform",
"(",
"self",
".",
"feature",
".",
"transform",
"(",
"blocks",
")",
")"
] | [
46,
4
] | [
60,
68
] | python | en | ['en', 'error', 'th'] | False |
DateField._check_fix_default_value | (self) |
Warn that using an actual date or datetime value is probably wrong;
it's only evaluated on server startup.
|
Warn that using an actual date or datetime value is probably wrong;
it's only evaluated on server startup.
| def _check_fix_default_value(self):
"""
Warn that using an actual date or datetime value is probably wrong;
it's only evaluated on server startup.
"""
if not self.has_default():
return []
now = timezone.now()
if not timezone.is_naive(now):
... | [
"def",
"_check_fix_default_value",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"has_default",
"(",
")",
":",
"return",
"[",
"]",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"if",
"not",
"timezone",
".",
"is_naive",
"(",
"now",
")",
":",
"now",... | [
1159,
4
] | [
1197,
17
] | python | en | ['en', 'error', 'th'] | False |
DateTimeField._check_fix_default_value | (self) |
Warn that using an actual date or datetime value is probably wrong;
it's only evaluated on server startup.
|
Warn that using an actual date or datetime value is probably wrong;
it's only evaluated on server startup.
| def _check_fix_default_value(self):
"""
Warn that using an actual date or datetime value is probably wrong;
it's only evaluated on server startup.
"""
if not self.has_default():
return []
now = timezone.now()
if not timezone.is_naive(now):
... | [
"def",
"_check_fix_default_value",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"has_default",
"(",
")",
":",
"return",
"[",
"]",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"if",
"not",
"timezone",
".",
"is_naive",
"(",
"now",
")",
":",
"now",... | [
1299,
4
] | [
1340,
17
] | python | en | ['en', 'error', 'th'] | False |
PositiveIntegerRelDbTypeMixin.rel_db_type | (self, connection) |
Return the data type that a related field pointing to this field should
use. In most cases, a foreign key pointing to a positive integer
primary key will have an integer column data type but some databases
(e.g. MySQL) have an unsigned integer type. In that case
(related_fields_... |
Return the data type that a related field pointing to this field should
use. In most cases, a foreign key pointing to a positive integer
primary key will have an integer column data type but some databases
(e.g. MySQL) have an unsigned integer type. In that case
(related_fields_... | def rel_db_type(self, connection):
"""
Return the data type that a related field pointing to this field should
use. In most cases, a foreign key pointing to a positive integer
primary key will have an integer column data type but some databases
(e.g. MySQL) have an unsigned integ... | [
"def",
"rel_db_type",
"(",
"self",
",",
"connection",
")",
":",
"if",
"connection",
".",
"features",
".",
"related_fields_match_type",
":",
"return",
"self",
".",
"db_type",
"(",
"connection",
")",
"else",
":",
"return",
"self",
".",
"integer_field_class",
"("... | [
2026,
4
] | [
2038,
76
] | python | en | ['en', 'error', 'th'] | False |
TimeField._check_fix_default_value | (self) |
Warn that using an actual date or datetime value is probably wrong;
it's only evaluated on server startup.
|
Warn that using an actual date or datetime value is probably wrong;
it's only evaluated on server startup.
| def _check_fix_default_value(self):
"""
Warn that using an actual date or datetime value is probably wrong;
it's only evaluated on server startup.
"""
if not self.has_default():
return []
now = timezone.now()
if not timezone.is_naive(now):
... | [
"def",
"_check_fix_default_value",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"has_default",
"(",
")",
":",
"return",
"[",
"]",
"now",
"=",
"timezone",
".",
"now",
"(",
")",
"if",
"not",
"timezone",
".",
"is_naive",
"(",
"now",
")",
":",
"now",... | [
2195,
4
] | [
2236,
17
] | python | en | ['en', 'error', 'th'] | False |
BinaryField.value_to_string | (self, obj) | Binary data is serialized as base64 | Binary data is serialized as base64 | def value_to_string(self, obj):
"""Binary data is serialized as base64"""
return b64encode(self.value_from_object(obj)).decode('ascii') | [
"def",
"value_to_string",
"(",
"self",
",",
"obj",
")",
":",
"return",
"b64encode",
"(",
"self",
".",
"value_from_object",
"(",
"obj",
")",
")",
".",
"decode",
"(",
"'ascii'",
")"
] | [
2385,
4
] | [
2387,
69
] | python | en | ['en', 'en', 'en'] | True |
get_srid_info | (srid, connection) |
Return 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.
|
Return 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):
"""
Return 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.
"""
from django.contrib.gis.gdal import SpatialRef... | [
"def",
"get_srid_info",
"(",
"srid",
",",
"connection",
")",
":",
"from",
"django",
".",
"contrib",
".",
"gis",
".",
"gdal",
"import",
"SpatialReference",
"global",
"_srid_cache",
"try",
":",
"# The SpatialRefSys model for the spatial backend.",
"SpatialRefSys",
"=",
... | [
22,
0
] | [
52,
35
] | python | en | ['en', 'error', 'th'] | False |
BaseSpatialField.__init__ | (self, verbose_name=None, srid=4326, spatial_index=True, **kwargs) |
The initialization function for base spatial 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 ... |
The initialization function for base spatial fields. Takes the following
as keyword arguments: | def __init__(self, verbose_name=None, srid=4326, spatial_index=True, **kwargs):
"""
The initialization function for base spatial fields. Takes the following
as keyword arguments:
srid:
The spatial reference system identifier, an OGC standard.
Defaults to 4326 (WGS84).
... | [
"def",
"__init__",
"(",
"self",
",",
"verbose_name",
"=",
"None",
",",
"srid",
"=",
"4326",
",",
"spatial_index",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Setting the index flag with the value of the `spatial_index` keyword.",
"self",
".",
"spatial_index",... | [
66,
4
] | [
92,
34
] | python | en | ['en', 'error', 'th'] | False |
BaseSpatialField.geodetic | (self, connection) |
Return true if this field's SRID corresponds with a coordinate
system that uses non-projected units (e.g., latitude/longitude).
|
Return true if this field's SRID corresponds with a coordinate
system that uses non-projected units (e.g., latitude/longitude).
| def geodetic(self, connection):
"""
Return true if this field's SRID corresponds with a coordinate
system that uses non-projected units (e.g., latitude/longitude).
"""
return get_srid_info(self.srid, connection).geodetic | [
"def",
"geodetic",
"(",
"self",
",",
"connection",
")",
":",
"return",
"get_srid_info",
"(",
"self",
".",
"srid",
",",
"connection",
")",
".",
"geodetic"
] | [
115,
4
] | [
120,
60
] | python | en | ['en', 'error', 'th'] | False |
BaseSpatialField.get_placeholder | (self, value, compiler, connection) |
Return the placeholder for the spatial column for the
given value.
|
Return the placeholder for the spatial column for the
given value.
| def get_placeholder(self, value, compiler, connection):
"""
Return the placeholder for the spatial column for the
given value.
"""
return connection.ops.get_geom_placeholder(self, value, compiler) | [
"def",
"get_placeholder",
"(",
"self",
",",
"value",
",",
"compiler",
",",
"connection",
")",
":",
"return",
"connection",
".",
"ops",
".",
"get_geom_placeholder",
"(",
"self",
",",
"value",
",",
"compiler",
")"
] | [
122,
4
] | [
127,
73
] | python | en | ['en', 'error', 'th'] | False |
BaseSpatialField.get_srid | (self, obj) |
Return the default SRID for the given geometry or raster, taking into
account the SRID set for the field. For example, if the input geometry
or raster doesn't have an SRID, then the SRID of the field will be
returned.
|
Return the default SRID for the given geometry or raster, taking into
account the SRID set for the field. For example, if the input geometry
or raster doesn't have an SRID, then the SRID of the field will be
returned.
| def get_srid(self, obj):
"""
Return the default SRID for the given geometry or raster, taking into
account the SRID set for the field. For example, if the input geometry
or raster doesn't have an SRID, then the SRID of the field will be
returned.
"""
srid = obj.sr... | [
"def",
"get_srid",
"(",
"self",
",",
"obj",
")",
":",
"srid",
"=",
"obj",
".",
"srid",
"# SRID of given geometry.",
"if",
"srid",
"is",
"None",
"or",
"self",
".",
"srid",
"==",
"-",
"1",
"or",
"(",
"srid",
"==",
"-",
"1",
"and",
"self",
".",
"srid"... | [
129,
4
] | [
140,
23
] | python | en | ['en', 'error', 'th'] | False |
BaseSpatialField.get_raster_prep_value | (self, value, is_candidate) |
Return a GDALRaster if conversion is successful, otherwise return None.
|
Return a GDALRaster if conversion is successful, otherwise return None.
| def get_raster_prep_value(self, value, is_candidate):
"""
Return a GDALRaster if conversion is successful, otherwise return None.
"""
if isinstance(value, gdal.GDALRaster):
return value
elif is_candidate:
try:
return gdal.GDALRaster(value)
... | [
"def",
"get_raster_prep_value",
"(",
"self",
",",
"value",
",",
"is_candidate",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"gdal",
".",
"GDALRaster",
")",
":",
"return",
"value",
"elif",
"is_candidate",
":",
"try",
":",
"return",
"gdal",
".",
"GDALRa... | [
154,
4
] | [
169,
98
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.__init__ | (self, verbose_name=None, dim=2, geography=False, *, extent=(-180.0, -90.0, 180.0, 90.0),
tolerance=0.05, **kwargs) |
The initialization function for geometry fields. In addition to the
parameters from BaseSpatialField, it takes the following as keyword
arguments:
dim:
The number of dimensions for this geometry. Defaults to 2.
extent:
Customize the extent, in a 4-tuple of W... |
The initialization function for geometry fields. In addition to the
parameters from BaseSpatialField, it takes the following as keyword
arguments: | def __init__(self, verbose_name=None, dim=2, geography=False, *, extent=(-180.0, -90.0, 180.0, 90.0),
tolerance=0.05, **kwargs):
"""
The initialization function for geometry fields. In addition to the
parameters from BaseSpatialField, it takes the following as keyword
ar... | [
"def",
"__init__",
"(",
"self",
",",
"verbose_name",
"=",
"None",
",",
"dim",
"=",
"2",
",",
"geography",
"=",
"False",
",",
"*",
",",
"extent",
"=",
"(",
"-",
"180.0",
",",
"-",
"90.0",
",",
"180.0",
",",
"90.0",
")",
",",
"tolerance",
"=",
"0.0... | [
210,
4
] | [
240,
61
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.select_format | (self, compiler, sql, params) |
Return the selection format string, depending on the requirements
of the spatial backend. For example, Oracle and MySQL require custom
selection formats in order to retrieve geometries in OGC WKB.
|
Return the selection format string, depending on the requirements
of the spatial backend. For example, Oracle and MySQL require custom
selection formats in order to retrieve geometries in OGC WKB.
| def select_format(self, compiler, sql, params):
"""
Return the selection format string, depending on the requirements
of the spatial backend. For example, Oracle and MySQL require custom
selection formats in order to retrieve geometries in OGC WKB.
"""
if not compiler.que... | [
"def",
"select_format",
"(",
"self",
",",
"compiler",
",",
"sql",
",",
"params",
")",
":",
"if",
"not",
"compiler",
".",
"query",
".",
"subquery",
":",
"return",
"compiler",
".",
"connection",
".",
"ops",
".",
"select",
"%",
"sql",
",",
"params",
"retu... | [
272,
4
] | [
280,
26
] | python | en | ['en', 'error', 'th'] | False |
main | (_) | Train a word2vec model. | Train a word2vec model. | def main(_):
"""Train a word2vec model."""
if not FLAGS.train_data or not FLAGS.eval_data or not FLAGS.save_path:
print("--train_data --eval_data and --save_path must be specified.")
sys.exit(1)
opts = Options()
with tf.Graph().as_default(), tf.Session() as session:
with tf.device("/cpu:0"):
m... | [
"def",
"main",
"(",
"_",
")",
":",
"if",
"not",
"FLAGS",
".",
"train_data",
"or",
"not",
"FLAGS",
".",
"eval_data",
"or",
"not",
"FLAGS",
".",
"save_path",
":",
"print",
"(",
"\"--train_data --eval_data and --save_path must be specified.\"",
")",
"sys",
".",
"... | [
510,
0
] | [
531,
28
] | python | en | ['en', 'ca', 'en'] | True |
Word2Vec.read_analogies | (self) | Reads through the analogy question file.
Returns:
questions: a [n, 4] numpy array containing the analogy question's
word ids.
questions_skipped: questions skipped due to unknown words.
| Reads through the analogy question file. | def read_analogies(self):
"""Reads through the analogy question file.
Returns:
questions: a [n, 4] numpy array containing the analogy question's
word ids.
questions_skipped: questions skipped due to unknown words.
"""
questions = []
questions_skipped = 0
with open(s... | [
"def",
"read_analogies",
"(",
"self",
")",
":",
"questions",
"=",
"[",
"]",
"questions_skipped",
"=",
"0",
"with",
"open",
"(",
"self",
".",
"_options",
".",
"eval_data",
",",
"\"rb\"",
")",
"as",
"analogy_f",
":",
"for",
"line",
"in",
"analogy_f",
":",
... | [
169,
2
] | [
192,
65
] | python | en | ['en', 'en', 'en'] | True |
Word2Vec.forward | (self, examples, labels) | Build the graph for the forward pass. | Build the graph for the forward pass. | def forward(self, examples, labels):
"""Build the graph for the forward pass."""
opts = self._options
# Declare all variables we need.
# Embedding: [vocab_size, emb_dim]
init_width = 0.5 / opts.emb_dim
emb = tf.Variable(
tf.random_uniform(
[opts.vocab_size, opts.emb_dim], -i... | [
"def",
"forward",
"(",
"self",
",",
"examples",
",",
"labels",
")",
":",
"opts",
"=",
"self",
".",
"_options",
"# Declare all variables we need.",
"# Embedding: [vocab_size, emb_dim]",
"init_width",
"=",
"0.5",
"/",
"opts",
".",
"emb_dim",
"emb",
"=",
"tf",
".",... | [
194,
2
] | [
257,
38
] | python | en | ['en', 'en', 'en'] | True |
Word2Vec.nce_loss | (self, true_logits, sampled_logits) | Build the graph for the NCE loss. | Build the graph for the NCE loss. | def nce_loss(self, true_logits, sampled_logits):
"""Build the graph for the NCE loss."""
# cross-entropy(logits, labels)
opts = self._options
true_xent = tf.nn.sigmoid_cross_entropy_with_logits(
labels=tf.ones_like(true_logits), logits=true_logits)
sampled_xent = tf.nn.sigmoid_cross_entropy... | [
"def",
"nce_loss",
"(",
"self",
",",
"true_logits",
",",
"sampled_logits",
")",
":",
"# cross-entropy(logits, labels)",
"opts",
"=",
"self",
".",
"_options",
"true_xent",
"=",
"tf",
".",
"nn",
".",
"sigmoid_cross_entropy_with_logits",
"(",
"labels",
"=",
"tf",
"... | [
259,
2
] | [
273,
26
] | python | en | ['en', 'en', 'en'] | True |
Word2Vec.optimize | (self, loss) | Build the graph to optimize the loss function. | Build the graph to optimize the loss function. | def optimize(self, loss):
"""Build the graph to optimize the loss function."""
# Optimizer nodes.
# Linear learning rate decay.
opts = self._options
words_to_train = float(opts.words_per_epoch * opts.epochs_to_train)
lr = opts.learning_rate * tf.maximum(
0.0001, 1.0 - tf.cast(self._word... | [
"def",
"optimize",
"(",
"self",
",",
"loss",
")",
":",
"# Optimizer nodes.",
"# Linear learning rate decay.",
"opts",
"=",
"self",
".",
"_options",
"words_to_train",
"=",
"float",
"(",
"opts",
".",
"words_per_epoch",
"*",
"opts",
".",
"epochs_to_train",
")",
"lr... | [
275,
2
] | [
289,
23
] | python | en | ['en', 'en', 'en'] | True |
Word2Vec.build_eval_graph | (self) | Build the eval graph. | Build the eval graph. | def build_eval_graph(self):
"""Build the eval graph."""
# Eval graph
# Each analogy task is to predict the 4th word (d) given three
# words: a, b, c. E.g., a=italy, b=rome, c=france, we should
# predict d=paris.
# The eval feeds three vectors of word ids for a, b, c, each of
# which is of... | [
"def",
"build_eval_graph",
"(",
"self",
")",
":",
"# Eval graph",
"# Each analogy task is to predict the 4th word (d) given three",
"# words: a, b, c. E.g., a=italy, b=rome, c=france, we should",
"# predict d=paris.",
"# The eval feeds three vectors of word ids for a, b, c, each of",
"# which... | [
291,
2
] | [
343,
33
] | python | en | ['en', 'en', 'en'] | True |
Word2Vec.build_graph | (self) | Build the graph for the full model. | Build the graph for the full model. | def build_graph(self):
"""Build the graph for the full model."""
opts = self._options
# The training data. A text file.
(words, counts, words_per_epoch, self._epoch, self._words, examples,
labels) = word2vec.skipgram_word2vec(filename=opts.train_data,
batch... | [
"def",
"build_graph",
"(",
"self",
")",
":",
"opts",
"=",
"self",
".",
"_options",
"# The training data. A text file.",
"(",
"words",
",",
"counts",
",",
"words_per_epoch",
",",
"self",
".",
"_epoch",
",",
"self",
".",
"_words",
",",
"examples",
",",
"labels... | [
345,
2
] | [
375,
33
] | python | en | ['en', 'en', 'en'] | True |
Word2Vec.save_vocab | (self) | Save the vocabulary to a file so the model can be reloaded. | Save the vocabulary to a file so the model can be reloaded. | def save_vocab(self):
"""Save the vocabulary to a file so the model can be reloaded."""
opts = self._options
with open(os.path.join(opts.save_path, "vocab.txt"), "w") as f:
for i in xrange(opts.vocab_size):
vocab_word = tf.compat.as_text(opts.vocab_words[i]).encode("utf-8")
f.write("%s... | [
"def",
"save_vocab",
"(",
"self",
")",
":",
"opts",
"=",
"self",
".",
"_options",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"opts",
".",
"save_path",
",",
"\"vocab.txt\"",
")",
",",
"\"w\"",
")",
"as",
"f",
":",
"for",
"i",
"in",
... | [
377,
2
] | [
385,
78
] | python | en | ['en', 'en', 'en'] | True |
Word2Vec.train | (self) | Train the model. | Train the model. | def train(self):
"""Train the model."""
opts = self._options
initial_epoch, initial_words = self._session.run([self._epoch, self._words])
summary_op = tf.summary.merge_all()
summary_writer = tf.summary.FileWriter(opts.save_path, self._session.graph)
workers = []
for _ in xrange(opts.concur... | [
"def",
"train",
"(",
"self",
")",
":",
"opts",
"=",
"self",
".",
"_options",
"initial_epoch",
",",
"initial_words",
"=",
"self",
".",
"_session",
".",
"run",
"(",
"[",
"self",
".",
"_epoch",
",",
"self",
".",
"_words",
"]",
")",
"summary_op",
"=",
"t... | [
394,
2
] | [
435,
16
] | python | en | ['en', 'it', 'en'] | True |
Word2Vec._predict | (self, analogy) | Predict the top 4 answers for analogy questions. | Predict the top 4 answers for analogy questions. | def _predict(self, analogy):
"""Predict the top 4 answers for analogy questions."""
idx, = self._session.run([self._analogy_pred_idx], {
self._analogy_a: analogy[:, 0],
self._analogy_b: analogy[:, 1],
self._analogy_c: analogy[:, 2]
})
return idx | [
"def",
"_predict",
"(",
"self",
",",
"analogy",
")",
":",
"idx",
",",
"=",
"self",
".",
"_session",
".",
"run",
"(",
"[",
"self",
".",
"_analogy_pred_idx",
"]",
",",
"{",
"self",
".",
"_analogy_a",
":",
"analogy",
"[",
":",
",",
"0",
"]",
",",
"s... | [
437,
2
] | [
444,
14
] | python | en | ['en', 'en', 'en'] | True |
Word2Vec.eval | (self) | Evaluate analogy questions and reports accuracy. | Evaluate analogy questions and reports accuracy. | def eval(self):
"""Evaluate analogy questions and reports accuracy."""
# How many questions we get right at precision@1.
correct = 0
try:
total = self._analogy_questions.shape[0]
except AttributeError as e:
raise AttributeError("Need to read analogy questions.")
start = 0
whil... | [
"def",
"eval",
"(",
"self",
")",
":",
"# How many questions we get right at precision@1.",
"correct",
"=",
"0",
"try",
":",
"total",
"=",
"self",
".",
"_analogy_questions",
".",
"shape",
"[",
"0",
"]",
"except",
"AttributeError",
"as",
"e",
":",
"raise",
"Attr... | [
446,
2
] | [
477,
71
] | python | en | ['en', 'en', 'en'] | True |
Word2Vec.analogy | (self, w0, w1, w2) | Predict word w3 as in w0:w1 vs w2:w3. | Predict word w3 as in w0:w1 vs w2:w3. | def analogy(self, w0, w1, w2):
"""Predict word w3 as in w0:w1 vs w2:w3."""
wid = np.array([[self._word2id.get(w, 0) for w in [w0, w1, w2]]])
idx = self._predict(wid)
for c in [self._id2word[i] for i in idx[0, :]]:
if c not in [w0, w1, w2]:
print(c)
return
print("unknown") | [
"def",
"analogy",
"(",
"self",
",",
"w0",
",",
"w1",
",",
"w2",
")",
":",
"wid",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"self",
".",
"_word2id",
".",
"get",
"(",
"w",
",",
"0",
")",
"for",
"w",
"in",
"[",
"w0",
",",
"w1",
",",
"w2",
"]",... | [
479,
2
] | [
487,
20
] | python | pl | ['en', 'pl', 'pl'] | True |
Word2Vec.nearby | (self, words, num=20) | Prints out nearby words given a list of words. | Prints out nearby words given a list of words. | def nearby(self, words, num=20):
"""Prints out nearby words given a list of words."""
ids = np.array([self._word2id.get(x, 0) for x in words])
vals, idx = self._session.run(
[self._nearby_val, self._nearby_idx], {self._nearby_word: ids})
for i in xrange(len(words)):
print("\n%s\n==========... | [
"def",
"nearby",
"(",
"self",
",",
"words",
",",
"num",
"=",
"20",
")",
":",
"ids",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"_word2id",
".",
"get",
"(",
"x",
",",
"0",
")",
"for",
"x",
"in",
"words",
"]",
")",
"vals",
",",
"idx",
"=... | [
489,
2
] | [
497,
66
] | python | en | ['en', 'en', 'en'] | True |
_dump_arg_defaults | (kwargs) | Inject default arguments for dump functions. | Inject default arguments for dump functions. | def _dump_arg_defaults(kwargs):
"""Inject default arguments for dump functions."""
if current_app:
kwargs.setdefault('cls', current_app.json_encoder)
if not current_app.config['JSON_AS_ASCII']:
kwargs.setdefault('ensure_ascii', False)
kwargs.setdefault('sort_keys', current_ap... | [
"def",
"_dump_arg_defaults",
"(",
"kwargs",
")",
":",
"if",
"current_app",
":",
"kwargs",
".",
"setdefault",
"(",
"'cls'",
",",
"current_app",
".",
"json_encoder",
")",
"if",
"not",
"current_app",
".",
"config",
"[",
"'JSON_AS_ASCII'",
"]",
":",
"kwargs",
".... | [
90,
0
] | [
99,
45
] | python | da | ['da', 'fr', 'en'] | False |
_load_arg_defaults | (kwargs) | Inject default arguments for load functions. | Inject default arguments for load functions. | def _load_arg_defaults(kwargs):
"""Inject default arguments for load functions."""
if current_app:
kwargs.setdefault('cls', current_app.json_decoder)
else:
kwargs.setdefault('cls', JSONDecoder) | [
"def",
"_load_arg_defaults",
"(",
"kwargs",
")",
":",
"if",
"current_app",
":",
"kwargs",
".",
"setdefault",
"(",
"'cls'",
",",
"current_app",
".",
"json_decoder",
")",
"else",
":",
"kwargs",
".",
"setdefault",
"(",
"'cls'",
",",
"JSONDecoder",
")"
] | [
102,
0
] | [
107,
45
] | python | en | ['da', 'en', 'en'] | True |
dumps | (obj, **kwargs) | Serialize ``obj`` to a JSON formatted ``str`` by using the application's
configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an
application on the stack.
This function can return ``unicode`` strings or ascii-only bytestrings by
default which coerce into unicode strings automatically. Th... | Serialize ``obj`` to a JSON formatted ``str`` by using the application's
configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an
application on the stack. | def dumps(obj, **kwargs):
"""Serialize ``obj`` to a JSON formatted ``str`` by using the application's
configured encoder (:attr:`~flask.Flask.json_encoder`) if there is an
application on the stack.
This function can return ``unicode`` strings or ascii-only bytestrings by
default which coerce into u... | [
"def",
"dumps",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"_dump_arg_defaults",
"(",
"kwargs",
")",
"encoding",
"=",
"kwargs",
".",
"pop",
"(",
"'encoding'",
",",
"None",
")",
"rv",
"=",
"_json",
".",
"dumps",
"(",
"obj",
",",
"*",
"*",
"kwarg... | [
110,
0
] | [
125,
13
] | python | en | ['en', 'en', 'en'] | True |
dump | (obj, fp, **kwargs) | Like :func:`dumps` but writes into a file object. | Like :func:`dumps` but writes into a file object. | def dump(obj, fp, **kwargs):
"""Like :func:`dumps` but writes into a file object."""
_dump_arg_defaults(kwargs)
encoding = kwargs.pop('encoding', None)
if encoding is not None:
fp = _wrap_writer_for_text(fp, encoding)
_json.dump(obj, fp, **kwargs) | [
"def",
"dump",
"(",
"obj",
",",
"fp",
",",
"*",
"*",
"kwargs",
")",
":",
"_dump_arg_defaults",
"(",
"kwargs",
")",
"encoding",
"=",
"kwargs",
".",
"pop",
"(",
"'encoding'",
",",
"None",
")",
"if",
"encoding",
"is",
"not",
"None",
":",
"fp",
"=",
"_... | [
128,
0
] | [
134,
33
] | python | en | ['en', 'haw', 'en'] | True |
loads | (s, **kwargs) | Unserialize a JSON object from a string ``s`` by using the application's
configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an
application on the stack.
| Unserialize a JSON object from a string ``s`` by using the application's
configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an
application on the stack.
| def loads(s, **kwargs):
"""Unserialize a JSON object from a string ``s`` by using the application's
configured decoder (:attr:`~flask.Flask.json_decoder`) if there is an
application on the stack.
"""
_load_arg_defaults(kwargs)
if isinstance(s, bytes):
s = s.decode(kwargs.pop('encoding', ... | [
"def",
"loads",
"(",
"s",
",",
"*",
"*",
"kwargs",
")",
":",
"_load_arg_defaults",
"(",
"kwargs",
")",
"if",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"s",
"=",
"s",
".",
"decode",
"(",
"kwargs",
".",
"pop",
"(",
"'encoding'",
",",
"None",
... | [
137,
0
] | [
145,
35
] | python | en | ['en', 'en', 'en'] | True |
load | (fp, **kwargs) | Like :func:`loads` but reads from a file object.
| Like :func:`loads` but reads from a file object.
| def load(fp, **kwargs):
"""Like :func:`loads` but reads from a file object.
"""
_load_arg_defaults(kwargs)
if not PY2:
fp = _wrap_reader_for_text(fp, kwargs.pop('encoding', None) or 'utf-8')
return _json.load(fp, **kwargs) | [
"def",
"load",
"(",
"fp",
",",
"*",
"*",
"kwargs",
")",
":",
"_load_arg_defaults",
"(",
"kwargs",
")",
"if",
"not",
"PY2",
":",
"fp",
"=",
"_wrap_reader_for_text",
"(",
"fp",
",",
"kwargs",
".",
"pop",
"(",
"'encoding'",
",",
"None",
")",
"or",
"'utf... | [
148,
0
] | [
154,
35
] | python | en | ['en', 'en', 'en'] | True |
htmlsafe_dumps | (obj, **kwargs) | Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this... | Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this... | def htmlsafe_dumps(obj, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this fu... | [
"def",
"htmlsafe_dumps",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"rv",
"=",
"dumps",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
".",
"replace",
"(",
"u'<'",
",",
"u'\\\\u003c'",
")",
".",
"replace",
"(",
"u'>'",
",",
"u'\\\\u003e'",
")",
".",... | [
157,
0
] | [
189,
13
] | python | en | ['en', 'en', 'en'] | True |
htmlsafe_dump | (obj, fp, **kwargs) | Like :func:`htmlsafe_dumps` but writes into a file object. | Like :func:`htmlsafe_dumps` but writes into a file object. | def htmlsafe_dump(obj, fp, **kwargs):
"""Like :func:`htmlsafe_dumps` but writes into a file object."""
fp.write(text_type(htmlsafe_dumps(obj, **kwargs))) | [
"def",
"htmlsafe_dump",
"(",
"obj",
",",
"fp",
",",
"*",
"*",
"kwargs",
")",
":",
"fp",
".",
"write",
"(",
"text_type",
"(",
"htmlsafe_dumps",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
")",
")"
] | [
192,
0
] | [
194,
54
] | python | en | ['en', 'en', 'en'] | True |
jsonify | (*args, **kwargs) | This function wraps :func:`dumps` to add a few enhancements that make
life easier. It turns the JSON output into a :class:`~flask.Response`
object with the :mimetype:`application/json` mimetype. For convenience, it
also converts multiple arguments into an array or multiple keyword arguments
into a dic... | This function wraps :func:`dumps` to add a few enhancements that make
life easier. It turns the JSON output into a :class:`~flask.Response`
object with the :mimetype:`application/json` mimetype. For convenience, it
also converts multiple arguments into an array or multiple keyword arguments
into a dic... | def jsonify(*args, **kwargs):
"""This function wraps :func:`dumps` to add a few enhancements that make
life easier. It turns the JSON output into a :class:`~flask.Response`
object with the :mimetype:`application/json` mimetype. For convenience, it
also converts multiple arguments into an array or mult... | [
"def",
"jsonify",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"indent",
"=",
"None",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
"if",
"current_app",
".",
"config",
"[",
"'JSONIFY_PRETTYPRINT_REGULAR'",
"]",
"and",
"not",
"request",
".",
"... | [
197,
0
] | [
264,
5
] | python | en | ['en', 'en', 'en'] | True |
JSONEncoder.default | (self, o) | Implement this method in a subclass such that it returns a
serializable object for ``o``, or calls the base implementation (to
raise a :exc:`TypeError`).
For example, to support arbitrary iterators, you could implement
default like this::
def default(self, o):
... | Implement this method in a subclass such that it returns a
serializable object for ``o``, or calls the base implementation (to
raise a :exc:`TypeError`). | def default(self, o):
"""Implement this method in a subclass such that it returns a
serializable object for ``o``, or calls the base implementation (to
raise a :exc:`TypeError`).
For example, to support arbitrary iterators, you could implement
default like this::
de... | [
"def",
"default",
"(",
"self",
",",
"o",
")",
":",
"if",
"isinstance",
"(",
"o",
",",
"date",
")",
":",
"return",
"http_date",
"(",
"o",
".",
"timetuple",
"(",
")",
")",
"if",
"isinstance",
"(",
"o",
",",
"uuid",
".",
"UUID",
")",
":",
"return",
... | [
56,
4
] | [
79,
49
] | python | en | ['en', 'en', 'en'] | True |
_group_matching | (tlist, cls) | Groups Tokens that have beginning and end. | Groups Tokens that have beginning and end. | def _group_matching(tlist, cls):
"""Groups Tokens that have beginning and end."""
opens = []
tidx_offset = 0
for idx, token in enumerate(list(tlist)):
tidx = idx - tidx_offset
if token.is_whitespace:
# ~50% of tokens will be whitespace. Will checking early
# for ... | [
"def",
"_group_matching",
"(",
"tlist",
",",
"cls",
")",
":",
"opens",
"=",
"[",
"]",
"tidx_offset",
"=",
"0",
"for",
"idx",
",",
"token",
"in",
"enumerate",
"(",
"list",
"(",
"tlist",
")",
")",
":",
"tidx",
"=",
"idx",
"-",
"tidx_offset",
"if",
"t... | [
16,
0
] | [
48,
47
] | python | en | ['en', 'en', 'en'] | True |
group_order | (tlist) | Group together Identifier and Asc/Desc token | Group together Identifier and Asc/Desc token | def group_order(tlist):
"""Group together Identifier and Asc/Desc token"""
tidx, token = tlist.token_next_by(t=T.Keyword.Order)
while token:
pidx, prev_ = tlist.token_prev(tidx)
if imt(prev_, i=sql.Identifier, t=T.Number):
tlist.group_tokens(sql.Identifier, pidx, tidx)
... | [
"def",
"group_order",
"(",
"tlist",
")",
":",
"tidx",
",",
"token",
"=",
"tlist",
".",
"token_next_by",
"(",
"t",
"=",
"T",
".",
"Keyword",
".",
"Order",
")",
"while",
"token",
":",
"pidx",
",",
"prev_",
"=",
"tlist",
".",
"token_prev",
"(",
"tidx",
... | [
352,
0
] | [
360,
70
] | python | en | ['en', 'en', 'en'] | True |
_group | (tlist, cls, match,
valid_prev=lambda t: True,
valid_next=lambda t: True,
post=None,
extend=True,
recurse=True
) | Groups together tokens that are joined by a middle token. i.e. x < y | Groups together tokens that are joined by a middle token. i.e. x < y | def _group(tlist, cls, match,
valid_prev=lambda t: True,
valid_next=lambda t: True,
post=None,
extend=True,
recurse=True
):
"""Groups together tokens that are joined by a middle token. i.e. x < y"""
tidx_offset = 0
pidx, prev_ = None, None
... | [
"def",
"_group",
"(",
"tlist",
",",
"cls",
",",
"match",
",",
"valid_prev",
"=",
"lambda",
"t",
":",
"True",
",",
"valid_next",
"=",
"lambda",
"t",
":",
"True",
",",
"post",
"=",
"None",
",",
"extend",
"=",
"True",
",",
"recurse",
"=",
"True",
")",... | [
421,
0
] | [
453,
33
] | python | en | ['en', 'en', 'en'] | True |
CookieStorage._get | (self, *args, **kwargs) |
Retrieve a list of messages from the messages cookie. If the
not_finished sentinel value is found at the end of the message list,
remove it and return a result indicating that not all messages were
retrieved by this storage.
|
Retrieve a list of messages from the messages cookie. If the
not_finished sentinel value is found at the end of the message list,
remove it and return a result indicating that not all messages were
retrieved by this storage.
| def _get(self, *args, **kwargs):
"""
Retrieve a list of messages from the messages cookie. If the
not_finished sentinel value is found at the end of the message list,
remove it and return a result indicating that not all messages were
retrieved by this storage.
"""
... | [
"def",
"_get",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"request",
".",
"COOKIES",
".",
"get",
"(",
"self",
".",
"cookie_name",
")",
"messages",
"=",
"self",
".",
"_decode",
"(",
"data",
")",
"al... | [
78,
4
] | [
91,
38
] | python | en | ['en', 'error', 'th'] | False |
CookieStorage._update_cookie | (self, encoded_data, response) |
Either set the cookie with the encoded data if there is any data to
store, or delete the cookie.
|
Either set the cookie with the encoded data if there is any data to
store, or delete the cookie.
| def _update_cookie(self, encoded_data, response):
"""
Either set the cookie with the encoded data if there is any data to
store, or delete the cookie.
"""
if encoded_data:
response.set_cookie(
self.cookie_name, encoded_data,
domain=sett... | [
"def",
"_update_cookie",
"(",
"self",
",",
"encoded_data",
",",
"response",
")",
":",
"if",
"encoded_data",
":",
"response",
".",
"set_cookie",
"(",
"self",
".",
"cookie_name",
",",
"encoded_data",
",",
"domain",
"=",
"settings",
".",
"SESSION_COOKIE_DOMAIN",
... | [
93,
4
] | [
111,
13
] | python | en | ['en', 'error', 'th'] | False |
CookieStorage._store | (self, messages, response, remove_oldest=True, *args, **kwargs) |
Store the messages to a cookie and return a list of any messages which
could not be stored.
If the encoded data is larger than ``max_cookie_size``, remove
messages until the data fits (these are the messages which are
returned), and add the not_finished sentinel value to indica... |
Store the messages to a cookie and return a list of any messages which
could not be stored. | def _store(self, messages, response, remove_oldest=True, *args, **kwargs):
"""
Store the messages to a cookie and return a list of any messages which
could not be stored.
If the encoded data is larger than ``max_cookie_size``, remove
messages until the data fits (these are the m... | [
"def",
"_store",
"(",
"self",
",",
"messages",
",",
"response",
",",
"remove_oldest",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"unstored_messages",
"=",
"[",
"]",
"encoded_data",
"=",
"self",
".",
"_encode",
"(",
"messages",
")... | [
113,
4
] | [
140,
32
] | python | en | ['en', 'error', 'th'] | False |
CookieStorage._legacy_hash | (self, value) |
# RemovedInDjango40Warning: pre-Django 3.1 hashes will be invalid.
Create an HMAC/SHA1 hash based on the value and the project setting's
SECRET_KEY, modified to make it unique for the present purpose.
|
# RemovedInDjango40Warning: pre-Django 3.1 hashes will be invalid.
Create an HMAC/SHA1 hash based on the value and the project setting's
SECRET_KEY, modified to make it unique for the present purpose.
| def _legacy_hash(self, value):
"""
# RemovedInDjango40Warning: pre-Django 3.1 hashes will be invalid.
Create an HMAC/SHA1 hash based on the value and the project setting's
SECRET_KEY, modified to make it unique for the present purpose.
"""
# The class wide key salt is not... | [
"def",
"_legacy_hash",
"(",
"self",
",",
"value",
")",
":",
"# The class wide key salt is not reused here since older Django",
"# versions had it fixed and making it dynamic would break old hashes if",
"# self.key_salt is changed.",
"key_salt",
"=",
"'django.contrib.messages'",
"return",... | [
142,
4
] | [
152,
55
] | python | en | ['en', 'error', 'th'] | False |
CookieStorage._encode | (self, messages, encode_empty=False) |
Return an encoded version of the messages list which can be stored as
plain text.
Since the data will be retrieved from the client-side, the encoded data
also contains a hash to ensure that the data was not tampered with.
|
Return an encoded version of the messages list which can be stored as
plain text. | def _encode(self, messages, encode_empty=False):
"""
Return an encoded version of the messages list which can be stored as
plain text.
Since the data will be retrieved from the client-side, the encoded data
also contains a hash to ensure that the data was not tampered with.
... | [
"def",
"_encode",
"(",
"self",
",",
"messages",
",",
"encode_empty",
"=",
"False",
")",
":",
"if",
"messages",
"or",
"encode_empty",
":",
"return",
"self",
".",
"signer",
".",
"sign_object",
"(",
"messages",
",",
"serializer",
"=",
"MessageSerializer",
",",
... | [
154,
4
] | [
163,
97
] | python | en | ['en', 'error', 'th'] | False |
CookieStorage._decode | (self, data) |
Safely decode an encoded text stream back into a list of messages.
If the encoded text stream contained an invalid hash or was in an
invalid format, return None.
|
Safely decode an encoded text stream back into a list of messages. | def _decode(self, data):
"""
Safely decode an encoded text stream back into a list of messages.
If the encoded text stream contained an invalid hash or was in an
invalid format, return None.
"""
if not data:
return None
try:
return self.si... | [
"def",
"_decode",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"None",
"try",
":",
"return",
"self",
".",
"signer",
".",
"unsign_object",
"(",
"data",
",",
"serializer",
"=",
"MessageSerializer",
")",
"# RemovedInDjango41Warning: w... | [
165,
4
] | [
197,
19
] | python | en | ['en', 'error', 'th'] | False |
_make_flow | (request, scopes, return_url=None) | Creates a Web Server Flow
Args:
request: A Django request object.
scopes: the request oauth2 scopes.
return_url: The URL to return to after the flow is complete. Defaults
to the path of the current request.
Returns:
An OAuth2 flow object that has been stored in the ... | Creates a Web Server Flow | def _make_flow(request, scopes, return_url=None):
"""Creates a Web Server Flow
Args:
request: A Django request object.
scopes: the request oauth2 scopes.
return_url: The URL to return to after the flow is complete. Defaults
to the path of the current request.
Returns:
... | [
"def",
"_make_flow",
"(",
"request",
",",
"scopes",
",",
"return_url",
"=",
"None",
")",
":",
"# Generate a CSRF token to prevent malicious requests.",
"csrf_token",
"=",
"hashlib",
".",
"sha256",
"(",
"os",
".",
"urandom",
"(",
"1024",
")",
")",
".",
"hexdigest... | [
43,
0
] | [
75,
15
] | python | en | ['en', 'hu', 'en'] | True |
_get_flow_for_token | (csrf_token, request) | Looks up the flow in session to recover information about requested
scopes.
Args:
csrf_token: The token passed in the callback request that should
match the one previously generated and stored in the request on the
initial authorization view.
Returns:
The OAuth2 Fl... | Looks up the flow in session to recover information about requested
scopes. | def _get_flow_for_token(csrf_token, request):
""" Looks up the flow in session to recover information about requested
scopes.
Args:
csrf_token: The token passed in the callback request that should
match the one previously generated and stored in the request on the
initial au... | [
"def",
"_get_flow_for_token",
"(",
"csrf_token",
",",
"request",
")",
":",
"flow_pickle",
"=",
"request",
".",
"session",
".",
"get",
"(",
"_FLOW_KEY",
".",
"format",
"(",
"csrf_token",
")",
",",
"None",
")",
"return",
"None",
"if",
"flow_pickle",
"is",
"N... | [
78,
0
] | [
92,
74
] | python | en | ['en', 'en', 'en'] | True |
oauth2_callback | (request) | View that handles the user's return from OAuth2 provider.
This view verifies the CSRF state and OAuth authorization code, and on
success stores the credentials obtained in the storage provider,
and redirects to the return_url specified in the authorize view and
stored in the session.
Args:
... | View that handles the user's return from OAuth2 provider. | def oauth2_callback(request):
""" View that handles the user's return from OAuth2 provider.
This view verifies the CSRF state and OAuth authorization code, and on
success stores the credentials obtained in the storage provider,
and redirects to the return_url specified in the authorize view and
sto... | [
"def",
"oauth2_callback",
"(",
"request",
")",
":",
"if",
"'error'",
"in",
"request",
".",
"GET",
":",
"reason",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'error_description'",
",",
"request",
".",
"GET",
".",
"get",
"(",
"'error'",
",",
"''",
")",... | [
95,
0
] | [
155,
41
] | python | en | ['en', 'en', 'en'] | True |
oauth2_authorize | (request) | View to start the OAuth2 Authorization flow.
This view starts the OAuth2 authorization flow. If scopes is passed in
as a GET URL parameter, it will authorize those scopes, otherwise the
default scopes specified in settings. The return_url can also be
specified as a GET parameter, otherwise the re... | View to start the OAuth2 Authorization flow. | def oauth2_authorize(request):
""" View to start the OAuth2 Authorization flow.
This view starts the OAuth2 authorization flow. If scopes is passed in
as a GET URL parameter, it will authorize those scopes, otherwise the
default scopes specified in settings. The return_url can also be
specifie... | [
"def",
"oauth2_authorize",
"(",
"request",
")",
":",
"return_url",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'return_url'",
",",
"None",
")",
"if",
"not",
"return_url",
":",
"return_url",
"=",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_REFERER'",
... | [
158,
0
] | [
192,
39
] | python | en | ['en', 'en', 'en'] | True |
URIVariable.parse | (self) | Parse the variable.
This finds the:
- operator,
- set of safe characters,
- variables, and
- defaults.
| Parse the variable. | def parse(self):
"""Parse the variable.
This finds the:
- operator,
- set of safe characters,
- variables, and
- defaults.
"""
var_list = self.original
if self.original[0] in URIVariable.operators:
self.operator = self... | [
"def",
"parse",
"(",
"self",
")",
":",
"var_list",
"=",
"self",
".",
"original",
"if",
"self",
".",
"original",
"[",
"0",
"]",
"in",
"URIVariable",
".",
"operators",
":",
"self",
".",
"operator",
"=",
"self",
".",
"original",
"[",
"0",
"]",
"var_list... | [
72,
4
] | [
115,
74
] | python | en | ['en', 'en', 'en'] | True |
URIVariable.post_parse | (self) | Set ``start``, ``join_str`` and ``safe`` attributes.
After parsing the variable, we need to set up these attributes and it
only makes sense to do it in a more easily testable way.
| Set ``start``, ``join_str`` and ``safe`` attributes. | def post_parse(self):
"""Set ``start``, ``join_str`` and ``safe`` attributes.
After parsing the variable, we need to set up these attributes and it
only makes sense to do it in a more easily testable way.
"""
self.safe = ''
self.start = self.join_str = self.operator
... | [
"def",
"post_parse",
"(",
"self",
")",
":",
"self",
".",
"safe",
"=",
"''",
"self",
".",
"start",
"=",
"self",
".",
"join_str",
"=",
"self",
".",
"operator",
"if",
"self",
".",
"operator",
"==",
"'+'",
":",
"self",
".",
"start",
"=",
"''",
"if",
... | [
117,
4
] | [
136,
44
] | python | en | ['en', 'da', 'en'] | True |
URIVariable._query_expansion | (self, name, value, explode, prefix) | Expansion method for the '?' and '&' operators. | Expansion method for the '?' and '&' operators. | def _query_expansion(self, name, value, explode, prefix):
"""Expansion method for the '?' and '&' operators."""
if value is None:
return None
tuples, items = is_list_of_tuples(value)
safe = self.safe
if list_test(value) and not tuples:
if not value:
... | [
"def",
"_query_expansion",
"(",
"self",
",",
"name",
",",
"value",
",",
"explode",
",",
"prefix",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"tuples",
",",
"items",
"=",
"is_list_of_tuples",
"(",
"value",
")",
"safe",
"=",
"self",
".... | [
138,
4
] | [
178,
25
] | python | en | ['en', 'en', 'en'] | True |
URIVariable._label_path_expansion | (self, name, value, explode, prefix) | Label and path expansion method.
Expands for operators: '/', '.'
| Label and path expansion method. | def _label_path_expansion(self, name, value, explode, prefix):
"""Label and path expansion method.
Expands for operators: '/', '.'
"""
join_str = self.join_str
safe = self.safe
if value is None or (len(value) == 0 and value != ''):
return None
tupl... | [
"def",
"_label_path_expansion",
"(",
"self",
",",
"name",
",",
"value",
",",
"explode",
",",
"prefix",
")",
":",
"join_str",
"=",
"self",
".",
"join_str",
"safe",
"=",
"self",
".",
"safe",
"if",
"value",
"is",
"None",
"or",
"(",
"len",
"(",
"value",
... | [
180,
4
] | [
218,
33
] | python | en | ['en', 'en', 'en'] | True |
URIVariable._semi_path_expansion | (self, name, value, explode, prefix) | Expansion method for ';' operator. | Expansion method for ';' operator. | def _semi_path_expansion(self, name, value, explode, prefix):
"""Expansion method for ';' operator."""
join_str = self.join_str
safe = self.safe
if value is None:
return None
if self.operator == '?':
join_str = '&'
tuples, items = is_list_of_tup... | [
"def",
"_semi_path_expansion",
"(",
"self",
",",
"name",
",",
"value",
",",
"explode",
",",
"prefix",
")",
":",
"join_str",
"=",
"self",
".",
"join_str",
"safe",
"=",
"self",
".",
"safe",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"if",
"self"... | [
220,
4
] | [
266,
19
] | python | en | ['en', 'en', 'en'] | True |
URIVariable.expand | (self, var_dict=None) | Expand the variable in question.
Using ``var_dict`` and the previously parsed defaults, expand this
variable and subvariables.
:param dict var_dict: dictionary of key-value pairs to be used during
expansion
:returns: dict(variable=value)
Examples::
# (... | Expand the variable in question. | def expand(self, var_dict=None):
"""Expand the variable in question.
Using ``var_dict`` and the previously parsed defaults, expand this
variable and subvariables.
:param dict var_dict: dictionary of key-value pairs to be used during
expansion
:returns: dict(variable... | [
"def",
"expand",
"(",
"self",
",",
"var_dict",
"=",
"None",
")",
":",
"return_values",
"=",
"[",
"]",
"for",
"name",
",",
"opts",
"in",
"self",
".",
"variables",
":",
"value",
"=",
"var_dict",
".",
"get",
"(",
"name",
",",
"None",
")",
"if",
"not",... | [
290,
4
] | [
345,
37
] | python | en | ['en', 'en', 'en'] | True |
FileField.generate_filename | (self, instance, filename) |
Apply (if callable) or prepend (if a string) upload_to to the filename,
then delegate further processing of the name to the storage backend.
Until the storage layer, all file paths are expected to be Unix style
(with forward slashes).
|
Apply (if callable) or prepend (if a string) upload_to to the filename,
then delegate further processing of the name to the storage backend.
Until the storage layer, all file paths are expected to be Unix style
(with forward slashes).
| def generate_filename(self, instance, filename):
"""
Apply (if callable) or prepend (if a string) upload_to to the filename,
then delegate further processing of the name to the storage backend.
Until the storage layer, all file paths are expected to be Unix style
(with forward sl... | [
"def",
"generate_filename",
"(",
"self",
",",
"instance",
",",
"filename",
")",
":",
"if",
"callable",
"(",
"self",
".",
"upload_to",
")",
":",
"filename",
"=",
"self",
".",
"upload_to",
"(",
"instance",
",",
"filename",
")",
"else",
":",
"dirname",
"=",... | [
308,
4
] | [
321,
55
] | python | en | ['en', 'error', 'th'] | False |
ImageField.update_dimension_fields | (self, instance, force=False, *args, **kwargs) |
Update field's width and height fields, if defined.
This method is hooked up to model's post_init signal to update
dimensions after instantiating a model instance. However, dimensions
won't be updated if the dimensions fields are already populated. This
avoids unnecessary rec... |
Update field's width and height fields, if defined. | def update_dimension_fields(self, instance, force=False, *args, **kwargs):
"""
Update field's width and height fields, if defined.
This method is hooked up to model's post_init signal to update
dimensions after instantiating a model instance. However, dimensions
won't be update... | [
"def",
"update_dimension_fields",
"(",
"self",
",",
"instance",
",",
"force",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Nothing to update if the field doesn't have dimension fields or if",
"# the field is deferred.",
"has_dimension_fields",
"="... | [
419,
4
] | [
474,
56
] | python | en | ['en', 'error', 'th'] | False |
sensitive_variables | (*variables) |
Indicate which variables used in the decorated function are sensitive so
that those variables can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Accept two forms:
* with specified variable names:
@sensitive_variables('user', 'password', '... |
Indicate which variables used in the decorated function are sensitive so
that those variables can later be treated in a special way, for example
by hiding them when logging unhandled exceptions. | def sensitive_variables(*variables):
"""
Indicate which variables used in the decorated function are sensitive so
that those variables can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Accept two forms:
* with specified variable names:
... | [
"def",
"sensitive_variables",
"(",
"*",
"variables",
")",
":",
"if",
"len",
"(",
"variables",
")",
"==",
"1",
"and",
"callable",
"(",
"variables",
"[",
"0",
"]",
")",
":",
"raise",
"TypeError",
"(",
"'sensitive_variables() must be called to use it as a decorator, ... | [
5,
0
] | [
43,
20
] | python | en | ['en', 'error', 'th'] | False |
sensitive_post_parameters | (*parameters) |
Indicate which POST parameters used in the decorated view are sensitive,
so that those parameters can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Accept two forms:
* with specified parameters:
@sensitive_post_parameters('password', 'cr... |
Indicate which POST parameters used in the decorated view are sensitive,
so that those parameters can later be treated in a special way, for example
by hiding them when logging unhandled exceptions. | def sensitive_post_parameters(*parameters):
"""
Indicate which POST parameters used in the decorated view are sensitive,
so that those parameters can later be treated in a special way, for example
by hiding them when logging unhandled exceptions.
Accept two forms:
* with specified parameters:
... | [
"def",
"sensitive_post_parameters",
"(",
"*",
"parameters",
")",
":",
"if",
"len",
"(",
"parameters",
")",
"==",
"1",
"and",
"callable",
"(",
"parameters",
"[",
"0",
"]",
")",
":",
"raise",
"TypeError",
"(",
"'sensitive_post_parameters() must be called to use it a... | [
46,
0
] | [
90,
20
] | python | en | ['en', 'error', 'th'] | False |
Operation.deconstruct | (self) |
Return a 3-tuple of class import path (or just name if it lives
under django.db.migrations), positional arguments, and keyword
arguments.
|
Return a 3-tuple of class import path (or just name if it lives
under django.db.migrations), positional arguments, and keyword
arguments.
| def deconstruct(self):
"""
Return a 3-tuple of class import path (or just name if it lives
under django.db.migrations), positional arguments, and keyword
arguments.
"""
return (
self.__class__.__name__,
self._constructor_args[0],
self._... | [
"def",
"deconstruct",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"_constructor_args",
"[",
"0",
"]",
",",
"self",
".",
"_constructor_args",
"[",
"1",
"]",
",",
")"
] | [
41,
4
] | [
51,
9
] | python | en | ['en', 'error', 'th'] | False |
Operation.state_forwards | (self, app_label, state) |
Take the state from the previous migration, and mutate it
so that it matches what this migration would perform.
|
Take the state from the previous migration, and mutate it
so that it matches what this migration would perform.
| def state_forwards(self, app_label, state):
"""
Take the state from the previous migration, and mutate it
so that it matches what this migration would perform.
"""
raise NotImplementedError('subclasses of Operation must provide a state_forwards() method') | [
"def",
"state_forwards",
"(",
"self",
",",
"app_label",
",",
"state",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Operation must provide a state_forwards() method'",
")"
] | [
53,
4
] | [
58,
99
] | python | en | ['en', 'error', 'th'] | False |
Operation.database_forwards | (self, app_label, schema_editor, from_state, to_state) |
Perform the mutation on the database schema in the normal
(forwards) direction.
|
Perform the mutation on the database schema in the normal
(forwards) direction.
| def database_forwards(self, app_label, schema_editor, from_state, to_state):
"""
Perform the mutation on the database schema in the normal
(forwards) direction.
"""
raise NotImplementedError('subclasses of Operation must provide a database_forwards() method') | [
"def",
"database_forwards",
"(",
"self",
",",
"app_label",
",",
"schema_editor",
",",
"from_state",
",",
"to_state",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Operation must provide a database_forwards() method'",
")"
] | [
60,
4
] | [
65,
102
] | python | en | ['en', 'error', 'th'] | False |
Operation.database_backwards | (self, app_label, schema_editor, from_state, to_state) |
Perform the mutation on the database schema in the reverse
direction - e.g. if this were CreateModel, it would in fact
drop the model's table.
|
Perform the mutation on the database schema in the reverse
direction - e.g. if this were CreateModel, it would in fact
drop the model's table.
| def database_backwards(self, app_label, schema_editor, from_state, to_state):
"""
Perform the mutation on the database schema in the reverse
direction - e.g. if this were CreateModel, it would in fact
drop the model's table.
"""
raise NotImplementedError('subclasses of Op... | [
"def",
"database_backwards",
"(",
"self",
",",
"app_label",
",",
"schema_editor",
",",
"from_state",
",",
"to_state",
")",
":",
"raise",
"NotImplementedError",
"(",
"'subclasses of Operation must provide a database_backwards() method'",
")"
] | [
67,
4
] | [
73,
103
] | python | en | ['en', 'error', 'th'] | False |
Operation.describe | (self) |
Output a brief summary of what the action does.
|
Output a brief summary of what the action does.
| def describe(self):
"""
Output a brief summary of what the action does.
"""
return "%s: %s" % (self.__class__.__name__, self._constructor_args) | [
"def",
"describe",
"(",
"self",
")",
":",
"return",
"\"%s: %s\"",
"%",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"_constructor_args",
")"
] | [
75,
4
] | [
79,
75
] | python | en | ['en', 'error', 'th'] | False |
Operation.migration_name_fragment | (self) |
A filename part suitable for automatically naming a migration
containing this operation, or None if not applicable.
|
A filename part suitable for automatically naming a migration
containing this operation, or None if not applicable.
| def migration_name_fragment(self):
"""
A filename part suitable for automatically naming a migration
containing this operation, or None if not applicable.
"""
return None | [
"def",
"migration_name_fragment",
"(",
"self",
")",
":",
"return",
"None"
] | [
82,
4
] | [
87,
19
] | python | en | ['en', 'error', 'th'] | False |
Operation.references_model | (self, name, app_label) |
Return True if there is a chance this operation references the given
model name (as a string), with an app label for accuracy.
Used for optimization. If in doubt, return True;
returning a false positive will merely make the optimizer a little
less efficient, while returning a f... |
Return True if there is a chance this operation references the given
model name (as a string), with an app label for accuracy. | def references_model(self, name, app_label):
"""
Return True if there is a chance this operation references the given
model name (as a string), with an app label for accuracy.
Used for optimization. If in doubt, return True;
returning a false positive will merely make the optimi... | [
"def",
"references_model",
"(",
"self",
",",
"name",
",",
"app_label",
")",
":",
"return",
"True"
] | [
89,
4
] | [
99,
19
] | python | en | ['en', 'error', 'th'] | False |
Operation.references_field | (self, model_name, name, app_label) |
Return True if there is a chance this operation references the given
field name, with an app label for accuracy.
Used for optimization. If in doubt, return True.
|
Return True if there is a chance this operation references the given
field name, with an app label for accuracy. | def references_field(self, model_name, name, app_label):
"""
Return True if there is a chance this operation references the given
field name, with an app label for accuracy.
Used for optimization. If in doubt, return True.
"""
return self.references_model(model_name, app... | [
"def",
"references_field",
"(",
"self",
",",
"model_name",
",",
"name",
",",
"app_label",
")",
":",
"return",
"self",
".",
"references_model",
"(",
"model_name",
",",
"app_label",
")"
] | [
101,
4
] | [
108,
59
] | python | en | ['en', 'error', 'th'] | False |
Operation.allow_migrate_model | (self, connection_alias, model) |
Return whether or not a model may be migrated.
This is a thin wrapper around router.allow_migrate_model() that
preemptively rejects any proxy, swapped out, or unmanaged model.
|
Return whether or not a model may be migrated. | def allow_migrate_model(self, connection_alias, model):
"""
Return whether or not a model may be migrated.
This is a thin wrapper around router.allow_migrate_model() that
preemptively rejects any proxy, swapped out, or unmanaged model.
"""
if not model._meta.can_migrate(... | [
"def",
"allow_migrate_model",
"(",
"self",
",",
"connection_alias",
",",
"model",
")",
":",
"if",
"not",
"model",
".",
"_meta",
".",
"can_migrate",
"(",
"connection_alias",
")",
":",
"return",
"False",
"return",
"router",
".",
"allow_migrate_model",
"(",
"conn... | [
110,
4
] | [
120,
66
] | python | en | ['en', 'error', 'th'] | False |
Operation.reduce | (self, operation, app_label) |
Return either a list of operations the actual operation should be
replaced with or a boolean that indicates whether or not the specified
operation can be optimized across.
|
Return either a list of operations the actual operation should be
replaced with or a boolean that indicates whether or not the specified
operation can be optimized across.
| def reduce(self, operation, app_label):
"""
Return either a list of operations the actual operation should be
replaced with or a boolean that indicates whether or not the specified
operation can be optimized across.
"""
if self.elidable:
return [operation]
... | [
"def",
"reduce",
"(",
"self",
",",
"operation",
",",
"app_label",
")",
":",
"if",
"self",
".",
"elidable",
":",
"return",
"[",
"operation",
"]",
"elif",
"operation",
".",
"elidable",
":",
"return",
"[",
"self",
"]",
"return",
"False"
] | [
122,
4
] | [
132,
20
] | python | en | ['en', 'error', 'th'] | False |
BatchPreprocessing.prepare_for_batch | (self, image, labels, bboxes, image_id=-1) |
All inputs have different dimensions, we need to update them in order to fit the batch,
Image: Depending on the config, we rescale image to the batch image size (and it will stay the same)
or maximum batch image size, which is then transformed to randomly selected size in preprocess_batch() me... |
All inputs have different dimensions, we need to update them in order to fit the batch, | def prepare_for_batch(self, image, labels, bboxes, image_id=-1):
"""
All inputs have different dimensions, we need to update them in order to fit the batch,
Image: Depending on the config, we rescale image to the batch image size (and it will stay the same)
or maximum batch image size, ... | [
"def",
"prepare_for_batch",
"(",
"self",
",",
"image",
",",
"labels",
",",
"bboxes",
",",
"image_id",
"=",
"-",
"1",
")",
":",
"labels",
"=",
"labels",
"[",
"0",
":",
"self",
".",
"model_config",
".",
"max_objects",
"]",
"bboxes",
"=",
"bboxes",
"[",
... | [
24,
4
] | [
114,
67
] | python | en | ['en', 'error', 'th'] | False |
BatchPreprocessing.preprocess_batch | (self, images, bboxes, labels, mask, image_ids, heights, widths) |
We have the all the inputs in batches, uniformly sized.
Images/bounding boxes are augmented if this was required.
First, the images are resized to a random size (from given range) if this is allowed.
If we use neural network with layers independent on image size, like convolutional one... |
We have the all the inputs in batches, uniformly sized.
Images/bounding boxes are augmented if this was required. | def preprocess_batch(self, images, bboxes, labels, mask, image_ids, heights, widths):
"""
We have the all the inputs in batches, uniformly sized.
Images/bounding boxes are augmented if this was required.
First, the images are resized to a random size (from given range) if this is allowe... | [
"def",
"preprocess_batch",
"(",
"self",
",",
"images",
",",
"bboxes",
",",
"labels",
",",
"mask",
",",
"image_ids",
",",
"heights",
",",
"widths",
")",
":",
"images",
"=",
"tf",
".",
"cast",
"(",
"images",
",",
"tf",
".",
"float32",
")",
"# select the ... | [
127,
4
] | [
212,
13
] | python | en | ['en', 'error', 'th'] | False |
_add_doc | (func, doc) | Add documentation to a function. | Add documentation to a function. | def _add_doc(func, doc):
"""Add documentation to a function."""
func.__doc__ = doc | [
"def",
"_add_doc",
"(",
"func",
",",
"doc",
")",
":",
"func",
".",
"__doc__",
"=",
"doc"
] | [
74,
0
] | [
76,
22
] | python | en | ['en', 'en', 'en'] | True |
_import_module | (name) | Import module, returning the module after the last dot. | Import module, returning the module after the last dot. | def _import_module(name):
"""Import module, returning the module after the last dot."""
__import__(name)
return sys.modules[name] | [
"def",
"_import_module",
"(",
"name",
")",
":",
"__import__",
"(",
"name",
")",
"return",
"sys",
".",
"modules",
"[",
"name",
"]"
] | [
79,
0
] | [
82,
28
] | python | en | ['en', 'en', 'en'] | True |
add_move | (move) | Add an item to six.moves. | Add an item to six.moves. | def add_move(move):
"""Add an item to six.moves."""
setattr(_MovedItems, move.name, move) | [
"def",
"add_move",
"(",
"move",
")",
":",
"setattr",
"(",
"_MovedItems",
",",
"move",
".",
"name",
",",
"move",
")"
] | [
485,
0
] | [
487,
41
] | python | en | ['en', 'en', 'en'] | True |
remove_move | (name) | Remove item from six.moves. | Remove item from six.moves. | def remove_move(name):
"""Remove item from six.moves."""
try:
delattr(_MovedItems, name)
except AttributeError:
try:
del moves.__dict__[name]
except KeyError:
raise AttributeError("no such move, %r" % (name,)) | [
"def",
"remove_move",
"(",
"name",
")",
":",
"try",
":",
"delattr",
"(",
"_MovedItems",
",",
"name",
")",
"except",
"AttributeError",
":",
"try",
":",
"del",
"moves",
".",
"__dict__",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"AttributeError",
... | [
490,
0
] | [
498,
62
] | python | en | ['en', 'en', 'en'] | True |
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(meta):
def __new__(cls, na... | [
"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",
"(",
"meta",
")... | [
799,
0
] | [
808,
61
] | python | en | ['en', 'en', 'en'] | True |
add_metaclass | (metaclass) | Class decorator for creating a class with a metaclass. | Class decorator for creating a class with a metaclass. | def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass."""
def wrapper(cls):
orig_vars = cls.__dict__.copy()
slots = orig_vars.get('__slots__')
if slots is not None:
if isinstance(slots, str):
slots = [slots]
for slo... | [
"def",
"add_metaclass",
"(",
"metaclass",
")",
":",
"def",
"wrapper",
"(",
"cls",
")",
":",
"orig_vars",
"=",
"cls",
".",
"__dict__",
".",
"copy",
"(",
")",
"slots",
"=",
"orig_vars",
".",
"get",
"(",
"'__slots__'",
")",
"if",
"slots",
"is",
"not",
"... | [
811,
0
] | [
824,
18
] | python | en | ['en', 'en', 'en'] | True |
python_2_unicode_compatible | (klass) |
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
|
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing. | def python_2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
To support Python 2 and 3 with a single code base, define a __str__ method
returning text and apply this decorator to the class.
"""
if PY2:
... | [
"def",
"python_2_unicode_compatible",
"(",
"klass",
")",
":",
"if",
"PY2",
":",
"if",
"'__str__'",
"not",
"in",
"klass",
".",
"__dict__",
":",
"raise",
"ValueError",
"(",
"\"@python_2_unicode_compatible cannot be applied \"",
"\"to %s because it doesn't define __str__().\""... | [
827,
0
] | [
842,
16
] | python | en | ['en', 'error', 'th'] | False |
_SixMetaPathImporter.is_package | (self, fullname) |
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
|
Return true, if the named module is a package. | def is_package(self, fullname):
"""
Return true, if the named module is a package.
We need this method to get correct spec objects with
Python 3.4 (see PEP451)
"""
return hasattr(self.__get_module(fullname), "__path__") | [
"def",
"is_package",
"(",
"self",
",",
"fullname",
")",
":",
"return",
"hasattr",
"(",
"self",
".",
"__get_module",
"(",
"fullname",
")",
",",
"\"__path__\"",
")"
] | [
208,
4
] | [
215,
63
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.