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
textual
tests/snapshot_tests/snapshot_apps/big_button.py
.py
from textual.app import App, ComposeResult from textual.widgets import Button class ButtonApp(App): CSS = """ Button { height: 9; } """ def compose(self) -> ComposeResult: yield Button("Hello") yield Button("Hello\nWorld !!") if __name__ == "__main__": app = ButtonAp...
20
338
astropy
astropy/cosmology/_src/traits/__init__.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Astropy Cosmology. **NOT public API**. The public API is provided by `astropy.cosmology.traits`. """ from .baryons import * from .curvature import * from .darkenergy import * from .darkmatter import * from .hubble import * from .matter import * from ....
19
470
coremltools
coremltools/converters/mil/mil/ops/defs/iOS15/recurrent.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 Operation, Var, types from coremltools.converters.mil.mil....
526
21,292
beam
sdks/python/apache_beam/yaml/examples/testing/input_data.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");...
360
11,502
onnxruntime
onnxruntime/core/flatbuffers/ort_flatbuffers_py/fbs/Dimension.py
.py
# automatically generated by the FlatBuffers compiler, do not modify # namespace: fbs import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class Dimension(object): __slots__ = ['_tab'] @classmethod def GetRootAs(cls, buf, offset=0): n = flatbuffers.encode.Get(flatbu...
72
2,191
gunicorn
benchmarks/run_benchmark.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. #!/usr/bin/env python3 """ Benchmark script for gunicorn gthread worker. This script runs various benchmarks against gunicorn and reports performance metrics. Requires: gunicorn, requests (for warmup), and wrk or ...
243
7,466
toolz
toolz/sandbox/parallel.py
.py
import functools from toolz.itertoolz import partition_all from toolz.utils import no_default def _reduce(func, seq, initial=None): if initial is None: return functools.reduce(func, seq) else: return functools.reduce(func, seq, initial) def fold(binop, seq, default=no_default, map=map, chunk...
84
2,966
astropy
astropy/stats/biweight.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module contains functions for computing robust statistics using Tukey's biweight function. """ from collections.abc import Callable import numpy as np from numpy.typing import ArrayLike, NDArray from astropy.stats.funcs import median_absolute_d...
800
29,030
openvino
tests/layer_tests/tensorflow_tests/test_tf_HSVToRGB.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 rng = np.random.default_rng(23345) class TestHSVToRGB(CommonTFLayerTest): def _prepare_input(self, inputs_info): ...
50
2,132
mlflow
mlflow/optuna/__init__.py
.py
from mlflow.optuna.storage import MlflowStorage __all__ = ["MlflowStorage"]
4
77
sphinx
tests/test_extensions/test_ext_viewcode.py
.py
"""Test sphinx.ext.viewcode extension.""" from __future__ import annotations import re import shutil from typing import TYPE_CHECKING import pygments import pytest if TYPE_CHECKING: from sphinx.application import Sphinx from sphinx.testing.util import SphinxTestApp def check_viewcode_output(app: SphinxTes...
196
6,912
jupyterlab
jupyterlab/tests/test_app.py
.py
# Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. """A lab app that runs a sub process for a demo or a test.""" import atexit import json import os import shutil import sys import tempfile from importlib.resources import files from os import path as osp from os.path ...
228
7,139
biopython
Bio/SeqIO/Interfaces.py
.py
# Copyright 2006-2021 by Peter Cock. All rights reserved. # # This file is part of the Biopython distribution and governed by your # choice of the "Biopython License Agreement" or the "BSD 3-Clause License". # Please see the LICENSE file that should have been included as part of this # package. """Bio.SeqIO support mo...
250
8,419
coremltools
coremltools/converters/sklearn/_NuSVC.py
.py
# Copyright (c) 2017, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from ..._deps import _HAS_SKLEARN from . import _SVC as _SVC if _HAS_SKLEARN: from sklearn.svm impo...
69
1,882
onnx
onnx/backend/test/case/node/reduce_log_sum.py
.py
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import numpy as np import onnx from onnx.backend.test.case.base import Base from onnx.backend.test.case.node import expect class ReduceLogSum(Base): @staticmethod def export_nokeepdims() -> N...
105
3,091
readthedocs.org
readthedocs/api/v3/serializers.py
.py
import datetime import urllib from django.conf import settings from django.contrib.auth.models import User from django.db.models import Q from django.urls import reverse from django.utils.translation import gettext as _ from rest_flex_fields import FlexFieldsModelSerializer from rest_flex_fields.serializers import Fle...
1,349
43,307
pyomo
pyomo/core/tests/unit/test_range.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...
919
34,635
saleor
saleor/graphql/account/mutations/customer_type/customer_type_reorder_attributes.py
.py
import graphene from django.core.exceptions import ObjectDoesNotExist, ValidationError from .....account import models from .....core.tracing import traced_atomic_transaction from .....permission.enums import CustomerTypePermissions from .....webhook.event_types import WebhookEventAsyncType from ....attribute.mutation...
97
3,641
openvino
tests/model_hub_tests/pytorch/test_timm.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import platform import re import pytest import timm import torch from models_hub_common.utils import get_models_list, retry from torch_utils import TestTorchConvertModel, skip_npu_precommit def filter_timm(timm_list: list) ...
191
7,550
mlflow
mlflow/tracking/context/git_context.py
.py
import logging from mlflow.tracking.context.abstract_context import RunContextProvider from mlflow.tracking.context.default_context import _get_main_file from mlflow.utils.git_utils import get_git_branch, get_git_commit, get_git_repo_url from mlflow.utils.mlflow_tags import ( MLFLOW_GIT_BRANCH, MLFLOW_GIT_COMM...
41
1,137
pyomo
pyomo/kernel/util.py
.py
# ____________________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and Engineering # Solutions of...
255
9,111
saleor
saleor/core/telemetry/saleor_attributes.py
.py
from typing import Final SALEOR_ENVIRONMENT_DOMAIN: Final = "saleor.environment.domain" COMPONENT: Final = "component" SPAN_TYPE: Final = "span.type" OPERATION_NAME: Final = "operation.name" # GraphQL GRAPHQL_DOCUMENT_FINGERPRINT: Final = "graphql.document_fingerprint" GRAPHQL_FIELD_NAME: Final = "graphql.field_name...
33
1,144
loguru
tests/exceptions/source/others/sys_tracebacklimit_negative.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...
58
674
openvino
src/bindings/python/tests/__init__.py
.py
# -*- coding: utf-8 -*- # Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import pytest skip_devtest = pytest.mark.skip(reason="Test might depend on machine, should be run by developers" "or advanced users for debug/testing purposes.") skip_need_...
11
418
jupytext
tests/data/notebooks/outputs/ipynb_to_percent/text_outputs_and_images.py
.py
# --- # jupyter: # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% [markdown] # This notebook contains outputs of many different types: text, HTML, plots and errors. # %% [markdown] # # Text outputs # # Using `print`, `sys.stdout` and `sys.stderr` # %% import sys prin...
74
1,250
onnxruntime
onnxruntime/test/python/quantization/test_fusions.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. # ---------------------------------------------------------------...
402
18,969
pyomo
pyomo/core/base/blockutil.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...
22
965
sqlmap
tamper/dollarquote.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ import os import re from lib.core.common import singleTimeWarnMessage from lib.core.enums import DBMS from lib.core.enums import PRIORITY __priority__ = PRIORITY.LOW def depend...
45
1,226
metrics
tests/unittests/classification/test_specificity_sensitivity.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...
487
21,757
openvino
src/frontends/paddle/tests/test_models/gen_scripts/generate_equal.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # pool2d paddle model generator # import numpy as np from save_model import saveModel import sys def equal(name : str, x, y): import paddle paddle.enable_static() node_x = paddle.static.data(name='x', shape=x.shape, dtyp...
47
1,185
cvxpy
cvxpy/tests/test_matrices.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...
134
5,053
openvino
tests/layer_tests/pytorch_tests/test_compressed_mm.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest import torch from pytorch_layer_test_class import PytorchLayerTest def pack_uint4(tensor): packed_tensor = tensor.contiguous() packed_tensor = packed_tensor.reshape(-1, 2) packed_tensor = t...
165
6,167
beam
sdks/python/apache_beam/ml/inference/model_manager.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...
819
27,794
pyfilesystem2
tests/test_tarfs.py
.py
# -*- encoding: UTF-8 from __future__ import unicode_literals import io import os import six import tarfile import tempfile import unittest from fs import tarfs from fs.compress import write_tar from fs.enums import ResourceType from fs.errors import NoURL from fs.opener import open_fs from fs.opener.errors import No...
318
9,770
hatch
src/hatch/cli/check/__init__.py
.py
from __future__ import annotations import click from hatch.cli.check.code import code from hatch.cli.check.fmt import fmt from hatch.cli.check.types import types @click.group(short_help="Check source code", invoke_without_command=True) @click.option("--fix", is_flag=True, help="Fix issues rather than just reporting...
29
765
onnxruntime
onnxruntime/python/tools/quantization/calibrate.py
.py
#!/usr/bin/env python # ------------------------------------------------------------------------- # Copyright (c) Microsoft, Intel Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------...
1,354
56,791
gunicorn
gunicorn/asgi/parser.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. """ HTTP parser for ASGI workers. Provides callback-based parsing using either the fast C parser (gunicorn_h1c) or the pure Python PythonProtocol fallback. """ import socket import struct from enum import IntEnum...
940
33,062
pymc
tests/step_methods/test_compound.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...
200
6,865
beam
playground/infrastructure/api/v1/api_pb2.py
.py
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: api/v1/api.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_po...
132
17,113
astropy
astropy/timeseries/periodograms/lombscargle/implementations/utils.py
.py
from math import factorial import numpy as np def bitceil(N): """ Find the bit (i.e., power of 2) immediately greater than or equal to N. Note: this works for numbers up to 2 ** 64. Roughly equivalent to int(2 ** np.ceil(np.log2(N))). """ return 1 << int(N - 1).bit_length() def next_fast_le...
500
14,393
openvino
tests/model_hub_tests/transformation_tests/test_stateful_to_stateless_transformation.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import openvino as ov from huggingface_hub import snapshot_download from openvino._offline_transformations import stateful_to_stateless_transformation from optimum.intel import OVModelForCausalLM from models_hub_common.utils import retry...
100
5,320
black
tests/data/cases/return_annotation_brackets.py
.py
# Control def double(a: int) -> int: return 2*a # Remove the brackets def double(a: int) -> (int): return 2*a # Some newline variations def double(a: int) -> ( int): return 2*a def double(a: int) -> (int ): return 2*a def double(a: int) -> ( int ): return 2*a # Don't lose the comments d...
220
5,207
wagtail
wagtail/admin/api/actions/convert_alias.py
.py
from django.core.exceptions import ValidationError as DjangoValidationError from rest_framework import status from rest_framework.exceptions import ValidationError from rest_framework.response import Response from rest_framework.serializers import Serializer from wagtail.actions.convert_alias import ConvertAliasPageAc...
31
1,092
luigi
luigi/notifications.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...
430
14,835
probability
tensorflow_probability/python/distributions/internal/correlation_matrix_volumes_lib.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...
299
12,871
pdm
src/pdm/cli/commands/publish/__init__.py
.py
from __future__ import annotations import argparse import os from typing import TYPE_CHECKING from pdm.cli.commands import build from pdm.cli.commands.base import BaseCommand from pdm.cli.commands.publish.package import PackageFile from pdm.cli.hooks import HookManager from pdm.cli.options import project_option, skip...
210
8,265
textual
src/textual/eta.py
.py
from __future__ import annotations import bisect from math import ceil from time import monotonic import rich.repr @rich.repr.auto(angular=True) class ETA: """Calculate speed and estimate time to arrival.""" def __init__( self, estimation_period: float = 60, extrapolate_period: float = 30 ) -> ...
130
4,645
saleor
saleor/tests/e2e/promotions/test_unable_to_query_nor_mutate_sale_updated_by_promotion_translations.py
.py
import json import pytest from ..product.utils.preparing_product import prepare_product from ..sales.utils import ( create_sale, raw_create_sale_channel_listing, sale_catalogues_add, ) from ..shop.utils.preparing_shop import prepare_default_shop from ..utils import assign_permissions from .utils import pr...
145
3,978
pymc
setup.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...
82
2,764
onnxruntime
onnxruntime/python/backend/backend_rep.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- """ Implements ONNX's backend API. """ from onnx.backend.base import Bac...
77
2,825
kombu
t/unit/transport/SQS/test_SQS.py
.py
"""Testing module for the kombu.transport.SQS package. NOTE: The SQSQueueMock and SQSConnectionMock classes originally come from http://github.com/pcsforeducation/sqs-mock-python. They have been patched slightly. """ from __future__ import annotations import base64 import logging import os import random import string...
2,376
88,658
confluent-kafka-python
tests/ducktape/services/kafka.py
.py
""" Kafka client wrapper for Ducktape tests Assumes Kafka is already running on localhost:9092 """ import time from ducktape.services.service import Service from confluent_kafka.admin import AdminClient, NewPartitions, NewTopic class KafkaClient(Service): """Kafka client wrapper - assumes external Kafka is run...
143
5,608
pyomo
pyomo/contrib/trustregion/tests/test_interface.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...
441
20,978
python-prompt-toolkit
examples/prompts/placeholder-text.py
.py
#!/usr/bin/env python """ Example of a placeholder that's displayed as long as no input is given. """ from prompt_toolkit import prompt from prompt_toolkit.formatted_text import HTML if __name__ == "__main__": answer = prompt( "Give me some input: ", placeholder=HTML('<style color="#888888">(pleas...
15
388
sphinx
tests/roots/test-ext-autodoc/target/singledispatchmethod_classmethod.py
.py
from functools import singledispatchmethod class Foo: """docstring""" @singledispatchmethod @classmethod def class_meth(cls, arg, kwarg=None): """A class method for general use.""" pass @class_meth.register(int) @class_meth.register(float) @classmethod def _class_meth...
32
768
saleor
saleor/discount/tests/test_utils/test_update_voucher_discount_object_for_order.py
.py
from decimal import Decimal import pytest from prices import Money from ....core.prices import quantize_price from ....core.taxes import zero_money from ....order import OrderStatus from ....order.calculations import fetch_order_prices_if_expired from ... import DiscountType, DiscountValueType, VoucherType from ...mo...
1,221
47,678
saleor
saleor/graphql/shop/tests/mutations/test_return_reason_reference_type_clear.py
.py
from ....tests.utils import assert_no_permission, get_graphql_content RETURN_REASON_REFERENCE_TYPE_CLEAR_MUTATION = """ mutation returnReasonReferenceClear { returnReasonReferenceClear { returnSettings { reasonReferenceType { id name ...
141
3,550
sqlmap
plugins/dbms/mysql/enumeration.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ from plugins.generic.enumeration import Enumeration as GenericEnumeration class Enumeration(GenericEnumeration): pass
12
264
toolz
bench/test_wordcount.py
.py
from toolz.curried import * import os if not os.path.exists('bench/shakespeare.txt'): os.system('wget http://www.gutenberg.org/files/100/100-0.txt' ' -O bench/shakespeare.txt') def stem(word): """ Stem word to primitive form """ return word.lower().rstrip(",.!:;'-\"").lstrip("'\"") wordcou...
19
479
probability
tensorflow_probability/python/distributions/joint_distribution_sequential.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...
819
34,536
metrics
tests/unittests/image/test_qnr.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...
221
8,004
pyomo
pyomo/dae/tests/test_diffvar.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...
176
6,585
wandb
tests/system_tests/test_functional/metaflow/flow_pytorch.py
.py
"""Test Metaflow Flow integration""" import os import torch import torch.nn as nn import torch.nn.functional as F # noqa: N812 import torch.optim as optim import wandb from metaflow import FlowSpec, Parameter, step from torch.optim.lr_scheduler import StepLR from torchvision import datasets, transforms from wandb.in...
147
4,604
sphinx
tests/roots/test-ext-autodoc/target/genericalias.py
.py
from __future__ import annotations from typing import Callable, List #: A list of int T = List[int] C = Callable[[int], None] # a generic alias not having a doccomment class Class: #: A list of int T = List[int] #: A list of Class L = List[Class]
18
263
saleor
saleor/graphql/translations/mutations/shipping_price_translate.py
.py
import graphene from ....permission.enums import SitePermissions from ....shipping import models as shipping_models from ...core import ResolveInfo from ...core.context import ChannelContext from ...core.descriptions import RICH_CONTENT from ...core.enums import LanguageCodeEnum from ...core.fields import JSONString f...
75
2,482
django-cms
cms/tests/test_mptree_backend.py
.py
""" Guardrail + functional tests for the swappable tree backend. * ``TreeFieldParityTests`` proves the swap is *migration-invisible*: Django builds migrations purely from field deconstruction, so if ``MaterializedPathMixin`` deconstructs its tree fields identically to treebeard's ``MP_Node``, substituting one fo...
1,056
41,445
pyro
pyro/contrib/gp/kernels/dot_product.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import torch from torch.distributions import constraints from pyro.contrib.gp.kernels.kernel import Kernel from pyro.nn.module import PyroParam class DotProduct(Kernel): r""" Base class for kernels which are functions of...
86
2,646
coremltools
deps/pybind11/tests/test_iostream.py
.py
from __future__ import annotations from contextlib import redirect_stderr, redirect_stdout from io import StringIO from pybind11_tests import iostream as m def test_captured(capsys): msg = "I've been redirected to Python, I hope!" m.captured_output(msg) stdout, stderr = capsys.readouterr() assert st...
294
7,180
cvxpy
cvxpy/reductions/dgp2dcp/dgp2dcp.py
.py
""" Copyright 2018 Akshay Agrawal 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...
224
8,781
saleor
saleor/tests/e2e/attributes/utils/__init__.py
.py
from .attribute_bulk_create import bulk_create_attributes from .create_attribute import attribute_create from .prepare_attributes import ( prepare_all_attributes, prepare_all_attributes_in_bulk, prepare_attributes_in_bulk, ) from .update_attribute import attribute_update __all__ = [ "attribute_create",...
18
479
probability
tensorflow_probability/python/experimental/fastgp/mbcg.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...
205
8,257
pyro
pyro/distributions/delta.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import numbers import torch from pyro.distributions.torch_distribution import TorchDistribution from pyro.distributions.util import sum_rightmost from . import constraints class Delta(TorchDistribution): """ Degenerate...
86
3,066
pynacl
src/nacl/bindings/crypto_box.py
.py
# Copyright 2013 Donald Stufft and individual contributors # # 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...
469
14,166
beam
infra/iam/migrate_roles.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...
340
13,942
saleor
saleor/product/signals.py
.py
from ..core.tasks import delete_from_storage_task def delete_background_image(sender, instance, **kwargs): if img := instance.background_image: delete_from_storage_task.delay(img.name) def delete_product_media_image(sender, instance, **kwargs): if file := instance.image: delete_from_storage_...
12
342
django-cms
docs/_ext/djangocms.py
.py
def setup(app): app.add_crossref_type( directivename = "setting", rolename = "setting", indextemplate = "pair: %s; setting", ) app.add_crossref_type( directivename = "templatetag", rolename = "ttag", indextemplate = "pair: %s; template tag" )
12
317
luigi
luigi/contrib/sqla.py
.py
# -*- coding: utf-8 -*- # # Copyright (c) 2015 Gouthaman Balaraman # # 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 applic...
414
16,182
wandb
wandb/sdk/launch/runner/local_process.py
.py
from __future__ import annotations import logging import shlex from typing import Any import wandb from .._project_spec import LaunchProject from ..errors import LaunchError from ..utils import ( LOG_PREFIX, MAX_ENV_LENGTHS, PROJECT_SYNCHRONOUS, sanitize_wandb_api_key, validate_wandb_python_deps,...
81
2,752
hydra
plugins/hydra_ray_launcher/examples/upload_download/train.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import logging import hydra from model.my_model import MyModel from omegaconf import DictConfig log = logging.getLogger(__name__) @hydra.main(config_path="conf", config_name="config") def main(cfg: DictConfig) -> None: log.info("Start traini...
21
487
hatch
tests/backend/metadata/test_hatch.py
.py
import pytest from hatchling.metadata.core import HatchMetadata from hatchling.plugin.manager import PluginManager from hatchling.version.scheme.standard import StandardScheme from hatchling.version.source.regex import RegexSource class TestBuildConfig: def test_default(self, isolation): config = {} ...
180
7,131
pyomo
examples/performance/jump/facility.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...
74
2,171
saleor
saleor/graphql/payment/tests/mutations/test_stored_payment_method_request_delete.py
.py
from unittest.mock import patch from .....payment.interface import ( StoredPaymentMethodRequestDeleteData, StoredPaymentMethodRequestDeleteResponseData, StoredPaymentMethodRequestDeleteResult, ) from .....plugins.manager import PluginsManager from ....core.enums import StoredPaymentMethodRequestDeleteError...
257
9,159
coremltools
coremltools/converters/mil/mil/block.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 copy from collections import Counter, OrderedDict from typing import List, Optional, Set, Tupl...
1,142
44,404
beam
sdks/python/apache_beam/ml/anomaly/detectors/iqr.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...
130
4,663
django-cms
cms/utils/compat/warnings.py
.py
class RemovedInDjangoCMS51Warning(DeprecationWarning): pass class RemovedInDjangoCMS60Warning(DeprecationWarning): pass
7
130
mlflow
tests/resources/example_project/check_conda_env.py
.py
# Import a dependency in MLflow's setup.py that's in our conda.yaml but not included with MLflow # by default, verify that we can use it. import os import sys import psutil import mlflow def main(expected_env_name): actual_conda_env = os.environ.get("CONDA_DEFAULT_ENV", None) assert actual_conda_env == exp...
23
586
readthedocs.org
readthedocs/builds/tests/test_trigger_build.py
.py
from unittest import mock import django_dynamic_fixture as fixture import pytest from readthedocs.builds.constants import ( BUILD_STATE_BUILDING, BUILD_STATE_CANCELLED, BUILD_STATE_CLONING, BUILD_STATE_FINISHED, BUILD_STATE_INSTALLING, BUILD_STATE_TRIGGERED, BUILD_STATE_UPLOADING, ) from r...
115
3,789
jupytext
tests/data/notebooks/outputs/ipynb_to_script_vscode_folding_markers/Notebook with many hash signs.py
.py
# --- # jupyter: # jupytext: # cell_markers: region,endregion # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # ################################################################## # This is a notebook that contains many hash signs. # Hopefully its python representatio...
31
931
mlflow
mlflow/genai/judges/utils/formatting_utils.py
.py
import logging from typing import TYPE_CHECKING if TYPE_CHECKING: from mlflow.genai.utils.type import FunctionCall from mlflow.types.chat import ChatTool _logger = logging.getLogger(__name__) def format_available_tools(available_tools: list["ChatTool"]) -> str: """Format available tools with description...
97
3,548
wandb
wandb/sdk/artifacts/_generated/unlink_artifact.py
.py
# Generated by ariadne-codegen # Source: tools/graphql_codegen/artifacts/ from __future__ import annotations from wandb._pydantic import GQLResult class UnlinkArtifact(GQLResult): result: UnlinkArtifactResult | None class UnlinkArtifactResult(GQLResult): success: bool UnlinkArtifact.model_rebuild()
18
316
textual
tests/test_masked_input.py
.py
from typing import Union import pytest from textual import on from textual.app import App, ComposeResult from textual.validation import Failure, ValidationResult from textual.widgets import MaskedInput InputEvent = Union[MaskedInput.Changed, MaskedInput.Submitted] class InputApp(App[None]): def __init__(self, ...
224
7,266
luigi
test/_mysqldb_test.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...
51
1,546
sphinx
sphinx/util/tags.py
.py
from __future__ import annotations from typing import TYPE_CHECKING import jinja2.environment import jinja2.nodes import jinja2.parser if TYPE_CHECKING: from collections.abc import Collection, Iterator _ENV = jinja2.environment.Environment() class BooleanParser(jinja2.parser.Parser): """Only allow conditi...
103
3,583
returns
returns/_internal/pipeline/pipe.py
.py
from returns._internal.pipeline.flow import flow def pipe(*functions): """ Allows to compose a value and up to 7 functions that use this value. We use a custom ``mypy`` plugin to make sure types are correct. Otherwise, it is currently impossible to properly type this function. Each next function...
35
1,016
openvino
tests/layer_tests/tensorflow_tests/test_tf_RGBToHSV.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import platform import pytest import tensorflow as tf from common.tf_layer_test_class import CommonTFLayerTest rng = np.random.default_rng(3476123) class TestRGBToHSV(CommonTFLayerTest): def _prepare_input(self,...
53
2,156
pyro
tests/pyroapi/conftest.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import pytest def pytest_runtest_call(item): try: item.runtest() except NotImplementedError as e: pytest.xfail(str(e))
12
234
sqlmap
lib/core/shell.py
.py
#!/usr/bin/env python """ Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org) See the file 'LICENSE' for copying permission """ import atexit import os from lib.core import readlineng as readline from lib.core.common import getSafeExString from lib.core.data import logger from lib.core.data import paths f...
164
5,533
black
tests/data/cases/preview_long_strings.py
.py
# flags: --unstable 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...
965
37,918
pymc
tests/distributions/test_multivariate.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...
2,640
92,946
wagtail
wagtail/blocks/definition_lookup.py
.py
from collections import defaultdict from importlib import import_module class BlockDefinitionLookup: """ A utility for constructing StreamField Block objects in migrations, starting from a compact representation that avoids repeating the same definition whenever a block is re-used in multiple places o...
86
3,274