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 |
|---|---|---|---|---|---|
hatch | src/hatch/env/internal/uv.py | .py | from __future__ import annotations
from typing import Any
def get_default_config() -> dict[str, Any]:
return {
"skip-install": True,
"installer": "uv",
}
| 11 | 181 |
pyomo | pyomo/repn/tests/ampl/test_nlv2.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,889 | 88,230 |
saleor | saleor/graphql/meta/types.py | .py | import graphene
from graphene.types.generic import GenericScalar
from ...core.models import ModelWithMetadata
from ..core import ResolveInfo
from ..core.context import BaseContext
from ..core.types import NonNullList
from .resolvers import (
check_private_metadata_privilege,
resolve_metadata,
resolve_objec... | 155 | 4,711 |
biopython | Bio/ExPASy/Enzyme.py | .py | # Copyright 1999 by Jeffrey Chang. All rights reserved.
# Copyright 2009 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.
"""Parse the enzyme.dat file from E... | 160 | 4,570 |
beam | learning/katas/python/Core Transforms/Branching/Branching/task.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... | 42 | 1,593 |
hatch | tests/cli/env/test_prune.py | .py | import os
from hatch.config.constants import AppEnvVars
from hatch.project.core import Project
from hatchling.utils.constants import DEFAULT_CONFIG_FILE
def test_unknown_type(hatch, helpers, temp_dir_data, config_file):
config_file.model.template.plugins["default"]["tests"] = False
config_file.save()
pr... | 181 | 5,006 |
hatch | src/hatch/config/user.py | .py | from __future__ import annotations
from typing import cast
from hatch.config.model import RootConfig
from hatch.utils.fs import Path
from hatch.utils.toml import load_toml_data
class ConfigFile:
def __init__(self, path: Path | None = None):
self._path: Path | None = path
self.model = cast(RootCo... | 68 | 1,655 |
mkdocs | mkdocs/tests/config/config_tests.py | .py | #!/usr/bin/env python
import os
import unittest
import mkdocs
from mkdocs import config
from mkdocs.config import config_options as c
from mkdocs.config import defaults
from mkdocs.config.base import ValidationError
from mkdocs.exceptions import ConfigurationError
from mkdocs.localization import parse_locale
from mkd... | 273 | 11,000 |
openvino | tests/layer_tests/pytorch_tests/test_rand.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
from pytorch_layer_test_class import PytorchLayerTest
# Random ops produce different outputs on each trace run, so the tracer always
# warns that the traced output doesn't match the Python function output.
# ... | 150 | 5,576 |
conda | tests/models/test_prefix_graph.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
import time
import warnings
from functools import cache
from pprint import pprint
import pytest
from pytest import MonkeyPatch
import conda.models.prefix_graph
from conda.base.context import context, reset_context
from conda.exceptions import ... | 1,026 | 27,348 |
black | tests/data/cases/pep_654.py | .py | # flags: --minimum-version=3.11
try:
raise OSError("blah")
except* ExceptionGroup as e:
pass
try:
async with trio.open_nursery() as nursery:
# Make two concurrent calls to child()
nursery.start_soon(child)
nursery.start_soon(child)
except* ValueError:
pass
try:
try:
... | 55 | 1,004 |
wandb | tests/system_tests/test_core/test_wandb_init.py | .py | import json
import os
import re
from pathlib import Path
from unittest import mock
import pytest
import wandb
from wandb.errors import AuthenticationError, CommError
from wandb.sdk.lib import runid
from tests.fixtures.wandb_backend_spy import WandbBackendSpy
def test_init_timeout__prints_retry_err(wandb_backend_spy... | 195 | 6,035 |
openvino | src/bindings/python/src/openvino/helpers/__init__.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# flake8: noqa
from openvino.helpers.packing import pack_data, unpack_data
| 7 | 159 |
deap | examples/gp/multiplexer.py | .py | # This file is part of EAP.
#
# EAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# EAP is distributed in ... | 100 | 3,295 |
saleor | saleor/graphql/order/mutations/order_cancel.py | .py | import graphene
from django.core.exceptions import ValidationError
from ....core.tracing import traced_atomic_transaction
from ....giftcard.utils import deactivate_order_gift_cards
from ....order import models
from ....order.actions import cancel_order
from ....order.error_codes import OrderErrorCode
from ....permissi... | 68 | 2,447 |
wandb | wandb/sdk/artifacts/_generated/run_output_artifacts.py | .py | # Generated by ariadne-codegen
# Source: tools/graphql_codegen/artifacts/
from __future__ import annotations
from pydantic import Field
from wandb._pydantic import GQLResult
from .fragments import ArtifactFragment, PageInfoFragment
class RunOutputArtifacts(GQLResult):
project: RunOutputArtifactsProject | None... | 40 | 1,080 |
mlflow | mlflow/server/auth/__main__.py | .py | from mlflow.server.auth.cli import commands
if __name__ == "__main__":
commands()
| 5 | 87 |
sphinx | tests/roots/test-versioning/conf.py | .py | project = 'versioning test root'
source_suffix = {
'.txt': 'restructuredtext',
}
exclude_patterns = ['_build']
| 6 | 115 |
probability | tensorflow_probability/python/distributions/matrix_normal_linear_operator_test.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... | 245 | 9,950 |
mlflow | tests/tracking/test_model_registry.py | .py | import time
from pathlib import Path
import pytest
from mlflow import MlflowClient
from mlflow.entities.model_registry import ModelVersion, RegisteredModel
from mlflow.exceptions import MlflowException
from mlflow.server import handlers
from mlflow.server.fastapi_app import app
from mlflow.server.handlers import init... | 691 | 29,107 |
hatch | tests/helpers/templates/wheel/standard_default_symlink.py | .py | from hatch.template import File
from hatch.utils.fs import Path
from hatchling.__about__ import __version__
from hatchling.metadata.spec import DEFAULT_METADATA_VERSION
from ..new.feature_no_src_layout import get_files as get_template_files
from .utils import update_record_file_contents
def get_files(**kwargs):
... | 51 | 1,357 |
pyro | pyro/contrib/funsor/handlers/named_messenger.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from collections import OrderedDict
from contextlib import ExitStack
from pyro.contrib.funsor.handlers.runtime import (
_DIM_STACK,
DimRequest,
DimType,
StackFrame,
)
from pyro.poutine.reentrant_messenger import Reentr... | 201 | 7,623 |
coveragepy | tests/modules/covmod1.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
# covmod1.py: Simplest module for testing.
i = 1
i += 1
| 7 | 214 |
django-cms | cms/tests/test_page_admin.py | .py | import datetime
import json
import re
import sys
from unittest import skipUnless
from unittest.mock import patch
from django.conf import settings
from django.contrib import admin
from django.contrib.sites.models import Site
from django.core.cache import cache
from django.db import IntegrityError, connection, transacti... | 5,343 | 223,014 |
mlflow | dev/clint/src/clint/rules/os_environ_delete_in_test.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class OsEnvironDeleteInTest(Rule):
def _message(self) -> str:
return (
"Do not delete `os.environ` in test directly (del os.environ[...] or "
"os.environ.pop(...)). Use `monkeypatch.delenv` "
... | 31 | 1,148 |
rq | rq/registry.py | .py | from __future__ import annotations
import calendar
import logging
import time
import warnings
from collections.abc import Sequence
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any, cast
from redis.exceptions import WatchError
from rq.serializers import resolve_serializer
from... | 744 | 30,286 |
sqlmap | plugins/dbms/db2/syntax.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from lib.core.convert import getBytes
from lib.core.settings import UNICODE_ENCODING
from plugins.generic.syntax import Syntax as GenericSyntax
class Syntax(GenericSyntax):
@... | 31 | 1,109 |
mlflow | mlflow/system_metrics/metrics/cpu_monitor.py | .py | """Class for monitoring CPU stats."""
import psutil
from mlflow.system_metrics.metrics.base_metrics_monitor import BaseMetricsMonitor
class CPUMonitor(BaseMetricsMonitor):
"""Class for monitoring CPU stats."""
def collect_metrics(self):
# Get CPU metrics.
cpu_percent = psutil.cpu_percent()
... | 24 | 776 |
wagtail | wagtail/contrib/redirects/tests/test_signal_handlers.py | .py | from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from wagtail.contrib.frontend_cache.tests import PURGED_URLS
from wagtail.contrib.redirects.models import Redirect
from wagtail.coreutils import get_dummy_request
from wagtail.models import Site
from wagtail.test.routabl... | 242 | 9,044 |
readthedocs.org | readthedocs/config/validation.py | .py | """Validations for the RTD configuration file."""
import os
from .exceptions import ConfigValidationError
def validate_list(value):
"""Check if ``value`` is an iterable."""
if isinstance(value, (dict, str)):
raise ConfigValidationError(
message_id=ConfigValidationError.INVALID_LIST,
... | 120 | 3,427 |
saleor | saleor/graphql/attribute/unions.py | .py | import graphene
from ...page import models as page_models
from ...product import models as product_models
from ..core import ResolveInfo
from ..page.types import PageType
from ..product.types import ProductType
class ReferenceType(graphene.Union):
class Meta:
description = (
"The reference ty... | 29 | 990 |
coremltools | coremltools/converters/mil/mil/types/type_state.py | .py | # Copyright (c) 2024, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from coremltools.converters.mil.mil.types.get_type_info import get_type_info
from coremltools.convert... | 49 | 1,164 |
wandb | tests/system_tests/test_functional/lightning/strategy_ddp.py | .py | import lightning as pl
from base import BoringModel, RandomDataset # type: ignore
from lightning.pytorch.loggers import WandbLogger
from torch.utils.data import DataLoader
def main():
# Set up data
num_samples = 1000
train = RandomDataset(32, num_samples)
train = DataLoader(train, batch_size=32)
... | 42 | 1,063 |
metrics | tests/unittests/text/test_edit.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... | 148 | 5,499 |
python-prompt-toolkit | src/prompt_toolkit/layout/controls.py | .py | """
User interface Controls for the layout.
"""
from __future__ import annotations
import time
from abc import ABCMeta, abstractmethod
from collections.abc import Callable, Hashable, Iterable
from typing import TYPE_CHECKING, NamedTuple
from prompt_toolkit.application.current import get_app
from prompt_toolkit.buffe... | 958 | 36,020 |
pdm | src/pdm/cli/commands/import_cmd.py | .py | from __future__ import annotations
import argparse
from pdm.cli.commands.base import BaseCommand
from pdm.exceptions import PdmUsageError
from pdm.formats import FORMATS
from pdm.project import Project
class Command(BaseCommand):
"""Import project metadata from other formats"""
name = "import"
def add... | 106 | 4,328 |
pyfilesystem2 | fs/mode.py | .py | """Abstract I/O mode container.
Mode strings are used in in `~fs.base.FS.open` and
`~fs.base.FS.openbin`.
"""
from __future__ import print_function, unicode_literals
import typing
import six
from ._typing import Text
if typing.TYPE_CHECKING:
from typing import FrozenSet, Set, Union
__all__ = ["Mode", "chec... | 239 | 6,220 |
textual | tests/tree/test_tree_node_label.py | .py | from rich.text import Text
from textual.widgets import Tree
from textual.widgets.tree import TreeNode
async def test_tree_node_label() -> None:
"""It should be possible to modify a TreeNode's label."""
node = TreeNode(Tree[None]("Xenomorph Lifecycle"), None, 0, "Facehugger")
assert node.label == Text("Fa... | 22 | 750 |
readthedocs.org | readthedocs/rtd_tests/tests/test_oauth_tasks.py | .py | from unittest.mock import patch
from allauth.socialaccount.models import SocialAccount
from allauth.socialaccount.providers.bitbucket_oauth2.views import (
BitbucketOAuth2Adapter,
)
from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter
from allauth.socialaccount.providers.gitlab.views import... | 195 | 7,849 |
mlflow | dev/clint/src/clint/rules/redundant_test_docstring.py | .py | """Rule to detect redundant docstrings in test files.
This rule flags:
- ALL single-line docstrings in test functions and classes (multi-line
function/class docstrings are allowed since they generally provide
meaningful context).
- ALL module-level docstrings in test files (single- or multi-line).
"""
import ast
... | 65 | 2,096 |
beam | sdks/python/apache_beam/testing/analyzers/perf_analysis_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... | 390 | 13,828 |
beam | sdks/python/apache_beam/dataframe/schemas_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... | 355 | 12,654 |
saleor | saleor/core/tests/test_anonymize.py | .py | from ..anonymize import obfuscate_address, obfuscate_email, obfuscate_string
def test_obfuscate_email():
# given
email = "abc@gmail.com"
# when
result = obfuscate_email(email)
# then
assert result == "a...@gmail.com"
def test_obfuscate_email_example_email():
# given
email = "abc@ex... | 98 | 1,999 |
conda | conda/common/serialize/json.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""JSON serialization utilities for conda."""
from __future__ import annotations
import json # noqa: TID251
from enum import Enum
from pathlib import Path
from typing import TYPE_CHECKING, overload
from frozendict import frozendict
if TYPE_... | 123 | 2,706 |
gunicorn | tests/requests/invalid/chunked_08.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.http.errors import InvalidHeader
request = InvalidHeader
| 7 | 177 |
astropy | astropy/cosmology/_src/traits/darkenergy.py | .py | __all__ = ("DarkEnergyComponent",)
from abc import abstractmethod
from math import exp, log
import numpy as np
from numpy.typing import ArrayLike
from astropy.cosmology._src.scipy_compat import quad
from astropy.cosmology._src.typing import FArray
from astropy.cosmology._src.utils import aszarr
from astropy.units im... | 154 | 5,274 |
sqlmap | tests/test_utils.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
Core utility helpers: constant-time compare, numeric checks, safe formatting,
list/value normalization, randomness generators.
"""
import os
import sys
import unittest
sys.path.inse... | 118 | 4,905 |
loguru | tests/exceptions/source/others/syntaxerror_without_traceback.py | .py | import sys
from loguru import logger
def test(diagnose, backtrace):
logger.remove()
logger.add(sys.stderr, format="", diagnose=diagnose, backtrace=backtrace, colorize=True)
try:
exec("foo =")
except SyntaxError:
type_, value, _ = sys.exc_info()
logger.opt(exception=(type_, va... | 21 | 416 |
conda | conda/gateways/anaconda_client.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Anaconda-client (binstar) token management for CondaSession."""
import os
import re
from logging import getLogger
from os.path import isdir, isfile, join
from stat import S_IREAD, S_IWRITE
from platformdirs import user_config_dir
from ..co... | 69 | 1,893 |
pyro | tests/integration_tests/conftest.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import pytest
def pytest_collection_modifyitems(items):
for item in items:
if item.nodeid.startswith("tests/integration_tests"):
if "stage" not in item.keywords:
item.add_marker(pytest.mark... | 14 | 451 |
textual | src/textual/walk.py | .py | """
Functions for *walking* the DOM.
!!! note
For most purposes you would be better off using [query][textual.dom.DOMNode.query], which uses these functions internally.
"""
from __future__ import annotations
from collections import deque
from operator import attrgetter
from typing import TYPE_CHECKING, Iterable... | 224 | 6,206 |
saleor | saleor/graphql/product/mutations/collection/collection_add_products.py | .py | import graphene
from .....core.tracing import traced_atomic_transaction
from .....discount.utils.promotion import mark_active_catalogue_promotion_rules_as_dirty
from .....permission.enums import ProductPermissions
from .....product import models
from ....core import ResolveInfo
from ....core.context import ChannelCont... | 65 | 2,476 |
onnxruntime | orttraining/tools/scripts/layer_norm_transform.py | .py | import os.path
import sys
import numpy as np
import onnx
from onnx import * # noqa: F403
def find_node(graph_proto, op_type):
nodes = []
map_input_node = {}
for node in graph_proto.node:
if node.op_type == op_type:
node_input = node.input[1] if op_type == "Div" or op_type == "Mul" el... | 187 | 6,953 |
cvxpy | cvxpy/reductions/complex2real/canonicalizers/param_canon.py | .py | """
Copyright 2013 Steven Diamond
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software... | 28 | 860 |
openvino | src/bindings/python/tests/test_graph/test_ops_scatter_nd_update.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
from openvino import PartialShape, Type
from openvino import opset4, opset15
scatter_version_opset = pytest.mark.parametrize("opset", [opset4, opset15])
@scatter_version_opset
... | 232 | 8,839 |
openvino | src/bindings/python/src/openvino/op/util/__init__.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""
Package: openvino.op.util
Low level wrappers for the c++ api in ov::op::util.
"""
# flake8: noqa
from openvino._pyopenvino.op.util import UnaryElementwiseArithmetic
from openvino._pyopenvino.op.util import BinaryElementwiseCompariso... | 23 | 1,000 |
openvino | src/frontends/tensorflow_lite/tests/test_models/gen_scripts/generate_malformed_tensor_name.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# Generate a crafted .tflite model whose Tensor.name field is absent.
#
# In the FlatBuffer schema for TensorFlow Lite, every table field is implicitly
# optional - the field is absent when its vtable slot offset is 0. The schema-
# gene... | 178 | 6,886 |
pyro | pyro/ops/integrator.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import warnings
from typing import Callable, Dict
from torch.autograd import grad
# Registry for exception handlers that can be used to catch certain failures
# during computation of `potential_fn` within `potential_grad`.
_EXCEP... | 130 | 5,119 |
loguru | tests/exceptions/source/modern/match_statement.py | .py | # fmt: off
import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True)
def case(x):
y = 1
match y / 0:
case 1:
pass
def match(x):
y = 1
match x:
case y: case(x)
with logger.catch():
match(1)
| 22 | 318 |
biopython | Tests/test_PDB_StructureAlignment.py | .py | # Copyright 2017 by Francesco Gastaldello. All rights reserved.
#
# Converted by Francesco Gastaldello from an older unit test copyright 2004
# by Thomas Hamelryck.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Ple... | 228 | 8,861 |
saleor | saleor/checkout/tests/webhooks/static_payloads/test_exclude_shipping.py | .py | import json
from decimal import Decimal
import graphene
from measurement.measures import Weight
from prices import Money
from .....shipping.interface import ShippingMethodData
from ....webhooks.exclude_shipping import (
_generate_excluded_shipping_methods_for_checkout_payload,
)
def test_generate_excluded_shipp... | 73 | 2,127 |
black | tests/data/cases/if_guard_inside_case.py | .py | # flags: --preview
def f(x):
match x:
# good refactor
case [
y
] if y == 123:
pass
case [
y
] if True:
pass
case [
y,
] if True:
pass
# bad refactor
case [
... | 50 | 675 |
onnx | onnx/fuzz/fuzz_parser.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import sys
import atheris
with atheris.instrument_imports():
from onnx import parser
def TestOneInput(data):
try:
text = data.decode("utf-8", "surrogatepass")
parser.parse_mode... | 29 | 538 |
jupytext | tests/functional/contents_manager/test_async_and_sync_contents_manager_are_in_sync.py | .py | from pathlib import Path
import pytest
from black import FileMode, format_str
from jupytext.async_contentsmanager import __file__ as async_contentsmanager_file
from jupytext.async_pairs import __file__ as async_pairs_file
from jupytext.sync_contentsmanager import __file__ as sync_contentsmanager_file
from jupytext.sy... | 56 | 1,846 |
mlflow | mlflow/genai/scorers/deepeval/utils.py | .py | """Utility functions and constants for DeepEval integration."""
from __future__ import annotations
from typing import Any
from mlflow.entities.span import SpanAttributeKey, SpanType
from mlflow.entities.trace import Trace
from mlflow.exceptions import MlflowException
from mlflow.genai.utils.trace_utils import (
... | 227 | 7,541 |
biopython | Tests/test_geo.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.
#
"""Tests the basic functionality of the GEO parsers."""
import unittest
from Bio import Geo
class TestGeo(unittest.TestCase):
def test_soft_e... | 4,988 | 289,276 |
hydra | tests/instantiate/module_shadowed_by_function.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
def a_function() -> None:
pass
| 4 | 106 |
beam | sdks/python/apache_beam/ml/transforms/embeddings/__init__.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... | 22 | 948 |
python-prompt-toolkit | examples/choices/many-choices.py | .py | from __future__ import annotations
from prompt_toolkit.shortcuts import choice
def main() -> None:
result = choice(
message="Please select an option:",
options=[(i, f"Option {i}") for i in range(1, 100)],
)
print(result)
if __name__ == "__main__":
main()
| 16 | 292 |
onnxruntime | orttraining/orttraining/python/training/_utils.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import importlib.util
import os
import sys
import numpy as np
import to... | 205 | 6,553 |
mlflow | tests/utils/test_requirements_utils.py | .py | import importlib
import os
import sys
from importlib.metadata import version
from unittest import mock
import cloudpickle
import importlib_metadata
import pytest
import mlflow
import mlflow.utils.requirements_utils
from mlflow.exceptions import MlflowException
from mlflow.utils.environment import infer_pip_requiremen... | 779 | 28,482 |
scikit-bio | skbio/diversity/alpha/tests/test_lladser.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.
# --------------------------------------------... | 236 | 8,608 |
clearml | clearml/backend_api/services/v2_13/models.py | .py | """
models service
This service provides a management interface for models (results of training tasks) stored in the system.
"""
from typing import List, Optional, Any
from datetime import datetime
import six
from clearml.backend_api.session import (
Request,
Response,
NonStrictDataModel,
schema_proper... | 4,048 | 137,000 |
onnx | onnx/reference/ops/op_average_pool.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from onnx.reference.ops.op_pool_common import CommonPool
class AveragePool_1(CommonPool):
def _run(
self,
x,
auto_pad=None,
ceil_mode=None,
kernel_shape=None... | 108 | 2,349 |
openvino | src/bindings/python/tests/test_graph/test_identity.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
from openvino.opset15 import parameter
from openvino.opset16 import identity
from openvino import PartialShape, Type
@pytest.mark.parametrize(
("input_shape", "expected_outp... | 32 | 1,021 |
wagtail | wagtail/documents/urls.py | .py | from django.urls import path, re_path
from wagtail.documents.views import serve
urlpatterns = [
re_path(r"^(\d+)/(.*)$", serve.serve, name="wagtaildocs_serve"),
path(
"authenticate_with_password/<int:restriction_id>/",
serve.authenticate_with_password,
name="wagtaildocs_authenticate_wi... | 13 | 343 |
saleor | saleor/product/management/commands/update_all_products_discounted_prices.py | .py | import logging
from django.core.management.base import BaseCommand
from ...models import Product
from ...utils.variant_prices import update_discounted_prices_for_promotion
logger = logging.getLogger(__name__)
DISCOUNTED_PRODUCT_BATCH = 500
class Command(BaseCommand):
help = "Recalculates the discounted prices... | 43 | 1,272 |
conda | tests/plugins/subcommands/doctor/health_checks/test_pinned.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Tests for the pinned file format health check."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from conda.base.constants import OK_MARK, PREFIX_PINNED_FILE, X_MARK
if TYPE_CHECKING:
from conda.tes... | 39 | 1,043 |
saleor | saleor/payment/tests/fixtures/gateway_config.py | .py | import pytest
from ....payment.interface import GatewayConfig
@pytest.fixture
def dummy_gateway_config():
return GatewayConfig(
gateway_name="Dummy",
auto_capture=True,
supported_currencies="USD",
connection_params={"secret-key": "nobodylikesspanishinqusition"},
)
| 14 | 308 |
pyomo | pyomo/contrib/pynumero/algorithms/solvers/tests/test_implicit_functions.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... | 363 | 13,203 |
mlflow | dev/clint/src/clint/rules/subprocess_check_call.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class SubprocessCheckCall(Rule):
def _message(self) -> str:
return (
"Use `subprocess.check_call(...)` instead of `subprocess.run(..., check=True)` "
"for better readability. Only applies when check=T... | 44 | 1,269 |
sphinx | tests/roots/test-ext-autosummary-skip-member/conf.py | .py | import sys
from pathlib import Path
sys.path.insert(0, str(Path.cwd().resolve()))
extensions = ['sphinx.ext.autosummary']
autosummary_generate = True
autodoc_default_options = {'members': True}
def skip_member(app, what, name, obj, skip, options):
if name == 'skipmeth':
return True
elif name == '_pr... | 21 | 439 |
jupytext | src/jupytext/quarto.py | .py | """Jupyter notebook to Quarto Markdown and back, using 'quarto convert'"""
import json
import os
import shutil
import subprocess
import sys
import tempfile
# Copy nbformat reads and writes to avoid them being patched in the contents manager!!
from nbformat import reads as ipynb_reads
from nbformat import writes as ip... | 164 | 5,995 |
textual | docs/examples/events/custom01.py | .py | from textual.app import App, ComposeResult
from textual.color import Color
from textual.message import Message
from textual.widgets import Static
class ColorButton(Static):
"""A color button."""
class Selected(Message):
"""Color selected message."""
def __init__(self, color: Color) -> None:
... | 49 | 1,423 |
saleor | saleor/invoice/events.py | .py | from ..account.models import User
from ..app.models import App
from ..order.models import Order
from .models import Invoice, InvoiceEvent, InvoiceEvents
def invoice_requested_event(
*, user: User | None, app: App | None, order: Order, number: str | None
) -> InvoiceEvent:
return InvoiceEvent.objects.create(
... | 69 | 1,751 |
coremltools | coremltools/optimize/torch/palettization/_utils.py | .py | # Copyright (c) 2024, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from typing import Tuple as _Tuple
import torch as _torch
import torch.distributed as _dist
def ve... | 85 | 3,096 |
probability | tensorflow_probability/python/util/deferred_tensor.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... | 1,009 | 37,379 |
readthedocs.org | readthedocs/api/v2/models.py | .py | from datetime import timedelta
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from rest_framework_api_key.models import AbstractAPIKey
from rest_framework_api_key.models import BaseAPIKeyManager
from readthedocs.projects.models import Project
cl... | 67 | 2,370 |
coremltools | coremltools/converters/mil/mil/types/type_unknown.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 .type_spec import Type
class unknown:
"""
unknown is basically Any type.
"""
... | 20 | 468 |
beam | sdks/python/apache_beam/transforms/enrichment_handlers/vertex_ai_feature_store_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... | 311 | 11,252 |
onnx | tests/python/schema_test.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import contextlib
from typing import TYPE_CHECKING
import pytest
import onnx
from onnx import defs
if TYPE_CHECKING:
from collections.abc import Sequence
class TestSchema:
def test_get_schem... | 569 | 21,461 |
beam | learning/katas/python/Introduction/Hello Beam/Hello Beam/task.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"); y... | 35 | 1,208 |
mlflow | tests/genai/judges/adapters/test_databricks_managed_adapter.py | .py | import json
from unittest import mock
import pytest
from mlflow.entities.trace import Trace
from mlflow.entities.trace_info import TraceInfo
from mlflow.entities.trace_location import TraceLocation
from mlflow.entities.trace_state import TraceState
from mlflow.exceptions import MlflowException
from mlflow.genai.judge... | 679 | 23,436 |
conda | tests/shell/test_xonsh.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from conda import __version__ as CONDA_VERSION
from conda.common.compat import on_win
if TYPE_CHECKING:
from . import Shell
pytestmark = [
pytest.mark... | 53 | 1,426 |
clearml | clearml/backend_interface/datasets/__init__.py | .py | """Backend dataset helpers for HyperDatasets."""
from .hyper_dataset import HyperDatasetManagementBackend
from .hyper_dataset_data_view import DataViewManagementBackend
__all__ = [
"HyperDatasetManagementBackend",
"DataViewManagementBackend",
]
| 10 | 255 |
onnxruntime | tools/python/compare_node_test_corpora.py | .py | #!/usr/bin/env python
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Byte-equivalence comparator for ONNX node-test corpora.
This is the CANONICAL, build-wired equivalence check (the ``onnx_node_tests_equivalence``
ctest invokes it): it compares an ALREADY-materialize... | 104 | 4,183 |
hypercorn | src/hypercorn/protocol/events.py | .py | from __future__ import annotations
from dataclasses import dataclass
from hypercorn.typing import ConnectionState
@dataclass(frozen=True)
class Event:
stream_id: int
@dataclass(frozen=True)
class Request(Event):
headers: list[tuple[bytes, bytes]]
http_version: str
method: str
raw_path: bytes
... | 66 | 1,143 |
wagtail | wagtail/admin/api/actions/base.py | .py | class APIAction:
serializer = None
def __init__(self, view, request):
self.view = view
self.request = request
| 7 | 135 |
pyomo | pyomo/contrib/mindtpy/tests/nonconvex2.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... | 96 | 3,485 |
wandb | wandb/sdk/artifacts/_generated/registry_user_members.py | .py | # Generated by ariadne-codegen
# Source: tools/graphql_codegen/artifacts/
from __future__ import annotations
from wandb._pydantic import GQLResult
from .fragments import UserRegistryMemberFragment
class RegistryUserMembers(GQLResult):
project: RegistryUserMembersProject | None
class RegistryUserMembersProjec... | 21 | 461 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.