id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
172,167 | from __future__ import annotations
import asyncio
import logging
import os
import re
import shlex
import shutil
import subprocess
import tempfile
from collections import deque
from enum import Enum
from functools import wraps
from typing import (
Any,
Awaitable,
Callable,
Coroutine,
Deque,
Itera... | Decorator that only starts the coroutine only if the previous call has finished. (Used to make sure that we have only one autocompleter, auto suggestor and validator running at a time.) When the coroutine raises `_Retry`, it is restarted. |
172,168 | from __future__ import annotations
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.key_binding.key_processor import KeyPressEvent
from .containers import Window
from .controls import FormattedTextControl
from .dimension import D
from .layout import L... | Create a dummy layout for use in an 'Application' that doesn't have a layout specified. When ENTER is pressed, the application quits. |
172,169 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from enum import Enum
from functools import partial
from typing import (
TYPE_CHECKING,
Callable,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from prompt_toolkit.application.current import get_app
fr... | Create a `Window` that displays the 'Window too small' text. |
172,170 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from enum import Enum
from functools import partial
from typing import (
TYPE_CHECKING,
Callable,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from prompt_toolkit.application.current import get_app
fr... | Make sure that the given argument is a :class:`.Window`. |
172,171 | from __future__ import annotations
from abc import ABCMeta, abstractmethod
from enum import Enum
from functools import partial
from typing import (
TYPE_CHECKING,
Callable,
Dict,
List,
Optional,
Sequence,
Tuple,
Union,
cast,
)
from prompt_toolkit.application.current import get_app
fr... | Checks whether the given value is a container object (for use in assert statements). |
172,172 | from __future__ import annotations
import math
from itertools import zip_longest
from typing import (
TYPE_CHECKING,
Callable,
Dict,
Iterable,
Optional,
Sequence,
Tuple,
TypeVar,
Union,
cast,
)
from weakref import WeakKeyDictionary
from prompt_toolkit.application.current import g... | Get the style/text tuples for a menu item, styled and trimmed to the given width. |
172,173 | from __future__ import annotations
import re
from abc import ABCMeta, abstractmethod
from typing import (
TYPE_CHECKING,
Callable,
Hashable,
List,
Optional,
Tuple,
Type,
Union,
cast,
)
from prompt_toolkit.application.current import get_app
from prompt_toolkit.cache import SimpleCache... | Merge multiple `Processor` objects into one. |
172,174 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
class Dimension:
"""
Specified dimension (width/height) of a user control or window.
The layout engine tries to honor the preferred size. If that is not
possible, because the terminal is larger or s... | Sum a list of :class:`.Dimension` instances. |
172,175 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
class Dimension:
"""
Specified dimension (width/height) of a user control or window.
The layout engine tries to honor the preferred size. If that is not
possible, because the terminal is larger or s... | Take the maximum of a list of :class:`.Dimension` instances. Used when we have a HSplit/VSplit, and we want to get the best width/height.) |
172,176 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
class Dimension:
"""
Specified dimension (width/height) of a user control or window.
The layout engine tries to honor the preferred size. If that is not
possible, because the terminal is larger or s... | Turn the given object into a `Dimension` object. |
172,177 | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
class Dimension:
"""
Specified dimension (width/height) of a user control or window.
The layout engine tries to honor the preferred size. If that is not
possible, because the terminal is larger or s... | Test whether the given value could be a valid dimension. (For usage in an assertion. It's not guaranteed in case of a callable.) |
172,178 | import base64
import json
import mimetypes
import os
from pathlib import Path
from typing import Any, Dict, Optional, Tuple
import jinja2
import markupsafe
from jupyter_core.paths import jupyter_path
from traitlets import Bool, Unicode, default
from traitlets.config import Config
from jinja2.loaders import split_templa... | Find a JupyterLab theme location by name. Parameters ---------- theme_name : str The name of the labextension theme you want to find. Raises ------ ValueError If the theme was not found, or if it was not specific enough. Returns ------- theme_name: str Full theme name (with scope, if any) labextension_path : Path The p... |
172,179 | import os
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
from traitlets import Bool, Instance, Integer, List, Unicode, default
from nbconvert.utils import _contextlib_chdir
from .latex import LatexExporter
The provided code snippet includes necessary dependencies for implementing th... | Add value to the environment variable varname in envdict e.g. prepend_to_env_search_path('BIBINPUTS', '/home/sally/foo', os.environ) |
172,180 | import html
import json
import os
import typing as t
import uuid
import warnings
from pathlib import Path
from jinja2 import (
BaseLoader,
ChoiceLoader,
DictLoader,
Environment,
FileSystemLoader,
TemplateNotFound,
)
from jupyter_core.paths import jupyter_path
from nbformat import NotebookNode
fr... | Recursively update one dictionary using another. None values will delete their keys. |
172,181 | import html
import json
import os
import typing as t
import uuid
import warnings
from pathlib import Path
from jinja2 import (
BaseLoader,
ChoiceLoader,
DictLoader,
Environment,
FileSystemLoader,
TemplateNotFound,
)
from jupyter_core.paths import jupyter_path
from nbformat import NotebookNode
fr... | Emit a deprecation warning. |
172,182 | import os
import sys
from nbformat import NotebookNode
from traitlets.config import get_config
from traitlets.log import get_logger
from traitlets.utils.importstring import import_item
from .exporter import Exporter
class Exporter(LoggingConfigurable):
"""
Class containing methods that sequentially run a list ... | Export a notebook object using specific exporter class. Parameters ---------- exporter : ``Exporter`` class or instance Class or instance of the exporter that should be used. If the method initializes its own instance of the class, it is ASSUMED that the class type provided exposes a constructor (``__init__``) with the... |
172,183 | import json
import os
import sys
from binascii import a2b_base64
from mimetypes import guess_extension
from textwrap import dedent
from traitlets import Set, Unicode
from .base import Preprocessor
def guess_extension(type: str, strict: bool = ...) -> Optional[str]: ...
The provided code snippet includes necessary dep... | This function fixes a problem with '.jpe' extensions of jpeg images which are then not recognised by latex. For any other case, the function works in the same way as mimetypes.guess_extension |
172,184 | import json
import os
import sys
from binascii import a2b_base64
from mimetypes import guess_extension
from textwrap import dedent
from traitlets import Set, Unicode
from .base import Preprocessor
The provided code snippet includes necessary dependencies for implementing the `platform_utf_8_encode` function. Write a P... | Encode data based on platform. |
172,185 | import functools
import re
from traitlets.log import get_logger
def get_logger():
"""Grab the global logger instance.
If a global Application is instantiated, grab its logger.
Otherwise, grab the root logger.
"""
global _logger
if _logger is None:
from .config import Application
... | Wrap a function to be executed on all cells of a notebook The wrapped function should have these parameters: cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows preprocessors to pass variables into the Jinja engine. index : int Index ... |
172,186 | import functools
import re
from traitlets.log import get_logger
cr_pat = re.compile(r".*\r(?=[^\n])")
The provided code snippet includes necessary dependencies for implementing the `coalesce_streams` function. Write a Python function `def coalesce_streams(cell, resources, index)` to solve the following problem:
Merge ... | Merge consecutive sequences of stream output into single stream to prevent extra newlines inserted at flush calls Parameters ---------- cell : NotebookNode cell Notebook cell being processed resources : dictionary Additional resources used in the conversion process. Allows transformers to pass variables into the Jinja ... |
172,187 | import typing as t
from jupyter_client.manager import KernelManager
from nbclient import NotebookClient
from nbclient import execute as _execute
from nbclient.exceptions import CellExecutionError
from nbformat import NotebookNode
from .base import Preprocessor
The provided code snippet includes necessary dependencies... | DEPRECATED. |
172,188 | import re
from .pandoc import convert_pandoc
The provided code snippet includes necessary dependencies for implementing the `markdown2html_mistune` function. Write a Python function `def markdown2html_mistune(source)` to solve the following problem:
mistune is unavailable, raise ImportError
Here is the function:
def... | mistune is unavailable, raise ImportError |
172,189 | import re
from .pandoc import convert_pandoc
def convert_pandoc(source, from_format, to_format, extra_args=None):
"""Convert between any two formats using pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
... | Convert a markdown string to LaTeX via pandoc. This function will raise an error if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. Parameters ---------- source : string Input string, assumed to be valid markdown. markup : string Markup used by pandoc's reader default : pandoc ext... |
172,190 | import re
from .pandoc import convert_pandoc
def convert_pandoc(source, from_format, to_format, extra_args=None):
"""Convert between any two formats using pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
... | Convert a markdown string to HTML via pandoc. |
172,191 | import re
from .pandoc import convert_pandoc
def convert_pandoc(source, from_format, to_format, extra_args=None):
"""Convert between any two formats using pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
... | Convert a markdown string to asciidoc via pandoc |
172,192 | import re
from .pandoc import convert_pandoc
def convert_pandoc(source, from_format, to_format, extra_args=None):
"""Convert between any two formats using pandoc.
This function will raise an error if pandoc is not installed.
Any error messages generated by pandoc are printed to stderr.
Parameters
... | Convert a markdown string to ReST via pandoc. This function will raise an error if pandoc is not installed. Any error messages generated by pandoc are printed to stderr. Parameters ---------- source : string Input string, assumed to be valid markdown. Returns ------- out : string Output as returned by pandoc. |
172,193 | import re
import markupsafe
_ANSI_RE = re.compile("\x1b\\[(.*?)([@-~])")
The provided code snippet includes necessary dependencies for implementing the `strip_ansi` function. Write a Python function `def strip_ansi(source)` to solve the following problem:
Remove ANSI escape codes from text. Parameters ---------- sourc... | Remove ANSI escape codes from text. Parameters ---------- source : str Source to remove the ANSI from |
172,194 | import re
import markupsafe
def _htmlconverter(fg, bg, bold, underline, inverse):
"""
Return start and end tags for given foreground/background/bold/underline.
"""
if (fg, bg, bold, underline, inverse) == (None, None, False, False, False):
return "", ""
classes = []
styles = []
if in... | Convert ANSI colors to HTML colors. Parameters ---------- text : unicode Text containing ANSI colors to convert to HTML |
172,195 | import re
import markupsafe
def _latexconverter(fg, bg, bold, underline, inverse):
"""
Return start and end markup given foreground/background/bold/underline.
"""
if (fg, bg, bold, underline, inverse) == (None, None, False, False, False):
return "", ""
starttag, endtag = "", ""
if invers... | Convert ANSI colors to LaTeX colors. Parameters ---------- text : unicode Text containing ANSI colors to convert to LaTeX |
172,196 | import re
from pandocfilters import RawInline, applyJSONFilters, stringify
def resolve_one_reference(key, val, fmt, meta):
"""
This takes a tuple of arguments that are compatible with ``pandocfilters.walk()`` that
allows identifying hyperlinks in the document and transforms them into valid LaTeX
\\hype... | This applies the resolve_one_reference to the text passed in via the source argument. This expects content in the form of a string encoded JSON object as represented internally in ``pandoc``. |
172,197 | from html.parser import HTMLParser
class CitationParser(HTMLParser):
"""Citation Parser
Replaces html tags with data-cite attribute with respective latex \\cite.
Inherites from HTMLParser, overrides:
- handle_starttag
- handle_endtag
"""
# number of open tags
opentags = None
# list... | Parse citations in Markdown cells. This looks for HTML tags having a data attribute names ``data-cite`` and replaces it by the call to LaTeX cite command. The transformation looks like this:: <cite data-cite="granger">(Granger, 2013)</cite> Becomes :: \\cite{granger} Any HTML tag can be used, which allows the citations... |
172,198 | from html import escape
from warnings import warn
from traitlets import observe
from traitlets.config import Dict
from nbconvert.utils.base import NbConvertBase
def highlight(code, lexer, formatter, outfile=None):
"""
Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.
If ``outfile... | Return a syntax-highlighted version of the input source Parameters ---------- source : str source of the cell to highlight output_formatter : Pygments formatter language : str language to highlight the syntax of metadata : NotebookNode cell metadata metadata of the cell to highlight |
172,199 | import base64
import mimetypes
import os
import re
from functools import partial
from html import escape
import bs4
from mistune import PLUGINS, BlockParser, HTMLRenderer, InlineParser, Markdown
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name
f... | Make the '.' special character match any character inside the pattern, including a newline. This is implemented with the inline flag `(?s:...)` and is equivalent to using `re.DOTALL` when it is the only pattern used. It is necessary since `mistune>=2.0.0`, where the pattern is passed to the undocumented `re.Scanner`. |
172,200 | import base64
import mimetypes
import os
import re
from functools import partial
from html import escape
import bs4
from mistune import PLUGINS, BlockParser, HTMLRenderer, InlineParser, Markdown
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name
f... | Convert a markdown string to HTML using mistune |
172,201 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Intelligently wrap text. Wrap text without breaking words if possible. Parameters ---------- text : str Text to wrap. width : int, optional Number of characters to wrap to, default 100. |
172,202 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Clean an html element. |
172,203 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Add an id and an anchor-link to an html header For use on markdown headings |
172,204 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Add prompts to code snippets |
172,205 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Remove all dollar symbols from text Parameters ---------- text : str Text to remove dollars from |
172,206 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Fix all fake URLs that start with ``files/``, stripping out the ``files/`` prefix. Applies to both urls (for html) and relative paths (for markdown paths). Parameters ---------- text : str Text in which to replace 'src="files/real...' with 'src="real...' |
172,207 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Build a Python comment line from input text. Parameters ---------- text : str Text to comment out. prefix : str Character to append to the start of each line. |
172,208 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Split the input text into separate lines and then return the lines that the caller is interested in. Parameters ---------- text : str Text to parse lines from. start : int, optional First line to grab from. end : int, optional Last line to grab from. |
172,209 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Transform IPython syntax to pure Python syntax Parameters ---------- code : str IPython code, to be transformed to pure Python |
172,210 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Turn a path into posix-style path/to/etc Mainly for use in latex on Windows, where native Windows paths are not allowed. |
172,211 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Turn a file path into a URL |
172,212 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | ensure a string is ascii |
172,213 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Prevent presence of enumerate or itemize blocks in latex headings cells |
172,214 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Strips a newline from the end of text. |
172,215 | import base64
import os
import re
import textwrap
import warnings
from urllib.parse import quote
from xml.etree.ElementTree import Element
import bleach
from defusedxml import ElementTree
from nbconvert.preprocessors.sanitize import _get_default_css_sanitizer
from nbconvert.filters.svg_constants import ALLOWED_SVG_ATT... | Encode base64 text |
172,216 | import re
LATEX_RE_SUBS = ((re.compile(r"\.\.\.+"), r"{\\ldots}"),)
LATEX_SUBS = {
"&": r"\&",
"%": r"\%",
"$": r"\$",
"#": r"\#",
"_": r"\_",
"{": r"\{",
"}": r"\}",
"~": r"\textasciitilde{}",
"^": r"\^{}",
"\\": r"\textbackslash{}",
}
The provided code snippet includes necessa... | Escape characters that may conflict with latex. Parameters ---------- text : str Text containing characters that may conflict with Latex |
172,217 |
The provided code snippet includes necessary dependencies for implementing the `get_metadata` function. Write a Python function `def get_metadata(output, key, mimetype=None)` to solve the following problem:
Resolve an output metadata key If mimetype given, resolve at mimetype level first, then fallback to top-level. ... | Resolve an output metadata key If mimetype given, resolve at mimetype level first, then fallback to top-level. Otherwise, just resolve at top-level. Returns None if no data found. |
172,218 | import os
import re
import os
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object, counter, instance=None,
inum=-1, format=None, machine=None):
# NOTE: Many counters require 2 samples to give acc... | Indent a string a given number of spaces or tabstops. indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. Parameters ---------- instr : basestring The string to be indented. nspaces : int (default: 4) The number of spaces to be indented. ntabs : int (default: 0) The number of tabs to be indented. flatten : bo... |
172,219 | import codecs
import errno
import os
import random
import shutil
import sys
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of... | Get a wrapper to write unicode to stdout/stderr as UTF-8. This ignores environment variables and default encodings, to reliably write unicode to stdout or stderr. :: unicode_std_stream().write(u'ł@e¶ŧ←') |
172,220 | import codecs
import errno
import os
import random
import shutil
import sys
import sys
if sys.platform[:5] == 'linux':
def jiffies(_proc_pid_stat=f'/proc/{os.getpid()}/stat', _load_time=[]):
"""
Return number of jiffies elapsed.
Return number of jiffies (1/100ths of... | Get a wrapper to read unicode from stdin as UTF-8. This ignores environment variables and default encodings, to reliably read unicode from stdin. :: totreat = unicode_stdin_stream().read() |
172,221 | import codecs
import errno
import os
import random
import shutil
import sys
def link(src, dst):
"""Hard links ``src`` to ``dst``, returning 0 or errno.
Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
supported by the operating system.
"""
if not hasattr(os, "link"):
... | Attempts to hardlink ``src`` to ``dst``, copying if the link fails. Attempts to maintain the semantics of ``shutil.copy``. Because ``os.link`` does not overwrite files, a unique temporary file will be used if the target already exists, then that file will be moved into place. |
172,222 | import codecs
import errno
import os
import random
import shutil
import sys
import os
if os.name == 'nt':
# Code "stolen" from enthought/debug/memusage.py
def GetPerformanceAttributes(object, counter, instance=None,
inum=-1, format=None, machine=None):
... | ensure that a directory exists If it doesn't exist, try to create it and protect against a race condition if another process is doing the same. The default permissions are 755, which differ from os.makedirs default of 777. |
172,223 | import re
import shutil
import subprocess
import warnings
from io import BytesIO, TextIOWrapper
from nbconvert.utils.version import check_version
from .exceptions import ConversionException
__version = None
The provided code snippet includes necessary dependencies for implementing the `clean_cache` function. Write a P... | Clean the internal cache. |
172,224 | import numpy as np
import math
from mpl_toolkits.axisartist.grid_finder import ExtremeFinderSimple
def select_step(v1, v2, nv, hour=False, include_last=True,
threshold_factor=3600.):
if v1 > v2:
v1, v2 = v2, v1
dv = (v2 - v1) / nv
if hour:
_select_step = select_step_hour
... | null |
172,225 | import numpy as np
import math
from mpl_toolkits.axisartist.grid_finder import ExtremeFinderSimple
def select_step(v1, v2, nv, hour=False, include_last=True,
threshold_factor=3600.):
def select_step360(v1, v2, nv, include_last=True, threshold_factor=3600):
return select_step(v1, v2, nv, hour=False,... | null |
172,226 | import numpy as np
from matplotlib import ticker as mticker
from matplotlib.transforms import Bbox, Transform
The provided code snippet includes necessary dependencies for implementing the `_find_line_box_crossings` function. Write a Python function `def _find_line_box_crossings(xys, bbox)` to solve the following prob... | Find the points where a polyline crosses a bbox, and the crossing angles. Parameters ---------- xys : (N, 2) array The polyline coordinates. bbox : `.Bbox` The bounding box. Returns ------- list of ((float, float), float) Four separate lists of crossings, for the left, right, bottom, and top sides of the bbox, respecti... |
172,227 | import functools
from itertools import chain
import numpy as np
import matplotlib as mpl
from matplotlib.path import Path
from matplotlib.transforms import Affine2D, IdentityTransform
from .axislines import AxisArtistHelper, GridHelperBase
from .axis_artist import AxisArtist
from .grid_finder import GridFinder
The pro... | Compute *func* and its derivatives along x and y at positions *xs*, *ys*, while ensuring that finite difference calculations don't try to evaluate values outside of *xlims*, *ylims*. |
172,228 | from numbers import Number
from matplotlib import _api
from matplotlib.axes import Axes
def _get_axes_aspect(ax):
aspect = ax.get_aspect()
if aspect == "auto":
aspect = 1.
return aspect | null |
172,229 | from numbers import Number
from matplotlib import _api
from matplotlib.axes import Axes
class Fixed(_Base):
"""
Simple fixed size with absolute part = *fixed_size* and relative part = 0.
"""
def __init__(self, fixed_size):
_api.check_isinstance(Number, fixed_size=fixed_size)
self.fixed_s... | Create a Fixed unit when the first argument is a float, or a Fraction unit if that is a string that ends with %. The second argument is only meaningful when Fraction unit is created. >>> a = Size.from_any(1.2) # => Size.Fixed(1.2) >>> Size.from_any("50%", a) # => Size.Fraction(0.5, a) |
172,230 | import numpy as np
import matplotlib as mpl
from matplotlib import _api
from matplotlib.gridspec import SubplotSpec
import matplotlib.transforms as mtransforms
from . import axes_size as Size
def _locate(x, y, w, h, summed_widths, equal_heights, fig_w, fig_h, anchor):
total_width = fig_w * w
max_height = fig_... | null |
172,231 | import numpy as np
import matplotlib as mpl
from matplotlib import _api
from matplotlib.gridspec import SubplotSpec
import matplotlib.transforms as mtransforms
from . import axes_size as Size
def make_axes_locatable(axes):
divider = AxesDivider(axes)
locator = divider.new_locator(nx=0, ny=0)
axes.set_axes_l... | Add auto-adjustable padding around *ax* to take its decorations (title, labels, ticks, ticklabels) into account during layout, using `.Divider.add_auto_adjustable_area`. By default, padding is determined from the decorations of *ax*. Pass *use_axes* to consider the decorations of other Axes instead. |
172,232 | from matplotlib import _api, cbook
import matplotlib.artist as martist
import matplotlib.transforms as mtransforms
from matplotlib.transforms import Bbox
from .mpl_axes import Axes
host_axes_class_factory = host_subplot_class_factory = \
cbook._make_class_factory(HostAxesBase, "{}HostAxes", "_base_axes_class")
cla... | Create axes that can act as a hosts to parasitic axes. Parameters ---------- figure : `~matplotlib.figure.Figure` Figure to which the axes will be added. Defaults to the current figure `.pyplot.gcf()`. *args, **kwargs Will be passed on to the underlying `~.axes.Axes` object creation. |
172,233 | from matplotlib import _api, _docstring
from matplotlib.offsetbox import AnchoredOffsetbox
from matplotlib.patches import Patch, Rectangle
from matplotlib.path import Path
from matplotlib.transforms import Bbox, BboxTransformTo
from matplotlib.transforms import IdentityTransform, TransformedBbox
from . import axes_size... | Create an anchored inset axes by scaling a parent axes. For usage, also see :doc:`the examples </gallery/axes_grid1/inset_locator_demo2>`. Parameters ---------- parent_axes : `~matplotlib.axes.Axes` Axes to place the inset axes. zoom : float Scaling factor of the data axes. *zoom* > 1 will enlarge the coordinates (i.e.... |
172,234 | from matplotlib import _api, _docstring
from matplotlib.offsetbox import AnchoredOffsetbox
from matplotlib.patches import Patch, Rectangle
from matplotlib.path import Path
from matplotlib.transforms import Bbox, BboxTransformTo
from matplotlib.transforms import IdentityTransform, TransformedBbox
from . import axes_size... | Draw a box to mark the location of an area represented by an inset axes. This function draws a box in *parent_axes* at the bounding box of *inset_axes*, and shows a connection with the inset axes by drawing lines at the corners, giving a "zoomed in" effect. Parameters ---------- parent_axes : `~matplotlib.axes.Axes` Ax... |
172,235 | import numpy as np
from .axes_divider import make_axes_locatable, Size
from .mpl_axes import Axes
def make_axes_locatable(axes):
divider = AxesDivider(axes)
locator = divider.new_locator(nx=0, ny=0)
axes.set_axes_locator(locator)
return divider
The provided code snippet includes necessary dependencie... | Parameters ---------- ax : `~matplotlib.axes.Axes` Axes instance to create the RGB Axes in. pad : float, optional Fraction of the Axes height to pad. axes_class : `matplotlib.axes.Axes` or None, optional Axes class to use for the R, G, and B Axes. If None, use the same class as *ax*. **kwargs : Forwarded to *axes_class... |
172,236 | from numbers import Number
import functools
import numpy as np
from matplotlib import _api, cbook
from matplotlib.gridspec import SubplotSpec
from .axes_divider import Size, SubplotDivider, Divider
from .mpl_axes import Axes
def _tick_only(ax, bottom_on, left_on):
bottom_off = not bottom_on
left_off = not left... | null |
172,237 | from collections import defaultdict
import functools
import itertools
import math
import textwrap
import numpy as np
import matplotlib as mpl
from matplotlib import _api, cbook, _docstring, _preprocess_data
import matplotlib.artist as martist
import matplotlib.axes as maxes
import matplotlib.collections as mcoll
import... | Return a tuple X, Y, Z with a test data set. |
172,238 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Return the given angle normalized to -180 < *a* <= 180 degrees. |
172,239 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Return the given angle normalized to -90 < *a* <= 90 degrees. |
172,240 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Return a direction vector. Parameters ---------- zdir : {'x', 'y', 'z', None, 3-tuple} The direction. Possible values are: - 'x': equivalent to (1, 0, 0) - 'y': equivalent to (0, 1, 0) - 'z': equivalent to (0, 0, 1) - *None*: equivalent to (0, 0, 0) - an iterable (x, y, z) is converted to a NumPy array, if not already ... |
172,241 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Convert a `.Text` to a `.Text3D` object. Parameters ---------- z : float The z-position in 3D space. zdir : {'x', 'y', 'z', 3-tuple} The direction of the text. Default: 'z'. See `.get_dir_vector` for a description of the values. |
172,242 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Convert a `.Line2D` to a `.Line3D` object. Parameters ---------- zs : float The location along the *zdir* axis in 3D space to position the line. zdir : {'x', 'y', 'z'} Plane to plot line orthogonal to. Default: 'z'. See `.get_dir_vector` for a description of the values. |
172,243 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Convert a `.LineCollection` to a `.Line3DCollection` object. |
172,244 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Convert a `.Patch` to a `.Patch3D` object. |
172,245 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Convert a `.PathPatch` to a `.PathPatch3D` object. |
172,246 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Convert a `.PatchCollection` into a `.Patch3DCollection` object (or a `.PathCollection` into a `.Path3DCollection` object). Parameters ---------- zs : float or array of floats The location or locations to place the patches in the collection along the *zdir* axis. Default: 0. zdir : {'x', 'y', 'z'} The axis in which to ... |
172,247 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Convert a `.PolyCollection` into a `.Poly3DCollection` object. Parameters ---------- zs : float or array of floats The location or locations to place the polygons in the collection along the *zdir* axis. Default: 0. zdir : {'x', 'y', 'z'} The axis in which to place the patches. Default: 'z'. See `.get_dir_vector` for a... |
172,248 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Modify the alphas of the color list according to depth. |
172,249 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Compute the normals of a list of polygons, one normal per polygon. Normals point towards the viewer for a face with its vertices in counterclockwise order, following the right hand rule. Uses three points equally spaced around the polygon. This method assumes that the points are in a plane. Otherwise, more than one sha... |
172,250 | import math
import numpy as np
from contextlib import contextmanager
from matplotlib import (
artist, cbook, colors as mcolors, lines, text as mtext,
path as mpath)
from matplotlib.collections import (
LineCollection, PolyCollection, PatchCollection, PathCollection)
from matplotlib.colors import Normalize
f... | Shade *color* using normal vectors given by *normals*, assuming a *lightsource* (using default position if not given). *color* can also be an array of the same length as *normals*. |
172,251 | import numpy as np
import numpy.linalg as linalg
The provided code snippet includes necessary dependencies for implementing the `_line2d_seg_dist` function. Write a Python function `def _line2d_seg_dist(p, s0, s1)` to solve the following problem:
Return the distance(s) from point(s) *p* to segment(s) (*s0*, *s1*). Par... | Return the distance(s) from point(s) *p* to segment(s) (*s0*, *s1*). Parameters ---------- p : (ndim,) or (N, ndim) array-like The points from which the distances are computed. s0, s1 : (ndim,) or (N, ndim) array-like The xy(z...) coordinates of the segment endpoints. |
172,252 | import numpy as np
import numpy.linalg as linalg
The provided code snippet includes necessary dependencies for implementing the `world_transformation` function. Write a Python function `def world_transformation(xmin, xmax, ymin, ymax, zmin, zmax, pb_aspect=None)` to so... | Produce a matrix that scales homogeneous coords in the specified ranges to [0, 1], or [0, pb_aspect[i]] if the plotbox aspect ratio is specified. |
172,253 | import numpy as np
import numpy.linalg as linalg
def _view_axes(E, R, V, roll):
"""
Get the unit viewing axes in data coordinates.
Parameters
----------
E : 3-element numpy array
The coordinates of the eye/camera.
R : 3-element numpy array
The coordinates of the center of the vie... | Return the view transformation matrix. Parameters ---------- E : 3-element numpy array The coordinates of the eye/camera. R : 3-element numpy array The coordinates of the center of the view box. V : 3-element numpy array Unit vector in the direction of the vertical axis. roll : float The roll angle in radians. |
172,254 | import numpy as np
import numpy.linalg as linalg
def persp_transformation(zfront, zback, focal_length):
e = focal_length
a = 1 # aspect ratio
b = (zfront+zback)/(zfront-zback)
c = -2*(zfront*zback)/(zfront-zback)
proj_matrix = np.array([[e, 0, 0, 0],
[0, e/a, 0, 0],... | null |
172,255 | import numpy as np
import numpy.linalg as linalg
def ortho_transformation(zfront, zback):
# note: w component in the resulting vector will be (zback-zfront), not 1
a = -(zfront + zback)
b = -(zfront - zback)
proj_matrix = np.array([[2, 0, 0, 0],
[0, 2, 0, 0],
... | null |
172,256 | import numpy as np
import numpy.linalg as linalg
def _vec_pad_ones(xs, ys, zs):
return np.array([xs, ys, zs, np.ones_like(xs)])
The provided code snippet includes necessary dependencies for implementing the `inv_transform` function. Write a Python function `def inv_transform(xs, ys, zs, M)` to solve the following ... | Transform the points by the inverse of the projection matrix *M*. |
172,257 | import numpy as np
import numpy.linalg as linalg
def _proj_transform_vec_clip(vec, M):
vecw = np.dot(M, vec)
w = vecw[3]
# clip here.
txs, tys, tzs = vecw[0] / w, vecw[1] / w, vecw[2] / w
tis = (0 <= vecw[0]) & (vecw[0] <= 1) & (0 <= vecw[1]) & (vecw[1] <= 1)
if np.any(tis):
tis = vecw[1... | Transform the points by the projection matrix and return the clipping result returns txs, tys, tzs, tis |
172,258 | import numpy as np
import numpy.linalg as linalg
def proj_trans_points(points, M):
xs, ys, zs = zip(*points)
return proj_transform(xs, ys, zs, M)
def proj_points(points, M):
return np.column_stack(proj_trans_points(points, M)) | null |
172,259 | import numpy as np
import numpy.linalg as linalg
def rot_x(V, alpha):
cosa, sina = np.cos(alpha), np.sin(alpha)
M1 = np.array([[1, 0, 0, 0],
[0, cosa, -sina, 0],
[0, sina, cosa, 0],
[0, 0, 0, 1]])
return np.dot(M1, V) | null |
172,260 | import inspect
import numpy as np
import matplotlib as mpl
from matplotlib import (
_api, artist, lines as mlines, axis as maxis, patches as mpatches,
transforms as mtransforms, colors as mcolors)
from . import art3d, proj3d
def _move_from_center(coord, centers, deltas, axmask=(True, True, True)):
"""
F... | For each coordinate where *axmask* is True, move *coord* away from *centers* by *deltas*. |
172,261 | import inspect
import numpy as np
import matplotlib as mpl
from matplotlib import (
_api, artist, lines as mlines, axis as maxis, patches as mpatches,
transforms as mtransforms, colors as mcolors)
from . import art3d, proj3d
def _tick_update_position(tick, tickxs, tickys, labelpos):
"""Update tick line and ... | Update tick line and label position and style. |
172,262 | import os
import re
import time
from os.path import basename
from multiprocessing import util
import distutils
The provided code snippet includes necessary dependencies for implementing the `concurrency_safe_rename` function. Write a Python function `def concurrency_safe_rename(src, dst)` to solve the following proble... | Renames ``src`` into ``dst`` overwriting ``dst`` if it exists. On Windows os.replace can yield permission errors if executed by two different processes. |
172,263 | import pickle
import os
import warnings
import io
from pathlib import Path
from .compressor import lz4, LZ4_NOT_INSTALLED_ERROR
from .compressor import _COMPRESSORS, register_compressor, BinaryZlibFile
from .compressor import (ZlibCompressorWrapper, GzipCompressorWrapper,
BZ2CompressorWrapper, ... | Persist an arbitrary Python object into one file. Read more in the :ref:`User Guide <persistence>`. Parameters ----------- value: any Python object The object to store to disk. filename: str, pathlib.Path, or file object. The file object or path of the file in which it is to be stored. The compression method correspond... |
172,264 | import pickle
import os
import warnings
import io
from pathlib import Path
from .compressor import lz4, LZ4_NOT_INSTALLED_ERROR
from .compressor import _COMPRESSORS, register_compressor, BinaryZlibFile
from .compressor import (ZlibCompressorWrapper, GzipCompressorWrapper,
BZ2CompressorWrapper, ... | null |
172,265 | import ast
import operator as op
def eval_(node):
if isinstance(node, ast.Num): # <number>
return node.n
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
return operators[type(node.op)](eval_(node.left), eval_(node.right))
elif isinstance(node, ast.UnaryOp): # <operator> <ope... | >>> eval_expr('2*6') 12 >>> eval_expr('2**6') 64 >>> eval_expr('1 + 2*3**(4) / (6 + -7)') -161.0 |
172,266 | from mmap import mmap
import errno
import os
import stat
import threading
import atexit
import tempfile
import time
import warnings
import weakref
from uuid import uuid4
from multiprocessing import util
from pickle import whichmodule, loads, dumps, HIGHEST_PROTOCOL, PicklingError
from .numpy_pickle import dump, load, l... | Wrapper around os.unlink with a retry mechanism. The retry mechanism has been implemented primarily to overcome a race condition happening during the finalizer of a np.memmap: when a process holding the last reference to a mmap-backed np.memmap/np.array is about to delete this array (and close the reference), it sends ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.