repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
saleor
saleor/permission/tests/test_one_of_permissions_or_auth_filter_required.py
.py
from unittest.mock import Mock import pytest from ..auth_filters import AuthorizationFilters from ..enums import CheckoutPermissions, OrderPermissions from ..utils import all_permissions_required @pytest.mark.parametrize( ("permissions", "expected_result"), [ (None, True), ([], True), ...
316
8,902
readthedocs.org
readthedocs/search/management/commands/reindex_elasticsearch.py
.py
import itertools import sys import textwrap from datetime import datetime from datetime import timedelta import structlog from django.apps import apps from django.conf import settings from django.core.management import BaseCommand from django_elasticsearch_dsl.registries import registry from readthedocs.builds.models...
307
10,940
beam
sdks/python/apache_beam/examples/snippets/transforms/elementwise/map_side_inputs_dict.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");...
83
2,421
clearml
clearml/hyperdatasets/data_entry.py
.py
import importlib import logging import uuid from collections import deque from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Set, Type, TypeVar from clearml.storage.manager import StorageManagerDiskSpaceFileSizeStrategy ENTRY_CLASS_KEY = "_clearml_data_entry_class" SUB_ENTRY_CLASS_KEY = "_c...
569
20,882
mlflow
tests/models/test_container.py
.py
import os from unittest import mock import pytest import yaml from mlflow.models.container import _install_model_dependencies_to_env from mlflow.utils import env_manager as em def _create_model_artifact(model_path, dependencies, build_dependencies=None): """Helper to create a minimal model artifact for testing....
228
7,408
probability
tensorflow_probability/examples/sprites_dataset.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...
364
13,849
pyomo
pyomo/contrib/doe/__init__.py
.py
# ____________________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and Engineering # Solutions of...
47
1,870
pyomo
pyomo/repn/standard_repn.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...
1,714
60,041
probability
tensorflow_probability/python/experimental/auto_batching/instructions_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...
243
7,147
mlflow
tests/gateway/test_redis_budget_tracker.py
.py
from datetime import datetime, timedelta, timezone from unittest.mock import patch import pytest from mlflow.entities.gateway_budget_policy import ( BudgetAction, BudgetDuration, BudgetDurationUnit, BudgetTargetScope, BudgetUnit, GatewayBudgetPolicy, ) from mlflow.gateway.budget_tracker import...
429
13,399
scikit-bio
skbio/io/format/tests/test_fasta.py
.py
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE.txt, distributed with this software. # --------------------------------------------...
1,096
48,483
pyro
pyro/poutine/util.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 from typing import TYPE_CHECKING, List, Optional from pyro import settings if TYPE_CHECKING: from pyro.distributions.distribution import Distribution from pyro.poutine.runtime import Message from pyro.poutine.trace_st...
148
4,790
beam
sdks/python/apache_beam/ml/rag/embeddings/huggingface_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...
248
8,278
sphinx
sphinx/pycode/parser.py
.py
"""Utilities parsing and analyzing Python code.""" from __future__ import annotations import ast import contextlib import functools import inspect import itertools import operator import re import tokenize from token import DEDENT, INDENT, NAME, NEWLINE, NUMBER, OP, STRING from tokenize import COMMENT, NL from typing...
628
22,880
probability
tensorflow_probability/python/stats/__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...
83
3,815
conda
tests/plugins/test_auth_handlers.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause import pytest from requests.auth import HTTPBasicAuth from conda import plugins from conda.exceptions import PluginError PLUGIN_NAME = "custom_auth" PLUGIN_NAME_ALT = "custom_auth_alt" class CustomCondaAuth(HTTPBasicAuth): def __init__(...
83
2,328
pyomo
examples/kernel/mosek/geometric2.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...
91
3,056
wagtail
wagtail/exceptions.py
.py
class PageClassNotFoundError(ImportError): """ Raised when a model class referenced by a page object's ``content_type`` value cannot be found in the codebase. Usually, this is as a result of switching to a different git branch without first running/reverting migrations. """ pass
10
309
probability
tensorflow_probability/python/experimental/psd_kernels/multitask_kernel.py
.py
# Copyright 2021 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
265
10,368
onnxruntime
orttraining/tools/scripts/opset12_model_transform.py
.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # # This converter is an internal util to upgrade existing bert/gpt-2 models, # which were previously transformed/optimized from original model, to Opset 12 # version as well as replacing deprecated node, i.e., TrainableDropou...
127
4,528
mlflow
tests/utils/test_exception.py
.py
import json from mlflow.exceptions import ExecutionException, RestException from mlflow.protos.databricks_pb2 import RESOURCE_DOES_NOT_EXIST, ErrorCode def test_execution_exception_string_repr(): exc = ExecutionException("Uh oh") assert str(exc) == "Uh oh" json.loads(exc.serialize_as_json()) def test_r...
40
1,246
mlflow
mlflow/server/gateway_api.py
.py
""" Database-backed Gateway API endpoints for MLflow Server. This module provides dynamic gateway endpoints that are configured from the database rather than from a static YAML configuration file. It integrates the AI Gateway functionality directly into the MLflow tracking server. """ import functools import io impor...
1,588
63,389
onnx
onnx/tools/update_model_dims.py
.py
# Copyright (c) ONNX Project Contributors # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations from typing import Any import onnx.checker from onnx import ModelProto, ValueInfoProto def update_inputs_outputs_dims( model: ModelProto, input_dims: dict[str, list[Any]], output_dims: dic...
99
3,462
ipython
docs/autogen_config.py
.py
#!/usr/bin/env python import inspect from pathlib import Path from IPython.terminal.ipapp import TerminalIPythonApp from traitlets import Undefined from collections import defaultdict here = (Path(__file__)).parent options = here / "source" / "config" / "options" generated = options / "config-generated.txt" import t...
123
3,819
onnx
onnx/backend/test/case/node/exp.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 Exp(Base): @staticmethod def export() -> None: node = ...
29
761
pdm
tests/models/test_session.py
.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from pdm.project.core import Project def test_session_sources_all_proxy(project: Project, mocker, monkeypatch): for key in ("http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "no_proxy", "NO_PROXY"): ...
27
1,023
biopython
Bio/Restriction/Restriction.py
.py
#!/usr/bin/env python # # Restriction Analysis Libraries. # Copyright (C) 2004. Frederic Sohm. # # 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. # """Restriction Enzyme classes. Notes abou...
2,641
83,768
sqlmap
thirdparty/chardet/langrussianmodel.py
.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from .sbcharsetprober import SingleByteCharSetModel # 3: Positive # 2: Likely # 1: Unlikely # 0: Negative RUSSIAN_LANG_MODEL = { 37: { # 'А' 37: 0, # 'А' 44: 1, # 'Б' 33: 1, # 'В' 46: 1, # 'Г' 41: 1, # 'Д' 48: 1,...
5,719
131,161
black
src/black/files.py
.py
import io import os import sys from collections.abc import Iterable, Iterator, Sequence from functools import lru_cache from pathlib import Path from re import Pattern from typing import TYPE_CHECKING, Any, Union from mypy_extensions import mypyc_attr from packaging.specifiers import InvalidSpecifier, Specifier, Speci...
436
14,921
pymc
pymc/logprob/cumsum.py
.py
# Copyright 2024 - present The PyMC Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
107
3,750
qutip
qutip/tests/solver/test_scattering.py
.py
""" This module includes a collection of testing functions for the QuTiP scattering module. Tests are approximate with low resolution to minimize runtime. """ # Author: Ben Bartlett # Contact: benbartlett@stanford.edu import numpy as np from qutip import create, destroy, basis from qutip.solver.scattering import * ...
92
3,405
hydra
examples/tutorials/basic/running_your_hydra_app/4_logging/my_app.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import logging from omegaconf import DictConfig import hydra # A logger for this file log = logging.getLogger(__name__) @hydra.main() def my_app(_cfg: DictConfig) -> None: log.info("Info level message") log.debug("Debug level message") ...
20
362
saleor
saleor/graphql/attribute/tests/type_handlers/test_reference_handler.py
.py
from collections import defaultdict import graphene from django.utils.text import slugify from text_unidecode import unidecode from ...enums import AttributeValueBulkActionEnum from ...utils.shared import AttrValuesInput from ...utils.type_handlers import AttributeInputErrors, ReferenceAttributeHandler def test_ref...
625
22,955
metrics
src/torchmetrics/functional/retrieval/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...
52
2,121
openvino
docs/scripts/filehelper.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import argparse import logging import os import re import shutil from pathlib import Path INLINE_LINKS_PATTERN = r'!?\[.*?\]\(([\w\/\-\.]+\.md)\)' REFERENCE_LINKS_PATTERN = r'\[.+\]\:\s*?([\w\/\-\.]+\.md)' INLINE_IMAGES_PATTERN = r'!?...
214
7,372
biopython
Tests/test_BioSQL_sqlite3.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. """Run BioSQL tests using SQLite.""" import os import unittest # Really do want "import *" to get all the test classes: from common_BioSQL import * ...
77
2,602
astropy
astropy/cosmology/_src/units.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Cosmological units.""" __all__ = ("littleh", "redshift") from typing import Final import astropy.units as u _ns = globals() # This is not formally a unit, but is used in that way in many contexts, and # an appropriate equivalency is only possible ...
36
1,046
openvino
tests/layer_tests/tensorflow2_keras_tests/test_tf2_keras_alpha_dropout.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import pytest import tensorflow as tf from common.tf2_layer_test_class import CommonTF2LayerTest class TestKerasAlphaDropout(CommonTF2LayerTest): def create_keras_alpha_dropout_net(self, rate, input_names, input_shapes, input_type...
54
2,842
cvxpy
cvxpy/tests/nlp_tests/test_dnlp.py
.py
""" Copyright, the CVXPY authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software ...
142
4,400
saleor
saleor/product/utils/availability.py
.py
from dataclasses import dataclass from decimal import Decimal from typing import Literal from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange from ...product.models import ProductChannelListing, ProductVariantChannelListing from ...tax import TaxCalculationStrategy from ...tax.calculations import calcula...
229
7,274
pdm
tasks/complete.py
.py
from pathlib import Path from argcomplete.shell_integration import shellcode COMPLETIONS = Path(__file__).parent.parent / "src/pdm/cli/completions" def main(): for shell, suffix, title in ( ("bash", "bash", "BASH"), ("zsh", "zsh", "ZSH"), ("fish", "fish", "FISH"), ("powershell", ...
21
546
coremltools
coremltools/converters/mil/mil/ops/tests/iOS16/test_image_resizing.py
.py
# Copyright (c) 2023, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause import itertools import numpy as np import pytest import coremltools as ct from coremltools.convert...
196
6,176
marshmallow
tests/test_error_store.py
.py
from typing import NamedTuple from marshmallow import missing from marshmallow.error_store import ErrorStore, merge_errors def test_missing_is_falsy(): assert bool(missing) is False class CustomError(NamedTuple): code: int message: str class TestMergeErrors: def test_merging_none_and_string(self)...
168
5,749
black
tests/test_ranges.py
.py
"""Test the black.ranges module.""" import pytest from black.ranges import adjusted_lines, parse_line_ranges, sanitized_lines @pytest.mark.parametrize( "lines_str, expected", [ (["1-5"], [(1, 5)]), (["1-1"], [(1, 1)]), (["1-3", "5-7"], [(1, 3), (5, 7)]), ], ) def test_parse_line_...
276
5,153
saleor
saleor/plugins/admin_email/tasks.py
.py
from ...celeryconf import app from ...core.db.connection import allow_writer from ...csv.events import export_failed_info_sent_event, export_file_sent_event from ...graphql.core.utils import from_global_id_or_none from ..email_common import EmailConfig, send_email @app.task(compression="zlib") def send_set_staff_pass...
86
2,502
loguru
tests/exceptions/source/others/level_name.py
.py
import sys from loguru import logger logger.remove() logger.add( sys.stderr, format="{level.name} | {level.no}", diagnose=False, backtrace=False, colorize=False ) def a(): with logger.catch(level="DEBUG"): 1 / 0 a()
17
238
onnxruntime
orttraining/orttraining/test/python/orttraining_test_ortmodule_fallback.py
.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # orttraining_test_ortmodule_api.py import copy import itertools import math import os import warnings from dataclasses import dataclass import _test_helpers import numpy as np import pytest import torch from _orttraining_or...
746
33,704
mlflow
examples/tensorflow/train.py
.py
# tensorflow 2.x core api import tensorflow as tf from sklearn.datasets import load_diabetes import mlflow from mlflow.models import infer_signature class Normalize(tf.Module): """Data Normalization class""" def __init__(self, x): # Initialize the mean and standard deviation for normalization ...
168
5,925
lemur
lemur/plugins/lemur_aws/tests/test_iam.py
.py
import pytest from moto import mock_iam, mock_sts from lemur.tests.vectors import EXTERNAL_VALID_STR, SAN_CERT_KEY def test_get_name_from_arn(): from lemur.plugins.lemur_aws.iam import get_name_from_arn arn = "arn:aws:iam::123456789012:server-certificate/tttt2.netflixtest.net-NetflixInc-20150624-20150625" ...
162
6,127
wagtail
wagtail/admin/widgets/button.py
.py
from django.forms.utils import flatatt from django.utils.functional import cached_property from wagtail import hooks from wagtail.admin.ui.components import Component from wagtail.admin.ui.menus import MenuItem class BaseButton(Component): template_name = "wagtailadmin/shared/button.html" show = True lab...
246
7,376
openvino
samples/python/benchmark/bert_benchmark/bert_benchmark.py
.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import logging as log from pathlib import Path import sys import tempfile from time import perf_counter import openvino as ov import datasets from transformers import AutoTokenizer from tra...
79
3,028
wandb
wandb/integration/sklearn/plot/regressor.py
.py
"""Define plots for regression models built with scikit-learn.""" from warnings import simplefilter import numpy as np import wandb from wandb.integration.sklearn import calculate, utils from . import shared # ignore all future warnings simplefilter(action="ignore", category=FutureWarning) def regressor(model, X...
122
3,943
onnxruntime
onnxruntime/test/python/contrib_ops/onnx_contrib_ops_helper.py
.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # # Helper functions for generating ONNX model and data to test ONNX Runtime contrib ops import os import shutil import subprocess import onnx from onnx import numpy_helper TOP_DIR = os.path.realpath(os.path.dirname(__file_...
81
2,760
openvino
src/bindings/python/src/openvino/opset12/ops.py
.py
# -*- coding: utf-8 -*- # Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """Factory functions for all ngraph ops.""" from functools import partial from typing import Optional from openvino import Node from openvino.utils.node_factory import _get_node_factory from openvino.utils.decora...
121
4,417
wagtail
wagtail/tests/test_comments.py
.py
from django.contrib.auth import get_user_model from django.test import TestCase from wagtail.models import Comment from wagtail.test.utils import Page, PageFixturesMixin class CommentTestingUtils: def setUp(self): self.page = Page.objects.get(title="Welcome to the Wagtail test site!") self.revisi...
45
1,728
pyro
pyro/distributions/transforms/discrete_cosine.py
.py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import torch from torch.distributions.transforms import Transform from pyro.ops.tensor_utils import dct, idct from .. import constraints class DiscreteCosineTransform(Transform): """ Discrete Cosine Transform of type-II. ...
105
3,383
metrics
src/torchmetrics/__init__.py
.py
r"""Root package info.""" import logging as __logging import os from lightning_utilities.core.imports import package_available from torchmetrics.__about__ import * # noqa: F403 _logger = __logging.getLogger("torchmetrics") _logger.addHandler(__logging.StreamHandler()) _logger.setLevel(__logging.INFO) _PACKAGE_ROO...
276
9,490
saleor
saleor/graphql/meta/tests/mutations/test_payment.py
.py
import graphene from .....payment.models import TransactionItem from .....payment.utils import payment_owned_by_user from ....tests.utils import assert_no_permission from . import PRIVATE_KEY, PRIVATE_VALUE, PUBLIC_KEY from .test_delete_private_metadata import ( execute_clear_private_metadata_for_item, item_wi...
233
7,085
wagtail
wagtail/admin/tests/api/utils.py
.py
from django.test import TransactionTestCase, tag from wagtail.test.utils import WagtailTestUtils @tag("transaction") class AdminAPITestCase(WagtailTestUtils, TransactionTestCase): def setUp(self): super().setUp() self.user = self.login()
11
261
metrics
src/torchmetrics/audio/srmr.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...
188
7,378
confluent-kafka-python
scripts/update-changelog.py
.py
#!/usr/bin/env python3 """update-changelog.py - Prepend unreleased commits to CHANGELOG.md Commits with 'fix' in the title or body go in the Fixes section. All other commits go in the Enhancements section. Usage: python3 scripts/update-changelog.py [new_version] [--dry-run] Arguments: new_version Version st...
154
4,671
biopython
Bio/SeqIO/TabIO.py
.py
# Copyright 2008-2017,2020 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 suppo...
159
5,196
openvino
src/bindings/python/tests/test_graph/test_ops_util_variable.py
.py
# -*- coding: utf-8 -*- # Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 from openvino import PartialShape, Type from openvino.op.util import VariableInfo, Variable def test_info_as_property(): info = VariableInfo() info.data_shape = PartialShape([1]) info.data_type = Typ...
48
1,509
probability
spinoffs/inference_gym/inference_gym/targets/ground_truth/radon_contextual_effects_minnesota_halfnormal.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...
345
8,673
textual
tests/snapshot_tests/snapshot_apps/text_area_alternate_screen.py
.py
from textual.app import App from textual.screen import Screen from textual.widgets import TextArea TEXT = """\ foo bar baz """ class AltScreen(Screen[None]): def compose(self): yield TextArea(TEXT) class TABug(App[None]): def on_mount(self): self.push_screen(AltScreen()) if __name__ == "_...
25
362
clearml
examples/hyperdatasets/legacy/data-ingestion/pytorch_dataset_example.py
.py
import numpy as np import torch.utils.data from allegroai import DataView, SingleFrame, Task from PIL import Image from torch.utils.data import DataLoader class ExampleDataset(torch.utils.data.Dataset): def __init__(self, dv): # automatically adjust dataset to balance all queries self.frames = dv....
52
1,322
gunicorn
tests/support.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. import functools import sys import unittest import platform from wsgiref.validate import validator HOST = "127.0.0.1" def create_app(name="World", count=1): message = (('Hello, %s!\n' % name) * count).encode...
68
1,851
openvino
tests/layer_tests/ovc_python_api_tests/test_pytorch.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import tempfile import unittest import numpy as np import pytest import torch from common.mo_convert_test_class import CommonMOConvertTest import openvino as ov from openvino import PartialShape, Dimension, Model, Type clas...
1,704
67,434
textual
tests/css/test_inheritance.py
.py
import pytest from textual.app import App, ComposeResult from textual.color import Color from textual.widget import Widget class Widget1(Widget): DEFAULT_CSS = """ Widget1 { background: red; } """ class Widget2(Widget1): DEFAULT_CSS = """ Widget1 { background: green; } ...
40
892
colorama
colorama/winterm.py
.py
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. try: from msvcrt import get_osfhandle except ImportError: def get_osfhandle(_): raise OSError("This isn't windows!") from . import win32 # from wincon.h class WinColor: BLACK = 0 BLUE = 1 GREEN = 2 CYAN ...
196
7,135
ipython
tests/test_utils_misc.py
.py
"""Tests for small IPython.utils modules: data, timing, frame and encoding.""" import importlib import sys import time import types import pytest from IPython.testing.decorators import skip_win32 from IPython.utils import data as data_mod from IPython.utils import encoding as encoding_mod from IPython.utils import ...
247
7,878
voila
hatch_build.py
.py
import os import sys from urllib.request import urlopen from hatchling.builders.hooks.plugin.interface import BuildHookInterface JUPYTERLAB_APPUTILS_VERSION = "3.2.8" JUPYTERLAB_THEME_LIGHT_VERSION = "3.2.8" CSS_FILES = [ ( f"https://unpkg.com/@jupyterlab/apputils@{JUPYTERLAB_APPUTILS_VERSION}/style/mate...
50
1,667
beam
sdks/python/apache_beam/tools/distribution_counter_microbenchmark.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 ...
71
2,394
saleor
saleor/graphql/app/tests/mutations/test_app_retry_install.py
.py
from unittest.mock import Mock, patch import graphene from .....app.models import App, AppInstallation from .....app.tasks import install_app_task from .....core import JobStatus from ....core.enums import AppErrorCode from ....tests.utils import get_graphql_content RETRY_INSTALL_APP_MUTATION = """ mutation AppR...
305
9,945
beam
sdks/python/apache_beam/examples/snippets/transforms/elementwise/map_test.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");...
130
4,074
beam
sdks/python/apache_beam/examples/streaming_wordcount_it_test.py
.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
112
4,339
mlflow
mlflow/entities/dataset_record_source.py
.py
from __future__ import annotations import json from dataclasses import asdict, dataclass from enum import Enum from typing import Any from mlflow.entities._mlflow_object import _MlflowObject from mlflow.exceptions import MlflowException from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE from mlflow.prot...
127
4,181
biopython
Bio/Graphics/KGML_vis.py
.py
# Copyright 2013 Leighton Pritchard. 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. """Classes and function...
443
17,637
pymc
pymc/logprob/checks.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...
123
4,467
openvino
src/frontends/paddle/tests/test_models/gen_scripts/generate_cumsum.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # cumsum paddle model generator # import numpy as np from save_model import saveModel import paddle import sys data_type = 'float32' def cumsum(name:str, x, axis, dtype=None): paddle.enable_static() with paddle.static.progra...
47
1,373
probability
tensorflow_probability/python/internal/backend/numpy/type_spec_registry.py
.py
# Copyright 2023 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...
40
1,178
ipython
examples/IPython Kernel/example-demo.py
.py
# -*- coding: utf-8 -*- """A simple interactive demo to illustrate the use of IPython's Demo class. Any python script can be run as a demo, but that does little more than showing it on-screen, syntax-highlighted in one shot. If you add a little simple markup, you can stop at specified intervals and return to the ipyt...
43
1,182
wandb
tests/system_tests/test_functional/keras/keras_metrics_logger_epochwise.py
.py
import numpy as np import tensorflow as tf import wandb from wandb.integration.keras import WandbMetricsLogger tf.keras.utils.set_random_seed(1234) run = wandb.init(project="keras") x = np.random.randint(255, size=(100, 28, 28, 1)) y = np.random.randint(10, size=(100,)) dataset = (x, y) def get_model(): model...
48
1,035
textual
docs/examples/guide/widgets/hello03.py
.py
from itertools import cycle from textual.app import App, ComposeResult from textual.widgets import Static hellos = cycle( [ "Hola", "Bonjour", "Guten tag", "Salve", "Nǐn hǎo", "Olá", "Asalaam alaikum", "Konnichiwa", "Anyoung haseyo", ...
48
884
beam
sdks/python/apache_beam/transforms/enrichment_it_test.py
.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
161
5,931
wagtail
wagtail/documents/tests/test_serializers.py
.py
from django.conf import settings from django.core.files.base import ContentFile from django.test import TestCase, override_settings from django.urls import reverse from wagtail.documents import models class TestCorrectDownloadUrlSerialization(TestCase): """Test asserts that in case of both `redirect` and `direct...
75
2,649
beam
sdks/python/apache_beam/examples/complete/top_wikipedia_sessions.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...
168
5,735
mlflow
mlflow/utils/environment.py
.py
import hashlib import importlib.metadata import logging import os import pathlib import re import shutil import subprocess import sys import tempfile from copy import deepcopy import yaml from packaging.requirements import InvalidRequirement, Requirement from packaging.specifiers import SpecifierSet from packaging.ver...
1,128
43,175
mlflow
tests/gateway/providers/test_tracing.py
.py
import time from typing import Any from unittest import mock import pytest import mlflow from mlflow.entities.trace_state import TraceState from mlflow.gateway.providers.base import BaseProvider, PassthroughAction from mlflow.gateway.schemas import chat, embeddings from mlflow.tracing.client import TracingClient from...
507
18,248
hatch
tests/helpers/templates/new/default.py
.py
from hatch.template import File from hatch.utils.fs import Path from ..licenses import MIT def get_files(**kwargs): description = kwargs.get("description", "") return [ File( Path("LICENSE.txt"), MIT.replace("<year>", f"{kwargs['year']}-present", 1).replace( "...
135
3,782
clearml
clearml/backend_api/services/v2_23/datasets.py
.py
""" datasets service This service provides a management interface for the datasets managed by the system. """ import six from datetime import datetime import enum from dateutil.parser import parse as parse_datetime from clearml.backend_api.session import ( Request, Response, NonStrictDataModel, schem...
8,345
273,994
astropy
astropy/timeseries/periodograms/lombscargle/setup_package.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst import os from numpy import get_include as get_numpy_include from setuptools import Extension ROOT = os.path.relpath(os.path.dirname(__file__)) def get_extensions(): ext = Extension( "astropy.timeseries.periodograms.lombscargle.implementat...
18
482
beam
sdks/python/apache_beam/io/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...
69
2,347
python-prompt-toolkit
examples/print-text/ansi.py
.py
#!/usr/bin/env python """ Demonstration of how to print using ANSI escape sequences. The advantage here is that this is cross platform. The escape sequences will be parsed and turned into appropriate Win32 API calls on Windows. """ from prompt_toolkit import print_formatted_text from prompt_toolkit.formatted_text imp...
52
1,225
hatch
src/hatch/cli/env/prune.py
.py
from __future__ import annotations from typing import TYPE_CHECKING import click if TYPE_CHECKING: from hatch.cli.application import Application @click.command(short_help="Remove all environments") @click.pass_obj def prune(app: Application): """Remove all environments.""" app.ensure_environment_plugin...
44
1,507
coveragepy
tests/mixins.py
.py
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt """ Test class mixins Some of these are transitional while working toward pure-pytest style. """ from __future__ import annotations import importlib import os ...
151
5,043
flit
flit_core/tests_core/test_build_thyself.py
.py
"""Tests of flit_core building itself""" import email.parser import os import os.path as osp import pytest import tarfile from testpath import assert_isdir, assert_isfile import zipfile from flit_core import buildapi @pytest.fixture() def cwd_project(): proj_dir = osp.dirname(osp.dirname(osp.abspath(buildapi.__fi...
65
1,818
onnxruntime
onnxruntime/test/python/transformers/test_qmoe_fp8_cuda.py
.py
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import...
252
9,576
mamba
micromamba/tests/test_prefix_interoperability.py
.py
""" Comprehensive test suite for prefix interoperability feature. This test suite verifies that mamba correctly handles pip-installed packages when prefix_data_interoperability is enabled, including: - Configuration and enabling the feature - Detecting pip packages - Removing pip packages when conda packages are insta...
694
28,024
wagtail
wagtail/snippets/tests/test_bulk_actions/test_custom_models.py
.py
from django.test import TestCase from django.urls import reverse from wagtail.test.testapp.models import Advert, FullFeaturedSnippet from wagtail.test.utils.wagtail_tests import WagtailTestUtils class TestCustomModels(WagtailTestUtils, TestCase): def setUp(self): self.user = self.login() def create_...
57
2,156