id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
174,404 | from .nbbase import nbformat, nbformat_minor
def _unbytes(obj):
"""There should be no bytes objects in a notebook
v2 stores png/jpeg as b64 ascii bytes
"""
if isinstance(obj, dict):
for k, v in obj.items():
obj[k] = _unbytes(v)
elif isinstance(obj, list):
for i, v in enum... | Convert a notebook to v3. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. from_version : int The original version of the notebook to convert. from_minor : int The original minor version of the notebook to convert (only relevant for v >= 3). |
174,405 | from .nbbase import nbformat, nbformat_minor
def heading_to_md(cell):
"""turn heading cell into corresponding markdown"""
cell.cell_type = "markdown"
level = cell.pop("level", 1)
cell.source = "#" * level + " " + cell.source
def raw_to_md(cell):
"""let raw passthrough as markdown"""
cell.cell_ty... | Convert a v3 notebook to v2. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. |
174,406 | from base64 import decodebytes, encodebytes
The provided code snippet includes necessary dependencies for implementing the `restore_bytes` function. Write a Python function `def restore_bytes(nb)` to solve the following problem:
Restore bytes of image data from unicode-only formats. Base64 encoding is handled elsewher... | Restore bytes of image data from unicode-only formats. Base64 encoding is handled elsewhere. Bytes objects in the notebook are always b64-encoded. We DO NOT encode/decode around file formats. Note: this is never used |
174,407 | from base64 import decodebytes, encodebytes
_multiline_outputs = ["text", "html", "svg", "latex", "javascript", "json"]
def _join_lines(lines):
"""join lines that have been written by splitlines()
Has logic to protect against `splitlines()`, which
should have been `splitlines(True)`
"""
if lines and... | rejoin multiline text into strings For reversing effects of ``split_lines(nb)``. This only rejoins lines that have been split, so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through split_lines. |
174,408 | from base64 import decodebytes, encodebytes
_multiline_outputs = ["text", "html", "svg", "latex", "javascript", "json"]
The provided code snippet includes necessary dependencies for implementing the `split_lines` function. Write a Python function `def split_lines(nb)` to solve the following problem:
split likely multi... | split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files. |
174,411 | from base64 import decodebytes, encodebytes
The provided code snippet includes necessary dependencies for implementing the `strip_transient` function. Write a Python function `def strip_transient(nb)` to solve the following problem:
Strip transient values that shouldn't be stored in files. This should be called in *bo... | Strip transient values that shouldn't be stored in files. This should be called in *both* read and write. |
174,412 | import re
import warnings
from traitlets.log import get_logger
from nbformat import v3 as _v_latest
from nbformat.v3 import (
NotebookNode,
nbformat,
nbformat_minor,
nbformat_schema,
new_author,
new_code_cell,
new_heading_cell,
new_metadata,
new_notebook,
new_output,
new_text... | DEPRECATED, use reads |
174,413 | import re
import warnings
from traitlets.log import get_logger
from nbformat import v3 as _v_latest
from nbformat.v3 import (
NotebookNode,
nbformat,
nbformat_minor,
nbformat_schema,
new_author,
new_code_cell,
new_heading_cell,
new_metadata,
new_notebook,
new_output,
new_text... | DEPRECATED: use nbconvert |
174,414 | import re
import warnings
from traitlets.log import get_logger
from nbformat import v3 as _v_latest
from nbformat.v3 import (
NotebookNode,
nbformat,
nbformat_minor,
nbformat_schema,
new_author,
new_code_cell,
new_heading_cell,
new_metadata,
new_notebook,
new_output,
new_text... | DEPRECATED: use nbconvert |
174,415 | import re
import warnings
from traitlets.log import get_logger
from nbformat import v3 as _v_latest
from nbformat.v3 import (
NotebookNode,
nbformat,
nbformat_minor,
nbformat_schema,
new_author,
new_code_cell,
new_heading_cell,
new_metadata,
new_notebook,
new_output,
new_text... | Read a notebook from a file and return the NotebookNode object. This function properly handles notebooks of any version. The notebook returned will always be in the current version's format. Parameters ---------- fp : file Any file-like object with a read method. Returns ------- nb : NotebookNode The notebook that was ... |
174,416 | import re
import warnings
from traitlets.log import get_logger
from nbformat import v3 as _v_latest
from nbformat.v3 import (
NotebookNode,
nbformat,
nbformat_minor,
nbformat_schema,
new_author,
new_code_cell,
new_heading_cell,
new_metadata,
new_notebook,
new_output,
new_text... | Write a notebook to a file in a given format in the current nbformat version. This function always writes the notebook in the current nbformat version. Parameters ---------- nb : NotebookNode The notebook to write. fp : file Any file-like object with a write method. |
174,417 | from nbformat.corpus.words import generate_corpus_id as random_cell_id
from nbformat.notebooknode import NotebookNode
def new_output(output_type, data=None, **kwargs):
"""Create a new output, to go in the ``cell.outputs`` list of a code cell."""
output = NotebookNode(output_type=output_type)
# populate defa... | Create a NotebookNode for an output from a kernel's IOPub message. Returns ------- NotebookNode: the output as a notebook node. Raises ------ ValueError: if the message is not an output message. |
174,418 | from nbformat.corpus.words import generate_corpus_id as random_cell_id
from nbformat.notebooknode import NotebookNode
def validate(node, ref=None):
"""validate a v4 node"""
from nbformat import validate as validate_orig
return validate_orig(node, ref=ref, version=nbformat)
class NotebookNode(Struct):
"... | Create a new code cell |
174,419 | from nbformat.corpus.words import generate_corpus_id as random_cell_id
from nbformat.notebooknode import NotebookNode
def validate(node, ref=None):
"""validate a v4 node"""
from nbformat import validate as validate_orig
return validate_orig(node, ref=ref, version=nbformat)
class NotebookNode(Struct):
"... | Create a new markdown cell |
174,420 | from nbformat.corpus.words import generate_corpus_id as random_cell_id
from nbformat.notebooknode import NotebookNode
def validate(node, ref=None):
"""validate a v4 node"""
from nbformat import validate as validate_orig
return validate_orig(node, ref=ref, version=nbformat)
class NotebookNode(Struct):
"... | Create a new raw cell |
174,421 | from nbformat.corpus.words import generate_corpus_id as random_cell_id
from nbformat.notebooknode import NotebookNode
nbformat = 4
nbformat_minor = 5
def validate(node, ref=None):
"""validate a v4 node"""
from nbformat import validate as validate_orig
return validate_orig(node, ref=ref, version=nbformat)
c... | Create a new notebook |
174,422 | import json
import re
from traitlets.log import get_logger
from nbformat import v3, validator
from .nbbase import NotebookNode, nbformat, nbformat_minor, random_cell_id
def _warn_if_invalid(nb, version):
"""Log validation errors, if there are any."""
from nbformat import ValidationError, validate
try:
... | Convert a notebook to latest v4. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. from_version : int The original version of the notebook to convert. from_minor : int The original minor version of the notebook to convert (only relevant for v >= 3). |
174,423 | import json
import re
from traitlets.log import get_logger
from nbformat import v3, validator
from .nbbase import NotebookNode, nbformat, nbformat_minor, random_cell_id
def _warn_if_invalid(nb, version):
"""Log validation errors, if there are any."""
from nbformat import ValidationError, validate
try:
... | Convert a v4 notebook to v3. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. |
174,424 | def _rejoin_mimebundle(data):
"""Rejoin the multi-line string fields in a mimebundle (in-place)"""
for key, value in list(data.items()):
if (
not _is_json_mime(key)
and isinstance(value, list)
and all(isinstance(line, str) for line in value)
):
dat... | rejoin multiline text into strings For reversing effects of ``split_lines(nb)``. This only rejoins lines that have been split, so if text objects were not split they will pass through unchanged. Used when reading JSON files that may have been passed through split_lines. |
174,425 | def _split_mimebundle(data):
"""Split multi-line string fields in a mimebundle (in-place)"""
for key, value in list(data.items()):
if isinstance(value, str) and (key.startswith("text/") or key in _non_text_split_mimes):
data[key] = value.splitlines(True)
return data
The provided code sn... | split likely multiline text into lists of strings For file output more friendly to line-based VCS. ``rejoin_lines(nb)`` will reverse the effects of ``split_lines(nb)``. Used when writing JSON files. |
174,426 |
The provided code snippet includes necessary dependencies for implementing the `strip_transient` function. Write a Python function `def strip_transient(nb)` to solve the following problem:
Strip transient values that shouldn't be stored in files. This should be called in *both* read and write.
Here is the function:
... | Strip transient values that shouldn't be stored in files. This should be called in *both* read and write. |
174,427 | import json
from .validator import ValidationError
def reads(s, **kwargs):
"""Read a notebook from a json string and return the
NotebookNode object.
This function properly reads notebooks of any version. No version
conversion is performed.
Parameters
----------
s : unicode | bytes
T... | Read a notebook from a file and return the NotebookNode object. This function properly reads notebooks of any version. No version conversion is performed. Parameters ---------- fp : file Any file-like object with a read method. Returns ------- nb : NotebookNode The notebook that was read. |
174,428 | from nbformat._struct import Struct
class NotebookNode(Struct):
"""A notebook node object."""
pass
The provided code snippet includes necessary dependencies for implementing the `from_dict` function. Write a Python function `def from_dict(d)` to solve the following problem:
Create notebook node(s) from an obje... | Create notebook node(s) from an object. |
174,429 | from nbformat._struct import Struct
class NotebookNode(Struct):
"""A notebook node object."""
pass
The provided code snippet includes necessary dependencies for implementing the `new_code_cell` function. Write a Python function `def new_code_cell(code=None, prompt_number=None)` to solve the following problem:
... | Create a new code cell with input and output |
174,430 | from nbformat._struct import Struct
class NotebookNode(Struct):
"""A notebook node object."""
pass
The provided code snippet includes necessary dependencies for implementing the `new_text_cell` function. Write a Python function `def new_text_cell(text=None)` to solve the following problem:
Create a new text ce... | Create a new text cell. |
174,431 | from nbformat._struct import Struct
class NotebookNode(Struct):
"""A notebook node object."""
pass
The provided code snippet includes necessary dependencies for implementing the `new_notebook` function. Write a Python function `def new_notebook(cells=None)` to solve the following problem:
Create a notebook by ... | Create a notebook by name, id and a list of worksheets. |
174,432 |
The provided code snippet includes necessary dependencies for implementing the `upgrade` function. Write a Python function `def upgrade(nb, orig_version=None)` to solve the following problem:
Upgrade a notebook.
Here is the function:
def upgrade(nb, orig_version=None):
"""Upgrade a notebook."""
msg = "Canno... | Upgrade a notebook. |
174,433 | import hashlib
import os
import sys
import typing as t
from collections import OrderedDict
from contextlib import contextmanager
from datetime import datetime, timezone
from hmac import HMAC
from base64 import encodebytes
from jupyter_core.application import JupyterApp, base_flags
from traitlets import Any, Bool, Bytes... | Yield every item in a container as bytes Allows any JSONable object to be passed to an HMAC digester without having to serialize the whole thing. |
174,434 | import hashlib
import os
import sys
import typing as t
from collections import OrderedDict
from contextlib import contextmanager
from datetime import datetime, timezone
from hmac import HMAC
from base64 import encodebytes
from jupyter_core.application import JupyterApp, base_flags
from traitlets import Any, Bool, Bytes... | Iterator that yields all cells in a notebook nbformat version independent |
174,435 | import hashlib
import os
import sys
import typing as t
from collections import OrderedDict
from contextlib import contextmanager
from datetime import datetime, timezone
from hmac import HMAC
from base64 import encodebytes
from jupyter_core.application import JupyterApp, base_flags
from traitlets import Any, Bool, Bytes... | Context manager for operating on a notebook with its signature removed Used for excluding the previous signature when computing a notebook's signature. |
174,436 | from collections.abc import Mapping, Hashable
from itertools import chain
from pyrsistent._pvector import pvector
from pyrsistent._transformations import transform
def pmap(initial={}, pre_size=0):
"""
Create new persistent map, inserts all elements in initial into the newly created map.
The optional argume... | Creates a new persistent map. Inserts all key value arguments into the newly created map. >>> m(a=13, b=14) == {'a': 13, 'b': 14} True |
174,437 | import operator
from functools import reduce
def reduce(function: Callable[[_T, _S], _T], sequence: Iterable[_S], initial: _T) -> _T: ...
def reduce(function: Callable[[_T, _T], _T], sequence: Iterable[_T]) -> _T: ...
The provided code snippet includes necessary dependencies for implementing the `get_in` function. Wr... | NB: This is a straight copy of the get_in implementation found in the toolz library (https://github.com/pytoolz/toolz/). It works with persistent data structures as well as the corresponding datastructures from the stdlib. Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. If coll[i0][i1]...[iX] cannot be found... |
174,438 | import sys
def namedtuple(
typename: Union[str, unicode],
field_names: Union[str, unicode, Iterable[Union[str, unicode]]],
verbose: bool = ...,
rename: bool = ...,
) -> Type[Tuple[Any, ...]]: ...
The provided code snippet includes necessary dependencies for implementing the `immutable` function. Write... | Produces a class that either can be used standalone or as a base class for persistent classes. This is a thin wrapper around a named tuple. Constructing a type and using it to instantiate objects: >>> Point = immutable('x, y', name='Point') >>> p = Point(1, 2) >>> p2 = p.set(x=3) >>> p Point(x=1, y=2) >>> p2 Point(x=3,... |
174,439 | from pyrsistent._checked_types import (
CheckedPMap,
CheckedPSet,
CheckedPVector,
CheckedType,
InvariantException,
_restore_pickle,
get_type,
maybe_parse_user_type,
maybe_parse_many_user_types,
)
from pyrsistent._checked_types import optional as optional_type
from pyrsistent._checked... | null |
174,440 | from pyrsistent._checked_types import (
CheckedPMap,
CheckedPSet,
CheckedPVector,
CheckedType,
InvariantException,
_restore_pickle,
get_type,
maybe_parse_user_type,
maybe_parse_many_user_types,
)
from pyrsistent._checked_types import optional as optional_type
from pyrsistent._checked... | null |
174,441 | from pyrsistent._checked_types import (
CheckedPMap,
CheckedPSet,
CheckedPVector,
CheckedType,
InvariantException,
_restore_pickle,
get_type,
maybe_parse_user_type,
maybe_parse_many_user_types,
)
from pyrsistent._checked_types import optional as optional_type
from pyrsistent._checked... | null |
174,442 | from pyrsistent._checked_types import (
CheckedPMap,
CheckedPSet,
CheckedPVector,
CheckedType,
InvariantException,
_restore_pickle,
get_type,
maybe_parse_user_type,
maybe_parse_many_user_types,
)
from pyrsistent._checked_types import optional as optional_type
from pyrsistent._checked... | null |
174,443 | from pyrsistent._checked_types import (
CheckedPMap,
CheckedPSet,
CheckedPVector,
CheckedType,
InvariantException,
_restore_pickle,
get_type,
maybe_parse_user_type,
maybe_parse_many_user_types,
)
from pyrsistent._checked_types import optional as optional_type
from pyrsistent._checked... | Create checked ``PSet`` field. :param item_type: The required type for the items in the set. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no value is given for the field. :return: A ``field`` containing a ``CheckedPSet`` of the given type. |
174,444 | from pyrsistent._checked_types import (
CheckedPMap,
CheckedPSet,
CheckedPVector,
CheckedType,
InvariantException,
_restore_pickle,
get_type,
maybe_parse_user_type,
maybe_parse_many_user_types,
)
from pyrsistent._checked_types import optional as optional_type
from pyrsistent._checked... | Create checked ``PVector`` field. :param item_type: The required type for the items in the vector. :param optional: If true, ``None`` can be used as a value for this field. :param initial: Initial value to pass to factory if no value is given for the field. :return: A ``field`` containing a ``CheckedPVector`` of the gi... |
174,445 | from pyrsistent._checked_types import (
CheckedPMap,
CheckedPSet,
CheckedPVector,
CheckedType,
InvariantException,
_restore_pickle,
get_type,
maybe_parse_user_type,
maybe_parse_many_user_types,
)
from pyrsistent._checked_types import optional as optional_type
from pyrsistent._checked... | Create a checked ``PMap`` field. :param key: The required type for the keys of the map. :param value: The required type for the values of the map. :param optional: If true, ``None`` can be used as a value for this field. :param invariant: Pass-through to ``field``. :return: A ``field`` containing a ``CheckedPMap``. |
174,446 | from functools import wraps
from pyrsistent._pmap import PMap, pmap
from pyrsistent._pset import PSet, pset
from pyrsistent._pvector import PVector, pvector
class PMap(object):
"""
Persistent map/dict. Tries to follow the same naming conventions as the built in dict where feasible.
Do not instantiate dire... | Recursively convert pyrsistent containers into simple Python containers. - pvector is converted to list, recursively - pmap is converted to dict, recursively on values (but not keys) - pset is converted to set, but not recursively - tuple is converted to tuple, recursively. If strict == True (the default): - thaw is ca... |
174,447 | from functools import wraps
from pyrsistent._pmap import PMap, pmap
from pyrsistent._pset import PSet, pset
from pyrsistent._pvector import PVector, pvector
def freeze(o, strict=True):
"""
Recursively convert simple Python containers into pyrsistent versions
of those containers.
- list is converted to p... | Convenience decorator to isolate mutation to within the decorated function (with respect to the input arguments). All arguments to the decorated function will be frozen so that they are guaranteed not to change. The return value is also frozen. |
174,448 | from collections.abc import Sequence, Hashable
from itertools import islice, chain
from numbers import Integral
from pyrsistent._plist import plist
def pdeque(iterable=(), maxlen=None):
"""
Return deque containing the elements of iterable. If maxlen is specified then
len(iterable) - maxlen elements are disc... | Return deque containing all arguments. >>> dq(1, 2, 3) pdeque([1, 2, 3]) |
174,449 | from pyrsistent._checked_types import (InvariantException, CheckedType, _restore_pickle, store_invariants)
from pyrsistent._field_common import (
set_fields, check_type, is_field_ignore_extra_complaint, PFIELD_NO_INITIAL, serialize, check_global_invariants
)
from pyrsistent._transformations import transform
class ... | null |
174,450 | from pyrsistent._checked_types import (InvariantException, CheckedType, _restore_pickle, store_invariants)
from pyrsistent._field_common import (
set_fields, check_type, is_field_ignore_extra_complaint, PFIELD_NO_INITIAL, serialize, check_global_invariants
)
from pyrsistent._transformations import transform
def ch... | null |
174,451 | from collections.abc import Sequence, Hashable
from numbers import Integral
from functools import reduce
def plist(iterable=(), reverse=False):
"""
Creates a new persistent list containing all elements of iterable.
Optional parameter reverse specifies if the elements should be inserted in
reverse order ... | Creates a new persistent list containing all arguments. >>> l(1, 2, 3) plist([1, 2, 3]) |
174,452 | from enum import Enum
from abc import abstractmethod, ABCMeta
from collections.abc import Iterable
from pyrsistent._pmap import PMap, pmap
from pyrsistent._pset import PSet, pset
from pyrsistent._pvector import PythonPVector, python_pvector
def maybe_parse_many_user_types(ts):
def _store_types(dct, bases, destination_... | null |
174,453 | from enum import Enum
from abc import abstractmethod, ABCMeta
from collections.abc import Iterable
from pyrsistent._pmap import PMap, pmap
from pyrsistent._pset import PSet, pset
from pyrsistent._pvector import PythonPVector, python_pvector
def wrap_invariant(invariant):
def _all_dicts(bases, seen=None):
def store_inv... | null |
174,454 | from enum import Enum
from abc import abstractmethod, ABCMeta
from collections.abc import Iterable
from pyrsistent._pmap import PMap, pmap
from pyrsistent._pset import PSet, pset
from pyrsistent._pvector import PythonPVector, python_pvector
class CheckedValueTypeError(CheckedTypeError):
"""
Raised when trying t... | null |
174,455 | from enum import Enum
from abc import abstractmethod, ABCMeta
from collections.abc import Iterable
from pyrsistent._pmap import PMap, pmap
from pyrsistent._pset import PSet, pset
from pyrsistent._pvector import PythonPVector, python_pvector
def _invariant_errors(elem, invariants):
return [data for valid, data in (i... | null |
174,456 | from enum import Enum
from abc import abstractmethod, ABCMeta
from collections.abc import Iterable
from pyrsistent._pmap import PMap, pmap
from pyrsistent._pset import PSet, pset
from pyrsistent._pvector import PythonPVector, python_pvector
The provided code snippet includes necessary dependencies for implementing the... | Convenience function to specify that a value may be of any of the types in type 'typs' or None |
174,457 | from enum import Enum
from abc import abstractmethod, ABCMeta
from collections.abc import Iterable
from pyrsistent._pmap import PMap, pmap
from pyrsistent._pset import PSet, pset
from pyrsistent._pvector import PythonPVector, python_pvector
class CheckedType(object):
"""
Marker class to enable creation and seri... | null |
174,458 | from collections.abc import Set, Hashable
import sys
from pyrsistent._pmap import pmap
def pset(iterable=(), pre_size=8):
"""
Creates a persistent set from iterable. Optionally takes a sizing parameter equivalent to that
used for :py:func:`pmap`.
>>> s1 = pset([1, 2, 3, 2])
>>> s1
pset([1, 2, 3]... | Create a persistent set. Takes an arbitrary number of arguments to insert into the new set. >>> s1 = s(1, 2, 3, 2) >>> s1 pset([1, 2, 3]) |
174,459 | import re
The provided code snippet includes necessary dependencies for implementing the `inc` function. Write a Python function `def inc(x)` to solve the following problem:
Add one to the current value
Here is the function:
def inc(x):
""" Add one to the current value """
return x + 1 | Add one to the current value |
174,460 | import re
The provided code snippet includes necessary dependencies for implementing the `dec` function. Write a Python function `def dec(x)` to solve the following problem:
Subtract one from the current value
Here is the function:
def dec(x):
""" Subtract one from the current value """
return x - 1 | Subtract one from the current value |
174,461 | import re
The provided code snippet includes necessary dependencies for implementing the `rex` function. Write a Python function `def rex(expr)` to solve the following problem:
Regular expression matcher to use together with transform functions
Here is the function:
def rex(expr):
""" Regular expression matcher ... | Regular expression matcher to use together with transform functions |
174,462 | import re
The provided code snippet includes necessary dependencies for implementing the `ny` function. Write a Python function `def ny(_)` to solve the following problem:
Matcher that matches any value
Here is the function:
def ny(_):
""" Matcher that matches any value """
return True | Matcher that matches any value |
174,463 | import re
def _chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
def _do_to_path(structure, path, command):
if not path:
return command(structure) if callable(command) else command
kvs = _get_keys_and_values(structure, path[0])
return _update_structure(structure, kvs, path[1:]... | null |
174,464 | from collections.abc import Container, Iterable, Sized, Hashable
from functools import reduce
from pyrsistent._pmap import pmap
def pbag(elements):
"""
Convert an iterable to a persistent bag.
Takes an iterable with elements to insert.
>>> pbag([1, 2, 3, 2])
pbag([1, 2, 2, 3])
"""
if not ele... | Construct a persistent bag. Takes an arbitrary number of arguments to insert into the new persistent bag. >>> b(1, 2, 3, 2) pbag([1, 2, 2, 3]) |
174,465 | from abc import abstractmethod, ABCMeta
from collections.abc import Sequence, Hashable
from numbers import Integral
import operator
from pyrsistent._transformations import transform
def _bitcount(val):
return bin(val).count("1") | null |
174,466 | from abc import abstractmethod, ABCMeta
from collections.abc import Sequence, Hashable
from numbers import Integral
import operator
from pyrsistent._transformations import transform
class PVector(metaclass=ABCMeta):
"""
Persistent vector implementation. Meant as a replacement for the cases where you would norma... | null |
174,467 | from abc import abstractmethod, ABCMeta
from collections.abc import Sequence, Hashable
from numbers import Integral
import operator
from pyrsistent._transformations import transform
def _index_or_slice(index, stop):
if stop is None:
return index
return slice(index, stop) | null |
174,468 | from abc import abstractmethod, ABCMeta
from collections.abc import Sequence, Hashable
from numbers import Integral
import operator
from pyrsistent._transformations import transform
_EMPTY_PVECTOR = PythonPVector(0, SHIFT, [], [])
The provided code snippet includes necessary dependencies for implementing the `python_p... | Create a new persistent vector containing the elements in iterable. >>> v1 = pvector([1, 2, 3]) >>> v1 pvector([1, 2, 3]) |
174,469 |
def nofollow(attrs, new=False):
href_key = (None, "href")
if href_key not in attrs:
return attrs
if attrs[href_key].startswith("mailto:"):
return attrs
rel_key = (None, "rel")
rel_values = [val for val in attrs.get(rel_key, "").split(" ") if val]
if "nofollow" not in [rel_va... | null |
174,470 |
def target_blank(attrs, new=False):
href_key = (None, "href")
if href_key not in attrs:
return attrs
if attrs[href_key].startswith("mailto:"):
return attrs
attrs[(None, "target")] = "_blank"
return attrs | null |
174,471 | import re
from urllib.parse import quote
from bleach import callbacks as linkify_callbacks
from bleach import html5lib_shim
TLDS = """ac ad ae aero af ag ai al am an ao aq ar arpa as asia at au aw ax az
ba bb bd be bf bg bh bi biz bj bm bn bo br bs bt bv bw by bz ca cat
cc cd cf cg ch ci ck cl cm cn co co... | Builds the url regex used by linkifier If you want a different set of tlds or allowed protocols, pass those in and stomp on the existing ``url_re``:: from bleach import linkifier my_url_re = linkifier.build_url_re(my_tlds_list, my_protocols) linker = LinkifyFilter(url_re=my_url_re) |
174,472 | import re
from urllib.parse import quote
from bleach import callbacks as linkify_callbacks
from bleach import html5lib_shim
TLDS = """ac ad ae aero af ag ai al am an ao aq ar arpa as asia at au aw ax az
ba bb bd be bf bg bh bi biz bj bm bn bo br bs bt bv bw by bz ca cat
cc cd cf cg ch ci ck cl cm cn co co... | Builds the email regex used by linkifier If you want a different set of tlds, pass those in and stomp on the existing ``email_re``:: from bleach import linkifier my_email_re = linkifier.build_email_re(my_tlds_list) linker = LinkifyFilter(email_re=my_url_re) |
174,473 | import re
import string
import warnings
from bleach._vendor.html5lib import ( # noqa: E402 module level import not at top of file
HTMLParser,
getTreeWalker,
)
from bleach._vendor.html5lib import (
constants,
)
from bleach._vendor.html5lib.constants import ( # noqa: E402 module level import not at top of ... | Converts all found entities in the text :arg text: the text to convert entities in :returns: unicode text with converted entities |
174,474 | from itertools import chain
import re
import warnings
from xml.sax.saxutils import unescape
from bleach import html5lib_shim
from bleach import parse_shim
The provided code snippet includes necessary dependencies for implementing the `attribute_filter_factory` function. Write a Python function `def attribute_filter_fa... | Generates attribute filter function for the given attributes value The attributes value can take one of several shapes. This returns a filter function appropriate to the attributes value. One nice thing about this is that there's less if/then shenanigans in the ``allow_token`` method. |
174,475 | from __future__ import absolute_import, division, unicode_literals
import re
import warnings
from .constants import DataLossWarning
reChar = re.compile(r"#x([\d|A-F]{4,4})")
reCharRange = re.compile(r"\[#x([\d|A-F]{4,4})-#x([\d|A-F]{4,4})\]")
def normaliseCharList(charList):
def hexToInt(hex_str):
def charStringToList... | null |
174,478 | from __future__ import absolute_import, division, unicode_literals
from types import ModuleType
from six import text_type, PY3
class ModuleType:
__doc__: Optional[str]
__file__: Optional[str]
__name__: str
__package__: Optional[str]
__path__: Optional[Iterable[str]]
__dict__: Dict[str, Any]
... | null |
174,480 | from __future__ import absolute_import, division, unicode_literals
from collections import OrderedDict
import re
from six import string_types
from . import base
from .._utils import moduleFactoryFactory
tag_regexp = re.compile("{([^}]*)}(.*)")
class OrderedDict(dict):
def __init__(self, data=None, **kwargs):
... | null |
174,481 | from __future__ import absolute_import, division, unicode_literals
from six import text_type
from collections import OrderedDict
from lxml import etree
from ..treebuilders.etree import tag_regexp
from . import base
from .. import _ihatexml
text_type = str
def ensure_str(s):
if s is None:
return None
e... | null |
174,484 | from __future__ import absolute_import, division, unicode_literals
from six import text_type
from six.moves import http_client, urllib
import codecs
import re
from io import BytesIO, StringIO
import webencodings
from .constants import EOF, spaceCharacters, asciiLetters, asciiUppercase
from .constants import _ReparseExc... | null |
174,487 | from __future__ import absolute_import, division, unicode_literals
from six import text_type
import re
from copy import copy
from . import base
from .. import _ihatexml
from .. import constants
from ..constants import namespaces
from .._utils import moduleFactoryFactory
tag_regexp = re.compile("{([^}]*)}(.*)")
text_ty... | null |
174,491 | from __future__ import absolute_import, division, unicode_literals
from six import with_metaclass, viewkeys
import types
from . import _inputstream
from . import _tokenizer
from . import treebuilders
from .treebuilders.base import Marker
from . import _utils
from .constants import (
spaceCharacters, asciiUpper2Lowe... | null |
174,492 | from __future__ import absolute_import, division, unicode_literals
from six import with_metaclass, viewkeys
import types
from . import _inputstream
from . import _tokenizer
from . import treebuilders
from .treebuilders.base import Marker
from . import _utils
from .constants import (
spaceCharacters, asciiUpper2Lowe... | null |
174,493 | from __future__ import absolute_import, division, unicode_literals
from six import text_type
import re
from codecs import register_error, xmlcharrefreplace_errors
from .constants import voidElements, booleanAttributes, spaceCharacters
from .constants import rcdataElements, entities, xmlEntities
from . import treewalker... | null |
174,497 | import re
import sys
import collections
from collections import namedtuple
class DefragResult(_DefragResultBase, _ResultMixinStr):
__slots__ = ()
def geturl(self):
if self.fragment:
return self.url + '#' + self.fragment
else:
return self.url
class SplitResult(_SplitResult... | null |
174,498 | import re
import sys
import collections
uses_netloc = ['', 'ftp', 'http', 'gopher', 'nntp', 'telnet',
'imap', 'wais', 'file', 'mms', 'https', 'shttp',
'snews', 'prospero', 'rtsp', 'rtspu', 'rsync',
'svn', 'svn+ssh', 'sftp', 'nfs', 'git', 'git+ssh',
'ws', 'wss'... | Join a base URL and a possibly relative URL to form an absolute interpretation of the latter. |
174,499 | import re
import sys
import collections
def _coerce_args(*args):
# Invokes decode if necessary to create str args
# and returns the coerced inputs along with
# an appropriate result coercion function
# - noop for str inputs
# - encoding function otherwise
str_input = isinstance(args[0], str)... | Removes any existing fragment from URL. Returns a tuple of the defragmented URL and the fragment. If the URL contained no fragments, the second element is the empty string. |
174,500 | import re
import sys
import collections
from collections import namedtuple
def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
encoding='utf-8', errors='replace', max_num_fields=None, separator='&'):
"""Parse a query given as a string argument.
Arguments:
qs: percent-encod... | Parse a query given as a string argument. Arguments: qs: percent-encoded query string to be parsed keep_blank_values: flag indicating whether blank values in percent-encoded queries should be treated as blank strings. A true value indicates that blanks should be retained as blank strings. The default false value indica... |
174,501 | import re
import sys
import collections
from collections import namedtuple
def unquote(string, encoding='utf-8', errors='replace'):
"""Replace %xx escapes by their single-character equivalent. The optional
encoding and errors parameters specify how to decode percent-encoded
sequences into Unicode characters... | Like unquote(), but also replace plus signs by spaces, as required for unquoting HTML form values. unquote_plus('%7e/abc+def') -> '~/abc def' |
174,502 | import re
import sys
import collections
from collections import namedtuple
def quote_plus(string, safe='', encoding=None, errors=None):
"""Like quote(), but also replace ' ' with '+', as required for quoting
HTML form values. Plus signs in the original string are escaped unless
they are included in safe. It... | Encode a dict or sequence of two-element tuples into a URL query string. If any values in the query arg are sequences and doseq is true, each sequence element is converted to a separate parameter. If the query arg is a sequence of two-element tuples, the order of the parameters in the output will match the order of par... |
174,503 | import re
import sys
import collections
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `to_bytes` function. Write a Python function `def to_bytes(url)` to solve the following problem:
to_bytes(u"URL") --> 'URL'.
Here is the function:
def to_bytes(url... | to_bytes(u"URL") --> 'URL'. |
174,504 | import re
import sys
import collections
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `unwrap` function. Write a Python function `def unwrap(url)` to solve the following problem:
unwrap('<URL:type://host/path>') --> 'type://host/path'.
Here is the fu... | unwrap('<URL:type://host/path>') --> 'type://host/path'. |
174,505 | import re
import sys
import collections
from collections import namedtuple
_typeprog = None
The provided code snippet includes necessary dependencies for implementing the `splittype` function. Write a Python function `def splittype(url)` to solve the following problem:
splittype('type:opaquestring') --> 'type', 'opaqu... | splittype('type:opaquestring') --> 'type', 'opaquestring'. |
174,506 | import re
import sys
import collections
from collections import namedtuple
_hostprog = None
The provided code snippet includes necessary dependencies for implementing the `splithost` function. Write a Python function `def splithost(url)` to solve the following problem:
splithost('//host[:port]/path') --> 'host[:port]'... | splithost('//host[:port]/path') --> 'host[:port]', '/path'. |
174,507 | import re
import sys
import collections
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `splituser` function. Write a Python function `def splituser(host)` to solve the following problem:
splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host... | splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'. |
174,508 | import re
import sys
import collections
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `splitpasswd` function. Write a Python function `def splitpasswd(user)` to solve the following problem:
splitpasswd('user:passwd') -> 'user', 'passwd'.
Here is the ... | splitpasswd('user:passwd') -> 'user', 'passwd'. |
174,509 | import re
import sys
import collections
from collections import namedtuple
_portprog = None
The provided code snippet includes necessary dependencies for implementing the `splitport` function. Write a Python function `def splitport(host)` to solve the following problem:
splitport('host:port') --> 'host', 'port'.
Here... | splitport('host:port') --> 'host', 'port'. |
174,510 | import re
import sys
import collections
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `splitnport` function. Write a Python function `def splitnport(host, defport=-1)` to solve the following problem:
Split host and port, returning numeric port. Return... | Split host and port, returning numeric port. Return given default port if no ':' found; defaults to -1. Return numerical port if a valid number are found after ':'. Return None if ':' but not a valid number. |
174,511 | import re
import sys
import collections
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `splitquery` function. Write a Python function `def splitquery(url)` to solve the following problem:
splitquery('/path?query') --> '/path', 'query'.
Here is the fun... | splitquery('/path?query') --> '/path', 'query'. |
174,512 | import re
import sys
import collections
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `splittag` function. Write a Python function `def splittag(url)` to solve the following problem:
splittag('/path#tag') --> '/path', 'tag'.
Here is the function:
de... | splittag('/path#tag') --> '/path', 'tag'. |
174,513 | import re
import sys
import collections
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `splitattr` function. Write a Python function `def splitattr(url)` to solve the following problem:
splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['att... | splitattr('/path;attr1=value1;attr2=value2;...') -> '/path', ['attr1=value1', 'attr2=value2', ...]. |
174,514 | import re
import sys
import collections
from collections import namedtuple
The provided code snippet includes necessary dependencies for implementing the `splitvalue` function. Write a Python function `def splitvalue(attr)` to solve the following problem:
splitvalue('attr=value') --> 'attr', 'value'.
Here is the func... | splitvalue('attr=value') --> 'attr', 'value'. |
174,515 | from html.entities import codepoint2name
from collections import defaultdict
import codecs
import re
import logging
import string
chardet_module = None
if chardet_module:
else:
from html.entities import html5
def chardet_dammit(s):
if isinstance(s, str):
return None
return chardet_module.de... | null |
174,516 | from html.entities import codepoint2name
from collections import defaultdict
import codecs
import re
import logging
import string
from html.entities import html5
def chardet_dammit(s):
return None | null |
174,517 | from io import BytesIO
from io import StringIO
from lxml import etree
from bs4.element import (
Comment,
Doctype,
NamespacedAttribute,
ProcessingInstruction,
XMLProcessingInstruction,
)
from bs4.builder import (
DetectsXMLParsedAsHTML,
FAST,
HTML,
HTMLTreeBuilder,
PERMISSIVE,
... | Invert a dictionary. |
174,518 | import re
import sys
import warnings
from bs4.css import CSS
from bs4.formatter import (
Formatter,
HTMLFormatter,
XMLFormatter,
)
The provided code snippet includes necessary dependencies for implementing the `_alias` function. Write a Python function `def _alias(attr)` to solve the following problem:
Ali... | Alias one attribute name to another for backward compatibility |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.