id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
173,680 | import codecs
import warnings
import re
from contextlib import contextmanager
from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule
from parso.python.tokenize import _get_token_collection
def _iter_definition_exprs_from_lists(exprlist):
def check_expr(child):
if child.type == 'atom':
... | null |
173,681 | import codecs
import warnings
import re
from contextlib import contextmanager
from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule
from parso.python.tokenize import _get_token_collection
_COMP_FOR_TYPES = ('comp_for', 'sync_comp_for')
def _is_argument_comprehension(argument):
return argument.chil... | null |
173,682 | import codecs
import warnings
import re
from contextlib import contextmanager
from parso.normalizer import Normalizer, NormalizerConfig, Issue, Rule
from parso.python.tokenize import _get_token_collection
def _any_fstring_error(version, node):
if version < (3, 9) or node is None:
return False
if node.t... | null |
173,683 | import re
from codecs import BOM_UTF8
from typing import Tuple
from parso.python.tokenize import group
class PrefixPart:
def __init__(self, leaf, typ, value, spacing='', start_pos=None):
def end_pos(self) -> Tuple[int, int]:
def create_spacing_part(self):
def __repr__(self):
def search_ancestor... | null |
173,684 | from __future__ import absolute_import
import sys
import re
import itertools as _itertools
from codecs import BOM_UTF8
from typing import NamedTuple, Tuple, Iterator, Iterable, List, Dict, \
Pattern, Set
from parso.python.token import PythonTokenTypes
from parso.utils import split_lines, PythonVersionInfo, parse_ve... | Generate tokens from a the source code (string). |
173,685 | from __future__ import absolute_import
import sys
import re
import itertools as _itertools
from codecs import BOM_UTF8
from typing import NamedTuple, Tuple, Iterator, Iterable, List, Dict, \
Pattern, Set
from parso.python.token import PythonTokenTypes
from parso.utils import split_lines, PythonVersionInfo, parse_ve... | A small helper function to help debug the tokenize_lines function. |
173,686 | from typing import Dict, Type
from parso import tree
from parso.pgen2.generator import ReservedString
def _token_to_transition(grammar, type_, value):
# Map from token to label
if type_.value.contains_syntax:
# Check for reserved words (keywords)
try:
return grammar.reserved_syntax_... | null |
173,687 | import hashlib
import os
from typing import Generic, TypeVar, Union, Dict, Optional, Any
from pathlib import Path
from parso._compatibility import is_pypy
from parso.pgen2 import generate_grammar
from parso.utils import split_lines, python_bytes_to_unicode, \
PythonVersionInfo, parse_version_string
from parso.pytho... | Loads a :py:class:`parso.Grammar`. The default version is the current Python version. :param str version: A python version string, e.g. ``version='3.8'``. :param str path: A path to a grammar file |
173,688 | import time
import os
import sys
import hashlib
import gc
import shutil
import platform
import logging
import warnings
import pickle
from pathlib import Path
from typing import Dict, Any
class Path(PurePath):
def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ...
def __enter__(self:... | null |
173,689 | import time
import os
import sys
import hashlib
import gc
import shutil
import platform
import logging
import warnings
import pickle
from pathlib import Path
from typing import Dict, Any
parser_cache: Dict[str, Any] = {}
def _load_from_file_system(hashed_grammar, path, p_time, cache_path=None):
cache_path = _get_ha... | Returns a module or None, if it fails. |
173,690 | import time
import os
import sys
import hashlib
import gc
import shutil
import platform
import logging
import warnings
import pickle
from pathlib import Path
from typing import Dict, Any
class _NodeCacheItem:
def __init__(self, node, lines, change_time=None):
def _set_cache_item(hashed_grammar, path, module_cache_... | null |
173,691 | from ast import literal_eval
from typing import TypeVar, Generic, Mapping, Sequence, Set, Union
from parso.pgen2.grammar_parser import GrammarParser, NFAState
def _dump_nfa(start, finish):
print("Dump of NFA for", start.from_rule)
todo = [start]
for i, state in enumerate(todo):
print(" State", i, ... | null |
173,692 | from ast import literal_eval
from typing import TypeVar, Generic, Mapping, Sequence, Set, Union
from parso.pgen2.grammar_parser import GrammarParser, NFAState
def _dump_dfas(dfas):
print("Dump of DFA for", dfas[0].from_rule)
for i, state in enumerate(dfas):
print(" State", i, state.is_final and "(fina... | null |
173,693 | from ast import literal_eval
from typing import TypeVar, Generic, Mapping, Sequence, Set, Union
from parso.pgen2.grammar_parser import GrammarParser, NFAState
class Grammar(Generic[_TokenTypeT]):
"""
Once initialized, this class supplies the grammar tables for the
parsing engine implemented by parse.py. Th... | ``bnf_text`` is a grammar in extended BNF (using * for repetition, + for at-least-once repetition, [] for optional parts, | for alternatives and () for grouping). It's not EBNF according to ISO/IEC 14977. It's a dialect Python uses in its own parser. |
173,694 | from __future__ import annotations
import re
from typing import Any
TOKENS = {
'class': RE_CLASS,
'param': RE_PARAM,
'empty': RE_EMPTY,
'lstrt': RE_LSTRT,
'dstrt': RE_DSTRT,
'tstrt': RE_TSTRT,
'lend': RE_LEND,
'dend': RE_DEND,
'tend': RE_TEND,
'sqstr': RE_SQSTR,
'sep': RE_SEP... | Make the object output string pretty. |
173,695 | from __future__ import annotations
import re
from functools import lru_cache
from . import util
from . import css_match as cm
from . import css_types as ct
from .util import SelectorSyntaxError
import warnings
from typing import Optional, Match, Any, Iterator, cast
def _cached_css_compile(
pattern: str,
namespa... | Purge the cache. |
173,696 | from __future__ import annotations
import re
from functools import lru_cache
from . import util
from . import css_match as cm
from . import css_types as ct
from .util import SelectorSyntaxError
import warnings
from typing import Optional, Match, Any, Iterator, cast
The provided code snippet includes necessary dependen... | Escape identifier. |
173,697 | from __future__ import annotations
from functools import wraps, lru_cache
import warnings
import re
from typing import Callable, Any, Optional
def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ...
class Callable(BaseTypingInstance):
def py__call__... | Raise a `DeprecationWarning` when wrapped function/method is called. Usage: @deprecated("This method will be removed in version X; use Y instead.") def some_method()" pass |
173,698 | from __future__ import annotations
from functools import wraps, lru_cache
import warnings
import re
from typing import Callable, Any, Optional
The provided code snippet includes necessary dependencies for implementing the `warn_deprecated` function. Write a Python function `def warn_deprecated(message: str, stacklevel... | Warn deprecated. |
173,699 | from __future__ import annotations
from functools import wraps, lru_cache
import warnings
import re
from typing import Callable, Any, Optional
RE_PATTERN_LINE_SPLIT = re.compile(r'(?:\r\n|(?!\r\n)[\n\r])|$')
The provided code snippet includes necessary dependencies for implementing the `get_pattern_context` function. ... | Get the pattern context. |
173,700 | from __future__ import annotations
from collections import namedtuple
import re
RE_VER = re.compile(
r'''(?x)
(?P<major>\d+)(?:\.(?P<minor>\d+))?(?:\.(?P<micro>\d+))?
(?:(?P<type>a|b|rc)(?P<pre>\d+))?
(?:\.post(?P<post>\d+))?
(?:\.dev(?P<dev>\d+))?
'''
)
PRE_REL_MAP = {"a": 'alpha', "b": 'beta',... | Parse version into a comparable Version tuple. |
173,701 | from __future__ import annotations
import copyreg
from .pretty import pretty
from typing import Any, Iterator, Hashable, Optional, Pattern, Iterable, Mapping
def _pickle(p: Any) -> Any:
return p.__base__(), tuple([getattr(p, s) for s in p.__slots__[:-1]])
Any = object()
The provided code snippet includes necessar... | Allow object to be pickled. |
173,702 | import hashlib
import hmac
import typing as _t
from .encoding import _base64_alphabet
from .encoding import base64_decode
from .encoding import base64_encode
from .encoding import want_bytes
from .exc import BadSignature
_t_secret_key = _t.Union[_t.Iterable[_t_str_bytes], _t_str_bytes]
def want_bytes(
s: _t_str_by... | null |
173,703 | import base64
import string
import struct
import typing as _t
from .exc import BadData
_t_str_bytes = _t.Union[str, bytes]
def want_bytes(
s: _t_str_bytes, encoding: str = "utf-8", errors: str = "strict"
) -> bytes:
if isinstance(s, str):
s = s.encode(encoding, errors)
return s
The provided code sn... | Base64 encode a string of bytes or text. The resulting bytes are safe to use in URLs. |
173,704 | import base64
import string
import struct
import typing as _t
from .exc import BadData
_t_str_bytes = _t.Union[str, bytes]
def want_bytes(
s: _t_str_bytes, encoding: str = "utf-8", errors: str = "strict"
) -> bytes:
if isinstance(s, str):
s = s.encode(encoding, errors)
return s
class BadData(Except... | Base64 decode a URL-safe string of bytes or text. The result is bytes. |
173,705 | import base64
import string
import struct
import typing as _t
from .exc import BadData
_int_to_bytes = _int64_struct.pack
def int_to_bytes(num: int) -> bytes:
return _int_to_bytes(num).lstrip(b"\x00") | null |
173,706 | import base64
import string
import struct
import typing as _t
from .exc import BadData
_bytes_to_int = _t.cast("_t.Callable[[bytes], _t.Tuple[int]]", _int64_struct.unpack)
def bytes_to_int(bytestr: bytes) -> int:
return _bytes_to_int(bytestr.rjust(8, b"\x00"))[0] | null |
173,707 | import json
import typing as _t
from .encoding import want_bytes
from .exc import BadPayload
from .exc import BadSignature
from .signer import _make_keys_list
from .signer import Signer
The provided code snippet includes necessary dependencies for implementing the `is_text_serializer` function. Write a Python function... | Checks whether a serializer generates text or binary. |
173,708 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`). |
173,709 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`). |
173,710 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`). |
173,711 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | null |
173,712 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | Function to convert a simple predicate function that returns ``True`` or ``False`` into a parse action. Can be used in places when a parse action is required and :class:`ParserElement.add_condition` cannot be used (such as when adding a condition to an operator level in :class:`infix_notation`). Optional keyword argume... |
173,713 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | null |
173,714 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | null |
173,715 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | null |
173,716 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | Do-nothing' debug action, to suppress debugging output during parsing. |
173,717 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | Decorator for debugging parse actions. When the parse action is called, this decorator will print ``">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)"``. When the parse action completes, the decorator will print ``"<<"`` followed by the returned value, or any exception that the pa... |
173,718 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | r"""Helper to easily define string ranges for use in :class:`Word` construction. Borrows syntax from regexp ``'[]'`` string range definitions:: srange("[0-9]") -> "0123456789" srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz" srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_" The input string must be enclosed in []'s, a... |
173,719 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | Helper to define a parse action by mapping a function to all elements of a :class:`ParseResults` list. If any additional args are passed, they are forwarded to the given function as additional arguments after the token, as in ``hex_integer = Word(hexnums).set_parse_action(token_map(int, 16))``, which will convert the p... |
173,720 | import os
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
from abc import ABC, abstractmethod
from enum import Enum
import string
import copy
import warnings
import re
import sys
from collections.abc import Ite... | Utility to simplify mass-naming of parser elements, for generating railroad diagram with named subdiagrams. |
173,721 | from .exceptions import ParseException
from .util import col
class ParseException(ParseBaseException):
"""
Exception thrown when a parse expression doesn't match the input string
Example::
try:
Word(nums).set_name("integer").parse_string("ABC")
except ParseException as pe:
... | Helper method for defining parse actions that require matching at a specific column in the input text. |
173,722 | from .exceptions import ParseException
from .util import col
The provided code snippet includes necessary dependencies for implementing the `replace_with` function. Write a Python function `def replace_with(repl_str)` to solve the following problem:
Helper method for common parse actions that simply return a literal v... | Helper method for common parse actions that simply return a literal value. Especially useful when used with :class:`transform_string<ParserElement.transform_string>` (). Example:: num = Word(nums).set_parse_action(lambda toks: int(toks[0])) na = one_of("N/A NA").set_parse_action(replace_with(math.nan)) term = na | num ... |
173,723 | from .exceptions import ParseException
from .util import col
The provided code snippet includes necessary dependencies for implementing the `remove_quotes` function. Write a Python function `def remove_quotes(s, l, t)` to solve the following problem:
Helper parse action for removing quotation marks from parsed quoted ... | Helper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quoted_string.parse_string("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use remove_quotes to strip quotation marks from parsed ... |
173,724 | from .exceptions import ParseException
from .util import col
def with_attribute(*args, **attr_dict):
"""
Helper to create a validating parse action to be used with start
tags created with :class:`make_xml_tags` or
:class:`make_html_tags`. Use ``with_attribute`` to qualify
a starting tag with a requi... | Simplified version of :class:`with_attribute` when matching on a div class - made difficult because ``class`` is a reserved word in Python. Example:: html = ''' <div> Some text <div class="grid">1 4 0 1 0</div> <div class="graph">1,3 2,3 1,1</div> <div>this <div> has no class</div> </div> ''' div,div_end = make_h... |
173,725 | import warnings
import types
import collections
import itertools
from functools import lru_cache
from typing import List, Union, Iterable
import collections
try:
# Python 3
from collections.abc import Iterable
from collections.abc import MutableMapping
except ImportError:
# Python 2.7
from collec... | null |
173,726 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
import cop... | Helper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing ``combine=True`` in the constructor. If ``combine`` is set to ``True``, the matching tokens are returned as ... |
173,727 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
import cop... | Helper to define a counted list of expressions. This helper defines a pattern of the form:: integer expr expr expr... where the leading integer tells how many expr expressions follow. The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed. If ``int_expr`` is specified, it ... |
173,728 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
class ParserElement(ABC):
"""Abstract base level parser element class."""
DEFAULT_WHITE_CHARS: str = " \n\t\r"
verbose_stacktrace: bool = False
_litera... | Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = match_previous_literal(first) match_expr = first + ":" + second will match ``"1:1"``, but not ``"1:2"``. Becaus... |
173,729 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
import copy
class ParserElement(ABC):
"""Abstract base level parser element class."""
DEFAULT_WHITE_CHARS: str = " \... | Helper to define an expression that is indirectly defined from the tokens matched in a previous expression, that is, it looks for a 'repeat' of a previous expression. For example:: first = Word(nums) second = match_previous_expr(first) match_expr = first + ":" + second will match ``"1:1"``, but not ``"1:2"``. Because t... |
173,730 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
import war... | Helper to quickly define a set of alternative :class:`Literal` s, and makes sure to do longest-first testing when there is a conflict, regardless of the input order, but returns a :class:`MatchFirst` for best performance. Parameters: - ``strs`` - a string of space-delimited literals, or a collection of string literals ... |
173,731 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
class ParserElement(ABC):
"""Abstract base level parser element class."""
DEFAULT_WHITE_CHARS: str = " \n\t\r"
verbose_stacktrace: bool = False
_litera... | Helper to easily and clearly define a dictionary by specifying the respective patterns for the key and value. Takes care of defining the :class:`Dict`, :class:`ZeroOrMore`, and :class:`Group` tokens in the proper order. The key pattern can include delimiting markers or punctuation, as long as they are suppressed, there... |
173,732 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
import copy
class Diagnostics(Enum):
"""
Diagnostic configuration (all default to disabled)
- ``warn_multiple_tokens_in_named_alternation`` - fla... | Helper to return the original, untokenized text for a given expression. Useful to restore the parsed fields of an HTML start tag into the raw tag text itself, or to revert separate tokens with intervening whitespace back to the original matching input text. By default, returns astring containing the original parsed tex... |
173,733 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
class ParserElement(ABC):
"""Abstract base level parser element class."""
DEFAULT_WHITE_CHARS: str = " \n\t\r"
verbose_stacktrace: bool = False
_litera... | Helper to undo pyparsing's default grouping of And expressions, even if all but one are non-empty. |
173,734 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
import copy
class ParserElement(ABC):
"""Abstract base level parser element class."""
DEFAULT_WHITE_CHARS: str = " \... | (DEPRECATED - future code should use the Located class) Helper to decorate a returned token with its starting and ending locations in the input string. This helper adds the following results names: - ``locn_start`` - location where matched expression begins - ``locn_end`` - location where matched expression ends - ``va... |
173,735 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
import typing
from typing import (
NamedTuple,
Union,
Callable,
Any,
Generator,
Tuple,
List,
TextIO,
Set,
Sequence,
)
import cop... | Helper method for defining nested lists enclosed in opening and closing delimiters (``"("`` and ``")"`` are the default). Parameters: - ``opener`` - opening character for a nested list (default= ``"("``); can also be a pyparsing expression - ``closer`` - closing character for a nested list (default= ``")"``); can also ... |
173,736 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")):
"""Internal helper to construct opening and closing tag expressions, given a tag na... | Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values. Example:: text = '<td>More info at the <a href="https://github.com/pyparsing/pyparsing/wiki">pyparsing</a> wiki page</td>' # make... |
173,737 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")):
"""Internal helper to construct opening and closing tag expressions, given a tag na... | Helper to construct opening and closing tag expressions for XML, given a tag name. Matches tags only in the given upper/lower case. Example: similar to :class:`make_html_tags` |
173,738 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
_htmlEntityMap = {k.rstrip(";"): v for k, v in html.entities.html5.items()}
The provided code snippet includes necessary dependencies for implementing the `replace_html... | Helper parser action to replace common HTML entities with their special characters |
173,739 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
class OpAssoc(Enum):
LEFT = 1
RIGHT = 2
InfixNotationOperatorSpec = Union[
Tuple[
InfixNotationOperatorArgType,
int,
OpAssoc,
... | Helper method for constructing grammars of expressions made up of operators working in a precedence hierarchy. Operators may be unary or binary, left- or right-associative. Parse actions can also be attached to operator expressions. The generated parser will also recognize the use of parentheses to override operator pr... |
173,740 | import html.entities
import re
import typing
from . import __diag__
from .core import *
from .util import _bslash, _flatten, _escape_regex_range_chars
class Empty(Token):
"""
An empty token, will always match.
"""
def __init__(self):
super().__init__()
self.mayReturnEmpty = True
... | (DEPRECATED - use IndentedBlock class instead) Helper method for defining space-delimited indentation blocks, such as those used to define block statements in Python source code. Parameters: - ``blockStatementExpr`` - expression defining syntax of statement that is repeated within the indented block - ``indentStack`` -... |
173,778 | import bs4
import collections
import dataclasses
import datetime
import itertools
import json
import logging
import re
import snscrape.base
import typing
import urllib.parse
def _timezone(s):
return pytz.timezone(s) | null |
173,779 | import bs4
import collections
import dataclasses
import datetime
import itertools
import json
import logging
import re
import snscrape.base
import typing
import urllib.parse
def _localised_datetime(tz, *args, **kwargs):
return tz.localize(datetime.datetime(*args, **kwargs)) | null |
173,780 | import bs4
import collections
import dataclasses
import datetime
import itertools
import json
import logging
import re
import snscrape.base
import typing
import urllib.parse
try:
import zoneinfo
except ImportError:
# Python 3.8 support; nowadays, Europe/Moscow is always UTC+3, but it's more complicated before 2014, s... | null |
173,781 | import bs4
import collections
import dataclasses
import datetime
import itertools
import json
import logging
import re
import snscrape.base
import typing
import urllib.parse
def _localised_datetime(tz, *args, **kwargs):
return datetime.datetime(*args, tzinfo = tz, **kwargs) | null |
173,782 | import dataclasses
import datetime
import logging
import re
import snscrape.base
import snscrape.version
import string
import time
import typing
The provided code snippet includes necessary dependencies for implementing the `_cmp_id` function. Write a Python function `def _cmp_id(id1, id2)` to solve the following prob... | Compare two Reddit IDs. Returns -1 if id1 is less than id2, 0 if they are equal, and 1 if id1 is greater than id2. id1 and id2 may have prefixes like t1_, but if included, they must be present on both and equal. |
173,783 | import argparse
import collections
import contextlib
import dataclasses
import datetime
import importlib.metadata
import inspect
import logging
import os
import requests
import sys
import tempfile
logger = logging
def _dump_stack_and_locals(trace, exc = None):
with tempfile.NamedTemporaryFile('w', prefix = 'snscrape_l... | null |
173,784 | import argparse
import collections
import contextlib
import dataclasses
import datetime
import importlib.metadata
import inspect
import logging
import os
import requests
import sys
import tempfile
def parse_datetime_arg(arg):
for format in ('%Y-%m-%d %H:%M:%S %z', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %z', '%Y-%m-%d'):
try... | null |
173,785 | import argparse
import collections
import contextlib
import dataclasses
import datetime
import importlib.metadata
import inspect
import logging
import os
import requests
import sys
import tempfile
logger = logging
class Logger(logging.Logger):
def _log_with_stack(self, level, *args, **kwargs):
def warning(sel... | null |
173,786 | import argparse
import collections
import contextlib
import dataclasses
import datetime
import importlib.metadata
import inspect
import logging
import os
import requests
import sys
import tempfile
dumpLocals = False
def configure_logging(verbosity, dumpLocals_):
global dumpLocals
dumpLocals = dumpLocals_
rootLogge... | null |
173,787 | import abc
import copy
import dataclasses
import datetime
import functools
import json
import logging
import requests
import requests.adapters
import urllib3.connection
import time
import warnings
class DeprecatedFeatureWarning(FutureWarning):
__getattr__, __dir__ = _module_deprecation_helper(__all__, Entity = Item)
d... | null |
173,788 | import abc
import copy
import dataclasses
import datetime
import functools
import json
import logging
import requests
import requests.adapters
import urllib3.connection
import time
import warnings
The provided code snippet includes necessary dependencies for implementing the `_json_serialise_datetime` function. Write ... | A JSON serialiser that converts datetime.datetime and datetime.date objects to ISO-8601 strings. |
173,789 | import abc
import copy
import dataclasses
import datetime
import functools
import json
import logging
import requests
import requests.adapters
import urllib3.connection
import time
import warnings
class _DeprecatedProperty:
def __init__(self, name, repl, replStr):
self.name = name
self.repl = repl
self.replStr =... | null |
173,790 | import abc
import copy
import dataclasses
import datetime
import functools
import json
import logging
import requests
import requests.adapters
import urllib3.connection
import time
import warnings
def nonempty_string(name):
def f(s):
s = s.strip()
if s:
return s
raise ValueError('must not be an empty string'... | null |
173,791 | class Indent:
def __init__(self, instance, line):
self.instance = instance
self.line = line
def __enter__(self):
self.instance._indent += 1
def __exit__(self, type_, value, traceback):
self.instance._indent -= 1
self.instance._indent_last_line = self.line
The provide... | Decorator for allowing to use method as normal method or with context manager for auto-indenting code blocks. |
173,792 | from collections import OrderedDict
import re
from .exceptions import JsonSchemaValueException, JsonSchemaDefinitionException
from .indent import indent
from .ref_resolver import RefResolver
def enforce_list(variable):
if isinstance(variable, list):
return variable
return [variable] | null |
173,793 | from collections import OrderedDict
import re
from .exceptions import JsonSchemaValueException, JsonSchemaDefinitionException
from .indent import indent
from .ref_resolver import RefResolver
def repr_regex(regex):
all_flags = ("A", "I", "DEBUG", "L", "M", "S", "X")
flags = " | ".join(f"re.{f}" for f in all_flag... | null |
173,794 | import contextlib
import json
import re
from urllib import parse as urlparse
from urllib.parse import unquote
from urllib.request import urlopen
from .exceptions import JsonSchemaDefinitionException
The provided code snippet includes necessary dependencies for implementing the `get_id` function. Write a Python functio... | Originally ID was `id` and since v7 it's `$id`. |
173,795 | import contextlib
import json
import re
from urllib import parse as urlparse
from urllib.parse import unquote
from urllib.request import urlopen
from .exceptions import JsonSchemaDefinitionException
class JsonSchemaDefinitionException(JsonSchemaException):
"""
Exception raised by generator of validation functi... | Return definition from path. Path is unescaped according https://tools.ietf.org/html/rfc6901 |
173,796 | import contextlib
import json
import re
from urllib import parse as urlparse
from urllib.parse import unquote
from urllib.request import urlopen
from .exceptions import JsonSchemaDefinitionException
def normalize(uri):
return urlparse.urlsplit(uri).geturl() | null |
173,797 | import contextlib
import json
import re
from urllib import parse as urlparse
from urllib.parse import unquote
from urllib.request import urlopen
from .exceptions import JsonSchemaDefinitionException
class JsonSchemaDefinitionException(JsonSchemaException):
"""
Exception raised by generator of validation functi... | Resolve a remote ``uri``. .. note:: urllib library is used to fetch requests from the remote ``uri`` if handlers does notdefine otherwise. |
173,798 | import re
from .parser import _next_significant, _to_token_iterator
def parse_b(tokens, a):
token = _next_significant(tokens)
if token is None:
return (a, 0)
elif token == '+':
return parse_signless_b(tokens, a, 1)
elif token == '-':
return parse_signless_b(tokens, a, -1)
eli... | Parse `<An+B> <https://drafts.csswg.org/css-syntax-3/#anb>`_, as found in `:nth-child() <https://drafts.csswg.org/selectors/#nth-child-pseudo>`_ and related Selector pseudo-classes. Although tinycss2 does not include a full Selector parser, this bit of syntax is included as it is particularly tricky to define on top of... |
173,799 | from .ast import AtRule, Declaration, ParseError, QualifiedRule
from .tokenizer import parse_component_value_list
def _to_token_iterator(input, skip_comments=False):
"""Iterate component values out of string or component values iterable.
:type input: :obj:`str` or :term:`iterable`
:param input: A string or ... | Parse a single :diagram:`declaration`. This is used e.g. for a declaration in an `@supports <https://drafts.csswg.org/css-conditional/#at-supports>`_ test. :type input: :obj:`str` or :term:`iterable` :param input: A string or an iterable of :term:`component values`. :type skip_comments: :obj:`bool` :param skip_comments... |
173,800 | from .ast import AtRule, Declaration, ParseError, QualifiedRule
from .tokenizer import parse_component_value_list
def _to_token_iterator(input, skip_comments=False):
"""Iterate component values out of string or component values iterable.
:type input: :obj:`str` or :term:`iterable`
:param input: A string or ... | Parse a :diagram:`declaration list` (which may also contain at-rules). This is used e.g. for the :attr:`~tinycss2.ast.QualifiedRule.content` of a style rule or ``@page`` rule, or for the ``style`` attribute of an HTML element. In contexts that don’t expect any at-rule, all :class:`~tinycss2.ast.AtRule` objects should s... |
173,801 | from .ast import AtRule, Declaration, ParseError, QualifiedRule
from .tokenizer import parse_component_value_list
def _to_token_iterator(input, skip_comments=False):
"""Iterate component values out of string or component values iterable.
:type input: :obj:`str` or :term:`iterable`
:param input: A string or ... | Parse a single :diagram:`qualified rule` or :diagram:`at-rule`. This would be used e.g. by `insertRule() <https://drafts.csswg.org/cssom/#dom-cssstylesheet-insertrule>`_ in an implementation of CSSOM. :type input: :obj:`str` or :term:`iterable` :param input: A string or an iterable of :term:`component values`. :type sk... |
173,802 | from .ast import AtRule, Declaration, ParseError, QualifiedRule
from .tokenizer import parse_component_value_list
def _to_token_iterator(input, skip_comments=False):
"""Iterate component values out of string or component values iterable.
:type input: :obj:`str` or :term:`iterable`
:param input: A string or ... | Parse a non-top-level :diagram:`rule list`. This is used for parsing the :attr:`~tinycss2.ast.AtRule.content` of nested rules like ``@media``. This differs from :func:`parse_stylesheet` in that top-level ``<!--`` and ``-->`` tokens are not ignored. :type input: :obj:`str` or :term:`iterable` :param input: A string or a... |
173,803 | from webencodings import UTF8, decode, lookup
from .parser import parse_stylesheet
def decode_stylesheet_bytes(css_bytes, protocol_encoding=None,
environment_encoding=None):
"""Determine the character encoding of a CSS stylesheet and decode it.
This is based on the presence of a :abb... | Parse :diagram:`stylesheet` from bytes, determining the character encoding as web browsers do. This is used when reading a file or fetching a URL. The character encoding is determined from the initial bytes (a :abbr:`BOM (Byte Order Mark)` or a ``@charset`` rule) as well as the parameters. The ultimate fallback is UTF-... |
173,804 | import collections
import re
from colorsys import hls_to_rgb
from .parser import parse_one_component_value
class RGBA(collections.namedtuple('RGBA', ['red', 'green', 'blue', 'alpha'])):
"""An RGBA color.
A tuple of four floats in the 0..1 range: ``(red, green, blue, alpha)``.
.. attribute:: red
Conv... | Parse a color value as defined in `CSS Color Level 3 <https://www.w3.org/TR/css-color-3/>`_. :type input: :obj:`str` or :term:`iterable` :param input: A string or an iterable of :term:`component values`. :returns: * :obj:`None` if the input is not a valid color value. (No exception is raised.) * The string ``'currentCo... |
173,805 | def _serialize_to(nodes, write):
"""Serialize an iterable of nodes to CSS syntax.
White chunks as a string by calling the provided :obj:`write` callback.
"""
bad_pairs = BAD_PAIRS
previous_type = None
for node in nodes:
serialization_type = (node.type if node.type != 'literal'
... | Serialize nodes to CSS syntax. This should be used for :term:`component values` instead of just :meth:`tinycss2.ast.Node.serialize` on each node as it takes care of corner cases such as ``;`` between declarations, and consecutive identifiers that would otherwise parse back as the same token. :type nodes: :term:`iterabl... |
173,806 | def serialize_name(value):
return ''.join(
c if c in ('abcdefghijklmnopqrstuvwxyz-_0123456789'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ') or ord(c) > 0x7F else
r'\A ' if c == '\n' else
r'\D ' if c == '\r' else
r'\C ' if c == '\f' else
'\\' + c
for c in value
... | Serialize any string as a CSS identifier :type value: :obj:`str` :param value: A string representing a CSS value. :returns: A :obj:`string <str>` that would parse as an :class:`tinycss2.ast.IdentToken` whose :attr:`tinycss2.ast.IdentToken.value` attribute equals the passed ``value`` argument. |
173,808 | from base64 import b64encode
from errno import EOPNOTSUPP, EINVAL, EAGAIN
import functools
from io import BytesIO
import logging
import os
from os import SEEK_CUR
import socket
import struct
import sys
def set_default_proxy(proxy_type=None, addr=None, port=None, rdns=True,
username=None, password=... | null |
173,811 | from base64 import b64encode
from errno import EOPNOTSUPP, EINVAL, EAGAIN
import functools
from io import BytesIO
import logging
import os
from os import SEEK_CUR
import socket
import struct
import sys
class ProxyError(IOError):
"""Socket_err contains original socket.error exception."""
def __init__(self, msg, ... | create_connection(dest_pair, *[, timeout], **proxy_args) -> socket object Like socket.create_connection(), but connects to proxy before returning the socket object. dest_pair - 2-tuple of (IP/hostname, port). **proxy_args - Same args passed to socksocket.set_proxy() if present. timeout - Optional socket timeout value, ... |
173,813 | import json
import pathlib
import platform
import click
from jsonschema import ValidationError
from rich.console import Console
from rich.json import JSON
from rich.markup import escape
from rich.padding import Padding
from rich.style import Style
from jupyter_events.schema import EventSchema, EventSchemaFileAbsent, Ev... | Validate a SCHEMA against Jupyter Event's meta schema. SCHEMA can be a JSON/YAML string or filepath to a schema. |
173,814 | from pathlib import Path
from yaml import dump as ydump
from yaml import load as yload
def loads(stream):
"""Load yaml from a stream."""
return yload(stream, Loader=SafeLoader)
class Path(PurePath):
def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ...
def __enter__(self: _... | Load yaml from a file. |
173,815 | from pathlib import Path
from yaml import dump as ydump
from yaml import load as yload
def dumps(stream):
"""Parse the first YAML document in a stream as an object."""
return ydump(stream, Dumper=SafeDumper)
class Path(PurePath):
def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P... | Parse the a YAML document in a file as an object. |
173,816 | import pathlib
import jsonschema
from jsonschema import Draft7Validator, RefResolver, ValidationError
from . import yaml
JUPYTER_EVENTS_SCHEMA_VALIDATOR = Draft7Validator(
schema=EVENT_METASCHEMA,
resolver=METASCHEMA_RESOLVER,
format_checker=draft7_format_checker,
)
The provided code snippet includes neces... | Validate a schema dict. |
173,817 | from __future__ import unicode_literals
import os.path as op
from .compat import text_type
from .util import preprocess_paths
from platform import version
import pythoncom
import pywintypes
from win32com.shell import shell, shellcon
from .IFileOperationProgressSink import CreateSink
def preprocess_paths(paths):
if... | null |
173,818 | from Foundation import NSFileManager, NSURL
from .compat import text_type
from .util import preprocess_paths
def check_op_result(op_result):
# First value will be false on failure
if not op_result[0]:
# Error is in third value, localized failure reason matchs ctypes version
raise OSError(op_resu... | null |
173,819 | from __future__ import unicode_literals
from ctypes import cdll, byref, Structure, c_char, c_char_p
from ctypes.util import find_library
from .compat import binary_type
from .util import preprocess_paths
FSPathMakeRefWithOptions = CoreServices.FSPathMakeRefWithOptions
FSMoveObjectToTrashSync = CoreServices.FSMoveObject... | null |
173,820 | from __future__ import unicode_literals
import os.path as op
from .compat import text_type
from .util import preprocess_paths
from ctypes import (
windll,
Structure,
byref,
c_uint,
create_unicode_buffer,
addressof,
GetLastError,
FormatError,
)
from ctypes.wintypes import HWND, UINT, LPCW... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.