id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
174,304
import asyncio import collections import errno import io import numbers import os import socket import ssl import sys import re from tornado.concurrent import Future, future_set_result_unless_cancelled from tornado import ioloop from tornado.log import gen_log from tornado.netutil import ssl_wrap_socket, _client_ssl_de...
null
174,305
import datetime from io import StringIO import linecache import os.path import posixpath import re import threading from tornado import escape from tornado.log import app_log from tornado.util import ObjectDict, exec_in, unicode_type from typing import Any, Union, Callable, List, Dict, Iterable, Optional, TextIO import...
null
174,306
import datetime from io import StringIO import linecache import os.path import posixpath import re import threading from tornado import escape from tornado.log import app_log from tornado.util import ObjectDict, exec_in, unicode_type from typing import Any, Union, Callable, List, Dict, Iterable, Optional, TextIO import...
null
174,307
import socket import sys import twisted.internet.abstract import twisted.internet.asyncioreactor from twisted.internet.defer import Deferred from twisted.python import failure import twisted.names.cache import twisted.names.client import twisted.names.hosts import twisted.names.resolve from tornado.concurrent i...
Install ``AsyncioSelectorReactor`` as the default Twisted reactor. .. deprecated:: 5.1 This function is provided for backwards compatibility; code that does not require compatibility with older versions of Tornado should use ``twisted.internet.asyncioreactor.install()`` directly. .. versionchanged:: 6.0.3 In Tornado 5....
174,308
import socket import sys import twisted.internet.abstract import twisted.internet.asyncioreactor from twisted.internet.defer import Deferred from twisted.python import failure import twisted.names.cache import twisted.names.client import twisted.names.hosts import twisted.names.resolve from tornado.concurrent i...
null
174,309
import asyncio import atexit import concurrent.futures import errno import functools import select import socket import sys import threading import typing import warnings from tornado.gen import convert_yielded from tornado.ioloop import IOLoop, _Selectable from typing import Any, TypeVar, Awaitable, Callable, Union, O...
null
174,310
import asyncio import atexit import concurrent.futures import errno import functools import select import socket import sys import threading import typing import warnings from tornado.gen import convert_yielded from tornado.ioloop import IOLoop, _Selectable from typing import Any, TypeVar, Awaitable, Callable, Union, O...
null
174,311
import asyncio import atexit import concurrent.futures import errno import functools import select import socket import sys import threading import typing import warnings from tornado.gen import convert_yielded from tornado.ioloop import IOLoop, _Selectable from typing import Any, TypeVar, Awaitable, Callable, Union, O...
Convert an `asyncio.Future` to a `tornado.concurrent.Future`. .. versionadded:: 4.1 .. deprecated:: 5.0 Tornado ``Futures`` have been merged with `asyncio.Future`, so this method is now a no-op.
174,312
import asyncio import atexit import concurrent.futures import errno import functools import select import socket import sys import threading import typing import warnings from tornado.gen import convert_yielded from tornado.ioloop import IOLoop, _Selectable from typing import Any, TypeVar, Awaitable, Callable, Union, O...
Convert a Tornado yieldable object to an `asyncio.Future`. .. versionadded:: 4.1 .. versionchanged:: 4.3 Now accepts any yieldable object, not just `tornado.concurrent.Future`. .. deprecated:: 5.0 Tornado ``Futures`` have been merged with `asyncio.Future`, so this method is now equivalent to `tornado.gen.convert_yielde...
174,313
import os import sys The provided code snippet includes necessary dependencies for implementing the `wait` function. Write a Python function `def wait() -> None` to solve the following problem: Wait for a watched file to change, then restart the process. Intended to be used at the end of scripts like unit test runners...
Wait for a watched file to change, then restart the process. Intended to be used at the end of scripts like unit test runners, to run the tests again after any source file changes (but see also the command-line interface in `main`)
174,314
import os import sys The provided code snippet includes necessary dependencies for implementing the `watch` function. Write a Python function `def watch(filename: str) -> None` to solve the following problem: Add a file to the watch list. All imported modules are watched by default. Here is the function: def watch(f...
Add a file to the watch list. All imported modules are watched by default.
174,315
import os import sys class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = se...
Add a function to be called before reloading the process. Note that for open file and socket handles it is generally preferable to set the ``FD_CLOEXEC`` flag (using `fcntl` or `os.set_inheritable`) instead of using a reload hook to close them.
174,316
import re from functools import partial from tornado import httputil from tornado.httpserver import _CallableAdapter from tornado.escape import url_escape, url_unescape, utf8 from tornado.log import app_log from tornado.util import basestring_type, import_object, re_unescape, unicode_type from typing import Any, Union,...
null
174,317
import re from functools import partial from tornado import httputil from tornado.httpserver import _CallableAdapter from tornado.escape import url_escape, url_unescape, utf8 from tornado.log import app_log from tornado.util import basestring_type, import_object, re_unescape, unicode_type from typing import Any, Union,...
null
174,318
import re from functools import partial from tornado import httputil from tornado.httpserver import _CallableAdapter from tornado.escape import url_escape, url_unescape, utf8 from tornado.log import app_log from tornado.util import basestring_type, import_object, re_unescape, unicode_type from typing import Any, Union,...
None-safe wrapper around url_unescape to handle unmatched optional groups correctly. Note that args are passed as bytes so the handler can decide what encoding to use.
174,319
import html.entities import json import re import urllib.parse from tornado.util import unicode_type import typing from typing import Union, Any, Optional, Dict, List, Callable _unicode = to_unicode def _convert_entity(m: typing.Match) -> str: if m.group(1) == "#": try: if m.group(2)[:1].lower()...
Un-escapes an XML-escaped string.
174,320
import html.entities import json import re import urllib.parse from tornado.util import unicode_type import typing from typing import Union, Any, Optional, Dict, List, Callable Any = object() The provided code snippet includes necessary dependencies for implementing the `json_encode` function. Write a Python function...
JSON-encodes the given Python object.
174,321
import html.entities import json import re import urllib.parse from tornado.util import unicode_type import typing from typing import Union, Any, Optional, Dict, List, Callable to_basestring = to_unicode Any = object() Union: _SpecialForm = ... The provided code snippet includes necessary dependencies for impleme...
Returns Python objects for the given JSON string. Supports both `str` and `bytes` inputs.
174,322
import html.entities import json import re import urllib.parse from tornado.util import unicode_type import typing from typing import Union, Any, Optional, Dict, List, Callable The provided code snippet includes necessary dependencies for implementing the `squeeze` function. Write a Python function `def squeeze(value:...
Replace all sequences of whitespace chars with a single space.
174,323
import html.entities import json import re import urllib.parse from tornado.util import unicode_type import typing from typing import Union, Any, Optional, Dict, List, Callable def utf8(value: bytes) -> bytes: pass def utf8(value: str) -> bytes: pass def utf8(value: None) -> None: pass def utf8(value: Union...
Returns a URL-encoded version of the given value. If ``plus`` is true (the default), spaces will be represented as "+" instead of "%20". This is appropriate for query strings but not for the path component of a URL. Note that this default is the reverse of Python's urllib module. .. versionadded:: 3.1 The ``plus`` argu...
174,324
import html.entities import json import re import urllib.parse from tornado.util import unicode_type import typing from typing import Union, Any, Optional, Dict, List, Callable def to_unicode(value: str) -> str: pass def to_unicode(value: bytes) -> str: pass def to_unicode(value: None) -> None: pass def to_...
Walks a simple data structure, converting byte strings to unicode. Supports lists, tuples, and dictionaries.
174,325
import html.entities import json import re import urllib.parse from tornado.util import unicode_type import typing from typing import Union, Any, Optional, Dict, List, Callable def xhtml_escape(value: Union[str, bytes]) -> str: """Escapes a string so it is valid within HTML or XML. Escapes the characters ``<``,...
Converts plain text into HTML with links. For example: ``linkify("Hello http://tornadoweb.org!")`` would return ``Hello <a href="http://tornadoweb.org">http://tornadoweb.org</a>!`` Parameters: * ``shorten``: Long urls will be shortened for display. * ``extra_params``: Extra text to include in the link tag, or a callabl...
174,326
import html.entities import json import re import urllib.parse from tornado.util import unicode_type import typing from typing import Union, Any, Optional, Dict, List, Callable Dict = _Alias() def _build_unicode_map() -> Dict[str, str]: unicode_map = {} for name, value in html.entities.name2codepoint.items():...
null
174,327
import codecs import csv import datetime import gettext import glob import os import re from tornado import escape from tornado.log import gen_log from tornado._locale_data import LOCALE_NAMES from typing import Iterable, Any, Union, Dict, Optional class Locale(object): """Object representing a locale. After ca...
Returns the closest match for the given locale codes. We iterate over all given locale codes in order. If we have a tight or a loose match for the code (e.g., "en" for "en_US"), we return the locale. Otherwise we move to the next code in the list. By default we return ``en_US`` if no translations are found for any of t...
174,328
import codecs import csv import datetime import gettext import glob import os import re from tornado import escape from tornado.log import gen_log from tornado._locale_data import LOCALE_NAMES from typing import Iterable, Any, Union, Dict, Optional _default_locale = "en_US" _translations = {} _supported_locales = froz...
Sets the default locale. The default locale is assumed to be the language used for all strings in the system. The translations loaded from disk are mappings from the default locale to the destination locale. Consequently, you don't need to create a translation file for the default locale.
174,329
import codecs import csv import datetime import gettext import glob import os import re from tornado import escape from tornado.log import gen_log from tornado._locale_data import LOCALE_NAMES from typing import Iterable, Any, Union, Dict, Optional _default_locale = "en_US" _translations = {} _supported_locales = froz...
Loads translations from CSV files in a directory. Translations are strings with optional Python-style named placeholders (e.g., ``My name is %(name)s``) and their associated translations. The directory should have translation files of the form ``LOCALE.csv``, e.g. ``es_GT.csv``. The CSV files should have two or three c...
174,330
import codecs import csv import datetime import gettext import glob import os import re from tornado import escape from tornado.log import gen_log from tornado._locale_data import LOCALE_NAMES from typing import Iterable, Any, Union, Dict, Optional _default_locale = "en_US" _translations = {} _supported_locales = froz...
Loads translations from `gettext`'s locale tree Locale tree is similar to system's ``/usr/share/locale``, like:: {directory}/{lang}/LC_MESSAGES/{domain}.mo Three steps are required to have your app translated: 1. Generate POT translation file:: xgettext --language=Python --keyword=_:1,2 -d mydomain file1.py file2.html ...
174,331
import codecs import csv import datetime import gettext import glob import os import re from tornado import escape from tornado.log import gen_log from tornado._locale_data import LOCALE_NAMES from typing import Iterable, Any, Union, Dict, Optional _supported_locales = frozenset([_default_locale]) class Iterable(Proto...
Returns a list of all the supported locale codes.
174,332
import datetime import numbers import re import sys import os import textwrap from tornado.escape import _unicode, native_str from tornado.log import define_logging_options from tornado.util import basestring_type, exec_in from typing import ( Any, Iterator, Iterable, Tuple, Set, Dict, Calla...
Parses global options from the command line. See `OptionParser.parse_command_line`.
174,333
import datetime import numbers import re import sys import os import textwrap from tornado.escape import _unicode, native_str from tornado.log import define_logging_options from tornado.util import basestring_type, exec_in from typing import ( Any, Iterator, Iterable, Tuple, Set, Dict, Calla...
Parses global options from a config file. See `OptionParser.parse_config_file`.
174,334
import datetime import numbers import re import sys import os import textwrap from tornado.escape import _unicode, native_str from tornado.log import define_logging_options from tornado.util import basestring_type, exec_in from typing import ( Any, Iterator, Iterable, Tuple, Set, Dict, Calla...
Prints all the command line options to stderr (or another file). See `OptionParser.print_help`.
174,335
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Map a header name to Http-Header-Case. >>> _normalize_header("coNtent-TYPE") 'Content-Type'
174,336
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Concatenate url and arguments regardless of whether url has existing query parameters. ``args`` may be either a dictionary or a list of key-value pairs (the latter allows for multiple values with the same key. >>> url_concat("http://example.com/foo", dict(c="d")) 'http://example.com/foo?c=d' >>> url_concat("http://exam...
174,337
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Parses a Range header. Returns either ``None`` or tuple ``(start, end)``. Note that while the HTTP headers use inclusive byte positions, this method returns indexes suitable for use in slices. >>> start, end = _parse_request_range("bytes=1-2") >>> start, end (1, 3) >>> [0, 1, 2, 3, 4][start:end] [1, 2] >>> _parse_reque...
174,338
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Returns a suitable Content-Range header: >>> print(_get_content_range(None, 1, 4)) bytes 0-0/4 >>> print(_get_content_range(1, 3, 4)) bytes 1-2/4 >>> print(_get_content_range(None, None, 4)) bytes 0-3/4
174,339
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Parses a form request body. Supports ``application/x-www-form-urlencoded`` and ``multipart/form-data``. The ``content_type`` parameter should be a string and ``body`` should be a byte string. The ``arguments`` and ``files`` parameters are dictionaries that will be updated with the parsed contents.
174,340
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Formats a timestamp in the format used by HTTP. The argument may be a numeric timestamp as returned by `time.time`, a time tuple as returned by `time.gmtime`, or a `datetime.datetime` object. >>> format_timestamp(1359312200) 'Sun, 27 Jan 2013 18:43:20 GMT'
174,341
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Returns a (method, path, version) tuple for an HTTP 1.x request line. The response is a `collections.namedtuple`. >>> parse_request_start_line("GET /foo HTTP/1.1") RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
174,342
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Returns a (version, code, reason) tuple for an HTTP 1.x response line. The response is a `collections.namedtuple`. >>> parse_response_start_line("HTTP/1.1 200 OK") ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')
174,343
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Inverse of _parse_header. >>> _encode_header('permessage-deflate', ... {'client_max_window_bits': 15, 'client_no_context_takeover': None}) 'permessage-deflate; client_max_window_bits=15; client_no_context_takeover'
174,344
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Encodes a username/password pair in the format used by HTTP auth. The return value is a byte string in the form ``username:password``. .. versionadded:: 5.1
174,345
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
null
174,346
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Returns ``(host, port)`` tuple from ``netloc``. Returned ``port`` will be ``None`` if not present. .. versionadded:: 4.1
174,347
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Generator converting a result of ``parse_qs`` back to name-value pairs. .. versionadded:: 5.0
174,348
import calendar import collections.abc import copy import datetime import email.utils from functools import lru_cache from http.client import responses import http.cookies import re from ssl import SSLError import time import unicodedata from urllib.parse import urlencode, urlparse, urlunparse, parse_qsl from tornado.e...
Parse a ``Cookie`` HTTP header into a dict of name/value pairs. This function attempts to mimic browser cookie parsing behavior; it specifically does not follow any of the cookie-related RFCs (because browsers don't either). The algorithm used is identical to that used by Django version 1.9.10. .. versionadded:: 4.4.2
174,349
import asyncio from concurrent import futures import functools import sys import types from tornado.log import app_log import typing from typing import Any, Callable, Optional, Tuple, Union Future = asyncio.Future def chain_future(a: "Future[_T]", b: "Future[_T]") -> None: """Chain two futures together so that when...
Decorator to run a synchronous method asynchronously on an executor. Returns a future. The executor to be used is determined by the ``executor`` attributes of ``self``. To use a different attribute name, pass a keyword argument to the decorator:: @run_on_executor(executor='_thread_pool') def foo(self): pass This decora...
174,350
import base64 import binascii import datetime import email.utils import functools import gzip import hashlib import hmac import http.cookies from inspect import isclass from io import BytesIO import mimetypes import numbers import os.path import re import socket import sys import threading import time import tornado im...
Apply to `RequestHandler` subclasses to enable streaming body support. This decorator implies the following changes: * `.HTTPServerRequest.body` is undefined, and body arguments will not be included in `RequestHandler.get_argument`. * `RequestHandler.prepare` is called when the request headers have been read instead of...
174,351
import base64 import binascii import datetime import email.utils import functools import gzip import hashlib import hmac import http.cookies from inspect import isclass from io import BytesIO import mimetypes import numbers import os.path import re import socket import sys import threading import time import tornado im...
null
174,352
import base64 import binascii import datetime import email.utils import functools import gzip import hashlib import hmac import http.cookies from inspect import isclass from io import BytesIO import mimetypes import numbers import os.path import re import socket import sys import threading import time import tornado im...
Use this decorator to remove trailing slashes from the request path. For example, a request to ``/foo/`` would redirect to ``/foo`` with this decorator. Your request handler mapping should use a regular expression like ``r'/foo/*'`` in conjunction with using the decorator.
174,353
import base64 import binascii import datetime import email.utils import functools import gzip import hashlib import hmac import http.cookies from inspect import isclass from io import BytesIO import mimetypes import numbers import os.path import re import socket import sys import threading import time import tornado im...
Use this decorator to add a missing trailing slash to the request path. For example, a request to ``/foo`` would redirect to ``/foo/`` with this decorator. Your request handler mapping should use a regular expression like ``r'/foo/?'`` in conjunction with using the decorator.
174,354
import base64 import binascii import datetime import email.utils import functools import gzip import hashlib import hmac import http.cookies from inspect import isclass from io import BytesIO import mimetypes import numbers import os.path import re import socket import sys import threading import time import tornado im...
Decorate methods with this to require that the user be logged in. If the user is not logged in, they will be redirected to the configured `login url <RequestHandler.get_login_url>`. If you configure a login url with a query parameter, Tornado will assume you know what you're doing and use it as-is. If not, it will add ...
174,355
import base64 import binascii import datetime import email.utils import functools import gzip import hashlib import hmac import http.cookies from inspect import isclass from io import BytesIO import mimetypes import numbers import os.path import re import socket import sys import threading import time import tornado im...
null
174,356
import base64 import binascii import datetime import email.utils import functools import gzip import hashlib import hmac import http.cookies from inspect import isclass from io import BytesIO import mimetypes import numbers import os.path import re import socket import sys import threading import time import tornado im...
null
174,357
import base64 import binascii import datetime import email.utils import functools import gzip import hashlib import hmac import http.cookies from inspect import isclass from io import BytesIO import mimetypes import numbers import os.path import re import socket import sys import threading import time import tornado im...
null
174,358
import base64 import binascii import datetime import email.utils import functools import gzip import hashlib import hmac import http.cookies from inspect import isclass from io import BytesIO import mimetypes import numbers import os.path import re import socket import sys import threading import time import tornado im...
null
174,359
import os import multiprocessing import signal import subprocess import sys import time from binascii import hexlify from tornado.concurrent import ( Future, future_set_result_unless_cancelled, future_set_exception_unless_cancelled, ) from tornado import ioloop from tornado.iostream import PipeIOStream from...
Starts multiple worker processes. If ``num_processes`` is None or <= 0, we detect the number of cores available on this machine and fork that number of child processes. If ``num_processes`` is given and > 0, we fork that specific number of sub-processes. Since we use processes and not threads, there is no shared memory...
174,360
import collections import datetime import heapq from tornado import gen, ioloop from tornado.concurrent import Future, future_set_result_unless_cancelled from tornado.locks import Event from typing import Union, TypeVar, Generic, Awaitable, Optional import typing Future = asyncio.Future Union: _SpecialForm = ... def...
null
174,361
import sys from io import BytesIO import tornado from tornado import escape from tornado import httputil from tornado.log import access_log from typing import List, Tuple, Optional, Callable, Any, Dict, Text from types import TracebackType import typing def to_wsgi_str(s: bytes) -> str: assert isinstance(s, bytes)...
null
174,362
import asyncio import builtins import collections from collections.abc import Generator import concurrent.futures import datetime import functools from functools import singledispatch from inspect import isawaitable import sys import types from tornado.concurrent import ( Future, is_future, chain_future, ...
Converts ``x`` into a `.Future`. If ``x`` is already a `.Future`, it is simply returned; otherwise it is wrapped in a new `.Future`. This is suitable for use as ``result = yield gen.maybe_future(f())`` when you don't know whether ``f()`` returns a `.Future` or not. .. deprecated:: 4.3 This function only handles ``Futur...
174,363
import asyncio import builtins import collections from collections.abc import Generator import concurrent.futures import datetime import functools from functools import singledispatch from inspect import isawaitable import sys import types from tornado.concurrent import ( Future, is_future, chain_future, ...
Wraps a `.Future` (or other yieldable object) in a timeout. Raises `tornado.util.TimeoutError` if the input future does not complete before ``timeout``, which may be specified in any form allowed by `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time relative to `.IOLoop.time`) If the wrapped `.Futur...
174,364
import asyncio import concurrent.futures import errno import os import sys import socket import ssl import stat from tornado.concurrent import dummy_executor, run_on_executor from tornado.ioloop import IOLoop from tornado.util import Configurable, errno_from_exception from typing import List, Callable, Any, Type, Dict,...
Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP addresses, which is most common for mixed IPv4 and IPv6 use). Address may be either an IP address or hostname. If it's a hostname, the server will liste...
174,365
import asyncio import concurrent.futures import errno import os import sys import socket import ssl import stat from tornado.concurrent import dummy_executor, run_on_executor from tornado.ioloop import IOLoop from tornado.util import Configurable, errno_from_exception from typing import List, Callable, Any, Type, Dict,...
Creates a listening unix socket. If a socket with the given name already exists, it will be deleted. If any other file with that name exists, an exception will be raised. Returns a socket object (not a list of socket objects like `bind_sockets`)
174,366
import asyncio import concurrent.futures import errno import os import sys import socket import ssl import stat from tornado.concurrent import dummy_executor, run_on_executor from tornado.ioloop import IOLoop from tornado.util import Configurable, errno_from_exception from typing import List, Callable, Any, Type, Dict,...
Adds an `.IOLoop` event handler to accept new connections on ``sock``. When a connection is accepted, ``callback(connection, address)`` will be run (``connection`` is a socket object, and ``address`` is the address of the other end of the connection). Note that this signature is different from the ``callback(fd, events...
174,367
import asyncio import concurrent.futures import errno import os import sys import socket import ssl import stat from tornado.concurrent import dummy_executor, run_on_executor from tornado.ioloop import IOLoop from tornado.util import Configurable, errno_from_exception from typing import List, Callable, Any, Type, Dict,...
Returns ``True`` if the given string is a well-formed IP address. Supports IPv4 and IPv6.
174,368
import asyncio import concurrent.futures import errno import os import sys import socket import ssl import stat from tornado.concurrent import dummy_executor, run_on_executor from tornado.ioloop import IOLoop from tornado.util import Configurable, errno_from_exception from typing import List, Callable, Any, Type, Dict,...
null
174,369
import asyncio import concurrent.futures import errno import os import sys import socket import ssl import stat from tornado.concurrent import dummy_executor, run_on_executor from tornado.ioloop import IOLoop from tornado.util import Configurable, errno_from_exception from typing import List, Callable, Any, Type, Dict,...
Returns an ``ssl.SSLSocket`` wrapping the given socket. ``ssl_options`` may be either an `ssl.SSLContext` object or a dictionary (as accepted by `ssl_options_to_context`). Additional keyword arguments are passed to ``wrap_socket`` (either the `~ssl.SSLContext` method or the `ssl` module function as appropriate). .. ver...
174,370
import base64 import binascii import hashlib import hmac import time import urllib.parse import uuid from tornado import httpclient from tornado import escape from tornado.httputil import url_concat from tornado.util import unicode_type from tornado.web import RequestHandler from typing import List, Any, Dict, cast, It...
Calculates the HMAC-SHA1 OAuth signature for the given request. See http://oauth.net/core/1.0/#signing_process
174,371
import base64 import binascii import hashlib import hmac import time import urllib.parse import uuid from tornado import httpclient from tornado import escape from tornado.httputil import url_concat from tornado.util import unicode_type from tornado.web import RequestHandler from typing import List, Any, Dict, cast, It...
Calculates the HMAC-SHA1 OAuth 1.0a signature for the given request. See http://oauth.net/core/1.0a/#signing_process
174,372
import base64 import binascii import hashlib import hmac import time import urllib.parse import uuid from tornado import httpclient from tornado import escape from tornado.httputil import url_concat from tornado.util import unicode_type from tornado.web import RequestHandler from typing import List, Any, Dict, cast, It...
null
174,373
import logging import logging.handlers import sys from tornado.escape import _unicode from tornado.util import unicode_type, basestring_type try: import colorama # type: ignore except ImportError: colorama = None try: import curses except ImportError: curses = None # type: ignore from typing import Di...
null
174,374
import logging import logging.handlers import sys from tornado.escape import _unicode from tornado.util import unicode_type, basestring_type from typing import Dict, Any, cast, Optional _unicode = to_unicode Any = object() def _safe_unicode(s: Any) -> str: try: return _unicode(s) except UnicodeDecode...
null
174,375
import logging import logging.handlers import sys from tornado.escape import _unicode from tornado.util import unicode_type, basestring_type from typing import Dict, Any, cast, Optional def enable_pretty_logging( options: Any = None, logger: Optional[logging.Logger] = None ) -> None: """Turns on formatted loggi...
Add logging-related flags to ``options``. These options are present automatically on the default options instance; this method is only necessary if you have created your own `.OptionParser`. .. versionadded:: 4.2 This function existed in prior versions but was broken and undocumented until 4.2.
174,376
import abc import asyncio import base64 import hashlib import os import sys import struct import tornado.escape import tornado.web from urllib.parse import urlparse import zlib from tornado.concurrent import Future, future_set_result_unless_cancelled from tornado.escape import utf8, native_str, to_unicode from tornado ...
null
174,377
import abc import asyncio import base64 import hashlib import os import sys import struct import tornado.escape import tornado.web from urllib.parse import urlparse import zlib from tornado.concurrent import Future, future_set_result_unless_cancelled from tornado.escape import utf8, native_str, to_unicode from tornado ...
Client-side websocket support. Takes a url and returns a Future whose result is a `WebSocketClientConnection`. ``compression_options`` is interpreted in the same way as the return value of `.WebSocketHandler.get_compression_options`. The connection supports two styles of operation. In the coroutine style, the applicati...
174,378
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 a value...
Create notebook node(s) from a value.
174,379
from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass The provided code snippet includes necessary dependencies for implementing the `new_output` function. Write a Python function `def new_output( # noqa output_type=None, output_text=None, output_png=No...
Create a new code cell with input and output
174,380
from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass The provided code snippet includes necessary dependencies for implementing the `new_author` function. Write a Python function `def new_author(name=None, email=None, affiliation=None, url=None)` to solve the follo...
Create a new author.
174,381
from .nbbase import new_code_cell, new_notebook, new_text_cell, new_worksheet def new_code_cell( input=None, prompt_number=None, outputs=None, language="python", collapsed=False # noqa ): """Create a new code cell with input and output""" cell = NotebookNode() cell.cell_type = "code" if language i...
Convert a notebook to the v2 format. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert. from_version : int The version of the notebook to convert from.
174,382
from .nbbase import new_code_cell, new_notebook, new_text_cell, new_worksheet The provided code snippet includes necessary dependencies for implementing the `downgrade` function. Write a Python function `def downgrade(nb)` to solve the following problem: Convert a v2 notebook to v1. Parameters ---------- nb : Notebook...
Convert a v2 notebook to v1. Parameters ---------- nb : NotebookNode The Python representation of the notebook to convert.
174,383
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.
174,384
from base64 import decodebytes, encodebytes _multiline_outputs = ["text", "html", "svg", "latex", "javascript", "json"] The provided code snippet includes necessary dependencies for implementing the `rejoin_lines` function. Write a Python function `def rejoin_lines(nb)` to solve the following problem: rejoin multiline...
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,385
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,386
from base64 import decodebytes, encodebytes The provided code snippet includes necessary dependencies for implementing the `base64_decode` function. Write a Python function `def base64_decode(nb)` to solve the following problem: Restore all bytes objects in the notebook from base64-encoded strings. Note: This is never...
Restore all bytes objects in the notebook from base64-encoded strings. Note: This is never used
174,387
from base64 import decodebytes, encodebytes The provided code snippet includes necessary dependencies for implementing the `base64_encode` function. Write a Python function `def base64_encode(nb)` to solve the following problem: Base64 encode all bytes objects in the notebook. These will be b64-encoded unicode strings...
Base64 encode all bytes objects in the notebook. These will be b64-encoded unicode strings Note: This is never used
174,388
REMOVED_MSG = """\ Reading notebooks as XML has been removed to harden security and avoid possible denial-of-service attacks. The XML notebook format was deprecated before the Jupyter (previously IPython) Notebook was ever released. We are not aware of anyone using it, so we have removed it. If you were using this code...
REMOVED
174,389
REMOVED_MSG = """\ Reading notebooks as XML has been removed to harden security and avoid possible denial-of-service attacks. The XML notebook format was deprecated before the Jupyter (previously IPython) Notebook was ever released. We are not aware of anyone using it, so we have removed it. If you were using this code...
REMOVED
174,390
REMOVED_MSG = """\ Reading notebooks as XML has been removed to harden security and avoid possible denial-of-service attacks. The XML notebook format was deprecated before the Jupyter (previously IPython) Notebook was ever released. We are not aware of anyone using it, so we have removed it. If you were using this code...
REMOVED
174,391
import json import os import pprint import warnings from copy import deepcopy from textwrap import dedent from typing import Any, Optional, Tuple from ._imports import import_item from .corpus.words import generate_corpus_id from .json_compat import ValidationError, _validator_for_name, get_current_validator from .read...
Checks whether the given notebook JSON conforms to the current notebook format schema. Returns True if the JSON is valid, and False otherwise. To see the individual errors that were encountered, please use the `validate` function instead.
174,392
import json import os import pprint import warnings from copy import deepcopy from textwrap import dedent from typing import Any, Optional, Tuple from ._imports import import_item from .corpus.words import generate_corpus_id from .json_compat import ValidationError, _validator_for_name, get_current_validator from .read...
(from jsonschema._utils.format_as_index, copied to avoid relying on private API) Construct a single string containing indexing operations for the indices. For example, [1, 2, "foo"] -> [1][2]["foo"]
174,393
import json import os import pprint import warnings from copy import deepcopy from textwrap import dedent from typing import Any, Optional, Tuple from ._imports import import_item from .corpus.words import generate_corpus_id from .json_compat import ValidationError, _validator_for_name, get_current_validator from .read...
Truncate objects for use in validation tracebacks Cell and output lists are squashed, as are long strings, lists, and dicts.
174,394
import json import os import pprint import warnings from copy import deepcopy from textwrap import dedent from typing import Any, Optional, Tuple from ._imports import import_item from .corpus.words import generate_corpus_id from .json_compat import ValidationError, _validator_for_name, get_current_validator from .read...
Normalise a notebook prior to validation. This tries to implement a couple of normalisation steps to standardise notebooks and make validation easier. You should in general not rely on this function and make sure the notebooks that reach nbformat are already in a normal form. If not you likely have a bug, and may have ...
174,395
from collections.abc import Mapping from ._struct import Struct class NotebookNode(Struct): """A dict-like node with attribute-access""" def __setitem__(self, key, value): """Set an item on the notebook.""" if isinstance(value, Mapping) and not isinstance(value, NotebookNode): value ...
Convert dict to dict-like NotebookNode Recursively converts any dict in the container to a NotebookNode. This does not check that the contents of the dictionary make a valid notebook or part of a notebook.
174,396
import warnings 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...
Create notebook node(s) from an object.
174,397
import warnings from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass def str_passthrough(obj): """ Used to be cast_unicode, add this temporarily to make sure no further breakage. """ if not isinstance(obj, str): raise AssertionError retur...
Create a new output, to go in the ``cell.outputs`` list of a code cell.
174,398
import warnings from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass def str_passthrough(obj): """ Used to be cast_unicode, add this temporarily to make sure no further breakage. """ if not isinstance(obj, str): raise AssertionError retur...
Create a new code cell with input and output
174,399
import warnings from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass def str_passthrough(obj): """ Used to be cast_unicode, add this temporarily to make sure no further breakage. """ if not isinstance(obj, str): raise AssertionError retur...
Create a new text cell.
174,400
import warnings from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass def str_passthrough(obj): """ Used to be cast_unicode, add this temporarily to make sure no further breakage. """ if not isinstance(obj, str): raise AssertionError retur...
Create a new section cell with a given integer level.
174,401
import warnings from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass The provided code snippet includes necessary dependencies for implementing the `new_worksheet` function. Write a Python function `def new_worksheet(name=None, cells=None, metadata=None)` to solve ...
Create a worksheet by name with with a list of cells.
174,402
import warnings from nbformat._struct import Struct nbformat = 3 nbformat_minor = 0 class NotebookNode(Struct): """A notebook node object.""" pass def str_passthrough(obj): """ Used to be cast_unicode, add this temporarily to make sure no further breakage. """ if not isinstance(obj, str): ...
Create a notebook by name, id and a list of worksheets.
174,403
import warnings from nbformat._struct import Struct class NotebookNode(Struct): """A notebook node object.""" pass def str_passthrough(obj): """ Used to be cast_unicode, add this temporarily to make sure no further breakage. """ if not isinstance(obj, str): raise AssertionError retur...
Create a new author.