id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
170,410
from qtpy import QtCore, QtGui, QtSvg, QtWidgets The provided code snippet includes necessary dependencies for implementing the `save_svg` function. Write a Python function `def save_svg(string, parent=None)` to solve the following problem: Prompts the user to save an SVG document to disk. Parameters ---------- string...
Prompts the user to save an SVG document to disk. Parameters ---------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. Returns ------- The name of the file to which the document was saved, or None if the save was cancelled.
170,411
from qtpy import QtCore, QtGui, QtSvg, QtWidgets The provided code snippet includes necessary dependencies for implementing the `svg_to_clipboard` function. Write a Python function `def svg_to_clipboard(string)` to solve the following problem: Copy a SVG document to the clipboard. Parameters ---------- string : basest...
Copy a SVG document to the clipboard. Parameters ---------- string : basestring A Python string containing a SVG document.
170,412
from qtpy import QtCore, QtGui, QtSvg, QtWidgets The provided code snippet includes necessary dependencies for implementing the `svg_to_image` function. Write a Python function `def svg_to_image(string, size=None)` to solve the following problem: Convert a SVG document to a QImage. Parameters ---------- string : bases...
Convert a SVG document to a QImage. Parameters ---------- string : basestring A Python string containing a SVG document. size : QSize, optional The size of the image that is produced. If not specified, the SVG document's default size is used. Raises ------ ValueError If an invalid SVG string is provided. Returns ------...
170,413
import ipython_genutils.text as text from qtpy import QtCore, QtGui, QtWidgets The provided code snippet includes necessary dependencies for implementing the `html_tableify` function. Write a Python function `def html_tableify(item_matrix, select=None, header=None , footer=None) ` to solve the following problem: retur...
returnr a string for an html table
170,414
import io import os import re from qtpy import QtWidgets IMG_RE = re.compile(r'<img src="(?P<name>[\d]+)" />') def default_image_tag(match, path = None, format = "png"): """ Return (X)HTML mark-up for the image-tag given by match. This default implementation merely removes the image, and exists mostly for d...
Export the contents of the ConsoleWidget as HTML. Parameters ---------- html : unicode, A Python unicode string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable, optional (default None) Used to convert images. See ``default_image_tag()`` for information. inline : bool, optiona...
170,415
import io import os import re from qtpy import QtWidgets IMG_RE = re.compile(r'<img src="(?P<name>[\d]+)" />') def default_image_tag(match, path = None, format = "png"): """ Return (X)HTML mark-up for the image-tag given by match. This default implementation merely removes the image, and exists mostly for d...
Export the contents of the ConsoleWidget as XHTML with inline SVGs. Parameters ---------- html : unicode, A Python unicode string containing the Qt HTML to export. filename : str The file to be saved. image_tag : callable, optional (default None) Used to convert images. See ``default_image_tag()`` for information.
170,416
from qtpy import QtGui from qtconsole.qstringhelpers import qstring_length from pygments.formatters.html import HtmlFormatter from pygments.lexer import RegexLexer, _TokenType, Text, Error from pygments.lexers import Python3Lexer from pygments.styles import get_style_by_name def get_tokens_unprocessed(self, text, stack...
null
170,417
import os import signal import sys from warnings import warn from packaging.version import parse from qtpy import QtCore, QtGui, QtWidgets, QT_VERSION from traitlets.config.application import boolean_flag from traitlets.config.application import catch_config_error from qtconsole.jupyter_widget import JupyterWidget from...
null
170,418
import sys import webbrowser from functools import partial from threading import Thread from jupyter_core.paths import jupyter_runtime_dir from pygments.styles import get_all_styles from qtpy import QtGui, QtCore, QtWidgets from qtconsole import styles from qtconsole.jupyter_widget import JupyterWidget from qtconsole.u...
call a function in a simple thread, to prevent blocking
170,419
import inspect from typing import Any, Callable, Optional from jupyter_core.utils import ensure_async, run_sync Any = object() Optional: _SpecialForm = ... class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """...
Run a hook callback.
170,420
import math import numbers import re import types from binascii import b2a_base64 from datetime import datetime from typing import Dict Dict = _Alias() The provided code snippet includes necessary dependencies for implementing the `encode_images` function. Write a Python function `def encode_images(format_dict: Dict)...
b64-encodes images in a displaypub format dict Perhaps this should be handled in json_clean itself? Parameters ---------- format_dict : dict A dictionary of display data keyed by mime-type Returns ------- format_dict : dict A copy of the same dictionary, but binary image data ('image/png', 'image/jpeg' or 'application/...
170,421
import math import numbers import re import types from binascii import b2a_base64 from datetime import datetime from typing import Dict ISO8601 = "%Y-%m-%dT%H:%M:%S.%f" datetime.strptime("1", "%d") class datetime(date): min: ClassVar[datetime] max: ClassVar[datetime] resolution: ClassVar[timedelta] if...
Clean an object to ensure it's safe to encode in JSON. Atomic, immutable objects are returned unmodified. Sets and tuples are converted to lists, lists are copied and dicts are also copied. Note: dicts whose keys could cause collisions upon encoding (such as a dict with both the number 1 and the string '1' as keys) wil...
170,422
import asyncio import atexit import base64 import collections import datetime import re import signal import typing as t from contextlib import asynccontextmanager, contextmanager from queue import Empty from textwrap import dedent from time import monotonic from jupyter_client import KernelManager from jupyter_client....
Get the timestamp for a message.
170,423
import asyncio import atexit import base64 import collections import datetime import re import signal import typing as t from contextlib import asynccontextmanager, contextmanager from queue import Empty from textwrap import dedent from time import monotonic from jupyter_client import KernelManager from jupyter_client....
Execute a notebook's code, updating outputs within the notebook object. This is a convenient wrapper around NotebookClient. It returns the modified notebook object. Parameters ---------- nb : NotebookNode The notebook object to be executed cwd : str, optional If supplied, the kernel will run in this directory km : Asyn...
170,424
from collections import namedtuple import os from tornado import ( gen, web, ) from ..base.handlers import ( IPythonHandler, FilesRedirectHandler, path_regex, ) from ..utils import ( maybe_future, url_escape, ) from ..transutils import _ def namedtuple( typename: Union[str, unicode], field_names: U...
null
170,425
import errno import glob import json import os import copy from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode, Bool The provided code snippet includes necessary dependencies for implementing the `recursive_update` function. Write a Python function `def recursive_update(target, new...
Recursively update one dictionary using another. None values will delete their keys.
170,426
import errno import glob import json import os import copy from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode, Bool The provided code snippet includes necessary dependencies for implementing the `remove_defaults` function. Write a Python function `def remove_defaults(data, default...
Recursively remove items from dict that are already in defaults
170,427
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Determine whether a given URL is absolute
170,428
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Convert a local file path to a URL
170,429
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Convert a URL to a local file path
170,430
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Escape special characters in a URL path Turns '/foo bar/' into '/foo%20bar/'
170,431
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Unescape special characters in a URL path Turns '/foo%20bar/' into '/foo bar/'
170,432
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Is a file hidden? This only checks the file itself; it should be called in combination with checking the directory containing the file. Use is_hidden() instead to check the file and its parent directories. Parameters ---------- abs_path : unicode The absolute path to check. stat_res : os.stat_result, optional Ignored o...
170,433
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Is a file hidden? This only checks the file itself; it should be called in combination with checking the directory containing the file. Use is_hidden() instead to check the file and its parent directories. Parameters ---------- abs_path : unicode The absolute path to check. stat_res : os.stat_result, optional The resul...
170,434
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Is a file hidden or contained in a hidden directory? This will start with the rightmost path element and work backwards to the given root to see if a path is hidden or in a hidden directory. Hidden is determined by either name starting with '.' or the UF_HIDDEN flag as reported by stat. If abs_path is the same director...
170,435
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Fill in for os.path.samefile when it is unavailable (Windows+py2). Do a case-insensitive string comparison in this case plus comparing the full stat result (including times) because Windows + py2 doesn't support the stat fields needed for identifying if it's the same file (st_ino, st_dev). Only to be used if os.path.sa...
170,436
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Convert an API path to a filesystem path If given, root will be prepended to the path. root must be a filesystem path already.
170,437
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
check version string v >= check If dev/prerelease tags result in TypeError for string-number comparison, it is assumed that the dependency is satisfied. Users on dev branches are responsible for keeping their own packages up to date.
170,438
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
null
170,439
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Copy of IPython.utils.process.check_pid
170,440
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Like tornado's deprecated gen.maybe_future but more compatible with asyncio for recent versions of tornado
170,441
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
If async, runs maybe_async and blocks until it has executed, possibly creating an event loop. If not async, just returns maybe_async as it is the result of something that has already executed. Parameters ---------- maybe_async : async or non-async object The object to be executed, if it is async. Returns ------- result...
170,442
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Encodes a UNIX socket URL from a socket path for the `http+unix` URI form.
170,443
import asyncio import concurrent.futures import ctypes import errno import inspect import os import socket import stat import sys from distutils.version import LooseVersion from urllib.parse import quote, unquote, urlparse, urljoin from urllib.request import pathname2url from tornado.concurrent import Future as Tornado...
Checks whether a UNIX socket path on disk is in use by attempting to connect to it.
170,444
import importlib import sys from jupyter_core.paths import jupyter_config_path from ._version import __version__ from .config_manager import BaseJSONConfigManager from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X ) from traitlets import Bool from traitlets.uti...
Toggle a server extension. By default, toggles the extension in the system-wide Jupyter configuration location (e.g. /usr/local/etc/jupyter). Parameters ---------- import_name : str Importable Python module (dotted-notation) exposing the magic-named `load_jupyter_server_extension` function enabled : bool [default: None...
170,445
import importlib import sys from jupyter_core.paths import jupyter_config_path from ._version import __version__ from .config_manager import BaseJSONConfigManager from .extensions import ( BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED, GREEN_OK, RED_X ) from traitlets import Bool from traitlets.uti...
Load server extension metadata from a module. Returns a tuple of ( the package as loaded a list of server extension specs: [ { "module": "mockextension" } ] ) Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_server_extension_paths` function
170,446
import io import os import zipfile from tornado import gen, web, escape from tornado.log import app_log from ..base.handlers import ( IPythonHandler, FilesRedirectHandler, path_regex, ) from ..utils import maybe_future from nbformat import from_dict from ipython_genutils.py3compat import cast_bytes from ipython...
null
170,447
import io import os import zipfile from tornado import gen, web, escape from tornado.log import app_log from ..base.handlers import ( IPythonHandler, FilesRedirectHandler, path_regex, ) from ..utils import maybe_future from nbformat import from_dict from ipython_genutils.py3compat import cast_bytes from ipython...
Zip up the output and resource files and respond with the zip file. Returns True if it has served a zip file, False if there are no resource files, in which case we serve the plain output file.
170,448
import io import os import zipfile from tornado import gen, web, escape from tornado.log import app_log from ..base.handlers import ( IPythonHandler, FilesRedirectHandler, path_regex, ) from ..utils import maybe_future from nbformat import from_dict from ipython_genutils.py3compat import cast_bytes from ipython...
get an exporter, raising appropriate errors
170,449
import os import json from socket import gaierror from tornado import web from tornado.escape import json_encode, json_decode, url_escape from tornado.httpclient import HTTPClient, AsyncHTTPClient, HTTPError from ..services.kernels.kernelmanager import AsyncMappingKernelManager from ..services.sessions.sessionmanager i...
Make an async request to kernel gateway endpoint, returns a response
170,450
import os import io import tarfile import nbformat The provided code snippet includes necessary dependencies for implementing the `_jupyter_bundlerextension_paths` function. Write a Python function `def _jupyter_bundlerextension_paths()` to solve the following problem: Metadata for notebook bundlerextension Here is t...
Metadata for notebook bundlerextension
170,451
import os import io import tarfile import nbformat The provided code snippet includes necessary dependencies for implementing the `bundle` function. Write a Python function `def bundle(handler, model)` to solve the following problem: Create a compressed tarball containing the notebook document. Parameters ---------- h...
Create a compressed tarball containing the notebook document. Parameters ---------- handler : tornado.web.RequestHandler Handler that serviced the bundle request model : dict Notebook model from the configured ContentManager
170,452
import os import shutil import errno import nbformat import fnmatch import glob The provided code snippet includes necessary dependencies for implementing the `copy_filelist` function. Write a Python function `def copy_filelist(src, dst, src_relative_filenames)` to solve the following problem: Copies the given list of...
Copies the given list of files, relative to src, into dst, creating directories along the way as needed and ignore existence errors. Skips any files that do not exist. Does not create empty directories from src in dst. Parameters ---------- src: str Root of the source directory dst: str Root of the destination director...
170,453
import os import io import zipfile import notebook.bundler.tools as tools The provided code snippet includes necessary dependencies for implementing the `_jupyter_bundlerextension_paths` function. Write a Python function `def _jupyter_bundlerextension_paths()` to solve the following problem: Metadata for notebook bund...
Metadata for notebook bundlerextension
170,454
import os import io import zipfile import notebook.bundler.tools as tools The provided code snippet includes necessary dependencies for implementing the `bundle` function. Write a Python function `def bundle(handler, model)` to solve the following problem: Create a zip file containing the original notebook and files r...
Create a zip file containing the original notebook and files referenced from it. Retain the referenced files in paths relative to the notebook. Return the zip as a file download. Assumes the notebook and other files are all on local disk. Parameters ---------- handler : tornado.web.RequestHandler Handler that serviced ...
170,455
import sys import os from ..extensions import BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED from .._version import __version__ from notebook.config_manager import BaseJSONConfigManager from jupyter_core.paths import jupyter_config_path from traitlets.utils.importstring import import_item from traitlets...
Enables bundlers defined in a Python package. Returns whether each bundle defined in the packaged was enabled or not. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_bundlerextension_paths` function user : bool [default: True] Whether to enable in the user's nbconfig direc...
170,456
import sys import os from ..extensions import BaseExtensionApp, _get_config_dir, GREEN_ENABLED, RED_DISABLED from .._version import __version__ from notebook.config_manager import BaseJSONConfigManager from jupyter_core.paths import jupyter_config_path from traitlets.utils.importstring import import_item from traitlets...
Disables bundlers defined in a Python package. Returns whether each bundle defined in the packaged was enabled or not. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_bundlerextension_paths` function user : bool [default: True] Whether to enable in the user's nbconfig dire...
170,457
import notebook import asyncio import binascii import datetime import errno import functools import gettext import hashlib import hmac import importlib import inspect import ipaddress import json import logging import mimetypes import os import random import re import select import signal import socket import stat impo...
Generate a list of n random ports near the given port. The first 5 ports will be sequential, and the remaining n-5 will be randomly selected in the range [port-2*n, port+2*n].
170,458
import notebook import asyncio import binascii import datetime import errno import functools import gettext import hashlib import hmac import importlib import inspect import ipaddress import json import logging import mimetypes import os import random import re import select import signal import socket import stat impo...
Load the (URL pattern, handler) tuples for each component.
170,459
import notebook import asyncio import binascii import datetime import errno import functools import gettext import hashlib import hmac import importlib import inspect import ipaddress import json import logging import mimetypes import os import random import re import select import signal import socket import stat impo...
Shutdown a notebook server in a separate process. *server_info* should be a dictionary as produced by list_running_servers(). Will first try to request shutdown using /api/shutdown . On Unix, if the server is still running after *timeout* seconds, it will send SIGTERM. After another timeout, it escalates to SIGKILL. Re...
170,460
import notebook import asyncio import binascii import datetime import errno import functools import gettext import hashlib import hmac import importlib import inspect import ipaddress import json import logging import mimetypes import os import random import re import select import signal import socket import stat impo...
Iterate over the server info files of running notebook servers. Given a runtime directory, find nbserver-* files in the security directory, and yield dicts of their information, each one pertaining to a currently running notebook server instance.
170,461
from notebook.auth import passwd from getpass import getpass from notebook.config_manager import BaseJSONConfigManager from jupyter_core.paths import jupyter_config_dir import argparse import sys def getpass(prompt: str = ..., stream: Optional[TextIO] = ...) -> str: ... class BaseJSONConfigManager(LoggingConfigurable...
null
170,462
from contextlib import contextmanager import getpass import hashlib import json import os import random import traceback import warnings from ipython_genutils.py3compat import cast_bytes, str_to_bytes, cast_unicode from traitlets.config import Config, ConfigFileNotFound, JSONFileConfigLoader from jupyter_core.paths imp...
Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- >>> from notebook.auth.security i...
170,463
from contextlib import contextmanager import getpass import hashlib import json import os import random import traceback import warnings from ipython_genutils.py3compat import cast_bytes, str_to_bytes, cast_unicode from traitlets.config import Config, ConfigFileNotFound, JSONFileConfigLoader from jupyter_core.paths imp...
Ask user for password, store it in notebook json configuration file
170,464
import inspect from traitlets import ClassBasedTraitType, Undefined, warn try: from traitlets.utils.descriptions import describe except ImportError: import inspect import re import types def add_article(name, definite=False, capital=False): """Returns the string with a prepended article. ...
Return string that describes a value Parameters ---------- article : str or None A definite or indefinite article. If the article is indefinite (i.e. "a" or "an") the appropriate one will be infered. Thus, the arguments of ``describe`` can themselves represent what the resulting string will actually look like. If None,...
170,465
from datetime import tzinfo, timedelta, datetime UTC = tzUTC() class tzinfo: def tzname(self, dt: Optional[datetime]) -> Optional[str]: ... def utcoffset(self, dt: Optional[datetime]) -> Optional[timedelta]: ... def dst(self, dt: Optional[datetime]) -> Optional[timedelta]: ... def fromutc(self, dt: dat...
decorator for adding UTC tzinfo to datetime's utcfoo methods
170,466
from datetime import tzinfo, timedelta, datetime The provided code snippet includes necessary dependencies for implementing the `isoformat` function. Write a Python function `def isoformat(dt)` to solve the following problem: Return iso-formatted timestamp Like .isoformat(), but uses Z for UTC instead of +00:00 Here ...
Return iso-formatted timestamp Like .isoformat(), but uses Z for UTC instead of +00:00
170,467
import json import struct import sys from urllib.parse import urlparse import tornado from tornado import gen, ioloop, web from tornado.iostream import StreamClosedError from tornado.websocket import WebSocketHandler, WebSocketClosedError from jupyter_client.session import Session from ipython_genutils.py3compat import...
serialize a message as a binary blob Header: 4 bytes: number of msg parts (nbufs) as 32b int 4 * nbufs bytes: offset for each buffer as integer as 32b int Offsets are from the start of the buffer, including the header. Returns ------- The message serialized to bytes.
170,468
import json import struct import sys from urllib.parse import urlparse import tornado from tornado import gen, ioloop, web from tornado.iostream import StreamClosedError from tornado.websocket import WebSocketHandler, WebSocketClosedError from jupyter_client.session import Session from ipython_genutils.py3compat import...
deserialize a message from a binary blog Header: 4 bytes: number of msg parts (nbufs) as 32b int 4 * nbufs bytes: offset for each buffer as integer as 32b int Offsets are from the start of the buffer, including the header. Returns ------- message dictionary
170,469
import datetime import functools import ipaddress import json import mimetypes import os import re import sys import traceback import types import warnings from http.client import responses from http.cookies import Morsel from urllib.parse import urlparse from jinja2 import TemplateNotFound from tornado import web, gen...
null
170,470
import datetime import functools import ipaddress import json import mimetypes import os import re import sys import traceback import types import warnings from http.client import responses from http.cookies import Morsel from urllib.parse import urlparse from jinja2 import TemplateNotFound from tornado import web, gen...
Decorate methods with this to return GitHub style JSON errors. This should be used on any JSON API on any handler method that can raise HTTPErrors. This will grab the latest HTTPError exception using sys.exc_info and then: 1. Set the HTTP status code based on the HTTPError 2. Create and return a JSON body with a messag...
170,471
from datetime import datetime import errno import os import shutil import stat import sys import warnings import mimetypes import nbformat from send2trash import send2trash from send2trash.exceptions import TrashPermissionError from tornado import web from .filecheckpoints import FileCheckpoints from .fileio import Fil...
convert notebooks to Python script after save with nbconvert replaces `jupyter notebook --script`
170,472
from contextlib import contextmanager import errno import os import shutil from tornado.web import HTTPError from notebook.utils import ( to_api_path, to_os_path, ) import nbformat from ipython_genutils.py3compat import str_to_unicode from traitlets.config import Configurable from traitlets import Bool from bas...
Name of invalid file after a failed atomic write and subsequent read.
170,473
from contextlib import contextmanager import errno import os import shutil from tornado.web import HTTPError from notebook.utils import ( to_api_path, to_os_path, ) import nbformat from ipython_genutils.py3compat import str_to_unicode from traitlets.config import Configurable from traitlets import Bool from bas...
Context manager to write to a file only if the entire write is successful. This works by copying the previous file contents to a temporary file in the same directory, and renaming that file back to the target if the context exits with an error. If the context is successful, the new data is synced to disk and the tempor...
170,474
from contextlib import contextmanager import errno import os import shutil from tornado.web import HTTPError from notebook.utils import ( to_api_path, to_os_path, ) import nbformat from ipython_genutils.py3compat import str_to_unicode from traitlets.config import Configurable from traitlets import Bool from bas...
Context manager to write file without doing atomic writing ( for weird filesystem eg: nfs). Parameters ---------- path : str The target file to write to. text : bool, optional Whether to open the file in text mode (i.e. to write unicode). Default is True. encoding : str, optional The encoding to use for files opened in...
170,475
import json from tornado import gen, web from notebook.utils import maybe_future, url_path_join, url_escape from notebook.base.handlers import ( IPythonHandler, APIHandler, path_regex, ) The provided code snippet includes necessary dependencies for implementing the `validate_model` function. Write a Python functio...
Validate a model returned by a ContentsManager method. If expect_content is True, then we expect non-null entries for 'content' and 'format'.
170,476
import glob import json import os pjoin = os.path.join from tornado import web, gen from ...base.handlers import APIHandler from ...utils import maybe_future, url_path_join, url_unescape def url_path_join(*pieces): """Join components of url into a relative url Use to prevent double slash when joining subpath....
Load a KernelSpec by name and return the REST API model
170,477
import glob import json import os from tornado import web, gen from ...base.handlers import APIHandler from ...utils import maybe_future, url_path_join, url_unescape The provided code snippet includes necessary dependencies for implementing the `is_kernelspec_model` function. Write a Python function `def is_kernelspec...
Returns True if spec_dict is already in proper form. This will occur when using a gateway.
170,478
import json from tornado.log import access_log from .prometheus.log_functions import prometheus_log_method access_log = logging.getLogger("tornado.access") def prometheus_log_method(handler): """ Tornado log handler for recording RED metrics. We record the following metrics: Rate - the number of r...
log a bit more information about each request than tornado's default - move static file get success to debug-level (reduces noise) - get proxied IP instead of proxy IP - log referer for redirect and failed requests - log user-agent for failed requests
170,479
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_P...
Check whether nbextension files have been installed Returns True if all files are found, False if any are missing. Parameters ---------- files : list(paths) a list of relative paths within nbextensions. user : bool [default: False] Whether to check the user's .jupyter/nbextensions directory. Otherwise check a system-wi...
170,480
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_P...
Install an nbextension bundled in a Python package. Returns a list of installed/updated directories. See install_nbextension for parameter information.
170,481
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_P...
Remove nbextension files from the first location they are found. Returns True if files were removed, False otherwise.
170,482
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_P...
Uninstall an nbextension bundled in a Python package. See parameters of `install_nbextension_python`
170,483
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_P...
Enable a named nbextension Returns True if the final state is the one requested. Parameters ---------- section : string The section of the server to change, one of NBCONFIG_SECTIONS require : string An importable AMD module inside the nbextensions static path user : bool [default: True] Whether to enable in the user's ...
170,484
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_P...
Disable a named nbextension Returns True if the final state is the one requested. Parameters ---------- section : string The section of the server to change, one of NBCONFIG_SECTIONS require : string An importable AMD module inside the nbextensions static path user : bool [default: True] Whether to enable in the user's...
170,485
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_P...
Disable an nbextension from the first config location where it is enabled. Returns True if it changed any config, False otherwise.
170,486
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_P...
Enable some nbextensions associated with a Python module. Returns a list of whether the state was achieved (i.e. changed, or was already right) Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function user : bool [default: True] Whether to enable in the ...
170,487
import os import shutil import sys import tarfile import zipfile from os.path import basename, join as pjoin, normpath from urllib.parse import urlparse from urllib.request import urlretrieve from jupyter_core.paths import ( jupyter_data_dir, jupyter_config_path, jupyter_path, SYSTEM_JUPYTER_PATH, ENV_JUPYTER_P...
Disable some nbextensions associated with a Python module. Returns True if the final state is the one requested. Parameters ---------- module : str Importable Python module exposing the magic-named `_jupyter_nbextension_paths` function user : bool [default: True] Whether to enable in the user's nbextensions directory. ...
170,488
import sys if PY3: from functools import wraps else: from functools import wraps as _wraps def wraps(f): def dec(func): _wraps(f)(func) func.__wrapped__ = f return func return dec def signature(obj: Callable[..., Any], *, follow_wrapped: bool = ...) -> Si...
Decorator to process a callback prototype. A callback prototype is a function whose signature includes all the values that will be passed by the callback API in question. The original function will be returned, with a ``prototype.adapt`` attribute which can be used to prepare third party callbacks.
170,489
from __future__ import absolute_import, division, print_function import itertools import functools import re import types from collections import OrderedDict def formatannotation(annotation, base_module=None): if isinstance(annotation, type): if annotation.__module__ in ('builtins', '__builtin__', base_mod...
null
170,490
from contextvars import ContextVar from typing import Optional import sys import threading current_async_library_cvar = ContextVar( "current_async_library_cvar", default=None ) thread_local = _ThreadLocal() class AsyncLibraryNotFoundError(RuntimeError): pass The provided code snippet includes necessary depend...
Detect which async library is currently running. The following libraries are currently supported: ================ =========== ============================ Library Requires Magic string ================ =========== ============================ **Trio** Trio v0.6+ ``"trio"`` **Curio** - ``"curio"`` **asyncio** ``"asynci...
170,491
import os import pprint from twython import Twython def credsfromfile(creds_file=None, subdir=None, verbose=False): """ Convenience function for authentication """ return Authenticate().load_creds( creds_file=creds_file, subdir=subdir, verbose=verbose ) The provided code snippet includes ne...
For OAuth 2, retrieve an access token for an app and append it to a credentials file.
170,492
import os import pprint from twython import Twython The provided code snippet includes necessary dependencies for implementing the `guess_path` function. Write a Python function `def guess_path(pth)` to solve the following problem: If the path is not absolute, guess that it is a subdirectory of the user's home directo...
If the path is not absolute, guess that it is a subdirectory of the user's home directory. :param str pth: The pathname of the directory where files of tweets should be written
170,493
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) SPACER = "###################################" def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated:...
Decorator for demo functions
170,494
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `setup` function. Write a Python functio...
Initialize global variables for the demos.
170,495
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) SPACER = "###################################" The provided code snippet includes necessary dependencies for implementi...
Use the simplified :class:`Twitter` class to write some tweets to a file.
170,496
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `sampletoscreen_demo` function. Write a ...
Sample from the Streaming API and send output to terminal.
170,497
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `tracktoscreen_demo` function. Write a P...
Track keywords from the public Streaming API and send output to terminal.
170,498
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `search_demo` function. Write a Python f...
Use the REST API to search for past tweets containing a given keyword.
170,499
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `tweets_by_user_demo` function. Write a ...
Use the REST API to search for past tweets by a given user.
170,500
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `lookup_by_userid_demo` function. Write ...
Use the REST API to convert a userID to a screen name.
170,501
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `followtoscreen_demo` function. Write a ...
Using the Streaming API, select just the tweets from a specified list of userIDs. This is will only give results in a reasonable time if the users in question produce a high volume of tweets, and may even so show some delay.
170,502
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) The provided code snippet includes necessary dependencies for implementing the `streamtofile_demo` function. Write a Py...
Write 20 tweets sampled from the public Streaming API to a file.
170,503
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) def yesterday(): """ Get yesterday's datetime as a 5-tuple. """ date = datetime.datetime.now() date ...
Query the REST API for Tweets about NLTK since yesterday and send the output to terminal. This example makes the assumption that there are sufficient Tweets since yesterday for the date to be an effective cut-off.
170,504
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) SPACER = "###################################" twitter_samples: TwitterCorpusReader = LazyCorpusLoader( "twitter_sa...
Use `TwitterCorpusReader` tp read a file of tweets, and print out * some full tweets in JSON format; * some raw strings from the tweets (i.e., the value of the `text` field); and * the result of tokenising the raw strings.
170,505
import datetime import json from functools import wraps from io import StringIO from nltk.twitter import ( Query, Streamer, TweetViewer, TweetWriter, Twitter, credsfromfile, ) class StringIO(TextIOWrapper): def __init__(self, initial_value: Optional[str] = ..., newline: Optional[str] = ...)...
Given a file object containing a list of Tweet IDs, fetch the corresponding full Tweets, if available.
170,506
import csv import gzip import json from nltk.internals import deprecated def extract_fields(tweet, fields): """ Extract field values from a full tweet and return them as a list :param json tweet: The tweet in JSON format :param list fields: The fields to be extracted from the tweet :rtype: list(str)...
Extract selected fields from a file of line-separated JSON tweets and write to a file in CSV format. This utility function allows a file of full tweets to be easily converted to a CSV file for easier processing. For example, just TweetIDs or just the text content of the Tweets can be extracted. Additionally, the functi...
170,507
import csv import gzip import json from nltk.internals import deprecated def _outf_writer(outfile, encoding, errors, gzip_compress=False): if gzip_compress: outf = gzip.open(outfile, "wt", newline="", encoding=encoding, errors=errors) else: outf = open(outfile, "w", newline="", encoding=encoding...
Get a CSV writer with optional compression.
170,508
import csv import gzip import json from nltk.internals import deprecated def extract_fields(tweet, fields): """ Extract field values from a full tweet and return them as a list :param json tweet: The tweet in JSON format :param list fields: The fields to be extracted from the tweet :rtype: list(str)...
Extract selected fields from a file of line-separated JSON tweets and write to a file in CSV format. This utility function allows a file of full Tweets to be easily converted to a CSV file for easier processing of Twitter entities. For example, the hashtags or media elements of a tweet can be extracted. It returns one ...
170,509
import random import warnings from abc import ABCMeta, abstractmethod from bisect import bisect from itertools import accumulate from nltk.lm.counter import NgramCounter from nltk.lm.util import log_base2 from nltk.lm.vocabulary import Vocabulary The provided code snippet includes necessary dependencies for implementi...
Return average (aka mean) for sequence of items.