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
saleor
saleor/graphql/account/mutations/account/account_set_default_address.py
.py
from typing import cast import graphene from django.core.exceptions import ValidationError from .....account import models, utils from .....account.error_codes import AccountErrorCode from .....checkout import AddressType from .....permission.auth_filters import AuthorizationFilters from .....webhook.event_types impo...
69
2,532
sphinx
tests/roots/test-intl/conf.py
.py
project = 'Sphinx intl <Tests>' source_suffix = { '.txt': 'restructuredtext', } keep_warnings = True templates_path = ['_templates'] html_additional_pages = {'contents': 'contents.html'} release = version = '2013.120' gettext_additional_targets = ['index'] exclude_patterns = ['_build']
11
291
saleor
saleor/graphql/discount/tests/mutations/test_sale_create.py
.py
import datetime from unittest.mock import patch import graphene from django.utils import timezone from freezegun import freeze_time from .....discount import DiscountValueType from .....discount.error_codes import DiscountErrorCode from .....discount.models import Promotion, PromotionRule from ....tests.utils import ...
344
11,420
structlog
tests/__init__.py
.py
# SPDX-License-Identifier: MIT OR Apache-2.0 # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the MIT License. See the LICENSE file in the root of this # repository for complete details.
5
226
cvxpy
cvxpy/reductions/dgp2dcp/canonicalizers/one_minus_pos_canon.py
.py
from cvxpy.atoms.elementwise.exp import exp from cvxpy.atoms.elementwise.log import log def one_minus_pos_canon(expr, args): return log(expr._ones - exp(args[0])), []
7
173
saleor
saleor/app/tests/fixtures/webhooks/shipping_app.py
.py
import pytest from .....app.models import App from .....webhook.event_types import WebhookEventAsyncType, WebhookEventSyncType from .....webhook.models import Webhook, WebhookEvent @pytest.fixture def shipping_app(db, permission_manage_shipping): app = App.objects.create(name="Shipping App", is_active=True) ...
110
3,199
sphinx
sphinx/search/ja.py
.py
"""Japanese search language: includes routine to split words.""" # Python Version of TinySegmenter # (https://chasen.org/~taku/software/TinySegmenter/) # TinySegmenter is super compact Japanese tokenizer. # # TinySegmenter was originally developed by Taku Kudo <taku(at)chasen.org>. # Python Version was developed by xn...
549
31,485
coremltools
coremltools/optimize/coreml/experimental/__init__.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 # TODO: coreml.experimental.linear_quantize_activations has been deprecated and related code will be ...
9
473
openvino
tests/layer_tests/tensorflow2_keras_tests/test_tf2_keras_conv_2d.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import pytest import tensorflow as tf from common.tf2_layer_test_class import CommonTF2LayerTest class TestKerasConv2D(CommonTF2LayerTest): def create_keras_conv2d_net(self, conv_params, input_names, input_shapes, input_type, ...
65
3,351
pyomo
pyomo/contrib/appsi/solvers/ipopt.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...
588
20,648
onnxruntime
onnxruntime/test/testdata/nnapi_internal_uint8_support.py
.py
import onnx from onnx import TensorProto, helper # This is to test the operators without "Qlinear" support but still support uint8 input # These operators need to be internal to a graph/partition # def GenerateModel(model_name): def GenerateModel(model_name): # noqa: N802 nodes = [ helper.make_node( ...
68
1,796
cvxpy
cvxpy/reductions/complex2real/canonicalizers/inequality_canon.py
.py
""" Copyright 2013 Steven Diamond 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, software...
42
1,460
readthedocs.org
readthedocs/integrations/utils.py
.py
"""Integration utility functions.""" def normalize_request_payload(request): """ Normalize the request body, hopefully to JSON. This will attempt to return a JSON body, backing down to a string body next. :param request: HTTP request object :type request: django.http.HttpRequest :returns: Th...
24
740
confluent-kafka-python
src/confluent_kafka/admin/_acl.py
.py
# Copyright 2022 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...
223
8,955
pyro
tests/ops/einsum/test_torch_log.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import itertools import pytest import torch from pyro.infer.util import torch_exp from pyro.ops.einsum import contract from tests.common import assert_equal @pytest.mark.parametrize("min_size", [1, 2]) @pytest.mark.parametrize(...
58
1,562
cvxpy
cvxpy/atoms/stats.py
.py
""" Copyright 2013 CVXPY 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 law or agreed to in writing, software d...
70
2,398
pyomo
pyomo/contrib/alternative_solutions/tests/test_lp_enum_solnpool.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...
47
1,745
saleor
saleor/graphql/tax/mutations/tax_country_configuration_delete.py
.py
from typing import Final import graphene from django_countries.fields import Country from ....permission.enums import CheckoutPermissions from ....tax import error_codes, models from ...account.enums import CountryCodeEnum from ...core import ResolveInfo from ...core.doc_category import DOC_CATEGORY_TAXES from ...cor...
56
1,942
ipython
IPython/core/magics/basic.py
.py
"""Implementation of basic magic functions.""" from __future__ import annotations from logging import error import io import os import platform from pprint import pformat import sys from warnings import warn from traitlets.utils.importstring import import_item from IPython.core import magic_arguments, page from IPyt...
772
28,157
jupytext
tests/external/pre_commit/test_pre_commit_5_reformat_markdown.py
.py
import pytest from git.exc import HookExecutionError from nbformat.v4.nbbase import new_code_cell, new_markdown_cell, new_notebook from pre_commit.main import main as pre_commit from jupytext import read, write @pytest.mark.requires_pandoc def test_pre_commit_hook_sync_reformat_code_and_markdown( tmpdir, cwd...
118
3,342
black
tests/data/cases/fmtskip5.py
.py
a, b, c = 3, 4, 5 if ( a == 3 and b != 9 # fmt: skip and c is not None ): print("I'm good!") else: print("I'm bad") # output a, b, c = 3, 4, 5 if ( a == 3 and b != 9 # fmt: skip and c is not None ): print("I'm good!") else: print("I'm bad")
23
301
cvxpy
cvxpy/reductions/solvers/conic_solvers/scipy_conif.py
.py
""" Copyright 2021 The CVXPY 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 law or agreed to in writing, so...
307
12,640
conda
conda/env/env.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """Environment object describing the conda environment.yaml file.""" from __future__ import annotations import os import re from itertools import chain from typing import TYPE_CHECKING from ..base.context import context from ..cli import comm...
478
14,892
black
tests/data/cases/remove_lone_list_item_parens.py
.py
items = [(123)] items = [(True)] items = [(((((True)))))] items = [(((((True,)))))] items = [((((()))))] items = [(x for x in [1])] items = {(123)} items = {(True)} items = {(((((True)))))} # Requires `hug_parens_with_braces_and_square_brackets` unstable style to remove parentheses # around multiline values items = [ ...
158
3,417
pyomo
examples/pyomo/callbacks/scalability/run.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...
37
1,321
wagtail
wagtail/actions/create_page.py
.py
from wagtail.actions.create import CreateAction class CreatePageAction(CreateAction): """ Save a new page to the database under ``parent``, creating a revision and logging the same ``wagtail.create`` + ``wagtail.edit`` pair of log entries the admin's own create view produces. :param instance: the...
58
2,172
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
saleor
saleor/tests/e2e/warehouse/utils/create_warehouse.py
.py
import uuid from ... import DEFAULT_WAREHOUSE_ADDRESS from ...utils import get_graphql_content WAREHOUSE_CREATE_MUTATION = """ mutation createWarehouse($input: WarehouseCreateInput!) { createWarehouse(input: $input) { errors { message field code } warehouse { id name ...
63
1,255
mlflow
mlflow/entities/model_registry/registered_model_alias.py
.py
from mlflow.entities.model_registry._model_registry_entity import _ModelRegistryEntity from mlflow.protos.model_registry_pb2 import RegisteredModelAlias as ProtoRegisteredModelAlias class RegisteredModelAlias(_ModelRegistryEntity): """Alias object associated with a registered model.""" def __init__(self, ali...
36
1,053
mamba
micromamba/test-server/reposerver.py
.py
import argparse import base64 import glob import os import re import shutil import sys from http.server import HTTPServer, SimpleHTTPRequestHandler from pathlib import Path try: import conda_content_trust.authentication as cct_authentication import conda_content_trust.common as cct_common import conda_cont...
456
16,451
saleor
saleor/page/tests/test_utils.py
.py
from unittest.mock import patch from ..models import Page from ..utils import mark_pages_search_vector_as_dirty_in_batches @patch("saleor.page.utils.MARK_SEARCH_VECTOR_DIRTY_BATCH_SIZE", 1) def test_mark_pages_search_vector_as_dirty_in_batches(page_list): # given page_ids = [page.id for page in page_list] ...
22
591
metrics
src/torchmetrics/functional/text/chrf.py
.py
# Copyright The Lightning team. # # 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 writin...
639
25,904
probability
tensorflow_probability/python/experimental/joint_distribution_layers/layers_test.py
.py
# Copyright 2021 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...
260
9,980
kafka
tests/kafkatest/tests/core/replication_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 use ...
182
8,724
conda
conda/cli/main_config.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """CLI implementation for `conda config`. Allows for programmatically interacting with conda's configuration files (e.g., `~/.condarc`). """ from __future__ import annotations import os import sys from argparse import SUPPRESS from collection...
859
27,663
loguru
tests/exceptions/source/others/sys_tracebacklimit_unset.py
.py
import sys from loguru import logger logger.remove() logger.add(sys.stderr, format="", diagnose=False, backtrace=False, colorize=False) logger.add(sys.stderr, format="", diagnose=True, backtrace=False, colorize=False) logger.add(sys.stderr, format="", diagnose=False, backtrace=True, colorize=False) logger.add(sys.std...
61
714
django-cms
cms/tests/test_static_analysis.py
.py
import os from unittest import TestCase from ruff.__main__ import find_ruff_bin class AboveStaticAnalysisCodeTest(TestCase): """ Name is pretty lame, but ensure it's executed before every other test """ def test_ruff(self): ruff = find_ruff_bin() self.assertEqual(os.spawnv(os.P_WAIT, ...
14
365
mlflow
mlflow/server/auth/db/cli.py
.py
import click import sqlalchemy from mlflow.server.auth.db import utils @click.group(name="db") def commands(): pass @commands.command() @click.option("--url", required=True) @click.option("--revision", default="head") def upgrade(url: str, revision: str) -> None: engine = sqlalchemy.create_engine(url) ...
19
373
coremltools
coremltools/optimize/torch/palettization/palettization_config.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 from collections import OrderedDict as _OrderedDict from typing import Any as _Any from typing import...
545
26,345
ipython
IPython/lib/deepreload.py
.py
""" Provides a reload() function that acts recursively. Python's normal :func:`python:reload` function only reloads the module that it's passed. The :func:`reload` function in this module also reloads everything imported from that module, which is useful when you're changing files deep inside a package. To use this a...
310
9,436
pyomo
pyomo/core/tests/examples/test_tutorials.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...
99
2,524
django-cms
cms/utils/placeholder.py
.py
import operator import os import warnings from collections import OrderedDict, defaultdict from functools import cache from typing import TYPE_CHECKING from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import connection, models from django.template import ( Con...
443
17,269
pyomo
scripts/performance/compare_components.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...
658
18,290
python-prompt-toolkit
src/prompt_toolkit/completion/nested.py
.py
""" Nestedcompleter for completion of hierarchical data structures. """ from __future__ import annotations from collections.abc import Iterable, Mapping from typing import Any from prompt_toolkit.completion import CompleteEvent, Completer, Completion from prompt_toolkit.completion.word_completer import WordCompleter...
111
3,855
onnxruntime
onnxruntime/python/tools/transformers/models/llama/quant_kv_dataloader.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import a...
109
4,851
mlflow
tests/server/auth/test_permissions.py
.py
import pytest from mlflow.exceptions import MlflowException from mlflow.server.auth.permissions import ( ALL_PERMISSIONS, EDIT, MANAGE, NO_PERMISSIONS, PERMISSION_PRIORITY, READ, RESOURCE_GRANTABLE_PERMISSIONS, USE, VALID_RESOURCE_TYPES, WORKSPACE_GRANTABLE_PERMISSIONS, _val...
224
8,608
mlflow
mlflow/models/evaluation/deprecated.py
.py
import functools import warnings from mlflow.models.evaluation import evaluate as model_evaluate @functools.wraps(model_evaluate) def evaluate(*args, **kwargs): warnings.warn( "The `mlflow.evaluate` API has been deprecated as of MLflow 3.0.0. " "Please use these new alternatives:\n\n" " -...
20
767
wagtail
wagtail/actions/registry.py
.py
from django.core.exceptions import ImproperlyConfigured from wagtail import hooks from wagtail.actions.base import BaseAction class ActionRegistry: """ A registry mapping model classes to the actions available for them. Registration is opt-in: a model only gets the actions that are explicitly regist...
71
2,571
readthedocs.org
readthedocs/notifications/tests/test_querysets.py
.py
import django_dynamic_fixture as fixture import pytest from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from readthedocs.core.notifications import MESSAGE_EMAIL_VALIDATION_PENDING from readthedocs.notifications.constants import CANCELLED, DISMISSED, READ, UNREAD fr...
154
4,722
astropy
astropy/io/fits/tests/test_image_dask.py
.py
# Tests related to writing dask arrays to FITS files in an efficient way import numpy as np import pytest from astropy.io import fits from astropy.io.fits import ImageHDU, PrimaryHDU da = pytest.importorskip("dask.array") @pytest.fixture def dask_array_in_mem(): return da.random.uniform(-1000, 1000, (1322, 755...
172
5,708
textual
src/textual/demo/data.py
.py
import json COUNTRIES = [ "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize"...
459
15,435
confluent-kafka-python
src/confluent_kafka/schema_registry/rules/encryption/localkms/local_client.py
.py
# Copyright 2024 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...
50
1,888
pyomo
doc/OnlineDocs/src/scripting/iterative1.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...
73
2,125
gunicorn
gunicorn/http2/errors.py
.py
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. """ HTTP/2 specific exceptions. These exceptions map to HTTP/2 error codes defined in RFC 7540. """ class HTTP2ErrorCode: """HTTP/2 Error Codes (RFC 7540 Section 7).""" NO_ERROR = ...
170
3,825
wandb
wandb/cli/beta_sandbox.py
.py
from __future__ import annotations import json from datetime import datetime import click from cwsandbox.cli.shell import _validate_cmd as _cwsandbox_validate_cmd from wandb.sandbox import CWSandboxError, Sandbox, SandboxStatus from wandb.sandbox._auth import override_sandbox_entity _STATUS_CHOICES = [s.value for s...
302
8,031
pyomo
examples/pyomobook/abstract-ch/param3.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...
35
1,142
mlflow
tests/otel/test_otel_autolog.py
.py
import asyncio import pytest langfuse = pytest.importorskip("langfuse", reason="langfuse is not installed") from langfuse import observe from langfuse._client.resource_manager import LangfuseResourceManager from opentelemetry import trace as otel_trace_api from opentelemetry.sdk.trace import TracerProvider as SdkTrac...
275
7,327
onnxruntime
onnxruntime/python/training/__init__.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- # This is a placeholder file. It is deployed with inference only wheel.
7
320
jupytext
tests/external/pre_commit/test_pre_commit_1_sync_with_no_config.py
.py
from copy import deepcopy import pytest from git.exc import HookExecutionError from nbformat.v4.nbbase import new_markdown_cell from pre_commit.main import main as pre_commit import jupytext from jupytext import TextFileContentsManager from jupytext.compare import compare_notebooks def test_pre_commit_hook_sync_wit...
88
2,564
onnxruntime
onnxruntime/test/python/onnxruntime_test_python_sparse_matmul.py
.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # pylint: disable=C0115,W0212,C0103,C0114 # -*- coding: UTF-8 -*- import unittest import numpy as np from helper import get_name import onnxruntime as onnxrt from onnxruntime.capi.onnxruntime_pybind11_state import OrtValue...
435
10,641
pyro
pyro/ops/einsum/torch_log.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import torch from pyro.ops.einsum.util import Tensordot from pyro.ops.special import safe_log def transpose(a, axes): return a.permute(axes) def einsum(equation, *operands): """ Log-sum-exp implementation of einsum...
61
2,010
mlflow
mlflow/entities/model_registry/model_version_deployment_job_run_state.py
.py
from mlflow.protos.databricks_uc_registry_messages_pb2 import ( ModelVersionDeploymentJobState as ProtoModelVersionDeploymentJobState, ) class ModelVersionDeploymentJobRunState: """Enum for model version deployment state of an :py:class:`mlflow.entities.model_registry.ModelVersion`. """ NO_VALID_...
45
2,043
openvino
src/bindings/python/tests/test_graph/test_data_movement.py
.py
# -*- coding: utf-8 -*- # Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest import openvino.opset8 as ov from openvino import Type, Shape def test_reverse_sequence(): input_data = ov.parameter((2, 3, 4, 2), name="input_data", dtype=np.int32) seq...
66
2,457
mlflow
dev/clint/tests/rules/test_log_model_artifact_path.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.log_model_artifact_path import LogModelArtifactPath def test_log_model_artifact_path(index: SymbolIndex) -> None: code = """ import mlflow # Bad - usi...
35
1,214
sphinx
tests/test_util/test_util_lines.py
.py
from __future__ import annotations import pytest from sphinx.util._lines import parse_line_num_spec def test_parse_line_num_spec() -> None: assert parse_line_num_spec('1,2,3', 10) == [0, 1, 2] assert parse_line_num_spec('4, 5, 6', 10) == [3, 4, 5] assert parse_line_num_spec('-4', 10) == [0, 1, 2, 3] ...
25
1,062
coremltools
coremltools/converters/mil/mil/types/type_double.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 math import numpy as np from coremltools import _logger as logger from .annotate import ann...
164
5,147
loguru
tests/test_contextualize.py
.py
import asyncio import sys import threading from unittest.mock import MagicMock import pytest from loguru import logger from loguru._contextvars import load_contextvar_class def test_contextualize(writer): logger.add(writer, format="{message} {extra[foo]} {extra[baz]}") with logger.contextualize(foo="bar", ...
222
5,667
sphinx
tests/test_transforms/test_transforms_post_transforms_code.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='trim_doctest_flags') def test_trim_doctest_flags_html(app: SphinxTestApp) -> None: app.build() result = (app.outdir / ...
57
1,648
structlog
src/structlog/threadlocal.py
.py
# SPDX-License-Identifier: MIT OR Apache-2.0 # This file is dual licensed under the terms of the Apache License, Version # 2.0, and the MIT License. See the LICENSE file in the root of this # repository for complete details. """ **Deprecated** primitives to keep context global but thread (and greenlet) local. See `t...
356
9,236
textual
tests/input/test_select_on_focus.py
.py
"""The standard path of selecting text on focus is well covered by snapshot tests.""" from textual import events from textual.app import App, ComposeResult from textual.widgets import Input from textual.widgets.input import Selection class InputApp(App[None]): """An app with an input widget.""" def compose(...
31
1,141
wandb
wandb/sdk/launch/inputs/files.py
.py
import json import os from typing import Any import yaml from ..errors import LaunchError FILE_OVERRIDE_ENV_VAR = "WANDB_LAUNCH_FILE_OVERRIDES" class FileOverrides: """Singleton that read file overrides json from environment variables.""" _instance = None def __new__(cls): if cls._instance is...
148
4,647
saleor
saleor/graphql/order/tests/mutations/test_fulfillment_return_products_by_app.py
.py
import graphene from .....order.models import FulfillmentStatus from .....page.models import PageType from ....tests.utils import get_graphql_content from .test_fulfillment_return_products import ORDER_FULFILL_RETURN_MUTATION def test_fulfillment_return_products_app_omits_reason_reference_when_configured( app_ap...
53
1,652
kombu
examples/simple_task_queue/tasks.py
.py
from __future__ import annotations def hello_task(who='world'): print(f'Hello {who}')
6
92
deap
doc/code/benchmarks/ackley.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 ackley_arg0(sol): return benchmarks.ackley(sol)[0] fig = plt.figure() # ax = Axes3D(fig, azim = -...
29
683
cvxpy
cvxpy/atoms/geo_mean.py
.py
""" Copyright 2013 Steven Diamond 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, software...
441
14,614
sqlmap
plugins/dbms/firebird/syntax.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ from lib.core.common import isDBMSVersionAtLeast from lib.core.convert import getOrds from plugins.generic.syntax import Syntax as GenericSyntax class Syntax(GenericSyntax): ...
36
1,150
mamba
docs/source/tools/mermaid.py
.py
""" sphinx-mermaid ~~~~~~~~~~~~~~~ https://github.com/mgaitan/sphinxcontrib-mermaid Modified for the purpose of CoSApp by the CoSApp team https://gitlab.com/cosapp/cosapp Allow mermaid diagrams to be included in Sphinx-generated documents inline. :copyright: Copyright 2016 by Martín Gaitán and others, see AUTHORS. :...
396
12,683
pdm
tests/cli/test_show.py
.py
"""Additional tests for the show command""" import pytest from pdm.cli.commands.show import filter_stable def test_filter_stable_with_stable_version(mocker): """Test filter_stable returns True for stable versions""" # Mock package with stable version package = mocker.Mock() package.version = "1.0.0"...
72
2,302
pyomo
examples/pyomobook/abstract-ch/set2.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...
21
736
mlflow
tests/genai/simulators/test_distillation.py
.py
from unittest import mock import pydantic import pytest from mlflow.entities.session import Session from mlflow.genai.simulators.distillation import ( _distill_goal_and_persona, _GoalAndPersona, generate_test_cases, ) @pytest.fixture def mock_session(): trace = mock.MagicMock() return Session([t...
214
7,042
cvxpy
cvxpy/reductions/dqcp2dcp/inverse.py
.py
""" Copyright, the CVXPY 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 or agreed to in writing, software ...
100
3,578
beam
sdks/python/apache_beam/examples/snippets/transforms/elementwise/values.py
.py
# coding=utf-8 # # 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");...
59
1,636
mlflow
mlflow/utils/jsonpath_utils.py
.py
""" JSONPath utilities for navigating and manipulating nested JSON structures. This module provides a simplified JSONPath-like implementation without adding external dependencies to MLflow. Instead of using a full JSONPath library, we implement a lightweight subset focused on trace data navigation using dot notation w...
333
12,173
saleor
saleor/graphql/menu/tests/mutations/test_assign_navigation.py
.py
import graphene from ....menu.enums import NavigationType from ....tests.utils import assert_no_permission, get_graphql_content def test_assign_menu( staff_api_client, menu, permission_manage_menus, permission_manage_settings, site_settings, ): query = """ mutation AssignMenu($menu: ID, $...
59
2,066
beam
sdks/python/apache_beam/examples/complete/distribopt.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...
380
13,933
pyfilesystem2
tests/test_time.py
.py
from __future__ import print_function, unicode_literals import unittest from datetime import datetime from fs.time import datetime_to_epoch, epoch_to_datetime try: from datetime import timezone except ImportError: from fs._tzcompat import timezone # type: ignore class TestEpoch(unittest.TestCase): def...
24
630
pyro
tests/contrib/test_hessian.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import torch import pyro.distributions as dist from pyro.ops.hessian import hessian from tests.common import assert_equal def test_hessian_mvn(): tmp = torch.randn(3, 10) cov = torch.matmul(tmp, tmp.t()) mvn = dist.M...
32
853
readthedocs.org
readthedocs/profiles/tests/test_views.py
.py
from unittest import mock import requests_mock from allauth.socialaccount.models import SocialAccount, SocialToken from allauth.socialaccount.providers.github.provider import GitHubProvider from django.conf import settings from django.contrib.auth.models import User from django.test import TestCase, override_settings ...
978
40,157
mlflow
mlflow/dspy/wrapper.py
.py
import json from dataclasses import asdict, is_dataclass from typing import TYPE_CHECKING, Any from packaging.version import Version if TYPE_CHECKING: import dspy from mlflow.exceptions import INVALID_PARAMETER_VALUE, MlflowException from mlflow.protos.databricks_pb2 import ( INVALID_PARAMETER_VALUE, ) from ...
237
9,004
openvino
src/bindings/python/tests/test_graph/test_grouped_matmul.py
.py
# -*- coding: utf-8 -*- # Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from openvino import Type, PartialShape from openvino.opset15 import parameter import openvino.opset17 as ov import pytest @pytest.mark.parametrize(("a_shape", "b_shape", "out_shape"), [ ((2, 4, 8), (2, 16, ...
41
1,594
wandb
wandb/apis/_generated/delete_invite.py
.py
# Generated by ariadne-codegen # Source: tools/graphql_codegen/api/ from __future__ import annotations from wandb._pydantic import GQLResult class DeleteInvite(GQLResult): result: DeleteInviteResult | None class DeleteInviteResult(GQLResult): success: bool | None DeleteInvite.model_rebuild()
18
309
coveragepy
tests/modules/plugins/a_plugin.py
.py
"""A plugin for tests to reference.""" from __future__ import annotations from typing import Any from coverage import CoveragePlugin from coverage.plugin_support import Plugins class Plugin(CoveragePlugin): pass def coverage_init( reg: Plugins, options: Any, # pylint: disable=unused-argument ) -> No...
20
358
mlflow
mlflow/data/meta_dataset.py
.py
import hashlib import json from typing import Any from mlflow.data.dataset import Dataset from mlflow.data.dataset_source import DatasetSource from mlflow.types import Schema class MetaDataset(Dataset): """Dataset that only contains metadata. This class is used to represent a dataset that only contains meta...
103
3,708
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
wagtail
wagtail/images/tests/test_api_v3/test_listing.py
.py
from django.urls import reverse from wagtail.models import CollectionViewRestriction from .base import TestV3ImagesBase class TestV3ImageListing(TestV3ImagesBase): def get_response(self, **params): return self.client.get(reverse("wagtailapi_v3:list_images"), params) def test_anonymous_can_list(self...
79
2,953
qutip
qutip/tests/test_mkl.py
.py
import pytest import numpy as np import scipy.linalg import scipy.sparse import qutip if qutip.settings.has_mkl: from qutip._mkl.spsolve import mkl_splu, mkl_spsolve pytestmark = [ pytest.mark.skipif(not qutip.settings.has_mkl, reason='MKL extensions not found.'), ] class Test_spsolve...
117
3,624
metrics
_samples/bert_score-own_model.py
.py
# Copyright The Lightning team. # # 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 writin...
132
4,661
metrics
src/torchmetrics/clustering/davies_bouldin_score.py
.py
# Copyright The Lightning team. # # 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 writin...
139
5,478
mlflow
dev/clint/src/clint/rules/nested_mock_patch.py
.py
import ast from clint.resolver import Resolver from clint.rules.base import Rule class NestedMockPatch(Rule): def _message(self) -> str: return ( "Do not nest `unittest.mock.patch` context managers. " "Use multiple context managers in a single `with` statement instead: " ...
55
1,963
pyomo
pyomo/core/tests/unit/test_indexed_slice.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...
847
29,156