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 |
|---|---|---|---|---|---|
mlflow | tests/genai/simulators/test_utils.py | .py | from unittest import mock
import pytest
from mlflow.genai.simulators.utils import (
format_history,
get_default_simulation_model,
invoke_model_without_tracing,
)
@pytest.mark.parametrize(
("history", "expected"),
[
([], None),
([{"role": "user", "content": "Hello"}], "user: Hello... | 108 | 3,451 |
mlflow | mlflow/dspy/autolog.py | .py | import logging
from packaging.version import Version
import mlflow
from mlflow.dspy.constant import FLAVOR_NAME
from mlflow.telemetry.events import AutologgingEvent
from mlflow.telemetry.track import _record_event
from mlflow.tracing.provider import trace_disabled
from mlflow.tracing.utils import construct_full_input... | 280 | 11,171 |
beam | sdks/python/apache_beam/io/components/rate_limit_pb2.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... | 64 | 3,989 |
bazel | third_party/py/mock/tests/testcallable.py | .py | # Copyright (C) 2007-2012 Michael Foord & the mock team
# E-mail: fuzzyman AT voidspace DOT org DOT uk
# http://www.voidspace.org.uk/python/mock/
from tests.support import is_instance, unittest2, X, SomeClass
from mock import (
Mock, MagicMock, NonCallableMagicMock,
NonCallableMock, patch, create_autospec,
... | 159 | 4,477 |
readthedocs.org | readthedocs/embed/v3/tests/test_access.py | .py | from contextlib import contextmanager
from unittest import mock
import pytest
from corsheaders.middleware import ACCESS_CONTROL_ALLOW_ORIGIN
from django.contrib.auth.models import User
from django.test import TestCase, override_settings
from django.urls import reverse
from django_dynamic_fixture import get
from readt... | 128 | 4,568 |
pyomo | pyomo/repn/tests/test_parameterized_linear.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... | 542 | 20,790 |
mlflow | dev/clint/src/clint/rules/do_not_disable.py | .py | from typing_extensions import Self
from clint.rules.base import Rule
class DoNotDisable(Rule):
RULES = {
"B006": "Use None as default and set value in function body instead of mutable defaults",
"F821": "Use typing.TYPE_CHECKING for forward references to optional dependencies",
}
def __i... | 30 | 937 |
wagtail | wagtail/snippets/tests/test_locking.py | .py | from django.contrib.admin.utils import quote
from django.contrib.auth import get_permission_codename
from django.contrib.auth.models import Group, Permission
from django.test import TestCase, override_settings
from django.urls import NoReverseMatch, reverse
from django.utils import timezone
from wagtail.admin.utils im... | 762 | 26,280 |
pyomo | examples/pyomobook/overview-ch/var_obj_con_snippet.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... | 25 | 950 |
saleor | saleor/graphql/app/utils.py | .py | from django.core.exceptions import ValidationError
from ...app.models import App
from ...permission.enums import AppPermission
from ..account.utils import get_out_of_scope_permissions
from ..core.enums import AppErrorCode
from ..utils import requestor_is_superuser
def ensure_can_manage_permissions(requestor, permiss... | 66 | 2,287 |
pyomo | examples/pyomo/concrete/knapsack-concrete.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... | 30 | 1,008 |
probability | tensorflow_probability/python/experimental/mcmc/kernel_outputs.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... | 110 | 3,699 |
pyomo | doc/OnlineDocs/src/data/param6a.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... | 35 | 1,148 |
biopython | Bio/Geo/__init__.py | .py | # Copyright 2001 by Katharine Lindner. All rights reserved.
# Copyright 2006 by PeterC. All rights reserved.
# Copyright 2007 by Michiel de Hoon. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part... | 68 | 2,176 |
hatch | src/hatch/project/frontend/core.py | .py | from __future__ import annotations
import json
from functools import cache
from typing import TYPE_CHECKING, Any, Literal
from hatch.utils.fs import Path
from hatch.utils.runner import ExecutionContext
if TYPE_CHECKING:
from hatch.env.plugin.interface import EnvironmentInterface
from hatch.project.core impor... | 327 | 12,582 |
sphinx | sphinx/ext/autodoc/_dynamic/_loader.py | .py | """Object loader for autodoc"""
from __future__ import annotations
import re
from inspect import Parameter
from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING, NewType, TypeVar
from sphinx.ext.autodoc._dynamic._docstrings import (
_docstring_lines_for_props,
_get_docst... | 503 | 17,547 |
mlflow | tests/genai/scorers/trulens/test_registry.py | .py | import pytest
from mlflow.genai.scorers.trulens.registry import get_argument_mapping, get_feedback_method_name
@pytest.mark.parametrize(
("metric_name", "expected_method"),
[
("Groundedness", "groundedness_measure_with_cot_reasons"),
("ContextRelevance", "context_relevance_with_cot_reasons"),... | 41 | 1,491 |
pyro | pyro/distributions/testing/__init__.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
This module contains tools for testing new distributions and distributions for
testing new Pyro inference algorithms.
"""
| 8 | 215 |
onnxruntime | onnxruntime/python/tools/transformers/convert_generation.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# -------------------------------------------------------------------------
"""
This converts GPT2 or T5 model to onnx with beam search operator.
Exa... | 3,607 | 141,487 |
onnxruntime | onnxruntime/python/tools/quantization/static_quantize_runner.py | .py | import argparse
import json
import os
import numpy as np
import onnx
import onnxruntime
from onnxruntime.quantization import QuantFormat, QuantType, StaticQuantConfig, quantize
from onnxruntime.quantization.calibrate import CalibrationDataReader, CalibrationMethod
class OnnxModelCalibrationDataReader(CalibrationDat... | 257 | 11,085 |
saleor | saleor/graphql/payment/mutations/transaction/transaction_process.py | .py | from typing import TYPE_CHECKING, cast
import graphene
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db.models import QuerySet
from .....app.models import App
from .....channel import TransactionFlowStrategy
from .....channel.models import Channel
from .....checkout i... | 247 | 9,472 |
textual | src/textual/markup.py | .py | """
Utilities related to content markup.
"""
from __future__ import annotations
from operator import itemgetter
from textual.css.parse import substitute_references
from textual.css.tokenizer import UnexpectedEnd
__all__ = ["MarkupError", "escape", "to_content"]
import re
from string import Template
from typing im... | 464 | 13,404 |
cvxpy | cvxpy/reductions/eliminate_pwl/canonicalizers/cummax_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... | 44 | 1,349 |
funcy | funcy/funcs.py | .py | from operator import __not__
from functools import partial, reduce, wraps
from ._inspect import get_spec, Spec
from .primitives import EMPTY
from .funcmakers import make_func, make_pred
__all__ = ['identity', 'constantly', 'caller',
# reexport functools for convenience
'reduce', 'partial',
... | 138 | 4,403 |
saleor | saleor/webhook/const.py | .py | WEBHOOK_CACHE_DEFAULT_TTL: int = 5 * 60 # 5 minutes
SYNC_WEBHOOK_FAILURE_CACHE_TTL: int = 1 # 1 second
SYNC_WEBHOOK_FAILURE_SENTINEL = (
"WEBHOOK_FAILURE" # Arbitrary value to indicate webhook failure in cache
)
APP_ID_PREFIX = "app"
MAX_FILTERABLE_CHANNEL_SLUGS_LIMIT = 500
| 9 | 283 |
openvino | tests/layer_tests/pytorch_tests/test_nms.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import platform
import pytest
from pytorch_layer_test_class import PytorchLayerTest
import numpy as np
import torch
import torchvision
@pytest.mark.parametrize('boxes_num', (1, 2, 3, 4, 5))
class TestNms(PytorchLayerTest):
def _p... | 44 | 1,547 |
pdm | src/pdm/pytest.py | .py | """
Some reusable fixtures for `pytest`.
+++ 2.4.0
To enable them in your test, add `pdm.pytest` as a plugin.
You can do so in your root `conftest.py`:
```python title="conftest.py"
# single plugin
pytest_plugins = "pytest.plugin"
# many plugins
pytest_plugins = [
...
"pdm.pytest",
...
]
```
"""
from _... | 676 | 21,315 |
pyomo | pyomo/contrib/viewer/tests/test_data_model_item.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... | 253 | 10,486 |
wandb | wandb/apis/_generated/get_viewer.py | .py | # Generated by ariadne-codegen
# Source: tools/graphql_codegen/api/
from __future__ import annotations
from wandb._pydantic import GQLResult
from .fragments import UserFragment
class GetViewer(GQLResult):
viewer: UserFragment | None
GetViewer.model_rebuild()
| 16 | 270 |
returns | tests/test_primitives/test_container/test_base_container/test_pickle.py | .py | import pickle # noqa: S403
from typing import Any
from hypothesis import example, given
from hypothesis import strategies as st
from returns.primitives.container import BaseContainer
class _CustomClass:
def __init__(self, inner_value: Any) -> None:
self.inner_value = inner_value
def __eq__(self, o... | 40 | 1,044 |
mlflow | tests/gateway/providers/test_ollama.py | .py | from unittest import mock
import pytest
from fastapi.encoders import jsonable_encoder
from mlflow.gateway.config import EndpointConfig
from mlflow.gateway.providers.ollama import OllamaConfig, OllamaProvider
from mlflow.gateway.schemas import chat, embeddings
from tests.gateway.tools import MockAsyncResponse, mock_h... | 119 | 3,430 |
metrics | tests/unittests/bases/test_aggregation.py | .py | import numpy as np
import pytest
import torch
from torchmetrics import Metric
from torchmetrics.aggregation import CatMetric, MaxMetric, MeanMetric, MinMetric, SumMetric
from torchmetrics.collections import MetricCollection
from unittests import BATCH_SIZE, NUM_BATCHES
from unittests._helpers.testers import MetricTest... | 233 | 8,476 |
mkdocs | mkdocs/tests/livereload_tests.py | .py | #!/usr/bin/env python
import contextlib
import email
import io
import sys
import threading
import time
import unittest
from pathlib import Path
from unittest import mock
from mkdocs.livereload import LiveReloadServer
from mkdocs.tests.base import change_dir, tempdir
class FakeRequest:
def __init__(self, content... | 627 | 24,723 |
mlflow | mlflow/prompt/constants.py | .py | # A special tag in RegisteredModel to indicate that it is a prompt
import re
IS_PROMPT_TAG_KEY = "mlflow.prompt.is_prompt"
# A special tag in ModelVersion to store the prompt text
PROMPT_TEXT_TAG_KEY = "mlflow.prompt.text"
# Unity Catalog tags cannot contain dots
PROMPT_TYPE_TAG_KEY = "_mlflow_prompt_type"
RESPONSE_F... | 32 | 1,136 |
mlflow | mlflow/deployments/server/constants.py | .py | MLFLOW_DEPLOYMENTS_HEALTH_ENDPOINT = "/health"
MLFLOW_DEPLOYMENTS_CRUD_ENDPOINT_BASE = "/api/2.0/endpoints/"
MLFLOW_DEPLOYMENTS_LIMITS_BASE = "/api/2.0/endpoints/limits/"
MLFLOW_DEPLOYMENTS_ENDPOINTS_BASE = "/endpoints/"
MLFLOW_DEPLOYMENTS_QUERY_SUFFIX = "/invocations"
MLFLOW_DEPLOYMENTS_LIST_ENDPOINTS_PAGE_SIZE = 3000... | 7 | 321 |
probability | tensorflow_probability/python/distributions/generalized_normal.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... | 289 | 11,539 |
conda | conda/_private/exception_guidance.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Structured error guidance for user-facing error messages.
``ErrorGuidance`` can be attached to ``conda.CondaError`` via the ``guidance`` keyword
so that terminal and `--json` output share the same logical cause / hint structure.
"""
from __... | 153 | 5,351 |
lemur | lemur/plugins/lemur_csr/plugin.py | .py | """
.. module: lemur.plugins.lemur_csr.plugin
An export plugin that exports CSR from a private key and certificate.
"""
import subprocess
from flask import current_app
from lemur.utils import mktempfile, mktemppath
from lemur.plugins.bases import ExportPlugin
from lemur.plugins import lemur_csr as csr
def run_proc... | 91 | 2,435 |
gunicorn | tests/test_http2_alpn.py | .py | # -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
"""Tests for HTTP/2 ALPN negotiation."""
import ssl
import pytest
from unittest import mock
from gunicorn import sock
def create_mock_ssl_socket(alpn_protocol=None):
"""Create a mock S... | 356 | 12,968 |
black | tests/data/cases/module_docstring_4.py | .py | """Single line module-level docstring should be followed by single newline."""
a = 1
# output
"""Single line module-level docstring should be followed by single newline."""
a = 1
| 9 | 182 |
sphinx | tests/roots/test-api-set-translator/translator.py | .py | from sphinx.writers.html import HTML5Translator
class ExtHTMLTranslator(HTML5Translator):
pass
| 6 | 101 |
jupyterlab | scripts/i18n_check.py | .py | """Handle a hash digest of the translatable strings."""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from hashlib import sha256
from pathlib import Path
from tempfile import TemporaryDirectory
import polib
from jupyterlab_translate.api import extract_language_pa... | 31 | 1,026 |
mlflow | mlflow/entities/logged_model_input.py | .py | from mlflow.entities._mlflow_object import _MlflowObject
from mlflow.protos.service_pb2 import ModelInput as ProtoModelInput
class LoggedModelInput(_MlflowObject):
"""ModelInput object associated with a Run."""
def __init__(self, model_id: str):
self._model_id = model_id
def __eq__(self, other: ... | 27 | 720 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_scatter_nd_add.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# fill_const paddle model generator
#
import numpy as np
from save_model import saveModel
import paddle
import sys
def scatter_nd_add(name : str, x,index,updates):
paddle.enable_static()
with paddle.static.program_guard(paddl... | 41 | 1,515 |
openvino | src/bindings/python/tests/test_graph/test_convert_promote_types.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import openvino.opset14 as ops
from openvino import Type
@pytest.mark.parametrize(
(
"lhs", "rhs", "promote_unsafe", "pytorch_scalar_promotion",
"u64_integer... | 104 | 4,515 |
django-cms | cms/utils/conf.py | .py | import os
from functools import update_wrapper
from typing import Any
from urllib.parse import urljoin
from django.conf import settings
from django.core.cache import caches
from django.core.exceptions import ImproperlyConfigured
from django.utils.connection import ConnectionProxy
from django.utils.translation import g... | 337 | 11,989 |
readthedocs.org | readthedocs/core/views/hooks.py | .py | """Views pertaining to builds."""
from dataclasses import dataclass
from typing import Literal
import structlog
from readthedocs.api.v2.models import BuildAPIKey
from readthedocs.builds.constants import EXTERNAL
from readthedocs.builds.constants import EXTERNAL_VERSION_STATE_CLOSED
from readthedocs.builds.constants ... | 185 | 5,909 |
pyomo | examples/pyomobook/overview-ch/wl_list.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... | 59 | 1,765 |
probability | spinoffs/inference_gym/inference_gym/__init__.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... | 20 | 771 |
sphinx | tests/test_project.py | .py | """Tests project module."""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from sphinx.project import Project
if TYPE_CHECKING:
from sphinx.testing.util import SphinxTestApp
DOCNAMES = {
'autodoc',
'bom',
'extapi',
'extensions',
'... | 107 | 3,099 |
wagtail | wagtail/locales/wagtail_hooks.py | .py | from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from wagtail import hooks
from wagtail.admin.menu import MenuItem
from wagtail.models import Site
from wagtail.permissions import policy_registry
from .views import LocaleViewSet
@hooks.register("register_admin_viewset")
def regi... | 33 | 856 |
hatch | src/hatch/env/plugin/interface.py | .py | from __future__ import annotations
import os
import sys
from abc import ABC, abstractmethod
from contextlib import contextmanager
from functools import cached_property
from os.path import isabs
from typing import TYPE_CHECKING, Any
from hatch.config.constants import AppEnvVars
from hatch.env.utils import add_verbosit... | 1,497 | 57,651 |
sqlmap | extra/kerberos/aes.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
# Dependency-free AES (FIPS-197) block cipher with CBC mode, supporting 128- and 256-bit keys. It is
# the primitive underneath Kerberos' AES-CTS-HMAC-SHA1-96 (RFC 3962) etypes, k... | 175 | 6,350 |
loguru | tests/exceptions/source/backtrace/not_enough_arguments.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=False, backtrace=True, diagnose=False)
@logger.catch
def decorated(x, y, z):
pass
def not_decorated(x, y, z):
pass
decorated(1)
with logger.catch():
not_decorated(2)
try:
not_decorated(3)
except Typ... | 27 | 353 |
probability | tensorflow_probability/python/sts/components/smooth_seasonal_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... | 163 | 6,013 |
biopython | Scripts/PDB/generate_three_to_one_dict.py | .py | # File download/unzip written 2012 by Lenna X. Peterson (arklenna@gmail.com)
# Dictionary extraction written 2011 by Hongbo Zhu
#
# 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.
"""Download PDB Chemi... | 121 | 3,695 |
mlflow | docs/api_reference/broken_links.py | .py | import contextlib
import socket
import subprocess
import sys
import time
import requests
from scrapy.crawler import CrawlerProcess
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
def get_safe_port():
with contextlib.closing(socket.socket(socket.AF_INET, socket.SOCK_ST... | 73 | 1,987 |
textual | docs/examples/styles/overflow.py | .py | from textual.app import App
from textual.containers import Horizontal, VerticalScroll
from textual.widgets import Static
TEXT = """I must not fear.
Fear is the mind-killer.
Fear is the little-death that brings total obliteration.
I will face my fear.
I will permit it to pass over me and through me.
And when it has gon... | 27 | 788 |
pyomo | pyomo/contrib/community_detection/plugins.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 13 | 615 |
coremltools | deps/pybind11/tests/test_class.py | .py | from __future__ import annotations
from unittest import mock
import pytest
import env
from pybind11_tests import PYBIND11_REFCNT_IMMORTAL, ConstructorStats, UserType
from pybind11_tests import class_ as m
def test_obj_class_name():
expected_name = "UserType" if env.PYPY else "pybind11_tests.UserType"
asser... | 504 | 15,331 |
openvino | src/bindings/python/src/openvino/frontend/jax/passes.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# flake8: noqa
# mypy: ignore-errors
from enum import Enum
from jax.lax import ConvDimensionNumbers
def enum_values_pass(value):
if isinstance(value, Enum):
return value.value
return value
def conv_dimension_numbers_p... | 66 | 1,780 |
wandb | wandb/sdk/data_types/base_types/wb_value.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Any, ClassVar
from wandb import util
from wandb.sdk import wandb_setup
if TYPE_CHECKING: # pragma: no cover
from wandb.sdk.artifacts.artifact import Artifact
from ...wandb_run import Run as LocalRun
TypeMappingType = dict[str, type["... | 292 | 11,592 |
pyomo | pyomo/opt/results/container.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... | 435 | 13,834 |
beam | sdks/python/apache_beam/runners/portability/fn_api_runner/__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... | 19 | 865 |
beam | sdks/python/apache_beam/ml/gcp/cloud_dlp_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... | 95 | 3,307 |
lemur | lemur/certificates/utils.py | .py | """
Utils to parse certificate data.
.. module: lemur.certificates.hooks
:platform: Unix
:copyright: (c) 2019 by Javier Ramos, see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Javier Ramos <javier.ramos@booking.com>
"""
from cryptography import x509
from cryptography... | 88 | 2,716 |
mlflow | tests/langchain/test_langchain_autolog.py | .py | import importlib
import json
import logging
import random
import time
from concurrent.futures import ThreadPoolExecutor
from operator import itemgetter
from typing import Any
from unittest import mock
import langchain_core
import pytest
from langchain_community.document_loaders import TextLoader
from langchain_communi... | 1,410 | 49,909 |
bazel | third_party/py/mock/tests/testhelpers.py | .py | # Copyright (C) 2007-2012 Michael Foord & the mock team
# E-mail: fuzzyman AT voidspace DOT org DOT uk
# http://www.voidspace.org.uk/python/mock/
from tests.support import unittest2, inPy3k
from mock import (
call, _Call, create_autospec, MagicMock,
Mock, ANY, _CallList, patch, PropertyMock
)
from datetime i... | 941 | 27,419 |
httpie | tests/test_cookie.py | .py | from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from .utils import http
class TestIntegration:
def setup_mock_server(self, handler):
"""Configure mock server."""
# Passing 0 as the port will cause a random free port to... | 48 | 1,876 |
beam | sdks/python/apache_beam/examples/snippets/transforms/aggregation/mean_per_key.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");... | 61 | 1,754 |
tqdm | tests/tests_tk.py | .py | """Test `tqdm.tk`."""
from .tests_tqdm import importorskip
def test_tk_import():
"""Test `tqdm.tk` import"""
importorskip('tqdm.tk')
| 8 | 143 |
sphinx | sphinx/util/display.py | .py | from __future__ import annotations
import functools
from sphinx._cli.util.colour import bold, terminal_supports_colour
from sphinx.locale import __
from sphinx.util import logging
TYPE_CHECKING = False
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator
from types import TracebackType
... | 96 | 3,050 |
hydra | plugins/hydra_ray_launcher/hydra_plugins/hydra_ray_launcher/_remote_invoke.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# This file is to be rsynced to ray cluster and invoke on the cluster.
import logging
import os
import sys
from pathlib import Path
from typing import List
from urllib.request import urlopen
import cloudpickle # type: ignore
import ray
from hydra... | 94 | 2,757 |
wandb | tests/system_tests/test_core/test_telemetry_full.py | .py | from unittest import mock
import wandb
from wandb.proto.wandb_telemetry_pb2 import Feature
# TODO: implement the telemetry context resolver
def get_features(telemetry) -> set[str]:
features = telemetry.get("3", [])
return {
Feature.DESCRIPTOR.fields_by_number[feature_number].name
for feature... | 134 | 4,318 |
textual | tests/test_line_split.py | .py | from textual._line_split import line_split
def test_split_string_to_lines_and_endings():
# Test with different line endings
assert line_split("Hello\r\nWorld\n") == [("Hello", "\r\n"), ("World", "\n")]
assert line_split("Hello\rWorld\r\n") == [("Hello", "\r"), ("World", "\r\n")]
assert line_split("Hel... | 27 | 849 |
saleor | saleor/tests/runner.py | .py | class PytestTestRunner:
"""Runs pytest to discover and run tests."""
def __init__(self, verbosity=1, failfast=False, keepdb=True, **kwargs):
self.verbosity = verbosity
self.failfast = failfast
self.keepdb = keepdb
def run_tests(self, test_labels):
"""Run pytest and return t... | 31 | 853 |
sphinx | tests/roots/test-ext-autodoc/target/hide_value.py | .py | #: docstring
#:
#: :meta hide-value:
SENTINEL1 = object()
#: :meta hide-value:
SENTINEL2 = object()
class Foo:
"""docstring"""
#: docstring
#:
#: :meta hide-value:
SENTINEL1 = object()
#: :meta hide-value:
SENTINEL2 = object()
| 20 | 260 |
hydra | tools/configen/tests/test_modules/default_flags/recursive.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Generated by configen, do not edit.
# See https://github.com/hydra-ecosystem/hydra/tree/main/tools/configen
# fmt: off
# isort:skip_file
# flake8: noqa
from dataclasses import dataclass, field
@dataclass
class EmptyConf:
_target_: str = "te... | 15 | 373 |
wagtail | wagtail/management/commands/api_tokens.py | .py | import json
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
from wagtail.log_actions import log
from wagtail.models import APIToken
class Command(BaseCommand):
help = "Manage Wagtail API tokens"
def add_arguments(self, parser):
subpar... | 116 | 4,566 |
returns | returns/pointfree/bind_async.py | .py | from collections.abc import Awaitable, Callable
from typing import TypeVar
from returns.interfaces.specific.future import FutureLikeN
from returns.primitives.hkt import Kinded, KindN, kinded
_FirstType = TypeVar('_FirstType')
_SecondType = TypeVar('_SecondType')
_ThirdType = TypeVar('_ThirdType')
_UpdatedType = TypeV... | 64 | 1,826 |
pyomo | pyomo/common/tests/relo_mod.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 13 | 669 |
clearml | clearml/utilities/locks/utils.py | .py | import atexit
import contextlib
import os
import tempfile
import time
from multiprocessing import RLock as ProcessRLock
from types import TracebackType
from typing import Generator, TextIO, Optional, Type, Any
from . import constants
from . import exceptions
from . import portalocker
current_time = getattr(time, "mon... | 375 | 11,381 |
wandb | wandb/sdk/data_types/graph.py | .py | import codecs
import os
import pprint
from wandb import util
from wandb.sdk.data_types._private import MEDIA_TMP
from wandb.sdk.data_types.base_types.media import Media, _numpy_arrays_to_lists
from wandb.sdk.data_types.base_types.wb_value import WBValue
from wandb.sdk.lib import runid
def _nest(thing):
# Use ten... | 440 | 12,751 |
pyro | pyro/contrib/funsor/infer/__init__.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from pyro.infer import SVI, config_enumerate # noqa: F401
from .discrete import infer_discrete # noqa: F401
from .elbo import ELBO # noqa: F401
from .trace_elbo import JitTrace_ELBO, Trace_ELBO # noqa: F401
from .traceenum_elbo im... | 16 | 514 |
python-prompt-toolkit | examples/choices/gray-frame-on-accept.py | .py | from __future__ import annotations
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.shortcuts import choice
from prompt_toolkit.styles import Style
def main() -> None:
style = Style.from_dict(
{
"selected-option": "bold",
"frame.border": "#ff4444",
"a... | 32 | 710 |
pyomo | pyomo/contrib/mindtpy/tests/nonconvex4.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... | 69 | 2,471 |
probability | tensorflow_probability/python/distributions/student_t_process_regression_model.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... | 746 | 35,212 |
metrics | src/torchmetrics/functional/retrieval/reciprocal_rank.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... | 63 | 2,518 |
mlflow | tests/tracking/request_auth/test_kubernetes_request_auth_provider.py | .py | from contextlib import contextmanager
from pathlib import Path
from unittest import mock
import pytest
pytest.importorskip("kubernetes")
from kubernetes.config.config_exception import ConfigException
import mlflow.tracking.request_auth.kubernetes_request_auth_provider as _k8s_auth
from mlflow.exceptions import Mlfl... | 425 | 14,456 |
wandb | tests/unit_tests/test_launch/test_runner/test_safe_watch.py | .py | from unittest.mock import MagicMock
import pytest
from kubernetes.client import ApiException
from urllib3.exceptions import ProtocolError
from wandb.sdk.launch.runner.kubernetes_monitor import SafeWatch
class MockWatch:
"""Mock class for testing."""
def __init__(self):
self.is_alive = True
s... | 85 | 2,388 |
loguru | loguru/_colorizer.py | .py | import re
from contextlib import contextmanager
from string import Formatter
@contextmanager
def try_formatting(*exceptions):
try:
yield
except exceptions as e:
raise ValueError(
"The logging message could not be formatted with the provided arguments.\n"
"Common causes ... | 513 | 16,264 |
beam | sdks/python/apache_beam/portability/__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... | 19 | 853 |
clearml | clearml/utilities/pigar/utils.py | .py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import difflib
import os
import re
import sys
from typing import Callable, Union, List, Tuple, Any, Generator
from typing import Dict as _Dict
PY32 = sys.version_info[:2] == (3, 2)
if sys.version_info[0] == 3:
binary_type =... | 147 | 3,898 |
probability | spinoffs/inference_gym/inference_gym/internal/array_to_source.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... | 45 | 1,407 |
black | tests/data/cases/fmtskip_type_ignore.py | .py | a = 1 # type: ignore
b = 1 # fmt: skip
| 3 | 41 |
ipython | tests/test_completerlib.py | .py | # -*- coding: utf-8 -*-
"""Tests for completerlib."""
import os
import sys
from os.path import join
from tempfile import TemporaryDirectory
import pytest
from IPython.core.completerlib import magic_run_completer, module_completion, try_import
from IPython.testing.decorators import onlyif_unicode_paths
class MockEv... | 138 | 4,194 |
onnx | onnx/backend/test/case/node/unsqueeze.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 Unsqueeze(Base):
@staticmethod
def export_unsqueeze_one_axis()... | 92 | 2,767 |
slimit | src/slimit/mangler.py | .py | ###############################################################################
#
# Copyright (c) 2011 Ruslan Spivak
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, inc... | 52 | 1,906 |
saleor | saleor/payment/tests/fixtures/gateway_response.py | .py | from decimal import Decimal
import pytest
from ....payment import TransactionKind
from ....payment.interface import GatewayResponse
@pytest.fixture
def action_required_gateway_response():
return GatewayResponse(
is_success=True,
action_required=True,
action_required_data={
"p... | 46 | 1,154 |
hydra | hydra/core/utils.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import logging
import os
import re
import sys
from contextlib import contextmanager
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from os.path import splitext
from pathlib import Path
from t... | 473 | 15,880 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.