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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
ParseResults.from_dict | (cls, other, name=None) |
Helper classmethod to construct a ParseResults from a dict, preserving the
name-value relations as results names. If an optional 'name' argument is
given, a nested ParseResults will be returned
|
Helper classmethod to construct a ParseResults from a dict, preserving the
name-value relations as results names. If an optional 'name' argument is
given, a nested ParseResults will be returned
| def from_dict(cls, other, name=None):
"""
Helper classmethod to construct a ParseResults from a dict, preserving the
name-value relations as results names. If an optional 'name' argument is
given, a nested ParseResults will be returned
"""
def is_iterable(obj):
... | [
"def",
"from_dict",
"(",
"cls",
",",
"other",
",",
"name",
"=",
"None",
")",
":",
"def",
"is_iterable",
"(",
"obj",
")",
":",
"try",
":",
"iter",
"(",
"obj",
")",
"except",
"Exception",
":",
"return",
"False",
"else",
":",
"if",
"PY_3",
":",
"retur... | [
1181,
4
] | [
1206,
18
] | python | en | ['en', 'error', '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
Parser... | r"""
Overrides the default whitespace chars | 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 t... | [
"def",
"setDefaultWhitespaceChars",
"(",
"chars",
")",
":",
"ParserElement",
".",
"DEFAULT_WHITE_CHARS",
"=",
"chars"
] | [
1356,
4
] | [
1369,
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") #... |
Set class to be used for inclusion of string literals into a parser. | 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")
... | [
"def",
"inlineLiteralsUsing",
"(",
"cls",
")",
":",
"ParserElement",
".",
"_literalStringClass",
"=",
"cls"
] | [
1372,
4
] | [
1391,
47
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.copy | (self) |
Make a copy of this :class:`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 :class:`ParserElement`. Useful for defining
different parse actions for the same parsing pattern, using copies of
the original parse element. | def copy(self):
"""
Make a copy of this :class:`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",
"... | [
1422,
4
] | [
1449,
18
] | python | en | ['en', 'error', '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 ch... |
Define name for this expression, makes debugging and exception messages clearer. | 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") # -... | [
"def",
"setName",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"name",
"=",
"name",
"self",
".",
"errmsg",
"=",
"\"Expected \"",
"+",
"self",
".",
"name",
"if",
"__diag__",
".",
"enable_debug_on_named_expressions",
":",
"self",
".",
"setDebug",
"(",
... | [
1451,
4
] | [
1464,
19
] | python | en | ['en', 'error', '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 :class:`ParserElement` object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple pla... |
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original :class:`ParserElement` object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple pla... | 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 :class:`ParserElement` object;
this is so that the client can define a basic elem... | [
"def",
"setResultsName",
"(",
"self",
",",
"name",
",",
"listAllMatches",
"=",
"False",
")",
":",
"return",
"self",
".",
"_setResultsName",
"(",
"name",
",",
"listAllMatches",
")"
] | [
1466,
4
] | [
1487,
57
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setBreak | (self, breakFlag=True) | Method to invoke the Python pdb debugger when this element is
about to be parsed. Set ``breakFlag`` to True to enable, False to
disable.
| Method to invoke the Python pdb debugger when this element is
about to be parsed. Set ``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 ``breakFlag`` to True to enable, False to
disable.
"""
if breakFlag:
_parseMethod = self._parse
def breaker(instring, loc, do... | [
"def",
"setBreak",
"(",
"self",
",",
"breakFlag",
"=",
"True",
")",
":",
"if",
"breakFlag",
":",
"_parseMethod",
"=",
"self",
".",
"_parse",
"def",
"breaker",
"(",
"instring",
",",
"loc",
",",
"doActions",
"=",
"True",
",",
"callPreParse",
"=",
"True",
... | [
1498,
4
] | [
1515,
19
] | python | en | ['en', 'en', 'en'] | True |
ParserElement.setParseAction | (self, *fns, **kwargs) |
Define one or more actions to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as ``fn(s, loc, toks)`` ,
``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:
- s = the original string being parsed (se... |
Define one or more actions to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as ``fn(s, loc, toks)`` ,
``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where: | def setParseAction(self, *fns, **kwargs):
"""
Define one or more actions to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as ``fn(s, loc, toks)`` ,
``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:
... | [
"def",
"setParseAction",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"list",
"(",
"fns",
")",
"==",
"[",
"None",
",",
"]",
":",
"self",
".",
"parseAction",
"=",
"[",
"]",
"else",
":",
"if",
"not",
"all",
"(",
"callabl... | [
1517,
4
] | [
1564,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.addParseAction | (self, *fns, **kwargs) |
Add one or more parse actions to expression's list of parse actions. See :class:`setParseAction`.
See examples in :class:`copy`.
|
Add one or more parse actions to expression's list of parse actions. See :class:`setParseAction`. | def addParseAction(self, *fns, **kwargs):
"""
Add one or more parse actions to expression's list of parse actions. See :class:`setParseAction`.
See examples in :class:`copy`.
"""
self.parseAction += list(map(_trim_arity, list(fns)))
self.callDuringTry = self.callDuringTr... | [
"def",
"addParseAction",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"parseAction",
"+=",
"list",
"(",
"map",
"(",
"_trim_arity",
",",
"list",
"(",
"fns",
")",
")",
")",
"self",
".",
"callDuringTry",
"=",
"self",
"... | [
1566,
4
] | [
1574,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.addCondition | (self, *fns, **kwargs) | Add a boolean predicate function to expression's list of parse actions. See
:class:`setParseAction` for function call signatures. Unlike ``setParseAction``,
functions passed to ``addCondition`` need to return boolean success/fail of the condition.
Optional keyword arguments:
- message =... | Add a boolean predicate function to expression's list of parse actions. See
:class:`setParseAction` for function call signatures. Unlike ``setParseAction``,
functions passed to ``addCondition`` need to return boolean success/fail of the condition. | def addCondition(self, *fns, **kwargs):
"""Add a boolean predicate function to expression's list of parse actions. See
:class:`setParseAction` for function call signatures. Unlike ``setParseAction``,
functions passed to ``addCondition`` need to return boolean success/fail of the condition.
... | [
"def",
"addCondition",
"(",
"self",
",",
"*",
"fns",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"fn",
"in",
"fns",
":",
"self",
".",
"parseAction",
".",
"append",
"(",
"conditionAsParseAction",
"(",
"fn",
",",
"message",
"=",
"kwargs",
".",
"get",
"("... | [
1576,
4
] | [
1599,
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
``fn(s, loc, expr, err)`` where:
- s = string being parsed
- loc = location where expression match was attempted and failed
- expr = the pars... | Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
``fn(s, loc, expr, err)`` where:
- s = string being parsed
- loc = location where expression match was attempted and failed
- expr = the pars... | 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
``fn(s, loc, expr, err)`` where:
- s = string being parsed
- loc = location where expression match was attempted... | [
"def",
"setFailAction",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"failAction",
"=",
"fn",
"return",
"self"
] | [
1601,
4
] | [
1612,
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 par... | [
"def",
"enablePackrat",
"(",
"cache_size_limit",
"=",
"128",
")",
":",
"if",
"not",
"ParserElement",
".",
"_packratEnabled",
":",
"ParserElement",
".",
"_packratEnabled",
"=",
"True",
"if",
"cache_size_limit",
"is",
"None",
":",
"ParserElement",
".",
"packrat_cach... | [
1866,
4
] | [
1898,
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.
Returns the parsed data as a :class:`ParseResults` object, which may be
accessed as a list, or as a dict or object with attributes if ... |
Execute the parse expression with the given string.
This is the main interface to the client code, once the complete
expression has been built. | 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.
Returns the parsed data as a :class:`ParseResults` object, which may be
ac... | [
"def",
"parseString",
"(",
"self",
",",
"instring",
",",
"parseAll",
"=",
"False",
")",
":",
"ParserElement",
".",
"resetCache",
"(",
")",
"if",
"not",
"self",
".",
"streamlined",
":",
"self",
".",
"streamline",
"(",
")",
"# ~ self.saveAsList = True",
"for",... | [
1900,
4
] | [
1956,
25
] | python | en | ['en', 'error', '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
``maxMatches`` argument, to clip scanning after 'n' matches are found. If
``overlap`` is specified, then overlapping matches will be... |
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
``maxMatches`` argument, to clip scanning after 'n' matches are found. If
``overlap`` is specified, then overlapping matches will be... | 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
``maxMatches`` argument, to clip scanning after 'n' matches ar... | [
"def",
"scanString",
"(",
"self",
",",
"instring",
",",
"maxMatches",
"=",
"_MAX_INT",
",",
"overlap",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"streamlined",
":",
"self",
".",
"streamline",
"(",
")",
"for",
"e",
"in",
"self",
".",
"ignoreExpr... | [
1958,
4
] | [
2030,
25
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.transformString | (self, instring) |
Extension to :class:`scanString`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transformString``, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking ``transformString()`` on a target string... |
Extension to :class:`scanString`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transformString``, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking ``transformString()`` on a target string... | def transformString(self, instring):
"""
Extension to :class:`scanString`, to modify matching text with modified tokens that may
be returned from a parse action. To use ``transformString``, define a grammar and
attach a parse action to it that modifies the returned token list.
I... | [
"def",
"transformString",
"(",
"self",
",",
"instring",
")",
":",
"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",
".",
... | [
2032,
4
] | [
2078,
25
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.searchString | (self, instring, maxMatches=_MAX_INT) |
Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppe... |
Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found. | def searchString(self, instring, maxMatches=_MAX_INT):
"""
Another extension to :class:`scanString`, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
``maxMatches`` argument, to clip searching after 'n' matches are found.
... | [
"def",
"searchString",
"(",
"self",
",",
"instring",
",",
"maxMatches",
"=",
"_MAX_INT",
")",
":",
"try",
":",
"return",
"ParseResults",
"(",
"[",
"t",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
",",
"maxMatches",... | [
2080,
4
] | [
2110,
25
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.split | (self, instring, maxsplit=_MAX_INT, includeSeparators=False) |
Generator method to split a string using the given expression as a separator.
May be called with optional ``maxsplit`` argument, to limit the number of splits;
and the optional ``includeSeparators`` argument (default= ``False``), if the separating
matching text should be included in the... |
Generator method to split a string using the given expression as a separator.
May be called with optional ``maxsplit`` argument, to limit the number of splits;
and the optional ``includeSeparators`` argument (default= ``False``), if the separating
matching text should be included in the... | def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False):
"""
Generator method to split a string using the given expression as a separator.
May be called with optional ``maxsplit`` argument, to limit the number of splits;
and the optional ``includeSeparators`` argument (defa... | [
"def",
"split",
"(",
"self",
",",
"instring",
",",
"maxsplit",
"=",
"_MAX_INT",
",",
"includeSeparators",
"=",
"False",
")",
":",
"splits",
"=",
"0",
"last",
"=",
"0",
"for",
"t",
",",
"s",
",",
"e",
"in",
"self",
".",
"scanString",
"(",
"instring",
... | [
2112,
4
] | [
2135,
29
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__add__ | (self, other) |
Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement
converts them to :class:`Literal`s by default.
Example::
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
print (hello, "->", greet.parseString(hel... |
Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement
converts them to :class:`Literal`s by default. | def __add__(self, other):
"""
Implementation of + operator - returns :class:`And`. Adding strings to a ParserElement
converts them to :class:`Literal`s by default.
Example::
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
prin... | [
"def",
"__add__",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"Ellipsis",
":",
"return",
"_PendingSkip",
"(",
"self",
")",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",... | [
2137,
4
] | [
2173,
33
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__radd__ | (self, other) |
Implementation of + operator when left operand is not a :class:`ParserElement`
|
Implementation of + operator when left operand is not a :class:`ParserElement`
| def __radd__(self, other):
"""
Implementation of + operator when left operand is not a :class:`ParserElement`
"""
if other is Ellipsis:
return SkipTo(self)("_skipped*") + self
if isinstance(other, basestring):
other = self._literalStringClass(other)
... | [
"def",
"__radd__",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"Ellipsis",
":",
"return",
"SkipTo",
"(",
"self",
")",
"(",
"\"_skipped*\"",
")",
"+",
"self",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"... | [
2175,
4
] | [
2188,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__sub__ | (self, other) |
Implementation of - operator, returns :class:`And` with error stop
|
Implementation of - operator, returns :class:`And` with error stop
| def __sub__(self, other):
"""
Implementation of - operator, returns :class:`And` with error stop
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of... | [
"def",
"__sub__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",... | [
2190,
4
] | [
2200,
46
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__rsub__ | (self, other) |
Implementation of - operator when left operand is not a :class:`ParserElement`
|
Implementation of - operator when left operand is not a :class:`ParserElement`
| def __rsub__(self, other):
"""
Implementation of - operator when left operand is not a :class:`ParserElement`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combi... | [
"def",
"__rsub__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")"... | [
2202,
4
] | [
2212,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__mul__ | (self, other) |
Implementation of * operator, allows use of ``expr * 3`` in place of
``expr + expr + expr``. Expressions may also me multiplied by a 2-integer
tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
may also include ``None`` as in:
- ``expr*(n, None)`` or ... |
Implementation of * operator, allows use of ``expr * 3`` in place of
``expr + expr + expr``. Expressions may also me multiplied by a 2-integer
tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
may also include ``None`` as in:
- ``expr*(n, None)`` or ... | def __mul__(self, other):
"""
Implementation of * operator, allows use of ``expr * 3`` in place of
``expr + expr + expr``. Expressions may also me multiplied by a 2-integer
tuple, similar to ``{min, max}`` multipliers in regular expressions. Tuples
may also include ``None`` as ... | [
"def",
"__mul__",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"Ellipsis",
":",
"other",
"=",
"(",
"0",
",",
"None",
")",
"elif",
"isinstance",
"(",
"other",
",",
"tuple",
")",
"and",
"other",
"[",
":",
"1",
"]",
"==",
"(",
"Ellipsis... | [
2214,
4
] | [
2286,
18
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__or__ | (self, other) |
Implementation of | operator - returns :class:`MatchFirst`
|
Implementation of | operator - returns :class:`MatchFirst`
| def __or__(self, other):
"""
Implementation of | operator - returns :class:`MatchFirst`
"""
if other is Ellipsis:
return _PendingSkip(self, must_skip=True)
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance... | [
"def",
"__or__",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"is",
"Ellipsis",
":",
"return",
"_PendingSkip",
"(",
"self",
",",
"must_skip",
"=",
"True",
")",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
... | [
2291,
4
] | [
2304,
40
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__ror__ | (self, other) |
Implementation of | operator when left operand is not a :class:`ParserElement`
|
Implementation of | operator when left operand is not a :class:`ParserElement`
| def __ror__(self, other):
"""
Implementation of | operator when left operand is not a :class:`ParserElement`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combin... | [
"def",
"__ror__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",... | [
2306,
4
] | [
2316,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__xor__ | (self, other) |
Implementation of ^ operator - returns :class:`Or`
|
Implementation of ^ operator - returns :class:`Or`
| def __xor__(self, other):
"""
Implementation of ^ operator - returns :class:`Or`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with Pa... | [
"def",
"__xor__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",... | [
2318,
4
] | [
2328,
32
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__rxor__ | (self, other) |
Implementation of ^ operator when left operand is not a :class:`ParserElement`
|
Implementation of ^ operator when left operand is not a :class:`ParserElement`
| def __rxor__(self, other):
"""
Implementation of ^ operator when left operand is not a :class:`ParserElement`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combi... | [
"def",
"__rxor__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")"... | [
2330,
4
] | [
2340,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__and__ | (self, other) |
Implementation of & operator - returns :class:`Each`
|
Implementation of & operator - returns :class:`Each`
| def __and__(self, other):
"""
Implementation of & operator - returns :class:`Each`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combine element of type %s with ... | [
"def",
"__and__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")",... | [
2342,
4
] | [
2352,
34
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__rand__ | (self, other) |
Implementation of & operator when left operand is not a :class:`ParserElement`
|
Implementation of & operator when left operand is not a :class:`ParserElement`
| def __rand__(self, other):
"""
Implementation of & operator when left operand is not a :class:`ParserElement`
"""
if isinstance(other, basestring):
other = self._literalStringClass(other)
if not isinstance(other, ParserElement):
warnings.warn("Cannot combi... | [
"def",
"__rand__",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"self",
".",
"_literalStringClass",
"(",
"other",
")",
"if",
"not",
"isinstance",
"(",
"other",
",",
"ParserElement",
")"... | [
2354,
4
] | [
2364,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__invert__ | (self) |
Implementation of ~ operator - returns :class:`NotAny`
|
Implementation of ~ operator - returns :class:`NotAny`
| def __invert__(self):
"""
Implementation of ~ operator - returns :class:`NotAny`
"""
return NotAny(self) | [
"def",
"__invert__",
"(",
"self",
")",
":",
"return",
"NotAny",
"(",
"self",
")"
] | [
2366,
4
] | [
2370,
27
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__getitem__ | (self, key) |
use ``[]`` indexing notation as a short form for expression repetition:
- ``expr[n]`` is equivalent to ``expr*n``
- ``expr[m, n]`` is equivalent to ``expr*(m, n)``
- ``expr[n, ...]`` or ``expr[n,]`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as "... |
use ``[]`` indexing notation as a short form for expression repetition:
- ``expr[n]`` is equivalent to ``expr*n``
- ``expr[m, n]`` is equivalent to ``expr*(m, n)``
- ``expr[n, ...]`` or ``expr[n,]`` is equivalent
to ``expr*n + ZeroOrMore(expr)``
(read as "... | def __getitem__(self, key):
"""
use ``[]`` indexing notation as a short form for expression repetition:
- ``expr[n]`` is equivalent to ``expr*n``
- ``expr[m, n]`` is equivalent to ``expr*(m, n)``
- ``expr[n, ...]`` or ``expr[n,]`` is equivalent
to ``expr*n + Zero... | [
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"# convert single arg keys to tuples",
"try",
":",
"if",
"isinstance",
"(",
"key",
",",
"str",
")",
":",
"key",
"=",
"(",
"key",
",",
")",
"iter",
"(",
"key",
")",
"except",
"TypeError",
":",
"ke... | [
2377,
4
] | [
2411,
18
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.__call__ | (self, name=None) |
Shortcut for :class:`setResultsName`, with ``listAllMatches=False``.
If ``name`` is given with a trailing ``'*'`` character, then ``listAllMatches`` will be
passed as ``True``.
If ``name` is omitted, same as calling :class:`copy`.
Example::
# these are equivalent... |
Shortcut for :class:`setResultsName`, with ``listAllMatches=False``. | def __call__(self, name=None):
"""
Shortcut for :class:`setResultsName`, with ``listAllMatches=False``.
If ``name`` is given with a trailing ``'*'`` character, then ``listAllMatches`` will be
passed as ``True``.
If ``name` is omitted, same as calling :class:`copy`.
Exa... | [
"def",
"__call__",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_setResultsName",
"(",
"name",
")",
"else",
":",
"return",
"self",
".",
"copy",
"(",
")"
] | [
2413,
4
] | [
2431,
30
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.suppress | (self) |
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from
cluttering up returned output.
|
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from
cluttering up returned output.
| def suppress(self):
"""
Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from
cluttering up returned output.
"""
return Suppress(self) | [
"def",
"suppress",
"(",
"self",
")",
":",
"return",
"Suppress",
"(",
"self",
")"
] | [
2433,
4
] | [
2438,
29
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.leaveWhitespace | (self) |
Disables the skipping of whitespace before matching the characters in the
:class:`ParserElement`'s defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
|
Disables the skipping of whitespace before matching the characters in the
:class:`ParserElement`'s defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
| def leaveWhitespace(self):
"""
Disables the skipping of whitespace before matching the characters in the
:class:`ParserElement`'s defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
"""
... | [
"def",
"leaveWhitespace",
"(",
"self",
")",
":",
"self",
".",
"skipWhitespace",
"=",
"False",
"return",
"self"
] | [
2440,
4
] | [
2447,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setWhitespaceChars | (self, chars) |
Overrides the default whitespace chars
|
Overrides the default whitespace chars
| def setWhitespaceChars(self, chars):
"""
Overrides the default whitespace chars
"""
self.skipWhitespace = True
self.whiteChars = chars
self.copyDefaultWhiteChars = False
return self | [
"def",
"setWhitespaceChars",
"(",
"self",
",",
"chars",
")",
":",
"self",
".",
"skipWhitespace",
"=",
"True",
"self",
".",
"whiteChars",
"=",
"chars",
"self",
".",
"copyDefaultWhiteChars",
"=",
"False",
"return",
"self"
] | [
2449,
4
] | [
2456,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.parseWithTabs | (self) |
Overrides default behavior to expand ``<TAB>``s to spaces before parsing the input string.
Must be called before ``parseString`` when the input grammar contains elements that
match ``<TAB>`` characters.
|
Overrides default behavior to expand ``<TAB>``s to spaces before parsing the input string.
Must be called before ``parseString`` when the input grammar contains elements that
match ``<TAB>`` characters.
| def parseWithTabs(self):
"""
Overrides default behavior to expand ``<TAB>``s to spaces before parsing the input string.
Must be called before ``parseString`` when the input grammar contains elements that
match ``<TAB>`` characters.
"""
self.keepTabs = True
return ... | [
"def",
"parseWithTabs",
"(",
"self",
")",
":",
"self",
".",
"keepTabs",
"=",
"True",
"return",
"self"
] | [
2458,
4
] | [
2465,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.ignore | (self, other) |
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj'... |
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns. | def ignore(self, other):
"""
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj... | [
"def",
"ignore",
"(",
"self",
",",
"other",
")",
":",
"if",
"isinstance",
"(",
"other",
",",
"basestring",
")",
":",
"other",
"=",
"Suppress",
"(",
"other",
")",
"if",
"isinstance",
"(",
"other",
",",
"Suppress",
")",
":",
"if",
"other",
"not",
"in",... | [
2467,
4
] | [
2489,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setDebugActions | (self, startAction, successAction, exceptionAction) |
Enable display of debugging messages while doing pattern matching.
|
Enable display of debugging messages while doing pattern matching.
| def setDebugActions(self, startAction, successAction, exceptionAction):
"""
Enable display of debugging messages while doing pattern matching.
"""
self.debugActions = (startAction or _defaultStartDebugAction,
successAction or _defaultSuccessDebugAction,
... | [
"def",
"setDebugActions",
"(",
"self",
",",
"startAction",
",",
"successAction",
",",
"exceptionAction",
")",
":",
"self",
".",
"debugActions",
"=",
"(",
"startAction",
"or",
"_defaultStartDebugAction",
",",
"successAction",
"or",
"_defaultSuccessDebugAction",
",",
... | [
2491,
4
] | [
2499,
19
] | python | en | ['en', 'error', 'th'] | False |
ParserElement.setDebug | (self, flag=True) |
Enable display of debugging messages while doing pattern matching.
Set ``flag`` to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debuggin... |
Enable display of debugging messages while doing pattern matching.
Set ``flag`` to True to enable, False to disable. | def setDebug(self, flag=True):
"""
Enable display of debugging messages while doing pattern matching.
Set ``flag`` to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd... | [
"def",
"setDebug",
"(",
"self",
",",
"flag",
"=",
"True",
")",
":",
"if",
"flag",
":",
"self",
".",
"setDebugActions",
"(",
"_defaultStartDebugAction",
",",
"_defaultSuccessDebugAction",
",",
"_defaultExceptionDebugAction",
")",
"else",
":",
"self",
".",
"debug"... | [
2501,
4
] | [
2542,
19
] | python | en | ['en', 'error', 'th'] | False |
InterruptibleMixin.__init__ | (self, *args, **kwargs) |
Save the original SIGINT handler for later.
|
Save the original SIGINT handler for later.
| def __init__(self, *args, **kwargs):
# type: (List[Any], Dict[Any, Any]) -> None
"""
Save the original SIGINT handler for later.
"""
super(InterruptibleMixin, self).__init__( # type: ignore
*args,
**kwargs
)
self.original_handler = signal... | [
"def",
"__init__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# type: (List[Any], Dict[Any, Any]) -> None",
"super",
"(",
"InterruptibleMixin",
",",
"self",
")",
".",
"__init__",
"(",
"# type: ignore",
"*",
"args",
",",
"*",
"*",
"kwa... | [
75,
4
] | [
93,
55
] | python | en | ['en', 'error', 'th'] | False |
InterruptibleMixin.finish | (self) |
Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
|
Restore the original SIGINT handler after finishing. | def finish(self):
# type: () -> None
"""
Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
"""
super(InterruptibleMixin, self).finish() # type: ignore
... | [
"def",
"finish",
"(",
"self",
")",
":",
"# type: () -> None",
"super",
"(",
"InterruptibleMixin",
",",
"self",
")",
".",
"finish",
"(",
")",
"# type: ignore",
"signal",
"(",
"SIGINT",
",",
"self",
".",
"original_handler",
")"
] | [
95,
4
] | [
104,
45
] | python | en | ['en', 'error', 'th'] | False |
InterruptibleMixin.handle_sigint | (self, signum, frame) |
Call self.finish() before delegating to the original SIGINT handler.
This handler should only be in place while the progress display is
active.
|
Call self.finish() before delegating to the original SIGINT handler. | def handle_sigint(self, signum, frame): # type: ignore
"""
Call self.finish() before delegating to the original SIGINT handler.
This handler should only be in place while the progress display is
active.
"""
self.finish()
self.original_handler(signum, frame) | [
"def",
"handle_sigint",
"(",
"self",
",",
"signum",
",",
"frame",
")",
":",
"# type: ignore",
"self",
".",
"finish",
"(",
")",
"self",
".",
"original_handler",
"(",
"signum",
",",
"frame",
")"
] | [
106,
4
] | [
114,
44
] | python | en | ['en', 'error', 'th'] | False |
get_distinguished_folder_id_element | (principal, folder_id) |
Build a DistinguishedFolderId element.
:param principal: The principal (email) whose folder is requested.
:param folder_id: The distinguished folder name. (See MSDN.)
:return: XML element
|
Build a DistinguishedFolderId element. | def get_distinguished_folder_id_element(principal, folder_id):
"""
Build a DistinguishedFolderId element.
:param principal: The principal (email) whose folder is requested.
:param folder_id: The distinguished folder name. (See MSDN.)
:return: XML element
"""
return T.DistinguishedFolderId(
... | [
"def",
"get_distinguished_folder_id_element",
"(",
"principal",
",",
"folder_id",
")",
":",
"return",
"T",
".",
"DistinguishedFolderId",
"(",
"{",
"\"Id\"",
":",
"folder_id",
"}",
",",
"T",
".",
"Mailbox",
"(",
"T",
".",
"EmailAddress",
"(",
"principal",
")",
... | [
3,
0
] | [
16,
5
] | python | en | ['en', 'error', 'th'] | False |
sparse_l1_descent | (
model_fn,
x,
eps=10.0,
eps_iter=1.0,
nb_iter=20,
y=None,
targeted=False,
clip_min=None,
clip_max=None,
rand_init=False,
clip_grad=False,
grad_sparsity=99,
sanity_checks=True,
) |
This class implements a variant of Projected Gradient Descent for the l1-norm
(Tramer and Boneh 2019). The l1-norm case is more tricky than the l-inf and l2
cases covered by the ProjectedGradientDescent class, because the steepest
descent direction for the l1-norm is too sparse (it updates a single
... |
This class implements a variant of Projected Gradient Descent for the l1-norm
(Tramer and Boneh 2019). The l1-norm case is more tricky than the l-inf and l2
cases covered by the ProjectedGradientDescent class, because the steepest
descent direction for the l1-norm is too sparse (it updates a single
... | def sparse_l1_descent(
model_fn,
x,
eps=10.0,
eps_iter=1.0,
nb_iter=20,
y=None,
targeted=False,
clip_min=None,
clip_max=None,
rand_init=False,
clip_grad=False,
grad_sparsity=99,
sanity_checks=True,
):
"""
This class implements a variant of Projected Gradient D... | [
"def",
"sparse_l1_descent",
"(",
"model_fn",
",",
"x",
",",
"eps",
"=",
"10.0",
",",
"eps_iter",
"=",
"1.0",
",",
"nb_iter",
"=",
"20",
",",
"y",
"=",
"None",
",",
"targeted",
"=",
"False",
",",
"clip_min",
"=",
"None",
",",
"clip_max",
"=",
"None",
... | [
7,
0
] | [
177,
25
] | python | en | ['en', 'error', 'th'] | False |
load_csv_to_dataframe | (path_to_file, metric_name) | Load csv to dataframe and return dataframe.abs
Args:
path_to_file: relative path to csv file.
It contains the data in the format
img_identifier,value
metric_name: name of metric
Returns:
new_dataframe: dataframe with the column names "im... | Load csv to dataframe and return dataframe.abs | def load_csv_to_dataframe(path_to_file, metric_name):
"""Load csv to dataframe and return dataframe.abs
Args:
path_to_file: relative path to csv file.
It contains the data in the format
img_identifier,value
metric_name: name of metric
Return... | [
"def",
"load_csv_to_dataframe",
"(",
"path_to_file",
",",
"metric_name",
")",
":",
"new_dataframe",
"=",
"pd",
".",
"read_csv",
"(",
"path_to_file",
",",
"header",
"=",
"None",
")",
"new_dataframe",
".",
"columns",
"=",
"[",
"\"img_identifier\"",
",",
"metric_na... | [
49,
0
] | [
64,
24
] | python | en | ['en', 'ceb', 'en'] | True |
get_df_from_all_csv_files | (exp_dir) | Return one dataframe with the data from all csv-files in exp_dir.
Args:
exp_dir: directory from which to read all csv-files in
Returns:
final_df: final dataframe that contains the joined data from all csv files | Return one dataframe with the data from all csv-files in exp_dir. | def get_df_from_all_csv_files(exp_dir):
"""Return one dataframe with the data from all csv-files in exp_dir.
Args:
exp_dir: directory from which to read all csv-files in
Returns:
final_df: final dataframe that contains the joined data from all csv files"""
# list of paths to all csv ... | [
"def",
"get_df_from_all_csv_files",
"(",
"exp_dir",
")",
":",
"# list of paths to all csv files",
"csv_files_list",
"=",
"glob",
".",
"glob",
"(",
"os",
".",
"path",
".",
"join",
"(",
"exp_dir",
",",
"\"*.csv\"",
")",
")",
"# iterate through all csv files",
"for",
... | [
67,
0
] | [
90,
19
] | python | en | ['en', 'en', 'en'] | True |
get_df_from_exp_dir_list | (exp_dir_list) | Get data for one experimental condition which is saved in the directory(ies) that are contained
in the list of directories exp_dir_list.
Args:
exp_dir_list: list of paths to directories
Returns:
all_data_df: one dataframe
| Get data for one experimental condition which is saved in the directory(ies) that are contained
in the list of directories exp_dir_list. | def get_df_from_exp_dir_list(exp_dir_list):
"""Get data for one experimental condition which is saved in the directory(ies) that are contained
in the list of directories exp_dir_list.
Args:
exp_dir_list: list of paths to directories
Returns:
all_data_df: one dataframe
"""
# i... | [
"def",
"get_df_from_exp_dir_list",
"(",
"exp_dir_list",
")",
":",
"# iterate over all folders within one experimental condition",
"for",
"exp_dir_i",
",",
"exp_dir",
"in",
"enumerate",
"(",
"exp_dir_list",
")",
":",
"# get one dataframe with the values from all csv files",
"# in ... | [
93,
0
] | [
116,
22
] | python | en | ['en', 'en', 'en'] | True |
get_df_with_data_from_real_MIRCs_only | (all_data_df) | Clean the data such that only data from images which yielded MIRCs is contained
Args:
all_data_df: dataframe with data from one experimental conditions
Returns:
all_data_df_real_MIRCs: dataframe with the data of those images that yielded real MIRCs only
| Clean the data such that only data from images which yielded MIRCs is contained | def get_df_with_data_from_real_MIRCs_only(all_data_df):
"""Clean the data such that only data from images which yielded MIRCs is contained
Args:
all_data_df: dataframe with data from one experimental conditions
Returns:
all_data_df_real_MIRCs: dataframe with the data of those images that y... | [
"def",
"get_df_with_data_from_real_MIRCs_only",
"(",
"all_data_df",
")",
":",
"# create a mask to only consider those data points that contain real",
"# MIRCs. This means that the recognition gap is larger than 0.",
"mask_real_MIRCs",
"=",
"all_data_df",
".",
"rec_gap",
">",
"0",
"# cr... | [
119,
0
] | [
135,
33
] | python | en | ['en', 'en', 'en'] | True |
is_collection | (obj) | Tests if an object is a collection. | Tests if an object is a collection. | def is_collection(obj):
"""Tests if an object is a collection."""
col = getattr(obj, '__getitem__', False)
val = False if (not col) else True
if isinstance(obj, basestring):
val = False
return val | [
"def",
"is_collection",
"(",
"obj",
")",
":",
"col",
"=",
"getattr",
"(",
"obj",
",",
"'__getitem__'",
",",
"False",
")",
"val",
"=",
"False",
"if",
"(",
"not",
"col",
")",
"else",
"True",
"if",
"isinstance",
"(",
"obj",
",",
"basestring",
")",
":",
... | [
13,
0
] | [
22,
14
] | python | en | ['en', 'en', 'en'] | True |
to_python | (obj,
in_dict,
str_keys=None,
date_keys=None,
int_keys=None,
object_map=None,
bool_keys=None,
dict_keys=None,
**kwargs) | Extends a given object for API Consumption.
:param obj: Object to extend.
:param in_dict: Dict to extract data from.
:param string_keys: List of in_dict keys that will be extracted as strings.
:param date_keys: List of in_dict keys that will be extrad as datetimes.
:param object_map: Dict of {key, ... | Extends a given object for API Consumption. | def to_python(obj,
in_dict,
str_keys=None,
date_keys=None,
int_keys=None,
object_map=None,
bool_keys=None,
dict_keys=None,
**kwargs):
"""Extends a given object for API Consumption.
:param obj: Object to extend.
:param in_dict: Dict to extract data from.
:param string_key... | [
"def",
"to_python",
"(",
"obj",
",",
"in_dict",
",",
"str_keys",
"=",
"None",
",",
"date_keys",
"=",
"None",
",",
"int_keys",
"=",
"None",
",",
"object_map",
"=",
"None",
",",
"bool_keys",
"=",
"None",
",",
"dict_keys",
"=",
"None",
",",
"*",
"*",
"k... | [
27,
0
] | [
89,
14
] | python | en | ['en', 'en', 'en'] | True |
to_api | (in_dict, int_keys=None, date_keys=None, bool_keys=None) | Extends a given object for API Production. | Extends a given object for API Production. | def to_api(in_dict, int_keys=None, date_keys=None, bool_keys=None):
"""Extends a given object for API Production."""
# Cast all int_keys to int()
if int_keys:
for in_key in int_keys:
if (in_key in in_dict) and (in_dict.get(in_key, None) is not None):
in_dict[in_key] = in... | [
"def",
"to_api",
"(",
"in_dict",
",",
"int_keys",
"=",
"None",
",",
"date_keys",
"=",
"None",
",",
"bool_keys",
"=",
"None",
")",
":",
"# Cast all int_keys to int()",
"if",
"int_keys",
":",
"for",
"in_key",
"in",
"int_keys",
":",
"if",
"(",
"in_key",
"in",... | [
93,
0
] | [
125,
18
] | python | en | ['en', 'en', 'en'] | True |
usage | () | Print out a usage message | Print out a usage message | def usage():
"""Print out a usage message"""
global options
l = len(options['long'])
options['shortlist'] = [s for s in options['short'] if s is not ":"]
print("python -m behave2cucumber [-h] [-d level|--debug=level]")
for i in range(l):
print(" -{0}|--{1:20} {2}".format(options['sh... | [
"def",
"usage",
"(",
")",
":",
"global",
"options",
"l",
"=",
"len",
"(",
"options",
"[",
"'long'",
"]",
")",
"options",
"[",
"'shortlist'",
"]",
"=",
"[",
"s",
"for",
"s",
"in",
"options",
"[",
"'short'",
"]",
"if",
"s",
"is",
"not",
"\":\"",
"]... | [
45,
0
] | [
54,
118
] | python | en | ['en', 'en', 'en'] | True |
manage_event | (event_date, event_type, input_data, meta_data, api_gw_url) | Manage an event sent by CloneSquad.
>- CUSTOMIZE THIS FUNCTION TO ADD YOUR BUSINESS LOGIC -<
:param event_type
:param input_data
:param meta_data
:return True if the event can be acked. False if CloneSquad needs to send again this event (retry).
| Manage an event sent by CloneSquad. | def manage_event(event_date, event_type, input_data, meta_data, api_gw_url):
""" Manage an event sent by CloneSquad.
>- CUSTOMIZE THIS FUNCTION TO ADD YOUR BUSINESS LOGIC -<
:param event_type
:param input_data
:param meta_data
:return True if the event can be acked. False if CloneSquad needs ... | [
"def",
"manage_event",
"(",
"event_date",
",",
"event_type",
",",
"input_data",
",",
"meta_data",
",",
"api_gw_url",
")",
":",
"print",
"(",
"f\"Date: {event_date}, Event: {event_type}, InputData: {input_data}\"",
")",
"# The instance ids associated with the current event",
"# ... | [
6,
0
] | [
46,
15
] | python | en | ['en', 'en', 'en'] | True |
lambda_handler | (event, context) | Sample Lambda function reacting to CloneSquad events sent from a Lambda invoke or a SQS trigger
| Sample Lambda function reacting to CloneSquad events sent from a Lambda invoke or a SQS trigger
| def lambda_handler(event, context):
""" Sample Lambda function reacting to CloneSquad events sent from a Lambda invoke or a SQS trigger
"""
#print("Event:")
#print(json.dumps(event, default=str))
notifications = []
if "Records" in event:
for r in event["Records"]:
if r.get(... | [
"def",
"lambda_handler",
"(",
"event",
",",
"context",
")",
":",
"#print(\"Event:\")",
"#print(json.dumps(event, default=str))",
"notifications",
"=",
"[",
"]",
"if",
"\"Records\"",
"in",
"event",
":",
"for",
"r",
"in",
"event",
"[",
"\"Records\"",
"]",
":",
"if... | [
50,
0
] | [
134,
71
] | python | en | ['en', 'en', 'en'] | True |
build_narrow_filter | (narrow: Iterable[Sequence[str]]) | Changes to this function should come with corresponding changes to
BuildNarrowFilterTest. | Changes to this function should come with corresponding changes to
BuildNarrowFilterTest. | def build_narrow_filter(narrow: Iterable[Sequence[str]]) -> Callable[[Mapping[str, Any]], bool]:
"""Changes to this function should come with corresponding changes to
BuildNarrowFilterTest."""
check_supported_events_narrow_filter(narrow)
def narrow_filter(event: Mapping[str, Any]) -> bool:
mess... | [
"def",
"build_narrow_filter",
"(",
"narrow",
":",
"Iterable",
"[",
"Sequence",
"[",
"str",
"]",
"]",
")",
"->",
"Callable",
"[",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"bool",
"]",
":",
"check_supported_events_narrow_filter",
"(",
"narrow",... | [
58,
0
] | [
98,
24
] | python | en | ['en', 'en', 'en'] | True |
format_email_subject | (email_subject: str) |
Escape CR and LF characters.
|
Escape CR and LF characters.
| def format_email_subject(email_subject: str) -> str:
"""
Escape CR and LF characters.
"""
return email_subject.replace("\n", "\\n").replace("\r", "\\r") | [
"def",
"format_email_subject",
"(",
"email_subject",
":",
"str",
")",
"->",
"str",
":",
"return",
"email_subject",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\\\\n\"",
")",
".",
"replace",
"(",
"\"\\r\"",
",",
"\"\\\\r\"",
")"
] | [
15,
0
] | [
19,
66
] | python | en | ['en', 'error', 'th'] | False |
TreeWalker.__init__ | (self, tree) | Creates a TreeWalker
:arg tree: the tree to walk
| Creates a TreeWalker | def __init__(self, tree):
"""Creates a TreeWalker
:arg tree: the tree to walk
"""
self.tree = tree | [
"def",
"__init__",
"(",
"self",
",",
"tree",
")",
":",
"self",
".",
"tree",
"=",
"tree"
] | [
26,
4
] | [
32,
24
] | python | en | ['en', 'et', 'en'] | True |
TreeWalker.error | (self, msg) | Generates an error token with the given message
:arg msg: the error message
:returns: SerializeError token
| Generates an error token with the given message | def error(self, msg):
"""Generates an error token with the given message
:arg msg: the error message
:returns: SerializeError token
"""
return {"type": "SerializeError", "data": msg} | [
"def",
"error",
"(",
"self",
",",
"msg",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"SerializeError\"",
",",
"\"data\"",
":",
"msg",
"}"
] | [
37,
4
] | [
45,
54
] | python | en | ['en', 'en', 'en'] | True |
TreeWalker.emptyTag | (self, namespace, name, attrs, hasChildren=False) | Generates an EmptyTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:arg hasChildren: whether or not to yield a SerializationError because
this tag shouldn't have ch... | Generates an EmptyTag token | def emptyTag(self, namespace, name, attrs, hasChildren=False):
"""Generates an EmptyTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:arg hasChildren: whether or not to... | [
"def",
"emptyTag",
"(",
"self",
",",
"namespace",
",",
"name",
",",
"attrs",
",",
"hasChildren",
"=",
"False",
")",
":",
"yield",
"{",
"\"type\"",
":",
"\"EmptyTag\"",
",",
"\"name\"",
":",
"name",
",",
"\"namespace\"",
":",
"namespace",
",",
"\"data\"",
... | [
47,
4
] | [
66,
57
] | python | de | ['en', 'de', 'nl'] | False |
TreeWalker.startTag | (self, namespace, name, attrs) | Generates a StartTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:returns: StartTag token
| Generates a StartTag token | def startTag(self, namespace, name, attrs):
"""Generates a StartTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:arg attrs: the attributes of the element as a dict
:returns: StartTag token
"""
return {"... | [
"def",
"startTag",
"(",
"self",
",",
"namespace",
",",
"name",
",",
"attrs",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"StartTag\"",
",",
"\"name\"",
":",
"name",
",",
"\"namespace\"",
":",
"namespace",
",",
"\"data\"",
":",
"attrs",
"}"
] | [
68,
4
] | [
83,
30
] | python | en | ['en', 'de', 'en'] | True |
TreeWalker.endTag | (self, namespace, name) | Generates an EndTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:returns: EndTag token
| Generates an EndTag token | def endTag(self, namespace, name):
"""Generates an EndTag token
:arg namespace: the namespace of the token--can be ``None``
:arg name: the name of the element
:returns: EndTag token
"""
return {"type": "EndTag",
"name": name,
"namespace... | [
"def",
"endTag",
"(",
"self",
",",
"namespace",
",",
"name",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"EndTag\"",
",",
"\"name\"",
":",
"name",
",",
"\"namespace\"",
":",
"namespace",
"}"
] | [
85,
4
] | [
97,
39
] | python | en | ['en', 'en', 'nl'] | True |
TreeWalker.text | (self, data) | Generates SpaceCharacters and Characters tokens
Depending on what's in the data, this generates one or more
``SpaceCharacters`` and ``Characters`` tokens.
For example:
>>> from html5lib.treewalkers.base import TreeWalker
>>> # Give it an empty tree just so it instantia... | Generates SpaceCharacters and Characters tokens | def text(self, data):
"""Generates SpaceCharacters and Characters tokens
Depending on what's in the data, this generates one or more
``SpaceCharacters`` and ``Characters`` tokens.
For example:
>>> from html5lib.treewalkers.base import TreeWalker
>>> # Give it a... | [
"def",
"text",
"(",
"self",
",",
"data",
")",
":",
"data",
"=",
"data",
"middle",
"=",
"data",
".",
"lstrip",
"(",
"spaceCharacters",
")",
"left",
"=",
"data",
"[",
":",
"len",
"(",
"data",
")",
"-",
"len",
"(",
"middle",
")",
"]",
"if",
"left",
... | [
99,
4
] | [
135,
60
] | python | en | ['en', 'en', 'en'] | True |
TreeWalker.comment | (self, data) | Generates a Comment token
:arg data: the comment
:returns: Comment token
| Generates a Comment token | def comment(self, data):
"""Generates a Comment token
:arg data: the comment
:returns: Comment token
"""
return {"type": "Comment", "data": data} | [
"def",
"comment",
"(",
"self",
",",
"data",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"Comment\"",
",",
"\"data\"",
":",
"data",
"}"
] | [
137,
4
] | [
145,
48
] | python | en | ['en', 'en', 'en'] | True |
TreeWalker.doctype | (self, name, publicId=None, systemId=None) | Generates a Doctype token
:arg name:
:arg publicId:
:arg systemId:
:returns: the Doctype token
| Generates a Doctype token | def doctype(self, name, publicId=None, systemId=None):
"""Generates a Doctype token
:arg name:
:arg publicId:
:arg systemId:
:returns: the Doctype token
"""
return {"type": "Doctype",
"name": name,
"publicId": publicId,
... | [
"def",
"doctype",
"(",
"self",
",",
"name",
",",
"publicId",
"=",
"None",
",",
"systemId",
"=",
"None",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"Doctype\"",
",",
"\"name\"",
":",
"name",
",",
"\"publicId\"",
":",
"publicId",
",",
"\"systemId\"",
":",... | [
147,
4
] | [
162,
37
] | python | en | ['en', 'en', 'en'] | True |
TreeWalker.entity | (self, name) | Generates an Entity token
:arg name: the entity name
:returns: an Entity token
| Generates an Entity token | def entity(self, name):
"""Generates an Entity token
:arg name: the entity name
:returns: an Entity token
"""
return {"type": "Entity", "name": name} | [
"def",
"entity",
"(",
"self",
",",
"name",
")",
":",
"return",
"{",
"\"type\"",
":",
"\"Entity\"",
",",
"\"name\"",
":",
"name",
"}"
] | [
164,
4
] | [
172,
47
] | python | en | ['en', 'en', 'nl'] | True |
TreeWalker.unknown | (self, nodeType) | Handles unknown node types | Handles unknown node types | def unknown(self, nodeType):
"""Handles unknown node types"""
return self.error("Unknown node type: " + nodeType) | [
"def",
"unknown",
"(",
"self",
",",
"nodeType",
")",
":",
"return",
"self",
".",
"error",
"(",
"\"Unknown node type: \"",
"+",
"nodeType",
")"
] | [
174,
4
] | [
176,
59
] | python | en | ['en', 'de', 'en'] | True |
PasswordResetTokenGenerator.make_token | (self, user) |
Return a token that can be used once to do a password reset
for the given user.
|
Return a token that can be used once to do a password reset
for the given user.
| def make_token(self, user):
"""
Return a token that can be used once to do a password reset
for the given user.
"""
return self._make_token_with_timestamp(user, self._num_days(self._today())) | [
"def",
"make_token",
"(",
"self",
",",
"user",
")",
":",
"return",
"self",
".",
"_make_token_with_timestamp",
"(",
"user",
",",
"self",
".",
"_num_days",
"(",
"self",
".",
"_today",
"(",
")",
")",
")"
] | [
15,
4
] | [
20,
83
] | python | en | ['en', 'error', 'th'] | False |
PasswordResetTokenGenerator.check_token | (self, user, token) |
Check that a password reset token is correct for a given user.
|
Check that a password reset token is correct for a given user.
| def check_token(self, user, token):
"""
Check that a password reset token is correct for a given user.
"""
if not (user and token):
return False
# Parse the token
try:
ts_b36, _ = token.split("-")
except ValueError:
return False... | [
"def",
"check_token",
"(",
"self",
",",
"user",
",",
"token",
")",
":",
"if",
"not",
"(",
"user",
"and",
"token",
")",
":",
"return",
"False",
"# Parse the token",
"try",
":",
"ts_b36",
",",
"_",
"=",
"token",
".",
"split",
"(",
"\"-\"",
")",
"except... | [
22,
4
] | [
51,
19
] | python | en | ['en', 'error', 'th'] | False |
PasswordResetTokenGenerator._make_hash_value | (self, user, timestamp) |
Hash the user's primary key and some user state that's sure to change
after a password reset to produce a token that invalidated when it's
used:
1. The password field will change upon a password reset (even if the
same password is chosen, due to password salting).
2. ... |
Hash the user's primary key and some user state that's sure to change
after a password reset to produce a token that invalidated when it's
used:
1. The password field will change upon a password reset (even if the
same password is chosen, due to password salting).
2. ... | def _make_hash_value(self, user, timestamp):
"""
Hash the user's primary key and some user state that's sure to change
after a password reset to produce a token that invalidated when it's
used:
1. The password field will change upon a password reset (even if the
same p... | [
"def",
"_make_hash_value",
"(",
"self",
",",
"user",
",",
"timestamp",
")",
":",
"# Truncate microseconds so that tokens are consistent even if the",
"# database doesn't support microseconds.",
"login_timestamp",
"=",
"''",
"if",
"user",
".",
"last_login",
"is",
"None",
"el... | [
64,
4
] | [
82,
83
] | python | en | ['en', 'error', 'th'] | False |
TestMissedMessages.test_multiple_stream_messages_and_mentions | (self) | Subject should be stream name and topic as usual. | Subject should be stream name and topic as usual. | def test_multiple_stream_messages_and_mentions(self) -> None:
"""Subject should be stream name and topic as usual."""
hamlet = self.example_user("hamlet")
msg_id_1 = self.send_stream_message(self.example_user("iago"), "Denmark", "Regular message")
msg_id_2 = self.send_stream_message(
... | [
"def",
"test_multiple_stream_messages_and_mentions",
"(",
"self",
")",
"->",
"None",
":",
"hamlet",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"msg_id_1",
"=",
"self",
".",
"send_stream_message",
"(",
"self",
".",
"example_user",
"(",
"\"iago\"",
... | [
954,
4
] | [
971,
63
] | python | en | ['en', 'en', 'en'] | True |
TestMissedMessages.test_stream_mentions_multiple_people | (self) | Subject should be stream name and topic as usual. | Subject should be stream name and topic as usual. | def test_stream_mentions_multiple_people(self) -> None:
"""Subject should be stream name and topic as usual."""
hamlet = self.example_user("hamlet")
msg_id_1 = self.send_stream_message(
self.example_user("iago"), "Denmark", "@**King Hamlet**"
)
msg_id_2 = self.send_st... | [
"def",
"test_stream_mentions_multiple_people",
"(",
"self",
")",
"->",
"None",
":",
"hamlet",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"msg_id_1",
"=",
"self",
".",
"send_stream_message",
"(",
"self",
".",
"example_user",
"(",
"\"iago\"",
")",
... | [
1004,
4
] | [
1027,
63
] | python | en | ['en', 'en', 'en'] | True |
TestMissedMessages.test_multiple_stream_messages_different_topics | (self) | Should receive separate emails for each topic within a stream. | Should receive separate emails for each topic within a stream. | def test_multiple_stream_messages_different_topics(self) -> None:
"""Should receive separate emails for each topic within a stream."""
hamlet = self.example_user("hamlet")
msg_id_1 = self.send_stream_message(self.example_user("othello"), "Denmark", "Message1")
msg_id_2 = self.send_stream... | [
"def",
"test_multiple_stream_messages_different_topics",
"(",
"self",
")",
"->",
"None",
":",
"hamlet",
"=",
"self",
".",
"example_user",
"(",
"\"hamlet\"",
")",
"msg_id_1",
"=",
"self",
".",
"send_stream_message",
"(",
"self",
".",
"example_user",
"(",
"\"othello... | [
1029,
4
] | [
1047,
62
] | python | en | ['en', 'en', 'en'] | True |
CacheControlAdapter.send | (self, request, cacheable_methods=None, **kw) |
Send a request. Use the request information to see if it
exists in the cache and cache the response if we need to and can.
|
Send a request. Use the request information to see if it
exists in the cache and cache the response if we need to and can.
| def send(self, request, cacheable_methods=None, **kw):
"""
Send a request. Use the request information to see if it
exists in the cache and cache the response if we need to and can.
"""
cacheable = cacheable_methods or self.cacheable_methods
if request.method in cacheable... | [
"def",
"send",
"(",
"self",
",",
"request",
",",
"cacheable_methods",
"=",
"None",
",",
"*",
"*",
"kw",
")",
":",
"cacheable",
"=",
"cacheable_methods",
"or",
"self",
".",
"cacheable_methods",
"if",
"request",
".",
"method",
"in",
"cacheable",
":",
"try",
... | [
35,
4
] | [
54,
19
] | python | en | ['en', 'error', 'th'] | False |
CacheControlAdapter.build_response | (
self, request, response, from_cache=False, cacheable_methods=None
) |
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
|
Build a response by making a request or using the cache. | def build_response(
self, request, response, from_cache=False, cacheable_methods=None
):
"""
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
"""
cacheable = cacheable_methods o... | [
"def",
"build_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"from_cache",
"=",
"False",
",",
"cacheable_methods",
"=",
"None",
")",
":",
"cacheable",
"=",
"cacheable_methods",
"or",
"self",
".",
"cacheable_methods",
"if",
"not",
"from_cache",
"... | [
56,
4
] | [
128,
19
] | python | en | ['en', 'error', 'th'] | False |
url_params_from_lookup_dict | (lookups) |
Convert the type of lookups specified in a ForeignKey limit_choices_to
attribute to a dictionary of query parameters
|
Convert the type of lookups specified in a ForeignKey limit_choices_to
attribute to a dictionary of query parameters
| def url_params_from_lookup_dict(lookups):
"""
Convert the type of lookups specified in a ForeignKey limit_choices_to
attribute to a dictionary of query parameters
"""
params = {}
if lookups and hasattr(lookups, 'items'):
for k, v in lookups.items():
if callable(v):
... | [
"def",
"url_params_from_lookup_dict",
"(",
"lookups",
")",
":",
"params",
"=",
"{",
"}",
"if",
"lookups",
"and",
"hasattr",
"(",
"lookups",
",",
"'items'",
")",
":",
"for",
"k",
",",
"v",
"in",
"lookups",
".",
"items",
"(",
")",
":",
"if",
"callable",
... | [
104,
0
] | [
121,
17
] | python | en | ['en', 'error', 'th'] | False |
AutocompleteMixin.build_attrs | (self, base_attrs, extra_attrs=None) |
Set select2's AJAX attributes.
Attributes can be set using the html5 data attribute.
Nested attributes require a double dash as per
https://select2.org/configuration/data-attributes#nested-subkey-options
|
Set select2's AJAX attributes. | def build_attrs(self, base_attrs, extra_attrs=None):
"""
Set select2's AJAX attributes.
Attributes can be set using the html5 data attribute.
Nested attributes require a double dash as per
https://select2.org/configuration/data-attributes#nested-subkey-options
"""
... | [
"def",
"build_attrs",
"(",
"self",
",",
"base_attrs",
",",
"extra_attrs",
"=",
"None",
")",
":",
"attrs",
"=",
"super",
"(",
")",
".",
"build_attrs",
"(",
"base_attrs",
",",
"extra_attrs",
"=",
"extra_attrs",
")",
"attrs",
".",
"setdefault",
"(",
"'class'"... | [
400,
4
] | [
420,
20
] | python | en | ['en', 'error', 'th'] | False |
AutocompleteMixin.optgroups | (self, name, value, attr=None) | Return selected options based on the ModelChoiceIterator. | Return selected options based on the ModelChoiceIterator. | def optgroups(self, name, value, attr=None):
"""Return selected options based on the ModelChoiceIterator."""
default = (None, [], 0)
groups = [default]
has_selected = False
selected_choices = {
str(v) for v in value
if str(v) not in self.choices.field.empt... | [
"def",
"optgroups",
"(",
"self",
",",
"name",
",",
"value",
",",
"attr",
"=",
"None",
")",
":",
"default",
"=",
"(",
"None",
",",
"[",
"]",
",",
"0",
")",
"groups",
"=",
"[",
"default",
"]",
"has_selected",
"=",
"False",
"selected_choices",
"=",
"{... | [
422,
4
] | [
446,
21
] | python | en | ['en', 'en', 'en'] | True |
instrumented_test_render | (self, context) |
An instrumented Template render method, providing a signal that can be
intercepted by the test Client.
|
An instrumented Template render method, providing a signal that can be
intercepted by the test Client.
| def instrumented_test_render(self, context):
"""
An instrumented Template render method, providing a signal that can be
intercepted by the test Client.
"""
template_rendered.send(sender=self, template=self, context=context)
return self.nodelist.render(context) | [
"def",
"instrumented_test_render",
"(",
"self",
",",
"context",
")",
":",
"template_rendered",
".",
"send",
"(",
"sender",
"=",
"self",
",",
"template",
"=",
"self",
",",
"context",
"=",
"context",
")",
"return",
"self",
".",
"nodelist",
".",
"render",
"("... | [
88,
0
] | [
94,
40
] | python | en | ['en', 'error', 'th'] | False |
setup_test_environment | (debug=None) |
Perform global pre-test setup, such as installing the instrumented template
renderer and setting the email backend to the locmem email backend.
|
Perform global pre-test setup, such as installing the instrumented template
renderer and setting the email backend to the locmem email backend.
| def setup_test_environment(debug=None):
"""
Perform global pre-test setup, such as installing the instrumented template
renderer and setting the email backend to the locmem email backend.
"""
if hasattr(_TestState, 'saved_data'):
# Executing this function twice would overwrite the saved valu... | [
"def",
"setup_test_environment",
"(",
"debug",
"=",
"None",
")",
":",
"if",
"hasattr",
"(",
"_TestState",
",",
"'saved_data'",
")",
":",
"# Executing this function twice would overwrite the saved values.",
"raise",
"RuntimeError",
"(",
"\"setup_test_environment() was already ... | [
101,
0
] | [
134,
16
] | python | en | ['en', 'error', 'th'] | False |
teardown_test_environment | () |
Perform any global post-test teardown, such as restoring the original
template renderer and restoring the email sending functions.
|
Perform any global post-test teardown, such as restoring the original
template renderer and restoring the email sending functions.
| def teardown_test_environment():
"""
Perform any global post-test teardown, such as restoring the original
template renderer and restoring the email sending functions.
"""
saved_data = _TestState.saved_data
settings.ALLOWED_HOSTS = saved_data.allowed_hosts
settings.DEBUG = saved_data.debug
... | [
"def",
"teardown_test_environment",
"(",
")",
":",
"saved_data",
"=",
"_TestState",
".",
"saved_data",
"settings",
".",
"ALLOWED_HOSTS",
"=",
"saved_data",
".",
"allowed_hosts",
"settings",
".",
"DEBUG",
"=",
"saved_data",
".",
"debug",
"settings",
".",
"EMAIL_BAC... | [
137,
0
] | [
150,
19
] | python | en | ['en', 'error', 'th'] | False |
setup_databases | (verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, aliases=None, **kwargs) | Create the test databases. | Create the test databases. | def setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, aliases=None, **kwargs):
"""Create the test databases."""
test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases)
old_names = []
for db_name, aliases in test_databases.values():
first_al... | [
"def",
"setup_databases",
"(",
"verbosity",
",",
"interactive",
",",
"keepdb",
"=",
"False",
",",
"debug_sql",
"=",
"False",
",",
"parallel",
"=",
"0",
",",
"aliases",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"test_databases",
",",
"mirrored_aliases... | [
153,
0
] | [
194,
20
] | python | en | ['en', 'en', 'en'] | True |
dependency_ordered | (test_databases, dependencies) |
Reorder test_databases into an order that honors the dependencies
described in TEST[DEPENDENCIES].
|
Reorder test_databases into an order that honors the dependencies
described in TEST[DEPENDENCIES].
| def dependency_ordered(test_databases, dependencies):
"""
Reorder test_databases into an order that honors the dependencies
described in TEST[DEPENDENCIES].
"""
ordered_test_databases = []
resolved_databases = set()
# Maps db signature to dependencies of all its aliases
dependencies_map... | [
"def",
"dependency_ordered",
"(",
"test_databases",
",",
"dependencies",
")",
":",
"ordered_test_databases",
"=",
"[",
"]",
"resolved_databases",
"=",
"set",
"(",
")",
"# Maps db signature to dependencies of all its aliases",
"dependencies_map",
"=",
"{",
"}",
"# Check th... | [
197,
0
] | [
236,
33
] | python | en | ['en', 'error', 'th'] | False |
get_unique_databases_and_mirrors | (aliases=None) |
Figure out which databases actually need to be created.
Deduplicate entries in DATABASES that correspond the same database or are
configured as test mirrors.
Return two values:
- test_databases: ordered mapping of signatures to (name, list of aliases)
where all aliases share... |
Figure out which databases actually need to be created. | def get_unique_databases_and_mirrors(aliases=None):
"""
Figure out which databases actually need to be created.
Deduplicate entries in DATABASES that correspond the same database or are
configured as test mirrors.
Return two values:
- test_databases: ordered mapping of signatures to (name, lis... | [
"def",
"get_unique_databases_and_mirrors",
"(",
"aliases",
"=",
"None",
")",
":",
"if",
"aliases",
"is",
"None",
":",
"aliases",
"=",
"connections",
"mirrored_aliases",
"=",
"{",
"}",
"test_databases",
"=",
"{",
"}",
"dependencies",
"=",
"{",
"}",
"default_sig... | [
239,
0
] | [
282,
43
] | python | en | ['en', 'error', 'th'] | False |
teardown_databases | (old_config, verbosity, parallel=0, keepdb=False) | Destroy all the non-mirror databases. | Destroy all the non-mirror databases. | def teardown_databases(old_config, verbosity, parallel=0, keepdb=False):
"""Destroy all the non-mirror databases."""
for connection, old_name, destroy in old_config:
if destroy:
if parallel > 1:
for index in range(parallel):
connection.creation.destroy_tes... | [
"def",
"teardown_databases",
"(",
"old_config",
",",
"verbosity",
",",
"parallel",
"=",
"0",
",",
"keepdb",
"=",
"False",
")",
":",
"for",
"connection",
",",
"old_name",
",",
"destroy",
"in",
"old_config",
":",
"if",
"destroy",
":",
"if",
"parallel",
">",
... | [
285,
0
] | [
296,
76
] | python | en | ['en', 'en', 'en'] | True |
compare_xml | (want, got) |
Try to do a 'xml-comparison' of want and got. Plain string comparison
doesn't always work because, for example, attribute ordering should not be
important. Ignore comment nodes, document type node, and leading and
trailing whitespaces.
Based on https://github.com/lxml/lxml/blob/master/src/lxml/doc... |
Try to do a 'xml-comparison' of want and got. Plain string comparison
doesn't always work because, for example, attribute ordering should not be
important. Ignore comment nodes, document type node, and leading and
trailing whitespaces. | def compare_xml(want, got):
"""
Try to do a 'xml-comparison' of want and got. Plain string comparison
doesn't always work because, for example, attribute ordering should not be
important. Ignore comment nodes, document type node, and leading and
trailing whitespaces.
Based on https://github.com... | [
"def",
"compare_xml",
"(",
"want",
",",
"got",
")",
":",
"_norm_whitespace_re",
"=",
"re",
".",
"compile",
"(",
"r'[ \\t\\n][ \\t\\n]+'",
")",
"def",
"norm_whitespace",
"(",
"v",
")",
":",
"return",
"_norm_whitespace_re",
".",
"sub",
"(",
"' '",
",",
"v",
... | [
535,
0
] | [
595,
45
] | python | en | ['en', 'error', 'th'] | False |
extend_sys_path | (*paths) | Context manager to temporarily add paths to sys.path. | Context manager to temporarily add paths to sys.path. | def extend_sys_path(*paths):
"""Context manager to temporarily add paths to sys.path."""
_orig_sys_path = sys.path[:]
sys.path.extend(paths)
try:
yield
finally:
sys.path = _orig_sys_path | [
"def",
"extend_sys_path",
"(",
"*",
"paths",
")",
":",
"_orig_sys_path",
"=",
"sys",
".",
"path",
"[",
":",
"]",
"sys",
".",
"path",
".",
"extend",
"(",
"paths",
")",
"try",
":",
"yield",
"finally",
":",
"sys",
".",
"path",
"=",
"_orig_sys_path"
] | [
668,
0
] | [
675,
33
] | python | en | ['en', 'en', 'en'] | True |
isolate_lru_cache | (lru_cache_object) | Clear the cache of an LRU cache object on entering and exiting. | Clear the cache of an LRU cache object on entering and exiting. | def isolate_lru_cache(lru_cache_object):
"""Clear the cache of an LRU cache object on entering and exiting."""
lru_cache_object.cache_clear()
try:
yield
finally:
lru_cache_object.cache_clear() | [
"def",
"isolate_lru_cache",
"(",
"lru_cache_object",
")",
":",
"lru_cache_object",
".",
"cache_clear",
"(",
")",
"try",
":",
"yield",
"finally",
":",
"lru_cache_object",
".",
"cache_clear",
"(",
")"
] | [
679,
0
] | [
685,
38
] | python | en | ['en', 'en', 'en'] | True |
captured_output | (stream_name) | Return a context manager used by captured_stdout/stdin/stderr
that temporarily replaces the sys stream *stream_name* with a StringIO.
Note: This function and the following ``captured_std*`` are copied
from CPython's ``test.support`` module. | Return a context manager used by captured_stdout/stdin/stderr
that temporarily replaces the sys stream *stream_name* with a StringIO. | def captured_output(stream_name):
"""Return a context manager used by captured_stdout/stdin/stderr
that temporarily replaces the sys stream *stream_name* with a StringIO.
Note: This function and the following ``captured_std*`` are copied
from CPython's ``test.support`` module."""
orig_stdout ... | [
"def",
"captured_output",
"(",
"stream_name",
")",
":",
"orig_stdout",
"=",
"getattr",
"(",
"sys",
",",
"stream_name",
")",
"setattr",
"(",
"sys",
",",
"stream_name",
",",
"StringIO",
"(",
")",
")",
"try",
":",
"yield",
"getattr",
"(",
"sys",
",",
"strea... | [
689,
0
] | [
700,
46
] | python | en | ['en', 'en', 'en'] | True |
captured_stdout | () | Capture the output of sys.stdout:
with captured_stdout() as stdout:
print("hello")
self.assertEqual(stdout.getvalue(), "hello\n")
| Capture the output of sys.stdout: | def captured_stdout():
"""Capture the output of sys.stdout:
with captured_stdout() as stdout:
print("hello")
self.assertEqual(stdout.getvalue(), "hello\n")
"""
return captured_output("stdout") | [
"def",
"captured_stdout",
"(",
")",
":",
"return",
"captured_output",
"(",
"\"stdout\"",
")"
] | [
703,
0
] | [
710,
36
] | python | en | ['en', 'en', 'en'] | True |
captured_stderr | () | Capture the output of sys.stderr:
with captured_stderr() as stderr:
print("hello", file=sys.stderr)
self.assertEqual(stderr.getvalue(), "hello\n")
| Capture the output of sys.stderr: | def captured_stderr():
"""Capture the output of sys.stderr:
with captured_stderr() as stderr:
print("hello", file=sys.stderr)
self.assertEqual(stderr.getvalue(), "hello\n")
"""
return captured_output("stderr") | [
"def",
"captured_stderr",
"(",
")",
":",
"return",
"captured_output",
"(",
"\"stderr\"",
")"
] | [
713,
0
] | [
720,
36
] | python | en | ['en', 'en', 'en'] | True |
captured_stdin | () | Capture the input to sys.stdin:
with captured_stdin() as stdin:
stdin.write('hello\n')
stdin.seek(0)
# call test code that consumes from sys.stdin
captured = input()
self.assertEqual(captured, "hello")
| Capture the input to sys.stdin: | def captured_stdin():
"""Capture the input to sys.stdin:
with captured_stdin() as stdin:
stdin.write('hello\n')
stdin.seek(0)
# call test code that consumes from sys.stdin
captured = input()
self.assertEqual(captured, "hello")
"""
return captured_ou... | [
"def",
"captured_stdin",
"(",
")",
":",
"return",
"captured_output",
"(",
"\"stdin\"",
")"
] | [
723,
0
] | [
733,
35
] | python | en | ['en', 'en', 'en'] | True |
freeze_time | (t) |
Context manager to temporarily freeze time.time(). This temporarily
modifies the time function of the time module. Modules which import the
time function directly (e.g. `from time import time`) won't be affected
This isn't meant as a public API, but helps reduce some repetitive code in
Django's tes... |
Context manager to temporarily freeze time.time(). This temporarily
modifies the time function of the time module. Modules which import the
time function directly (e.g. `from time import time`) won't be affected
This isn't meant as a public API, but helps reduce some repetitive code in
Django's tes... | def freeze_time(t):
"""
Context manager to temporarily freeze time.time(). This temporarily
modifies the time function of the time module. Modules which import the
time function directly (e.g. `from time import time`) won't be affected
This isn't meant as a public API, but helps reduce some repetiti... | [
"def",
"freeze_time",
"(",
"t",
")",
":",
"_real_time",
"=",
"time",
".",
"time",
"time",
".",
"time",
"=",
"lambda",
":",
"t",
"try",
":",
"yield",
"finally",
":",
"time",
".",
"time",
"=",
"_real_time"
] | [
737,
0
] | [
750,
30
] | python | en | ['en', 'error', 'th'] | False |
require_jinja2 | (test_func) |
Decorator to enable a Jinja2 template engine in addition to the regular
Django template engine for a test or skip it if Jinja2 isn't available.
|
Decorator to enable a Jinja2 template engine in addition to the regular
Django template engine for a test or skip it if Jinja2 isn't available.
| def require_jinja2(test_func):
"""
Decorator to enable a Jinja2 template engine in addition to the regular
Django template engine for a test or skip it if Jinja2 isn't available.
"""
test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func)
return override_settings(TEMPLATES=[{
... | [
"def",
"require_jinja2",
"(",
"test_func",
")",
":",
"test_func",
"=",
"skipIf",
"(",
"jinja2",
"is",
"None",
",",
"\"this test requires jinja2\"",
")",
"(",
"test_func",
")",
"return",
"override_settings",
"(",
"TEMPLATES",
"=",
"[",
"{",
"'BACKEND'",
":",
"'... | [
753,
0
] | [
766,
18
] | python | en | ['en', 'error', 'th'] | False |
tag | (*tags) | Decorator to add tags to a test class or method. | Decorator to add tags to a test class or method. | def tag(*tags):
"""Decorator to add tags to a test class or method."""
def decorator(obj):
if hasattr(obj, 'tags'):
obj.tags = obj.tags.union(tags)
else:
setattr(obj, 'tags', set(tags))
return obj
return decorator | [
"def",
"tag",
"(",
"*",
"tags",
")",
":",
"def",
"decorator",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'tags'",
")",
":",
"obj",
".",
"tags",
"=",
"obj",
".",
"tags",
".",
"union",
"(",
"tags",
")",
"else",
":",
"setattr",
"(",
... | [
828,
0
] | [
836,
20
] | python | en | ['en', 'en', 'en'] | True |
register_lookup | (field, *lookups, lookup_name=None) |
Context manager to temporarily register lookups on a model field using
lookup_name (or the lookup's lookup_name if not provided).
|
Context manager to temporarily register lookups on a model field using
lookup_name (or the lookup's lookup_name if not provided).
| def register_lookup(field, *lookups, lookup_name=None):
"""
Context manager to temporarily register lookups on a model field using
lookup_name (or the lookup's lookup_name if not provided).
"""
try:
for lookup in lookups:
field.register_lookup(lookup, lookup_name)
yield
... | [
"def",
"register_lookup",
"(",
"field",
",",
"*",
"lookups",
",",
"lookup_name",
"=",
"None",
")",
":",
"try",
":",
"for",
"lookup",
"in",
"lookups",
":",
"field",
".",
"register_lookup",
"(",
"lookup",
",",
"lookup_name",
")",
"yield",
"finally",
":",
"... | [
840,
0
] | [
851,
57
] | python | en | ['en', 'error', 'th'] | False |
ContextList.keys | (self) |
Flattened keys of subcontexts.
|
Flattened keys of subcontexts.
| def keys(self):
"""
Flattened keys of subcontexts.
"""
return set(chain.from_iterable(d for subcontext in self for d in subcontext)) | [
"def",
"keys",
"(",
"self",
")",
":",
"return",
"set",
"(",
"chain",
".",
"from_iterable",
"(",
"d",
"for",
"subcontext",
"in",
"self",
"for",
"d",
"in",
"subcontext",
")",
")"
] | [
81,
4
] | [
85,
85
] | python | en | ['en', 'error', 'th'] | False |
inject_into_urllib3 | () | Monkey-patch urllib3 with PyOpenSSL-backed SSL-support. | Monkey-patch urllib3 with PyOpenSSL-backed SSL-support. | def inject_into_urllib3():
"Monkey-patch urllib3 with PyOpenSSL-backed SSL-support."
_validate_dependencies_met()
util.SSLContext = PyOpenSSLContext
util.ssl_.SSLContext = PyOpenSSLContext
util.HAS_SNI = HAS_SNI
util.ssl_.HAS_SNI = HAS_SNI
util.IS_PYOPENSSL = True
util.ssl_.IS_PYOPENSS... | [
"def",
"inject_into_urllib3",
"(",
")",
":",
"_validate_dependencies_met",
"(",
")",
"util",
".",
"SSLContext",
"=",
"PyOpenSSLContext",
"util",
".",
"ssl_",
".",
"SSLContext",
"=",
"PyOpenSSLContext",
"util",
".",
"HAS_SNI",
"=",
"HAS_SNI",
"util",
".",
"ssl_",... | [
114,
0
] | [
124,
33
] | python | en | ['en', 'en', 'en'] | True |
extract_from_urllib3 | () | Undo monkey-patching by :func:`inject_into_urllib3`. | Undo monkey-patching by :func:`inject_into_urllib3`. | def extract_from_urllib3():
"Undo monkey-patching by :func:`inject_into_urllib3`."
util.SSLContext = orig_util_SSLContext
util.ssl_.SSLContext = orig_util_SSLContext
util.HAS_SNI = orig_util_HAS_SNI
util.ssl_.HAS_SNI = orig_util_HAS_SNI
util.IS_PYOPENSSL = False
util.ssl_.IS_PYOPENSSL = Fal... | [
"def",
"extract_from_urllib3",
"(",
")",
":",
"util",
".",
"SSLContext",
"=",
"orig_util_SSLContext",
"util",
".",
"ssl_",
".",
"SSLContext",
"=",
"orig_util_SSLContext",
"util",
".",
"HAS_SNI",
"=",
"orig_util_HAS_SNI",
"util",
".",
"ssl_",
".",
"HAS_SNI",
"=",... | [
127,
0
] | [
135,
34
] | python | en | ['en', 'ny', 'sw'] | False |
_validate_dependencies_met | () |
Verifies that PyOpenSSL's package-level dependencies have been met.
Throws `ImportError` if they are not met.
|
Verifies that PyOpenSSL's package-level dependencies have been met.
Throws `ImportError` if they are not met.
| def _validate_dependencies_met():
"""
Verifies that PyOpenSSL's package-level dependencies have been met.
Throws `ImportError` if they are not met.
"""
# Method added in `cryptography==1.1`; not available in older versions
from cryptography.x509.extensions import Extensions
if getattr(Exten... | [
"def",
"_validate_dependencies_met",
"(",
")",
":",
"# Method added in `cryptography==1.1`; not available in older versions",
"from",
"cryptography",
".",
"x509",
".",
"extensions",
"import",
"Extensions",
"if",
"getattr",
"(",
"Extensions",
",",
"\"get_extension_for_class\"",
... | [
138,
0
] | [
161,
9
] | python | en | ['en', 'error', 'th'] | False |
_dnsname_to_stdlib | (name) |
Converts a dNSName SubjectAlternativeName field to the form used by the
standard library on the given Python version.
Cryptography produces a dNSName as a unicode string that was idna-decoded
from ASCII bytes. We need to idna-encode that string to get it back, and
then on Python 3 we also need to ... |
Converts a dNSName SubjectAlternativeName field to the form used by the
standard library on the given Python version. | def _dnsname_to_stdlib(name):
"""
Converts a dNSName SubjectAlternativeName field to the form used by the
standard library on the given Python version.
Cryptography produces a dNSName as a unicode string that was idna-decoded
from ASCII bytes. We need to idna-encode that string to get it back, and
... | [
"def",
"_dnsname_to_stdlib",
"(",
"name",
")",
":",
"def",
"idna_encode",
"(",
"name",
")",
":",
"\"\"\"\n Borrowed wholesale from the Python Cryptography Project. It turns out\n that we can't just safely call `idna.encode`: it can explode for\n wildcard names. This avoi... | [
164,
0
] | [
204,
15
] | python | en | ['en', 'error', 'th'] | False |
get_subj_alt_name | (peer_cert) |
Given an PyOpenSSL certificate, provides all the subject alternative names.
|
Given an PyOpenSSL certificate, provides all the subject alternative names.
| def get_subj_alt_name(peer_cert):
"""
Given an PyOpenSSL certificate, provides all the subject alternative names.
"""
# Pass the cert to cryptography, which has much better APIs for this.
if hasattr(peer_cert, "to_cryptography"):
cert = peer_cert.to_cryptography()
else:
# This is... | [
"def",
"get_subj_alt_name",
"(",
"peer_cert",
")",
":",
"# Pass the cert to cryptography, which has much better APIs for this.",
"if",
"hasattr",
"(",
"peer_cert",
",",
"\"to_cryptography\"",
")",
":",
"cert",
"=",
"peer_cert",
".",
"to_cryptography",
"(",
")",
"else",
... | [
207,
0
] | [
258,
16
] | python | en | ['en', 'error', 'th'] | False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.