Search is not available for this dataset
identifier stringlengths 1 155 | parameters stringlengths 2 6.09k | docstring stringlengths 11 63.4k | docstring_summary stringlengths 0 63.4k | function stringlengths 29 99.8k | function_tokens list | start_point list | end_point list | language stringclasses 1
value | docstring_language stringlengths 2 7 | docstring_language_predictions stringlengths 18 23 | is_langid_reliable stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
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(),
... | [
"def",
"create_main_parser",
"(",
")",
"->",
"ConfigOptionParser",
":",
"parser",
"=",
"ConfigOptionParser",
"(",
"usage",
"=",
"\"\\n%prog <command> [options]\"",
",",
"add_help_option",
"=",
"False",
",",
"formatter",
"=",
"UpdatingDefaultsHelpFormatter",
"(",
")",
... | [
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 ... | [
"def",
"_mask_cipher_secret",
"(",
"secret",
")",
":",
"mask",
"=",
"_get_new_csrf_string",
"(",
")",
"chars",
"=",
"CSRF_ALLOWED_CHARS",
"pairs",
"=",
"zip",
"(",
"(",
"chars",
".",
"index",
"(",
"x",
")",
"for",
"x",
"in",
"secret",
")",
",",
"(",
"c... | [
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... | [
"def",
"_unmask_cipher_token",
"(",
"token",
")",
":",
"mask",
"=",
"token",
"[",
":",
"CSRF_SECRET_LENGTH",
"]",
"token",
"=",
"token",
"[",
"CSRF_SECRET_LENGTH",
":",
"]",
"chars",
"=",
"CSRF_ALLOWED_CHARS",
"pairs",
"=",
"zip",
"(",
"(",
"chars",
".",
"... | [
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 outgoin... |
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: Co... | [
"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_s... | [
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",
"=",
... | [
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",
"b... | [
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 isinstanc... | [
"def",
"iter_field_objects",
"(",
"fields",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"dict",
")",
":",
"i",
"=",
"six",
".",
"iteritems",
"(",
"fields",
")",
"else",
":",
"i",
"=",
"iter",
"(",
"fields",
")",
"for",
"field",
"in",
"i",
":"... | [
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 an... | [
"def",
"iter_fields",
"(",
"fields",
")",
":",
"if",
"isinstance",
"(",
"fields",
",",
"dict",
")",
":",
"return",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"fields",
")",
")",
"return",
"(",
"(",
"... | [
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.choos... |
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 ... | [
"def",
"encode_multipart_formdata",
"(",
"fields",
",",
"boundary",
"=",
"None",
")",
":",
"body",
"=",
"BytesIO",
"(",
")",
"if",
"boundary",
"is",
"None",
":",
"boundary",
"=",
"choose_boundary",
"(",
")",
"for",
"field",
"in",
"iter_field_objects",
"(",
... | [
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 var... |
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 var... | 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... | [
"def",
"variant_count",
"(",
"table",
":",
"pandas",
".",
"DataFrame",
",",
"reference",
":",
"pandas",
".",
"Series",
")",
"->",
"pandas",
".",
"Series",
":",
"present_df",
":",
"pandas",
".",
"DataFrame",
"=",
"table",
".",
"apply",
"(",
"lambda",
"s",... | [
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 refe... |
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 refe... | 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... | [
"def",
"filter_variants_in_all_samples",
"(",
"df",
":",
"pandas",
".",
"DataFrame",
",",
"reference_label",
":",
"str",
")",
"->",
"pandas",
".",
"DataFrame",
":",
"reference",
"=",
"df",
".",
"pop",
"(",
"reference_label",
")",
"variants",
"=",
"variant_coun... | [
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 ... |
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 ... | 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', ... | [
"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"... | [
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... |
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... | 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.
... | [
"def",
"_forward_dyn",
"(",
"self",
",",
"frames",
",",
"n_fwd_times",
",",
"need_intermediate",
",",
"train_noise_frac",
"=",
"0",
")",
":",
"if",
"n_fwd_times",
"==",
"0",
":",
"return",
"frames",
",",
"None",
",",
"{",
"}",
"rollout",
"=",
"[",
"]",
... | [
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 ... |
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 ... | 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)... | [
"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",
... | [
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, n... | [
"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",
... | [
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
... | [
"def",
"__init__",
"(",
"self",
",",
"memo",
"=",
"\"\"",
",",
"tags",
"=",
"\"\"",
")",
":",
"self",
".",
"memo",
"=",
"memo",
"self",
".",
"tags",
"=",
"tags",
"self",
".",
"creation_date",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
... | [
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 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('... | [
"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... | 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 t... | [
"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}')
... | 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{/use... | [
"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
els... | [
"def",
"to_python",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"value",
",",
"oauth2client",
".",
"client",
".",
"Credentials",
")",
":",
"return",
"value",
"else",
":",
"try",
":... | [
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_... | [
"def",
"get_prep_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"encoding",
".",
"smart_text",
"(",
"base64",
".",
"b64encode",
"(",
"jsonpickle",
".",
"encode",
"(",
"value",
")",
... | [
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... | [
"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(... | [
"def",
"unpack",
"(",
"src_dir",
",",
"dst_dir",
")",
":",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"src_dir",
")",
":",
"subdir",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"dirpath",
",",
"src_dir",
")",
... | [
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_basena... | [
"def",
"install_as_egg",
"(",
"self",
",",
"destination_eggdir",
")",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"self",
".",
"filename",
")",
"as",
"zf",
":",
"dist_basename",
"=",
"'%s-%s'",
"%",
"(",
"self",
".",
"project_name",
",",
"self",
".",
"v... | [
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 ValueErro... | [
"def",
"check_module",
"(",
"feature",
")",
":",
"if",
"not",
"(",
"feature",
"in",
"modules",
")",
":",
"raise",
"ValueError",
"(",
"f\"Unknown module {feature}\"",
")",
"module",
",",
"ver",
"=",
"modules",
"[",
"feature",
"]",
"try",
":",
"__import__",
... | [
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... | [
"def",
"version_module",
"(",
"feature",
")",
":",
"if",
"not",
"check_module",
"(",
"feature",
")",
":",
"return",
"None",
"module",
",",
"ver",
"=",
"modules",
"[",
"feature",
"]",
"if",
"ver",
"is",
"None",
":",
"return",
"None",
"return",
"getattr",
... | [
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"Unk... | [
"def",
"check_codec",
"(",
"feature",
")",
":",
"if",
"feature",
"not",
"in",
"codecs",
":",
"raise",
"ValueError",
"(",
"f\"Unknown codec {feature}\"",
")",
"codec",
",",
"lib",
"=",
"codecs",
"[",
"feature",
"]",
"return",
"codec",
"+",
"\"_encoder\"",
"in... | [
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.
"""
... | [
"def",
"version_codec",
"(",
"feature",
")",
":",
"if",
"not",
"check_codec",
"(",
"feature",
")",
":",
"return",
"None",
"codec",
",",
"lib",
"=",
"codecs",
"[",
"feature",
"]",
"version",
"=",
"getattr",
"(",
"Image",
".",
"core",
",",
"lib",
"+",
... | [
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 feat... | [
"def",
"check_feature",
"(",
"feature",
")",
":",
"if",
"feature",
"not",
"in",
"features",
":",
"raise",
"ValueError",
"(",
"f\"Unknown feature {feature}\"",
")",
"module",
",",
"flag",
",",
"ver",
"=",
"features",
"[",
"feature",
"]",
"try",
":",
"imported... | [
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, fla... | [
"def",
"version_feature",
"(",
"feature",
")",
":",
"if",
"not",
"check_feature",
"(",
"feature",
")",
":",
"return",
"None",
"module",
",",
"flag",
",",
"ver",
"=",
"features",
"[",
"feature",
"]",
"if",
"ver",
"is",
"None",
":",
"return",
"None",
"re... | [
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... | [
"def",
"check",
"(",
"feature",
")",
":",
"if",
"feature",
"in",
"modules",
":",
"return",
"check_module",
"(",
"feature",
")",
"if",
"feature",
"in",
"codecs",
":",
"return",
"check_codec",
"(",
"feature",
")",
"if",
"feature",
"in",
"features",
":",
"r... | [
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_... | [
"def",
"version",
"(",
"feature",
")",
":",
"if",
"feature",
"in",
"modules",
":",
"return",
"version_module",
"(",
"feature",
")",
"if",
"feature",
"in",
"codecs",
":",
"return",
"version_codec",
"(",
"feature",
")",
"if",
"feature",
"in",
"features",
":"... | [
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 printe... |
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 l... | [
"def",
"pilinfo",
"(",
"out",
"=",
"None",
",",
"supported_formats",
"=",
"True",
")",
":",
"if",
"out",
"is",
"None",
":",
"out",
"=",
"sys",
".",
"stdout",
"Image",
".",
"init",
"(",
")",
"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.
"""
... | [
"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,... | [
"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'... | [
"def",
"_init_length",
"(",
"self",
",",
"request_method",
")",
":",
"length",
"=",
"self",
".",
"headers",
".",
"get",
"(",
"\"content-length\"",
")",
"if",
"length",
"is",
"not",
"None",
":",
"if",
"self",
".",
"chunked",
":",
"# This Response will fail wi... | [
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:
... | [
"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",
"(",
")",... | [
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 sel... | [
"def",
"_decode",
"(",
"self",
",",
"data",
",",
"decode_content",
",",
"flush_decoder",
")",
":",
"if",
"not",
"decode_content",
":",
"return",
"data",
"try",
":",
"if",
"self",
".",
"_decoder",
":",
"data",
"=",
"self",
".",
"_decoder",
".",
"decompres... | [
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:
... | [
"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.",... | [
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 fu... |
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 skipp... | [
"def",
"read",
"(",
"self",
",",
"amt",
"=",
"None",
",",
"decode_content",
"=",
"None",
",",
"cache_content",
"=",
"False",
")",
":",
"self",
".",
"_init_decoder",
"(",
")",
"if",
"decode_content",
"is",
"None",
":",
"decode_content",
"=",
"self",
".",
... | [
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 r... |
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 w... | [
"def",
"stream",
"(",
"self",
",",
"amt",
"=",
"2",
"**",
"16",
",",
"decode_content",
"=",
"None",
")",
":",
"if",
"self",
".",
"chunked",
"and",
"self",
".",
"supports_chunked_reads",
"(",
")",
":",
"for",
"line",
"in",
"self",
".",
"read_chunked",
... | [
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... | [
"def",
"from_httplib",
"(",
"ResponseCls",
",",
"r",
",",
"*",
"*",
"response_kw",
")",
":",
"headers",
"=",
"r",
".",
"msg",
"if",
"not",
"isinstance",
"(",
"headers",
",",
"HTTPHeaderDict",
")",
":",
"if",
"six",
".",
"PY2",
":",
"# Python 2.7",
"hea... | [
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().
"""
... | [
"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.
:p... |
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 c... | [
"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",
... | [
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.... | [
"def",
"geturl",
"(",
"self",
")",
":",
"if",
"self",
".",
"retries",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"retries",
".",
"history",
")",
":",
"return",
"self",
".",
"retries",
".",
"history",
"[",
"-",
"1",
"]",
".",
"redirect_loc... | [
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,
... | [
"def",
"match_to_datetime",
"(",
"match",
":",
"\"Match\"",
")",
"->",
"Union",
"[",
"datetime",
",",
"date",
"]",
":",
"(",
"year_str",
",",
"month_str",
",",
"day_str",
",",
"hour_str",
",",
"minute_str",
",",
"sec_str",
",",
"micros_str",
",",
"zulu_tim... | [
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_)
... | [
"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_... | [
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
... | 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
... | 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.parseStrin... | [
"def",
"col",
"(",
"loc",
",",
"strg",
")",
":",
"s",
"=",
"strg",
"return",
"1",
"if",
"0",
"<",
"loc",
"<",
"len",
"(",
"s",
")",
"and",
"s",
"[",
"loc",
"-",
"1",
"]",
"==",
"'\\n'",
"else",
"loc",
"-",
"s",
".",
"rfind",
"(",
"\"\\n\"",... | [
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
... | 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
... | 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.parse... | [
"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",
"st... | [
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 ==... | [
"def",
"__getattr__",
"(",
"self",
",",
"aname",
")",
":",
"if",
"(",
"aname",
"==",
"\"lineno\"",
")",
":",
"return",
"lineno",
"(",
"self",
".",
"loc",
",",
"self",
".",
"pstr",
")",
"elif",
"(",
"aname",
"in",
"(",
"\"col\"",
",",
"\"column\"",
... | [
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 = "... | [
"def",
"markInputline",
"(",
"self",
",",
"markerString",
"=",
"\">!<\"",
")",
":",
"line_str",
"=",
"self",
".",
"line",
"line_column",
"=",
"self",
".",
"column",
"-",
"1",
"if",
"markerString",
":",
"line_str",
"=",
"\"\"",
".",
"join",
"(",
"(",
"l... | [
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 argum... |
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 argum... | 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 to... | [
"def",
"pop",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"args",
":",
"args",
"=",
"[",
"-",
"1",
"]",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"'default'",
":",... | [
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(... |
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(... | 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::
in... | [
"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 ... |
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 ... | 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 actio... | [
"def",
"insert",
"(",
"self",
",",
"index",
",",
"insStr",
")",
":",
"self",
".",
"__toklist",
".",
"insert",
"(",
"index",
",",
"insStr",
")",
"# fixup indices in token dictionary\r",
"for",
"name",
",",
"occurrences",
"in",
"self",
".",
"__tokdict",
".",
... | [
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_... |
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_... | 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 ... | [
"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):
token... |
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):
token... | 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_p... | [
"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 Par... |
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 Par... | 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... | [
"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(re... |
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(re... | 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')
... | [
"def",
"asDict",
"(",
"self",
")",
":",
"if",
"PY_3",
":",
"item_fn",
"=",
"self",
".",
"items",
"else",
":",
"item_fn",
"=",
"self",
".",
"iteritems",
"def",
"toItem",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ParseResults",
")",
... | [
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
... | [
"def",
"copy",
"(",
"self",
")",
":",
"ret",
"=",
"ParseResults",
"(",
"self",
".",
"__toklist",
")",
"ret",
".",
"__tokdict",
"=",
"self",
".",
"__tokdict",
".",
"copy",
"(",
")",
"ret",
".",
"__parent",
"=",
"self",
".",
"__parent",
"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)... | [
"def",
"asXML",
"(",
"self",
",",
"doctag",
"=",
"None",
",",
"namedItemsOnly",
"=",
"False",
",",
"indent",
"=",
"\"\"",
",",
"formatted",
"=",
"True",
")",
":",
"nl",
"=",
"\"\\n\"",
"out",
"=",
"[",
"]",
"namedItems",
"=",
"dict",
"(",
"(",
"v",... | [
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(... | 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(... | 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_... | [
"def",
"getName",
"(",
"self",
")",
":",
"if",
"self",
".",
"__name",
":",
"return",
"self",
".",
"__name",
"elif",
"self",
".",
"__parent",
":",
"par",
"=",
"self",
".",
"__parent",
"(",
")",
"if",
"par",
":",
"return",
"par",
".",
"__lookup",
"("... | [
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("m... |
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("m... | 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)... | [
"def",
"dump",
"(",
"self",
",",
"indent",
"=",
"''",
",",
"depth",
"=",
"0",
",",
"full",
"=",
"True",
")",
":",
"out",
"=",
"[",
"]",
"NL",
"=",
"'\\n'",
"out",
".",
"append",
"(",
"indent",
"+",
"_ustr",
"(",
"self",
".",
"asList",
"(",
")... | [
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... |
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... | 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})
Exampl... | [
"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
... | 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
... | 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']
... | [
"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.pa... |
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.pa... | 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("d... | [
"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().... |
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().... | 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]))
... | [
"def",
"copy",
"(",
"self",
")",
":",
"cpy",
"=",
"copy",
".",
"copy",
"(",
"self",
")",
"cpy",
".",
"parseAction",
"=",
"self",
".",
"parseAction",
"[",
":",
"]",
"cpy",
".",
"ignoreExprs",
"=",
"self",
".",
"ignoreExprs",
"[",
":",
"]",
"if",
"... | [
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 in... |
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 in... | 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").parseStr... | [
"def",
"setName",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"errmsg",
"=",
"\"Expected \"",
"+",
"self",
".",
"name",
"if",
"hasattr",
"(",
"self",
",",
"\"exception\"",
")",
":",
"self",
".",
"exception",
"."... | [
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 plac... |
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 plac... | 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 ele... | [
"def",
"setResultsName",
"(",
"self",
",",
"name",
",",
"listAllMatches",
"=",
"False",
")",
":",
"newself",
"=",
"self",
".",
"copy",
"(",
")",
"if",
"name",
".",
"endswith",
"(",
"\"*\"",
")",
":",
"name",
"=",
"name",
"[",
":",
"-",
"1",
"]",
... | [
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, ... | [
"def",
"setBreak",
"(",
"self",
",",
"breakFlag",
"=",
"True",
")",
":",
"if",
"breakFlag",
":",
"_parseMethod",
"=",
"self",
".",
"_parse",
"def",
"breaker",
"(",
"instring",
",",
"loc",
",",
"doActions",
"=",
"True",
",",
"callPreParse",
"=",
"True",
... | [
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)
... |
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)
... | 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 = ... | [
"def",
"setParseAction",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"parseAction",
"=",
"list",
"(",
"map",
"(",
"_trim_arity",
",",
"list",
"(",
"fns",
")",
")",
")",
"self",
".",
"callDuringTry",
"=",
"kwargs",
... | [
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... | [
"def",
"addParseAction",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"parseAction",
"+=",
"list",
"(",
"map",
"(",
"_trim_arity",
",",
"list",
"(",
"fns",
")",
")",
")",
"self",
".",
"callDuringTry",
"=",
"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:
... | 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:
... | 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 ... | [
"def",
"addCondition",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"msg",
"=",
"kwargs",
".",
"get",
"(",
"\"message\"",
",",
"\"failed user-defined condition\"",
")",
"exc_type",
"=",
"ParseFatalException",
"if",
"kwargs",
".",
"get",
... | [
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 ... | 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 ... | 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 atte... | [
"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
... | 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
... | 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... | [
"def",
"enablePackrat",
"(",
"cache_size_limit",
"=",
"128",
")",
":",
"if",
"not",
"ParserElement",
".",
"_packratEnabled",
":",
"ParserElement",
".",
"_packratEnabled",
"=",
"True",
"if",
"cache_size_limit",
"is",
"None",
":",
"ParserElement",
".",
"packrat_cach... | [
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... |
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... | 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
... | [
"def",
"parseString",
"(",
"self",
",",
"instring",
",",
"parseAll",
"=",
"False",
")",
":",
"ParserElement",
".",
"resetCache",
"(",
")",
"if",
"not",
"self",
".",
"streamlined",
":",
"self",
".",
"streamline",
"(",
")",
"#~ self.saveAsList = True\r",
"for"... | [
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 ... |
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 ... | 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' match... | [
"def",
"scanString",
"(",
"self",
",",
"instring",
",",
"maxMatches",
"=",
"_MAX_INT",
",",
"overlap",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"streamlined",
":",
"self",
".",
"streamline",
"(",
")",
"for",
"e",
"in",
"self",
".",
"ignoreExpr... | [
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 ... |
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 ... | 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.
... | [
"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",
".... | [
1691,
4
] | [
1732,
25
] | python | en | ['en', 'ja', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.