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
loguru
tests/exceptions/source/modern/exception_group_catch.py
.py
# fmt: off import sys from loguru import logger logger.remove() logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True) x = ValueError def a(): try: raise ExceptionGroup("group", [ValueError(1)]) except* x as e: raise ValueError(2) def b(): try: raise Exceptio...
26
410
saleor
saleor/discount/utils/voucher.py
.py
from collections.abc import Iterable, Sequence from dataclasses import asdict, dataclass from decimal import Decimal from typing import TYPE_CHECKING, Optional, Union, cast from uuid import UUID from django.db.models import Case, Exists, F, IntegerField, OuterRef, Value, When from django.utils import timezone from pri...
720
25,689
pyomo
pyomo/contrib/satsolver/tests/test_satsolver.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...
262
8,997
luigi
luigi/contrib/spark.py
.py
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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...
365
12,273
mlflow
mlflow/llama_index/autolog.py
.py
from mlflow.llama_index.constant import FLAVOR_NAME from mlflow.telemetry.events import AutologgingEvent from mlflow.telemetry.track import _record_event from mlflow.utils.autologging_utils import autologging_integration def autolog( log_traces: bool = True, disable: bool = False, silent: bool = False, ):...
59
2,196
astropy
astropy/timeseries/downsample.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import warnings from itertools import pairwise import numpy as np from astropy import units as u from astropy.time import Time, TimeDelta from astropy.timeseries.binned import BinnedTimeSeries from astropy.timeseries.sampled import TimeSeries from astro...
314
12,872
saleor
saleor/graphql/app/dataloaders/app.py
.py
import hashlib from collections import defaultdict from dataclasses import dataclass from django.contrib.auth.hashers import check_password from django.core.cache import cache from ....app.models import App, AppToken from ...core.dataloaders import DataLoader # Cache timeout for the app token loader CACHE_TIMEOUT = ...
127
4,379
hatch
scripts/generate_coverage_summary.py
.py
import json from collections import defaultdict from lxml import etree # nosec B410 from utils import ROOT PACKAGES = { "backend/src/hatchling/": "hatchling", "src/hatch/": "hatch", "tests/": "tests", } def main(): coverage_report = ROOT / "coverage.xml" root = etree.fromstring(coverage_report....
54
1,807
mlflow
dev/clint/src/clint/rules/unknown_mlflow_function.py
.py
from clint.rules.base import Rule class UnknownMlflowFunction(Rule): def __init__(self, function_name: str) -> None: self.function_name = function_name def _message(self) -> str: return ( f"Unknown MLflow function: `{self.function_name}`. " "This function may not exist...
13
356
saleor
saleor/plugins/openid_connect/exceptions.py
.py
class AuthenticationError(Exception): """Raises when error occurred during authentication."""
3
98
onnxruntime
onnxruntime/python/tools/transformers/models/gpt2/benchmark_gpt2.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- # This s...
414
15,517
bazel
third_party/py/concurrent/futures/process.py
.py
# Copyright 2009 Brian Quinlan. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Implements ProcessPoolExecutor. The follow diagram and text describe the data-flow through the system: |======================= In-process =====================|== Out-of-process ==| +----------+ +----------...
346
14,324
saleor
saleor/webhook/payload_helpers.py
.py
from typing import TYPE_CHECKING, Any, Optional import graphene from django.utils import timezone from graphene.utils.str_converters import to_camel_case from .. import __version__ from ..account.models import User if TYPE_CHECKING: from ..plugins.base_plugin import RequestorOrLazyObject def generate_requestor...
39
1,092
conda
conda/common/path/__init__.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """Common path utilities.""" from __future__ import annotations import os import re from functools import cache from logging import getLogger from os.path import ( abspath, expanduser, expandvars, normcase, split, ) from ty...
242
6,203
probability
tensorflow_probability/python/distributions/probit_bernoulli_test.py
.py
# Copyright 2018 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...
369
14,402
probability
tensorflow_probability/python/bijectors/__init__.py
.py
# Copyright 2018 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...
185
8,822
saleor
saleor/graphql/app/enums.py
.py
from typing import Final import graphene from ...app import error_codes from ...app.types import AppType from ..core.doc_category import DOC_CATEGORY_APPS from ..core.enums import to_enum def description(enum): if enum is None: return "Enum determining type of your App." if enum == AppTypeEnum.LOCAL...
89
2,623
pyomo
pyomo/devel/initialization/utils.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...
57
1,811
coremltools
coremltools/test/utils.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 os.path import numpy as np import pandas as pd import requests def load_boston(): DATA_UR...
33
1,025
metrics
tests/unittests/retrieval/test_r_precision.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...
180
6,743
saleor
saleor/giftcard/search.py
.py
from django.conf import settings from django.db.models import Q, QuerySet, Value, prefetch_related_objects from ..account.models import User from ..core.db.connection import allow_writer from ..core.postgres import FlatConcatSearchVector, NoValidationSearchVector from .models import GiftCard GIFTCARD_FIELDS_TO_PREFET...
70
2,755
mlflow
mlflow/tracking/_model_registry/fluent.py
.py
import json import logging import os import threading import uuid import warnings from typing import Any from pydantic import BaseModel import mlflow from mlflow.entities.logged_model import LoggedModel from mlflow.entities.model_registry import ModelVersion, Prompt, PromptVersion, RegisteredModel from mlflow.entitie...
947
37,660
onnxruntime
orttraining/orttraining/python/training/ort_triton/__init__.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- import threading from functools import wraps from onnxruntime.capi impo...
43
1,530
pyomo
pyomo/contrib/pynumero/examples/external_grey_box/external_with_objective.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...
161
4,855
pyro
pyro/infer/autoguide/effect.py
.py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 from operator import attrgetter from typing import Callable, Optional, Tuple, Union import torch from torch.distributions import biject_to, constraints import pyro.distributions as dist from pyro.distributions.distribution import Dis...
456
19,656
readthedocs.org
readthedocs/oauth/services/__init__.py
.py
"""Conditional classes for OAuth services.""" from readthedocs.core.utils.extend import SettingsOverrideObject from readthedocs.oauth.services import bitbucket from readthedocs.oauth.services import github from readthedocs.oauth.services import gitlab from readthedocs.oauth.services.githubapp import GitHubAppService ...
35
941
coremltools
coremltools/optimize/torch/pruning/_base_pruner.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 copy as _copy import logging as _logging from typing import Optional as _Optional from typing ...
163
7,160
mlflow
examples/pyspark_ml_autologging/one_vs_rest.py
.py
from pyspark.ml.classification import LogisticRegression, OneVsRest from pyspark.ml.feature import VectorAssembler from pyspark.sql import SparkSession from sklearn.datasets import load_iris import mlflow with SparkSession.builder.getOrCreate() as spark: df = load_iris(as_frame=True).frame.rename(columns={"target...
23
765
ipython
tests/test_historyapp.py
.py
# coding: utf-8 """Tests for IPython.core.historyapp""" import sqlite3 import sys from contextlib import closing import pytest from traitlets.config.configurable import SingletonConfigurable from IPython.core.historyapp import HistoryApp, HistoryClear, HistoryTrim def _clear_singleton(inst): """Unregister a S...
178
6,063
mlflow
examples/diffusers/demo_diffusers_adapter.py
.py
""" Demo: MLflow Diffusers Adapter Flavor (LoRA) This script demonstrates the full workflow of logging and loading a diffusion model LoRA adapter using the native mlflow.diffusers flavor. No GPU or real model weights required — uses a fake adapter for validation. """ import tempfile from pathlib import Path import ...
114
4,203
returns
tests/test_result/test_result_map.py
.py
from returns.result import Failure, Success def test_map_success(): """Ensures that Success is mappable.""" assert Success(5).map(str) == Success('5') def test_alt_failure(): """Ensures that Failure is mappable.""" assert Failure(5).map(str) == Failure(5) assert Failure(5).alt(str) == Failure('5...
18
438
openvino
tools/ovc/openvino/tools/ovc/moc_frontend/paddle_frontend_utils.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import sys import tempfile class paddle_frontend_converter: def __init__(self, model, inputs=None, outputs=None): self.model = model self.inputs = inputs self.outputs = outputs self.tmp = N...
84
3,392
pyro
tutorial/source/conf.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import sphinx_rtd_theme from pyro import __version__ # -*- coding: utf-8 -*- # # Pyro Tutorials documentation build configuration file, created by # sphinx-quickstart on Tue Oct 31 11:33:17 2017. # # This file is execfile()d with...
189
5,615
onnx
tests/python/model_container_refeval_test.py
.py
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import os import tempfile import numpy as np import numpy.testing as npt import pytest import onnx import onnx.helper import onnx.model_container import onnx.numpy_helper import onnx.reference def _...
137
4,893
qutip
qutip/tests/test_openmp.py
.py
import numpy as np from numpy.testing import assert_equal import pytest from qutip import * from qutip.settings import settings as qset # if qset.has_openmp: # from qutip.core.cy.openmp.benchmark import _spmvpy, _spmvpy_openmp # @unittest.skipIf(qset.has_openmp == False, 'OPENMP not available.') @pytest.mark.skipi...
112
3,882
wandb
wandb/apis/_generated/input_types.py
.py
# Generated by ariadne-codegen # Source: core/api/graphql/schemas/schema-latest.graphql from __future__ import annotations from pydantic import Field from wandb._pydantic import GQLId, GQLInput class ArtifactTypeInput(GQLInput): description: str | None = None name: str = Field(max_length=128, pattern="^[-\...
67
2,447
onnxruntime
onnxruntime/test/testdata/transform/fusion/bias_gelu_gen.py
.py
import onnx from onnx import TensorProto, helper graph = helper.make_graph( [ # nodes # Add node before Gelu helper.make_node("Add", ["A", "B"], ["add0_out"], "add0"), # Gelu subgraph helper.make_node("Div", ["add0_out", "div_const"], ["div_out"], "div"), helper.make_node("...
69
2,457
readthedocs.org
readthedocs/rtd_tests/tests/test_oauth.py
.py
import copy import json from unittest import mock from allauth.socialaccount.providers.bitbucket_oauth2.provider import BitbucketOAuth2Provider from allauth.socialaccount.providers.gitlab.provider import GitLabProvider import requests_mock from allauth.socialaccount.models import SocialAccount, SocialToken from allaut...
3,562
142,578
mlflow
mlflow/genai/__init__.py
.py
from mlflow.genai import ( datasets, judges, scorers, ) from mlflow.genai.agent_tester import test_agent from mlflow.genai.datasets import ( EvaluationDatasetVersion, create_dataset, delete_dataset, delete_dataset_tag, get_dataset, search_datasets, set_dataset_tags, ) from mlflow...
158
4,085
sqlmap
plugins/dbms/postgresql/connector.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ try: import psycopg2 import psycopg2.extensions psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extension...
77
2,485
kafka
tests/kafkatest/services/trogdor/task_spec.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 ...
55
1,795
conda
conda/common/logic.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """ The basic idea to nest logical expressions is instead of trying to denest things via distribution, we add new variables. So if we have some logical expression expr, we replace it with x and add expr <-> x to the clauses, where x is a new var...
313
11,114
mkdocs-material
material/plugins/projects/builder/log.py
.py
# Copyright (c) 2016-2025 Martin Donath <martin.donath@squidfunk.com> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, c...
101
4,033
textual
src/textual/_callback.py
.py
from __future__ import annotations import asyncio from functools import partial from inspect import isawaitable, signature from typing import TYPE_CHECKING, Any, Callable from textual import active_app if TYPE_CHECKING: from textual.app import App # Maximum seconds before warning about a slow callback INVOKE_TI...
97
2,753
mkdocs
mkdocs/tests/config/config_options_legacy_tests.py
.py
from __future__ import annotations import contextlib import copy import io import os import re import sys import textwrap import unittest from typing import Any from unittest import mock import mkdocs from mkdocs.config import base from mkdocs.config import config_options as c from mkdocs.tests.base import tempdir fr...
1,647
54,973
onnx
onnx/reference/ops/op_reduce_l1.py
.py
# Copyright (c) ONNX Project Contributors # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import numpy as np from onnx.reference.ops._op import OpRunReduceNumpy class ReduceL1_1(OpRunReduceNumpy): def _run(self, data, axes=None, keepdims=None): axes = tuple(axes) if axes is not...
35
1,140
biopython
Doc/examples/Proux_et_al_2002_Figure_6.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. # """GenomeDiagram script to mimic Proux et al 2002 Figure 6. You can use the Entrez module to download the 3 required GenBank files This is an exten...
234
7,276
pyro
pyro/ops/einsum/torch_map.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import operator from functools import reduce from pyro.ops import packed from pyro.ops.einsum.adjoint import ( Backward, einsum_backward_sample, transpose, unflatten, ) from pyro.ops.einsum.util import Tensordot ...
62
1,952
black
tests/data/cases/preview_long_dict_values.py
.py
# flags: --preview x = { "xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": ( "xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxx{xx}xxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx" ) } x = { "xx_xxxxx_xxxxxxxxxx_xxxxxxxxx_xx": ( "xx:xxxxxxxxxxxxxxxxx_xxxxx_xxxxxxx_xxxxxxxxxxx{xx}xxx_xxxxx_xxxxxxxxx_xxxxxxxxxxxx_xxxx" ...
304
8,191
readthedocs.org
readthedocs/oauth/clients.py
.py
from datetime import datetime import structlog from django.conf import settings from django.utils import timezone from github import Auth from github import GithubIntegration from requests_oauthlib import OAuth2Session log = structlog.get_logger(__name__) def _get_token_updater(token): """ Update token giv...
88
2,558
readthedocs.org
readthedocs/core/utils/db.py
.py
from collections import Counter from itertools import batched def delete_in_batches( queryset, batch_size=50, start: int | None = None, end: int | None = None ) -> tuple[int, dict]: """ Delete a queryset in batches to avoid long transactions or big queries. When deleting a large number of records at ...
108
4,266
saleor
saleor/graphql/tests/test_context.py
.py
from unittest import mock import graphene from django.utils import timezone from ..context import clear_context, get_context_value from ..core.dataloaders import DataLoader from .utils import get_graphql_content QUERY_ORDER_BY_ID = """ query orderById($id: ID!) { order(id: $id) { lines { totalPrice { ...
87
2,141
readthedocs.org
readthedocs/search/tests/test_search_tasks.py
.py
"""Tests for search tasks.""" from unittest import mock import pytest from django.urls import reverse from django.utils import timezone from readthedocs.search.models import SearchQuery from readthedocs.search import tasks @pytest.mark.django_db @pytest.mark.search @pytest.mark.usefixtures("all_projects") class Te...
113
4,327
astropy
astropy/units/tests/test_quantity_array_methods.py
.py
# The purpose of these tests are to ensure that calling quantities using # array methods returns quantities with the right units, or raises exceptions. import numpy as np import pytest from numpy.testing import assert_array_equal from astropy import units as u from astropy.utils.compat.optional_deps import HAS_ARRAY_...
609
21,367
mlflow
mlflow/store/db_migrations/versions/cfd24bdc0731_update_run_status_constraint_with_killed.py
.py
"""Update run status constraint with killed Create Date: 2019-10-11 15:55:10.853449 """ import alembic from alembic import op from packaging.version import Version from sqlalchemy import CheckConstraint, Enum from mlflow.entities import RunStatus, ViewType from mlflow.entities.lifecycle_stage import LifecycleStage ...
77
2,783
metrics
tests/unittests/segmentation/test_mean_iou.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...
200
7,708
onnxruntime
orttraining/orttraining/python/training/ort_triton/_sorted_graph.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- import copy import itertools import onnx import sympy from onnx import ...
224
10,254
omegaconf
omegaconf/errors.py
.py
from typing import Any, Optional, Type class OmegaConfBaseException(Exception): # would ideally be typed Optional[Node] parent_node: Any child_node: Any key: Any full_key: Optional[str] value: Any msg: Optional[str] cause: Optional[Exception] object_type: Optional[Type[Any]] ob...
141
3,617
mlflow
tests/entities/test_dataset.py
.py
from mlflow.entities import Dataset def _check(dataset, name, digest, source_type, source, schema=None, profile=None): assert isinstance(dataset, Dataset) assert dataset.name == name assert dataset.digest == digest assert dataset.source_type == source_type assert dataset.source == source asser...
66
1,915
astropy
astropy/wcs/wcsapi/tests/test_fitswcs.py
.py
# Note that we test the main astropy.wcs.WCS class directly rather than testing # the mix-in class on its own (since it's not functional without being used as # a mix-in) import re import warnings import numpy as np import pytest from numpy.testing import assert_allclose, assert_array_equal, assert_equal from packagi...
1,704
53,918
openvino
tests/layer_tests/tensorflow_tests/test_tf_Xlog1py.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest import tensorflow as tf from common.tf_layer_test_class import CommonTFLayerTest from common.utils.tf_utils import mix_two_arrays_with_several_values rng = np.random.default_rng(235345) class TestXlog...
49
2,076
pymc
pymc/backends/base.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...
648
20,855
beam
sdks/python/apache_beam/runners/dataflow/dataflow_exercise_streaming_metrics_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...
107
3,403
wandb
wandb/sdk/lib/printer_asyncio.py
.py
import asyncio from collections.abc import Callable from typing import TypeVar from wandb.sdk import wandb_setup from wandb.sdk.lib import asyncio_compat, printer _T = TypeVar("_T") def run_async_with_spinner( spinner_printer: printer.Printer, text: str, func: Callable[[], _T], ) -> _T: """Run a slo...
46
1,357
textual
src/textual/css/_help_text.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import Iterable, Sequence from typing_extensions import Literal from textual.color import ColorParseError from textual.css._error_tools import friendly_list from textual.css._help_renderables import Bullet, Example, HelpText from textua...
859
30,032
astropy
astropy/coordinates/builtin_frames/itrs.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from astropy.coordinates.attributes import EarthLocationAttribute, TimeAttribute from astropy.coordinates.baseframe import BaseCoordinateFrame, base_doc from astropy.coordinates.earth import EarthLocation from astropy.coordinates.representation import ( ...
93
4,268
probability
discussion/robust_inverse_graphics/util/test_util.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...
115
3,221
pyfilesystem2
fs/_version.py
.py
"""Version, used in module and setup.py. """ __version__ = "2.4.16"
4
68
hatch
tests/cli/config/test_restore.py
.py
def test_standard(hatch, config_file): config_file.model.project = "foo" config_file.save() result = hatch("config", "restore") assert result.exit_code == 0, result.output assert result.output == "Settings were successfully restored.\n" config_file.load() assert config_file.model.project ...
26
660
kombu
t/integration/test_redis.py
.py
from __future__ import annotations import os import socket from time import sleep import pytest import redis import kombu from kombu.transport.redis import Transport from .common import (BaseExchangeTypes, BaseMessage, BasePriority, BasicFunctionality) def get_connection( hostname, po...
418
15,236
wagtail
wagtail/admin/localization.py
.py
import functools import types import zoneinfo from django.conf import settings from django.utils.dates import MONTHS, WEEKDAYS, WEEKDAYS_ABBR from django.utils.timezone import override as override_tz from django.utils.translation import gettext as _ from django.utils.translation import override # Wagtail languages wi...
157
5,772
pyro
pyro/poutine/block_messenger.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 from functools import partial from typing import TYPE_CHECKING, Callable, List, Optional from pyro.poutine.messenger import Messenger if TYPE_CHECKING: from pyro.poutine.runtime import Message def _block_fn( expose: Lis...
170
5,615
onnxruntime
onnxruntime/test/python/onnxruntime_test_python_keras.py
.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -*- coding: UTF-8 -*- # Taken from https://github.com/onnx/onnxmltools/blob/master/tests/end2end/test_custom_op.py. import unittest import numpy as np import onnxmltools from keras import Sequential from keras import backe...
84
2,564
mlflow
mlflow/store/db_migrations/env.py
.py
from alembic import context from sqlalchemy import engine_from_config, pool # this is the Alembic Config object, which provides # access to the values within the .ini file in use. config = context.config # add your model's MetaData object here # for 'autogenerate' support # from myapp import mymodel # target_metadata...
79
2,550
probability
tensorflow_probability/python/internal/backend/numpy/linalg_impl.py
.py
# Copyright 2019 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...
683
22,369
readthedocs.org
readthedocs/settings/base.py
.py
# pylint: disable=missing-docstring import os import re import socket import subprocess import structlog from pathlib import Path from celery.schedules import crontab from corsheaders.defaults import default_headers from django.conf.global_settings import PASSWORD_HASHERS from readthedocs.builds import constants_doc...
1,251
46,297
deap
examples/es/fctmin.py
.py
# This file is part of DEAP. # # DEAP is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # DEAP is distributed ...
85
2,928
wandb
tests/system_tests/test_launch/test_job_status_tracker.py
.py
import base64 from unittest import mock from unittest.mock import MagicMock import pytest import wandb from wandb.sdk.launch.agent.job_status_tracker import JobAndRunStatusTracker @pytest.mark.asyncio async def test_check_stop_run_not_exist(user): job_tracker = JobAndRunStatusTracker( "run_queue_item_id"...
51
1,695
onnx
onnx/backend/test/case/node/quantizelinear.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 import TensorProto from onnx.backend.test.case.base import Base from onnx.backend.test.case.node import expect from onnx.helper import make_tensor class Quant...
500
13,752
openvino
tests/layer_tests/pytorch_tests/test_split.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import pytest import torch from pytorch_layer_test_class import PytorchLayerTest, skip_if_export class TestSplit(PytorchLayerTest): def _prepare_input(self): return (self.random.randn(1, 10, 224, 224),) def create_mod...
151
5,343
openvino
tests/samples_tests/smoke_tests/common/common_utils.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """ Copyright (C) 2018-2026 Intel Corporation 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.a...
81
3,437
pyomo
pyomo/contrib/mindtpy/tests/test_mindtpy_global_lp_nlp.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...
130
4,977
probability
tensorflow_probability/python/experimental/mcmc/particle_filter.py
.py
# Copyright 2020 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...
1,028
47,076
black
tests/data/cases/pep_572_slices.py
.py
x[(a:=0):] x[:(a:=0)] # output x[(a := 0) :] x[: (a := 0)]
7
60
beam
sdks/python/apache_beam/ml/anomaly/specifiable.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...
444
14,655
saleor
saleor/graphql/shipping/filters.py
.py
import django_filters from ...shipping.models import ShippingZone from ..channel.types import Channel from ..core.doc_category import DOC_CATEGORY_SHIPPING from ..core.filters import FilterInputObjectType, GlobalIDMultipleChoiceFilter from ..utils import resolve_global_ids_to_primary_keys def filter_channels(qs, _, ...
34
1,014
openvino
src/frontends/paddle/tests/test_models/gen_scripts/generate_set_value.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import sys # # set_value paddle model generator # import numpy as np import paddle from save_model import saveModel maxint32 = np.iinfo(np.int32).max def _set_attr_ints(op, name, values, framework_pb2): for attr in op.a...
340
11,010
pyro
tests/ops/test_linalg.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import pytest import torch from pyro.ops.linalg import rinverse from tests.common import assert_equal @pytest.mark.parametrize( "A", [ torch.tensor([[17.0]]), torch.tensor([[1.0, 2.0], [2.0, -3.0]]), ...
38
1,204
hydra
plugins/hydra_ray_launcher/tests/test_ray_launcher.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import sys from pathlib import Path from types import SimpleNamespace from typing import Any, cast from hydra.core.plugins import Plugins from hydra.plugins.launcher import Launcher from hydra.test_utils.launcher_common_tests import ( Integrati...
190
5,659
saleor
saleor/graphql/product/mutations/product/product_media_delete.py
.py
import graphene from .....permission.enums import ProductPermissions from .....product import models from ....core import ResolveInfo from ....core.context import ChannelContext from ....core.doc_category import DOC_CATEGORY_PRODUCTS from ....core.mutations import BaseMutation from ....core.types import ProductError f...
42
1,621
textual
tests/workers/test_worker.py
.py
import asyncio import pytest from textual.app import App from textual.worker import ( DeadlockError, NoActiveWorker, Worker, WorkerCancelled, WorkerError, WorkerFailed, WorkerState, get_current_worker, ) async def test_initialize(): """Test initial values.""" def foo() -> st...
238
6,227
pyomo
pyomo/contrib/solver/tests/solvers/test_knitro_direct.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...
578
23,251
jupyterlab
jupyterlab/extensions/manager.py
.py
"""Base classes for the extension manager.""" # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. import json import re from dataclasses import dataclass, field, fields, replace from pathlib import Path import tornado from jupyterlab_server.translation_utils import tr...
712
27,539
onnxruntime
tools/python/util/convert_onnx_models_to_ort.py
.py
#!/usr/bin/env python3 # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from __future__ import annotations import argparse import contextlib import enum import os import pathlib import tempfile import onnxruntime as ort from .file_utils import files_from_file_or_dir, pat...
381
16,559
coremltools
coremltools/models/ml_program/experimental/torch/__init__.py
.py
# Copyright (c) 2025, 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 coremltools._deps import _HAS_TORCH if _HAS_TORCH: from . import debugging_utils, perf_utils
10
319
coremltools
coremltools/converters/mil/frontend/tensorflow/ssa_passes/backfill_make_list_elem_type.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 from coremltools.converters.mil.mil import Builder as mb from coremltools.converters.mil.mil import t...
122
4,794
saleor
saleor/graphql/menu/tests/bulk_mutations/test_menu_item_bulk_delete.py
.py
from unittest import mock import graphene from .....menu.models import MenuItem from ....tests.utils import get_graphql_content BULK_DELETE_MENU_ITEMS_MUTATION = """ mutation menuItemBulkDelete($ids: [ID!]!) { menuItemBulkDelete(ids: $ids) { count } } """ def test_delete_men...
98
2,586
python-prompt-toolkit
examples/prompts/get-multiline-input.py
.py
#!/usr/bin/env python from prompt_toolkit import prompt from prompt_toolkit.formatted_text import HTML def prompt_continuation(width, line_number, wrap_count): """ The continuation: display line numbers and '->' before soft wraps. Notice that we can return any kind of formatted text from here. The p...
30
1,005
ipython
tests/test_run.py
.py
# encoding: utf-8 """Tests for code execution (%run and related), which is particularly tricky. Because of how %run manages namespaces, and the fact that we are trying here to verify subtle object deletion and reference counting issues, the %run tests will be kept in this separate file. This makes it easier to aggreg...
624
18,316
mlflow
mlflow/store/fs2db/__init__.py
.py
# ruff: noqa: T201 import warnings from functools import partial from pathlib import Path from mlflow.exceptions import MlflowException def _log(progress: bool, msg: str) -> None: if progress: print(msg) def _resolve_mlruns(source: Path) -> Path: mlruns = source / "mlruns" if mlruns.is_dir(): ...
166
6,220