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
biopython
Bio/KEGG/Enzyme/__init__.py
.py
# Copyright 2001 by Tarjei Mikkelsen. All rights reserved. # Copyright 2007 by Michiel de Hoon. 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. """Code to work with the KEGG En...
340
11,185
beam
sdks/python/apache_beam/utils/python_callable_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...
97
2,766
python-prompt-toolkit
src/prompt_toolkit/input/win32_pipe.py
.py
from __future__ import annotations import sys assert sys.platform == "win32" from collections.abc import Callable, Iterator from contextlib import AbstractContextManager, contextmanager from ctypes import windll from ctypes.wintypes import HANDLE from prompt_toolkit.eventloop.win32 import create_win32_event from ....
159
4,763
astropy
astropy/io/ascii/tests/test_c_reader.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import functools import io import os import re import sys from contextlib import nullcontext from io import BytesIO from textwrap import dedent import numpy as np import pytest from numpy import ma from numpy.testing import assert_allclose from astropy....
1,749
59,983
wandb
tests/system_tests/test_api/test_service_api.py
.py
from types import SimpleNamespace from wandb.apis.public.service_api import ServiceApi from wandb.proto import wandb_internal_pb2 as pb from wandb.sdk import wandb_setup from wandb.sdk.lib.service.service_connection import WandbApiFailedError from tests.fixtures.wandb_backend_spy import WandbBackendSpy def stub_ser...
146
4,187
luigi
test/contrib/docker_runner_test.py
.py
# -*- coding: utf-8 -*- # # Copyright 2017 Open Targets # # 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...
166
4,707
sphinx
tests/roots/test-ext-autosummary-imported_members/autosummary_dummy_package/autosummary_dummy_module.py
.py
class Bar: """Bar class""" pass def foo(): """Foo function""" pass
10
86
toolz
toolz/sandbox/core.py
.py
from toolz.itertoolz import getter, cons, pluck from itertools import tee, starmap # See #166: https://github.com/pytoolz/toolz/issues/166 # See #173: https://github.com/pytoolz/toolz/pull/173 class EqualityHashKey: """ Create a hash key that uses equality comparisons between items. This may be used to creat...
134
4,327
beam
sdks/python/apache_beam/runners/dask/dask_runner.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...
254
9,278
coremltools
coremltools/converters/mil/mil/ops/defs/iOS17/__init__.py
.py
# Copyright (c) 2022, 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._deployment_compatibility import AvailableTarget as target _IOS17_TA...
48
1,325
pyomo
pyomo/dae/tests/test_flatten.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...
2,125
79,019
coremltools
coremltools/converters/mil/frontend/tensorflow/__init__.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 logging # suppress TensorFlow stdout prints import os from coremltools._deps import _HAS_TF ...
24
762
conda
conda/cli/main_update.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """CLI implementation for `conda update`. Updates the specified packages in an existing environment. """ from __future__ import annotations import sys from typing import TYPE_CHECKING from ..notices import notices if TYPE_CHECKING: from...
125
3,903
flit
flit/tomlify.py
.py
"""Convert a flit.ini file to pyproject.toml """ import argparse from collections import OrderedDict import configparser import os from pathlib import Path import tomli_w from .config import metadata_list_fields TEMPLATE = """\ [build-system] requires = ["flit_core >=2,<4"] build-backend = "flit_core.buildapi" [too...
84
2,281
sqlmap
plugins/dbms/access/filesystem.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.exception import SqlmapUnsupportedFeatureException from plugins.generic.filesystem import Filesystem as GenericFilesystem class Filesystem(GenericFilesystem): d...
19
690
wandb
tests/system_tests/test_functional/lightning/test_lightning.py
.py
import pathlib def test_strategy_ddp_spawn(wandb_backend_spy, execute_script): script_path = pathlib.Path(__file__).parent / "strategy_ddp_spawn.py" execute_script(script_path) with wandb_backend_spy.freeze() as snapshot: run_ids = snapshot.run_ids() assert len(run_ids) == 1 run_i...
41
1,530
sphinx
tests/test_builders/test_build_html_5_output.py
.py
"""Test the HTML builder and check output against XPath.""" from __future__ import annotations import re from typing import TYPE_CHECKING import pytest from docutils import nodes from tests.test_builders.xpath_util import check_xpath if TYPE_CHECKING: from collections.abc import Callable, Iterable from pat...
568
21,427
probability
tensorflow_probability/python/distributions/weibull.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...
291
10,735
scikit-bio
skbio/metadata/tests/test_io.py
.py
import collections import os.path import tempfile import unittest from packaging.version import Version import numpy as np import pandas as pd from skbio.util import get_data_path from skbio.metadata._metadata import (SampleMetadata, CategoricalMetadataColumn, NumericMetadataColum...
1,614
57,044
onnxruntime
onnxruntime/test/testdata/ep_partitioning_tests.py
.py
import onnx from onnx import TensorProto, helper # Create graph with Add and Sub nodes that can be used to test partitioning when one of the operators # can run using the test EP and the other cannot. # As the operators take 2 inputs and produce one output we can easily create edges to test different scenarios def cr...
109
4,507
onnxruntime
onnxruntime/test/python/quantization/test_minimum_real_range_option.py
.py
#!/usr/bin/env python # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # ---------------------------------------------------------------...
107
4,325
wandb
tests/system_tests/test_core/test_public_api.py
.py
"""Tests for the `wandb.apis.PublicApi` module.""" from __future__ import annotations import json from typing import Any from unittest import mock import pytest import wandb import wandb.apis.public import wandb.util from wandb import Api from wandb.apis._generated import ProjectFragment, UserFragment from wandb.api...
1,489
45,004
beam
sdks/python/apache_beam/yaml/json_utils.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...
372
13,403
onnxruntime
onnxruntime/test/python/transformers/bert_padding.py
.py
# From https://github.com/Dao-AILab/flash-attention/blob/2286d7cea7ca8264165c16b2442b6436c43140de/flash_attn/bert_padding.py import torch import torch.nn.functional as F from einops import rearrange, repeat class IndexFirstAxis(torch.autograd.Function): @staticmethod def forward(ctx, input, indices): ...
132
5,786
jupytext
src/jupytext/cell_reader.py
.py
"""Read notebook cells from their text representation""" import re from collections import defaultdict from copy import copy from itertools import count from nbformat.v4.nbbase import new_code_cell, new_markdown_cell, new_raw_cell from .doxygen import doxygen_to_markdown from .languages import _SCRIPT_EXTENSIONS # ...
956
38,995
readthedocs.org
readthedocs/api/v2/tasks.py
.py
from datetime import timedelta import structlog from django.utils import timezone from readthedocs.api.v2.models import BuildAPIKey from readthedocs.worker import app log = structlog.get_logger(__name__) @app.task(queue="web") def delete_old_revoked_build_api_keys(days=15): """ Delete revoked and expired ...
31
921
wandb
tests/system_tests/test_functional/test_util/util_import_lazy.py
.py
import wandb.util as util util.get_module("PIL.Image", lazy=True) # ruff: noqa import PIL.Image assert hasattr(PIL.Image, "Image")
9
134
conda
conda/_private/shards/shards.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """ Models for sharded repodata, and to make monolithic repodata look like sharded repodata. """ from __future__ import annotations import abc import concurrent.futures import json # noqa import logging from collections import defaultdict fro...
874
31,483
sqlmap
extra/esperanto/__main__.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ from . import __version__ from .atlas import _REPL from .engine import Esperanto, hostExtract from .records import ( OracleUndecided, ExtractResult, QueryBudgetExceeded) _SIT...
756
37,253
onnxruntime
onnxruntime/python/tools/transformers/models/llama/benchmark_e2e.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 ...
609
24,869
beam
sdks/python/apache_beam/examples/wordcount_xlang_sql.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...
124
4,039
pyomo
pyomo/contrib/solver/solvers/gurobi/gurobi_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...
159
5,370
sphinx
sphinx/domains/c/__init__.py
.py
"""The C language domain.""" from __future__ import annotations from types import NoneType from typing import TYPE_CHECKING from docutils import nodes from docutils.parsers.rst import directives from sphinx import addnodes from sphinx.directives import ObjectDescription from sphinx.domains import Domain, ObjType fr...
999
34,475
hydra
tools/release/test_release.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from contextlib import nullcontext import pytest from tools.release import release from tools.release.release import ( DevReleasePackageInfo, LocalPackageInfo, Package, PackageInfo, fail_if_any_target_version_published, fil...
249
7,393
luigi
examples/wordcount.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...
80
2,905
sphinx
sphinx/roles.py
.py
"""Handlers for additional ReST roles.""" from __future__ import annotations import re from typing import TYPE_CHECKING import docutils.parsers.rst.directives import docutils.parsers.rst.states from docutils import nodes, utils from sphinx import addnodes from sphinx.locale import _, __ from sphinx.util import ws_r...
650
22,497
rq
tests/test_cron_job.py
.py
from datetime import datetime, timedelta, timezone from unittest.mock import patch from rq import Queue, utils from rq.cron import CronJob, CronScheduler from rq.defaults import DEFAULT_CRON_JOB_HISTORY_TTL from rq.utils import NOT_JSON_SERIALIZABLE from rq.webhook import Webhook from tests import RQTestCase from test...
471
20,536
saleor
saleor/graphql/tax/mutations/tax_class_update.py
.py
from typing import Final import graphene from django.core.exceptions import ValidationError 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...
151
5,521
textual
docs/examples/guide/reactivity/dynamic_watch.py
.py
from textual.app import App, ComposeResult from textual.reactive import reactive from textual.widget import Widget from textual.widgets import Button, Label, ProgressBar class Counter(Widget): DEFAULT_CSS = "Counter { height: auto; }" counter = reactive(0) # (1)! def compose(self) -> ComposeResult: ...
36
972
coveragepy
tests/test_data.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 """Tests for coverage.data, and coverage.sqldata.""" from __future__ import annotations import gc import glob import os import os.path import re import sqlite3...
1,167
43,228
loguru
tests/exceptions/source/ownership/_init.py
.py
import os import sys import sysconfig usersite = os.path.abspath(os.path.join(os.path.dirname(__file__), "usersite")) sys.path.append(usersite) sysconfig._INSTALL_SCHEMES["posix_user"]["purelib"] = usersite
8
208
qutip
qutip/tests/core/data/test_operators.py
.py
import pytest import numpy import qutip from qutip.core import data as _data from qutip import settings @pytest.mark.parametrize('type_left', _data.to.dtypes) @pytest.mark.parametrize('type_right', _data.to.dtypes) @pytest.mark.parametrize(['operator', 'dispatch'], [ pytest.param(lambda left, right: left + right,...
81
2,640
openvino
src/frontends/onnx/tests/tests_python/test_ops_convpool.py
.py
# -*- coding: utf-8 -*- # Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import onnx import pytest from onnx.helper import make_graph, make_model, make_node, make_tensor_value_info from onnx.onnx_cpp2py_export.checker import ValidationError from tests.runtime import...
400
15,422
saleor
saleor/permission/apps.py
.py
from django.apps import AppConfig from django.db.models.signals import post_migrate from .management import create_permissions class AccountAppConfig(AppConfig): name = "saleor.permission" def ready(self): post_migrate.connect( create_permissions, dispatch_uid="django.contrib...
15
368
pyomo
examples/pyomobook/abstract-ch/param2a.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...
24
832
confluent-kafka-python
src/confluent_kafka/admin/_scram.py
.py
# Copyright 2023 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...
126
3,588
pyro
pyro/ops/indexing.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import torch def _is_batched(arg): return isinstance(arg, torch.Tensor) and arg.dim() def _flatten(args, out): if isinstance(args, tuple): for arg in args: _flatten(arg, out) else: # Comb...
218
7,458
onnx
onnx/reference/ops/op_reduce_log_sum_exp.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 def compute_log_sum_exp(data, axes, keepdims): data_max = data.copy() ind = np.isinf(data_max) data_max[ind] = -np.in...
44
1,283
textual
docs/examples/styles/offset.py
.py
from textual.app import App from textual.widgets import Label class OffsetApp(App): CSS_PATH = "offset.tcss" def compose(self): yield Label("Paul (offset 8 2)", classes="paul") yield Label("Duncan (offset 4 10)", classes="duncan") yield Label("Chani (offset 0 -3)", classes="chani") ...
17
383
wandb
wandb/sdk/lib/wbauth/__init__.py
.py
__all__ = ( "Auth", "AuthApiKey", "AuthIdentityTokenFile", "HostUrl", "session_credentials", "authenticate_session", "unauthenticate_session", "use_explicit_auth", "set_auth_settings", "check_api_key", "prompt_and_save_api_key", "read_netrc_auth", "write_netrc_auth", ...
30
760
astropy
astropy/wcs/wcsapi/__init__.py
.py
from .high_level_api import * from .high_level_wcs_wrapper import * from .low_level_api import * from .utils import * from .wrappers import *
6
142
clearml
clearml/backend_api/services/v2_13/organization.py
.py
""" organization service This service provides organization level operations """ from typing import List, Optional, Any import six from clearml.backend_api.session import Request, Response, schema_property class GetTagsRequest(Request): """ Get all the user and system tags used for the company tasks and mode...
149
5,225
confluent-kafka-python
tests/integration/schema_registry/_sync/test_json_serializers.py
.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2020 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 requi...
471
14,505
lemur
lemur/tests/test_logs.py
.py
import pytest from lemur.tests.vectors import ( VALID_ADMIN_API_TOKEN, VALID_ADMIN_HEADER_TOKEN, VALID_USER_HEADER_TOKEN, ) from lemur.logs.views import * # noqa def test_private_key_audit(client, certificate): from lemur.certificates.views import CertificatePrivateKey, api assert len(certifica...
33
836
black
tests/data/cases/long_strings_flag_disabled.py
.py
x = "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even take up three or more lines... like four or five... but probably just three." x += "This is a really long string that can't possibly be expected to fit all together on one line. In fact it may even ta...
297
11,608
saleor
saleor/tests/e2e/sales/utils/sale_create.py
.py
from ...utils import get_graphql_content SALE_CREATE_MUTATION = """ mutation createSale($input: SaleInput!) { saleCreate(input: $input) { errors { field code message } sale { id name type startDate endDate } } } """ def create_sale( staff_api_cl...
45
845
pyomo
pyomo/contrib/sensitivity_toolbox/examples/feedbackController.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...
152
3,866
returns
tests/test_contrib/test_hypothesis/test_laws/test_custom_strategy_for_callable.py
.py
""" Test that we can register a custom strategy for callables. We use the strategy to generates `Maybe`s and `Result`s for `Kind1[_F_Applicative, _SecondType]`. Without the custom strategy, we would simply get instances of `_Wrapper`, even though it is not an `Applicative`, because `_Wrapper` is a subtype of `KindN` ...
162
4,727
saleor
saleor/checkout/tests/test_checkout_cleaner.py
.py
import pytest from ...core.exceptions import GiftCardNotApplicable from ..checkout_cleaner import _validate_gift_cards def test_validate_gift_cards_rejects_mismatched_assignment( checkout_with_gift_card, customer_user, staff_user ): # given checkout = checkout_with_gift_card checkout.user = staff_use...
38
1,188
hydra
examples/plugins/example_sweeper_plugin/setup.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # type: ignore from setuptools import find_namespace_packages, setup with open("README.md") as fh: LONG_DESC = fh.read() setup( name="hydra-example-sweeper", version="1.0.0", author="Omry Yadan", author_email...
40
1,711
coremltools
coremltools/optimize/coreml/experimental/_post_training_quantization.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 rem...
266
10,778
mlflow
dev/create_release_tag.py
.py
""" How to test this script ----------------------- # Ensure origin points to your fork git remote -v | grep origin # Pretend we're releasing MLflow 9.0.0 git checkout -b branch-9.0 # First, test the dry run mode python dev/create_release_tag.py --new-version 9.0.0 --dry-run git tag -d v9.0.0 # Open https://github.c...
59
1,806
eve
eve/methods/get.py
.py
# -*- coding: utf-8 -*- """ eve.methods.get ~~~~~~~~~~~~~~~ This module implements the API 'GET' methods, supported by both the resources and single item endpoints. :copyright: (c) 2017 by Nicola Iarocci. :license: BSD, see LICENSE for more details. """ from __future__ import division import...
704
24,994
clearml
examples/frameworks/fire/fire_multi_cmd.py
.py
# ClearML - Example of Python Fire integration, processing multiple commands, when fire is initialized with no component # from clearml import Task import fire def hello(count, name="clearml", prefix="prefix_", suffix="_suffix", **kwargs): for _ in range(count): print("Hello %s%s%s!" % (prefix, name, suf...
23
600
cvxpy
cvxpy/reductions/dnlp2smooth/canonicalizers/pnorm_canon.py
.py
""" Copyright 2025 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, softwa...
41
1,404
onnxruntime
onnxruntime/test/testdata/transform/fusion/div_mul.py
.py
import onnx from onnx import OperatorSetIdProto, TensorProto, helper opsets = [] onnxdomain = OperatorSetIdProto() onnxdomain.version = 12 onnxdomain.domain = "" # The empty string ("") or absence of this field implies the operator set that is defined as part of the ONNX specification. opsets.append(onnxdomain) msdo...
71
2,667
hydra
tests/test_apps/app_with_cfg_groups/my_app_with_runtime_choices_print.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import Any from omegaconf import DictConfig import hydra @hydra.main(config_path="conf", config_name="config_with_runtime_option") def my_app(cfg: DictConfig) -> Any: print(cfg.optimizer_option) if __name__ == "__main__": m...
16
328
coremltools
deps/pybind11/tests/test_copy_move.py
.py
from __future__ import annotations import pytest from pybind11_tests import copy_move_policies as m def test_lacking_copy_ctor(): with pytest.raises(RuntimeError) as excinfo: m.lacking_copy_ctor.get_one() assert "is non-copyable!" in str(excinfo.value) def test_lacking_move_ctor(): with pytest...
141
5,090
readthedocs.org
readthedocs/organizations/tests/test_views.py
.py
import csv from django.core.files.uploadedfile import SimpleUploadedFile import io import itertools from unittest import mock from django.contrib.auth.models import User from django.core.cache import cache from django.test import TestCase from django.test.utils import override_settings from django.urls import reverse ...
623
23,699
saleor
saleor/graphql/giftcard/bulk_mutations/gift_card_bulk_activate.py
.py
import graphene from django.core.exceptions import ValidationError from ....core.tracing import traced_atomic_transaction from ....giftcard import events, models from ....giftcard.error_codes import GiftCardErrorCode from ....giftcard.utils import is_gift_card_expired from ....permission.enums import GiftcardPermissio...
63
2,430
saleor
saleor/discount/tests/test_utils/test_mark_promotion_rules_as_dirty.py
.py
import datetime from decimal import Decimal from unittest.mock import patch import graphene from ... import RewardValueType from ...models import Promotion, PromotionRule from ...utils.promotion import mark_catalogue_promotion_rules_as_dirty @patch("saleor.discount.utils.promotion.PromotionRule.objects.filter") def...
94
2,761
saleor
saleor/graphql/warehouse/tests/queries/test_stock.py
.py
import datetime import graphene from django.utils import timezone from .....permission.enums import ProductPermissions from .....warehouse.models import Reservation from .....warehouse.tests.utils import get_quantity_allocated_for_stock from ....tests.utils import ( assert_no_permission, get_graphql_content, ...
177
5,505
onnxruntime
onnxruntime/python/tools/transformers/models/stable_diffusion/pipeline_stable_diffusion.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- # Modified from TensorRT demo diffusion, which has the following license...
832
33,198
notebook
tests/test_app.py
.py
import os import pytest from jupyter_server.serverapp import flags as serverapp_flags from tornado.httpclient import HTTPClientError from notebook.app import JupyterNotebookApp, NotebookHandler, TreeHandler @pytest.fixture def notebooks(jp_create_notebook, notebookapp): nbpaths = ( "notebook1.ipynb", ...
113
3,217
sqlmap
thirdparty/chardet/jisfreq.py
.py
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights R...
326
25,777
django-cms
docs/django_settings.py
.py
import os from pathlib import Path BASE_DIR = Path(__file__).resolve() INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.admin', 'django.contrib.sites', 'django.contrib.staticfiles', 'django.contrib.messages', 'treebeard...
57
1,665
mlflow
tests/store/model_registry/test_rest_store_webhooks.py
.py
from pathlib import Path from typing import Iterator import pytest from cryptography.fernet import Fernet from mlflow.entities.webhook import WebhookAction, WebhookEntity, WebhookEvent, WebhookStatus from mlflow.environment_variables import MLFLOW_WEBHOOK_SECRET_ENCRYPTION_KEY from mlflow.exceptions import MlflowExce...
215
8,743
kombu
kombu/asynchronous/aws/sqs/queue.py
.py
"""Amazon SQS queue implementation.""" from __future__ import annotations from vine import transform from .message import AsyncMessage _all__ = ['AsyncQueue'] def list_first(rs): """Get the first item in a list, or None if list empty.""" return rs[0] if len(rs) == 1 else None class AsyncQueue: """As...
131
4,402
wagtail
wagtail/hooks.py
.py
from contextlib import ContextDecorator from operator import itemgetter from wagtail.utils.apps import get_app_submodules _hooks = {} def register(hook_name, fn=None, order=0): """ Register hook for ``hook_name``. Can be used as a decorator:: @register('hook_name') def my_hook(...): ...
116
2,847
coremltools
coremltools/converters/mil/frontend/tensorflow2/test/testing_utils.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 numpy as np import pytest tf = pytest.importorskip("tensorflow", minversion="2.1.0") from te...
307
10,337
loguru
tests/exceptions/source/diagnose/syntax_highlighting.py
.py
# fmt: off import sys from loguru import logger logger.remove() logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True) def a(): 1 / 0 + 1 * 0 - 1 % 0 // 1**0 @ 1 # Error def b(): a() or False == None != True def c(): 1, 2.5, 3.0, 0.4, "str", r"rrr", rb"binary", b() def d...
34
503
saleor
saleor/tests/e2e/payment/utils/query_payment.py
.py
from ...utils import get_graphql_content PAYMENT_QUERY = """ query payment($id: ID!) { payment(id: $id) { id isActive checkout { token } } } """ def get_payment( api_client, payment_id, ): variables = {"id": payment_i...
26
472
openvino
tests/layer_tests/pytorch_tests/test_loop.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import platform import pytest from pytorch_layer_test_class import PytorchLayerTest import torch class TestWhileLoopFX(PytorchLayerTest): """Tests for torch.while_loop support in FX export (torch.export).""" def _prepare_inpu...
132
4,835
pyomo
pyomo/contrib/interior_point/linalg/tests/test_linear_solvers.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...
153
5,717
onnxruntime
orttraining/orttraining/python/training/optim/_modifier.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # # Copyright (c) 2020, NVIDIA CORPORATION. # Some functions in this file are adapted from following sources: # - clip_grad_norm_fp32 : https://github...
163
6,669
pyomo
pyomo/core/tests/examples/pmedian1.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...
13
592
mlflow
mlflow/utils/rest_utils.py
.py
import base64 import contextlib import json import logging import random import time import warnings from contextvars import ContextVar from functools import lru_cache from typing import Any, Callable import requests from mlflow.environment_variables import ( _MLFLOW_DATABRICKS_TRAFFIC_ID, _MLFLOW_HTTP_REQUES...
809
31,874
saleor
saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_order_bulk_created.py
.py
import json from unittest.mock import patch import graphene from django.test import override_settings from ......core.models import EventDelivery from ......graphql.webhook.subscription_query import SubscriptionQuery from ......webhook.event_types import WebhookEventAsyncType from .....manager import get_plugins_mana...
238
7,380
wagtail
wagtail/contrib/forms/utils.py
.py
from functools import lru_cache import swapper from django.contrib.contenttypes.models import ContentType from wagtail import hooks from wagtail.coreutils import safe_snake_case from wagtail.models import get_page_models from wagtail.permissions import policy_registry def get_field_clean_name(label): """ Co...
43
1,379
bazel
src/test/py/bazel/bzlmod/bzlmod_query_test.py
.py
# pylint: disable=g-backslash-continuation # Copyright 2022 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/LICEN...
382
12,805
onnxruntime
orttraining/orttraining/python/training/optim/__init__.py
.py
from .config import AdamConfig, LambConfig, SGDConfig, _OptimizerConfig # noqa: F401 from .fp16_optimizer import FP16_Optimizer # noqa: F401 from .fused_adam import AdamWMode, FusedAdam # noqa: F401 from .lr_scheduler import ( ConstantWarmupLRScheduler, # noqa: F401 CosineWarmupLRScheduler, # noqa: F401 ...
11
436
wandb
tests/unit_tests/test_autolog_patch_integration.py
.py
from typing import Any from unittest.mock import MagicMock import pytest import wandb from wandb.sdk.integration_utils.auto_logging import AutologAPI, PatchAPI class PatchAPITest(PatchAPI): def __init__(self, *args, **kwargs): self._test_api = kwargs.pop("test_api") super().__init__(*args, **kwar...
105
2,824
probability
tensorflow_probability/python/bijectors/shift_test.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...
51
1,963
pyro
pyro/contrib/gp/likelihoods/gaussian.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import torch from torch.distributions import constraints import pyro import pyro.distributions as dist from pyro.contrib.gp.likelihoods.likelihood import Likelihood from pyro.nn.module import PyroParam class Gaussian(Likelihood)...
49
1,677
pyro
tests/distributions/test_haar.py
.py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import pytest import torch from pyro.distributions.transforms import HaarTransform from tests.common import assert_equal @pytest.mark.parametrize("size", [1, 3, 4, 7, 8, 9]) def test_haar_ortho(size): haar = HaarTransform() ...
17
399
wagtail
wagtail/admin/views/pages/workflow.py
.py
import swapper from django.utils.translation import gettext as _ from wagtail.admin import messages from wagtail.admin.utils import get_latest_str from wagtail.admin.views.generic import workflow Page = swapper.load_model("wagtailcore", "Page") class WorkflowPageViewMixin: model = Page pk_url_kwarg = "page_...
59
1,716
openvino
src/frontends/tensorflow/tests/test_models/gen_scripts/generate_unsupported_op_itergetnext.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import os import sys import tensorflow as tf def main(): tf.compat.v1.reset_default_graph() with tf.compat.v1.Session() as sess: iteratorv2 = tf.raw_ops.IteratorV2(shared_name="iterator", container="...
39
1,407
pyro
tests/ops/test_integrator.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import logging from collections import namedtuple import pytest import torch from pyro.ops.integrator import velocity_verlet from tests.common import assert_equal logger = logging.getLogger(__name__) TEST_EXAMPLES = [] EXAMPLE...
181
4,558
conda
tests/shell/__init__.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations import os import sys from contextlib import contextmanager from dataclasses import dataclass from os.path import dirname from shutil import which from signal import SIGINT from typing import TYPE_CHECKING, ove...
330
12,333
beam
sdks/python/apache_beam/io/gcp/tests/bigquery_matcher.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...
269
9,185