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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Client.head | (self, path, data=None, follow=False, secure=False, **extra) | Request a response from the server using HEAD. | Request a response from the server using HEAD. | def head(self, path, data=None, follow=False, secure=False, **extra):
"""Request a response from the server using HEAD."""
self.extra = extra
response = super().head(path, data=data, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, **e... | [
"def",
"head",
"(",
"self",
",",
"path",
",",
"data",
"=",
"None",
",",
"follow",
"=",
"False",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"self",
".",
"extra",
"=",
"extra",
"response",
"=",
"super",
"(",
")",
".",
"head",
... | [
755,
4
] | [
761,
23
] | python | en | ['en', 'en', 'en'] | True |
Client.options | (self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra) | Request a response from the server using OPTIONS. | Request a response from the server using OPTIONS. | def options(self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra):
"""Request a response from the server using OPTIONS."""
self.extra = extra
response = super().options(path, data=data, content_type=content_type, secure=secure, **extra... | [
"def",
"options",
"(",
"self",
",",
"path",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"follow",
"=",
"False",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"self",
".",
"extra",
"=",
"extra",
... | [
763,
4
] | [
770,
23
] | python | en | ['en', 'en', 'en'] | True |
Client.put | (self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra) | Send a resource to the server using PUT. | Send a resource to the server using PUT. | def put(self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra):
"""Send a resource to the server using PUT."""
self.extra = extra
response = super().put(path, data=data, content_type=content_type, secure=secure, **extra)
if follow:
... | [
"def",
"put",
"(",
"self",
",",
"path",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"follow",
"=",
"False",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"self",
".",
"extra",
"=",
"extra",
"r... | [
772,
4
] | [
779,
23
] | python | en | ['en', 'en', 'en'] | True |
Client.patch | (self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra) | Send a resource to the server using PATCH. | Send a resource to the server using PATCH. | def patch(self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra):
"""Send a resource to the server using PATCH."""
self.extra = extra
response = super().patch(path, data=data, content_type=content_type, secure=secure, **extra)
if ... | [
"def",
"patch",
"(",
"self",
",",
"path",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"follow",
"=",
"False",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"self",
".",
"extra",
"=",
"extra",
... | [
781,
4
] | [
788,
23
] | python | en | ['en', 'en', 'en'] | True |
Client.delete | (self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra) | Send a DELETE request to the server. | Send a DELETE request to the server. | def delete(self, path, data='', content_type='application/octet-stream',
follow=False, secure=False, **extra):
"""Send a DELETE request to the server."""
self.extra = extra
response = super().delete(path, data=data, content_type=content_type, secure=secure, **extra)
if fol... | [
"def",
"delete",
"(",
"self",
",",
"path",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"'application/octet-stream'",
",",
"follow",
"=",
"False",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"self",
".",
"extra",
"=",
"extra",
... | [
790,
4
] | [
797,
23
] | python | en | ['en', 'it', 'en'] | True |
Client.trace | (self, path, data='', follow=False, secure=False, **extra) | Send a TRACE request to the server. | Send a TRACE request to the server. | def trace(self, path, data='', follow=False, secure=False, **extra):
"""Send a TRACE request to the server."""
self.extra = extra
response = super().trace(path, data=data, secure=secure, **extra)
if follow:
response = self._handle_redirects(response, data=data, **extra)
... | [
"def",
"trace",
"(",
"self",
",",
"path",
",",
"data",
"=",
"''",
",",
"follow",
"=",
"False",
",",
"secure",
"=",
"False",
",",
"*",
"*",
"extra",
")",
":",
"self",
".",
"extra",
"=",
"extra",
"response",
"=",
"super",
"(",
")",
".",
"trace",
... | [
799,
4
] | [
805,
23
] | python | en | ['en', 'en', 'en'] | True |
Client._handle_redirects | (self, response, data='', content_type='', **extra) |
Follow any redirects by requesting responses from the server using GET.
|
Follow any redirects by requesting responses from the server using GET.
| def _handle_redirects(self, response, data='', content_type='', **extra):
"""
Follow any redirects by requesting responses from the server using GET.
"""
response.redirect_chain = []
redirect_status_codes = (
HTTPStatus.MOVED_PERMANENTLY,
HTTPStatus.FOUND,... | [
"def",
"_handle_redirects",
"(",
"self",
",",
"response",
",",
"data",
"=",
"''",
",",
"content_type",
"=",
"''",
",",
"*",
"*",
"extra",
")",
":",
"response",
".",
"redirect_chain",
"=",
"[",
"]",
"redirect_status_codes",
"=",
"(",
"HTTPStatus",
".",
"M... | [
807,
4
] | [
862,
23
] | python | en | ['en', 'error', 'th'] | False |
AsyncClient.request | (self, **request) |
The master request method. Compose the scope dictionary and pass to the
handler, return the result of the handler. Assume defaults for the
query environment, which can be overridden using the arguments to the
request.
|
The master request method. Compose the scope dictionary and pass to the
handler, return the result of the handler. Assume defaults for the
query environment, which can be overridden using the arguments to the
request.
| async def request(self, **request):
"""
The master request method. Compose the scope dictionary and pass to the
handler, return the result of the handler. Assume defaults for the
query environment, which can be overridden using the arguments to the
request.
"""
if... | [
"async",
"def",
"request",
"(",
"self",
",",
"*",
"*",
"request",
")",
":",
"if",
"'follow'",
"in",
"request",
":",
"raise",
"NotImplementedError",
"(",
"'AsyncClient request methods do not accept the follow '",
"'parameter.'",
")",
"scope",
"=",
"self",
".",
"_ba... | [
879,
4
] | [
925,
23
] | python | en | ['en', 'error', 'th'] | False |
suppressed_cache_errors | () | If we can't access the cache then we can just skip caching and process
requests as if caching wasn't enabled.
| If we can't access the cache then we can just skip caching and process
requests as if caching wasn't enabled.
| def suppressed_cache_errors() -> Iterator[None]:
"""If we can't access the cache then we can just skip caching and process
requests as if caching wasn't enabled.
"""
try:
yield
except OSError:
pass | [
"def",
"suppressed_cache_errors",
"(",
")",
"->",
"Iterator",
"[",
"None",
"]",
":",
"try",
":",
"yield",
"except",
"OSError",
":",
"pass"
] | [
20,
0
] | [
27,
12
] | python | en | ['en', 'en', 'en'] | True |
_default_template_ctx_processor | () | Default template context processor. Injects `request`,
`session` and `g`.
| Default template context processor. Injects `request`,
`session` and `g`.
| def _default_template_ctx_processor():
"""Default template context processor. Injects `request`,
`session` and `g`.
"""
reqctx = _request_ctx_stack.top
appctx = _app_ctx_stack.top
rv = {}
if appctx is not None:
rv['g'] = appctx.g
if reqctx is not None:
rv['request'] = re... | [
"def",
"_default_template_ctx_processor",
"(",
")",
":",
"reqctx",
"=",
"_request_ctx_stack",
".",
"top",
"appctx",
"=",
"_app_ctx_stack",
".",
"top",
"rv",
"=",
"{",
"}",
"if",
"appctx",
"is",
"not",
"None",
":",
"rv",
"[",
"'g'",
"]",
"=",
"appctx",
".... | [
17,
0
] | [
29,
13
] | python | en | ['en', 'en', 'pt'] | True |
_render | (template, context, app) | Renders the template and fires the signal | Renders the template and fires the signal | def _render(template, context, app):
"""Renders the template and fires the signal"""
before_render_template.send(app, template=template, context=context)
rv = template.render(context)
template_rendered.send(app, template=template, context=context)
return rv | [
"def",
"_render",
"(",
"template",
",",
"context",
",",
"app",
")",
":",
"before_render_template",
".",
"send",
"(",
"app",
",",
"template",
"=",
"template",
",",
"context",
"=",
"context",
")",
"rv",
"=",
"template",
".",
"render",
"(",
"context",
")",
... | [
111,
0
] | [
117,
13
] | python | en | ['en', 'en', 'en'] | True |
render_template | (template_name_or_list, **context) | Renders a template from the template folder with the given
context.
:param template_name_or_list: the name of the template to be
rendered, or an iterable with template names
the first one existing will be rendered
:param context: the varia... | Renders a template from the template folder with the given
context. | def render_template(template_name_or_list, **context):
"""Renders a template from the template folder with the given
context.
:param template_name_or_list: the name of the template to be
rendered, or an iterable with template names
the fir... | [
"def",
"render_template",
"(",
"template_name_or_list",
",",
"*",
"*",
"context",
")",
":",
"ctx",
"=",
"_app_ctx_stack",
".",
"top",
"ctx",
".",
"app",
".",
"update_template_context",
"(",
"context",
")",
"return",
"_render",
"(",
"ctx",
".",
"app",
".",
... | [
120,
0
] | [
133,
36
] | python | en | ['en', 'en', 'en'] | True |
render_template_string | (source, **context) | Renders a template from the given template source string
with the given context. Template variables will be autoescaped.
:param source: the source code of the template to be
rendered
:param context: the variables that should be available in the
context of the template... | Renders a template from the given template source string
with the given context. Template variables will be autoescaped. | def render_template_string(source, **context):
"""Renders a template from the given template source string
with the given context. Template variables will be autoescaped.
:param source: the source code of the template to be
rendered
:param context: the variables that should be availa... | [
"def",
"render_template_string",
"(",
"source",
",",
"*",
"*",
"context",
")",
":",
"ctx",
"=",
"_app_ctx_stack",
".",
"top",
"ctx",
".",
"app",
".",
"update_template_context",
"(",
"context",
")",
"return",
"_render",
"(",
"ctx",
".",
"app",
".",
"jinja_e... | [
136,
0
] | [
148,
36
] | python | en | ['en', 'en', 'en'] | True |
_check_link_requires_python | (
link: Link,
version_info: Tuple[int, int, int],
ignore_requires_python: bool = False,
) |
Return whether the given Python version is compatible with a link's
"Requires-Python" value.
:param version_info: A 3-tuple of ints representing the Python
major-minor-micro version to check.
:param ignore_requires_python: Whether to ignore the "Requires-Python"
value if the given Pyth... |
Return whether the given Python version is compatible with a link's
"Requires-Python" value. | def _check_link_requires_python(
link: Link,
version_info: Tuple[int, int, int],
ignore_requires_python: bool = False,
) -> bool:
"""
Return whether the given Python version is compatible with a link's
"Requires-Python" value.
:param version_info: A 3-tuple of ints representing the Python
... | [
"def",
"_check_link_requires_python",
"(",
"link",
":",
"Link",
",",
"version_info",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
",",
"ignore_requires_python",
":",
"bool",
"=",
"False",
",",
")",
"->",
"bool",
":",
"try",
":",
"is_compatible",
... | [
52,
0
] | [
91,
15
] | python | en | ['en', 'error', 'th'] | False |
filter_unallowed_hashes | (
candidates: List[InstallationCandidate],
hashes: Hashes,
project_name: str,
) |
Filter out candidates whose hashes aren't allowed, and return a new
list of candidates.
If at least one candidate has an allowed hash, then all candidates with
either an allowed hash or no hash specified are returned. Otherwise,
the given candidates are returned.
Including the candidates wit... |
Filter out candidates whose hashes aren't allowed, and return a new
list of candidates. | def filter_unallowed_hashes(
candidates: List[InstallationCandidate],
hashes: Hashes,
project_name: str,
) -> List[InstallationCandidate]:
"""
Filter out candidates whose hashes aren't allowed, and return a new
list of candidates.
If at least one candidate has an allowed hash, then all cand... | [
"def",
"filter_unallowed_hashes",
"(",
"candidates",
":",
"List",
"[",
"InstallationCandidate",
"]",
",",
"hashes",
":",
"Hashes",
",",
"project_name",
":",
"str",
",",
")",
"->",
"List",
"[",
"InstallationCandidate",
"]",
":",
"if",
"not",
"hashes",
":",
"l... | [
231,
0
] | [
302,
19
] | python | en | ['en', 'error', 'th'] | False |
_find_name_version_sep | (fragment: str, canonical_name: str) | Find the separator's index based on the package's canonical name.
:param fragment: A <package>+<version> filename "fragment" (stem) or
egg fragment.
:param canonical_name: The package's canonical name.
This function is needed since the canonicalized name does not necessarily
have the same leng... | Find the separator's index based on the package's canonical name. | def _find_name_version_sep(fragment: str, canonical_name: str) -> int:
"""Find the separator's index based on the package's canonical name.
:param fragment: A <package>+<version> filename "fragment" (stem) or
egg fragment.
:param canonical_name: The package's canonical name.
This function is n... | [
"def",
"_find_name_version_sep",
"(",
"fragment",
":",
"str",
",",
"canonical_name",
":",
"str",
")",
"->",
"int",
":",
"# Project name and version must be separated by one single dash. Find all",
"# occurrences of dashes; if the string in front of it matches the canonical",
"# name,... | [
940,
0
] | [
963,
67
] | python | en | ['en', 'en', 'en'] | True |
_extract_version_from_fragment | (fragment: str, canonical_name: str) | Parse the version string from a <package>+<version> filename
"fragment" (stem) or egg fragment.
:param fragment: The string to parse. E.g. foo-2.1
:param canonical_name: The canonicalized name of the package this
belongs to.
| Parse the version string from a <package>+<version> filename
"fragment" (stem) or egg fragment. | def _extract_version_from_fragment(fragment: str, canonical_name: str) -> Optional[str]:
"""Parse the version string from a <package>+<version> filename
"fragment" (stem) or egg fragment.
:param fragment: The string to parse. E.g. foo-2.1
:param canonical_name: The canonicalized name of the package thi... | [
"def",
"_extract_version_from_fragment",
"(",
"fragment",
":",
"str",
",",
"canonical_name",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"try",
":",
"version_start",
"=",
"_find_name_version_sep",
"(",
"fragment",
",",
"canonical_name",
")",
"+",
... | [
966,
0
] | [
981,
18
] | python | en | ['en', 'en', 'en'] | True |
LinkEvaluator.__init__ | (
self,
project_name: str,
canonical_name: str,
formats: FrozenSet[str],
target_python: TargetPython,
allow_yanked: bool,
ignore_requires_python: Optional[bool] = None,
) |
:param project_name: The user supplied package name.
:param canonical_name: The canonical package name.
:param formats: The formats allowed for this package. Should be a set
with 'binary' or 'source' or both in it.
:param target_python: The target Python interpreter to use w... |
:param project_name: The user supplied package name.
:param canonical_name: The canonical package name.
:param formats: The formats allowed for this package. Should be a set
with 'binary' or 'source' or both in it.
:param target_python: The target Python interpreter to use w... | def __init__(
self,
project_name: str,
canonical_name: str,
formats: FrozenSet[str],
target_python: TargetPython,
allow_yanked: bool,
ignore_requires_python: Optional[bool] = None,
) -> None:
"""
:param project_name: The user supplied package n... | [
"def",
"__init__",
"(",
"self",
",",
"project_name",
":",
"str",
",",
"canonical_name",
":",
"str",
",",
"formats",
":",
"FrozenSet",
"[",
"str",
"]",
",",
"target_python",
":",
"TargetPython",
",",
"allow_yanked",
":",
"bool",
",",
"ignore_requires_python",
... | [
106,
4
] | [
141,
40
] | python | en | ['en', 'error', 'th'] | False |
LinkEvaluator.evaluate_link | (self, link: Link) |
Determine whether a link is a candidate for installation.
:return: A tuple (is_candidate, result), where `result` is (1) a
version string if `is_candidate` is True, and (2) if
`is_candidate` is False, an optional string to log the reason
the link fails to qualify.
... |
Determine whether a link is a candidate for installation. | def evaluate_link(self, link: Link) -> Tuple[bool, Optional[str]]:
"""
Determine whether a link is a candidate for installation.
:return: A tuple (is_candidate, result), where `result` is (1) a
version string if `is_candidate` is True, and (2) if
`is_candidate` is False,... | [
"def",
"evaluate_link",
"(",
"self",
",",
"link",
":",
"Link",
")",
"->",
"Tuple",
"[",
"bool",
",",
"Optional",
"[",
"str",
"]",
"]",
":",
"version",
"=",
"None",
"if",
"link",
".",
"is_yanked",
"and",
"not",
"self",
".",
"_allow_yanked",
":",
"reas... | [
143,
4
] | [
228,
30
] | python | en | ['en', 'error', 'th'] | False |
CandidatePreferences.__init__ | (
self,
prefer_binary: bool = False,
allow_all_prereleases: bool = False,
) |
:param allow_all_prereleases: Whether to allow all pre-releases.
|
:param allow_all_prereleases: Whether to allow all pre-releases.
| def __init__(
self,
prefer_binary: bool = False,
allow_all_prereleases: bool = False,
) -> None:
"""
:param allow_all_prereleases: Whether to allow all pre-releases.
"""
self.allow_all_prereleases = allow_all_prereleases
self.prefer_binary = prefer_bin... | [
"def",
"__init__",
"(",
"self",
",",
"prefer_binary",
":",
"bool",
"=",
"False",
",",
"allow_all_prereleases",
":",
"bool",
"=",
"False",
",",
")",
"->",
"None",
":",
"self",
".",
"allow_all_prereleases",
"=",
"allow_all_prereleases",
"self",
".",
"prefer_bina... | [
312,
4
] | [
321,
42
] | python | en | ['en', 'error', 'th'] | False |
BestCandidateResult.__init__ | (
self,
candidates: List[InstallationCandidate],
applicable_candidates: List[InstallationCandidate],
best_candidate: Optional[InstallationCandidate],
) |
:param candidates: A sequence of all available candidates found.
:param applicable_candidates: The applicable candidates.
:param best_candidate: The most preferred candidate found, or None
if no applicable candidates were found.
|
:param candidates: A sequence of all available candidates found.
:param applicable_candidates: The applicable candidates.
:param best_candidate: The most preferred candidate found, or None
if no applicable candidates were found.
| def __init__(
self,
candidates: List[InstallationCandidate],
applicable_candidates: List[InstallationCandidate],
best_candidate: Optional[InstallationCandidate],
) -> None:
"""
:param candidates: A sequence of all available candidates found.
:param applicable_... | [
"def",
"__init__",
"(",
"self",
",",
"candidates",
":",
"List",
"[",
"InstallationCandidate",
"]",
",",
"applicable_candidates",
":",
"List",
"[",
"InstallationCandidate",
"]",
",",
"best_candidate",
":",
"Optional",
"[",
"InstallationCandidate",
"]",
",",
")",
... | [
331,
4
] | [
353,
44
] | python | en | ['en', 'error', 'th'] | False |
BestCandidateResult.iter_all | (self) | Iterate through all candidates.
| Iterate through all candidates.
| def iter_all(self) -> Iterable[InstallationCandidate]:
"""Iterate through all candidates.
"""
return iter(self._candidates) | [
"def",
"iter_all",
"(",
"self",
")",
"->",
"Iterable",
"[",
"InstallationCandidate",
"]",
":",
"return",
"iter",
"(",
"self",
".",
"_candidates",
")"
] | [
355,
4
] | [
358,
37
] | python | en | ['en', 'en', 'en'] | True |
BestCandidateResult.iter_applicable | (self) | Iterate through the applicable candidates.
| Iterate through the applicable candidates.
| def iter_applicable(self) -> Iterable[InstallationCandidate]:
"""Iterate through the applicable candidates.
"""
return iter(self._applicable_candidates) | [
"def",
"iter_applicable",
"(",
"self",
")",
"->",
"Iterable",
"[",
"InstallationCandidate",
"]",
":",
"return",
"iter",
"(",
"self",
".",
"_applicable_candidates",
")"
] | [
360,
4
] | [
363,
48
] | python | en | ['en', 'en', 'en'] | True |
CandidateEvaluator.create | (
cls,
project_name: str,
target_python: Optional[TargetPython] = None,
prefer_binary: bool = False,
allow_all_prereleases: bool = False,
specifier: Optional[specifiers.BaseSpecifier] = None,
hashes: Optional[Hashes] = None,
) | Create a CandidateEvaluator object.
:param target_python: The target Python interpreter to use when
checking compatibility. If None (the default), a TargetPython
object will be constructed from the running Python.
:param specifier: An optional object implementing `filter`
... | Create a CandidateEvaluator object. | def create(
cls,
project_name: str,
target_python: Optional[TargetPython] = None,
prefer_binary: bool = False,
allow_all_prereleases: bool = False,
specifier: Optional[specifiers.BaseSpecifier] = None,
hashes: Optional[Hashes] = None,
) -> "CandidateEvaluator"... | [
"def",
"create",
"(",
"cls",
",",
"project_name",
":",
"str",
",",
"target_python",
":",
"Optional",
"[",
"TargetPython",
"]",
"=",
"None",
",",
"prefer_binary",
":",
"bool",
"=",
"False",
",",
"allow_all_prereleases",
":",
"bool",
"=",
"False",
",",
"spec... | [
374,
4
] | [
407,
9
] | python | en | ['pt', 'en', 'en'] | True |
CandidateEvaluator.__init__ | (
self,
project_name: str,
supported_tags: List[Tag],
specifier: specifiers.BaseSpecifier,
prefer_binary: bool = False,
allow_all_prereleases: bool = False,
hashes: Optional[Hashes] = None,
) |
:param supported_tags: The PEP 425 tags supported by the target
Python in order of preference (most preferred first).
|
:param supported_tags: The PEP 425 tags supported by the target
Python in order of preference (most preferred first).
| def __init__(
self,
project_name: str,
supported_tags: List[Tag],
specifier: specifiers.BaseSpecifier,
prefer_binary: bool = False,
allow_all_prereleases: bool = False,
hashes: Optional[Hashes] = None,
) -> None:
"""
:param supported_tags: The ... | [
"def",
"__init__",
"(",
"self",
",",
"project_name",
":",
"str",
",",
"supported_tags",
":",
"List",
"[",
"Tag",
"]",
",",
"specifier",
":",
"specifiers",
".",
"BaseSpecifier",
",",
"prefer_binary",
":",
"bool",
"=",
"False",
",",
"allow_all_prereleases",
":... | [
409,
4
] | [
433,
9
] | python | en | ['en', 'error', 'th'] | False |
CandidateEvaluator.get_applicable_candidates | (
self,
candidates: List[InstallationCandidate],
) |
Return the applicable candidates from a list of candidates.
|
Return the applicable candidates from a list of candidates.
| def get_applicable_candidates(
self,
candidates: List[InstallationCandidate],
) -> List[InstallationCandidate]:
"""
Return the applicable candidates from a list of candidates.
"""
# Using None infers from the specifier instead.
allow_prereleases = self._allow_... | [
"def",
"get_applicable_candidates",
"(",
"self",
",",
"candidates",
":",
"List",
"[",
"InstallationCandidate",
"]",
",",
")",
"->",
"List",
"[",
"InstallationCandidate",
"]",
":",
"# Using None infers from the specifier instead.",
"allow_prereleases",
"=",
"self",
".",
... | [
435,
4
] | [
470,
73
] | python | en | ['en', 'error', 'th'] | False |
CandidateEvaluator._sort_key | (self, candidate: InstallationCandidate) |
Function to pass as the `key` argument to a call to sorted() to sort
InstallationCandidates by preference.
Returns a tuple such that tuples sorting as greater using Python's
default comparison operator are more preferred.
The preference is as follows:
First and foremo... |
Function to pass as the `key` argument to a call to sorted() to sort
InstallationCandidates by preference. | def _sort_key(self, candidate: InstallationCandidate) -> CandidateSortingKey:
"""
Function to pass as the `key` argument to a call to sorted() to sort
InstallationCandidates by preference.
Returns a tuple such that tuples sorting as greater using Python's
default comparison oper... | [
"def",
"_sort_key",
"(",
"self",
",",
"candidate",
":",
"InstallationCandidate",
")",
"->",
"CandidateSortingKey",
":",
"valid_tags",
"=",
"self",
".",
"_supported_tags",
"support_num",
"=",
"len",
"(",
"valid_tags",
")",
"build_tag",
":",
"BuildTag",
"=",
"(",
... | [
472,
4
] | [
532,
9
] | python | en | ['en', 'error', 'th'] | False |
CandidateEvaluator.sort_best_candidate | (
self,
candidates: List[InstallationCandidate],
) |
Return the best candidate per the instance's sort order, or None if
no candidate is acceptable.
|
Return the best candidate per the instance's sort order, or None if
no candidate is acceptable.
| def sort_best_candidate(
self,
candidates: List[InstallationCandidate],
) -> Optional[InstallationCandidate]:
"""
Return the best candidate per the instance's sort order, or None if
no candidate is acceptable.
"""
if not candidates:
return None
... | [
"def",
"sort_best_candidate",
"(",
"self",
",",
"candidates",
":",
"List",
"[",
"InstallationCandidate",
"]",
",",
")",
"->",
"Optional",
"[",
"InstallationCandidate",
"]",
":",
"if",
"not",
"candidates",
":",
"return",
"None",
"best_candidate",
"=",
"max",
"(... | [
534,
4
] | [
545,
29
] | python | en | ['en', 'error', 'th'] | False |
CandidateEvaluator.compute_best_candidate | (
self,
candidates: List[InstallationCandidate],
) |
Compute and return a `BestCandidateResult` instance.
|
Compute and return a `BestCandidateResult` instance.
| def compute_best_candidate(
self,
candidates: List[InstallationCandidate],
) -> BestCandidateResult:
"""
Compute and return a `BestCandidateResult` instance.
"""
applicable_candidates = self.get_applicable_candidates(candidates)
best_candidate = self.sort_bes... | [
"def",
"compute_best_candidate",
"(",
"self",
",",
"candidates",
":",
"List",
"[",
"InstallationCandidate",
"]",
",",
")",
"->",
"BestCandidateResult",
":",
"applicable_candidates",
"=",
"self",
".",
"get_applicable_candidates",
"(",
"candidates",
")",
"best_candidate... | [
547,
4
] | [
562,
9
] | python | en | ['en', 'error', 'th'] | False |
PackageFinder.__init__ | (
self,
link_collector: LinkCollector,
target_python: TargetPython,
allow_yanked: bool,
format_control: Optional[FormatControl] = None,
candidate_prefs: Optional[CandidatePreferences] = None,
ignore_requires_python: Optional[bool] = None,
) |
This constructor is primarily meant to be used by the create() class
method and from tests.
:param format_control: A FormatControl object, used to control
the selection of source packages / binary packages when consulting
the index and links.
:param candidate_pr... |
This constructor is primarily meant to be used by the create() class
method and from tests. | def __init__(
self,
link_collector: LinkCollector,
target_python: TargetPython,
allow_yanked: bool,
format_control: Optional[FormatControl] = None,
candidate_prefs: Optional[CandidatePreferences] = None,
ignore_requires_python: Optional[bool] = None,
) -> None... | [
"def",
"__init__",
"(",
"self",
",",
"link_collector",
":",
"LinkCollector",
",",
"target_python",
":",
"TargetPython",
",",
"allow_yanked",
":",
"bool",
",",
"format_control",
":",
"Optional",
"[",
"FormatControl",
"]",
"=",
"None",
",",
"candidate_prefs",
":",... | [
572,
4
] | [
605,
45
] | python | en | ['en', 'error', 'th'] | False |
PackageFinder.create | (
cls,
link_collector: LinkCollector,
selection_prefs: SelectionPreferences,
target_python: Optional[TargetPython] = None,
) | Create a PackageFinder.
:param selection_prefs: The candidate selection preferences, as a
SelectionPreferences object.
:param target_python: The target Python interpreter to use when
checking compatibility. If None (the default), a TargetPython
object will be constru... | Create a PackageFinder. | def create(
cls,
link_collector: LinkCollector,
selection_prefs: SelectionPreferences,
target_python: Optional[TargetPython] = None,
) -> "PackageFinder":
"""Create a PackageFinder.
:param selection_prefs: The candidate selection preferences, as a
Selecti... | [
"def",
"create",
"(",
"cls",
",",
"link_collector",
":",
"LinkCollector",
",",
"selection_prefs",
":",
"SelectionPreferences",
",",
"target_python",
":",
"Optional",
"[",
"TargetPython",
"]",
"=",
"None",
",",
")",
"->",
"\"PackageFinder\"",
":",
"if",
"target_p... | [
612,
4
] | [
641,
9
] | python | en | ['en', 'af', 'en'] | True |
PackageFinder._sort_links | (self, links: Iterable[Link]) |
Returns elements of links in order, non-egg links first, egg links
second, while eliminating duplicates
|
Returns elements of links in order, non-egg links first, egg links
second, while eliminating duplicates
| def _sort_links(self, links: Iterable[Link]) -> List[Link]:
"""
Returns elements of links in order, non-egg links first, egg links
second, while eliminating duplicates
"""
eggs, no_eggs = [], []
seen: Set[Link] = set()
for link in links:
if link not in... | [
"def",
"_sort_links",
"(",
"self",
",",
"links",
":",
"Iterable",
"[",
"Link",
"]",
")",
"->",
"List",
"[",
"Link",
"]",
":",
"eggs",
",",
"no_eggs",
"=",
"[",
"]",
",",
"[",
"]",
"seen",
":",
"Set",
"[",
"Link",
"]",
"=",
"set",
"(",
")",
"f... | [
695,
4
] | [
709,
29
] | python | en | ['en', 'error', 'th'] | False |
PackageFinder.get_install_candidate | (
self, link_evaluator: LinkEvaluator, link: Link
) |
If the link is a candidate for install, convert it to an
InstallationCandidate and return it. Otherwise, return None.
|
If the link is a candidate for install, convert it to an
InstallationCandidate and return it. Otherwise, return None.
| def get_install_candidate(
self, link_evaluator: LinkEvaluator, link: Link
) -> Optional[InstallationCandidate]:
"""
If the link is a candidate for install, convert it to an
InstallationCandidate and return it. Otherwise, return None.
"""
is_candidate, result = link_e... | [
"def",
"get_install_candidate",
"(",
"self",
",",
"link_evaluator",
":",
"LinkEvaluator",
",",
"link",
":",
"Link",
")",
"->",
"Optional",
"[",
"InstallationCandidate",
"]",
":",
"is_candidate",
",",
"result",
"=",
"link_evaluator",
".",
"evaluate_link",
"(",
"l... | [
718,
4
] | [
735,
9
] | python | en | ['en', 'error', 'th'] | False |
PackageFinder.evaluate_links | (
self, link_evaluator: LinkEvaluator, links: Iterable[Link]
) |
Convert links that are candidates to InstallationCandidate objects.
|
Convert links that are candidates to InstallationCandidate objects.
| def evaluate_links(
self, link_evaluator: LinkEvaluator, links: Iterable[Link]
) -> List[InstallationCandidate]:
"""
Convert links that are candidates to InstallationCandidate objects.
"""
candidates = []
for link in self._sort_links(links):
candidate = se... | [
"def",
"evaluate_links",
"(",
"self",
",",
"link_evaluator",
":",
"LinkEvaluator",
",",
"links",
":",
"Iterable",
"[",
"Link",
"]",
")",
"->",
"List",
"[",
"InstallationCandidate",
"]",
":",
"candidates",
"=",
"[",
"]",
"for",
"link",
"in",
"self",
".",
... | [
737,
4
] | [
749,
25
] | python | en | ['en', 'error', 'th'] | False |
PackageFinder.find_all_candidates | (self, project_name: str) | Find all available InstallationCandidate for project_name
This checks index_urls and find_links.
All versions found are returned as an InstallationCandidate list.
See LinkEvaluator.evaluate_link() for details on which files
are accepted.
| Find all available InstallationCandidate for project_name | def find_all_candidates(self, project_name: str) -> List[InstallationCandidate]:
"""Find all available InstallationCandidate for project_name
This checks index_urls and find_links.
All versions found are returned as an InstallationCandidate list.
See LinkEvaluator.evaluate_link() for d... | [
"def",
"find_all_candidates",
"(",
"self",
",",
"project_name",
":",
"str",
")",
"->",
"List",
"[",
"InstallationCandidate",
"]",
":",
"link_evaluator",
"=",
"self",
".",
"make_link_evaluator",
"(",
"project_name",
")",
"collected_sources",
"=",
"self",
".",
"_l... | [
772,
4
] | [
815,
48
] | python | en | ['en', 'en', 'en'] | True |
PackageFinder.make_candidate_evaluator | (
self,
project_name: str,
specifier: Optional[specifiers.BaseSpecifier] = None,
hashes: Optional[Hashes] = None,
) | Create a CandidateEvaluator object to use.
| Create a CandidateEvaluator object to use.
| def make_candidate_evaluator(
self,
project_name: str,
specifier: Optional[specifiers.BaseSpecifier] = None,
hashes: Optional[Hashes] = None,
) -> CandidateEvaluator:
"""Create a CandidateEvaluator object to use.
"""
candidate_prefs = self._candidate_prefs
... | [
"def",
"make_candidate_evaluator",
"(",
"self",
",",
"project_name",
":",
"str",
",",
"specifier",
":",
"Optional",
"[",
"specifiers",
".",
"BaseSpecifier",
"]",
"=",
"None",
",",
"hashes",
":",
"Optional",
"[",
"Hashes",
"]",
"=",
"None",
",",
")",
"->",
... | [
817,
4
] | [
833,
9
] | python | en | ['en', 'en', 'en'] | True |
PackageFinder.find_best_candidate | (
self,
project_name: str,
specifier: Optional[specifiers.BaseSpecifier] = None,
hashes: Optional[Hashes] = None,
) | Find matches for the given project and specifier.
:param specifier: An optional object implementing `filter`
(e.g. `packaging.specifiers.SpecifierSet`) to filter applicable
versions.
:return: A `BestCandidateResult` instance.
| Find matches for the given project and specifier. | def find_best_candidate(
self,
project_name: str,
specifier: Optional[specifiers.BaseSpecifier] = None,
hashes: Optional[Hashes] = None,
) -> BestCandidateResult:
"""Find matches for the given project and specifier.
:param specifier: An optional object implementing `... | [
"def",
"find_best_candidate",
"(",
"self",
",",
"project_name",
":",
"str",
",",
"specifier",
":",
"Optional",
"[",
"specifiers",
".",
"BaseSpecifier",
"]",
"=",
"None",
",",
"hashes",
":",
"Optional",
"[",
"Hashes",
"]",
"=",
"None",
",",
")",
"->",
"Be... | [
836,
4
] | [
856,
69
] | python | en | ['en', 'en', 'en'] | True |
PackageFinder.find_requirement | (
self, req: InstallRequirement, upgrade: bool
) | Try to find a Link matching req
Expects req, an InstallRequirement and upgrade, a boolean
Returns a InstallationCandidate if found,
Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise
| Try to find a Link matching req | def find_requirement(
self, req: InstallRequirement, upgrade: bool
) -> Optional[InstallationCandidate]:
"""Try to find a Link matching req
Expects req, an InstallRequirement and upgrade, a boolean
Returns a InstallationCandidate if found,
Raises DistributionNotFound or Best... | [
"def",
"find_requirement",
"(",
"self",
",",
"req",
":",
"InstallRequirement",
",",
"upgrade",
":",
"bool",
")",
"->",
"Optional",
"[",
"InstallationCandidate",
"]",
":",
"hashes",
"=",
"req",
".",
"hashes",
"(",
"trust_internet",
"=",
"False",
")",
"best_ca... | [
858,
4
] | [
937,
29
] | python | en | ['en', 'en', 'en'] | True |
_markers | (pem_marker) |
Returns the start and end PEM markers, as bytes.
|
Returns the start and end PEM markers, as bytes.
| def _markers(pem_marker):
"""
Returns the start and end PEM markers, as bytes.
"""
if not is_bytes(pem_marker):
pem_marker = pem_marker.encode('ascii')
return (b'-----BEGIN ' + pem_marker + b'-----',
b'-----END ' + pem_marker + b'-----') | [
"def",
"_markers",
"(",
"pem_marker",
")",
":",
"if",
"not",
"is_bytes",
"(",
"pem_marker",
")",
":",
"pem_marker",
"=",
"pem_marker",
".",
"encode",
"(",
"'ascii'",
")",
"return",
"(",
"b'-----BEGIN '",
"+",
"pem_marker",
"+",
"b'-----'",
",",
"b'-----END '... | [
23,
0
] | [
32,
49
] | python | en | ['en', 'error', 'th'] | False |
load_pem | (contents, pem_marker) | Loads a PEM file.
:param contents: the contents of the file to interpret
:param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
when your file has '-----BEGIN RSA PRIVATE KEY-----' and
'-----END RSA PRIVATE KEY-----' markers.
:return: the base64-decoded content between... | Loads a PEM file. | def load_pem(contents, pem_marker):
"""Loads a PEM file.
:param contents: the contents of the file to interpret
:param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
when your file has '-----BEGIN RSA PRIVATE KEY-----' and
'-----END RSA PRIVATE KEY-----' markers.
... | [
"def",
"load_pem",
"(",
"contents",
",",
"pem_marker",
")",
":",
"# We want bytes, not text. If it's text, it can be converted to ASCII bytes.",
"if",
"not",
"is_bytes",
"(",
"contents",
")",
":",
"contents",
"=",
"contents",
".",
"encode",
"(",
"'ascii'",
")",
"(",
... | [
35,
0
] | [
98,
41
] | python | en | ['en', 'bg', 'en'] | True |
save_pem | (contents, pem_marker) | Saves a PEM file.
:param contents: the contents to encode in PEM format
:param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
when your file has '-----BEGIN RSA PRIVATE KEY-----' and
'-----END RSA PRIVATE KEY-----' markers.
:return: the base64-encoded content between ... | Saves a PEM file. | def save_pem(contents, pem_marker):
"""Saves a PEM file.
:param contents: the contents to encode in PEM format
:param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
when your file has '-----BEGIN RSA PRIVATE KEY-----' and
'-----END RSA PRIVATE KEY-----' markers.
:... | [
"def",
"save_pem",
"(",
"contents",
",",
"pem_marker",
")",
":",
"(",
"pem_start",
",",
"pem_end",
")",
"=",
"_markers",
"(",
"pem_marker",
")",
"b64",
"=",
"base64",
".",
"standard_b64encode",
"(",
"contents",
")",
".",
"replace",
"(",
"b'\\n'",
",",
"b... | [
101,
0
] | [
125,
32
] | python | en | ['en', 'hi-Latn', 'en'] | True |
BaseItemRecommendation.__init__ | (self, train_file, test_file, output_file=None, as_binary=False, rank_length=10,
similarity_metric="cosine", sep='\t', output_sep='\t') |
This class is base for all item recommendation algorithms. Inherits the class Recommender
and implements / adds common methods and attributes for rank approaches.
:param train_file: File which contains the train set. This file needs to have at least 3 columns
(user item feedback_valu... |
This class is base for all item recommendation algorithms. Inherits the class Recommender
and implements / adds common methods and attributes for rank approaches. | def __init__(self, train_file, test_file, output_file=None, as_binary=False, rank_length=10,
similarity_metric="cosine", sep='\t', output_sep='\t'):
"""
This class is base for all item recommendation algorithms. Inherits the class Recommender
and implements / adds common metho... | [
"def",
"__init__",
"(",
"self",
",",
"train_file",
",",
"test_file",
",",
"output_file",
"=",
"None",
",",
"as_binary",
"=",
"False",
",",
"rank_length",
"=",
"10",
",",
"similarity_metric",
"=",
"\"cosine\"",
",",
"sep",
"=",
"'\\t'",
",",
"output_sep",
"... | [
19,
4
] | [
75,
25
] | python | en | ['en', 'error', 'th'] | False |
BaseItemRecommendation.read_files | (self) |
Method to initialize recommender algorithm.
|
Method to initialize recommender algorithm. | def read_files(self):
"""
Method to initialize recommender algorithm.
"""
self.train_set = ReadFile(self.train_file, sep=self.sep, as_binary=self.as_binary).read()
if self.test_file is not None:
self.test_set = ReadFile(self.test_file).read()
self.users ... | [
"def",
"read_files",
"(",
"self",
")",
":",
"self",
".",
"train_set",
"=",
"ReadFile",
"(",
"self",
".",
"train_file",
",",
"sep",
"=",
"self",
".",
"sep",
",",
"as_binary",
"=",
"self",
".",
"as_binary",
")",
".",
"read",
"(",
")",
"if",
"self",
"... | [
77,
4
] | [
97,
50
] | python | en | ['en', 'error', 'th'] | False |
BaseItemRecommendation.create_matrix | (self) |
Method to create a feedback matrix
|
Method to create a feedback matrix | def create_matrix(self):
"""
Method to create a feedback matrix
"""
self.matrix = np.zeros((len(self.users), len(self.items)))
for user in self.train_set['users']:
for item in self.train_set['feedback'][user]:
self.matrix[self.user_to_user_id[user]]... | [
"def",
"create_matrix",
"(",
"self",
")",
":",
"self",
".",
"matrix",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"self",
".",
"users",
")",
",",
"len",
"(",
"self",
".",
"items",
")",
")",
")",
"for",
"user",
"in",
"self",
".",
"train_set",
... | [
99,
4
] | [
110,
58
] | python | en | ['en', 'error', 'th'] | False |
BaseItemRecommendation.compute_similarity | (self, transpose=False) |
Method to compute a similarity matrix from original df_matrix
:param transpose: If True, calculate the similarity in a transpose matrix
:type transpose: bool, default False
|
Method to compute a similarity matrix from original df_matrix | def compute_similarity(self, transpose=False):
"""
Method to compute a similarity matrix from original df_matrix
:param transpose: If True, calculate the similarity in a transpose matrix
:type transpose: bool, default False
"""
# Calculate distance matrix
if tr... | [
"def",
"compute_similarity",
"(",
"self",
",",
"transpose",
"=",
"False",
")",
":",
"# Calculate distance matrix",
"if",
"transpose",
":",
"similarity_matrix",
"=",
"np",
".",
"float32",
"(",
"squareform",
"(",
"pdist",
"(",
"self",
".",
"matrix",
".",
"T",
... | [
112,
4
] | [
132,
32
] | python | en | ['en', 'error', 'th'] | False |
BaseItemRecommendation.evaluate | (self, metrics, verbose=True, as_table=False, table_sep='\t', n_ranks=None) |
Method to evaluate the final ranking
:param metrics: List of evaluation metrics
:type metrics: list, default ('Prec', 'Recall', 'MAP, 'NDCG')
:param verbose: Print the evaluation results
:type verbose: bool, default True
:param as_table: Print the evaluation results a... |
Method to evaluate the final ranking | def evaluate(self, metrics, verbose=True, as_table=False, table_sep='\t', n_ranks=None):
"""
Method to evaluate the final ranking
:param metrics: List of evaluation metrics
:type metrics: list, default ('Prec', 'Recall', 'MAP, 'NDCG')
:param verbose: Print the evaluation result... | [
"def",
"evaluate",
"(",
"self",
",",
"metrics",
",",
"verbose",
"=",
"True",
",",
"as_table",
"=",
"False",
",",
"table_sep",
"=",
"'\\t'",
",",
"n_ranks",
"=",
"None",
")",
":",
"self",
".",
"evaluation_results",
"=",
"{",
"}",
"if",
"metrics",
"is",
... | [
134,
4
] | [
162,
86
] | python | en | ['en', 'error', 'th'] | False |
BaseItemRecommendation.write_ranking | (self) |
Method to write final ranking
|
Method to write final ranking | def write_ranking(self):
"""
Method to write final ranking
"""
if self.output_file is not None:
WriteFile(self.output_file, data=self.ranking, sep=self.sep).write() | [
"def",
"write_ranking",
"(",
"self",
")",
":",
"if",
"self",
".",
"output_file",
"is",
"not",
"None",
":",
"WriteFile",
"(",
"self",
".",
"output_file",
",",
"data",
"=",
"self",
".",
"ranking",
",",
"sep",
"=",
"self",
".",
"sep",
")",
".",
"write",... | [
164,
4
] | [
171,
80
] | python | en | ['en', 'error', 'th'] | False |
BaseItemRecommendation.compute | (self, verbose=True) |
Method to run the recommender algorithm
:param verbose: Print the information about recommender
:type verbose: bool, default True
|
Method to run the recommender algorithm | def compute(self, verbose=True):
"""
Method to run the recommender algorithm
:param verbose: Print the information about recommender
:type verbose: bool, default True
"""
# read files
self.read_files()
# initialize empty ranking (Don't remove: importan... | [
"def",
"compute",
"(",
"self",
",",
"verbose",
"=",
"True",
")",
":",
"# read files",
"self",
".",
"read_files",
"(",
")",
"# initialize empty ranking (Don't remove: important to Cross Validation)",
"self",
".",
"ranking",
"=",
"[",
"]",
"if",
"verbose",
":",
"tes... | [
173,
4
] | [
207,
46
] | python | en | ['en', 'error', 'th'] | False |
Loader.get_template_sources | (self, template_name) |
Return an Origin object pointing to an absolute path in each directory
in template_dirs. For security reasons, if a path doesn't lie inside
one of the template_dirs it is excluded from the result set.
|
Return an Origin object pointing to an absolute path in each directory
in template_dirs. For security reasons, if a path doesn't lie inside
one of the template_dirs it is excluded from the result set.
| def get_template_sources(self, template_name):
"""
Return an Origin object pointing to an absolute path in each directory
in template_dirs. For security reasons, if a path doesn't lie inside
one of the template_dirs it is excluded from the result set.
"""
for template_dir... | [
"def",
"get_template_sources",
"(",
"self",
",",
"template_name",
")",
":",
"for",
"template_dir",
"in",
"self",
".",
"get_dirs",
"(",
")",
":",
"try",
":",
"name",
"=",
"safe_join",
"(",
"template_dir",
",",
"template_name",
")",
"except",
"SuspiciousFileOper... | [
27,
4
] | [
45,
13
] | python | en | ['en', 'error', 'th'] | False |
HDFStorage.download_files | (self, urls, count_callback=None) | Downloads all necessary files that are not yet stored on the disk using multiple processes.
download_finished_callback and error_callback cannot be bound or unbound methods in Windows, so pass
functions instead.
| Downloads all necessary files that are not yet stored on the disk using multiple processes.
download_finished_callback and error_callback cannot be bound or unbound methods in Windows, so pass
functions instead.
| def download_files(self, urls, count_callback=None):
"""Downloads all necessary files that are not yet stored on the disk using multiple processes.
download_finished_callback and error_callback cannot be bound or unbound methods in Windows, so pass
functions instead.
"""
urls = l... | [
"def",
"download_files",
"(",
"self",
",",
"urls",
",",
"count_callback",
"=",
"None",
")",
":",
"urls",
"=",
"list",
"(",
"self",
".",
"filter_files",
"(",
"urls",
",",
"self",
".",
"_storage_directory",
")",
")",
"if",
"count_callback",
"is",
"not",
"N... | [
127,
4
] | [
146,
29
] | python | en | ['en', 'en', 'en'] | True |
_int64_feature | (value) | Wrapper for inserting int64 features into Example proto. | Wrapper for inserting int64 features into Example proto. | def _int64_feature(value):
"""Wrapper for inserting int64 features into Example proto."""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(int64_list=tf.train.Int64List(value=value)) | [
"def",
"_int64_feature",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"value",
"]",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"int64_list",
"=",
"tf",
".",
"train",
".",
"Int64Lis... | [
41,
0
] | [
45,
69
] | python | en | ['en', 'en', 'en'] | True |
_bytes_feature | (value) | Wrapper for inserting bytes features into Example proto. | Wrapper for inserting bytes features into Example proto. | def _bytes_feature(value):
"""Wrapper for inserting bytes features into Example proto."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) | [
"def",
"_bytes_feature",
"(",
"value",
")",
":",
"return",
"tf",
".",
"train",
".",
"Feature",
"(",
"bytes_list",
"=",
"tf",
".",
"train",
".",
"BytesList",
"(",
"value",
"=",
"[",
"value",
"]",
")",
")"
] | [
48,
0
] | [
50,
71
] | python | en | ['en', 'en', 'en'] | True |
_convert_to_example | (filename, image_buffer, label_int, label_str, height,
width) | Build an Example proto for an example.
Args:
filename: string, path to an image file, e.g., '/path/to/example.JPG'
image_buffer: string, JPEG encoding of RGB image
label_int: integer, identifier for ground truth (0-based)
label_str: string, identifier for ground truth, e.g., 'daisy'
height: integ... | Build an Example proto for an example. | def _convert_to_example(filename, image_buffer, label_int, label_str, height,
width):
"""Build an Example proto for an example.
Args:
filename: string, path to an image file, e.g., '/path/to/example.JPG'
image_buffer: string, JPEG encoding of RGB image
label_int: integer, identi... | [
"def",
"_convert_to_example",
"(",
"filename",
",",
"image_buffer",
",",
"label_int",
",",
"label_str",
",",
"height",
",",
"width",
")",
":",
"colorspace",
"=",
"'RGB'",
"channels",
"=",
"3",
"image_format",
"=",
"'JPEG'",
"example",
"=",
"tf",
".",
"train"... | [
53,
0
] | [
85,
16
] | python | en | ['en', 'en', 'en'] | True |
_get_image_data | (filename, coder) | Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height: integer, image height in pixels.
width: integer, im... | Process a single image file. | def _get_image_data(filename, coder):
"""Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height: integer, ima... | [
"def",
"_get_image_data",
"(",
"filename",
",",
"coder",
")",
":",
"# Read the image file.",
"with",
"tf",
".",
"gfile",
".",
"FastGFile",
"(",
"filename",
",",
"'r'",
")",
"as",
"ifp",
":",
"image_data",
"=",
"ifp",
".",
"read",
"(",
")",
"# Decode the RG... | [
110,
0
] | [
134,
34
] | python | en | ['en', 'ny', 'en'] | True |
convert_to_example | (csvline, categories) | Parse a line of CSV file and convert to TF Record.
Args:
csvline: line from input CSV file
categories: list of labels
Yields:
serialized TF example if the label is in categories
| Parse a line of CSV file and convert to TF Record. | def convert_to_example(csvline, categories):
"""Parse a line of CSV file and convert to TF Record.
Args:
csvline: line from input CSV file
categories: list of labels
Yields:
serialized TF example if the label is in categories
"""
filename, label = csvline.encode('ascii', 'ignore').split(',')
if... | [
"def",
"convert_to_example",
"(",
"csvline",
",",
"categories",
")",
":",
"filename",
",",
"label",
"=",
"csvline",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
".",
"split",
"(",
"','",
")",
"if",
"label",
"in",
"categories",
":",
"# ignore labels... | [
137,
0
] | [
154,
37
] | python | en | ['en', 'en', 'en'] | True |
distutils_scheme | (
dist_name: str,
user: bool = False,
home: str = None,
root: str = None,
isolated: bool = False,
prefix: str = None,
*,
ignore_config_files: bool = False,
) |
Return a distutils install scheme
|
Return a distutils install scheme
| def distutils_scheme(
dist_name: str,
user: bool = False,
home: str = None,
root: str = None,
isolated: bool = False,
prefix: str = None,
*,
ignore_config_files: bool = False,
) -> Dict[str, str]:
"""
Return a distutils install scheme
"""
from distutils.dist import Distri... | [
"def",
"distutils_scheme",
"(",
"dist_name",
":",
"str",
",",
"user",
":",
"bool",
"=",
"False",
",",
"home",
":",
"str",
"=",
"None",
",",
"root",
":",
"str",
"=",
"None",
",",
"isolated",
":",
"bool",
"=",
"False",
",",
"prefix",
":",
"str",
"=",... | [
23,
0
] | [
101,
17
] | python | en | ['en', 'error', 'th'] | False |
get_scheme | (
dist_name: str,
user: bool = False,
home: Optional[str] = None,
root: Optional[str] = None,
isolated: bool = False,
prefix: Optional[str] = None,
) |
Get the "scheme" corresponding to the input parameters. The distutils
documentation provides the context for the available schemes:
https://docs.python.org/3/install/index.html#alternate-installation
:param dist_name: the name of the package to retrieve the scheme for, used
in the headers sche... |
Get the "scheme" corresponding to the input parameters. The distutils
documentation provides the context for the available schemes:
https://docs.python.org/3/install/index.html#alternate-installation | def get_scheme(
dist_name: str,
user: bool = False,
home: Optional[str] = None,
root: Optional[str] = None,
isolated: bool = False,
prefix: Optional[str] = None,
) -> Scheme:
"""
Get the "scheme" corresponding to the input parameters. The distutils
documentation provides the context ... | [
"def",
"get_scheme",
"(",
"dist_name",
":",
"str",
",",
"user",
":",
"bool",
"=",
"False",
",",
"home",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"root",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"isolated",
":",
"bool",
"=",
... | [
104,
0
] | [
136,
5
] | python | en | ['en', 'error', 'th'] | False |
parse_bits | (parser, bits, params, varargs, varkw, defaults,
kwonly, kwonly_defaults, takes_context, name) |
Parse bits for template tag helpers simple_tag and inclusion_tag, in
particular by detecting syntax errors and by extracting positional and
keyword arguments.
|
Parse bits for template tag helpers simple_tag and inclusion_tag, in
particular by detecting syntax errors and by extracting positional and
keyword arguments.
| def parse_bits(parser, bits, params, varargs, varkw, defaults,
kwonly, kwonly_defaults, takes_context, name):
"""
Parse bits for template tag helpers simple_tag and inclusion_tag, in
particular by detecting syntax errors and by extracting positional and
keyword arguments.
"""
if t... | [
"def",
"parse_bits",
"(",
"parser",
",",
"bits",
",",
"params",
",",
"varargs",
",",
"varkw",
",",
"defaults",
",",
"kwonly",
",",
"kwonly_defaults",
",",
"takes_context",
",",
"name",
")",
":",
"if",
"takes_context",
":",
"if",
"params",
"[",
"0",
"]",
... | [
236,
0
] | [
308,
23
] | python | en | ['en', 'error', 'th'] | False |
import_library | (name) |
Load a Library object from a template tag module.
|
Load a Library object from a template tag module.
| def import_library(name):
"""
Load a Library object from a template tag module.
"""
try:
module = import_module(name)
except ImportError as e:
raise InvalidTemplateLibrary(
"Invalid template library specified. ImportError raised when "
"trying to load '%s': %s... | [
"def",
"import_library",
"(",
"name",
")",
":",
"try",
":",
"module",
"=",
"import_module",
"(",
"name",
")",
"except",
"ImportError",
"as",
"e",
":",
"raise",
"InvalidTemplateLibrary",
"(",
"\"Invalid template library specified. ImportError raised when \"",
"\"trying t... | [
311,
0
] | [
327,
9
] | python | en | ['en', 'error', 'th'] | False |
Library.filter | (self, name=None, filter_func=None, **flags) |
Register a callable as a template filter. Example:
@register.filter
def lower(value):
return value.lower()
|
Register a callable as a template filter. Example: | def filter(self, name=None, filter_func=None, **flags):
"""
Register a callable as a template filter. Example:
@register.filter
def lower(value):
return value.lower()
"""
if name is None and filter_func is None:
# @register.filter()
de... | [
"def",
"filter",
"(",
"self",
",",
"name",
"=",
"None",
",",
"filter_func",
"=",
"None",
",",
"*",
"*",
"flags",
")",
":",
"if",
"name",
"is",
"None",
"and",
"filter_func",
"is",
"None",
":",
"# @register.filter()",
"def",
"dec",
"(",
"func",
")",
":... | [
53,
4
] | [
93,
13
] | python | en | ['en', 'error', 'th'] | False |
Library.simple_tag | (self, func=None, takes_context=None, name=None) |
Register a callable as a compiled template tag. Example:
@register.simple_tag
def hello(*args, **kwargs):
return 'world'
|
Register a callable as a compiled template tag. Example: | def simple_tag(self, func=None, takes_context=None, name=None):
"""
Register a callable as a compiled template tag. Example:
@register.simple_tag
def hello(*args, **kwargs):
return 'world'
"""
def dec(func):
params, varargs, varkw, defaults, kwonl... | [
"def",
"simple_tag",
"(",
"self",
",",
"func",
"=",
"None",
",",
"takes_context",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"def",
"dec",
"(",
"func",
")",
":",
"params",
",",
"varargs",
",",
"varkw",
",",
"defaults",
",",
"kwonly",
",",
"kw... | [
99,
4
] | [
133,
72
] | python | en | ['en', 'error', 'th'] | False |
Library.inclusion_tag | (self, filename, func=None, takes_context=None, name=None) |
Register a callable as an inclusion tag:
@register.inclusion_tag('results.html')
def show_results(poll):
choices = poll.choice_set.all()
return {'choices': choices}
|
Register a callable as an inclusion tag: | def inclusion_tag(self, filename, func=None, takes_context=None, name=None):
"""
Register a callable as an inclusion tag:
@register.inclusion_tag('results.html')
def show_results(poll):
choices = poll.choice_set.all()
return {'choices': choices}
"""
... | [
"def",
"inclusion_tag",
"(",
"self",
",",
"filename",
",",
"func",
"=",
"None",
",",
"takes_context",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"def",
"dec",
"(",
"func",
")",
":",
"params",
",",
"varargs",
",",
"varkw",
",",
"defaults",
",",
... | [
135,
4
] | [
160,
18
] | python | en | ['en', 'error', 'th'] | False |
InclusionNode.render | (self, context) |
Render the specified template and context. Cache the template object
in render_context to avoid reparsing and loading when used in a for
loop.
|
Render the specified template and context. Cache the template object
in render_context to avoid reparsing and loading when used in a for
loop.
| def render(self, context):
"""
Render the specified template and context. Cache the template object
in render_context to avoid reparsing and loading when used in a for
loop.
"""
resolved_args, resolved_kwargs = self.get_resolved_arguments(context)
_dict = self.fun... | [
"def",
"render",
"(",
"self",
",",
"context",
")",
":",
"resolved_args",
",",
"resolved_kwargs",
"=",
"self",
".",
"get_resolved_arguments",
"(",
"context",
")",
"_dict",
"=",
"self",
".",
"func",
"(",
"*",
"resolved_args",
",",
"*",
"*",
"resolved_kwargs",
... | [
206,
4
] | [
233,
36
] | python | en | ['en', 'error', 'th'] | False |
page_not_found | (request, exception, template_name=ERROR_404_TEMPLATE_NAME) |
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/'). It's
quoted to prevent a content injection attack.
exception
The message from the exception which triggered the 404 (... |
Default 404 handler. | def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
"""
Default 404 handler.
Templates: :template:`404.html`
Context:
request_path
The path of the requested URL (e.g., '/app/pages/bad_page/'). It's
quoted to prevent a content injection attack.
... | [
"def",
"page_not_found",
"(",
"request",
",",
"exception",
",",
"template_name",
"=",
"ERROR_404_TEMPLATE_NAME",
")",
":",
"exception_repr",
"=",
"exception",
".",
"__class__",
".",
"__name__",
"# Try to get an \"interesting\" exception message, if any (and not the ugly",
"# ... | [
30,
0
] | [
75,
64
] | python | en | ['en', 'error', 'th'] | False |
server_error | (request, template_name=ERROR_500_TEMPLATE_NAME) |
500 error handler.
Templates: :template:`500.html`
Context: None
|
500 error handler. | def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
"""
500 error handler.
Templates: :template:`500.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
if template_name != ERROR_500_TEMPLATE_NAME:
... | [
"def",
"server_error",
"(",
"request",
",",
"template_name",
"=",
"ERROR_500_TEMPLATE_NAME",
")",
":",
"try",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"template_name",
")",
"except",
"TemplateDoesNotExist",
":",
"if",
"template_name",
"!=",
"ERROR... | [
79,
0
] | [
96,
53
] | python | en | ['en', 'error', 'th'] | False |
bad_request | (request, exception, template_name=ERROR_400_TEMPLATE_NAME) |
400 error handler.
Templates: :template:`400.html`
Context: None
|
400 error handler. | def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
"""
400 error handler.
Templates: :template:`400.html`
Context: None
"""
try:
template = loader.get_template(template_name)
except TemplateDoesNotExist:
if template_name != ERROR_400_TEMPLATE_NAME:
... | [
"def",
"bad_request",
"(",
"request",
",",
"exception",
",",
"template_name",
"=",
"ERROR_400_TEMPLATE_NAME",
")",
":",
"try",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"template_name",
")",
"except",
"TemplateDoesNotExist",
":",
"if",
"template_na... | [
100,
0
] | [
118,
52
] | python | en | ['en', 'error', 'th'] | False |
permission_denied | (request, exception, template_name=ERROR_403_TEMPLATE_NAME) |
Permission denied (403) handler.
Templates: :template:`403.html`
Context: None
If the template does not exist, an Http403 response containing the text
"403 Forbidden" (as per RFC 7231) will be returned.
|
Permission denied (403) handler. | def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
"""
Permission denied (403) handler.
Templates: :template:`403.html`
Context: None
If the template does not exist, an Http403 response containing the text
"403 Forbidden" (as per RFC 7231) will be returned.
"... | [
"def",
"permission_denied",
"(",
"request",
",",
"exception",
",",
"template_name",
"=",
"ERROR_403_TEMPLATE_NAME",
")",
":",
"try",
":",
"template",
"=",
"loader",
".",
"get_template",
"(",
"template_name",
")",
"except",
"TemplateDoesNotExist",
":",
"if",
"templ... | [
125,
0
] | [
147,
5
] | python | en | ['en', 'error', 'th'] | False |
compute_class_weights | (root, train_data_list) |
We want to weight the the positive pixels by the ratio of negative to positive.
Three scenarios:
1. Equal classes. neg/pos ~ 1. Standard binary cross-entropy
2. Many more negative examples. The network will learn to always output negative. In this way we want to
i... |
We want to weight the the positive pixels by the ratio of negative to positive.
Three scenarios:
1. Equal classes. neg/pos ~ 1. Standard binary cross-entropy
2. Many more negative examples. The network will learn to always output negative. In this way we want to
i... | def compute_class_weights(root, train_data_list):
'''
We want to weight the the positive pixels by the ratio of negative to positive.
Three scenarios:
1. Equal classes. neg/pos ~ 1. Standard binary cross-entropy
2. Many more negative examples. The network will learn to always... | [
"def",
"compute_class_weights",
"(",
"root",
",",
"train_data_list",
")",
":",
"pos",
"=",
"0.0",
"neg",
"=",
"0.0",
"for",
"img_name",
"in",
"tqdm",
"(",
"train_data_list",
")",
":",
"img",
"=",
"sitk",
".",
"GetArrayFromImage",
"(",
"sitk",
".",
"ReadIma... | [
56,
0
] | [
77,
20
] | python | en | ['en', 'error', 'th'] | False |
validate_twilio_request | (f) | Validates that incoming requests genuinely originated from Twilio | Validates that incoming requests genuinely originated from Twilio | def validate_twilio_request(f):
"""Validates that incoming requests genuinely originated from Twilio"""
@wraps(f)
def decorated_function(*args, **kwargs):
# Create an instance of the RequestValidator class
validator = RequestValidator(os.environ.get('TWILIO_AUTH_TOKEN'))
# Validate ... | [
"def",
"validate_twilio_request",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"decorated_function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Create an instance of the RequestValidator class",
"validator",
"=",
"RequestValidator",
"(",
... | [
10,
0
] | [
30,
29
] | python | en | ['en', 'en', 'en'] | True |
convert_exception_to_response | (get_response) |
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate response, and all other exceptions will be
converted to 5... |
Wrap the given get_response callable in exception-to-response conversion. | def convert_exception_to_response(get_response):
"""
Wrap the given get_response callable in exception-to-response conversion.
All exceptions will be converted. All known 4xx exceptions (Http404,
PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
converted to the appropriate respo... | [
"def",
"convert_exception_to_response",
"(",
"get_response",
")",
":",
"if",
"asyncio",
".",
"iscoroutinefunction",
"(",
"get_response",
")",
":",
"@",
"wraps",
"(",
"get_response",
")",
"async",
"def",
"inner",
"(",
"request",
")",
":",
"try",
":",
"response"... | [
20,
0
] | [
50,
20
] | python | en | ['en', 'error', 'th'] | False |
handle_uncaught_exception | (request, resolver, exc_info) |
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
|
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
| def handle_uncaught_exception(request, resolver, exc_info):
"""
Processing for any otherwise uncaught exceptions (those that will
generate HTTP 500 responses).
"""
if settings.DEBUG_PROPAGATE_EXCEPTIONS:
raise
if settings.DEBUG:
return debug.technical_500_response(request, *exc_... | [
"def",
"handle_uncaught_exception",
"(",
"request",
",",
"resolver",
",",
"exc_info",
")",
":",
"if",
"settings",
".",
"DEBUG_PROPAGATE_EXCEPTIONS",
":",
"raise",
"if",
"settings",
".",
"DEBUG",
":",
"return",
"debug",
".",
"technical_500_response",
"(",
"request"... | [
139,
0
] | [
152,
28
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.to_python | (self, value) | Transform the value to a Geometry object. | Transform the value to a Geometry object. | def to_python(self, value):
"""Transform the value to a Geometry object."""
if value in self.empty_values:
return None
if not isinstance(value, GEOSGeometry):
if hasattr(self.widget, 'deserialize'):
try:
value = self.widget.deserialize... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"in",
"self",
".",
"empty_values",
":",
"return",
"None",
"if",
"not",
"isinstance",
"(",
"value",
",",
"GEOSGeometry",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"widget",
",",
... | [
33,
4
] | [
59,
20
] | python | en | ['en', 'en', 'en'] | True |
GeometryField.clean | (self, value) |
Validate that the input value can be converted to a Geometry object
and return it. Raise a ValidationError if the value cannot be
instantiated as a Geometry.
|
Validate that the input value can be converted to a Geometry object
and return it. Raise a ValidationError if the value cannot be
instantiated as a Geometry.
| def clean(self, value):
"""
Validate that the input value can be converted to a Geometry object
and return it. Raise a ValidationError if the value cannot be
instantiated as a Geometry.
"""
geom = super().clean(value)
if geom is None:
return geom
... | [
"def",
"clean",
"(",
"self",
",",
"value",
")",
":",
"geom",
"=",
"super",
"(",
")",
".",
"clean",
"(",
"value",
")",
"if",
"geom",
"is",
"None",
":",
"return",
"geom",
"# Ensuring that the geometry is of the correct type (indicated",
"# using the OGC string label... | [
61,
4
] | [
84,
19
] | python | en | ['en', 'error', 'th'] | False |
GeometryField.has_changed | (self, initial, data) | Compare geographic value of data with its initial value. | Compare geographic value of data with its initial value. | def has_changed(self, initial, data):
""" Compare geographic value of data with its initial value. """
try:
data = self.to_python(data)
initial = self.to_python(initial)
except ValidationError:
return True
# Only do a geographic comparison if both va... | [
"def",
"has_changed",
"(",
"self",
",",
"initial",
",",
"data",
")",
":",
"try",
":",
"data",
"=",
"self",
".",
"to_python",
"(",
"data",
")",
"initial",
"=",
"self",
".",
"to_python",
"(",
"initial",
")",
"except",
"ValidationError",
":",
"return",
"T... | [
86,
4
] | [
104,
46
] | python | en | ['en', 'en', 'en'] | True |
pep562 | (module_name: str) | Helper function to apply PEP 562. | Helper function to apply PEP 562. | def pep562(module_name: str) -> None:
"""Helper function to apply PEP 562."""
if sys.version_info < (3, 7):
Pep562(module_name) | [
"def",
"pep562",
"(",
"module_name",
":",
"str",
")",
"->",
"None",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"7",
")",
":",
"Pep562",
"(",
"module_name",
")"
] | [
56,
0
] | [
60,
27
] | python | en | ['en', 'af', 'en'] | True |
Pep562.__init__ | (self, name: str) | Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7. | Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7. | def __init__(self, name: str) -> None:
"""Acquire `__getattr__` and `__dir__`, but only replace module for versions less than Python 3.7."""
self._module = sys.modules[name]
self._get_attr = getattr(self._module, "__getattr__", None)
self._get_dir: Optional[Callable[..., List[str]]] = g... | [
"def",
"__init__",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"_module",
"=",
"sys",
".",
"modules",
"[",
"name",
"]",
"self",
".",
"_get_attr",
"=",
"getattr",
"(",
"self",
".",
"_module",
",",
"\"__getattr__\"",
",",... | [
28,
4
] | [
36,
32
] | python | en | ['en', 'en', 'en'] | True |
Pep562.__dir__ | (self) | Return the overridden `dir` if one was provided, else apply `dir` to the module. | Return the overridden `dir` if one was provided, else apply `dir` to the module. | def __dir__(self) -> List[str]:
"""Return the overridden `dir` if one was provided, else apply `dir` to the module."""
return self._get_dir() if self._get_dir else dir(self._module) | [
"def",
"__dir__",
"(",
"self",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"self",
".",
"_get_dir",
"(",
")",
"if",
"self",
".",
"_get_dir",
"else",
"dir",
"(",
"self",
".",
"_module",
")"
] | [
38,
4
] | [
41,
70
] | python | en | ['en', 'en', 'en'] | True |
Pep562.__getattr__ | (self, name: str) |
Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.
|
Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.
| def __getattr__(self, name: str) -> Any:
"""
Attempt to retrieve the attribute from the module, and if missing, use the overridden function if present.
"""
try:
return getattr(self._module, name)
except AttributeError:
if self._get_attr:
r... | [
"def",
"__getattr__",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Any",
":",
"try",
":",
"return",
"getattr",
"(",
"self",
".",
"_module",
",",
"name",
")",
"except",
"AttributeError",
":",
"if",
"self",
".",
"_get_attr",
":",
"return",
"self",
... | [
43,
4
] | [
53,
17
] | python | en | ['en', 'error', 'th'] | False |
run | () |
Run the script in sys.argv[1] as if it had
been invoked naturally.
|
Run the script in sys.argv[1] as if it had
been invoked naturally.
| def run():
"""
Run the script in sys.argv[1] as if it had
been invoked naturally.
"""
__builtins__
script_name = sys.argv[1]
namespace = dict(
__file__=script_name,
__name__='__main__',
__doc__=None,
)
sys.argv[:] = sys.argv[1:]
open_ = getattr(tokenize, ... | [
"def",
"run",
"(",
")",
":",
"__builtins__",
"script_name",
"=",
"sys",
".",
"argv",
"[",
"1",
"]",
"namespace",
"=",
"dict",
"(",
"__file__",
"=",
"script_name",
",",
"__name__",
"=",
"'__main__'",
",",
"__doc__",
"=",
"None",
",",
")",
"sys",
".",
... | [
12,
0
] | [
30,
25
] | python | en | ['en', 'error', 'th'] | False |
reshape_gt_to_pred | (pred_pix, gt_pix) | Resize the gt_pix to same size as pred_pix if not.
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
Returns:
gt_pix BxH1xW1
| Resize the gt_pix to same size as pred_pix if not.
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
Returns:
gt_pix BxH1xW1
| def reshape_gt_to_pred(pred_pix, gt_pix):
"""Resize the gt_pix to same size as pred_pix if not.
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
Returns:
gt_pix BxH1xW1
"""
if pred_pix.shape[2:] == gt_pix.shape[1:]:
return gt_pix
gt_pix = nn.functional.interpolate(... | [
"def",
"reshape_gt_to_pred",
"(",
"pred_pix",
",",
"gt_pix",
")",
":",
"if",
"pred_pix",
".",
"shape",
"[",
"2",
":",
"]",
"==",
"gt_pix",
".",
"shape",
"[",
"1",
":",
"]",
":",
"return",
"gt_pix",
"gt_pix",
"=",
"nn",
".",
"functional",
".",
"interp... | [
21,
0
] | [
39,
17
] | python | en | ['en', 'en', 'en'] | True |
PixCELoss._pix_wts_default | (cls, out_dim, gt_pix) | This pixel weighting was used until 2020-01-21. | This pixel weighting was used until 2020-01-21. | def _pix_wts_default(cls, out_dim, gt_pix):
"""This pixel weighting was used until 2020-01-21."""
cls_weights = np.ones((out_dim, ), dtype=np.float32)
cls_weights[0] = 0.1 # 10x lower, as it degenerates to white bgs
return torch.as_tensor(cls_weights, device=gt_pix.device) | [
"def",
"_pix_wts_default",
"(",
"cls",
",",
"out_dim",
",",
"gt_pix",
")",
":",
"cls_weights",
"=",
"np",
".",
"ones",
"(",
"(",
"out_dim",
",",
")",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"cls_weights",
"[",
"0",
"]",
"=",
"0.1",
"# 10x lower... | [
50,
4
] | [
54,
65
] | python | en | ['en', 'en', 'en'] | True |
PixCELoss._pix_wts_count_reciprocal | (cls, out_dim, gt_pix) | This pixel weighting is default from 2020-01-22.
Gave better results on 0018 template. | This pixel weighting is default from 2020-01-22.
Gave better results on 0018 template. | def _pix_wts_count_reciprocal(cls, out_dim, gt_pix):
"""This pixel weighting is default from 2020-01-22.
Gave better results on 0018 template."""
uniq_elts, uniq_cnts = torch.unique(gt_pix, return_counts=True)
uniq_elts = uniq_elts.cpu().numpy().tolist()
uniq_cnts = uniq_cnts.cpu... | [
"def",
"_pix_wts_count_reciprocal",
"(",
"cls",
",",
"out_dim",
",",
"gt_pix",
")",
":",
"uniq_elts",
",",
"uniq_cnts",
"=",
"torch",
".",
"unique",
"(",
"gt_pix",
",",
"return_counts",
"=",
"True",
")",
"uniq_elts",
"=",
"uniq_elts",
".",
"cpu",
"(",
")",... | [
57,
4
] | [
67,
65
] | python | en | ['en', 'en', 'en'] | True |
PixCELoss._per_pixel_softmax | (self, pred_pix, gt_pix) |
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
|
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
| def _per_pixel_softmax(self, pred_pix, gt_pix):
"""
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
"""
pred_pix = pred_pix.permute(0, 2, 3, 1)
out_dim = pred_pix.shape[-1]
cls_weights = self.wt_fn(out_dim, gt_pix)
criterion = nn.CrossEntro... | [
"def",
"_per_pixel_softmax",
"(",
"self",
",",
"pred_pix",
",",
"gt_pix",
")",
":",
"pred_pix",
"=",
"pred_pix",
".",
"permute",
"(",
"0",
",",
"2",
",",
"3",
",",
"1",
")",
"out_dim",
"=",
"pred_pix",
".",
"shape",
"[",
"-",
"1",
"]",
"cls_weights",... | [
69,
4
] | [
80,
20
] | python | en | ['en', 'error', 'th'] | False |
PixCELoss._bce | (cls, pred_pix, gt_pix) |
Binary cross entropy
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
|
Binary cross entropy
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
| def _bce(cls, pred_pix, gt_pix):
"""
Binary cross entropy
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
"""
gt_pix = nn.functional.one_hot(gt_pix,
num_classes=phyre.NUM_COLORS).permute(
... | [
"def",
"_bce",
"(",
"cls",
",",
"pred_pix",
",",
"gt_pix",
")",
":",
"gt_pix",
"=",
"nn",
".",
"functional",
".",
"one_hot",
"(",
"gt_pix",
",",
"num_classes",
"=",
"phyre",
".",
"NUM_COLORS",
")",
".",
"permute",
"(",
"0",
",",
"3",
",",
"1",
",",... | [
83,
4
] | [
94,
42
] | python | en | ['en', 'error', 'th'] | False |
PixCELoss._per_channel_spatial_softmax | (
cls,
pred_pix,
gt_pix,
gt_dist=True,
# Not exposed, used for a quick expt
target_temp=1) |
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
|
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
| def _per_channel_spatial_softmax(
cls,
pred_pix,
gt_pix,
gt_dist=True,
# Not exposed, used for a quick expt
target_temp=1):
"""
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
"""
gt_pix = nn.... | [
"def",
"_per_channel_spatial_softmax",
"(",
"cls",
",",
"pred_pix",
",",
"gt_pix",
",",
"gt_dist",
"=",
"True",
",",
"# Not exposed, used for a quick expt",
"target_temp",
"=",
"1",
")",
":",
"gt_pix",
"=",
"nn",
".",
"functional",
".",
"one_hot",
"(",
"gt_pix",... | [
105,
4
] | [
130,
18
] | python | en | ['en', 'error', 'th'] | False |
PixCELoss._per_channel_spatial_kl | (cls, pred_pix, gt_pix) |
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
|
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
| def _per_channel_spatial_kl(cls, pred_pix, gt_pix):
"""
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
"""
gt_pix = nn.functional.one_hot(gt_pix,
num_classes=phyre.NUM_COLORS).permute(
... | [
"def",
"_per_channel_spatial_kl",
"(",
"cls",
",",
"pred_pix",
",",
"gt_pix",
")",
":",
"gt_pix",
"=",
"nn",
".",
"functional",
".",
"one_hot",
"(",
"gt_pix",
",",
"num_classes",
"=",
"phyre",
".",
"NUM_COLORS",
")",
".",
"permute",
"(",
"0",
",",
"3",
... | [
139,
4
] | [
155,
65
] | python | en | ['en', 'error', 'th'] | False |
PixL2Loss.forward | (self, pred_pix, gt_pix) |
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
|
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
| def forward(self, pred_pix, gt_pix):
"""
Args:
pred_pix ([Bx7xH1xW1])
gt_pix ([BxH2xW2])
"""
gt_pix = reshape_gt_to_pred(pred_pix, gt_pix)
# Add the channel dimension to gt_pix
gt_pix = nn.functional.one_hot(gt_pix,
... | [
"def",
"forward",
"(",
"self",
",",
"pred_pix",
",",
"gt_pix",
")",
":",
"gt_pix",
"=",
"reshape_gt_to_pred",
"(",
"pred_pix",
",",
"gt_pix",
")",
"# Add the channel dimension to gt_pix",
"gt_pix",
"=",
"nn",
".",
"functional",
".",
"one_hot",
"(",
"gt_pix",
"... | [
166,
4
] | [
178,
42
] | python | en | ['en', 'error', 'th'] | False |
InfoNCELoss.__init__ | (self, in_dim, temp=0.07, l2_norm_feats=True, nce_dim=None) |
Args:
in_dim: Dimension of the incoming features
temp (float): temprature
l2_norm_feats (bool): Whether to normalize feats before
nce_dim (int): If not None, reduce the dimensionality to this number
|
Args:
in_dim: Dimension of the incoming features
temp (float): temprature
l2_norm_feats (bool): Whether to normalize feats before
nce_dim (int): If not None, reduce the dimensionality to this number
| def __init__(self, in_dim, temp=0.07, l2_norm_feats=True, nce_dim=None):
"""
Args:
in_dim: Dimension of the incoming features
temp (float): temprature
l2_norm_feats (bool): Whether to normalize feats before
nce_dim (int): If not None, reduce the dimensiona... | [
"def",
"__init__",
"(",
"self",
",",
"in_dim",
",",
"temp",
"=",
"0.07",
",",
"l2_norm_feats",
"=",
"True",
",",
"nce_dim",
"=",
"None",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"temp",
"=",
"temp",
"self",
".",
"l2_norm... | [
183,
4
] | [
199,
41
] | python | en | ['en', 'error', 'th'] | False |
InfoNCELoss.forward | (self, pred, gt) |
Args:
pred (BxNobjxDxH'xW')
gt (BxNobjxDxH'xW')
From https://arxiv.org/pdf/1911.05722.pdf
|
Args:
pred (BxNobjxDxH'xW')
gt (BxNobjxDxH'xW')
From https://arxiv.org/pdf/1911.05722.pdf
| def forward(self, pred, gt):
"""
Args:
pred (BxNobjxDxH'xW')
gt (BxNobjxDxH'xW')
From https://arxiv.org/pdf/1911.05722.pdf
"""
def spatial_to_batch(feat):
"""Move the H', W', Nobj dimension to batch,
so will do a spatial-obj NCE... | [
"def",
"forward",
"(",
"self",
",",
"pred",
",",
"gt",
")",
":",
"def",
"spatial_to_batch",
"(",
"feat",
")",
":",
"\"\"\"Move the H', W', Nobj dimension to batch,\n so will do a spatial-obj NCE.\"\"\"",
"feat_dim",
"=",
"feat",
".",
"shape",
"[",
"2",
"]",... | [
201,
4
] | [
226,
52
] | python | en | ['en', 'error', 'th'] | False |
gen_vis_vid_preds | (orig_vid,
orig_objs,
model,
n_fwd_times=None,
run_decode=True,
n_hist_frames=3) |
Generate a visualization of some training videos, along with model rollout
(actual autoregressive rollout, so need to test again).
Args:
orig_vid: (B, T, Nobj, H, W) video batch
model: the pytorch model for forward prediction
Returns:
RGB frames (B, T, 3, H, W) as torch tensor, ... |
Generate a visualization of some training videos, along with model rollout
(actual autoregressive rollout, so need to test again).
Args:
orig_vid: (B, T, Nobj, H, W) video batch
model: the pytorch model for forward prediction
Returns:
RGB frames (B, T, 3, H, W) as torch tensor, ... | def gen_vis_vid_preds(orig_vid,
orig_objs,
model,
n_fwd_times=None,
run_decode=True,
n_hist_frames=3):
"""
Generate a visualization of some training videos, along with model rollout
(actual autoregr... | [
"def",
"gen_vis_vid_preds",
"(",
"orig_vid",
",",
"orig_objs",
",",
"model",
",",
"n_fwd_times",
"=",
"None",
",",
"run_decode",
"=",
"True",
",",
"n_hist_frames",
"=",
"3",
")",
":",
"# Generate the predictions",
"if",
"n_fwd_times",
"is",
"None",
":",
"n_fwd... | [
42,
0
] | [
83,
39
] | python | en | ['en', 'error', 'th'] | False |
ObjTrainer.load_agent_from_folder | (cls,
model: NeuralModel,
agent_folder: str,
strict: bool = True) |
This loader is used in the offline_agents code, to load at test time.
|
This loader is used in the offline_agents code, to load at test time.
| def load_agent_from_folder(cls,
model: NeuralModel,
agent_folder: str,
strict: bool = True) -> NeuralModel:
"""
This loader is used in the offline_agents code, to load at test time.
"""
last_chec... | [
"def",
"load_agent_from_folder",
"(",
"cls",
",",
"model",
":",
"NeuralModel",
",",
"agent_folder",
":",
"str",
",",
"strict",
":",
"bool",
"=",
"True",
")",
"->",
"NeuralModel",
":",
"last_checkpoint",
"=",
"get_latest_checkpoint",
"(",
"agent_folder",
")",
"... | [
91,
4
] | [
111,
20
] | python | en | ['en', 'error', 'th'] | False |
ObjTrainer.gen_model | (cls, cfg, override_cfg=None, on_cpu=False) | Generate the random init model. | Generate the random init model. | def gen_model(cls, cfg, override_cfg=None, on_cpu=False):
"""Generate the random init model."""
if override_cfg is not None:
model = obj_nets.FwdObject(override_cfg)
else:
model = obj_nets.FwdObject(cfg)
if on_cpu:
return model.cpu()
print('Us... | [
"def",
"gen_model",
"(",
"cls",
",",
"cfg",
",",
"override_cfg",
"=",
"None",
",",
"on_cpu",
"=",
"False",
")",
":",
"if",
"override_cfg",
"is",
"not",
"None",
":",
"model",
"=",
"obj_nets",
".",
"FwdObject",
"(",
"override_cfg",
")",
"else",
":",
"mod... | [
113,
4
] | [
129,
20
] | python | en | ['en', 'ms', 'en'] | True |
ObjTrainer.train | (cls, model, dataset, output_dir, summary_writer,
full_eval_from_model, cfg) | Main train function. | Main train function. | def train(cls, model, dataset, output_dir, summary_writer,
full_eval_from_model, cfg):
"""Main train function."""
updates = cfg.train.num_iter
report_every = cfg.train.report_every
save_checkpoints_every = cfg.train.save_checkpoints_every
full_eval_every = cfg.train... | [
"def",
"train",
"(",
"cls",
",",
"model",
",",
"dataset",
",",
"output_dir",
",",
"summary_writer",
",",
"full_eval_from_model",
",",
"cfg",
")",
":",
"updates",
"=",
"cfg",
".",
"train",
".",
"num_iter",
"report_every",
"=",
"cfg",
".",
"train",
".",
"r... | [
132,
4
] | [
391,
26
] | python | en | ['en', 'ja', 'en'] | True |
read_random_bits | (nbits) | Reads 'nbits' random bits.
If nbits isn't a whole number of bytes, an extra byte will be appended with
only the lower bits set.
| Reads 'nbits' random bits. | def read_random_bits(nbits):
"""Reads 'nbits' random bits.
If nbits isn't a whole number of bytes, an extra byte will be appended with
only the lower bits set.
"""
nbytes, rbits = divmod(nbits, 8)
# Get the random bytes
randomdata = os.urandom(nbytes)
# Add the remaining random bits
... | [
"def",
"read_random_bits",
"(",
"nbits",
")",
":",
"nbytes",
",",
"rbits",
"=",
"divmod",
"(",
"nbits",
",",
"8",
")",
"# Get the random bytes",
"randomdata",
"=",
"os",
".",
"urandom",
"(",
"nbytes",
")",
"# Add the remaining random bits",
"if",
"rbits",
">",... | [
26,
0
] | [
44,
21
] | python | en | ['en', 'bg', 'en'] | True |
read_random_int | (nbits) | Reads a random integer of approximately nbits bits.
| Reads a random integer of approximately nbits bits.
| def read_random_int(nbits):
"""Reads a random integer of approximately nbits bits.
"""
randomdata = read_random_bits(nbits)
value = transform.bytes2int(randomdata)
# Ensure that the number is large enough to just fill out the required
# number of bits.
value |= 1 << (nbits - 1)
return... | [
"def",
"read_random_int",
"(",
"nbits",
")",
":",
"randomdata",
"=",
"read_random_bits",
"(",
"nbits",
")",
"value",
"=",
"transform",
".",
"bytes2int",
"(",
"randomdata",
")",
"# Ensure that the number is large enough to just fill out the required",
"# number of bits.",
... | [
47,
0
] | [
58,
16
] | python | en | ['en', 'ca', 'en'] | True |
read_random_odd_int | (nbits) | Reads a random odd integer of approximately nbits bits.
>>> read_random_odd_int(512) & 1
1
| Reads a random odd integer of approximately nbits bits. | def read_random_odd_int(nbits):
"""Reads a random odd integer of approximately nbits bits.
>>> read_random_odd_int(512) & 1
1
"""
value = read_random_int(nbits)
# Make sure it's odd
return value | 1 | [
"def",
"read_random_odd_int",
"(",
"nbits",
")",
":",
"value",
"=",
"read_random_int",
"(",
"nbits",
")",
"# Make sure it's odd",
"return",
"value",
"|",
"1"
] | [
61,
0
] | [
71,
20
] | python | en | ['en', 'cs', 'en'] | True |
randint | (maxvalue) | Returns a random integer x with 1 <= x <= maxvalue
May take a very long time in specific situations. If maxvalue needs N bits
to store, the closer maxvalue is to (2 ** N) - 1, the faster this function
is.
| Returns a random integer x with 1 <= x <= maxvalue | def randint(maxvalue):
"""Returns a random integer x with 1 <= x <= maxvalue
May take a very long time in specific situations. If maxvalue needs N bits
to store, the closer maxvalue is to (2 ** N) - 1, the faster this function
is.
"""
bit_size = common.bit_size(maxvalue)
tries = 0
whi... | [
"def",
"randint",
"(",
"maxvalue",
")",
":",
"bit_size",
"=",
"common",
".",
"bit_size",
"(",
"maxvalue",
")",
"tries",
"=",
"0",
"while",
"True",
":",
"value",
"=",
"read_random_int",
"(",
"bit_size",
")",
"if",
"value",
"<=",
"maxvalue",
":",
"break",
... | [
74,
0
] | [
97,
16
] | python | en | ['en', 'ca', 'en'] | True |
BaseNSVD1.__init__ | (self, train_file, test_file, output_file=None, factors=10, init_mean=0, init_stdev=0.1,
sep='\t', output_sep='\t', random_seed=None) |
This class is base for all NSVD1 algorithms.
:param train_file: File which contains the train set. This file needs to have at least 3 columns
(user item feedback_value).
:type train_file: str
:param test_file: File which contains the test set. This file needs to have at least ... |
This class is base for all NSVD1 algorithms. | def __init__(self, train_file, test_file, output_file=None, factors=10, init_mean=0, init_stdev=0.1,
sep='\t', output_sep='\t', random_seed=None):
"""
This class is base for all NSVD1 algorithms.
:param train_file: File which contains the train set. This file needs to have at l... | [
"def",
"__init__",
"(",
"self",
",",
"train_file",
",",
"test_file",
",",
"output_file",
"=",
"None",
",",
"factors",
"=",
"10",
",",
"init_mean",
"=",
"0",
",",
"init_stdev",
"=",
"0.1",
",",
"sep",
"=",
"'\\t'",
",",
"output_sep",
"=",
"'\\t'",
",",
... | [
24,
4
] | [
86,
29
] | python | en | ['en', 'error', 'th'] | False |
BaseNSVD1.init_model | (self) |
Method to treat and initialize the model
|
Method to treat and initialize the model | def init_model(self):
"""
Method to treat and initialize the model
"""
# Map items and users with their respective ids and upgrade unobserved items with test set samples
for i, item in enumerate(self.items):
self.item_to_item_id.update({item: i})
self.it... | [
"def",
"init_model",
"(",
"self",
")",
":",
"# Map items and users with their respective ids and upgrade unobserved items with test set samples",
"for",
"i",
",",
"item",
"in",
"enumerate",
"(",
"self",
".",
"items",
")",
":",
"self",
".",
"item_to_item_id",
".",
"updat... | [
88,
4
] | [
100,
50
] | python | en | ['en', 'error', 'th'] | False |
BaseNSVD1.predict | (self) |
This method computes a final rating for unknown pairs (user, item)
|
This method computes a final rating for unknown pairs (user, item) | def predict(self):
"""
This method computes a final rating for unknown pairs (user, item)
"""
if self.test_file is not None:
for user in self.test_set['users']:
for item in self.test_set['feedback'][user]:
rui = self._predict(self.user_to... | [
"def",
"predict",
"(",
"self",
")",
":",
"if",
"self",
".",
"test_file",
"is",
"not",
"None",
":",
"for",
"user",
"in",
"self",
".",
"test_set",
"[",
"'users'",
"]",
":",
"for",
"item",
"in",
"self",
".",
"test_set",
"[",
"'feedback'",
"]",
"[",
"u... | [
120,
4
] | [
132,
32
] | 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.