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
sequence | start_point
sequence | end_point
sequence | language
stringclasses 1
value | docstring_language
stringlengths 2
7
| docstring_language_predictions
stringlengths 18
23
| is_langid_reliable
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|
create_main_parser | () | Creates and returns the main parser for pip's CLI | Creates and returns the main parser for pip's CLI | def create_main_parser() -> ConfigOptionParser:
"""Creates and returns the main parser for pip's CLI"""
parser = ConfigOptionParser(
usage="\n%prog <command> [options]",
add_help_option=False,
formatter=UpdatingDefaultsHelpFormatter(),
name="global",
prog=get_prog(),
)
parser.disable_interspersed_args()
parser.version = get_pip_version()
# add the general options
gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
parser.add_option_group(gen_opts)
# so the help formatter knows
parser.main = True # type: ignore
# create command listing for description
description = [""] + [
f"{name:27} {command_info.summary}"
for name, command_info in commands_dict.items()
]
parser.description = "\n".join(description)
return parser | [
"def",
"create_main_parser",
"(",
")",
"->",
"ConfigOptionParser",
":",
"parser",
"=",
"ConfigOptionParser",
"(",
"usage",
"=",
"\"\\n%prog <command> [options]\"",
",",
"add_help_option",
"=",
"False",
",",
"formatter",
"=",
"UpdatingDefaultsHelpFormatter",
"(",
")",
",",
"name",
"=",
"\"global\"",
",",
"prog",
"=",
"get_prog",
"(",
")",
",",
")",
"parser",
".",
"disable_interspersed_args",
"(",
")",
"parser",
".",
"version",
"=",
"get_pip_version",
"(",
")",
"# add the general options",
"gen_opts",
"=",
"cmdoptions",
".",
"make_option_group",
"(",
"cmdoptions",
".",
"general_group",
",",
"parser",
")",
"parser",
".",
"add_option_group",
"(",
"gen_opts",
")",
"# so the help formatter knows",
"parser",
".",
"main",
"=",
"True",
"# type: ignore",
"# create command listing for description",
"description",
"=",
"[",
"\"\"",
"]",
"+",
"[",
"f\"{name:27} {command_info.summary}\"",
"for",
"name",
",",
"command_info",
"in",
"commands_dict",
".",
"items",
"(",
")",
"]",
"parser",
".",
"description",
"=",
"\"\\n\"",
".",
"join",
"(",
"description",
")",
"return",
"parser"
] | [
16,
0
] | [
44,
17
] | python | en | ['en', 'en', 'en'] | True |
_get_failure_view | () | Return the view to be used for CSRF rejections. | Return the view to be used for CSRF rejections. | def _get_failure_view():
"""Return the view to be used for CSRF rejections."""
return get_callable(settings.CSRF_FAILURE_VIEW) | [
"def",
"_get_failure_view",
"(",
")",
":",
"return",
"get_callable",
"(",
"settings",
".",
"CSRF_FAILURE_VIEW",
")"
] | [
35,
0
] | [
37,
51
] | python | en | ['en', 'en', 'en'] | True |
_mask_cipher_secret | (secret) |
Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
token by adding a mask and applying it to the secret.
|
Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
token by adding a mask and applying it to the secret.
| def _mask_cipher_secret(secret):
"""
Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
token by adding a mask and applying it to the secret.
"""
mask = _get_new_csrf_string()
chars = CSRF_ALLOWED_CHARS
pairs = zip((chars.index(x) for x in secret), (chars.index(x) for x in mask))
cipher = ''.join(chars[(x + y) % len(chars)] for x, y in pairs)
return mask + cipher | [
"def",
"_mask_cipher_secret",
"(",
"secret",
")",
":",
"mask",
"=",
"_get_new_csrf_string",
"(",
")",
"chars",
"=",
"CSRF_ALLOWED_CHARS",
"pairs",
"=",
"zip",
"(",
"(",
"chars",
".",
"index",
"(",
"x",
")",
"for",
"x",
"in",
"secret",
")",
",",
"(",
"chars",
".",
"index",
"(",
"x",
")",
"for",
"x",
"in",
"mask",
")",
")",
"cipher",
"=",
"''",
".",
"join",
"(",
"chars",
"[",
"(",
"x",
"+",
"y",
")",
"%",
"len",
"(",
"chars",
")",
"]",
"for",
"x",
",",
"y",
"in",
"pairs",
")",
"return",
"mask",
"+",
"cipher"
] | [
44,
0
] | [
53,
24
] | python | en | ['en', 'error', 'th'] | False |
_unmask_cipher_token | (token) |
Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
CSRF_TOKEN_LENGTH, and that its first half is a mask), use it to decrypt
the second half to produce the original secret.
|
Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
CSRF_TOKEN_LENGTH, and that its first half is a mask), use it to decrypt
the second half to produce the original secret.
| def _unmask_cipher_token(token):
"""
Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
CSRF_TOKEN_LENGTH, and that its first half is a mask), use it to decrypt
the second half to produce the original secret.
"""
mask = token[:CSRF_SECRET_LENGTH]
token = token[CSRF_SECRET_LENGTH:]
chars = CSRF_ALLOWED_CHARS
pairs = zip((chars.index(x) for x in token), (chars.index(x) for x in mask))
return ''.join(chars[x - y] for x, y in pairs) | [
"def",
"_unmask_cipher_token",
"(",
"token",
")",
":",
"mask",
"=",
"token",
"[",
":",
"CSRF_SECRET_LENGTH",
"]",
"token",
"=",
"token",
"[",
"CSRF_SECRET_LENGTH",
":",
"]",
"chars",
"=",
"CSRF_ALLOWED_CHARS",
"pairs",
"=",
"zip",
"(",
"(",
"chars",
".",
"index",
"(",
"x",
")",
"for",
"x",
"in",
"token",
")",
",",
"(",
"chars",
".",
"index",
"(",
"x",
")",
"for",
"x",
"in",
"mask",
")",
")",
"return",
"''",
".",
"join",
"(",
"chars",
"[",
"x",
"-",
"y",
"]",
"for",
"x",
",",
"y",
"in",
"pairs",
")"
] | [
56,
0
] | [
66,
50
] | python | en | ['en', 'error', 'th'] | False |
get_token | (request) |
Return the CSRF token required for a POST form. The token is an
alphanumeric value. A new token is created if one is not already set.
A side effect of calling this function is to make the csrf_protect
decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
header to the outgoing response. For this reason, you may need to use this
function lazily, as is done by the csrf context processor.
|
Return the CSRF token required for a POST form. The token is an
alphanumeric value. A new token is created if one is not already set. | def get_token(request):
"""
Return the CSRF token required for a POST form. The token is an
alphanumeric value. A new token is created if one is not already set.
A side effect of calling this function is to make the csrf_protect
decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
header to the outgoing response. For this reason, you may need to use this
function lazily, as is done by the csrf context processor.
"""
if "CSRF_COOKIE" not in request.META:
csrf_secret = _get_new_csrf_string()
request.META["CSRF_COOKIE"] = _mask_cipher_secret(csrf_secret)
else:
csrf_secret = _unmask_cipher_token(request.META["CSRF_COOKIE"])
request.META["CSRF_COOKIE_USED"] = True
return _mask_cipher_secret(csrf_secret) | [
"def",
"get_token",
"(",
"request",
")",
":",
"if",
"\"CSRF_COOKIE\"",
"not",
"in",
"request",
".",
"META",
":",
"csrf_secret",
"=",
"_get_new_csrf_string",
"(",
")",
"request",
".",
"META",
"[",
"\"CSRF_COOKIE\"",
"]",
"=",
"_mask_cipher_secret",
"(",
"csrf_secret",
")",
"else",
":",
"csrf_secret",
"=",
"_unmask_cipher_token",
"(",
"request",
".",
"META",
"[",
"\"CSRF_COOKIE\"",
"]",
")",
"request",
".",
"META",
"[",
"\"CSRF_COOKIE_USED\"",
"]",
"=",
"True",
"return",
"_mask_cipher_secret",
"(",
"csrf_secret",
")"
] | [
73,
0
] | [
89,
43
] | python | en | ['en', 'error', 'th'] | False |
rotate_token | (request) |
Change the CSRF token in use for a request - should be done on login
for security purposes.
|
Change the CSRF token in use for a request - should be done on login
for security purposes.
| def rotate_token(request):
"""
Change the CSRF token in use for a request - should be done on login
for security purposes.
"""
request.META.update({
"CSRF_COOKIE_USED": True,
"CSRF_COOKIE": _get_new_csrf_token(),
})
request.csrf_cookie_needs_reset = True | [
"def",
"rotate_token",
"(",
"request",
")",
":",
"request",
".",
"META",
".",
"update",
"(",
"{",
"\"CSRF_COOKIE_USED\"",
":",
"True",
",",
"\"CSRF_COOKIE\"",
":",
"_get_new_csrf_token",
"(",
")",
",",
"}",
")",
"request",
".",
"csrf_cookie_needs_reset",
"=",
"True"
] | [
92,
0
] | [
101,
42
] | python | en | ['en', 'error', 'th'] | False |
choose_boundary | () |
Our embarrassingly-simple replacement for mimetools.choose_boundary.
|
Our embarrassingly-simple replacement for mimetools.choose_boundary.
| def choose_boundary():
"""
Our embarrassingly-simple replacement for mimetools.choose_boundary.
"""
boundary = binascii.hexlify(os.urandom(16))
if not six.PY2:
boundary = boundary.decode("ascii")
return boundary | [
"def",
"choose_boundary",
"(",
")",
":",
"boundary",
"=",
"binascii",
".",
"hexlify",
"(",
"os",
".",
"urandom",
"(",
"16",
")",
")",
"if",
"not",
"six",
".",
"PY2",
":",
"boundary",
"=",
"boundary",
".",
"decode",
"(",
"\"ascii\"",
")",
"return",
"boundary"
] | [
14,
0
] | [
21,
19
] | python | en | ['en', 'error', 'th'] | False |
iter_field_objects | (fields) |
Iterate over fields.
Supports list of (k, v) tuples and dicts, and lists of
:class:`~urllib3.fields.RequestField`.
|
Iterate over fields. | def iter_field_objects(fields):
"""
Iterate over fields.
Supports list of (k, v) tuples and dicts, and lists of
:class:`~urllib3.fields.RequestField`.
"""
if isinstance(fields, dict):
i = six.iteritems(fields)
else:
i = iter(fields)
for field in i:
if isinstance(field, RequestField):
yield field
else:
yield RequestField.from_tuples(*field) | [
"def",
"iter_field_objects",
"(",
"fields",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"dict",
")",
":",
"i",
"=",
"six",
".",
"iteritems",
"(",
"fields",
")",
"else",
":",
"i",
"=",
"iter",
"(",
"fields",
")",
"for",
"field",
"in",
"i",
":",
"if",
"isinstance",
"(",
"field",
",",
"RequestField",
")",
":",
"yield",
"field",
"else",
":",
"yield",
"RequestField",
".",
"from_tuples",
"(",
"*",
"field",
")"
] | [
24,
0
] | [
41,
50
] | python | en | ['en', 'error', 'th'] | False |
iter_fields | (fields) |
.. deprecated:: 1.6
Iterate over fields.
The addition of :class:`~urllib3.fields.RequestField` makes this function
obsolete. Instead, use :func:`iter_field_objects`, which returns
:class:`~urllib3.fields.RequestField` objects.
Supports list of (k, v) tuples and dicts.
|
.. deprecated:: 1.6 | def iter_fields(fields):
"""
.. deprecated:: 1.6
Iterate over fields.
The addition of :class:`~urllib3.fields.RequestField` makes this function
obsolete. Instead, use :func:`iter_field_objects`, which returns
:class:`~urllib3.fields.RequestField` objects.
Supports list of (k, v) tuples and dicts.
"""
if isinstance(fields, dict):
return ((k, v) for k, v in six.iteritems(fields))
return ((k, v) for k, v in fields) | [
"def",
"iter_fields",
"(",
"fields",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"dict",
")",
":",
"return",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"fields",
")",
")",
"return",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"fields",
")"
] | [
44,
0
] | [
59,
38
] | python | en | ['en', 'error', 'th'] | False |
encode_multipart_formdata | (fields, boundary=None) |
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
:param boundary:
If not specified, then a random boundary will be generated using
:func:`urllib3.filepost.choose_boundary`.
|
Encode a dictionary of ``fields`` using the multipart/form-data MIME format. | def encode_multipart_formdata(fields, boundary=None):
"""
Encode a dictionary of ``fields`` using the multipart/form-data MIME format.
:param fields:
Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).
:param boundary:
If not specified, then a random boundary will be generated using
:func:`urllib3.filepost.choose_boundary`.
"""
body = BytesIO()
if boundary is None:
boundary = choose_boundary()
for field in iter_field_objects(fields):
body.write(b("--%s\r\n" % (boundary)))
writer(body).write(field.render_headers())
data = field.data
if isinstance(data, int):
data = str(data) # Backwards compatibility
if isinstance(data, six.text_type):
writer(body).write(data)
else:
body.write(data)
body.write(b"\r\n")
body.write(b("--%s--\r\n" % (boundary)))
content_type = str("multipart/form-data; boundary=%s" % boundary)
return body.getvalue(), content_type | [
"def",
"encode_multipart_formdata",
"(",
"fields",
",",
"boundary",
"=",
"None",
")",
":",
"body",
"=",
"BytesIO",
"(",
")",
"if",
"boundary",
"is",
"None",
":",
"boundary",
"=",
"choose_boundary",
"(",
")",
"for",
"field",
"in",
"iter_field_objects",
"(",
"fields",
")",
":",
"body",
".",
"write",
"(",
"b",
"(",
"\"--%s\\r\\n\"",
"%",
"(",
"boundary",
")",
")",
")",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"field",
".",
"render_headers",
"(",
")",
")",
"data",
"=",
"field",
".",
"data",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"data",
"=",
"str",
"(",
"data",
")",
"# Backwards compatibility",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"text_type",
")",
":",
"writer",
"(",
"body",
")",
".",
"write",
"(",
"data",
")",
"else",
":",
"body",
".",
"write",
"(",
"data",
")",
"body",
".",
"write",
"(",
"b\"\\r\\n\"",
")",
"body",
".",
"write",
"(",
"b",
"(",
"\"--%s--\\r\\n\"",
"%",
"(",
"boundary",
")",
")",
")",
"content_type",
"=",
"str",
"(",
"\"multipart/form-data; boundary=%s\"",
"%",
"boundary",
")",
"return",
"body",
".",
"getvalue",
"(",
")",
",",
"content_type"
] | [
62,
0
] | [
97,
40
] | python | en | ['en', 'error', 'th'] | False |
default_storage | (request) |
Callable with the same interface as the storage classes.
This isn't just default_storage = import_string(settings.MESSAGE_STORAGE)
to avoid accessing the settings at the module level.
|
Callable with the same interface as the storage classes. | def default_storage(request):
"""
Callable with the same interface as the storage classes.
This isn't just default_storage = import_string(settings.MESSAGE_STORAGE)
to avoid accessing the settings at the module level.
"""
return import_string(settings.MESSAGE_STORAGE)(request) | [
"def",
"default_storage",
"(",
"request",
")",
":",
"return",
"import_string",
"(",
"settings",
".",
"MESSAGE_STORAGE",
")",
"(",
"request",
")"
] | [
4,
0
] | [
11,
59
] | python | en | ['en', 'error', 'th'] | False |
variant_count | (table: pandas.DataFrame, reference: pandas.Series) |
Counts the number of samples a specific variant occurs in.
Parameters
----------
table: pandas.DataFrame
The table should be indexed by sequence Id and position, and have samples as columns and varaints as rows.
reference:pandas.Series
The reference series used to determine if a given position counts as a variant.
Returns
-------
pandas.Series
Maps indexed positions to a count of the number of samples a variant occurs in.
|
Counts the number of samples a specific variant occurs in.
Parameters
----------
table: pandas.DataFrame
The table should be indexed by sequence Id and position, and have samples as columns and varaints as rows.
reference:pandas.Series
The reference series used to determine if a given position counts as a variant.
Returns
-------
pandas.Series
Maps indexed positions to a count of the number of samples a variant occurs in.
| def variant_count(table: pandas.DataFrame, reference: pandas.Series) -> pandas.Series:
"""
Counts the number of samples a specific variant occurs in.
Parameters
----------
table: pandas.DataFrame
The table should be indexed by sequence Id and position, and have samples as columns and varaints as rows.
reference:pandas.Series
The reference series used to determine if a given position counts as a variant.
Returns
-------
pandas.Series
Maps indexed positions to a count of the number of samples a variant occurs in.
"""
present_df: pandas.DataFrame = table.apply(lambda s: s != reference)
return present_df.sum(axis = 1) | [
"def",
"variant_count",
"(",
"table",
":",
"pandas",
".",
"DataFrame",
",",
"reference",
":",
"pandas",
".",
"Series",
")",
"->",
"pandas",
".",
"Series",
":",
"present_df",
":",
"pandas",
".",
"DataFrame",
"=",
"table",
".",
"apply",
"(",
"lambda",
"s",
":",
"s",
"!=",
"reference",
")",
"return",
"present_df",
".",
"sum",
"(",
"axis",
"=",
"1",
")"
] | [
3,
0
] | [
19,
32
] | python | en | ['en', 'error', 'th'] | False |
filter_variants_in_all_samples | (df: pandas.DataFrame, reference_label: str) |
Filters out variant which appear in all samples.
Parameters
----------
df: pandas.DataFrame
A Dataframe where columns correspond to samples and rows correspond to unique variants.
The table should be indexed by sequence Id and position.
reference_label: str
Used to annotate mutations that appear in the reference sample.
|
Filters out variant which appear in all samples.
Parameters
----------
df: pandas.DataFrame
A Dataframe where columns correspond to samples and rows correspond to unique variants.
The table should be indexed by sequence Id and position.
reference_label: str
Used to annotate mutations that appear in the reference sample.
| def filter_variants_in_all_samples(df: pandas.DataFrame, reference_label: str) -> pandas.DataFrame:
"""
Filters out variant which appear in all samples.
Parameters
----------
df: pandas.DataFrame
A Dataframe where columns correspond to samples and rows correspond to unique variants.
The table should be indexed by sequence Id and position.
reference_label: str
Used to annotate mutations that appear in the reference sample.
"""
reference = df.pop(reference_label)
variants = variant_count(df, reference)
present_in_all = variants == len(df.columns)
return df[~present_in_all] | [
"def",
"filter_variants_in_all_samples",
"(",
"df",
":",
"pandas",
".",
"DataFrame",
",",
"reference_label",
":",
"str",
")",
"->",
"pandas",
".",
"DataFrame",
":",
"reference",
"=",
"df",
".",
"pop",
"(",
"reference_label",
")",
"variants",
"=",
"variant_count",
"(",
"df",
",",
"reference",
")",
"present_in_all",
"=",
"variants",
"==",
"len",
"(",
"df",
".",
"columns",
")",
"return",
"df",
"[",
"~",
"present_in_all",
"]"
] | [
22,
0
] | [
37,
27
] | python | en | ['en', 'error', 'th'] | False |
PixelClasssificationModel._cls | (self, feat_hist, pix_hist, feat_preds, pix_preds) |
Wrapper around the classifier, collates all the input frames/features
and predicted future frames/features.
The images, features are already summed over the objects
Args:
feat_hist: (B, T, C, H', W')
pix_hist: (B, T, 7, H, W)
feat_preds [list of (B, C, H', W')] -- len = num predictions
pix_preds [list of (B, 7, H, W)] -- len = num predictions
The elements could be None, since not all models predict pixels
Returns:
(B,) predicted scores for the clips
|
Wrapper around the classifier, collates all the input frames/features
and predicted future frames/features.
The images, features are already summed over the objects
Args:
feat_hist: (B, T, C, H', W')
pix_hist: (B, T, 7, H, W)
feat_preds [list of (B, C, H', W')] -- len = num predictions
pix_preds [list of (B, 7, H, W)] -- len = num predictions
The elements could be None, since not all models predict pixels
Returns:
(B,) predicted scores for the clips
| def _cls(self, feat_hist, pix_hist, feat_preds, pix_preds):
"""
Wrapper around the classifier, collates all the input frames/features
and predicted future frames/features.
The images, features are already summed over the objects
Args:
feat_hist: (B, T, C, H', W')
pix_hist: (B, T, 7, H, W)
feat_preds [list of (B, C, H', W')] -- len = num predictions
pix_preds [list of (B, 7, H, W)] -- len = num predictions
The elements could be None, since not all models predict pixels
Returns:
(B,) predicted scores for the clips
"""
feats_combined = feat_hist
if feat_preds is not None and len(feat_preds) > 0:
feats_combined = torch.cat([feat_hist] +
[el.unsqueeze(1) for el in feat_preds],
dim=1)
pix_combined = pix_hist
if (pix_preds is not None and len(pix_preds) > 0
and pix_preds[0] is not None):
pix_combined = torch.cat([pix_combined] +
[el.unsqueeze(1) for el in pix_preds],
dim=1)
# Sum over objs -- we want the classifier model to see everything
# at the same time
# They are summed now, but need the dimension still
pix_combined = pix_combined.unsqueeze(2)
feats_combined = feats_combined.unsqueeze(2)
# If need to keep only a subset of the frames
if self.nframes_to_cls > 0:
pix_combined = pix_combined[:, :self.nframes_to_cls, ...]
feats_combined = feats_combined[:, :self.nframes_to_cls, ...]
feats_combined = self.spat_att(feats_combined)
# Keep the last prediction, as that should ideally be the best
# prediction of whether it was solved or not
# torch.max was hard to optimize through
return self.cls(feats_combined, pix_combined)[:, -1] | [
"def",
"_cls",
"(",
"self",
",",
"feat_hist",
",",
"pix_hist",
",",
"feat_preds",
",",
"pix_preds",
")",
":",
"feats_combined",
"=",
"feat_hist",
"if",
"feat_preds",
"is",
"not",
"None",
"and",
"len",
"(",
"feat_preds",
")",
">",
"0",
":",
"feats_combined",
"=",
"torch",
".",
"cat",
"(",
"[",
"feat_hist",
"]",
"+",
"[",
"el",
".",
"unsqueeze",
"(",
"1",
")",
"for",
"el",
"in",
"feat_preds",
"]",
",",
"dim",
"=",
"1",
")",
"pix_combined",
"=",
"pix_hist",
"if",
"(",
"pix_preds",
"is",
"not",
"None",
"and",
"len",
"(",
"pix_preds",
")",
">",
"0",
"and",
"pix_preds",
"[",
"0",
"]",
"is",
"not",
"None",
")",
":",
"pix_combined",
"=",
"torch",
".",
"cat",
"(",
"[",
"pix_combined",
"]",
"+",
"[",
"el",
".",
"unsqueeze",
"(",
"1",
")",
"for",
"el",
"in",
"pix_preds",
"]",
",",
"dim",
"=",
"1",
")",
"# Sum over objs -- we want the classifier model to see everything",
"# at the same time",
"# They are summed now, but need the dimension still",
"pix_combined",
"=",
"pix_combined",
".",
"unsqueeze",
"(",
"2",
")",
"feats_combined",
"=",
"feats_combined",
".",
"unsqueeze",
"(",
"2",
")",
"# If need to keep only a subset of the frames",
"if",
"self",
".",
"nframes_to_cls",
">",
"0",
":",
"pix_combined",
"=",
"pix_combined",
"[",
":",
",",
":",
"self",
".",
"nframes_to_cls",
",",
"...",
"]",
"feats_combined",
"=",
"feats_combined",
"[",
":",
",",
":",
"self",
".",
"nframes_to_cls",
",",
"...",
"]",
"feats_combined",
"=",
"self",
".",
"spat_att",
"(",
"feats_combined",
")",
"# Keep the last prediction, as that should ideally be the best",
"# prediction of whether it was solved or not",
"# torch.max was hard to optimize through",
"return",
"self",
".",
"cls",
"(",
"feats_combined",
",",
"pix_combined",
")",
"[",
":",
",",
"-",
"1",
"]"
] | [
904,
4
] | [
942,
60
] | python | en | ['en', 'error', 'th'] | False |
FwdObject._forward_dyn | (self,
frames,
n_fwd_times,
need_intermediate,
train_noise_frac=0) |
Returns tuple of the full rollout, including GT frames, predicitons,
and any losses incurred making the predicitons.
If need_intermediate, predicitons is all preidictions made during
n_fwd_times, otherwise only the last prediction and its
corresponding losses are returned.
|
Returns tuple of the full rollout, including GT frames, predicitons,
and any losses incurred making the predicitons.
If need_intermediate, predicitons is all preidictions made during
n_fwd_times, otherwise only the last prediction and its
corresponding losses are returned.
| def _forward_dyn(self,
frames,
n_fwd_times,
need_intermediate,
train_noise_frac=0):
"""
Returns tuple of the full rollout, including GT frames, predicitons,
and any losses incurred making the predicitons.
If need_intermediate, predicitons is all preidictions made during
n_fwd_times, otherwise only the last prediction and its
corresponding losses are returned.
"""
if n_fwd_times == 0:
return frames, None, {}
rollout = []
previous_frames = frames.clone()
if train_noise_frac > 0:
# frames is B x T x N x F
dataset_std = self.train_noise_std # naive approximation
noise_amt = torch.normal(
0, dataset_std,
(previous_frames.shape[0], previous_frames.shape[1],
previous_frames.shape[2], 3))
bool_noise = torch.empty(noise_amt.shape).uniform_(
0, 1) > train_noise_frac
noise_amt *= bool_noise.type(torch.FloatTensor)
# no noise on padding
row_sum = torch.sum(previous_frames, dim=-1)
pad = row_sum == 0
pad_mask = pad
noise_amt[pad_mask] = 0.0
noise_amt = noise_amt.to(previous_frames.device)
previous_frames[:, :, :, :3] += noise_amt
for _ in range(n_fwd_times):
pred_frame = self.forward_model(previous_frames)
tmp = previous_frames[:, 1:].clone()
previous_frames[:, -1] = pred_frame
previous_frames[:, :-1] = tmp.clone()
rollout.append(pred_frame.unsqueeze(1))
full_rollout = torch.cat([frames] + rollout, dim=1)
if need_intermediate:
# Return all predicitons
return full_rollout, torch.cat(rollout, dim=1), {}
# Only return the last frame predicted
return full_rollout, rollout[-1], {} | [
"def",
"_forward_dyn",
"(",
"self",
",",
"frames",
",",
"n_fwd_times",
",",
"need_intermediate",
",",
"train_noise_frac",
"=",
"0",
")",
":",
"if",
"n_fwd_times",
"==",
"0",
":",
"return",
"frames",
",",
"None",
",",
"{",
"}",
"rollout",
"=",
"[",
"]",
"previous_frames",
"=",
"frames",
".",
"clone",
"(",
")",
"if",
"train_noise_frac",
">",
"0",
":",
"# frames is B x T x N x F",
"dataset_std",
"=",
"self",
".",
"train_noise_std",
"# naive approximation",
"noise_amt",
"=",
"torch",
".",
"normal",
"(",
"0",
",",
"dataset_std",
",",
"(",
"previous_frames",
".",
"shape",
"[",
"0",
"]",
",",
"previous_frames",
".",
"shape",
"[",
"1",
"]",
",",
"previous_frames",
".",
"shape",
"[",
"2",
"]",
",",
"3",
")",
")",
"bool_noise",
"=",
"torch",
".",
"empty",
"(",
"noise_amt",
".",
"shape",
")",
".",
"uniform_",
"(",
"0",
",",
"1",
")",
">",
"train_noise_frac",
"noise_amt",
"*=",
"bool_noise",
".",
"type",
"(",
"torch",
".",
"FloatTensor",
")",
"# no noise on padding",
"row_sum",
"=",
"torch",
".",
"sum",
"(",
"previous_frames",
",",
"dim",
"=",
"-",
"1",
")",
"pad",
"=",
"row_sum",
"==",
"0",
"pad_mask",
"=",
"pad",
"noise_amt",
"[",
"pad_mask",
"]",
"=",
"0.0",
"noise_amt",
"=",
"noise_amt",
".",
"to",
"(",
"previous_frames",
".",
"device",
")",
"previous_frames",
"[",
":",
",",
":",
",",
":",
",",
":",
"3",
"]",
"+=",
"noise_amt",
"for",
"_",
"in",
"range",
"(",
"n_fwd_times",
")",
":",
"pred_frame",
"=",
"self",
".",
"forward_model",
"(",
"previous_frames",
")",
"tmp",
"=",
"previous_frames",
"[",
":",
",",
"1",
":",
"]",
".",
"clone",
"(",
")",
"previous_frames",
"[",
":",
",",
"-",
"1",
"]",
"=",
"pred_frame",
"previous_frames",
"[",
":",
",",
":",
"-",
"1",
"]",
"=",
"tmp",
".",
"clone",
"(",
")",
"rollout",
".",
"append",
"(",
"pred_frame",
".",
"unsqueeze",
"(",
"1",
")",
")",
"full_rollout",
"=",
"torch",
".",
"cat",
"(",
"[",
"frames",
"]",
"+",
"rollout",
",",
"dim",
"=",
"1",
")",
"if",
"need_intermediate",
":",
"# Return all predicitons",
"return",
"full_rollout",
",",
"torch",
".",
"cat",
"(",
"rollout",
",",
"dim",
"=",
"1",
")",
",",
"{",
"}",
"# Only return the last frame predicted",
"return",
"full_rollout",
",",
"rollout",
"[",
"-",
"1",
"]",
",",
"{",
"}"
] | [
967,
4
] | [
1014,
44
] | python | en | ['en', 'error', 'th'] | False |
FwdObject._slice_for_dyn | (self, features_batched, n_hist_frames, nslices=-1) |
Args:
features_batched: BxTx.... can deal with any following
dimensions, typically it is (BxTxNobjxDxH'xW')
n_hist_frames (int): Number of frames to use as history
nslices (int): If -1, make as many slices of the training data
as possible. If 1, keep only the first one. (1 used when
training classifier on top, which should always see videos
from the start)
Returns:
B'x n_hist_frames x ... (B'x n_hist_frames x Nobj x D x H' x W')
|
Args:
features_batched: BxTx.... can deal with any following
dimensions, typically it is (BxTxNobjxDxH'xW')
n_hist_frames (int): Number of frames to use as history
nslices (int): If -1, make as many slices of the training data
as possible. If 1, keep only the first one. (1 used when
training classifier on top, which should always see videos
from the start) | def _slice_for_dyn(self, features_batched, n_hist_frames, nslices=-1):
"""
Args:
features_batched: BxTx.... can deal with any following
dimensions, typically it is (BxTxNobjxDxH'xW')
n_hist_frames (int): Number of frames to use as history
nslices (int): If -1, make as many slices of the training data
as possible. If 1, keep only the first one. (1 used when
training classifier on top, which should always see videos
from the start)
Returns:
B'x n_hist_frames x ... (B'x n_hist_frames x Nobj x D x H' x W')
"""
clip_hist = []
assert features_batched.shape[1] >= n_hist_frames
for i in range((features_batched.shape[1] - n_hist_frames + 1)):
if nslices > 0 and i >= nslices:
break
clip_hist.append(features_batched[:, i:i + n_hist_frames, ...])
clip_hist = torch.cat(clip_hist, dim=0)
return clip_hist | [
"def",
"_slice_for_dyn",
"(",
"self",
",",
"features_batched",
",",
"n_hist_frames",
",",
"nslices",
"=",
"-",
"1",
")",
":",
"clip_hist",
"=",
"[",
"]",
"assert",
"features_batched",
".",
"shape",
"[",
"1",
"]",
">=",
"n_hist_frames",
"for",
"i",
"in",
"range",
"(",
"(",
"features_batched",
".",
"shape",
"[",
"1",
"]",
"-",
"n_hist_frames",
"+",
"1",
")",
")",
":",
"if",
"nslices",
">",
"0",
"and",
"i",
">=",
"nslices",
":",
"break",
"clip_hist",
".",
"append",
"(",
"features_batched",
"[",
":",
",",
"i",
":",
"i",
"+",
"n_hist_frames",
",",
"...",
"]",
")",
"clip_hist",
"=",
"torch",
".",
"cat",
"(",
"clip_hist",
",",
"dim",
"=",
"0",
")",
"return",
"clip_hist"
] | [
1031,
4
] | [
1052,
24
] | python | en | ['en', 'error', 'th'] | False |
FwdObject._compute_losses | (self, pred_obj_roll, gt_obj_roll, n_hist_frames,
n_fwd_times) |
Compute all losses possible.
|
Compute all losses possible.
| def _compute_losses(self, pred_obj_roll, gt_obj_roll, n_hist_frames,
n_fwd_times):
"""
Compute all losses possible.
"""
dummy_loss = torch.Tensor([-1]).to(pred_obj_roll.device)
losses = {}
# NCE and pixel loss
# find the GT for each clip, note that all predictions may not have a GT
# since the last n_hist_frames for a video will make a prediction that
# goes out of the list of frames that were extracted for that video.
obj_preds = []
obj_gt = []
batch_size = gt_obj_roll.shape[0] #vid_feat.shape[0]
gt_max_time = gt_obj_roll.shape[1] #vid_feat.shape[1]
# Max slices that could have been made of the data, to use all of the
# training clip
max_slices_with_gt = gt_max_time - n_hist_frames - n_fwd_times + 1
num_slices = pred_obj_roll.shape[0] // batch_size # clip_pred
for i in range(min(max_slices_with_gt, num_slices)):
corr_pred = pred_obj_roll[i * batch_size:(i + 1) * batch_size,
...] # clip_pred
# Get the corresponding GT predictions for this pred
corr_gt = gt_obj_roll[:, i + n_hist_frames + n_fwd_times -
1] # vid_feat
assert corr_gt.shape == corr_pred.shape
obj_preds.append(corr_pred) #feat_preds
obj_gt.append(corr_gt) #feat_gt
if len(obj_gt) > 0: # feat_gt
# Keep a batch dimension to the loss, since it will be run over
# multiple GPUs
obj_preds = torch.cat(obj_preds) # feat_preds
obj_gt = torch.cat(obj_gt) # feat_preds
losses['l2'] = self.l2_loss(obj_preds, obj_gt).unsqueeze(0)
return losses | [
"def",
"_compute_losses",
"(",
"self",
",",
"pred_obj_roll",
",",
"gt_obj_roll",
",",
"n_hist_frames",
",",
"n_fwd_times",
")",
":",
"dummy_loss",
"=",
"torch",
".",
"Tensor",
"(",
"[",
"-",
"1",
"]",
")",
".",
"to",
"(",
"pred_obj_roll",
".",
"device",
")",
"losses",
"=",
"{",
"}",
"# NCE and pixel loss",
"# find the GT for each clip, note that all predictions may not have a GT",
"# since the last n_hist_frames for a video will make a prediction that",
"# goes out of the list of frames that were extracted for that video.",
"obj_preds",
"=",
"[",
"]",
"obj_gt",
"=",
"[",
"]",
"batch_size",
"=",
"gt_obj_roll",
".",
"shape",
"[",
"0",
"]",
"#vid_feat.shape[0]",
"gt_max_time",
"=",
"gt_obj_roll",
".",
"shape",
"[",
"1",
"]",
"#vid_feat.shape[1]",
"# Max slices that could have been made of the data, to use all of the",
"# training clip",
"max_slices_with_gt",
"=",
"gt_max_time",
"-",
"n_hist_frames",
"-",
"n_fwd_times",
"+",
"1",
"num_slices",
"=",
"pred_obj_roll",
".",
"shape",
"[",
"0",
"]",
"//",
"batch_size",
"# clip_pred",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"max_slices_with_gt",
",",
"num_slices",
")",
")",
":",
"corr_pred",
"=",
"pred_obj_roll",
"[",
"i",
"*",
"batch_size",
":",
"(",
"i",
"+",
"1",
")",
"*",
"batch_size",
",",
"...",
"]",
"# clip_pred",
"# Get the corresponding GT predictions for this pred",
"corr_gt",
"=",
"gt_obj_roll",
"[",
":",
",",
"i",
"+",
"n_hist_frames",
"+",
"n_fwd_times",
"-",
"1",
"]",
"# vid_feat",
"assert",
"corr_gt",
".",
"shape",
"==",
"corr_pred",
".",
"shape",
"obj_preds",
".",
"append",
"(",
"corr_pred",
")",
"#feat_preds",
"obj_gt",
".",
"append",
"(",
"corr_gt",
")",
"#feat_gt",
"if",
"len",
"(",
"obj_gt",
")",
">",
"0",
":",
"# feat_gt",
"# Keep a batch dimension to the loss, since it will be run over",
"# multiple GPUs",
"obj_preds",
"=",
"torch",
".",
"cat",
"(",
"obj_preds",
")",
"# feat_preds",
"obj_gt",
"=",
"torch",
".",
"cat",
"(",
"obj_gt",
")",
"# feat_preds",
"losses",
"[",
"'l2'",
"]",
"=",
"self",
".",
"l2_loss",
"(",
"obj_preds",
",",
"obj_gt",
")",
".",
"unsqueeze",
"(",
"0",
")",
"return",
"losses"
] | [
1078,
4
] | [
1114,
21
] | python | en | ['en', 'error', 'th'] | False |
Note.__init__ | (self, memo="", tags="") | Initialize a note with memo and optional
space-separated tags. Automatically set the note's
creation date and a unique id. | Initialize a note with memo and optional
space-separated tags. Automatically set the note's
creation date and a unique id. | def __init__(self, memo="", tags=""):
"""Initialize a note with memo and optional
space-separated tags. Automatically set the note's
creation date and a unique id."""
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
global last_id
last_id += 1
self.id = last_id | [
"def",
"__init__",
"(",
"self",
",",
"memo",
"=",
"\"\"",
",",
"tags",
"=",
"\"\"",
")",
":",
"self",
".",
"memo",
"=",
"memo",
"self",
".",
"tags",
"=",
"tags",
"self",
".",
"creation_date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"global",
"last_id",
"last_id",
"+=",
"1",
"self",
".",
"id",
"=",
"last_id"
] | [
6,
4
] | [
15,
25
] | python | en | ['en', 'en', 'en'] | True |
Note.match | (self, pattern) | Determine if this note matches the pattern text.
Return True if it matches, False otherwise.
Search is case sensitive and matches both text and
tags. | Determine if this note matches the pattern text.
Return True if it matches, False otherwise.
Search is case sensitive and matches both text and
tags. | def match(self, pattern):
"""Determine if this note matches the pattern text.
Return True if it matches, False otherwise.
Search is case sensitive and matches both text and
tags."""
return pattern in self.memo or pattern in self.tags | [
"def",
"match",
"(",
"self",
",",
"pattern",
")",
":",
"return",
"pattern",
"in",
"self",
".",
"memo",
"or",
"pattern",
"in",
"self",
".",
"tags"
] | [
17,
4
] | [
22,
59
] | python | en | ['en', 'en', 'en'] | True |
Notebook.__init__ | (self) | Initializes a notebook with an empty list. | Initializes a notebook with an empty list. | def __init__(self):
"Initializes a notebook with an empty list."
self.notes = [] | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"notes",
"=",
"[",
"]"
] | [
29,
4
] | [
31,
23
] | python | en | ['en', 'en', 'en'] | True |
Notebook._find_note | (self, note_id) | Locate the note with the given id. | Locate the note with the given id. | def _find_note(self, note_id):
"Locate the note with the given id."
for note in self.notes:
if note.id == note_id:
return note | [
"def",
"_find_note",
"(",
"self",
",",
"note_id",
")",
":",
"for",
"note",
"in",
"self",
".",
"notes",
":",
"if",
"note",
".",
"id",
"==",
"note_id",
":",
"return",
"note"
] | [
33,
4
] | [
37,
27
] | python | en | ['en', 'en', 'en'] | True |
Notebook.new_note | (self, memo, tags="") | Create a new note and add it to the list. | Create a new note and add it to the list. | def new_note(self, memo, tags=""):
"Create a new note and add it to the list."
self.notes.append(Note(memo, tags)) | [
"def",
"new_note",
"(",
"self",
",",
"memo",
",",
"tags",
"=",
"\"\"",
")",
":",
"self",
".",
"notes",
".",
"append",
"(",
"Note",
"(",
"memo",
",",
"tags",
")",
")"
] | [
39,
4
] | [
41,
43
] | python | en | ['en', 'en', 'en'] | True |
Notebook.modify_memo | (self, note_id, memo) | Find the note with the given id and change its memo to the given value | Find the note with the given id and change its memo to the given value | def modify_memo(self, note_id, memo):
"Find the note with the given id and change its memo to the given value"
self._find_note(note_id).memo = memo | [
"def",
"modify_memo",
"(",
"self",
",",
"note_id",
",",
"memo",
")",
":",
"self",
".",
"_find_note",
"(",
"note_id",
")",
".",
"memo",
"=",
"memo"
] | [
43,
4
] | [
45,
44
] | python | en | ['en', 'en', 'en'] | True |
Notebook.modify_tags | (self, note_id, tags) | Find the note with the given id and change its tags to the given value | Find the note with the given id and change its tags to the given value | def modify_tags(self, note_id, tags):
"Find the note with the given id and change its tags to the given value"
for note in self.notes:
if note.id == note_id:
note.tags = tags
break | [
"def",
"modify_tags",
"(",
"self",
",",
"note_id",
",",
"tags",
")",
":",
"for",
"note",
"in",
"self",
".",
"notes",
":",
"if",
"note",
".",
"id",
"==",
"note_id",
":",
"note",
".",
"tags",
"=",
"tags",
"break"
] | [
47,
4
] | [
52,
21
] | python | en | ['en', 'en', 'en'] | True |
Notebook.search | (self, pattern) | Find all notes that match the given pattern string. | Find all notes that match the given pattern string. | def search(self, pattern):
"Find all notes that match the given pattern string."
return [note for note in self.notes if note.match(pattern)] | [
"def",
"search",
"(",
"self",
",",
"pattern",
")",
":",
"return",
"[",
"note",
"for",
"note",
"in",
"self",
".",
"notes",
"if",
"note",
".",
"match",
"(",
"pattern",
")",
"]"
] | [
54,
4
] | [
56,
67
] | python | en | ['en', 'en', 'en'] | True |
expand | (uri, var_dict=None, **kwargs) | Expand the template with the given parameters.
:param str uri: The templated URI to expand
:param dict var_dict: Optional dictionary with variables and values
:param kwargs: Alternative way to pass arguments
:returns: str
Example::
expand('https://api.github.com{/end}', {'end': 'users'})
expand('https://api.github.com{/end}', end='gists')
.. note:: Passing values by both parts, may override values in
``var_dict``. For example::
expand('https://{var}', {'var': 'val1'}, var='val2')
``val2`` will be used instead of ``val1``.
| Expand the template with the given parameters. | def expand(uri, var_dict=None, **kwargs):
"""Expand the template with the given parameters.
:param str uri: The templated URI to expand
:param dict var_dict: Optional dictionary with variables and values
:param kwargs: Alternative way to pass arguments
:returns: str
Example::
expand('https://api.github.com{/end}', {'end': 'users'})
expand('https://api.github.com{/end}', end='gists')
.. note:: Passing values by both parts, may override values in
``var_dict``. For example::
expand('https://{var}', {'var': 'val1'}, var='val2')
``val2`` will be used instead of ``val1``.
"""
return URITemplate(uri).expand(var_dict, **kwargs) | [
"def",
"expand",
"(",
"uri",
",",
"var_dict",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"URITemplate",
"(",
"uri",
")",
".",
"expand",
"(",
"var_dict",
",",
"*",
"*",
"kwargs",
")"
] | [
11,
0
] | [
32,
54
] | python | en | ['en', 'en', 'en'] | True |
partial | (uri, var_dict=None, **kwargs) | Partially expand the template with the given parameters.
If all of the parameters for the template are not given, return a
partially expanded template.
:param dict var_dict: Optional dictionary with variables and values
:param kwargs: Alternative way to pass arguments
:returns: :class:`URITemplate`
Example::
t = URITemplate('https://api.github.com{/end}')
t.partial() # => URITemplate('https://api.github.com{/end}')
| Partially expand the template with the given parameters. | def partial(uri, var_dict=None, **kwargs):
"""Partially expand the template with the given parameters.
If all of the parameters for the template are not given, return a
partially expanded template.
:param dict var_dict: Optional dictionary with variables and values
:param kwargs: Alternative way to pass arguments
:returns: :class:`URITemplate`
Example::
t = URITemplate('https://api.github.com{/end}')
t.partial() # => URITemplate('https://api.github.com{/end}')
"""
return URITemplate(uri).partial(var_dict, **kwargs) | [
"def",
"partial",
"(",
"uri",
",",
"var_dict",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"URITemplate",
"(",
"uri",
")",
".",
"partial",
"(",
"var_dict",
",",
"*",
"*",
"kwargs",
")"
] | [
35,
0
] | [
51,
55
] | python | en | ['en', 'en', 'en'] | True |
variables | (uri) | Parse the variables of the template.
This returns all of the variable names in the URI Template.
:returns: Set of variable names
:rtype: set
Example::
variables('https://api.github.com{/end})
# => {'end'}
variables('https://api.github.com/repos{/username}{/repository}')
# => {'username', 'repository'}
| Parse the variables of the template. | def variables(uri):
"""Parse the variables of the template.
This returns all of the variable names in the URI Template.
:returns: Set of variable names
:rtype: set
Example::
variables('https://api.github.com{/end})
# => {'end'}
variables('https://api.github.com/repos{/username}{/repository}')
# => {'username', 'repository'}
"""
return set(URITemplate(uri).variable_names) | [
"def",
"variables",
"(",
"uri",
")",
":",
"return",
"set",
"(",
"URITemplate",
"(",
"uri",
")",
".",
"variable_names",
")"
] | [
54,
0
] | [
70,
47
] | python | en | ['en', 'en', 'en'] | True |
CredentialsField.from_db_value | (self, value, expression, connection, context) | Overrides ``models.Field`` method. This converts the value
returned from the database to an instance of this class.
| Overrides ``models.Field`` method. This converts the value
returned from the database to an instance of this class.
| def from_db_value(self, value, expression, connection, context):
"""Overrides ``models.Field`` method. This converts the value
returned from the database to an instance of this class.
"""
return self.to_python(value) | [
"def",
"from_db_value",
"(",
"self",
",",
"value",
",",
"expression",
",",
"connection",
",",
"context",
")",
":",
"return",
"self",
".",
"to_python",
"(",
"value",
")"
] | [
37,
4
] | [
41,
36
] | python | en | ['en', 'en', 'en'] | True |
CredentialsField.to_python | (self, value) | Overrides ``models.Field`` method. This is used to convert
bytes (from serialization etc) to an instance of this class | Overrides ``models.Field`` method. This is used to convert
bytes (from serialization etc) to an instance of this class | def to_python(self, value):
"""Overrides ``models.Field`` method. This is used to convert
bytes (from serialization etc) to an instance of this class"""
if value is None:
return None
elif isinstance(value, oauth2client.client.Credentials):
return value
else:
try:
return jsonpickle.decode(
base64.b64decode(encoding.smart_bytes(value)).decode())
except ValueError:
return pickle.loads(
base64.b64decode(encoding.smart_bytes(value))) | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"value",
",",
"oauth2client",
".",
"client",
".",
"Credentials",
")",
":",
"return",
"value",
"else",
":",
"try",
":",
"return",
"jsonpickle",
".",
"decode",
"(",
"base64",
".",
"b64decode",
"(",
"encoding",
".",
"smart_bytes",
"(",
"value",
")",
")",
".",
"decode",
"(",
")",
")",
"except",
"ValueError",
":",
"return",
"pickle",
".",
"loads",
"(",
"base64",
".",
"b64decode",
"(",
"encoding",
".",
"smart_bytes",
"(",
"value",
")",
")",
")"
] | [
43,
4
] | [
56,
66
] | python | en | ['en', 'en', 'en'] | True |
CredentialsField.get_prep_value | (self, value) | Overrides ``models.Field`` method. This is used to convert
the value from an instances of this class to bytes that can be
inserted into the database.
| Overrides ``models.Field`` method. This is used to convert
the value from an instances of this class to bytes that can be
inserted into the database.
| def get_prep_value(self, value):
"""Overrides ``models.Field`` method. This is used to convert
the value from an instances of this class to bytes that can be
inserted into the database.
"""
if value is None:
return None
else:
return encoding.smart_text(
base64.b64encode(jsonpickle.encode(value).encode())) | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"encoding",
".",
"smart_text",
"(",
"base64",
".",
"b64encode",
"(",
"jsonpickle",
".",
"encode",
"(",
"value",
")",
".",
"encode",
"(",
")",
")",
")"
] | [
58,
4
] | [
67,
68
] | python | en | ['en', 'en', 'en'] | True |
CredentialsField.value_to_string | (self, obj) | Convert the field value from the provided model to a string.
Used during model serialization.
Args:
obj: db.Model, model object
Returns:
string, the serialized field value
| Convert the field value from the provided model to a string. | def value_to_string(self, obj):
"""Convert the field value from the provided model to a string.
Used during model serialization.
Args:
obj: db.Model, model object
Returns:
string, the serialized field value
"""
value = self._get_val_from_obj(obj)
return self.get_prep_value(value) | [
"def",
"value_to_string",
"(",
"self",
",",
"obj",
")",
":",
"value",
"=",
"self",
".",
"_get_val_from_obj",
"(",
"obj",
")",
"return",
"self",
".",
"get_prep_value",
"(",
"value",
")"
] | [
69,
4
] | [
81,
41
] | python | en | ['en', 'en', 'en'] | True |
unpack | (src_dir, dst_dir) | Move everything under `src_dir` to `dst_dir`, and delete the former. | Move everything under `src_dir` to `dst_dir`, and delete the former. | def unpack(src_dir, dst_dir):
'''Move everything under `src_dir` to `dst_dir`, and delete the former.'''
for dirpath, dirnames, filenames in os.walk(src_dir):
subdir = os.path.relpath(dirpath, src_dir)
for f in filenames:
src = os.path.join(dirpath, f)
dst = os.path.join(dst_dir, subdir, f)
os.renames(src, dst)
for n, d in reversed(list(enumerate(dirnames))):
src = os.path.join(dirpath, d)
dst = os.path.join(dst_dir, subdir, d)
if not os.path.exists(dst):
# Directory does not exist in destination,
# rename it and prune it from os.walk list.
os.renames(src, dst)
del dirnames[n]
# Cleanup.
for dirpath, dirnames, filenames in os.walk(src_dir, topdown=True):
assert not filenames
os.rmdir(dirpath) | [
"def",
"unpack",
"(",
"src_dir",
",",
"dst_dir",
")",
":",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"src_dir",
")",
":",
"subdir",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"dirpath",
",",
"src_dir",
")",
"for",
"f",
"in",
"filenames",
":",
"src",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"f",
")",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst_dir",
",",
"subdir",
",",
"f",
")",
"os",
".",
"renames",
"(",
"src",
",",
"dst",
")",
"for",
"n",
",",
"d",
"in",
"reversed",
"(",
"list",
"(",
"enumerate",
"(",
"dirnames",
")",
")",
")",
":",
"src",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dirpath",
",",
"d",
")",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dst_dir",
",",
"subdir",
",",
"d",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dst",
")",
":",
"# Directory does not exist in destination,",
"# rename it and prune it from os.walk list.",
"os",
".",
"renames",
"(",
"src",
",",
"dst",
")",
"del",
"dirnames",
"[",
"n",
"]",
"# Cleanup.",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"src_dir",
",",
"topdown",
"=",
"True",
")",
":",
"assert",
"not",
"filenames",
"os",
".",
"rmdir",
"(",
"dirpath",
")"
] | [
30,
0
] | [
49,
25
] | python | en | ['en', 'en', 'en'] | True |
Wheel.tags | (self) | List tags (py_version, abi, platform) supported by this wheel. | List tags (py_version, abi, platform) supported by this wheel. | def tags(self):
'''List tags (py_version, abi, platform) supported by this wheel.'''
return itertools.product(self.py_version.split('.'),
self.abi.split('.'),
self.platform.split('.')) | [
"def",
"tags",
"(",
"self",
")",
":",
"return",
"itertools",
".",
"product",
"(",
"self",
".",
"py_version",
".",
"split",
"(",
"'.'",
")",
",",
"self",
".",
"abi",
".",
"split",
"(",
"'.'",
")",
",",
"self",
".",
"platform",
".",
"split",
"(",
"'.'",
")",
")"
] | [
62,
4
] | [
66,
58
] | python | en | ['en', 'en', 'en'] | True |
Wheel.is_compatible | (self) | Is the wheel is compatible with the current platform? | Is the wheel is compatible with the current platform? | def is_compatible(self):
'''Is the wheel is compatible with the current platform?'''
supported_tags = pep425tags.get_supported()
return next((True for t in self.tags() if t in supported_tags), False) | [
"def",
"is_compatible",
"(",
"self",
")",
":",
"supported_tags",
"=",
"pep425tags",
".",
"get_supported",
"(",
")",
"return",
"next",
"(",
"(",
"True",
"for",
"t",
"in",
"self",
".",
"tags",
"(",
")",
"if",
"t",
"in",
"supported_tags",
")",
",",
"False",
")"
] | [
68,
4
] | [
71,
78
] | python | en | ['en', 'en', 'en'] | True |
Wheel.install_as_egg | (self, destination_eggdir) | Install wheel as an egg directory. | Install wheel as an egg directory. | def install_as_egg(self, destination_eggdir):
'''Install wheel as an egg directory.'''
with zipfile.ZipFile(self.filename) as zf:
dist_basename = '%s-%s' % (self.project_name, self.version)
dist_info = '%s.dist-info' % dist_basename
dist_data = '%s.data' % dist_basename
def get_metadata(name):
with zf.open('%s/%s' % (dist_info, name)) as fp:
value = fp.read().decode('utf-8') if PY3 else fp.read()
return email.parser.Parser().parsestr(value)
wheel_metadata = get_metadata('WHEEL')
dist_metadata = get_metadata('METADATA')
# Check wheel format version is supported.
wheel_version = parse_version(wheel_metadata.get('Wheel-Version'))
if not parse_version('1.0') <= wheel_version < parse_version('2.0dev0'):
raise ValueError('unsupported wheel format version: %s' % wheel_version)
# Extract to target directory.
os.mkdir(destination_eggdir)
zf.extractall(destination_eggdir)
# Convert metadata.
dist_info = os.path.join(destination_eggdir, dist_info)
dist = Distribution.from_location(
destination_eggdir, dist_info,
metadata=PathMetadata(destination_eggdir, dist_info)
)
# Note: we need to evaluate and strip markers now,
# as we can't easily convert back from the syntax:
# foobar; "linux" in sys_platform and extra == 'test'
def raw_req(req):
req.marker = None
return str(req)
install_requires = list(sorted(map(raw_req, dist.requires())))
extras_require = {
extra: list(sorted(
req
for req in map(raw_req, dist.requires((extra,)))
if req not in install_requires
))
for extra in dist.extras
}
egg_info = os.path.join(destination_eggdir, 'EGG-INFO')
os.rename(dist_info, egg_info)
os.rename(os.path.join(egg_info, 'METADATA'),
os.path.join(egg_info, 'PKG-INFO'))
setup_dist = SetuptoolsDistribution(attrs=dict(
install_requires=install_requires,
extras_require=extras_require,
))
write_requirements(setup_dist.get_command_obj('egg_info'),
None, os.path.join(egg_info, 'requires.txt'))
# Move data entries to their correct location.
dist_data = os.path.join(destination_eggdir, dist_data)
dist_data_scripts = os.path.join(dist_data, 'scripts')
if os.path.exists(dist_data_scripts):
egg_info_scripts = os.path.join(destination_eggdir,
'EGG-INFO', 'scripts')
os.mkdir(egg_info_scripts)
for entry in os.listdir(dist_data_scripts):
# Remove bytecode, as it's not properly handled
# during easy_install scripts install phase.
if entry.endswith('.pyc'):
os.unlink(os.path.join(dist_data_scripts, entry))
else:
os.rename(os.path.join(dist_data_scripts, entry),
os.path.join(egg_info_scripts, entry))
os.rmdir(dist_data_scripts)
for subdir in filter(os.path.exists, (
os.path.join(dist_data, d)
for d in ('data', 'headers', 'purelib', 'platlib')
)):
unpack(subdir, destination_eggdir)
if os.path.exists(dist_data):
os.rmdir(dist_data)
# Fix namespace packages.
namespace_packages = os.path.join(egg_info, 'namespace_packages.txt')
if os.path.exists(namespace_packages):
with open(namespace_packages) as fp:
namespace_packages = fp.read().split()
for mod in namespace_packages:
mod_dir = os.path.join(destination_eggdir, *mod.split('.'))
mod_init = os.path.join(mod_dir, '__init__.py')
if os.path.exists(mod_dir) and not os.path.exists(mod_init):
with open(mod_init, 'w') as fp:
fp.write(NAMESPACE_PACKAGE_INIT) | [
"def",
"install_as_egg",
"(",
"self",
",",
"destination_eggdir",
")",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"self",
".",
"filename",
")",
"as",
"zf",
":",
"dist_basename",
"=",
"'%s-%s'",
"%",
"(",
"self",
".",
"project_name",
",",
"self",
".",
"version",
")",
"dist_info",
"=",
"'%s.dist-info'",
"%",
"dist_basename",
"dist_data",
"=",
"'%s.data'",
"%",
"dist_basename",
"def",
"get_metadata",
"(",
"name",
")",
":",
"with",
"zf",
".",
"open",
"(",
"'%s/%s'",
"%",
"(",
"dist_info",
",",
"name",
")",
")",
"as",
"fp",
":",
"value",
"=",
"fp",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"if",
"PY3",
"else",
"fp",
".",
"read",
"(",
")",
"return",
"email",
".",
"parser",
".",
"Parser",
"(",
")",
".",
"parsestr",
"(",
"value",
")",
"wheel_metadata",
"=",
"get_metadata",
"(",
"'WHEEL'",
")",
"dist_metadata",
"=",
"get_metadata",
"(",
"'METADATA'",
")",
"# Check wheel format version is supported.",
"wheel_version",
"=",
"parse_version",
"(",
"wheel_metadata",
".",
"get",
"(",
"'Wheel-Version'",
")",
")",
"if",
"not",
"parse_version",
"(",
"'1.0'",
")",
"<=",
"wheel_version",
"<",
"parse_version",
"(",
"'2.0dev0'",
")",
":",
"raise",
"ValueError",
"(",
"'unsupported wheel format version: %s'",
"%",
"wheel_version",
")",
"# Extract to target directory.",
"os",
".",
"mkdir",
"(",
"destination_eggdir",
")",
"zf",
".",
"extractall",
"(",
"destination_eggdir",
")",
"# Convert metadata.",
"dist_info",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination_eggdir",
",",
"dist_info",
")",
"dist",
"=",
"Distribution",
".",
"from_location",
"(",
"destination_eggdir",
",",
"dist_info",
",",
"metadata",
"=",
"PathMetadata",
"(",
"destination_eggdir",
",",
"dist_info",
")",
")",
"# Note: we need to evaluate and strip markers now,",
"# as we can't easily convert back from the syntax:",
"# foobar; \"linux\" in sys_platform and extra == 'test'",
"def",
"raw_req",
"(",
"req",
")",
":",
"req",
".",
"marker",
"=",
"None",
"return",
"str",
"(",
"req",
")",
"install_requires",
"=",
"list",
"(",
"sorted",
"(",
"map",
"(",
"raw_req",
",",
"dist",
".",
"requires",
"(",
")",
")",
")",
")",
"extras_require",
"=",
"{",
"extra",
":",
"list",
"(",
"sorted",
"(",
"req",
"for",
"req",
"in",
"map",
"(",
"raw_req",
",",
"dist",
".",
"requires",
"(",
"(",
"extra",
",",
")",
")",
")",
"if",
"req",
"not",
"in",
"install_requires",
")",
")",
"for",
"extra",
"in",
"dist",
".",
"extras",
"}",
"egg_info",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination_eggdir",
",",
"'EGG-INFO'",
")",
"os",
".",
"rename",
"(",
"dist_info",
",",
"egg_info",
")",
"os",
".",
"rename",
"(",
"os",
".",
"path",
".",
"join",
"(",
"egg_info",
",",
"'METADATA'",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"egg_info",
",",
"'PKG-INFO'",
")",
")",
"setup_dist",
"=",
"SetuptoolsDistribution",
"(",
"attrs",
"=",
"dict",
"(",
"install_requires",
"=",
"install_requires",
",",
"extras_require",
"=",
"extras_require",
",",
")",
")",
"write_requirements",
"(",
"setup_dist",
".",
"get_command_obj",
"(",
"'egg_info'",
")",
",",
"None",
",",
"os",
".",
"path",
".",
"join",
"(",
"egg_info",
",",
"'requires.txt'",
")",
")",
"# Move data entries to their correct location.",
"dist_data",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination_eggdir",
",",
"dist_data",
")",
"dist_data_scripts",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dist_data",
",",
"'scripts'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dist_data_scripts",
")",
":",
"egg_info_scripts",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination_eggdir",
",",
"'EGG-INFO'",
",",
"'scripts'",
")",
"os",
".",
"mkdir",
"(",
"egg_info_scripts",
")",
"for",
"entry",
"in",
"os",
".",
"listdir",
"(",
"dist_data_scripts",
")",
":",
"# Remove bytecode, as it's not properly handled",
"# during easy_install scripts install phase.",
"if",
"entry",
".",
"endswith",
"(",
"'.pyc'",
")",
":",
"os",
".",
"unlink",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dist_data_scripts",
",",
"entry",
")",
")",
"else",
":",
"os",
".",
"rename",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dist_data_scripts",
",",
"entry",
")",
",",
"os",
".",
"path",
".",
"join",
"(",
"egg_info_scripts",
",",
"entry",
")",
")",
"os",
".",
"rmdir",
"(",
"dist_data_scripts",
")",
"for",
"subdir",
"in",
"filter",
"(",
"os",
".",
"path",
".",
"exists",
",",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dist_data",
",",
"d",
")",
"for",
"d",
"in",
"(",
"'data'",
",",
"'headers'",
",",
"'purelib'",
",",
"'platlib'",
")",
")",
")",
":",
"unpack",
"(",
"subdir",
",",
"destination_eggdir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dist_data",
")",
":",
"os",
".",
"rmdir",
"(",
"dist_data",
")",
"# Fix namespace packages.",
"namespace_packages",
"=",
"os",
".",
"path",
".",
"join",
"(",
"egg_info",
",",
"'namespace_packages.txt'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"namespace_packages",
")",
":",
"with",
"open",
"(",
"namespace_packages",
")",
"as",
"fp",
":",
"namespace_packages",
"=",
"fp",
".",
"read",
"(",
")",
".",
"split",
"(",
")",
"for",
"mod",
"in",
"namespace_packages",
":",
"mod_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination_eggdir",
",",
"*",
"mod",
".",
"split",
"(",
"'.'",
")",
")",
"mod_init",
"=",
"os",
".",
"path",
".",
"join",
"(",
"mod_dir",
",",
"'__init__.py'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"mod_dir",
")",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"mod_init",
")",
":",
"with",
"open",
"(",
"mod_init",
",",
"'w'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"NAMESPACE_PACKAGE_INIT",
")"
] | [
79,
4
] | [
162,
60
] | python | en | ['en', 'en', 'en'] | True |
check_module | (feature) |
Checks if a module is available.
:param feature: The module to check for.
:returns: ``True`` if available, ``False`` otherwise.
:raises ValueError: If the module is not defined in this version of Pillow.
|
Checks if a module is available. | def check_module(feature):
"""
Checks if a module is available.
:param feature: The module to check for.
:returns: ``True`` if available, ``False`` otherwise.
:raises ValueError: If the module is not defined in this version of Pillow.
"""
if not (feature in modules):
raise ValueError(f"Unknown module {feature}")
module, ver = modules[feature]
try:
__import__(module)
return True
except ImportError:
return False | [
"def",
"check_module",
"(",
"feature",
")",
":",
"if",
"not",
"(",
"feature",
"in",
"modules",
")",
":",
"raise",
"ValueError",
"(",
"f\"Unknown module {feature}\"",
")",
"module",
",",
"ver",
"=",
"modules",
"[",
"feature",
"]",
"try",
":",
"__import__",
"(",
"module",
")",
"return",
"True",
"except",
"ImportError",
":",
"return",
"False"
] | [
18,
0
] | [
35,
20
] | python | en | ['en', 'error', 'th'] | False |
version_module | (feature) |
:param feature: The module to check for.
:returns:
The loaded version number as a string, or ``None`` if unknown or not available.
:raises ValueError: If the module is not defined in this version of Pillow.
|
:param feature: The module to check for.
:returns:
The loaded version number as a string, or ``None`` if unknown or not available.
:raises ValueError: If the module is not defined in this version of Pillow.
| def version_module(feature):
"""
:param feature: The module to check for.
:returns:
The loaded version number as a string, or ``None`` if unknown or not available.
:raises ValueError: If the module is not defined in this version of Pillow.
"""
if not check_module(feature):
return None
module, ver = modules[feature]
if ver is None:
return None
return getattr(__import__(module, fromlist=[ver]), ver) | [
"def",
"version_module",
"(",
"feature",
")",
":",
"if",
"not",
"check_module",
"(",
"feature",
")",
":",
"return",
"None",
"module",
",",
"ver",
"=",
"modules",
"[",
"feature",
"]",
"if",
"ver",
"is",
"None",
":",
"return",
"None",
"return",
"getattr",
"(",
"__import__",
"(",
"module",
",",
"fromlist",
"=",
"[",
"ver",
"]",
")",
",",
"ver",
")"
] | [
38,
0
] | [
53,
59
] | python | en | ['en', 'error', 'th'] | False |
get_supported_modules | () |
:returns: A list of all supported modules.
|
:returns: A list of all supported modules.
| def get_supported_modules():
"""
:returns: A list of all supported modules.
"""
return [f for f in modules if check_module(f)] | [
"def",
"get_supported_modules",
"(",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"modules",
"if",
"check_module",
"(",
"f",
")",
"]"
] | [
56,
0
] | [
60,
50
] | python | en | ['en', 'error', 'th'] | False |
check_codec | (feature) |
Checks if a codec is available.
:param feature: The codec to check for.
:returns: ``True`` if available, ``False`` otherwise.
:raises ValueError: If the codec is not defined in this version of Pillow.
|
Checks if a codec is available. | def check_codec(feature):
"""
Checks if a codec is available.
:param feature: The codec to check for.
:returns: ``True`` if available, ``False`` otherwise.
:raises ValueError: If the codec is not defined in this version of Pillow.
"""
if feature not in codecs:
raise ValueError(f"Unknown codec {feature}")
codec, lib = codecs[feature]
return codec + "_encoder" in dir(Image.core) | [
"def",
"check_codec",
"(",
"feature",
")",
":",
"if",
"feature",
"not",
"in",
"codecs",
":",
"raise",
"ValueError",
"(",
"f\"Unknown codec {feature}\"",
")",
"codec",
",",
"lib",
"=",
"codecs",
"[",
"feature",
"]",
"return",
"codec",
"+",
"\"_encoder\"",
"in",
"dir",
"(",
"Image",
".",
"core",
")"
] | [
71,
0
] | [
84,
48
] | python | en | ['en', 'error', 'th'] | False |
version_codec | (feature) |
:param feature: The codec to check for.
:returns:
The version number as a string, or ``None`` if not available.
Checked at compile time for ``jpg``, run-time otherwise.
:raises ValueError: If the codec is not defined in this version of Pillow.
|
:param feature: The codec to check for.
:returns:
The version number as a string, or ``None`` if not available.
Checked at compile time for ``jpg``, run-time otherwise.
:raises ValueError: If the codec is not defined in this version of Pillow.
| def version_codec(feature):
"""
:param feature: The codec to check for.
:returns:
The version number as a string, or ``None`` if not available.
Checked at compile time for ``jpg``, run-time otherwise.
:raises ValueError: If the codec is not defined in this version of Pillow.
"""
if not check_codec(feature):
return None
codec, lib = codecs[feature]
version = getattr(Image.core, lib + "_version")
if feature == "libtiff":
return version.split("\n")[0].split("Version ")[1]
return version | [
"def",
"version_codec",
"(",
"feature",
")",
":",
"if",
"not",
"check_codec",
"(",
"feature",
")",
":",
"return",
"None",
"codec",
",",
"lib",
"=",
"codecs",
"[",
"feature",
"]",
"version",
"=",
"getattr",
"(",
"Image",
".",
"core",
",",
"lib",
"+",
"\"_version\"",
")",
"if",
"feature",
"==",
"\"libtiff\"",
":",
"return",
"version",
".",
"split",
"(",
"\"\\n\"",
")",
"[",
"0",
"]",
".",
"split",
"(",
"\"Version \"",
")",
"[",
"1",
"]",
"return",
"version"
] | [
87,
0
] | [
105,
18
] | python | en | ['en', 'error', 'th'] | False |
get_supported_codecs | () |
:returns: A list of all supported codecs.
|
:returns: A list of all supported codecs.
| def get_supported_codecs():
"""
:returns: A list of all supported codecs.
"""
return [f for f in codecs if check_codec(f)] | [
"def",
"get_supported_codecs",
"(",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"codecs",
"if",
"check_codec",
"(",
"f",
")",
"]"
] | [
108,
0
] | [
112,
48
] | python | en | ['en', 'error', 'th'] | False |
check_feature | (feature) |
Checks if a feature is available.
:param feature: The feature to check for.
:returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown.
:raises ValueError: If the feature is not defined in this version of Pillow.
|
Checks if a feature is available. | def check_feature(feature):
"""
Checks if a feature is available.
:param feature: The feature to check for.
:returns: ``True`` if available, ``False`` if unavailable, ``None`` if unknown.
:raises ValueError: If the feature is not defined in this version of Pillow.
"""
if feature not in features:
raise ValueError(f"Unknown feature {feature}")
module, flag, ver = features[feature]
try:
imported_module = __import__(module, fromlist=["PIL"])
return getattr(imported_module, flag)
except ImportError:
return None | [
"def",
"check_feature",
"(",
"feature",
")",
":",
"if",
"feature",
"not",
"in",
"features",
":",
"raise",
"ValueError",
"(",
"f\"Unknown feature {feature}\"",
")",
"module",
",",
"flag",
",",
"ver",
"=",
"features",
"[",
"feature",
"]",
"try",
":",
"imported_module",
"=",
"__import__",
"(",
"module",
",",
"fromlist",
"=",
"[",
"\"PIL\"",
"]",
")",
"return",
"getattr",
"(",
"imported_module",
",",
"flag",
")",
"except",
"ImportError",
":",
"return",
"None"
] | [
128,
0
] | [
145,
19
] | python | en | ['en', 'error', 'th'] | False |
version_feature | (feature) |
:param feature: The feature to check for.
:returns: The version number as a string, or ``None`` if not available.
:raises ValueError: If the feature is not defined in this version of Pillow.
|
:param feature: The feature to check for.
:returns: The version number as a string, or ``None`` if not available.
:raises ValueError: If the feature is not defined in this version of Pillow.
| def version_feature(feature):
"""
:param feature: The feature to check for.
:returns: The version number as a string, or ``None`` if not available.
:raises ValueError: If the feature is not defined in this version of Pillow.
"""
if not check_feature(feature):
return None
module, flag, ver = features[feature]
if ver is None:
return None
return getattr(__import__(module, fromlist=[ver]), ver) | [
"def",
"version_feature",
"(",
"feature",
")",
":",
"if",
"not",
"check_feature",
"(",
"feature",
")",
":",
"return",
"None",
"module",
",",
"flag",
",",
"ver",
"=",
"features",
"[",
"feature",
"]",
"if",
"ver",
"is",
"None",
":",
"return",
"None",
"return",
"getattr",
"(",
"__import__",
"(",
"module",
",",
"fromlist",
"=",
"[",
"ver",
"]",
")",
",",
"ver",
")"
] | [
148,
0
] | [
162,
59
] | python | en | ['en', 'error', 'th'] | False |
get_supported_features | () |
:returns: A list of all supported features.
|
:returns: A list of all supported features.
| def get_supported_features():
"""
:returns: A list of all supported features.
"""
return [f for f in features if check_feature(f)] | [
"def",
"get_supported_features",
"(",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"features",
"if",
"check_feature",
"(",
"f",
")",
"]"
] | [
165,
0
] | [
169,
52
] | python | en | ['en', 'error', 'th'] | False |
check | (feature) |
:param feature: A module, codec, or feature name.
:returns:
``True`` if the module, codec, or feature is available,
``False`` or ``None`` otherwise.
|
:param feature: A module, codec, or feature name.
:returns:
``True`` if the module, codec, or feature is available,
``False`` or ``None`` otherwise.
| def check(feature):
"""
:param feature: A module, codec, or feature name.
:returns:
``True`` if the module, codec, or feature is available,
``False`` or ``None`` otherwise.
"""
if feature in modules:
return check_module(feature)
if feature in codecs:
return check_codec(feature)
if feature in features:
return check_feature(feature)
warnings.warn(f"Unknown feature '{feature}'.", stacklevel=2)
return False | [
"def",
"check",
"(",
"feature",
")",
":",
"if",
"feature",
"in",
"modules",
":",
"return",
"check_module",
"(",
"feature",
")",
"if",
"feature",
"in",
"codecs",
":",
"return",
"check_codec",
"(",
"feature",
")",
"if",
"feature",
"in",
"features",
":",
"return",
"check_feature",
"(",
"feature",
")",
"warnings",
".",
"warn",
"(",
"f\"Unknown feature '{feature}'.\"",
",",
"stacklevel",
"=",
"2",
")",
"return",
"False"
] | [
172,
0
] | [
187,
16
] | python | en | ['en', 'error', 'th'] | False |
version | (feature) |
:param feature:
The module, codec, or feature to check for.
:returns:
The version number as a string, or ``None`` if unknown or not available.
|
:param feature:
The module, codec, or feature to check for.
:returns:
The version number as a string, or ``None`` if unknown or not available.
| def version(feature):
"""
:param feature:
The module, codec, or feature to check for.
:returns:
The version number as a string, or ``None`` if unknown or not available.
"""
if feature in modules:
return version_module(feature)
if feature in codecs:
return version_codec(feature)
if feature in features:
return version_feature(feature)
return None | [
"def",
"version",
"(",
"feature",
")",
":",
"if",
"feature",
"in",
"modules",
":",
"return",
"version_module",
"(",
"feature",
")",
"if",
"feature",
"in",
"codecs",
":",
"return",
"version_codec",
"(",
"feature",
")",
"if",
"feature",
"in",
"features",
":",
"return",
"version_feature",
"(",
"feature",
")",
"return",
"None"
] | [
190,
0
] | [
203,
15
] | python | en | ['en', 'error', 'th'] | False |
get_supported | () |
:returns: A list of all supported modules, features, and codecs.
|
:returns: A list of all supported modules, features, and codecs.
| def get_supported():
"""
:returns: A list of all supported modules, features, and codecs.
"""
ret = get_supported_modules()
ret.extend(get_supported_features())
ret.extend(get_supported_codecs())
return ret | [
"def",
"get_supported",
"(",
")",
":",
"ret",
"=",
"get_supported_modules",
"(",
")",
"ret",
".",
"extend",
"(",
"get_supported_features",
"(",
")",
")",
"ret",
".",
"extend",
"(",
"get_supported_codecs",
"(",
")",
")",
"return",
"ret"
] | [
206,
0
] | [
214,
14
] | python | en | ['en', 'error', 'th'] | False |
pilinfo | (out=None, supported_formats=True) |
Prints information about this installation of Pillow.
This function can be called with ``python3 -m PIL``.
:param out:
The output stream to print to. Defaults to ``sys.stdout`` if ``None``.
:param supported_formats:
If ``True``, a list of all supported image file formats will be printed.
|
Prints information about this installation of Pillow.
This function can be called with ``python3 -m PIL``. | def pilinfo(out=None, supported_formats=True):
"""
Prints information about this installation of Pillow.
This function can be called with ``python3 -m PIL``.
:param out:
The output stream to print to. Defaults to ``sys.stdout`` if ``None``.
:param supported_formats:
If ``True``, a list of all supported image file formats will be printed.
"""
if out is None:
out = sys.stdout
Image.init()
print("-" * 68, file=out)
print(f"Pillow {PIL.__version__}", file=out)
py_version = sys.version.splitlines()
print(f"Python {py_version[0].strip()}", file=out)
for py_version in py_version[1:]:
print(f" {py_version.strip()}", file=out)
print("-" * 68, file=out)
print(
f"Python modules loaded from {os.path.dirname(Image.__file__)}",
file=out,
)
print(
f"Binary modules loaded from {os.path.dirname(Image.core.__file__)}",
file=out,
)
print("-" * 68, file=out)
for name, feature in [
("pil", "PIL CORE"),
("tkinter", "TKINTER"),
("freetype2", "FREETYPE2"),
("littlecms2", "LITTLECMS2"),
("webp", "WEBP"),
("transp_webp", "WEBP Transparency"),
("webp_mux", "WEBPMUX"),
("webp_anim", "WEBP Animation"),
("jpg", "JPEG"),
("jpg_2000", "OPENJPEG (JPEG2000)"),
("zlib", "ZLIB (PNG/ZIP)"),
("libtiff", "LIBTIFF"),
("raqm", "RAQM (Bidirectional Text)"),
("libimagequant", "LIBIMAGEQUANT (Quantization method)"),
("xcb", "XCB (X protocol)"),
]:
if check(name):
if name == "jpg" and check_feature("libjpeg_turbo"):
v = "libjpeg-turbo " + version_feature("libjpeg_turbo")
else:
v = version(name)
if v is not None:
version_static = name in ("pil", "jpg")
if name == "littlecms2":
# this check is also in src/_imagingcms.c:setup_module()
version_static = tuple(int(x) for x in v.split(".")) < (2, 7)
t = "compiled for" if version_static else "loaded"
if name == "raqm":
for f in ("fribidi", "harfbuzz"):
v2 = version_feature(f)
if v2 is not None:
v += f", {f} {v2}"
print("---", feature, "support ok,", t, v, file=out)
else:
print("---", feature, "support ok", file=out)
else:
print("***", feature, "support not installed", file=out)
print("-" * 68, file=out)
if supported_formats:
extensions = collections.defaultdict(list)
for ext, i in Image.EXTENSION.items():
extensions[i].append(ext)
for i in sorted(Image.ID):
line = f"{i}"
if i in Image.MIME:
line = f"{line} {Image.MIME[i]}"
print(line, file=out)
if i in extensions:
print(
"Extensions: {}".format(", ".join(sorted(extensions[i]))), file=out
)
features = []
if i in Image.OPEN:
features.append("open")
if i in Image.SAVE:
features.append("save")
if i in Image.SAVE_ALL:
features.append("save_all")
if i in Image.DECODERS:
features.append("decode")
if i in Image.ENCODERS:
features.append("encode")
print("Features: {}".format(", ".join(features)), file=out)
print("-" * 68, file=out) | [
"def",
"pilinfo",
"(",
"out",
"=",
"None",
",",
"supported_formats",
"=",
"True",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"sys",
".",
"stdout",
"Image",
".",
"init",
"(",
")",
"print",
"(",
"\"-\"",
"*",
"68",
",",
"file",
"=",
"out",
")",
"print",
"(",
"f\"Pillow {PIL.__version__}\"",
",",
"file",
"=",
"out",
")",
"py_version",
"=",
"sys",
".",
"version",
".",
"splitlines",
"(",
")",
"print",
"(",
"f\"Python {py_version[0].strip()}\"",
",",
"file",
"=",
"out",
")",
"for",
"py_version",
"in",
"py_version",
"[",
"1",
":",
"]",
":",
"print",
"(",
"f\" {py_version.strip()}\"",
",",
"file",
"=",
"out",
")",
"print",
"(",
"\"-\"",
"*",
"68",
",",
"file",
"=",
"out",
")",
"print",
"(",
"f\"Python modules loaded from {os.path.dirname(Image.__file__)}\"",
",",
"file",
"=",
"out",
",",
")",
"print",
"(",
"f\"Binary modules loaded from {os.path.dirname(Image.core.__file__)}\"",
",",
"file",
"=",
"out",
",",
")",
"print",
"(",
"\"-\"",
"*",
"68",
",",
"file",
"=",
"out",
")",
"for",
"name",
",",
"feature",
"in",
"[",
"(",
"\"pil\"",
",",
"\"PIL CORE\"",
")",
",",
"(",
"\"tkinter\"",
",",
"\"TKINTER\"",
")",
",",
"(",
"\"freetype2\"",
",",
"\"FREETYPE2\"",
")",
",",
"(",
"\"littlecms2\"",
",",
"\"LITTLECMS2\"",
")",
",",
"(",
"\"webp\"",
",",
"\"WEBP\"",
")",
",",
"(",
"\"transp_webp\"",
",",
"\"WEBP Transparency\"",
")",
",",
"(",
"\"webp_mux\"",
",",
"\"WEBPMUX\"",
")",
",",
"(",
"\"webp_anim\"",
",",
"\"WEBP Animation\"",
")",
",",
"(",
"\"jpg\"",
",",
"\"JPEG\"",
")",
",",
"(",
"\"jpg_2000\"",
",",
"\"OPENJPEG (JPEG2000)\"",
")",
",",
"(",
"\"zlib\"",
",",
"\"ZLIB (PNG/ZIP)\"",
")",
",",
"(",
"\"libtiff\"",
",",
"\"LIBTIFF\"",
")",
",",
"(",
"\"raqm\"",
",",
"\"RAQM (Bidirectional Text)\"",
")",
",",
"(",
"\"libimagequant\"",
",",
"\"LIBIMAGEQUANT (Quantization method)\"",
")",
",",
"(",
"\"xcb\"",
",",
"\"XCB (X protocol)\"",
")",
",",
"]",
":",
"if",
"check",
"(",
"name",
")",
":",
"if",
"name",
"==",
"\"jpg\"",
"and",
"check_feature",
"(",
"\"libjpeg_turbo\"",
")",
":",
"v",
"=",
"\"libjpeg-turbo \"",
"+",
"version_feature",
"(",
"\"libjpeg_turbo\"",
")",
"else",
":",
"v",
"=",
"version",
"(",
"name",
")",
"if",
"v",
"is",
"not",
"None",
":",
"version_static",
"=",
"name",
"in",
"(",
"\"pil\"",
",",
"\"jpg\"",
")",
"if",
"name",
"==",
"\"littlecms2\"",
":",
"# this check is also in src/_imagingcms.c:setup_module()",
"version_static",
"=",
"tuple",
"(",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"v",
".",
"split",
"(",
"\".\"",
")",
")",
"<",
"(",
"2",
",",
"7",
")",
"t",
"=",
"\"compiled for\"",
"if",
"version_static",
"else",
"\"loaded\"",
"if",
"name",
"==",
"\"raqm\"",
":",
"for",
"f",
"in",
"(",
"\"fribidi\"",
",",
"\"harfbuzz\"",
")",
":",
"v2",
"=",
"version_feature",
"(",
"f",
")",
"if",
"v2",
"is",
"not",
"None",
":",
"v",
"+=",
"f\", {f} {v2}\"",
"print",
"(",
"\"---\"",
",",
"feature",
",",
"\"support ok,\"",
",",
"t",
",",
"v",
",",
"file",
"=",
"out",
")",
"else",
":",
"print",
"(",
"\"---\"",
",",
"feature",
",",
"\"support ok\"",
",",
"file",
"=",
"out",
")",
"else",
":",
"print",
"(",
"\"***\"",
",",
"feature",
",",
"\"support not installed\"",
",",
"file",
"=",
"out",
")",
"print",
"(",
"\"-\"",
"*",
"68",
",",
"file",
"=",
"out",
")",
"if",
"supported_formats",
":",
"extensions",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"for",
"ext",
",",
"i",
"in",
"Image",
".",
"EXTENSION",
".",
"items",
"(",
")",
":",
"extensions",
"[",
"i",
"]",
".",
"append",
"(",
"ext",
")",
"for",
"i",
"in",
"sorted",
"(",
"Image",
".",
"ID",
")",
":",
"line",
"=",
"f\"{i}\"",
"if",
"i",
"in",
"Image",
".",
"MIME",
":",
"line",
"=",
"f\"{line} {Image.MIME[i]}\"",
"print",
"(",
"line",
",",
"file",
"=",
"out",
")",
"if",
"i",
"in",
"extensions",
":",
"print",
"(",
"\"Extensions: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"extensions",
"[",
"i",
"]",
")",
")",
")",
",",
"file",
"=",
"out",
")",
"features",
"=",
"[",
"]",
"if",
"i",
"in",
"Image",
".",
"OPEN",
":",
"features",
".",
"append",
"(",
"\"open\"",
")",
"if",
"i",
"in",
"Image",
".",
"SAVE",
":",
"features",
".",
"append",
"(",
"\"save\"",
")",
"if",
"i",
"in",
"Image",
".",
"SAVE_ALL",
":",
"features",
".",
"append",
"(",
"\"save_all\"",
")",
"if",
"i",
"in",
"Image",
".",
"DECODERS",
":",
"features",
".",
"append",
"(",
"\"decode\"",
")",
"if",
"i",
"in",
"Image",
".",
"ENCODERS",
":",
"features",
".",
"append",
"(",
"\"encode\"",
")",
"print",
"(",
"\"Features: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"features",
")",
")",
",",
"file",
"=",
"out",
")",
"print",
"(",
"\"-\"",
"*",
"68",
",",
"file",
"=",
"out",
")"
] | [
217,
0
] | [
319,
37
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.get_redirect_location | (self) |
Should we redirect and where to?
:returns: Truthy redirect location string if we got a redirect status
code and valid location. ``None`` if redirect status and no
location. ``False`` if not a redirect status code.
|
Should we redirect and where to? | def get_redirect_location(self):
"""
Should we redirect and where to?
:returns: Truthy redirect location string if we got a redirect status
code and valid location. ``None`` if redirect status and no
location. ``False`` if not a redirect status code.
"""
if self.status in self.REDIRECT_STATUSES:
return self.headers.get("location")
return False | [
"def",
"get_redirect_location",
"(",
"self",
")",
":",
"if",
"self",
".",
"status",
"in",
"self",
".",
"REDIRECT_STATUSES",
":",
"return",
"self",
".",
"headers",
".",
"get",
"(",
"\"location\"",
")",
"return",
"False"
] | [
261,
4
] | [
272,
20
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.drain_conn | (self) |
Read and discard any remaining HTTP response data in the response connection.
Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.
|
Read and discard any remaining HTTP response data in the response connection. | def drain_conn(self):
"""
Read and discard any remaining HTTP response data in the response connection.
Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.
"""
try:
self.read()
except (HTTPError, SocketError, BaseSSLError, HTTPException):
pass | [
"def",
"drain_conn",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"read",
"(",
")",
"except",
"(",
"HTTPError",
",",
"SocketError",
",",
"BaseSSLError",
",",
"HTTPException",
")",
":",
"pass"
] | [
281,
4
] | [
290,
16
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.tell | (self) |
Obtain the number of bytes pulled over the wire so far. May differ from
the amount of content returned by :meth:``urllib3.response.HTTPResponse.read``
if bytes are encoded on the wire (e.g, compressed).
|
Obtain the number of bytes pulled over the wire so far. May differ from
the amount of content returned by :meth:``urllib3.response.HTTPResponse.read``
if bytes are encoded on the wire (e.g, compressed).
| def tell(self):
"""
Obtain the number of bytes pulled over the wire so far. May differ from
the amount of content returned by :meth:``urllib3.response.HTTPResponse.read``
if bytes are encoded on the wire (e.g, compressed).
"""
return self._fp_bytes_read | [
"def",
"tell",
"(",
"self",
")",
":",
"return",
"self",
".",
"_fp_bytes_read"
] | [
308,
4
] | [
314,
34
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse._init_length | (self, request_method) |
Set initial length value for Response content if available.
|
Set initial length value for Response content if available.
| def _init_length(self, request_method):
"""
Set initial length value for Response content if available.
"""
length = self.headers.get("content-length")
if length is not None:
if self.chunked:
# This Response will fail with an IncompleteRead if it can't be
# received as chunked. This method falls back to attempt reading
# the response before raising an exception.
log.warning(
"Received response with both Content-Length and "
"Transfer-Encoding set. This is expressly forbidden "
"by RFC 7230 sec 3.3.2. Ignoring Content-Length and "
"attempting to process response as Transfer-Encoding: "
"chunked."
)
return None
try:
# RFC 7230 section 3.3.2 specifies multiple content lengths can
# be sent in a single Content-Length header
# (e.g. Content-Length: 42, 42). This line ensures the values
# are all valid ints and that as long as the `set` length is 1,
# all values are the same. Otherwise, the header is invalid.
lengths = set([int(val) for val in length.split(",")])
if len(lengths) > 1:
raise InvalidHeader(
"Content-Length contained multiple "
"unmatching values (%s)" % length
)
length = lengths.pop()
except ValueError:
length = None
else:
if length < 0:
length = None
# Convert status to int for comparison
# In some cases, httplib returns a status of "_UNKNOWN"
try:
status = int(self.status)
except ValueError:
status = 0
# Check for responses that shouldn't include a body
if status in (204, 304) or 100 <= status < 200 or request_method == "HEAD":
length = 0
return length | [
"def",
"_init_length",
"(",
"self",
",",
"request_method",
")",
":",
"length",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"\"content-length\"",
")",
"if",
"length",
"is",
"not",
"None",
":",
"if",
"self",
".",
"chunked",
":",
"# This Response will fail with an IncompleteRead if it can't be",
"# received as chunked. This method falls back to attempt reading",
"# the response before raising an exception.",
"log",
".",
"warning",
"(",
"\"Received response with both Content-Length and \"",
"\"Transfer-Encoding set. This is expressly forbidden \"",
"\"by RFC 7230 sec 3.3.2. Ignoring Content-Length and \"",
"\"attempting to process response as Transfer-Encoding: \"",
"\"chunked.\"",
")",
"return",
"None",
"try",
":",
"# RFC 7230 section 3.3.2 specifies multiple content lengths can",
"# be sent in a single Content-Length header",
"# (e.g. Content-Length: 42, 42). This line ensures the values",
"# are all valid ints and that as long as the `set` length is 1,",
"# all values are the same. Otherwise, the header is invalid.",
"lengths",
"=",
"set",
"(",
"[",
"int",
"(",
"val",
")",
"for",
"val",
"in",
"length",
".",
"split",
"(",
"\",\"",
")",
"]",
")",
"if",
"len",
"(",
"lengths",
")",
">",
"1",
":",
"raise",
"InvalidHeader",
"(",
"\"Content-Length contained multiple \"",
"\"unmatching values (%s)\"",
"%",
"length",
")",
"length",
"=",
"lengths",
".",
"pop",
"(",
")",
"except",
"ValueError",
":",
"length",
"=",
"None",
"else",
":",
"if",
"length",
"<",
"0",
":",
"length",
"=",
"None",
"# Convert status to int for comparison",
"# In some cases, httplib returns a status of \"_UNKNOWN\"",
"try",
":",
"status",
"=",
"int",
"(",
"self",
".",
"status",
")",
"except",
"ValueError",
":",
"status",
"=",
"0",
"# Check for responses that shouldn't include a body",
"if",
"status",
"in",
"(",
"204",
",",
"304",
")",
"or",
"100",
"<=",
"status",
"<",
"200",
"or",
"request_method",
"==",
"\"HEAD\"",
":",
"length",
"=",
"0",
"return",
"length"
] | [
316,
4
] | [
366,
21
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse._init_decoder | (self) |
Set-up the _decoder attribute if necessary.
|
Set-up the _decoder attribute if necessary.
| def _init_decoder(self):
"""
Set-up the _decoder attribute if necessary.
"""
# Note: content-encoding value should be case-insensitive, per RFC 7230
# Section 3.2
content_encoding = self.headers.get("content-encoding", "").lower()
if self._decoder is None:
if content_encoding in self.CONTENT_DECODERS:
self._decoder = _get_decoder(content_encoding)
elif "," in content_encoding:
encodings = [
e.strip()
for e in content_encoding.split(",")
if e.strip() in self.CONTENT_DECODERS
]
if len(encodings):
self._decoder = _get_decoder(content_encoding) | [
"def",
"_init_decoder",
"(",
"self",
")",
":",
"# Note: content-encoding value should be case-insensitive, per RFC 7230",
"# Section 3.2",
"content_encoding",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"\"content-encoding\"",
",",
"\"\"",
")",
".",
"lower",
"(",
")",
"if",
"self",
".",
"_decoder",
"is",
"None",
":",
"if",
"content_encoding",
"in",
"self",
".",
"CONTENT_DECODERS",
":",
"self",
".",
"_decoder",
"=",
"_get_decoder",
"(",
"content_encoding",
")",
"elif",
"\",\"",
"in",
"content_encoding",
":",
"encodings",
"=",
"[",
"e",
".",
"strip",
"(",
")",
"for",
"e",
"in",
"content_encoding",
".",
"split",
"(",
"\",\"",
")",
"if",
"e",
".",
"strip",
"(",
")",
"in",
"self",
".",
"CONTENT_DECODERS",
"]",
"if",
"len",
"(",
"encodings",
")",
":",
"self",
".",
"_decoder",
"=",
"_get_decoder",
"(",
"content_encoding",
")"
] | [
368,
4
] | [
385,
66
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse._decode | (self, data, decode_content, flush_decoder) |
Decode the data passed in and potentially flush the decoder.
|
Decode the data passed in and potentially flush the decoder.
| def _decode(self, data, decode_content, flush_decoder):
"""
Decode the data passed in and potentially flush the decoder.
"""
if not decode_content:
return data
try:
if self._decoder:
data = self._decoder.decompress(data)
except self.DECODER_ERROR_CLASSES as e:
content_encoding = self.headers.get("content-encoding", "").lower()
raise DecodeError(
"Received response with content-encoding: %s, but "
"failed to decode it." % content_encoding,
e,
)
if flush_decoder:
data += self._flush_decoder()
return data | [
"def",
"_decode",
"(",
"self",
",",
"data",
",",
"decode_content",
",",
"flush_decoder",
")",
":",
"if",
"not",
"decode_content",
":",
"return",
"data",
"try",
":",
"if",
"self",
".",
"_decoder",
":",
"data",
"=",
"self",
".",
"_decoder",
".",
"decompress",
"(",
"data",
")",
"except",
"self",
".",
"DECODER_ERROR_CLASSES",
"as",
"e",
":",
"content_encoding",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"\"content-encoding\"",
",",
"\"\"",
")",
".",
"lower",
"(",
")",
"raise",
"DecodeError",
"(",
"\"Received response with content-encoding: %s, but \"",
"\"failed to decode it.\"",
"%",
"content_encoding",
",",
"e",
",",
")",
"if",
"flush_decoder",
":",
"data",
"+=",
"self",
".",
"_flush_decoder",
"(",
")",
"return",
"data"
] | [
391,
4
] | [
411,
19
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse._flush_decoder | (self) |
Flushes the decoder. Should only be called if the decoder is actually
being used.
|
Flushes the decoder. Should only be called if the decoder is actually
being used.
| def _flush_decoder(self):
"""
Flushes the decoder. Should only be called if the decoder is actually
being used.
"""
if self._decoder:
buf = self._decoder.decompress(b"")
return buf + self._decoder.flush()
return b"" | [
"def",
"_flush_decoder",
"(",
"self",
")",
":",
"if",
"self",
".",
"_decoder",
":",
"buf",
"=",
"self",
".",
"_decoder",
".",
"decompress",
"(",
"b\"\"",
")",
"return",
"buf",
"+",
"self",
".",
"_decoder",
".",
"flush",
"(",
")",
"return",
"b\"\""
] | [
413,
4
] | [
422,
18
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse._error_catcher | (self) |
Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool.
|
Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api. | def _error_catcher(self):
"""
Catch low-level python exceptions, instead re-raising urllib3
variants, so that low-level exceptions are not leaked in the
high-level api.
On exit, release the connection back to the pool.
"""
clean_exit = False
try:
try:
yield
except SocketTimeout:
# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but
# there is yet no clean way to get at it from this context.
raise ReadTimeoutError(self._pool, None, "Read timed out.")
except BaseSSLError as e:
# FIXME: Is there a better way to differentiate between SSLErrors?
if "read operation timed out" not in str(e):
# SSL errors related to framing/MAC get wrapped and reraised here
raise SSLError(e)
raise ReadTimeoutError(self._pool, None, "Read timed out.")
except (HTTPException, SocketError) as e:
# This includes IncompleteRead.
raise ProtocolError("Connection broken: %r" % e, e)
# If no exception is thrown, we should avoid cleaning up
# unnecessarily.
clean_exit = True
finally:
# If we didn't terminate cleanly, we need to throw away our
# connection.
if not clean_exit:
# The response may not be closed but we're not going to use it
# anymore so close it now to ensure that the connection is
# released back to the pool.
if self._original_response:
self._original_response.close()
# Closing the response may not actually be sufficient to close
# everything, so if we have a hold of the connection close that
# too.
if self._connection:
self._connection.close()
# If we hold the original response but it's closed now, we should
# return the connection back to the pool.
if self._original_response and self._original_response.isclosed():
self.release_conn() | [
"def",
"_error_catcher",
"(",
"self",
")",
":",
"clean_exit",
"=",
"False",
"try",
":",
"try",
":",
"yield",
"except",
"SocketTimeout",
":",
"# FIXME: Ideally we'd like to include the url in the ReadTimeoutError but",
"# there is yet no clean way to get at it from this context.",
"raise",
"ReadTimeoutError",
"(",
"self",
".",
"_pool",
",",
"None",
",",
"\"Read timed out.\"",
")",
"except",
"BaseSSLError",
"as",
"e",
":",
"# FIXME: Is there a better way to differentiate between SSLErrors?",
"if",
"\"read operation timed out\"",
"not",
"in",
"str",
"(",
"e",
")",
":",
"# SSL errors related to framing/MAC get wrapped and reraised here",
"raise",
"SSLError",
"(",
"e",
")",
"raise",
"ReadTimeoutError",
"(",
"self",
".",
"_pool",
",",
"None",
",",
"\"Read timed out.\"",
")",
"except",
"(",
"HTTPException",
",",
"SocketError",
")",
"as",
"e",
":",
"# This includes IncompleteRead.",
"raise",
"ProtocolError",
"(",
"\"Connection broken: %r\"",
"%",
"e",
",",
"e",
")",
"# If no exception is thrown, we should avoid cleaning up",
"# unnecessarily.",
"clean_exit",
"=",
"True",
"finally",
":",
"# If we didn't terminate cleanly, we need to throw away our",
"# connection.",
"if",
"not",
"clean_exit",
":",
"# The response may not be closed but we're not going to use it",
"# anymore so close it now to ensure that the connection is",
"# released back to the pool.",
"if",
"self",
".",
"_original_response",
":",
"self",
".",
"_original_response",
".",
"close",
"(",
")",
"# Closing the response may not actually be sufficient to close",
"# everything, so if we have a hold of the connection close that",
"# too.",
"if",
"self",
".",
"_connection",
":",
"self",
".",
"_connection",
".",
"close",
"(",
")",
"# If we hold the original response but it's closed now, we should",
"# return the connection back to the pool.",
"if",
"self",
".",
"_original_response",
"and",
"self",
".",
"_original_response",
".",
"isclosed",
"(",
")",
":",
"self",
".",
"release_conn",
"(",
")"
] | [
425,
4
] | [
478,
35
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.read | (self, amt=None, decode_content=None, cache_content=False) |
Similar to :meth:`http.client.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
:param cache_content:
If True, will save the returned data such that the same result is
returned despite of the state of the underlying file object. This
is useful if you want the ``.data`` property to continue working
after having ``.read()`` the file object. (Overridden if ``amt`` is
set.)
|
Similar to :meth:`http.client.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``. | def read(self, amt=None, decode_content=None, cache_content=False):
"""
Similar to :meth:`http.client.HTTPResponse.read`, but with two additional
parameters: ``decode_content`` and ``cache_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
:param cache_content:
If True, will save the returned data such that the same result is
returned despite of the state of the underlying file object. This
is useful if you want the ``.data`` property to continue working
after having ``.read()`` the file object. (Overridden if ``amt`` is
set.)
"""
self._init_decoder()
if decode_content is None:
decode_content = self.decode_content
if self._fp is None:
return
flush_decoder = False
fp_closed = getattr(self._fp, "closed", False)
with self._error_catcher():
if amt is None:
# cStringIO doesn't like amt=None
data = self._fp.read() if not fp_closed else b""
flush_decoder = True
else:
cache_content = False
data = self._fp.read(amt) if not fp_closed else b""
if (
amt != 0 and not data
): # Platform-specific: Buggy versions of Python.
# Close the connection when no data is returned
#
# This is redundant to what httplib/http.client _should_
# already do. However, versions of python released before
# December 15, 2012 (http://bugs.python.org/issue16298) do
# not properly close the connection in all cases. There is
# no harm in redundantly calling close.
self._fp.close()
flush_decoder = True
if self.enforce_content_length and self.length_remaining not in (
0,
None,
):
# This is an edge case that httplib failed to cover due
# to concerns of backward compatibility. We're
# addressing it here to make sure IncompleteRead is
# raised during streaming, so all calls with incorrect
# Content-Length are caught.
raise IncompleteRead(self._fp_bytes_read, self.length_remaining)
if data:
self._fp_bytes_read += len(data)
if self.length_remaining is not None:
self.length_remaining -= len(data)
data = self._decode(data, decode_content, flush_decoder)
if cache_content:
self._body = data
return data | [
"def",
"read",
"(",
"self",
",",
"amt",
"=",
"None",
",",
"decode_content",
"=",
"None",
",",
"cache_content",
"=",
"False",
")",
":",
"self",
".",
"_init_decoder",
"(",
")",
"if",
"decode_content",
"is",
"None",
":",
"decode_content",
"=",
"self",
".",
"decode_content",
"if",
"self",
".",
"_fp",
"is",
"None",
":",
"return",
"flush_decoder",
"=",
"False",
"fp_closed",
"=",
"getattr",
"(",
"self",
".",
"_fp",
",",
"\"closed\"",
",",
"False",
")",
"with",
"self",
".",
"_error_catcher",
"(",
")",
":",
"if",
"amt",
"is",
"None",
":",
"# cStringIO doesn't like amt=None",
"data",
"=",
"self",
".",
"_fp",
".",
"read",
"(",
")",
"if",
"not",
"fp_closed",
"else",
"b\"\"",
"flush_decoder",
"=",
"True",
"else",
":",
"cache_content",
"=",
"False",
"data",
"=",
"self",
".",
"_fp",
".",
"read",
"(",
"amt",
")",
"if",
"not",
"fp_closed",
"else",
"b\"\"",
"if",
"(",
"amt",
"!=",
"0",
"and",
"not",
"data",
")",
":",
"# Platform-specific: Buggy versions of Python.",
"# Close the connection when no data is returned",
"#",
"# This is redundant to what httplib/http.client _should_",
"# already do. However, versions of python released before",
"# December 15, 2012 (http://bugs.python.org/issue16298) do",
"# not properly close the connection in all cases. There is",
"# no harm in redundantly calling close.",
"self",
".",
"_fp",
".",
"close",
"(",
")",
"flush_decoder",
"=",
"True",
"if",
"self",
".",
"enforce_content_length",
"and",
"self",
".",
"length_remaining",
"not",
"in",
"(",
"0",
",",
"None",
",",
")",
":",
"# This is an edge case that httplib failed to cover due",
"# to concerns of backward compatibility. We're",
"# addressing it here to make sure IncompleteRead is",
"# raised during streaming, so all calls with incorrect",
"# Content-Length are caught.",
"raise",
"IncompleteRead",
"(",
"self",
".",
"_fp_bytes_read",
",",
"self",
".",
"length_remaining",
")",
"if",
"data",
":",
"self",
".",
"_fp_bytes_read",
"+=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"length_remaining",
"is",
"not",
"None",
":",
"self",
".",
"length_remaining",
"-=",
"len",
"(",
"data",
")",
"data",
"=",
"self",
".",
"_decode",
"(",
"data",
",",
"decode_content",
",",
"flush_decoder",
")",
"if",
"cache_content",
":",
"self",
".",
"_body",
"=",
"data",
"return",
"data"
] | [
480,
4
] | [
552,
19
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.stream | (self, amt=2 ** 16, decode_content=None) |
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may return less. This is particularly
likely when using compressed data. However, the empty string will
never be returned.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
|
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed. | def stream(self, amt=2 ** 16, decode_content=None):
"""
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator will return up to
much data per iteration, but may return less. This is particularly
likely when using compressed data. However, the empty string will
never be returned.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
"""
if self.chunked and self.supports_chunked_reads():
for line in self.read_chunked(amt, decode_content=decode_content):
yield line
else:
while not is_fp_closed(self._fp):
data = self.read(amt=amt, decode_content=decode_content)
if data:
yield data | [
"def",
"stream",
"(",
"self",
",",
"amt",
"=",
"2",
"**",
"16",
",",
"decode_content",
"=",
"None",
")",
":",
"if",
"self",
".",
"chunked",
"and",
"self",
".",
"supports_chunked_reads",
"(",
")",
":",
"for",
"line",
"in",
"self",
".",
"read_chunked",
"(",
"amt",
",",
"decode_content",
"=",
"decode_content",
")",
":",
"yield",
"line",
"else",
":",
"while",
"not",
"is_fp_closed",
"(",
"self",
".",
"_fp",
")",
":",
"data",
"=",
"self",
".",
"read",
"(",
"amt",
"=",
"amt",
",",
"decode_content",
"=",
"decode_content",
")",
"if",
"data",
":",
"yield",
"data"
] | [
554,
4
] | [
578,
30
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.from_httplib | (ResponseCls, r, **response_kw) |
Given an :class:`http.client.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.
|
Given an :class:`http.client.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object. | def from_httplib(ResponseCls, r, **response_kw):
"""
Given an :class:`http.client.HTTPResponse` instance ``r``, return a
corresponding :class:`urllib3.response.HTTPResponse` object.
Remaining parameters are passed to the HTTPResponse constructor, along
with ``original_response=r``.
"""
headers = r.msg
if not isinstance(headers, HTTPHeaderDict):
if six.PY2:
# Python 2.7
headers = HTTPHeaderDict.from_httplib(headers)
else:
headers = HTTPHeaderDict(headers.items())
# HTTPResponse objects in Python 3 don't have a .strict attribute
strict = getattr(r, "strict", 0)
resp = ResponseCls(
body=r,
headers=headers,
status=r.status,
version=r.version,
reason=r.reason,
strict=strict,
original_response=r,
**response_kw
)
return resp | [
"def",
"from_httplib",
"(",
"ResponseCls",
",",
"r",
",",
"*",
"*",
"response_kw",
")",
":",
"headers",
"=",
"r",
".",
"msg",
"if",
"not",
"isinstance",
"(",
"headers",
",",
"HTTPHeaderDict",
")",
":",
"if",
"six",
".",
"PY2",
":",
"# Python 2.7",
"headers",
"=",
"HTTPHeaderDict",
".",
"from_httplib",
"(",
"headers",
")",
"else",
":",
"headers",
"=",
"HTTPHeaderDict",
"(",
"headers",
".",
"items",
"(",
")",
")",
"# HTTPResponse objects in Python 3 don't have a .strict attribute",
"strict",
"=",
"getattr",
"(",
"r",
",",
"\"strict\"",
",",
"0",
")",
"resp",
"=",
"ResponseCls",
"(",
"body",
"=",
"r",
",",
"headers",
"=",
"headers",
",",
"status",
"=",
"r",
".",
"status",
",",
"version",
"=",
"r",
".",
"version",
",",
"reason",
"=",
"r",
".",
"reason",
",",
"strict",
"=",
"strict",
",",
"original_response",
"=",
"r",
",",
"*",
"*",
"response_kw",
")",
"return",
"resp"
] | [
581,
4
] | [
610,
19
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.supports_chunked_reads | (self) |
Checks if the underlying file-like object looks like a
:class:`http.client.HTTPResponse` object. We do this by testing for
the fp attribute. If it is present we assume it returns raw chunks as
processed by read_chunked().
|
Checks if the underlying file-like object looks like a
:class:`http.client.HTTPResponse` object. We do this by testing for
the fp attribute. If it is present we assume it returns raw chunks as
processed by read_chunked().
| def supports_chunked_reads(self):
"""
Checks if the underlying file-like object looks like a
:class:`http.client.HTTPResponse` object. We do this by testing for
the fp attribute. If it is present we assume it returns raw chunks as
processed by read_chunked().
"""
return hasattr(self._fp, "fp") | [
"def",
"supports_chunked_reads",
"(",
"self",
")",
":",
"return",
"hasattr",
"(",
"self",
".",
"_fp",
",",
"\"fp\"",
")"
] | [
679,
4
] | [
686,
38
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.read_chunked | (self, amt=None, decode_content=None) |
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
|
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``. | def read_chunked(self, amt=None, decode_content=None):
"""
Similar to :meth:`HTTPResponse.read`, but with an additional
parameter: ``decode_content``.
:param amt:
How much of the content to read. If specified, caching is skipped
because it doesn't make sense to cache partial content as the full
response.
:param decode_content:
If True, will attempt to decode the body based on the
'content-encoding' header.
"""
self._init_decoder()
# FIXME: Rewrite this method and make it a class with a better structured logic.
if not self.chunked:
raise ResponseNotChunked(
"Response is not chunked. "
"Header 'transfer-encoding: chunked' is missing."
)
if not self.supports_chunked_reads():
raise BodyNotHttplibCompatible(
"Body should be http.client.HTTPResponse like. "
"It should have have an fp attribute which returns raw chunks."
)
with self._error_catcher():
# Don't bother reading the body of a HEAD request.
if self._original_response and is_response_to_head(self._original_response):
self._original_response.close()
return
# If a response is already read and closed
# then return immediately.
if self._fp.fp is None:
return
while True:
self._update_chunk_length()
if self.chunk_left == 0:
break
chunk = self._handle_chunk(amt)
decoded = self._decode(
chunk, decode_content=decode_content, flush_decoder=False
)
if decoded:
yield decoded
if decode_content:
# On CPython and PyPy, we should never need to flush the
# decoder. However, on Jython we *might* need to, so
# lets defensively do it anyway.
decoded = self._flush_decoder()
if decoded: # Platform-specific: Jython.
yield decoded
# Chunk content ends with \r\n: discard it.
while True:
line = self._fp.fp.readline()
if not line:
# Some sites may not end with '\r\n'.
break
if line == b"\r\n":
break
# We read everything; close the "file".
if self._original_response:
self._original_response.close() | [
"def",
"read_chunked",
"(",
"self",
",",
"amt",
"=",
"None",
",",
"decode_content",
"=",
"None",
")",
":",
"self",
".",
"_init_decoder",
"(",
")",
"# FIXME: Rewrite this method and make it a class with a better structured logic.",
"if",
"not",
"self",
".",
"chunked",
":",
"raise",
"ResponseNotChunked",
"(",
"\"Response is not chunked. \"",
"\"Header 'transfer-encoding: chunked' is missing.\"",
")",
"if",
"not",
"self",
".",
"supports_chunked_reads",
"(",
")",
":",
"raise",
"BodyNotHttplibCompatible",
"(",
"\"Body should be http.client.HTTPResponse like. \"",
"\"It should have have an fp attribute which returns raw chunks.\"",
")",
"with",
"self",
".",
"_error_catcher",
"(",
")",
":",
"# Don't bother reading the body of a HEAD request.",
"if",
"self",
".",
"_original_response",
"and",
"is_response_to_head",
"(",
"self",
".",
"_original_response",
")",
":",
"self",
".",
"_original_response",
".",
"close",
"(",
")",
"return",
"# If a response is already read and closed",
"# then return immediately.",
"if",
"self",
".",
"_fp",
".",
"fp",
"is",
"None",
":",
"return",
"while",
"True",
":",
"self",
".",
"_update_chunk_length",
"(",
")",
"if",
"self",
".",
"chunk_left",
"==",
"0",
":",
"break",
"chunk",
"=",
"self",
".",
"_handle_chunk",
"(",
"amt",
")",
"decoded",
"=",
"self",
".",
"_decode",
"(",
"chunk",
",",
"decode_content",
"=",
"decode_content",
",",
"flush_decoder",
"=",
"False",
")",
"if",
"decoded",
":",
"yield",
"decoded",
"if",
"decode_content",
":",
"# On CPython and PyPy, we should never need to flush the",
"# decoder. However, on Jython we *might* need to, so",
"# lets defensively do it anyway.",
"decoded",
"=",
"self",
".",
"_flush_decoder",
"(",
")",
"if",
"decoded",
":",
"# Platform-specific: Jython.",
"yield",
"decoded",
"# Chunk content ends with \\r\\n: discard it.",
"while",
"True",
":",
"line",
"=",
"self",
".",
"_fp",
".",
"fp",
".",
"readline",
"(",
")",
"if",
"not",
"line",
":",
"# Some sites may not end with '\\r\\n'.",
"break",
"if",
"line",
"==",
"b\"\\r\\n\"",
":",
"break",
"# We read everything; close the \"file\".",
"if",
"self",
".",
"_original_response",
":",
"self",
".",
"_original_response",
".",
"close",
"(",
")"
] | [
724,
4
] | [
792,
47
] | python | en | ['en', 'error', 'th'] | False |
HTTPResponse.geturl | (self) |
Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location.
|
Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location.
| def geturl(self):
"""
Returns the URL that was the source of this response.
If the request that generated this response redirected, this method
will return the final redirect location.
"""
if self.retries is not None and len(self.retries.history):
return self.retries.history[-1].redirect_location
else:
return self._request_url | [
"def",
"geturl",
"(",
"self",
")",
":",
"if",
"self",
".",
"retries",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"retries",
".",
"history",
")",
":",
"return",
"self",
".",
"retries",
".",
"history",
"[",
"-",
"1",
"]",
".",
"redirect_location",
"else",
":",
"return",
"self",
".",
"_request_url"
] | [
794,
4
] | [
803,
36
] | python | en | ['en', 'error', 'th'] | False |
match_to_datetime | (match: "Match") | Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
Raises ValueError if the match does not correspond to a valid date
or datetime.
| Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`. | def match_to_datetime(match: "Match") -> Union[datetime, date]:
"""Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
Raises ValueError if the match does not correspond to a valid date
or datetime.
"""
(
year_str,
month_str,
day_str,
hour_str,
minute_str,
sec_str,
micros_str,
zulu_time,
offset_dir_str,
offset_hour_str,
offset_minute_str,
) = match.groups()
year, month, day = int(year_str), int(month_str), int(day_str)
if hour_str is None:
return date(year, month, day)
hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)
micros = int(micros_str[1:].ljust(6, "0")[:6]) if micros_str else 0
if offset_dir_str:
offset_dir = 1 if offset_dir_str == "+" else -1
tz: Optional[tzinfo] = timezone(
timedelta(
hours=offset_dir * int(offset_hour_str),
minutes=offset_dir * int(offset_minute_str),
)
)
elif zulu_time:
tz = timezone.utc
else: # local date-time
tz = None
return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz) | [
"def",
"match_to_datetime",
"(",
"match",
":",
"\"Match\"",
")",
"->",
"Union",
"[",
"datetime",
",",
"date",
"]",
":",
"(",
"year_str",
",",
"month_str",
",",
"day_str",
",",
"hour_str",
",",
"minute_str",
",",
"sec_str",
",",
"micros_str",
",",
"zulu_time",
",",
"offset_dir_str",
",",
"offset_hour_str",
",",
"offset_minute_str",
",",
")",
"=",
"match",
".",
"groups",
"(",
")",
"year",
",",
"month",
",",
"day",
"=",
"int",
"(",
"year_str",
")",
",",
"int",
"(",
"month_str",
")",
",",
"int",
"(",
"day_str",
")",
"if",
"hour_str",
"is",
"None",
":",
"return",
"date",
"(",
"year",
",",
"month",
",",
"day",
")",
"hour",
",",
"minute",
",",
"sec",
"=",
"int",
"(",
"hour_str",
")",
",",
"int",
"(",
"minute_str",
")",
",",
"int",
"(",
"sec_str",
")",
"micros",
"=",
"int",
"(",
"micros_str",
"[",
"1",
":",
"]",
".",
"ljust",
"(",
"6",
",",
"\"0\"",
")",
"[",
":",
"6",
"]",
")",
"if",
"micros_str",
"else",
"0",
"if",
"offset_dir_str",
":",
"offset_dir",
"=",
"1",
"if",
"offset_dir_str",
"==",
"\"+\"",
"else",
"-",
"1",
"tz",
":",
"Optional",
"[",
"tzinfo",
"]",
"=",
"timezone",
"(",
"timedelta",
"(",
"hours",
"=",
"offset_dir",
"*",
"int",
"(",
"offset_hour_str",
")",
",",
"minutes",
"=",
"offset_dir",
"*",
"int",
"(",
"offset_minute_str",
")",
",",
")",
")",
"elif",
"zulu_time",
":",
"tz",
"=",
"timezone",
".",
"utc",
"else",
":",
"# local date-time",
"tz",
"=",
"None",
"return",
"datetime",
"(",
"year",
",",
"month",
",",
"day",
",",
"hour",
",",
"minute",
",",
"sec",
",",
"micros",
",",
"tzinfo",
"=",
"tz",
")"
] | [
33,
0
] | [
69,
75
] | python | en | ['en', 'en', 'en'] | True |
_xml_escape | (data) | Escape &, <, >, ", ', etc. in a string of data. | Escape &, <, >, ", ', etc. in a string of data. | def _xml_escape(data):
"""Escape &, <, >, ", ', etc. in a string of data."""
# ampersand must be replaced first
from_symbols = '&><"\''
to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split())
for from_,to_ in zip(from_symbols, to_symbols):
data = data.replace(from_, to_)
return data | [
"def",
"_xml_escape",
"(",
"data",
")",
":",
"# ampersand must be replaced first\r",
"from_symbols",
"=",
"'&><\"\\''",
"to_symbols",
"=",
"(",
"'&'",
"+",
"s",
"+",
"';'",
"for",
"s",
"in",
"\"amp gt lt quot apos\"",
".",
"split",
"(",
")",
")",
"for",
"from_",
",",
"to_",
"in",
"zip",
"(",
"from_symbols",
",",
"to_symbols",
")",
":",
"data",
"=",
"data",
".",
"replace",
"(",
"from_",
",",
"to_",
")",
"return",
"data"
] | [
161,
0
] | [
169,
15
] | python | en | ['en', 'en', 'en'] | True |
col | (loc,strg) | Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
| Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
| def col (loc,strg):
"""Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
s = strg
return 1 if 0<loc<len(s) and s[loc-1] == '\n' else loc - s.rfind("\n", 0, loc) | [
"def",
"col",
"(",
"loc",
",",
"strg",
")",
":",
"s",
"=",
"strg",
"return",
"1",
"if",
"0",
"<",
"loc",
"<",
"len",
"(",
"s",
")",
"and",
"s",
"[",
"loc",
"-",
"1",
"]",
"==",
"'\\n'",
"else",
"loc",
"-",
"s",
".",
"rfind",
"(",
"\"\\n\"",
",",
"0",
",",
"loc",
")"
] | [
944,
0
] | [
955,
82
] | python | en | ['en', 'en', 'en'] | True |
lineno | (loc,strg) | Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
| Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
| def lineno(loc,strg):
"""Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
return strg.count("\n",0,loc) + 1 | [
"def",
"lineno",
"(",
"loc",
",",
"strg",
")",
":",
"return",
"strg",
".",
"count",
"(",
"\"\\n\"",
",",
"0",
",",
"loc",
")",
"+",
"1"
] | [
957,
0
] | [
967,
37
] | python | en | ['en', 'en', 'en'] | True |
line | ( loc, strg ) | Returns the line of text containing loc within a string, counting newlines as line separators.
| Returns the line of text containing loc within a string, counting newlines as line separators.
| def line( loc, strg ):
"""Returns the line of text containing loc within a string, counting newlines as line separators.
"""
lastCR = strg.rfind("\n", 0, loc)
nextCR = strg.find("\n", loc)
if nextCR >= 0:
return strg[lastCR+1:nextCR]
else:
return strg[lastCR+1:] | [
"def",
"line",
"(",
"loc",
",",
"strg",
")",
":",
"lastCR",
"=",
"strg",
".",
"rfind",
"(",
"\"\\n\"",
",",
"0",
",",
"loc",
")",
"nextCR",
"=",
"strg",
".",
"find",
"(",
"\"\\n\"",
",",
"loc",
")",
"if",
"nextCR",
">=",
"0",
":",
"return",
"strg",
"[",
"lastCR",
"+",
"1",
":",
"nextCR",
"]",
"else",
":",
"return",
"strg",
"[",
"lastCR",
"+",
"1",
":",
"]"
] | [
969,
0
] | [
977,
30
] | python | en | ['en', 'en', 'en'] | True |
nullDebugAction | (*args) | Do-nothing' debug action, to suppress debugging output during parsing. | Do-nothing' debug action, to suppress debugging output during parsing. | def nullDebugAction(*args):
"""'Do-nothing' debug action, to suppress debugging output during parsing."""
pass | [
"def",
"nullDebugAction",
"(",
"*",
"args",
")",
":",
"pass"
] | [
988,
0
] | [
990,
8
] | python | en | ['en', 'jv', 'en'] | True |
ParseBaseException._from_exception | (cls, pe) |
internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses
|
internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses
| def _from_exception(cls, pe):
"""
internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses
"""
return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement) | [
"def",
"_from_exception",
"(",
"cls",
",",
"pe",
")",
":",
"return",
"cls",
"(",
"pe",
".",
"pstr",
",",
"pe",
".",
"loc",
",",
"pe",
".",
"msg",
",",
"pe",
".",
"parserElement",
")"
] | [
197,
4
] | [
202,
61
] | python | en | ['en', 'ja', 'th'] | False |
ParseBaseException.__getattr__ | ( self, aname ) | supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text
| supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text
| def __getattr__( self, aname ):
"""supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text
"""
if( aname == "lineno" ):
return lineno( self.loc, self.pstr )
elif( aname in ("col", "column") ):
return col( self.loc, self.pstr )
elif( aname == "line" ):
return line( self.loc, self.pstr )
else:
raise AttributeError(aname) | [
"def",
"__getattr__",
"(",
"self",
",",
"aname",
")",
":",
"if",
"(",
"aname",
"==",
"\"lineno\"",
")",
":",
"return",
"lineno",
"(",
"self",
".",
"loc",
",",
"self",
".",
"pstr",
")",
"elif",
"(",
"aname",
"in",
"(",
"\"col\"",
",",
"\"column\"",
")",
")",
":",
"return",
"col",
"(",
"self",
".",
"loc",
",",
"self",
".",
"pstr",
")",
"elif",
"(",
"aname",
"==",
"\"line\"",
")",
":",
"return",
"line",
"(",
"self",
".",
"loc",
",",
"self",
".",
"pstr",
")",
"else",
":",
"raise",
"AttributeError",
"(",
"aname",
")"
] | [
204,
4
] | [
217,
39
] | python | en | ['en', 'en', 'en'] | True |
ParseBaseException.markInputline | ( self, markerString = ">!<" ) | Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
| Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
| def markInputline( self, markerString = ">!<" ):
"""Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
"""
line_str = self.line
line_column = self.column - 1
if markerString:
line_str = "".join((line_str[:line_column],
markerString, line_str[line_column:]))
return line_str.strip() | [
"def",
"markInputline",
"(",
"self",
",",
"markerString",
"=",
"\">!<\"",
")",
":",
"line_str",
"=",
"self",
".",
"line",
"line_column",
"=",
"self",
".",
"column",
"-",
"1",
"if",
"markerString",
":",
"line_str",
"=",
"\"\"",
".",
"join",
"(",
"(",
"line_str",
"[",
":",
"line_column",
"]",
",",
"markerString",
",",
"line_str",
"[",
"line_column",
":",
"]",
")",
")",
"return",
"line_str",
".",
"strip",
"(",
")"
] | [
224,
4
] | [
233,
31
] | python | en | ['en', 'en', 'en'] | True |
ParseResults.haskeys | ( self ) | Since keys() returns an iterator, this method is helpful in bypassing
code that looks for the existence of any defined results names. | Since keys() returns an iterator, this method is helpful in bypassing
code that looks for the existence of any defined results names. | def haskeys( self ):
"""Since keys() returns an iterator, this method is helpful in bypassing
code that looks for the existence of any defined results names."""
return bool(self.__tokdict) | [
"def",
"haskeys",
"(",
"self",
")",
":",
"return",
"bool",
"(",
"self",
".",
"__tokdict",
")"
] | [
482,
4
] | [
485,
35
] | python | en | ['en', 'en', 'en'] | True |
ParseResults.pop | ( self, *args, **kwargs) |
Removes and returns item at specified index (default=C{last}).
Supports both C{list} and C{dict} semantics for C{pop()}. If passed no
argument or an integer argument, it will use C{list} semantics
and pop tokens from the list of parsed tokens. If passed a
non-integer argument (most likely a string), it will use C{dict}
semantics and pop the corresponding value from any defined
results names. A second default return value argument is
supported, just as in C{dict.pop()}.
Example::
def remove_first(tokens):
tokens.pop(0)
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321']
label = Word(alphas)
patt = label("LABEL") + OneOrMore(Word(nums))
print(patt.parseString("AAB 123 321").dump())
# Use pop() in a parse action to remove named result (note that corresponding value is not
# removed from list form of results)
def remove_LABEL(tokens):
tokens.pop("LABEL")
return tokens
patt.addParseAction(remove_LABEL)
print(patt.parseString("AAB 123 321").dump())
prints::
['AAB', '123', '321']
- LABEL: AAB
['AAB', '123', '321']
|
Removes and returns item at specified index (default=C{last}).
Supports both C{list} and C{dict} semantics for C{pop()}. If passed no
argument or an integer argument, it will use C{list} semantics
and pop tokens from the list of parsed tokens. If passed a
non-integer argument (most likely a string), it will use C{dict}
semantics and pop the corresponding value from any defined
results names. A second default return value argument is
supported, just as in C{dict.pop()}.
Example::
def remove_first(tokens):
tokens.pop(0)
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321']
label = Word(alphas)
patt = label("LABEL") + OneOrMore(Word(nums))
print(patt.parseString("AAB 123 321").dump())
# Use pop() in a parse action to remove named result (note that corresponding value is not
# removed from list form of results)
def remove_LABEL(tokens):
tokens.pop("LABEL")
return tokens
patt.addParseAction(remove_LABEL)
print(patt.parseString("AAB 123 321").dump())
prints::
['AAB', '123', '321']
- LABEL: AAB
['AAB', '123', '321']
| def pop( self, *args, **kwargs):
"""
Removes and returns item at specified index (default=C{last}).
Supports both C{list} and C{dict} semantics for C{pop()}. If passed no
argument or an integer argument, it will use C{list} semantics
and pop tokens from the list of parsed tokens. If passed a
non-integer argument (most likely a string), it will use C{dict}
semantics and pop the corresponding value from any defined
results names. A second default return value argument is
supported, just as in C{dict.pop()}.
Example::
def remove_first(tokens):
tokens.pop(0)
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321']
label = Word(alphas)
patt = label("LABEL") + OneOrMore(Word(nums))
print(patt.parseString("AAB 123 321").dump())
# Use pop() in a parse action to remove named result (note that corresponding value is not
# removed from list form of results)
def remove_LABEL(tokens):
tokens.pop("LABEL")
return tokens
patt.addParseAction(remove_LABEL)
print(patt.parseString("AAB 123 321").dump())
prints::
['AAB', '123', '321']
- LABEL: AAB
['AAB', '123', '321']
"""
if not args:
args = [-1]
for k,v in kwargs.items():
if k == 'default':
args = (args[0], v)
else:
raise TypeError("pop() got an unexpected keyword argument '%s'" % k)
if (isinstance(args[0], int) or
len(args) == 1 or
args[0] in self):
index = args[0]
ret = self[index]
del self[index]
return ret
else:
defaultvalue = args[1]
return defaultvalue | [
"def",
"pop",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"args",
"=",
"[",
"-",
"1",
"]",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'default'",
":",
"args",
"=",
"(",
"args",
"[",
"0",
"]",
",",
"v",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"pop() got an unexpected keyword argument '%s'\"",
"%",
"k",
")",
"if",
"(",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"int",
")",
"or",
"len",
"(",
"args",
")",
"==",
"1",
"or",
"args",
"[",
"0",
"]",
"in",
"self",
")",
":",
"index",
"=",
"args",
"[",
"0",
"]",
"ret",
"=",
"self",
"[",
"index",
"]",
"del",
"self",
"[",
"index",
"]",
"return",
"ret",
"else",
":",
"defaultvalue",
"=",
"args",
"[",
"1",
"]",
"return",
"defaultvalue"
] | [
487,
4
] | [
537,
31
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.get | (self, key, defaultValue=None) |
Returns named result matching the given key, or if there is no
such name, then returns the given C{defaultValue} or C{None} if no
C{defaultValue} is specified.
Similar to C{dict.get()}.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString("1999/12/31")
print(result.get("year")) # -> '1999'
print(result.get("hour", "not specified")) # -> 'not specified'
print(result.get("hour")) # -> None
|
Returns named result matching the given key, or if there is no
such name, then returns the given C{defaultValue} or C{None} if no
C{defaultValue} is specified.
Similar to C{dict.get()}.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString("1999/12/31")
print(result.get("year")) # -> '1999'
print(result.get("hour", "not specified")) # -> 'not specified'
print(result.get("hour")) # -> None
| def get(self, key, defaultValue=None):
"""
Returns named result matching the given key, or if there is no
such name, then returns the given C{defaultValue} or C{None} if no
C{defaultValue} is specified.
Similar to C{dict.get()}.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString("1999/12/31")
print(result.get("year")) # -> '1999'
print(result.get("hour", "not specified")) # -> 'not specified'
print(result.get("hour")) # -> None
"""
if key in self:
return self[key]
else:
return defaultValue | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"defaultValue",
"=",
"None",
")",
":",
"if",
"key",
"in",
"self",
":",
"return",
"self",
"[",
"key",
"]",
"else",
":",
"return",
"defaultValue"
] | [
539,
4
] | [
559,
31
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.insert | ( self, index, insStr ) |
Inserts new element at location index in the list of parsed tokens.
Similar to C{list.insert()}.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to insert the parse location in the front of the parsed results
def insert_locn(locn, tokens):
tokens.insert(0, locn)
print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
|
Inserts new element at location index in the list of parsed tokens.
Similar to C{list.insert()}.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to insert the parse location in the front of the parsed results
def insert_locn(locn, tokens):
tokens.insert(0, locn)
print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
| def insert( self, index, insStr ):
"""
Inserts new element at location index in the list of parsed tokens.
Similar to C{list.insert()}.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to insert the parse location in the front of the parsed results
def insert_locn(locn, tokens):
tokens.insert(0, locn)
print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
"""
self.__toklist.insert(index, insStr)
# fixup indices in token dictionary
for name,occurrences in self.__tokdict.items():
for k, (value, position) in enumerate(occurrences):
occurrences[k] = _ParseResultsWithOffset(value, position + (position > index)) | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"insStr",
")",
":",
"self",
".",
"__toklist",
".",
"insert",
"(",
"index",
",",
"insStr",
")",
"# fixup indices in token dictionary\r",
"for",
"name",
",",
"occurrences",
"in",
"self",
".",
"__tokdict",
".",
"items",
"(",
")",
":",
"for",
"k",
",",
"(",
"value",
",",
"position",
")",
"in",
"enumerate",
"(",
"occurrences",
")",
":",
"occurrences",
"[",
"k",
"]",
"=",
"_ParseResultsWithOffset",
"(",
"value",
",",
"position",
"+",
"(",
"position",
">",
"index",
")",
")"
] | [
561,
4
] | [
579,
94
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.append | ( self, item ) |
Add single element to end of ParseResults list of elements.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to compute the sum of the parsed integers, and add it to the end
def append_sum(tokens):
tokens.append(sum(map(int, tokens)))
print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
|
Add single element to end of ParseResults list of elements.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to compute the sum of the parsed integers, and add it to the end
def append_sum(tokens):
tokens.append(sum(map(int, tokens)))
print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
| def append( self, item ):
"""
Add single element to end of ParseResults list of elements.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to compute the sum of the parsed integers, and add it to the end
def append_sum(tokens):
tokens.append(sum(map(int, tokens)))
print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
"""
self.__toklist.append(item) | [
"def",
"append",
"(",
"self",
",",
"item",
")",
":",
"self",
".",
"__toklist",
".",
"append",
"(",
"item",
")"
] | [
581,
4
] | [
593,
35
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.extend | ( self, itemseq ) |
Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] for t in tokens]))
return ''.join(tokens)
print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
|
Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] for t in tokens]))
return ''.join(tokens)
print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
| def extend( self, itemseq ):
"""
Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] for t in tokens]))
return ''.join(tokens)
print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
"""
if isinstance(itemseq, ParseResults):
self += itemseq
else:
self.__toklist.extend(itemseq) | [
"def",
"extend",
"(",
"self",
",",
"itemseq",
")",
":",
"if",
"isinstance",
"(",
"itemseq",
",",
"ParseResults",
")",
":",
"self",
"+=",
"itemseq",
"else",
":",
"self",
".",
"__toklist",
".",
"extend",
"(",
"itemseq",
")"
] | [
595,
4
] | [
611,
42
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.clear | ( self ) |
Clear all elements and results names.
|
Clear all elements and results names.
| def clear( self ):
"""
Clear all elements and results names.
"""
del self.__toklist[:]
self.__tokdict.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"del",
"self",
".",
"__toklist",
"[",
":",
"]",
"self",
".",
"__tokdict",
".",
"clear",
"(",
")"
] | [
613,
4
] | [
618,
30
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.asList | ( self ) |
Returns the parse results as a nested list of matching tokens, all converted to strings.
Example::
patt = OneOrMore(Word(alphas))
result = patt.parseString("sldkj lsdkj sldkj")
# even though the result prints in string-like form, it is actually a pyparsing ParseResults
print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
# Use asList() to create an actual list
result_list = result.asList()
print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
|
Returns the parse results as a nested list of matching tokens, all converted to strings.
Example::
patt = OneOrMore(Word(alphas))
result = patt.parseString("sldkj lsdkj sldkj")
# even though the result prints in string-like form, it is actually a pyparsing ParseResults
print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
# Use asList() to create an actual list
result_list = result.asList()
print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
| def asList( self ):
"""
Returns the parse results as a nested list of matching tokens, all converted to strings.
Example::
patt = OneOrMore(Word(alphas))
result = patt.parseString("sldkj lsdkj sldkj")
# even though the result prints in string-like form, it is actually a pyparsing ParseResults
print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
# Use asList() to create an actual list
result_list = result.asList()
print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
"""
return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist] | [
"def",
"asList",
"(",
"self",
")",
":",
"return",
"[",
"res",
".",
"asList",
"(",
")",
"if",
"isinstance",
"(",
"res",
",",
"ParseResults",
")",
"else",
"res",
"for",
"res",
"in",
"self",
".",
"__toklist",
"]"
] | [
680,
4
] | [
694,
96
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.asDict | ( self ) |
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
result_dict = result.asDict()
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
# even though a ParseResults supports dict-like access, sometime you just need to have a dict
import json
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
|
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
result_dict = result.asDict()
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
# even though a ParseResults supports dict-like access, sometime you just need to have a dict
import json
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
| def asDict( self ):
"""
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
result_dict = result.asDict()
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
# even though a ParseResults supports dict-like access, sometime you just need to have a dict
import json
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
"""
if PY_3:
item_fn = self.items
else:
item_fn = self.iteritems
def toItem(obj):
if isinstance(obj, ParseResults):
if obj.haskeys():
return obj.asDict()
else:
return [toItem(v) for v in obj]
else:
return obj
return dict((k,toItem(v)) for k,v in item_fn()) | [
"def",
"asDict",
"(",
"self",
")",
":",
"if",
"PY_3",
":",
"item_fn",
"=",
"self",
".",
"items",
"else",
":",
"item_fn",
"=",
"self",
".",
"iteritems",
"def",
"toItem",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ParseResults",
")",
":",
"if",
"obj",
".",
"haskeys",
"(",
")",
":",
"return",
"obj",
".",
"asDict",
"(",
")",
"else",
":",
"return",
"[",
"toItem",
"(",
"v",
")",
"for",
"v",
"in",
"obj",
"]",
"else",
":",
"return",
"obj",
"return",
"dict",
"(",
"(",
"k",
",",
"toItem",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"item_fn",
"(",
")",
")"
] | [
696,
4
] | [
729,
55
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.copy | ( self ) |
Returns a new copy of a C{ParseResults} object.
|
Returns a new copy of a C{ParseResults} object.
| def copy( self ):
"""
Returns a new copy of a C{ParseResults} object.
"""
ret = ParseResults( self.__toklist )
ret.__tokdict = self.__tokdict.copy()
ret.__parent = self.__parent
ret.__accumNames.update( self.__accumNames )
ret.__name = self.__name
return ret | [
"def",
"copy",
"(",
"self",
")",
":",
"ret",
"=",
"ParseResults",
"(",
"self",
".",
"__toklist",
")",
"ret",
".",
"__tokdict",
"=",
"self",
".",
"__tokdict",
".",
"copy",
"(",
")",
"ret",
".",
"__parent",
"=",
"self",
".",
"__parent",
"ret",
".",
"__accumNames",
".",
"update",
"(",
"self",
".",
"__accumNames",
")",
"ret",
".",
"__name",
"=",
"self",
".",
"__name",
"return",
"ret"
] | [
731,
4
] | [
740,
18
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.asXML | ( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ) |
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
|
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
| def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
"""
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
"""
nl = "\n"
out = []
namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items()
for v in vlist)
nextLevelIndent = indent + " "
# collapse out indents if formatting is not desired
if not formatted:
indent = ""
nextLevelIndent = ""
nl = ""
selfTag = None
if doctag is not None:
selfTag = doctag
else:
if self.__name:
selfTag = self.__name
if not selfTag:
if namedItemsOnly:
return ""
else:
selfTag = "ITEM"
out += [ nl, indent, "<", selfTag, ">" ]
for i,res in enumerate(self.__toklist):
if isinstance(res,ParseResults):
if i in namedItems:
out += [ res.asXML(namedItems[i],
namedItemsOnly and doctag is None,
nextLevelIndent,
formatted)]
else:
out += [ res.asXML(None,
namedItemsOnly and doctag is None,
nextLevelIndent,
formatted)]
else:
# individual token, see if there is a name for it
resTag = None
if i in namedItems:
resTag = namedItems[i]
if not resTag:
if namedItemsOnly:
continue
else:
resTag = "ITEM"
xmlBodyText = _xml_escape(_ustr(res))
out += [ nl, nextLevelIndent, "<", resTag, ">",
xmlBodyText,
"</", resTag, ">" ]
out += [ nl, indent, "</", selfTag, ">" ]
return "".join(out) | [
"def",
"asXML",
"(",
"self",
",",
"doctag",
"=",
"None",
",",
"namedItemsOnly",
"=",
"False",
",",
"indent",
"=",
"\"\"",
",",
"formatted",
"=",
"True",
")",
":",
"nl",
"=",
"\"\\n\"",
"out",
"=",
"[",
"]",
"namedItems",
"=",
"dict",
"(",
"(",
"v",
"[",
"1",
"]",
",",
"k",
")",
"for",
"(",
"k",
",",
"vlist",
")",
"in",
"self",
".",
"__tokdict",
".",
"items",
"(",
")",
"for",
"v",
"in",
"vlist",
")",
"nextLevelIndent",
"=",
"indent",
"+",
"\" \"",
"# collapse out indents if formatting is not desired\r",
"if",
"not",
"formatted",
":",
"indent",
"=",
"\"\"",
"nextLevelIndent",
"=",
"\"\"",
"nl",
"=",
"\"\"",
"selfTag",
"=",
"None",
"if",
"doctag",
"is",
"not",
"None",
":",
"selfTag",
"=",
"doctag",
"else",
":",
"if",
"self",
".",
"__name",
":",
"selfTag",
"=",
"self",
".",
"__name",
"if",
"not",
"selfTag",
":",
"if",
"namedItemsOnly",
":",
"return",
"\"\"",
"else",
":",
"selfTag",
"=",
"\"ITEM\"",
"out",
"+=",
"[",
"nl",
",",
"indent",
",",
"\"<\"",
",",
"selfTag",
",",
"\">\"",
"]",
"for",
"i",
",",
"res",
"in",
"enumerate",
"(",
"self",
".",
"__toklist",
")",
":",
"if",
"isinstance",
"(",
"res",
",",
"ParseResults",
")",
":",
"if",
"i",
"in",
"namedItems",
":",
"out",
"+=",
"[",
"res",
".",
"asXML",
"(",
"namedItems",
"[",
"i",
"]",
",",
"namedItemsOnly",
"and",
"doctag",
"is",
"None",
",",
"nextLevelIndent",
",",
"formatted",
")",
"]",
"else",
":",
"out",
"+=",
"[",
"res",
".",
"asXML",
"(",
"None",
",",
"namedItemsOnly",
"and",
"doctag",
"is",
"None",
",",
"nextLevelIndent",
",",
"formatted",
")",
"]",
"else",
":",
"# individual token, see if there is a name for it\r",
"resTag",
"=",
"None",
"if",
"i",
"in",
"namedItems",
":",
"resTag",
"=",
"namedItems",
"[",
"i",
"]",
"if",
"not",
"resTag",
":",
"if",
"namedItemsOnly",
":",
"continue",
"else",
":",
"resTag",
"=",
"\"ITEM\"",
"xmlBodyText",
"=",
"_xml_escape",
"(",
"_ustr",
"(",
"res",
")",
")",
"out",
"+=",
"[",
"nl",
",",
"nextLevelIndent",
",",
"\"<\"",
",",
"resTag",
",",
"\">\"",
",",
"xmlBodyText",
",",
"\"</\"",
",",
"resTag",
",",
"\">\"",
"]",
"out",
"+=",
"[",
"nl",
",",
"indent",
",",
"\"</\"",
",",
"selfTag",
",",
"\">\"",
"]",
"return",
"\"\"",
".",
"join",
"(",
"out",
")"
] | [
742,
4
] | [
801,
27
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.getName | (self) | r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B
| r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B
| def getName(self):
r"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B
"""
if self.__name:
return self.__name
elif self.__parent:
par = self.__parent()
if par:
return par.__lookup(self)
else:
return None
elif (len(self) == 1 and
len(self.__tokdict) == 1 and
next(iter(self.__tokdict.values()))[0][1] in (0,-1)):
return next(iter(self.__tokdict.keys()))
else:
return None | [
"def",
"getName",
"(",
"self",
")",
":",
"if",
"self",
".",
"__name",
":",
"return",
"self",
".",
"__name",
"elif",
"self",
".",
"__parent",
":",
"par",
"=",
"self",
".",
"__parent",
"(",
")",
"if",
"par",
":",
"return",
"par",
".",
"__lookup",
"(",
"self",
")",
"else",
":",
"return",
"None",
"elif",
"(",
"len",
"(",
"self",
")",
"==",
"1",
"and",
"len",
"(",
"self",
".",
"__tokdict",
")",
"==",
"1",
"and",
"next",
"(",
"iter",
"(",
"self",
".",
"__tokdict",
".",
"values",
"(",
")",
")",
")",
"[",
"0",
"]",
"[",
"1",
"]",
"in",
"(",
"0",
",",
"-",
"1",
")",
")",
":",
"return",
"next",
"(",
"iter",
"(",
"self",
".",
"__tokdict",
".",
"keys",
"(",
")",
")",
")",
"else",
":",
"return",
"None"
] | [
810,
4
] | [
845,
23
] | python | cy | ['en', 'cy', 'hi'] | False |
ParseResults.dump | (self, indent='', depth=0, full=True) |
Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(result.dump())
prints::
['12', '/', '31', '/', '1999']
- day: 1999
- month: 31
- year: 12
|
Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(result.dump())
prints::
['12', '/', '31', '/', '1999']
- day: 1999
- month: 31
- year: 12
| def dump(self, indent='', depth=0, full=True):
"""
Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(result.dump())
prints::
['12', '/', '31', '/', '1999']
- day: 1999
- month: 31
- year: 12
"""
out = []
NL = '\n'
out.append( indent+_ustr(self.asList()) )
if full:
if self.haskeys():
items = sorted((str(k), v) for k,v in self.items())
for k,v in items:
if out:
out.append(NL)
out.append( "%s%s- %s: " % (indent,(' '*depth), k) )
if isinstance(v,ParseResults):
if v:
out.append( v.dump(indent,depth+1) )
else:
out.append(_ustr(v))
else:
out.append(repr(v))
elif any(isinstance(vv,ParseResults) for vv in self):
v = self
for i,vv in enumerate(v):
if isinstance(vv,ParseResults):
out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),vv.dump(indent,depth+1) ))
else:
out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),_ustr(vv)))
return "".join(out) | [
"def",
"dump",
"(",
"self",
",",
"indent",
"=",
"''",
",",
"depth",
"=",
"0",
",",
"full",
"=",
"True",
")",
":",
"out",
"=",
"[",
"]",
"NL",
"=",
"'\\n'",
"out",
".",
"append",
"(",
"indent",
"+",
"_ustr",
"(",
"self",
".",
"asList",
"(",
")",
")",
")",
"if",
"full",
":",
"if",
"self",
".",
"haskeys",
"(",
")",
":",
"items",
"=",
"sorted",
"(",
"(",
"str",
"(",
"k",
")",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"items",
"(",
")",
")",
"for",
"k",
",",
"v",
"in",
"items",
":",
"if",
"out",
":",
"out",
".",
"append",
"(",
"NL",
")",
"out",
".",
"append",
"(",
"\"%s%s- %s: \"",
"%",
"(",
"indent",
",",
"(",
"' '",
"*",
"depth",
")",
",",
"k",
")",
")",
"if",
"isinstance",
"(",
"v",
",",
"ParseResults",
")",
":",
"if",
"v",
":",
"out",
".",
"append",
"(",
"v",
".",
"dump",
"(",
"indent",
",",
"depth",
"+",
"1",
")",
")",
"else",
":",
"out",
".",
"append",
"(",
"_ustr",
"(",
"v",
")",
")",
"else",
":",
"out",
".",
"append",
"(",
"repr",
"(",
"v",
")",
")",
"elif",
"any",
"(",
"isinstance",
"(",
"vv",
",",
"ParseResults",
")",
"for",
"vv",
"in",
"self",
")",
":",
"v",
"=",
"self",
"for",
"i",
",",
"vv",
"in",
"enumerate",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"vv",
",",
"ParseResults",
")",
":",
"out",
".",
"append",
"(",
"\"\\n%s%s[%d]:\\n%s%s%s\"",
"%",
"(",
"indent",
",",
"(",
"' '",
"*",
"(",
"depth",
")",
")",
",",
"i",
",",
"indent",
",",
"(",
"' '",
"*",
"(",
"depth",
"+",
"1",
")",
")",
",",
"vv",
".",
"dump",
"(",
"indent",
",",
"depth",
"+",
"1",
")",
")",
")",
"else",
":",
"out",
".",
"append",
"(",
"\"\\n%s%s[%d]:\\n%s%s%s\"",
"%",
"(",
"indent",
",",
"(",
"' '",
"*",
"(",
"depth",
")",
")",
",",
"i",
",",
"indent",
",",
"(",
"' '",
"*",
"(",
"depth",
"+",
"1",
")",
")",
",",
"_ustr",
"(",
"vv",
")",
")",
")",
"return",
"\"\"",
".",
"join",
"(",
"out",
")"
] | [
847,
4
] | [
890,
27
] | python | en | ['en', 'ja', 'th'] | False |
ParseResults.pprint | (self, *args, **kwargs) |
Pretty-printer for parsed results as a list, using the C{pprint} module.
Accepts additional positional or keyword args as defined for the
C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})
Example::
ident = Word(alphas, alphanums)
num = Word(nums)
func = Forward()
term = ident | num | Group('(' + func + ')')
func <<= ident + Group(Optional(delimitedList(term)))
result = func.parseString("fna a,b,(fnb c,d,200),100")
result.pprint(width=40)
prints::
['fna',
['a',
'b',
['(', 'fnb', ['c', 'd', '200'], ')'],
'100']]
|
Pretty-printer for parsed results as a list, using the C{pprint} module.
Accepts additional positional or keyword args as defined for the
C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})
Example::
ident = Word(alphas, alphanums)
num = Word(nums)
func = Forward()
term = ident | num | Group('(' + func + ')')
func <<= ident + Group(Optional(delimitedList(term)))
result = func.parseString("fna a,b,(fnb c,d,200),100")
result.pprint(width=40)
prints::
['fna',
['a',
'b',
['(', 'fnb', ['c', 'd', '200'], ')'],
'100']]
| def pprint(self, *args, **kwargs):
"""
Pretty-printer for parsed results as a list, using the C{pprint} module.
Accepts additional positional or keyword args as defined for the
C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})
Example::
ident = Word(alphas, alphanums)
num = Word(nums)
func = Forward()
term = ident | num | Group('(' + func + ')')
func <<= ident + Group(Optional(delimitedList(term)))
result = func.parseString("fna a,b,(fnb c,d,200),100")
result.pprint(width=40)
prints::
['fna',
['a',
'b',
['(', 'fnb', ['c', 'd', '200'], ')'],
'100']]
"""
pprint.pprint(self.asList(), *args, **kwargs) | [
"def",
"pprint",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"pprint",
".",
"pprint",
"(",
"self",
".",
"asList",
"(",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
892,
4
] | [
913,
53
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.setDefaultWhitespaceChars | ( chars ) | r"""
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
| r"""
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
| def setDefaultWhitespaceChars( chars ):
r"""
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
"""
ParserElement.DEFAULT_WHITE_CHARS = chars | [
"def",
"setDefaultWhitespaceChars",
"(",
"chars",
")",
":",
"ParserElement",
".",
"DEFAULT_WHITE_CHARS",
"=",
"chars"
] | [
1085,
4
] | [
1097,
49
] | python | cy | ['en', 'cy', 'hi'] | False |
ParserElement.inlineLiteralsUsing | (cls) |
Set class to be used for inclusion of string literals into a parser.
Example::
# default literal class used is Literal
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# change to Suppress
ParserElement.inlineLiteralsUsing(Suppress)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '12', '31']
|
Set class to be used for inclusion of string literals into a parser.
Example::
# default literal class used is Literal
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# change to Suppress
ParserElement.inlineLiteralsUsing(Suppress)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '12', '31']
| def inlineLiteralsUsing(cls):
"""
Set class to be used for inclusion of string literals into a parser.
Example::
# default literal class used is Literal
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# change to Suppress
ParserElement.inlineLiteralsUsing(Suppress)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '12', '31']
"""
ParserElement._literalStringClass = cls | [
"def",
"inlineLiteralsUsing",
"(",
"cls",
")",
":",
"ParserElement",
".",
"_literalStringClass",
"=",
"cls"
] | [
1100,
4
] | [
1118,
47
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.copy | ( self ) |
Make a copy of this C{ParserElement}. Useful for defining different parse actions
for the same parsing pattern, using copies of the original parse element.
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K")
integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M"))
prints::
[5120, 100, 655360, 268435456]
Equivalent form of C{expr.copy()} is just C{expr()}::
integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
|
Make a copy of this C{ParserElement}. Useful for defining different parse actions
for the same parsing pattern, using copies of the original parse element.
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K")
integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M"))
prints::
[5120, 100, 655360, 268435456]
Equivalent form of C{expr.copy()} is just C{expr()}::
integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
| def copy( self ):
"""
Make a copy of this C{ParserElement}. Useful for defining different parse actions
for the same parsing pattern, using copies of the original parse element.
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K")
integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M"))
prints::
[5120, 100, 655360, 268435456]
Equivalent form of C{expr.copy()} is just C{expr()}::
integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
"""
cpy = copy.copy( self )
cpy.parseAction = self.parseAction[:]
cpy.ignoreExprs = self.ignoreExprs[:]
if self.copyDefaultWhiteChars:
cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
return cpy | [
"def",
"copy",
"(",
"self",
")",
":",
"cpy",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"cpy",
".",
"parseAction",
"=",
"self",
".",
"parseAction",
"[",
":",
"]",
"cpy",
".",
"ignoreExprs",
"=",
"self",
".",
"ignoreExprs",
"[",
":",
"]",
"if",
"self",
".",
"copyDefaultWhiteChars",
":",
"cpy",
".",
"whiteChars",
"=",
"ParserElement",
".",
"DEFAULT_WHITE_CHARS",
"return",
"cpy"
] | [
1143,
4
] | [
1164,
18
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.setName | ( self, name ) |
Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
|
Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
| def setName( self, name ):
"""
Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
"""
self.name = name
self.errmsg = "Expected " + self.name
if hasattr(self,"exception"):
self.exception.msg = self.errmsg
return self | [
"def",
"setName",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"errmsg",
"=",
"\"Expected \"",
"+",
"self",
".",
"name",
"if",
"hasattr",
"(",
"self",
",",
"\"exception\"",
")",
":",
"self",
".",
"exception",
".",
"msg",
"=",
"self",
".",
"errmsg",
"return",
"self"
] | [
1166,
4
] | [
1178,
19
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.setResultsName | ( self, name, listAllMatches=False ) |
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original C{ParserElement} object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
You can also set results names using the abbreviated syntax,
C{expr("name")} in place of C{expr.setResultsName("name")} -
see L{I{__call__}<__call__>}.
Example::
date_str = (integer.setResultsName("year") + '/'
+ integer.setResultsName("month") + '/'
+ integer.setResultsName("day"))
# equivalent form:
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
|
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original C{ParserElement} object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
You can also set results names using the abbreviated syntax,
C{expr("name")} in place of C{expr.setResultsName("name")} -
see L{I{__call__}<__call__>}.
Example::
date_str = (integer.setResultsName("year") + '/'
+ integer.setResultsName("month") + '/'
+ integer.setResultsName("day"))
# equivalent form:
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
| def setResultsName( self, name, listAllMatches=False ):
"""
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original C{ParserElement} object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
You can also set results names using the abbreviated syntax,
C{expr("name")} in place of C{expr.setResultsName("name")} -
see L{I{__call__}<__call__>}.
Example::
date_str = (integer.setResultsName("year") + '/'
+ integer.setResultsName("month") + '/'
+ integer.setResultsName("day"))
# equivalent form:
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
"""
newself = self.copy()
if name.endswith("*"):
name = name[:-1]
listAllMatches=True
newself.resultsName = name
newself.modalResults = not listAllMatches
return newself | [
"def",
"setResultsName",
"(",
"self",
",",
"name",
",",
"listAllMatches",
"=",
"False",
")",
":",
"newself",
"=",
"self",
".",
"copy",
"(",
")",
"if",
"name",
".",
"endswith",
"(",
"\"*\"",
")",
":",
"name",
"=",
"name",
"[",
":",
"-",
"1",
"]",
"listAllMatches",
"=",
"True",
"newself",
".",
"resultsName",
"=",
"name",
"newself",
".",
"modalResults",
"=",
"not",
"listAllMatches",
"return",
"newself"
] | [
1180,
4
] | [
1206,
22
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.setBreak | (self,breakFlag = True) | Method to invoke the Python pdb debugger when this element is
about to be parsed. Set C{breakFlag} to True to enable, False to
disable.
| Method to invoke the Python pdb debugger when this element is
about to be parsed. Set C{breakFlag} to True to enable, False to
disable.
| def setBreak(self,breakFlag = True):
"""Method to invoke the Python pdb debugger when this element is
about to be parsed. Set C{breakFlag} to True to enable, False to
disable.
"""
if breakFlag:
_parseMethod = self._parse
def breaker(instring, loc, doActions=True, callPreParse=True):
import pdb
pdb.set_trace()
return _parseMethod( instring, loc, doActions, callPreParse )
breaker._originalParseMethod = _parseMethod
self._parse = breaker
else:
if hasattr(self._parse,"_originalParseMethod"):
self._parse = self._parse._originalParseMethod
return self | [
"def",
"setBreak",
"(",
"self",
",",
"breakFlag",
"=",
"True",
")",
":",
"if",
"breakFlag",
":",
"_parseMethod",
"=",
"self",
".",
"_parse",
"def",
"breaker",
"(",
"instring",
",",
"loc",
",",
"doActions",
"=",
"True",
",",
"callPreParse",
"=",
"True",
")",
":",
"import",
"pdb",
"pdb",
".",
"set_trace",
"(",
")",
"return",
"_parseMethod",
"(",
"instring",
",",
"loc",
",",
"doActions",
",",
"callPreParse",
")",
"breaker",
".",
"_originalParseMethod",
"=",
"_parseMethod",
"self",
".",
"_parse",
"=",
"breaker",
"else",
":",
"if",
"hasattr",
"(",
"self",
".",
"_parse",
",",
"\"_originalParseMethod\"",
")",
":",
"self",
".",
"_parse",
"=",
"self",
".",
"_parse",
".",
"_originalParseMethod",
"return",
"self"
] | [
1208,
4
] | [
1224,
19
] | python | en | ['en', 'en', 'en'] | True |
ParserElement.setParseAction | ( self, *fns, **kwargs ) |
Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
- s = the original string being parsed (see note below)
- loc = the location of the matching substring
- toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value.
Optional keyword arguments:
- callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{parseString}<parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
Example::
integer = Word(nums)
date_str = integer + '/' + integer + '/' + integer
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# use parse action to convert to ints at parse time
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
date_str = integer + '/' + integer + '/' + integer
# note that integer fields are now ints, not strings
date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
|
Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
- s = the original string being parsed (see note below)
- loc = the location of the matching substring
- toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value.
Optional keyword arguments:
- callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{parseString}<parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
Example::
integer = Word(nums)
date_str = integer + '/' + integer + '/' + integer
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# use parse action to convert to ints at parse time
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
date_str = integer + '/' + integer + '/' + integer
# note that integer fields are now ints, not strings
date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
| def setParseAction( self, *fns, **kwargs ):
"""
Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
- s = the original string being parsed (see note below)
- loc = the location of the matching substring
- toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value.
Optional keyword arguments:
- callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{parseString}<parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
Example::
integer = Word(nums)
date_str = integer + '/' + integer + '/' + integer
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# use parse action to convert to ints at parse time
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
date_str = integer + '/' + integer + '/' + integer
# note that integer fields are now ints, not strings
date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
"""
self.parseAction = list(map(_trim_arity, list(fns)))
self.callDuringTry = kwargs.get("callDuringTry", False)
return self | [
"def",
"setParseAction",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"parseAction",
"=",
"list",
"(",
"map",
"(",
"_trim_arity",
",",
"list",
"(",
"fns",
")",
")",
")",
"self",
".",
"callDuringTry",
"=",
"kwargs",
".",
"get",
"(",
"\"callDuringTry\"",
",",
"False",
")",
"return",
"self"
] | [
1226,
4
] | [
1262,
19
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.addParseAction | ( self, *fns, **kwargs ) |
Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}.
See examples in L{I{copy}<copy>}.
|
Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}.
See examples in L{I{copy}<copy>}.
| def addParseAction( self, *fns, **kwargs ):
"""
Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}.
See examples in L{I{copy}<copy>}.
"""
self.parseAction += list(map(_trim_arity, list(fns)))
self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
return self | [
"def",
"addParseAction",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"parseAction",
"+=",
"list",
"(",
"map",
"(",
"_trim_arity",
",",
"list",
"(",
"fns",
")",
")",
")",
"self",
".",
"callDuringTry",
"=",
"self",
".",
"callDuringTry",
"or",
"kwargs",
".",
"get",
"(",
"\"callDuringTry\"",
",",
"False",
")",
"return",
"self"
] | [
1264,
4
] | [
1272,
19
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.addCondition | (self, *fns, **kwargs) | Add a boolean predicate function to expression's list of parse actions. See
L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction},
functions passed to C{addCondition} need to return boolean success/fail of the condition.
Optional keyword arguments:
- message = define a custom message to be used in the raised exception
- fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
year_int = integer.copy()
year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
date_str = year_int + '/' + integer + '/' + integer
result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
| Add a boolean predicate function to expression's list of parse actions. See
L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction},
functions passed to C{addCondition} need to return boolean success/fail of the condition.
Optional keyword arguments:
- message = define a custom message to be used in the raised exception
- fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
year_int = integer.copy()
year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
date_str = year_int + '/' + integer + '/' + integer
result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
| def addCondition(self, *fns, **kwargs):
"""Add a boolean predicate function to expression's list of parse actions. See
L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction},
functions passed to C{addCondition} need to return boolean success/fail of the condition.
Optional keyword arguments:
- message = define a custom message to be used in the raised exception
- fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
year_int = integer.copy()
year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
date_str = year_int + '/' + integer + '/' + integer
result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
"""
msg = kwargs.get("message", "failed user-defined condition")
exc_type = ParseFatalException if kwargs.get("fatal", False) else ParseException
for fn in fns:
def pa(s,l,t):
if not bool(_trim_arity(fn)(s,l,t)):
raise exc_type(s,l,msg)
self.parseAction.append(pa)
self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
return self | [
"def",
"addCondition",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"kwargs",
".",
"get",
"(",
"\"message\"",
",",
"\"failed user-defined condition\"",
")",
"exc_type",
"=",
"ParseFatalException",
"if",
"kwargs",
".",
"get",
"(",
"\"fatal\"",
",",
"False",
")",
"else",
"ParseException",
"for",
"fn",
"in",
"fns",
":",
"def",
"pa",
"(",
"s",
",",
"l",
",",
"t",
")",
":",
"if",
"not",
"bool",
"(",
"_trim_arity",
"(",
"fn",
")",
"(",
"s",
",",
"l",
",",
"t",
")",
")",
":",
"raise",
"exc_type",
"(",
"s",
",",
"l",
",",
"msg",
")",
"self",
".",
"parseAction",
".",
"append",
"(",
"pa",
")",
"self",
".",
"callDuringTry",
"=",
"self",
".",
"callDuringTry",
"or",
"kwargs",
".",
"get",
"(",
"\"callDuringTry\"",
",",
"False",
")",
"return",
"self"
] | [
1274,
4
] | [
1299,
19
] | python | en | ['en', 'en', 'en'] | True |
ParserElement.setFailAction | ( self, fn ) | Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
C{fn(s,loc,expr,err)} where:
- s = string being parsed
- loc = location where expression match was attempted and failed
- expr = the parse expression that failed
- err = the exception thrown
The function returns no value. It may throw C{L{ParseFatalException}}
if it is desired to stop parsing immediately. | Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
C{fn(s,loc,expr,err)} where:
- s = string being parsed
- loc = location where expression match was attempted and failed
- expr = the parse expression that failed
- err = the exception thrown
The function returns no value. It may throw C{L{ParseFatalException}}
if it is desired to stop parsing immediately. | def setFailAction( self, fn ):
"""Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
C{fn(s,loc,expr,err)} where:
- s = string being parsed
- loc = location where expression match was attempted and failed
- expr = the parse expression that failed
- err = the exception thrown
The function returns no value. It may throw C{L{ParseFatalException}}
if it is desired to stop parsing immediately."""
self.failAction = fn
return self | [
"def",
"setFailAction",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"failAction",
"=",
"fn",
"return",
"self"
] | [
1301,
4
] | [
1312,
19
] | python | en | ['en', 'en', 'en'] | True |
ParserElement.enablePackrat | (cache_size_limit=128) | Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
Parameters:
- cache_size_limit - (default=C{128}) - if an integer value is provided
will limit the size of the packrat cache; if None is passed, then
the cache size will be unbounded; if 0 is passed, the cache will
be effectively disabled.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method C{ParserElement.enablePackrat()}. If
your program uses C{psyco} to "compile as you go", you must call
C{enablePackrat} before calling C{psyco.full()}. If you do not do this,
Python will crash. For best results, call C{enablePackrat()} immediately
after importing pyparsing.
Example::
import pyparsing
pyparsing.ParserElement.enablePackrat()
| Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
Parameters:
- cache_size_limit - (default=C{128}) - if an integer value is provided
will limit the size of the packrat cache; if None is passed, then
the cache size will be unbounded; if 0 is passed, the cache will
be effectively disabled.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method C{ParserElement.enablePackrat()}. If
your program uses C{psyco} to "compile as you go", you must call
C{enablePackrat} before calling C{psyco.full()}. If you do not do this,
Python will crash. For best results, call C{enablePackrat()} immediately
after importing pyparsing.
Example::
import pyparsing
pyparsing.ParserElement.enablePackrat()
| def enablePackrat(cache_size_limit=128):
"""Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
Parameters:
- cache_size_limit - (default=C{128}) - if an integer value is provided
will limit the size of the packrat cache; if None is passed, then
the cache size will be unbounded; if 0 is passed, the cache will
be effectively disabled.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method C{ParserElement.enablePackrat()}. If
your program uses C{psyco} to "compile as you go", you must call
C{enablePackrat} before calling C{psyco.full()}. If you do not do this,
Python will crash. For best results, call C{enablePackrat()} immediately
after importing pyparsing.
Example::
import pyparsing
pyparsing.ParserElement.enablePackrat()
"""
if not ParserElement._packratEnabled:
ParserElement._packratEnabled = True
if cache_size_limit is None:
ParserElement.packrat_cache = ParserElement._UnboundedCache()
else:
ParserElement.packrat_cache = ParserElement._FifoCache(cache_size_limit)
ParserElement._parse = ParserElement._parseCache | [
"def",
"enablePackrat",
"(",
"cache_size_limit",
"=",
"128",
")",
":",
"if",
"not",
"ParserElement",
".",
"_packratEnabled",
":",
"ParserElement",
".",
"_packratEnabled",
"=",
"True",
"if",
"cache_size_limit",
"is",
"None",
":",
"ParserElement",
".",
"packrat_cache",
"=",
"ParserElement",
".",
"_UnboundedCache",
"(",
")",
"else",
":",
"ParserElement",
".",
"packrat_cache",
"=",
"ParserElement",
".",
"_FifoCache",
"(",
"cache_size_limit",
")",
"ParserElement",
".",
"_parse",
"=",
"ParserElement",
".",
"_parseCache"
] | [
1536,
4
] | [
1568,
60
] | python | en | ['en', 'en', 'en'] | True |
ParserElement.parseString | ( self, instring, parseAll=False ) |
Execute the parse expression with the given string.
This is the main interface to the client code, once the complete
expression has been built.
If you want the grammar to require that the entire input string be
successfully parsed, then set C{parseAll} to True (equivalent to ending
the grammar with C{L{StringEnd()}}).
Note: C{parseString} implicitly calls C{expandtabs()} on the input string,
in order to report proper column numbers in parse actions.
If the input string contains tabs and
the grammar uses parse actions that use the C{loc} argument to index into the
string being parsed, you can ensure you have a consistent view of the input
string by:
- calling C{parseWithTabs} on your grammar before calling C{parseString}
(see L{I{parseWithTabs}<parseWithTabs>})
- define your parse action using the full C{(s,loc,toks)} signature, and
reference the input string using the parse action's C{s} argument
- explictly expand the tabs in your input string before calling
C{parseString}
Example::
Word('a').parseString('aaaaabaaa') # -> ['aaaaa']
Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text
|
Execute the parse expression with the given string.
This is the main interface to the client code, once the complete
expression has been built.
If you want the grammar to require that the entire input string be
successfully parsed, then set C{parseAll} to True (equivalent to ending
the grammar with C{L{StringEnd()}}).
Note: C{parseString} implicitly calls C{expandtabs()} on the input string,
in order to report proper column numbers in parse actions.
If the input string contains tabs and
the grammar uses parse actions that use the C{loc} argument to index into the
string being parsed, you can ensure you have a consistent view of the input
string by:
- calling C{parseWithTabs} on your grammar before calling C{parseString}
(see L{I{parseWithTabs}<parseWithTabs>})
- define your parse action using the full C{(s,loc,toks)} signature, and
reference the input string using the parse action's C{s} argument
- explictly expand the tabs in your input string before calling
C{parseString}
Example::
Word('a').parseString('aaaaabaaa') # -> ['aaaaa']
Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text
| def parseString( self, instring, parseAll=False ):
"""
Execute the parse expression with the given string.
This is the main interface to the client code, once the complete
expression has been built.
If you want the grammar to require that the entire input string be
successfully parsed, then set C{parseAll} to True (equivalent to ending
the grammar with C{L{StringEnd()}}).
Note: C{parseString} implicitly calls C{expandtabs()} on the input string,
in order to report proper column numbers in parse actions.
If the input string contains tabs and
the grammar uses parse actions that use the C{loc} argument to index into the
string being parsed, you can ensure you have a consistent view of the input
string by:
- calling C{parseWithTabs} on your grammar before calling C{parseString}
(see L{I{parseWithTabs}<parseWithTabs>})
- define your parse action using the full C{(s,loc,toks)} signature, and
reference the input string using the parse action's C{s} argument
- explictly expand the tabs in your input string before calling
C{parseString}
Example::
Word('a').parseString('aaaaabaaa') # -> ['aaaaa']
Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text
"""
ParserElement.resetCache()
if not self.streamlined:
self.streamline()
#~ self.saveAsList = True
for e in self.ignoreExprs:
e.streamline()
if not self.keepTabs:
instring = instring.expandtabs()
try:
loc, tokens = self._parse( instring, 0 )
if parseAll:
loc = self.preParse( instring, loc )
se = Empty() + StringEnd()
se._parse( instring, loc )
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc
else:
return tokens | [
"def",
"parseString",
"(",
"self",
",",
"instring",
",",
"parseAll",
"=",
"False",
")",
":",
"ParserElement",
".",
"resetCache",
"(",
")",
"if",
"not",
"self",
".",
"streamlined",
":",
"self",
".",
"streamline",
"(",
")",
"#~ self.saveAsList = True\r",
"for",
"e",
"in",
"self",
".",
"ignoreExprs",
":",
"e",
".",
"streamline",
"(",
")",
"if",
"not",
"self",
".",
"keepTabs",
":",
"instring",
"=",
"instring",
".",
"expandtabs",
"(",
")",
"try",
":",
"loc",
",",
"tokens",
"=",
"self",
".",
"_parse",
"(",
"instring",
",",
"0",
")",
"if",
"parseAll",
":",
"loc",
"=",
"self",
".",
"preParse",
"(",
"instring",
",",
"loc",
")",
"se",
"=",
"Empty",
"(",
")",
"+",
"StringEnd",
"(",
")",
"se",
".",
"_parse",
"(",
"instring",
",",
"loc",
")",
"except",
"ParseBaseException",
"as",
"exc",
":",
"if",
"ParserElement",
".",
"verbose_stacktrace",
":",
"raise",
"else",
":",
"# catch and re-raise exception from here, clears out pyparsing internal stack trace\r",
"raise",
"exc",
"else",
":",
"return",
"tokens"
] | [
1570,
4
] | [
1618,
25
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.scanString | ( self, instring, maxMatches=_MAX_INT, overlap=False ) |
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
C{maxMatches} argument, to clip scanning after 'n' matches are found. If
C{overlap} is specified, then overlapping matches will be reported.
Note that the start and end locations are reported relative to the string
being parsed. See L{I{parseString}<parseString>} for more information on parsing
strings with embedded tabs.
Example::
source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
print(source)
for tokens,start,end in Word(alphas).scanString(source):
print(' '*start + '^'*(end-start))
print(' '*start + tokens[0])
prints::
sldjf123lsdjjkf345sldkjf879lkjsfd987
^^^^^
sldjf
^^^^^^^
lsdjjkf
^^^^^^
sldkjf
^^^^^^
lkjsfd
|
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
C{maxMatches} argument, to clip scanning after 'n' matches are found. If
C{overlap} is specified, then overlapping matches will be reported.
Note that the start and end locations are reported relative to the string
being parsed. See L{I{parseString}<parseString>} for more information on parsing
strings with embedded tabs.
Example::
source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
print(source)
for tokens,start,end in Word(alphas).scanString(source):
print(' '*start + '^'*(end-start))
print(' '*start + tokens[0])
prints::
sldjf123lsdjjkf345sldkjf879lkjsfd987
^^^^^
sldjf
^^^^^^^
lsdjjkf
^^^^^^
sldkjf
^^^^^^
lkjsfd
| def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ):
"""
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
C{maxMatches} argument, to clip scanning after 'n' matches are found. If
C{overlap} is specified, then overlapping matches will be reported.
Note that the start and end locations are reported relative to the string
being parsed. See L{I{parseString}<parseString>} for more information on parsing
strings with embedded tabs.
Example::
source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
print(source)
for tokens,start,end in Word(alphas).scanString(source):
print(' '*start + '^'*(end-start))
print(' '*start + tokens[0])
prints::
sldjf123lsdjjkf345sldkjf879lkjsfd987
^^^^^
sldjf
^^^^^^^
lsdjjkf
^^^^^^
sldkjf
^^^^^^
lkjsfd
"""
if not self.streamlined:
self.streamline()
for e in self.ignoreExprs:
e.streamline()
if not self.keepTabs:
instring = _ustr(instring).expandtabs()
instrlen = len(instring)
loc = 0
preparseFn = self.preParse
parseFn = self._parse
ParserElement.resetCache()
matches = 0
try:
while loc <= instrlen and matches < maxMatches:
try:
preloc = preparseFn( instring, loc )
nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
except ParseException:
loc = preloc+1
else:
if nextLoc > loc:
matches += 1
yield tokens, preloc, nextLoc
if overlap:
nextloc = preparseFn( instring, loc )
if nextloc > loc:
loc = nextLoc
else:
loc += 1
else:
loc = nextLoc
else:
loc = preloc+1
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc | [
"def",
"scanString",
"(",
"self",
",",
"instring",
",",
"maxMatches",
"=",
"_MAX_INT",
",",
"overlap",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"streamlined",
":",
"self",
".",
"streamline",
"(",
")",
"for",
"e",
"in",
"self",
".",
"ignoreExprs",
":",
"e",
".",
"streamline",
"(",
")",
"if",
"not",
"self",
".",
"keepTabs",
":",
"instring",
"=",
"_ustr",
"(",
"instring",
")",
".",
"expandtabs",
"(",
")",
"instrlen",
"=",
"len",
"(",
"instring",
")",
"loc",
"=",
"0",
"preparseFn",
"=",
"self",
".",
"preParse",
"parseFn",
"=",
"self",
".",
"_parse",
"ParserElement",
".",
"resetCache",
"(",
")",
"matches",
"=",
"0",
"try",
":",
"while",
"loc",
"<=",
"instrlen",
"and",
"matches",
"<",
"maxMatches",
":",
"try",
":",
"preloc",
"=",
"preparseFn",
"(",
"instring",
",",
"loc",
")",
"nextLoc",
",",
"tokens",
"=",
"parseFn",
"(",
"instring",
",",
"preloc",
",",
"callPreParse",
"=",
"False",
")",
"except",
"ParseException",
":",
"loc",
"=",
"preloc",
"+",
"1",
"else",
":",
"if",
"nextLoc",
">",
"loc",
":",
"matches",
"+=",
"1",
"yield",
"tokens",
",",
"preloc",
",",
"nextLoc",
"if",
"overlap",
":",
"nextloc",
"=",
"preparseFn",
"(",
"instring",
",",
"loc",
")",
"if",
"nextloc",
">",
"loc",
":",
"loc",
"=",
"nextLoc",
"else",
":",
"loc",
"+=",
"1",
"else",
":",
"loc",
"=",
"nextLoc",
"else",
":",
"loc",
"=",
"preloc",
"+",
"1",
"except",
"ParseBaseException",
"as",
"exc",
":",
"if",
"ParserElement",
".",
"verbose_stacktrace",
":",
"raise",
"else",
":",
"# catch and re-raise exception from here, clears out pyparsing internal stack trace\r",
"raise",
"exc"
] | [
1620,
4
] | [
1689,
25
] | python | en | ['en', 'ja', 'th'] | False |
ParserElement.transformString | ( self, instring ) |
Extension to C{L{scanString}}, to modify matching text with modified tokens that may
be returned from a parse action. To use C{transformString}, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking C{transformString()} on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. C{transformString()} returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
Prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
|
Extension to C{L{scanString}}, to modify matching text with modified tokens that may
be returned from a parse action. To use C{transformString}, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking C{transformString()} on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. C{transformString()} returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
Prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
| def transformString( self, instring ):
"""
Extension to C{L{scanString}}, to modify matching text with modified tokens that may
be returned from a parse action. To use C{transformString}, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking C{transformString()} on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. C{transformString()} returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
Prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
"""
out = []
lastE = 0
# force preservation of <TAB>s, to minimize unwanted transformation of string, and to
# keep string locs straight between transformString and scanString
self.keepTabs = True
try:
for t,s,e in self.scanString( instring ):
out.append( instring[lastE:s] )
if t:
if isinstance(t,ParseResults):
out += t.asList()
elif isinstance(t,list):
out += t
else:
out.append(t)
lastE = e
out.append(instring[lastE:])
out = [o for o in out if o]
return "".join(map(_ustr,_flatten(out)))
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc | [
"def",
"transformString",
"(",
"self",
",",
"instring",
")",
":",
"out",
"=",
"[",
"]",
"lastE",
"=",
"0",
"# force preservation of <TAB>s, to minimize unwanted transformation of string, and to\r",
"# keep string locs straight between transformString and scanString\r",
"self",
".",
"keepTabs",
"=",
"True",
"try",
":",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
")",
":",
"out",
".",
"append",
"(",
"instring",
"[",
"lastE",
":",
"s",
"]",
")",
"if",
"t",
":",
"if",
"isinstance",
"(",
"t",
",",
"ParseResults",
")",
":",
"out",
"+=",
"t",
".",
"asList",
"(",
")",
"elif",
"isinstance",
"(",
"t",
",",
"list",
")",
":",
"out",
"+=",
"t",
"else",
":",
"out",
".",
"append",
"(",
"t",
")",
"lastE",
"=",
"e",
"out",
".",
"append",
"(",
"instring",
"[",
"lastE",
":",
"]",
")",
"out",
"=",
"[",
"o",
"for",
"o",
"in",
"out",
"if",
"o",
"]",
"return",
"\"\"",
".",
"join",
"(",
"map",
"(",
"_ustr",
",",
"_flatten",
"(",
"out",
")",
")",
")",
"except",
"ParseBaseException",
"as",
"exc",
":",
"if",
"ParserElement",
".",
"verbose_stacktrace",
":",
"raise",
"else",
":",
"# catch and re-raise exception from here, clears out pyparsing internal stack trace\r",
"raise",
"exc"
] | [
1691,
4
] | [
1732,
25
] | python | en | ['en', 'ja', 'th'] | False |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.