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
metrics
tests/unittests/__init__.py
.py
import os.path import warnings from typing import NamedTuple import numpy import torch from cachier import cachier from torch import Tensor from unittests.conftest import ( BATCH_SIZE, EXTRA_DIM, NUM_BATCHES, NUM_CLASSES, NUM_PROCESSES, THRESHOLD, USE_PYTEST_POOL, setup_ddp, ) # addin...
67
1,595
mlflow
dev/clint/src/clint/rules/os_environ_set_in_test.py
.py
import ast from clint.resolver import Resolver from clint.rules.base import Rule class OsEnvironSetInTest(Rule): def _message(self) -> str: return "Do not set `os.environ` in test directly. Use `monkeypatch.setenv` (https://docs.pytest.org/en/stable/reference/reference.html#pytest.MonkeyPatch.setenv)." ...
20
700
saleor
saleor/product/tests/fixtures/category.py
.py
import datetime import pytest from ....attribute.utils import associate_attribute_values_to_instance from ...models import Category, Product, ProductChannelListing @pytest.fixture def category_generator(): def create_category( name="Default", slug="default", ): category = Category.ob...
344
11,297
wandb
wandb/integration/weave/interface.py
.py
"""Internal APIs for integrating with weave. The public functions here are intended to be called by weave and care should be taken to maintain backward compatibility. """ from __future__ import annotations import dataclasses from wandb.sdk import wandb_setup @dataclasses.dataclass(frozen=True) class RunPath: ...
50
1,165
bazel
src/create_embedded_tools_lib.py
.py
# pylint: disable=g-bad-file-header # Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
95
3,763
pyro
pyro/distributions/gaussian_scale_mixture.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import math import torch from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.distributions import Categorical, constraints from pyro.distributions.torch_distribution import Torch...
212
8,374
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
clearml
clearml/utilities/locks/exceptions.py
.py
from typing import Any class BaseLockException(Exception): # Error codes: LOCK_FAILED = 1 def __init__(self, *args: Any, **kwargs: Any) -> None: self.fh = kwargs.pop("fh", None) Exception.__init__(self, *args, **kwargs) class LockException(BaseLockException): pass class AlreadyLoc...
23
402
returns
returns/methods/partition.py
.py
from collections.abc import Iterable from typing import TypeVar from returns.interfaces.unwrappable import Unwrappable from returns.primitives.exceptions import UnwrapFailedError _ValueType_co = TypeVar('_ValueType_co', covariant=True) _ErrorType_co = TypeVar('_ErrorType_co', covariant=True) def partition( cont...
37
1,092
hatch
tests/project/test_sources.py
.py
import pytest from hatch.dep.core import Dependency from hatch.project.sources import ( GitSource, IndexSource, PathSource, UrlSource, WorkspaceSource, apply_source_to_requirement, collect_global_install_args, decorate_dependencies, decorate_dependency, describe_source, merg...
530
19,673
sphinx
tests/test_util/test_util_matching.py
.py
"""Tests sphinx.util.matching functions.""" from __future__ import annotations from typing import TYPE_CHECKING from sphinx.util.matching import Matcher, compile_matchers, get_matching_files if TYPE_CHECKING: from pathlib import Path def test_compile_matchers() -> None: # exact matching pat = compile_...
322
8,549
mlflow
dev/clint/tests/rules/test_use_sys_executable.py
.py
from pathlib import Path from clint.config import Config from clint.index import SymbolIndex from clint.linter import Position, Range, lint_file from clint.rules import UseSysExecutable def test_use_sys_executable(index: SymbolIndex) -> None: code = """ import subprocess import sys # Bad subprocess.run(["mlflow...
28
818
pyomo
pyomo/gdp/util.py
.py
# ____________________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and Engineering # Solutions of...
686
24,485
saleor
saleor/graphql/channel/mutations/channel_activate.py
.py
import graphene from django.core.exceptions import ValidationError from ....channel.error_codes import ChannelErrorCode from ....permission.enums import ChannelPermissions from ....webhook.event_types import WebhookEventAsyncType from ...core import ResolveInfo from ...core.doc_category import DOC_CATEGORY_CHANNELS fr...
56
2,054
deap
doc/code/benchmarks/rosenbrock.py
.py
from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.colors import LogNorm import matplotlib.pyplot as plt try: import numpy as np except: exit() from deap import benchmarks def rosenbrock_arg0(sol): return benchmarks.rosenbrock(sol)[0] fig = plt.figure() # ax = Axes3D(fig, ...
29
691
jupytext
tests/functional/simple_notebooks/test_ipynb_to_R.py
.py
import nbformat import pytest import jupytext from jupytext.compare import compare_notebooks @pytest.mark.parametrize("ext", [".r", ".R"]) def test_identity_source_write_read(ipynb_R_file, ext): """ Test that writing the notebook with R, and read again, is the same as removing outputs """ with o...
22
492
scikit-bio
skbio/stats/_subsample.py
.py
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE.txt, distributed with this software. # --------------------------------------------...
253
7,968
mlflow
dev/clint/tests/rules/test_forbidden_make_judge_in_builtin_scorers.py
.py
from pathlib import Path from clint.config import Config from clint.index import SymbolIndex from clint.linter import lint_file from clint.rules.forbidden_make_judge_in_builtin_scorers import ( ForbiddenMakeJudgeInBuiltinScorers, ) def test_forbidden_make_judge_in_builtin_scorers(index: SymbolIndex) -> None: ...
87
2,954
wagtail
wagtail/api/v3/querysets.py
.py
from http import HTTPStatus from typing import cast import swapper from django.http import HttpRequest from ninja.errors import HttpError from wagtail.api.querysets import get_public_pages_queryset from wagtail.permission_policies.pages import PagePermissionPolicy from wagtail.permissions import policy_registry Page...
50
2,000
django-cms
cms/test_utils/fixtures/fakemlng.py
.py
from cms.api import add_plugin from cms.test_utils.project.fakemlng.models import MainModel, Translations class FakemlngFixtures: def create_fixtures(self): main = MainModel.objects.create() en = Translations.objects.create(master=main, language_code='en') Translations.objects.create(maste...
14
646
coremltools
coremltools/optimize/torch/palettization/palettizer.py
.py
# Copyright (c) 2024, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause import logging as _logging from typing import Dict as _Dict from typing import Optional as _Optional ...
420
19,524
wagtail
wagtail/admin/views/pages/bulk_actions/unpublish.py
.py
from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext from wagtail.admin.views.pages.bulk_actions.page_bulk_action import PageBulkAction class UnpublishBulkAction(PageBulkAction): display_name = _("Unpublish") action_type = "unpublish" aria_label = _("Unpubl...
80
2,986
beam
sdks/python/apache_beam/runners/interactive/sql/beam_sql_magics.py
.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
471
17,942
pyro
tests/distributions/test_extended.py
.py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import math import pytest import torch from torch.autograd import grad import pyro.distributions as dist from pyro.contrib.epidemiology.distributions import set_approx_log_prob_tol from tests.common import assert_equal def check_gr...
97
3,462
saleor
saleor/graphql/account/tests/queries/test_customers_filtering.py
.py
import graphene import pytest from freezegun import freeze_time from .....account.models import User from .....account.search import update_user_search_vector from .....order.models import Order from ....tests.utils import get_graphql_content @pytest.fixture def query_customer_with_filter(): query = """ quer...
545
16,486
beam
sdks/python/apache_beam/ml/anomaly/univariate/quantile_test.py
.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
163
4,780
pyfilesystem2
fs/tree.py
.py
# coding: utf-8 """Render a FS object as text tree views. Color is supported on UNIX terminals. """ from __future__ import print_function, unicode_literals import sys import typing from fs.path import abspath, join, normpath if typing.TYPE_CHECKING: from typing import List, Optional, Text, TextIO, Tuple f...
173
5,656
ipython
IPython/utils/contexts.py
.py
"""Miscellaneous context managers.""" from __future__ import annotations from types import TracebackType from typing import Any # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. class preserve_keys: """Preserve a set of keys in a dictionary. Upon entering...
68
1,866
readthedocs.org
readthedocs/proxito/views/utils.py
.py
import structlog from django.http import HttpResponse from django.shortcuts import render from readthedocs.core.views import ErrorView from ..exceptions import ContextualizedHttp404 log = structlog.get_logger(__name__) # noqa class ProxitoErrorView(ErrorView): base_path = "errors/proxito" def fast_404(requ...
61
1,930
coveragepy
tests/test_json.py
.py
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt """Test json-based summary reporting for coverage.py""" from __future__ import annotations import json import os from datetime import datetime from typing impo...
567
17,936
eve
eve/logging.py
.py
from __future__ import absolute_import import logging from flask import request # TODO right now we are only logging exceptions. We should probably # add support for some INFO and maybe DEBUG level logging (like, log each time # a endpoint is hit, etc.) class RequestFilter(logging.Filter): """Adds Flask's requ...
49
1,325
sqlmap
extra/dbwire/presto.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ """ Minimal pure-python Presto/Trino client over its native HTTP/REST interface (stdlib only, no presto-python-client). A query is POSTed to /v1/statement; the server returns JSON...
193
8,272
ipython
tests/test_sentinel.py
.py
"""Tests for IPython.utils.sentinel.""" from IPython.utils.sentinel import Sentinel def test_sentinel_repr(): s = Sentinel("MY_VALUE", "mymodule") assert repr(s) == "mymodule.MY_VALUE" def test_sentinel_repr_with_dotted_module(): s = Sentinel("MISSING", "IPython.utils") assert repr(s) == "IPython.u...
42
1,108
biopython
Tests/test_SeqIO_write.py
.py
# Copyright 2007-2010 by Peter Cock. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Tests for SeqIO write module.""" import os import unittest import warnings from io import...
311
10,705
wandb
wandb/trigger.py
.py
"""Module to facilitate adding hooks to wandb actions. Usage: import trigger trigger.register('on_something', func) trigger.call('on_something', *args, **kwargs) trigger.unregister('on_something', func) """ from collections.abc import Callable from typing import Any _triggers = {} def reset(): ...
31
642
saleor
saleor/product/tests/fixtures/collection.py
.py
import datetime import pytest from django.utils import timezone from ....tests.utils import dummy_editorjs from ...models import Collection, CollectionChannelListing @pytest.fixture def collection(db): collection = Collection.objects.create( name="Collection", slug="collection", descript...
149
4,070
django-cms
cms/tests/test_extensions.py
.py
from copy import deepcopy from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.contrib.sites.models import Site from cms.api import create_page, create_page_content from cms.extensions import PageContentExtension, PageExtension, extension_pool from cms.extension...
496
22,640
sphinx
tests/test_extensions/test_ext_extlinks.py
.py
from __future__ import annotations from typing import TYPE_CHECKING import pytest if TYPE_CHECKING: from sphinx.testing.util import SphinxTestApp @pytest.mark.sphinx( 'html', testroot='ext-extlinks-hardcoded-urls', confoverrides={'extlinks_detect_hardcoded_links': False}, ) def test_extlinks_detect...
61
2,310
saleor
saleor/tests/e2e/orders/utils/order_update_shipping.py
.py
from saleor.graphql.tests.utils import get_graphql_content ORDER_UPDATE_SHIPPING_MUTATION = """ mutation OrderUpdateShipping($input: OrderUpdateShippingInput!, $id: ID!) { orderUpdateShipping(input: $input, order: $id) { errors { message field code } order { id subtotal { ...
97
1,651
mlflow
mlflow/genai/judges/tools/registry.py
.py
""" Tool registry for MLflow GenAI judges. This module provides a registry system for managing and invoking JudgeTool instances. """ import json import logging from typing import Any import mlflow from mlflow.entities import SpanType, Trace from mlflow.environment_variables import MLFLOW_GENAI_EVAL_ENABLE_SCORER_TRA...
148
4,753
mlflow
dev/clint/tests/test_resolve_paths.py
.py
from __future__ import annotations import subprocess from pathlib import Path from unittest.mock import patch import pytest from clint.utils import ALLOWED_EXTS, _git_ls_files, resolve_paths @pytest.fixture def git_repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: """Create and initialize a git rep...
280
9,184
astropy
astropy/cosmology/_src/tests/flrw/test_wpwazpcdm.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Testing :mod:`astropy.cosmology.wpwazpcdm`.""" import numpy as np import pytest import astropy.cosmology.units as cu import astropy.units as u from astropy.cosmology import FlatwpwaCDM, wpwaCDM from astropy.cosmology._src.parameter import Parameter f...
311
11,683
pymc
tests/logprob/test_cumsum.py
.py
# Copyright 2024 - present The PyMC Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
122
3,924
pyro
tests/distributions/test_tensor_type.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import pytest import scipy.stats as sp import torch import pyro.distributions as dist from tests.common import assert_equal @pytest.fixture() def test_data(): return torch.DoubleTensor([0.4]) @pytest.fixture() def alpha():...
78
2,032
ipython
tests/test_iplib.py
.py
"""Tests for the key interactiveshell module, where the main ipython class is defined.""" import stack_data import sys SV_VERSION = tuple([int(x) for x in stack_data.__version__.split(".")[0:2]]) def test_reset(): """reset must clear most namespaces.""" # Check that reset runs without error ip.reset() ...
244
6,477
ipython
IPython/testing/plugin/dtexample.py
.py
"""Simple example using doctests. This file just contains doctests both using plain python and IPython prompts. All tests should be loaded by nose. """ import os def pyfunc(): """Some pure python tests... >>> pyfunc() 'pyfunc' >>> import os >>> 2+3 5 >>> for i in range(3): ... ...
168
2,916
pyfilesystem2
fs/memoryfs.py
.py
"""Manage a volatile in-memory filesystem. """ from __future__ import absolute_import, unicode_literals import typing import contextlib import io import os import six import time from collections import OrderedDict from threading import RLock from . import errors from ._typing import overload from .base import FS fr...
662
22,022
saleor
saleor/giftcard/utils.py
.py
import datetime import logging from collections import defaultdict from collections.abc import Iterable from typing import TYPE_CHECKING, Optional from uuid import UUID from dateutil.relativedelta import relativedelta from django.core.exceptions import ValidationError from django.db import transaction from django.db.m...
403
14,461
python-prompt-toolkit
src/prompt_toolkit/layout/containers.py
.py
""" Container for the layout. (Containers can contain other containers or user interface controls.) """ from __future__ import annotations from abc import ABCMeta, abstractmethod from collections.abc import Callable, Sequence from enum import Enum from functools import partial from typing import TYPE_CHECKING, Union,...
2,768
100,195
saleor
saleor/webhook/tests/fixtures/utils.py
.py
from ....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType from ....webhook.models import WebhookEvent def prepare_async_and_sync_events(webhook): return [ WebhookEvent( webhook=webhook, event_type=WebhookEventSyncType.PAYMENT_AUTHORIZE ), WebhookEvent(webh...
27
711
saleor
saleor/checkout/search/loaders.py
.py
from itertools import chain from typing import TYPE_CHECKING, NamedTuple from uuid import UUID from ...graphql.account.dataloaders import AddressByIdLoader, UserByUserIdLoader from ...graphql.checkout.dataloaders.models import ( CheckoutLinesByCheckoutTokenLoader, TransactionItemsByCheckoutIDLoader, ) from ......
177
6,472
pyomo
examples/pyomo/tutorials/data.py
.py
# ____________________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and Engineering # Solutions of...
132
2,893
python-prompt-toolkit
src/prompt_toolkit/output/flush_stdout.py
.py
from __future__ import annotations import errno import os import sys from collections.abc import Iterator from contextlib import contextmanager from typing import IO, TextIO __all__ = ["flush_stdout"] def flush_stdout(stdout: TextIO, data: str) -> None: # If the IO object has an `encoding` and `buffer` attribut...
89
3,263
saleor
saleor/checkout/models.py
.py
"""Checkout-related ORM models.""" import datetime from decimal import Decimal from operator import attrgetter from typing import TYPE_CHECKING, Optional from uuid import uuid4 from django.conf import settings from django.contrib.postgres.indexes import BTreeIndex, GinIndex from django.contrib.postgres.search import ...
540
19,449
sphinx
tests/roots/test-ext-viewcode-find-package/main_package/subpackage/__init__.py
.py
from main_package.subpackage._subpackage2 import submodule __all__ = ['submodule']
4
84
ipython
tests/test_magics_pylab.py
.py
"""Tests for the %matplotlib and %pylab magics (IPython.core.magics.pylab).""" import pytest matplotlib = pytest.importorskip("matplotlib") matplotlib.use("Agg") from IPython.core.magics import pylab as pylab_magics_module @pytest.fixture def fake_enable_pylab(monkeypatch): """Replace shell.enable_pylab with a...
130
4,244
confluent-kafka-python
tests/oauthbearer/aws/test_aws_autowire.py
.py
# Copyright 2026 Confluent Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
262
8,868
jupytext
tests/data/notebooks/outputs/ipynb_to_marimo/Notebook with many hash signs.py
.py
import marimo __generated_with = "0.17.8" app = marimo.App() @app.cell(hide_code=True) def _(mo): mo.md(r""" ################################################################## This is a notebook that contains many hash signs. Hopefully its python representation is not recognized as a Sphinx Gallery s...
50
1,136
onnxruntime
onnxruntime/python/tools/transformers/models/stable_diffusion/demo_txt2img.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- # Modified from TensorRT demo diffusion, which has the following license...
104
3,312
django-cms
cms/test_utils/project/backwards_wizards/cms_wizards.py
.py
from cms.test_utils.project.backwards_wizards.wizards import wizard from cms.wizards.wizard_pool import wizard_pool # NOTE: We keep this line separate from the actual wizard definition # because if both are in the same file then importing the wizard causes # this line to run, which makes it impossible to test properly...
8
350
funcy
tests/test_debug.py
.py
import re from funcy.debug import * from funcy.flow import silent from funcy.seqs import lmap def test_tap(): assert capture(tap, 42) == '42\n' assert capture(tap, 42, label='Life and ...') == 'Life and ...: 42\n' def test_log_calls_keyword(): log = [] @log_calls(log.append) def f(x, y=2): ...
183
4,062
kafka
tests/kafkatest/utils/__init__.py
.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
17
895
beam
sdks/python/apache_beam/examples/inference/pytorch_sentiment.py
.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
333
12,230
python-prompt-toolkit
src/prompt_toolkit/input/posix_pipe.py
.py
from __future__ import annotations import sys assert sys.platform != "win32" import os from collections.abc import Iterator from contextlib import AbstractContextManager, contextmanager from typing import TextIO, cast from ..utils import DummyContext from .base import PipeInput from .vt100 import Vt100Input __all_...
120
3,209
mlflow
mlflow/gateway/providers/base.py
.py
from abc import ABC, abstractmethod from enum import Enum from typing import Any, AsyncIterable import numpy as np import mlflow from mlflow.entities import SpanType from mlflow.entities.gateway_endpoint import FallbackStrategy from mlflow.exceptions import MlflowException from mlflow.gateway.base_models import Confi...
896
35,606
jupytext
tests/data/notebooks/outputs/ipynb_to_marimo/jupyter.py
.py
import marimo __generated_with = "0.17.8" app = marimo.App() @app.cell(hide_code=True) def _(mo): mo.md(r""" # Jupyter notebook This notebook is a simple jupyter notebook. It only has markdown and code cells. And it does not contain consecutive markdown cells. We start with an addition: """) ret...
61
818
django-cms
cms/middleware/toolbar.py
.py
""" Edit Toolbar middleware """ from django import forms from django.core.exceptions import ValidationError from django.urls import resolve from django.urls.exceptions import Resolver404 from django.utils.functional import SimpleLazyObject from cms.toolbar.toolbar import CMSToolbar from cms.toolbar.utils import get_to...
112
3,602
python-prompt-toolkit
src/prompt_toolkit/key_binding/bindings/basic.py
.py
# pylint: disable=function-redefined from __future__ import annotations from prompt_toolkit.application.current import get_app from prompt_toolkit.filters import ( Condition, emacs_insert_mode, has_selection, in_paste_mode, is_multiline, vi_insert_mode, ) from prompt_toolkit.key_binding.key_pro...
258
7,229
pyomo
pyomo/core/tests/unit/kernel/test_tuple_container.py
.py
# ____________________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and Engineering # Solutions of...
821
31,629
black
tests/data/cases/docstring_newline.py
.py
""" 87 characters ............................................................................ """
4
99
astropy
astropy/table/row.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import collections from collections import OrderedDict from operator import index as operator_index import numpy as np class Row: """A class to represent one row of a Table object. A Row object is returned when a Table object is indexed with a...
225
7,122
saleor
saleor/tests/e2e/checkout/discounts/vouchers/test_checkout_use_voucher_for_cheapest_product.py
.py
import pytest from ....product.utils import ( create_product_variant, create_product_variant_channel_listing, ) from ....product.utils.preparing_product import prepare_product from ....shop.utils import prepare_default_shop from ....utils import assign_permissions from ....vouchers.utils import create_voucher,...
229
7,496
beam
sdks/python/apache_beam/transforms/managed.py
.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
232
8,505
beam
sdks/python/apache_beam/runners/dataflow/internal/apiclient_test.py
.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
1,921
79,915
slimit
src/slimit/yacctab.py
.py
# coding=utf-8 # yacctab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'programAND ANDEQUAL BAND BLOCK_COMMENT BNOT BOR BREAK BXOR CASE CATCH CLASS COLON COMMA CONDOP CONST CONTINUE DEBUGGER DEFAULT DELETE DIV DIVEQUAL DO ELSE ...
332
179,617
qutip
qutip/ipynbtools.py
.py
""" This module contains utility functions for using QuTiP with IPython notebooks. """ from qutip.ui.progressbar import HTMLProgressBar from .settings import _blas_info, available_cpu_count import IPython from IPython.display import HTML, display import matplotlib.pyplot as plt from matplotlib import animation from ba...
317
10,033
coremltools
coremltools/converters/mil/mil/ops/tests/iOS14/test_image_resizing.py
.py
# Copyright (c) 2020, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause import functools import itertools import numpy as np import pytest import coremltools as ct from co...
554
18,498
biopython
Tests/test_UniGene.py
.py
# This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Tests for UniGene module.""" import unittest from Bio import UniGene class TestUniGene(unittest.TestCase): def test_parse(self): # S...
1,214
74,974
probability
discussion/robust_inverse_graphics/nerf/rendering_test.py
.py
# Copyright 2024 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
184
6,191
astropy
astropy/coordinates/representation/base.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Base classes for representations and differentials.""" import abc import functools import operator import warnings from typing import ClassVar, Final import numpy as np import astropy.units as u from astropy.coordinates.angles import Angle from astro...
1,654
64,985
biopython
Bio/Graphics/DisplayRepresentation.py
.py
# Copyright 2001 by Brad Chapman. All rights reserved. # # This file is part of the Biopython distribution and governed by your # choice of the "Biopython License Agreement" or the "BSD 3-Clause License". # Please see the LICENSE file that should have been included as part of this # package. """Represent information f...
184
6,749
mlflow
tests/gateway/test_runner.py
.py
from pathlib import Path import pytest from tests.gateway.tools import Gateway, save_yaml BASE_ROUTE = "/api/2.0/endpoints/" @pytest.fixture def basic_config_dict(): return { "endpoints": [ { "name": "completions-gpt4", "endpoint_type": "llm/v1/completions", ...
231
7,059
gunicorn
examples/celery_alternative/app.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. """ Web Application - FastAPI app demonstrating Celery replacement. This shows how to call dirty arbiter tasks from your web application using the async API, which doesn't block the event loop. Key difference fro...
462
13,740
mkdocs
mkdocs/utils/babel_stub.py
.py
from __future__ import annotations from string import ascii_letters from typing import NamedTuple class UnknownLocaleError(Exception): pass class Locale(NamedTuple): language: str territory: str = '' def __str__(self): if self.territory: return f'{self.language}_{self.territory...
30
860
hatch
tests/helpers/templates/wheel/standard_default_shared_scripts.py
.py
from hatch.template import File from hatch.utils.fs import Path from hatchling.__about__ import __version__ from hatchling.metadata.spec import DEFAULT_METADATA_VERSION from ..new.feature_no_src_layout import get_files as get_template_files from .utils import update_record_file_contents def get_files(**kwargs): ...
88
2,280
pyomo
pyomo/contrib/preprocessing/tests/test_init_vars.py
.py
# ____________________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and Engineering # Solutions of...
84
2,899
beam
sdks/python/apache_beam/runners/interactive/augmented_pipeline.py
.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
128
5,117
scikit-bio
skbio/stats/composition/_ancom.py
.py
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE.txt, distributed with this software. # --------------------------------------------...
427
16,081
bazel
tools/aquery_differ/aquery_differ_test.py
.py
# pylint: disable=g-direct-third-party-import # Copyright 2018 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LI...
503
13,978
saleor
saleor/graphql/shipping/bulk_mutations/__init__.py
.py
from .shipping_price_bulk_delete import ShippingPriceBulkDelete from .shipping_zone_bulk_delete import ShippingZoneBulkDelete __all__ = ["ShippingPriceBulkDelete", "ShippingZoneBulkDelete"]
5
191
mlflow
tests/tracing/test_tracing_client.py
.py
import contextvars import json import uuid from unittest.mock import Mock, patch import pytest from opentelemetry import trace as trace_api from opentelemetry.sdk.trace import ReadableSpan as OTelReadableSpan import mlflow from mlflow.entities.experiment import Experiment from mlflow.entities.experiment_tag import Ex...
796
29,115
beam
sdks/python/apache_beam/examples/cookbook/bigtableio_it_test.py
.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
207
6,938
wandb
wandb/sdk/lib/capped_dict.py
.py
from __future__ import annotations import collections from typing import Any class CappedDict(collections.OrderedDict): default_max_size = 50 def __init__(self, max_size: int | None = None) -> None: self.max_size = max_size or self.default_max_size super().__init__() def __setitem__(sel...
29
843
onnx
onnx/backend/test/case/node/sub.py
.py
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import numpy as np import onnx from onnx.backend.test.case.base import Base from onnx.backend.test.case.node import expect class Sub(Base): @staticmethod def export() -> None: node = ...
74
2,604
onnx
onnx/reference/ops/op_gemm.py
.py
# Copyright (c) ONNX Project Contributors # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import numpy as np from onnx.reference.op_run import OpRun def _gemm00(a, b, c, alpha, beta): o = np.dot(a, b) * alpha if c is not None and beta != 0: o += c * beta return o def ...
78
1,945
sphinx
tests/test_ext_autosummary/test_ext_autosummary.py
.py
"""Test the autosummary extension.""" from __future__ import annotations import sys from contextlib import chdir from io import StringIO from typing import TYPE_CHECKING from unittest.mock import Mock, patch import pytest from docutils import nodes from sphinx import addnodes from sphinx.ext.autosummary import ( ...
1,001
31,401
httpie
httpie/cli/nested_json/errors.py
.py
from typing import Optional from .tokens import Token, HIGHLIGHTER class NestedJSONSyntaxError(ValueError): def __init__( self, source: str, token: Optional[Token], message: str, message_kind: str = 'Syntax', ) -> None: self.source = source self.token =...
28
745
coremltools
coremltools/test/pipeline/test_pipeline.py
.py
# Copyright (c) 2017, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause import itertools import tempfile import unittest import numpy as np import pytest from ..utils import ...
404
15,103
dirty-equals
dirty_equals/_datetime.py
.py
from __future__ import annotations as _annotations from datetime import date, datetime, timedelta, timezone, tzinfo from typing import Any from zoneinfo import ZoneInfo from ._numeric import IsNumeric from ._utils import Omit class IsDatetime(IsNumeric[datetime]): """ Check if the value is a datetime, and m...
307
11,208
scikit-bio
skbio/stats/evolve/tests/test_hommola.py
.py
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE.txt, distributed with this software. # --------------------------------------------...
180
7,846