repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
voila | voila/tornado/execution_request_handler.py | .py | import asyncio
import json
from typing import Awaitable, Union
from jupyter_server.base.handlers import JupyterHandler
from tornado.websocket import WebSocketHandler
from tornado.web import HTTPError
try:
JUPYTER_SERVER_2 = True
from jupyter_server.base.websocket import WebSocketMixin
except ImportError:
J... | 145 | 6,017 |
voila | voila/tornado/treehandler.py | .py | #############################################################################
# Copyright (c) 2018, Voilà Contributors #
# Copyright (c) 2018, QuantStack #
# #
# Distri... | 118 | 4,928 |
voila | voila/tornado/contentshandler.py | .py | import json
import os
try:
from jupyter_client.jsonutil import json_default
except ImportError:
from jupyter_client.jsonutil import date_default as json_default
from tornado import web
from jupyter_server.base.handlers import APIHandler
from jupyter_server.services.contents.handlers import validate_model
from ... | 86 | 3,135 |
voila | voila/tornado/kernel_websocket_handler.py | .py | import json
from typing import Any, Dict, Optional, Union
try:
from jupyter_server.services.kernels.websocket import (
KernelWebsocketHandler as WebsocketHandler,
)
except ImportError:
from jupyter_server.services.kernels.handlers import (
ZMQChannelsHandler as WebsocketHandler,
)
def... | 44 | 1,338 |
voila | voila/tornado/handler.py | .py | #############################################################################
# Copyright (c) 2018, Voilà Contributors #
# Copyright (c) 2018, QuantStack #
# #
# Distri... | 21 | 919 |
voila | docs/conf.py | .py | import os
# Add dev disclaimer.
_release = {}
exec(
compile(open("../voila/_version.py").read(), "../voila/_version.py", "exec"),
_release,
)
if _release["version_info"][-1] == "dev":
rst_prolog = """
.. note::
This documentation is for a development version of Voilà. There may be
sign... | 53 | 1,264 |
voila | tests/execute_output_test.py | .py | import os
from copy import deepcopy
from nbformat import NO_CONVERT, read
from voila.execute import executenb
BASE_DIR = os.path.dirname(__file__)
WIDGET_MIME_TYPE_VIEW = "application/vnd.jupyter.widget-view+json"
WIDGET_MIME_TYPE_STATE = "application/vnd.jupyter.widget-state+json"
# based on nbconvert.preprocesso... | 61 | 2,304 |
voila | tests/utils_test.py | .py | from typing import Dict, List, Set
from voila.utils import filter_extension
federated_extensions = [{"name": "foo"}, {"name": "bar"}, {"name": "foo-bar"}]
def list_to_set(inp: List[Dict]) -> Set:
return set([x["name"] for x in inp])
def test_filter_extension():
extensions = filter_extension(federated_exte... | 24 | 703 |
voila | tests/conftest.py | .py | # fixtures common for app and server
import os
import time
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def base_url():
return "/"
@pytest.fixture
def notebook_directory():
return os.path.join(BASE_DIR, "notebooks")
@pytest.fixture
def print_notebook_url(base_url):
return base_... | 39 | 672 |
voila | tests/server/nbextensions_test.py | .py | # tests programmatic config of template system
import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def jupyter_server_config():
def config(app):
pass
os.environ["JUPYTER_CONFIG_DIR"] = os.path.join(
BASE_DIR, "..", "configs", "general"
)
yield config
del... | 28 | 702 |
voila | tests/server/show_traceback_test.py | .py | import pytest
@pytest.fixture(params=[True, False])
def show_tracebacks(request):
return request.param
@pytest.fixture
def jupyter_server_args_extra(show_tracebacks):
return [f"--VoilaConfiguration.show_tracebacks={show_tracebacks}"]
async def test_syntax_error(
http_server_client, syntax_error_notebo... | 28 | 849 |
voila | tests/server/static_files_test.py | .py | import pytest
import tornado
from voila.static_file_handler import TemplateStaticFileHandler
async def test_static_file_absolute_path(app, base_url, http_server_client):
response_lab = await http_server_client.fetch(
f"{base_url}voila/templates/lab/static/voila.js"
)
assert response_lab.code == 2... | 57 | 2,125 |
voila | tests/server/no_strip_sources_test.py | .py | import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def jupyter_server_args_extra():
return ["--VoilaConfiguration.strip_sources=False"]
async def test_hello_world(http_server_client, print_notebook_url):
response = await http_server_client.fetch(print_notebook_url)
assert res... | 19 | 496 |
voila | tests/server/execute_test.py | .py | # test basics of Voilà running a notebook
async def test_hello_world(http_server_client, print_notebook_url):
response = await http_server_client.fetch(print_notebook_url)
assert response.code == 200
html_text = response.body.decode("utf-8")
assert "Hi Voilà" in html_text
assert "print(" not in ht... | 13 | 486 |
voila | tests/server/execute_cpp_test.py | .py | import os
import pytest
TEST_XEUS_CPP = os.environ.get("VOILA_TEST_XEUS_CPP", "") == "1"
@pytest.fixture
def cpp_file_url(base_url):
return base_url + "voila/render/print.xcpp"
@pytest.fixture
def jupyter_server_args_extra():
return ['--VoilaConfiguration.extension_language_mapping={".xcpp": "C++23"}']
... | 30 | 800 |
voila | tests/server/cwd_subdir_test.py | .py | # NOTE: this is a duplicate of ../app/cwd_subdir_test.py
# we might want to find a better pattern of executing test for the app and extension
import pytest
@pytest.fixture
def cwd_subdir_notebook_url(base_url):
return base_url + "voila/render/subdir/cwd_subdir.ipynb"
@pytest.fixture
def voila_args(notebook_dire... | 20 | 661 |
voila | tests/server/tree_test.py | .py | # test tree rendering
import pytest
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ["--VoilaTest.root_dir=%r" % notebook_directory, *voila_args_extra]
@pytest.fixture
def jupyter_server_args_extra():
return [
'--VoilaConfiguration.extension_language_mapping={".xcpp": "C... | 29 | 912 |
voila | tests/server/conftest.py | .py | import os
import pytest
from jupyter_server.serverapp import ServerApp
from tornado import httpserver
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def jupyter_server_config():
return lambda app: None
@pytest.fixture
def jupyter_server_args_extra():
return []
@pytest.fixture
def jupyter_server_ar... | 48 | 1,250 |
voila | tests/skip_template/setup.py | .py | import os
from setuptools import setup
data_files = []
for dirpath, _dirnames, filenames in os.walk("share/jupyter/voila/templates"):
if filenames:
data_files.append(
(dirpath, [os.path.join(dirpath, filename) for filename in filenames])
)
setup(
name="skip_template",
version... | 22 | 517 |
voila | tests/test_template/setup.py | .py | import os
from setuptools import setup
data_files = []
for dirpath, _dirnames, filenames in os.walk("share/jupyter/voila/templates"):
if filenames:
data_files.append(
(dirpath, [os.path.join(dirpath, filename) for filename in filenames])
)
setup(
name="test_template",
version... | 22 | 517 |
voila | tests/template_prefixes/loader_test.py | .py | """Tests loading template of jinja2 templates"""
import os
from jinja2 import Environment, FileSystemLoader
from voila.paths import collect_paths
HERE = os.path.dirname(__file__)
ROOT_DIRS = [os.path.join(HERE, "user"), os.path.join(HERE, "system")]
def test_loader_default_nbconvert():
paths = collect_paths(... | 59 | 2,417 |
voila | tests/app/no_kernelspec_test.py | .py | import pytest
NOTEBOOK_PATH = "no_kernelspec.ipynb"
@pytest.fixture
def non_existing_kernel_notebook(base_url):
return base_url + f"voila/render/{NOTEBOOK_PATH}"
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ["--VoilaTest.root_dir=%r" % notebook_directory, *voila_args_extra]
... | 23 | 604 |
voila | tests/app/preheat_with_query_string_test.py | .py | import asyncio
import os
import time
import pytest
@pytest.fixture(params=[['--Voila.base_url="/base/"'], []])
def using_base_url(request):
return request.param
@pytest.fixture(params=[['--Voila.server_url="/server/"'], []])
def using_server_url(request):
return request.param
@pytest.fixture()
def voila_... | 64 | 1,547 |
voila | tests/app/config_paths_test.py | .py | # test all objects that should be configurable
import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def voila_config_file_paths_arg():
path = os.path.join(BASE_DIR, "..", "configs", "general")
return "--VoilaTest.config_file_paths=[%r]" % path
def test_config_app(voila_app):
as... | 32 | 862 |
voila | tests/app/nbextensions_test.py | .py | # tests programmatic config of template system
import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def voila_config():
def config(app):
pass
os.environ["JUPYTER_CONFIG_DIR"] = os.path.join(BASE_DIR, "../configs/general")
yield config
del os.environ["JUPYTER_CONFIG_D... | 33 | 923 |
voila | tests/app/show_traceback_test.py | .py | import pytest
NOTEBOOK_PATH = "syntax_error.ipynb"
@pytest.fixture(params=[True, False])
def show_tracebacks(request):
return request.param
@pytest.fixture
def notebook_show_traceback_path(base_url):
return base_url + f"voila/render/{NOTEBOOK_PATH}"
@pytest.fixture
def voila_args(notebook_directory, voil... | 39 | 1,130 |
voila | tests/app/preheat_default_kernel_env_test.py | .py | import asyncio
import os
import pytest
@pytest.fixture()
def voila_args_extra():
return ['--VoilaKernelManager.default_env_variables={"FOO": "BAR"}']
@pytest.fixture
def preheat_mode():
return True
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "prehea... | 36 | 760 |
voila | tests/app/prelaunch_hook_test.py | .py | # tests prelaunch hook config
import os
import pytest
from nbformat import NotebookNode
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "print.ipynb")
@pytest.fixture
def voila_config():
def foo(req, notebook, cwd):
... | 44 | 1,087 |
voila | tests/app/many_iopub_messages_test.py | .py | import os
import pytest
MAX_TIMEOUT_SECONDS = 240
@pytest.fixture
def preheat_mode():
return False
@pytest.fixture
def voila_args_extra():
return [f"--VoilaExecutor.timeout={MAX_TIMEOUT_SECONDS}"]
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "many_i... | 30 | 643 |
voila | tests/app/static_files_test.py | .py | import pytest
import tornado
from voila.static_file_handler import TemplateStaticFileHandler
async def test_static_file_absolute_path(voila_app, app, base_url, http_server_client):
response_lab = await http_server_client.fetch(
f"{base_url}voila/templates/lab/static/voila.js"
)
assert response_la... | 59 | 2,186 |
voila | tests/app/cwd_test.py | .py | # tests the --template argument of voila
import os
import pytest
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "cwd.ipynb")
async def test_template_cwd(http_server_client, base_url):
response = await http_server_client.fetch(base_url)
html_text = respon... | 16 | 388 |
voila | tests/app/progressive_rendering_test.py | .py | import asyncio
import os
import time
import pytest
@pytest.fixture
def progressive_rendering_mode():
return True
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "preheat", "pre_heat.ipynb")
NOTEBOOK_EXECUTION_TIME = 2
TIME_THRESHOLD = NOTEBOOK_EXECUTION_TIM... | 40 | 948 |
voila | tests/app/preheat_multiple_notebooks_test.py | .py | import asyncio
import os
import time
import pytest
BASE_DIR = os.path.dirname(__file__)
NOTEBOOK_EXECUTION_TIME = 3
NUMBER_PREHEATED_KERNEL = 2
TIME_THRESHOLD = 1
@pytest.fixture
def voila_config_file_paths_arg():
path = os.path.join(BASE_DIR, "..", "configs", "preheat")
return "--VoilaTest.config_file_path... | 60 | 1,577 |
voila | tests/app/image_inlining_test.py | .py | # tests the --template argument of voila
import base64
import os
import pytest
NOTEBOOK_PATH = "images.ipynb"
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, NOTEBOOK_PATH)
async def test_image_inlining(http_server_client, base_url, notebook_directory):
resp... | 29 | 803 |
voila | tests/app/prelaunch_hook_papermill_test.py | .py | # tests prelaunch hook config
import os
from urllib.parse import quote_plus
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "print_parameterized.ipynb")
@pytest.fixture
def voila_config():
def parameterize_w... | 64 | 1,999 |
voila | tests/app/no_strip_sources_test.py | .py | import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def voila_args_extra():
return ["--VoilaConfiguration.strip_sources=False", "--VoilaExecutor.timeout=240"]
async def test_no_strip_sources(http_server_client, base_url):
response = await http_server_client.fetch(base_url)
ass... | 19 | 503 |
voila | tests/app/non_existing_kernel_test.py | .py | import pytest
NOTEBOOK_PATH = "non_existing_kernel.ipynb"
@pytest.fixture
def non_existing_kernel_notebook(base_url):
return base_url + f"voila/render/{NOTEBOOK_PATH}"
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ["--VoilaTest.root_dir=%r" % notebook_directory, *voila_args_e... | 20 | 588 |
voila | tests/app/execute_test.py | .py | # test basics of voila running a notebook
import asyncio
import json
import re
from unittest import mock
import tornado.web
async def test_hello_world(http_server_client, base_url):
response = await http_server_client.fetch(base_url)
assert response.code == 200
html_text = response.body.decode("utf-8")
... | 63 | 2,144 |
voila | tests/app/template_custom_test.py | .py | # tests programmatic config of template system
import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def voila_args_extra():
return ["--template=test_template", "--VoilaExecutor.timeout=240"]
@pytest.fixture
def voila_config():
def config(app):
path_test_template = os.path.a... | 35 | 947 |
voila | tests/app/kernel_death_test.py | .py | import os
import pytest
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "autokill.ipynb")
@pytest.fixture
def voila_args_extra():
return ["--debug"]
@pytest.fixture
def preheat_mode():
return False
async def test_kernel_death(http_server_client, base_... | 25 | 476 |
voila | tests/app/execute_cpp_test.py | .py | import os
import pytest
TEST_XEUS_CPP = os.environ.get("VOILA_TEST_XEUS_CPP", "") == "1"
NOTEBOOK_PATH = "print.xcpp"
@pytest.fixture
def cpp_file_url(base_url, preheat_mode):
return base_url + f"voila/render/{NOTEBOOK_PATH}"
@pytest.fixture
def voila_args_extra():
return [
'--VoilaConfiguration.e... | 34 | 908 |
voila | tests/app/progressive_rendering_activation_test.py | .py | import os
import voila.app
import pytest
@pytest.fixture
def progressive_rendering_mode():
return True
@pytest.fixture
def preheat_mode():
return True
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "preheat", "pre_heat.ipynb")
class VoilaTest(voila.ap... | 38 | 847 |
voila | tests/app/shutdown_kernel_test.py | .py | import re
import pytest
@pytest.fixture
def voila_config():
def config(voila_app):
voila_app.tornado_settings["disable_check_xsrf"] = True
return config
async def test_shutdown_handler(http_server_client, base_url):
response = await http_server_client.fetch(base_url)
html_text = response.bo... | 24 | 677 |
voila | tests/app/contents_handler_test.py | .py | import json
import pytest
import tornado
@pytest.fixture
def preheat_mode():
return False
@pytest.fixture
def contents_prefix(base_url):
return base_url + "voila/api/contents"
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ["--VoilaTest.root_dir=%r" % notebook_directory, ... | 50 | 1,527 |
voila | tests/app/page_config_hook_test.py | .py | import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "print.ipynb")
@pytest.fixture
def voila_config():
def foo(current_page_config, **kwargs):
current_page_config["foo"] = "my custom config"
... | 30 | 664 |
voila | tests/app/no_metadata.py | .py | import pytest
NOTEBOOK_PATH = "no_metadata.ipynb"
@pytest.fixture
def non_existing_notebook_metadata(base_url):
return base_url + f"voila/render/{NOTEBOOK_PATH}"
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ["--VoilaTest.root_dir=%r" % notebook_directory, *voila_args_extra]
... | 22 | 610 |
voila | tests/app/cwd_subdir_test.py | .py | # test serving a notebook
import pytest
NOTEBOOK_PATH = "subdir/cwd_subdir.ipynb"
@pytest.fixture
def cwd_subdir_notebook_url(base_url):
return base_url + f"voila/render/{NOTEBOOK_PATH}"
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ["--VoilaTest.root_dir=%r" % notebook_direc... | 21 | 581 |
voila | tests/app/serve_directory_test.py | .py | # test serving a notebook or python/c++ notebook
import os
import pytest
TEST_XEUS_CPP = os.environ.get("VOILA_TEST_XEUS_CPP", "") == "1"
@pytest.fixture
def preheat_mode():
return False
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ["--VoilaTest.root_dir=%r" % notebook_dire... | 48 | 1,408 |
voila | tests/app/template_sanity_test.py | .py | # tests basic things the templates should have
import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture(params=["lab", "classic"])
def voila_args_extra(request):
return [f"--template={request.param}"]
async def test_lists_extension(http_server_client, base_url, voila_app):
response = a... | 19 | 487 |
voila | tests/app/cgi-test.py | .py | import pytest
NOTEBOOK_PATH = "cgi.ipynb"
@pytest.fixture
def notebook_cgi_path(base_url):
return base_url + f"voila/render/{NOTEBOOK_PATH}"
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ["--VoilaTest.root_dir=%r" % notebook_directory, *voila_args_extra]
async def test_cgi_... | 20 | 552 |
voila | tests/app/tree_test.py | .py | # test tree rendering
import pytest
@pytest.fixture
def preheat_mode():
return False
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ["--VoilaTest.root_dir=%r" % notebook_directory, *voila_args_extra]
@pytest.fixture
def voila_args_extra():
return [
'--VoilaConfigu... | 35 | 982 |
voila | tests/app/preheat_activation_test.py | .py | import asyncio
import os
import time
import pytest
@pytest.fixture
def preheat_mode():
return True
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "preheat", "pre_heat.ipynb")
NOTEBOOK_EXECUTION_TIME = 2
TIME_THRESHOLD = NOTEBOOK_EXECUTION_TIME
async def ... | 111 | 3,436 |
voila | tests/app/template_config_file_test.py | .py | # tests config of template system from JSON file
import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def voila_args_extra():
path_test_template = os.path.abspath(
os.path.join(
BASE_DIR,
"../test_template/share/jupyter/voila/templates/test_template/nbconv... | 37 | 1,075 |
voila | tests/app/timeout_test.py | .py | import os
import pytest
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "sleep.ipynb")
@pytest.fixture
def voila_args_extra():
return ["--VoilaExecutor.timeout=1", "--KernelManager.shutdown_wait_time=0.1"]
async def test_timeout(http_server_client, base_url... | 20 | 476 |
voila | tests/app/template_cli_test.py | .py | # tests programmatic config of template system
import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def voila_args_extra():
path_test_template = os.path.abspath(
os.path.join(
BASE_DIR, "../test_template/share/jupyter/voila/templates/test_template/"
)
)
... | 32 | 860 |
voila | tests/app/notebooks_test.py | .py | # simply tests if some notebooks execute
import pytest
NOTEBOOK_PATH = "other_comms.ipynb"
@pytest.fixture
def notebook_other_comms_path(base_url):
return base_url + f"voila/render/{NOTEBOOK_PATH}"
@pytest.fixture
def voila_args(notebook_directory, voila_args_extra):
return ["--VoilaTest.root_dir=%r" % not... | 21 | 601 |
voila | tests/app/preheat_configuration_test.py | .py | import asyncio
import os
import time
import pytest
BASE_DIR = os.path.dirname(__file__)
NOTEBOOK_EXECUTION_TIME = 3
NUMBER_PREHEATED_KERNEL = 2
TIME_THRESHOLD = 1
@pytest.fixture
def voila_config_file_paths_arg():
path = os.path.join(BASE_DIR, "..", "configs", "preheat")
return "--VoilaTest.config_file_path... | 60 | 1,664 |
voila | tests/app/preprocessor_test.py | .py | # tests the --template argument of Voilà
import os
import pytest
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, "skip-voila-cell.ipynb")
@pytest.fixture
def voila_args_extra():
return ["--template=skip_template"]
async def test_markdown_preprocessor(http_s... | 23 | 570 |
voila | tests/app/template_arg_test.py | .py | # tests the --template argument of Voilà
import pytest
@pytest.fixture
def voila_args_extra():
return ["--template=test_template", "--VoilaExecutor.timeout=240"]
async def test_template(http_server_client, base_url):
response = await http_server_client.fetch(base_url)
assert response.code == 200
ass... | 15 | 434 |
voila | tests/app/syntax_error_test.py | .py | import os
import pytest
NOTEBOOK_PATH = "syntax_error.ipynb"
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, NOTEBOOK_PATH)
async def test_syntax_error(http_server_client, base_url):
response = await http_server_client.fetch(base_url)
assert response.cod... | 19 | 489 |
voila | tests/app/conftest.py | .py | import os
import pytest
import voila.app
BASE_DIR = os.path.dirname(__file__)
class VoilaTest(voila.app.Voila):
def listen(self):
pass # the ioloop is taken care of by the pytest-tornado framework
@pytest.fixture
def voila_config():
return lambda app: None
@pytest.fixture
def voila_args_extra(... | 85 | 1,994 |
voila | scripts/bump-version.py | .py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.import click
# Heavily inspired by:
# - https://github.com/jupyterlab/jupyterlab/blob/master/buildutils/src/bumpversion.ts
# - https://github.com/jupyterlab/retrolab/blob/main/buildutils/src/release-bump.ts
import clic... | 113 | 3,246 |
more-itertools | more_itertools/__init__.py | .py | """More routines for operating on iterables, beyond itertools"""
from .more import * # noqa
from .recipes import * # noqa
__version__ = '11.1.0'
| 7 | 149 |
more-itertools | more_itertools/recipes.py | .py | """Imported from the recipes section of the itertools documentation.
All functions taken from the recipes section of the itertools library docs
[1]_.
Some backward-compatible usability improvements have been made.
.. [1] http://docs.python.org/library/itertools.html#recipes
"""
import random
from bisect import bis... | 1,622 | 46,429 |
more-itertools | more_itertools/more.py | .py | __lazy_modules__ = frozenset({'queue', 'threading'})
import math
import types
from collections import Counter, defaultdict, deque
from collections.abc import Sequence
from contextlib import suppress
from functools import cached_property, partial, wraps
from heapq import heapify, heapreplace
from itertools import (
... | 5,565 | 172,000 |
more-itertools | tests/test_recipes.py | .py | from collections import Counter
from decimal import Decimal
from doctest import DocTestSuite
from fractions import Fraction
from functools import reduce
from itertools import (
combinations,
count,
groupby,
permutations,
islice,
)
from operator import mul, eq
from math import comb, prod, factorial
f... | 1,712 | 56,509 |
more-itertools | tests/test_more.py | .py | from __future__ import annotations
import cmath
import gc
import platform
import types
import weakref
from collections import Counter, deque
from collections.abc import Set, Sequence, Iterable, Iterator, Hashable
from datetime import datetime, timedelta
from decimal import Decimal
from doctest import DocTestSuite
fro... | 7,079 | 242,480 |
toolz | toolz/utils.py | .py | def raises(err, lamda):
try:
lamda()
return False
except err:
return True
no_default = '__no__default__'
| 10 | 139 |
toolz | toolz/dicttoolz.py | .py | import operator
import collections
from functools import reduce
from collections.abc import Mapping
__all__ = ('merge', 'merge_with', 'valmap', 'keymap', 'itemmap',
'valfilter', 'keyfilter', 'itemfilter',
'assoc', 'dissoc', 'assoc_in', 'update_in', 'get_in')
def _get_factory(f, kwargs):
fac... | 340 | 8,955 |
toolz | toolz/__init__.py | .py | from .itertoolz import *
from .functoolz import *
from .dicttoolz import *
from .recipes import *
from functools import partial, reduce
sorted = sorted
map = map
filter = filter
# Aliases
comp = compose
from . import curried, sandbox
functoolz._sigs.create_signature_registry()
def __getattr__(name):
if ... | 33 | 543 |
toolz | toolz/functoolz.py | .py | from functools import reduce, partial
import inspect
import sys
from operator import attrgetter, not_
from importlib import import_module
from types import MethodType
from .utils import no_default
PYPY = hasattr(sys, 'pypy_version_info') and sys.version_info[0] > 2
__all__ = ('identity', 'apply', 'thread_first', 't... | 1,050 | 29,757 |
toolz | toolz/itertoolz.py | .py | import itertools
import heapq
import collections
import operator
from functools import partial
from itertools import filterfalse, zip_longest
from collections.abc import Sequence
from toolz.utils import no_default
__all__ = ('remove', 'accumulate', 'groupby', 'merge_sorted', 'interleave',
'unique', 'isiter... | 1,058 | 27,697 |
toolz | toolz/compatibility.py | .py | import warnings
warnings.warn("The toolz.compatibility module is no longer "
"needed in Python 3 and has been deprecated. Please "
"import these utilities directly from the standard library. "
"This module will be removed in a future release.",
category=Deprecatio... | 31 | 997 |
toolz | toolz/recipes.py | .py | import itertools
from .itertoolz import frequencies, pluck, getter
__all__ = ('countby', 'partitionby')
def countby(key, seq):
""" Count elements of a collection by a key function
>>> countby(len, ['cat', 'mouse', 'dog'])
{3: 2, 5: 1}
>>> def iseven(x): return x % 2 == 0
>>> countby(iseven, [1... | 47 | 1,256 |
toolz | toolz/_signatures.py | .py | """Internal module for better introspection of builtins.
The main functions are ``is_builtin_valid_args``, ``is_builtin_partial_args``,
and ``has_unknown_args``. Other functions in this module support these three.
Notably, we create a ``signatures`` registry to enable introspection of
builtin functions in any Python... | 785 | 20,555 |
toolz | toolz/sandbox/parallel.py | .py | import functools
from toolz.itertoolz import partition_all
from toolz.utils import no_default
def _reduce(func, seq, initial=None):
if initial is None:
return functools.reduce(func, seq)
else:
return functools.reduce(func, seq, initial)
def fold(binop, seq, default=no_default, map=map, chunk... | 84 | 2,966 |
toolz | toolz/sandbox/core.py | .py | from toolz.itertoolz import getter, cons, pluck
from itertools import tee, starmap
# See #166: https://github.com/pytoolz/toolz/issues/166
# See #173: https://github.com/pytoolz/toolz/pull/173
class EqualityHashKey:
""" Create a hash key that uses equality comparisons between items.
This may be used to creat... | 134 | 4,327 |
toolz | toolz/sandbox/tests/test_core.py | .py | from toolz import curry, unique, first, take
from toolz.sandbox.core import EqualityHashKey, unzip
from itertools import count, repeat
def test_EqualityHashKey_default_key():
EqualityHashDefault = curry(EqualityHashKey, None)
L1 = [1]
L2 = [2]
data1 = [L1, L1, L2, [], [], [1], [2], {}, ()]
set1 = s... | 102 | 3,830 |
toolz | toolz/sandbox/tests/test_parallel.py | .py | from toolz.sandbox.parallel import fold
from toolz import reduce
from operator import add
from pickle import dumps, loads
from multiprocessing import Pool
# is comparison will fail between this and no_default
no_default2 = loads(dumps('__no__default__'))
def test_fold():
assert fold(add, range(10), 0) == reduce... | 31 | 904 |
toolz | toolz/tests/test_curried.py | .py | import toolz
import toolz.curried
from toolz.curried import (take, first, second, sorted, merge_with, reduce,
merge, operator as cop)
from collections import defaultdict
from importlib import import_module
from operator import add
def test_take():
assert list(take(2)([1, 2, 3])) == [1, ... | 118 | 3,724 |
toolz | toolz/tests/test_tlz.py | .py | import toolz
def test_tlz():
import tlz
tlz.curry
tlz.functoolz.curry
assert tlz.__package__ == 'tlz'
assert tlz.__name__ == 'tlz'
import tlz.curried
assert tlz.curried.__package__ == 'tlz.curried'
assert tlz.curried.__name__ == 'tlz.curried'
tlz.curried.curry
import tlz.currie... | 58 | 1,593 |
toolz | toolz/tests/test_compatibility.py | .py | import pytest
import importlib
def test_compat_warn():
with pytest.warns(DeprecationWarning):
# something else is importing this,
import toolz.compatibility
# reload to be sure we warn
importlib.reload(toolz.compatibility)
| 10 | 260 |
toolz | toolz/tests/test_curried_doctests.py | .py | import doctest
import toolz
def test_doctests():
toolz.__test__ = {}
for name, func in vars(toolz).items():
if isinstance(func, toolz.curry):
toolz.__test__[name] = func.func
assert doctest.testmod(toolz).failed == 0
del toolz.__test__
| 12 | 274 |
toolz | toolz/tests/test_itertoolz.py | .py | import itertools
from itertools import starmap
from toolz.utils import raises
from functools import partial
from random import Random
from pickle import dumps, loads
from toolz.itertoolz import (remove, groupby, merge_sorted,
concat, concatv, interleave, unique,
... | 589 | 19,626 |
toolz | toolz/tests/test_inspect_args.py | .py | import functools
import inspect
import itertools
import operator
import sys
import toolz
from toolz.functoolz import (curry, is_valid_args, is_partial_args, is_arity,
num_required_args, has_varargs, has_keywords)
from toolz._signatures import builtins
import toolz._signatures as _sigs
from ... | 505 | 16,539 |
toolz | toolz/tests/test_dicttoolz.py | .py | from collections import defaultdict as _defaultdict
from collections.abc import Mapping
import os
from toolz.dicttoolz import (merge, merge_with, valmap, keymap, update_in,
assoc, dissoc, keyfilter, valfilter, itemmap,
itemfilter, assoc_in)
from toolz.functoolz ... | 271 | 9,037 |
toolz | toolz/tests/test_signatures.py | .py | import functools
import toolz._signatures as _sigs
from toolz._signatures import builtins, _is_valid_args, _is_partial_args
def test_is_valid(check_valid=_is_valid_args, incomplete=False):
orig_check_valid = check_valid
check_valid = lambda func, *args, **kwargs: orig_check_valid(func, args, kwargs)
asse... | 86 | 2,873 |
toolz | toolz/tests/test_recipes.py | .py | from toolz import first, identity, countby, partitionby
def iseven(x):
return x % 2 == 0
def test_countby():
assert countby(iseven, [1, 2, 3]) == {True: 1, False: 2}
assert countby(len, ['cat', 'dog', 'mouse']) == {3: 2, 5: 1}
assert countby(0, ('ab', 'ac', 'bc')) == {'a': 2, 'b': 1}
def test_part... | 28 | 820 |
toolz | toolz/tests/test_package.py | .py | import toolz
def test_has_version():
# If this test fails, then toolz probably isn't installed properly.
# For local development, try `pip install -e .` from the project directory.
version = toolz.__version__
assert isinstance(version, str)
assert version.startswith("1.")
| 10 | 295 |
toolz | toolz/tests/test_serialization.py | .py | from toolz import *
import toolz
import toolz.curried
import pickle
from toolz.utils import raises
def test_compose():
f = compose(str, sum)
g = pickle.loads(pickle.dumps(f))
assert f((1, 2)) == g((1, 2))
def test_curry():
f = curry(map)(str)
g = pickle.loads(pickle.dumps(f))
assert list(f((... | 193 | 5,759 |
toolz | toolz/tests/test_functoolz.py | .py | import inspect
import toolz
from toolz.functoolz import (thread_first, thread_last, memoize, curry,
compose, compose_left, pipe, complement, do, juxt,
flip, excepts, apply)
from operator import add, mul, itemgetter
from toolz.utils import raises
from functools i... | 800 | 20,332 |
toolz | toolz/tests/test_utils.py | .py | from toolz.utils import raises
def test_raises():
assert raises(ZeroDivisionError, lambda: 1 / 0)
assert not raises(ZeroDivisionError, lambda: 1)
| 7 | 156 |
toolz | toolz/curried/exceptions.py | .py | import toolz
__all__ = ['merge_with', 'merge']
@toolz.curry
def merge_with(func, d, *dicts, **kwargs):
return toolz.merge_with(func, d, *dicts, **kwargs)
@toolz.curry
def merge(d, *dicts, **kwargs):
return toolz.merge(d, *dicts, **kwargs)
merge_with.__doc__ = toolz.merge_with.__doc__
merge.__doc__ = too... | 19 | 337 |
toolz | toolz/curried/__init__.py | .py | """
Alternate namespace for toolz such that all functions are curried
Currying provides implicit partial evaluation of all functions
Example:
Get usually requires two arguments, an index and a collection
>>> from toolz.curried import get
>>> get(0, ('a', 'b'))
'a'
When we use it in higher order ... | 104 | 2,700 |
toolz | toolz/curried/operator.py | .py | import operator
from toolz.functoolz import curry
# Tests will catch if/when this needs updated
IGNORE = {
"__abs__", "__index__", "__inv__", "__invert__", "__neg__", "__not__",
"__pos__", "_abs", "abs", "attrgetter", "index", "inv", "invert",
"is_none", "is_not_none", "itemgetter", "neg", "not_", "pos",... | 21 | 515 |
toolz | bench/test_curry.py | .py | from toolz.curried import get
pairs = [(1, 2) for i in range(100000)]
def test_get_curried():
first = get(0)
for p in pairs:
first(p)
| 11 | 154 |
toolz | bench/test_join.py | .py | from toolz.curried import *
try:
xrange
except NameError:
xrange = range
def burn(seq):
for item in seq:
pass
small = [(i, str(i)) for i in range(100)] * 10
big = pipe([110]*10000, map(range), concat, list)
def test_many_to_many_large():
burn(join(get(0), small, identity, big))
def test_... | 35 | 640 |
toolz | bench/test_wordcount.py | .py | from toolz.curried import *
import os
if not os.path.exists('bench/shakespeare.txt'):
os.system('wget http://www.gutenberg.org/files/100/100-0.txt'
' -O bench/shakespeare.txt')
def stem(word):
""" Stem word to primitive form """
return word.lower().rstrip(",.!:;'-\"").lstrip("'\"")
wordcou... | 19 | 479 |
toolz | bench/test_groupby.py | .py | from toolz import groupby, identity
data = list(range(1000)) * 1000
def test_groupby():
groupby(identity, data)
| 9 | 120 |
toolz | bench/test_get_list.py | .py | from toolz import get
tuples = [(1, 2, 3) for i in range(100000)]
def test_get():
for tup in tuples:
get([1, 2], tup)
| 9 | 133 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.