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 |
|---|---|---|---|---|---|
qutip | qutip/tests/core/test_eigenstates.py | .py | import pytest
import numpy as np
import qutip
from itertools import combinations
def _canonicalise_eigenvector(vec):
"""
Normalise an eigenvector so that the first non-zero value is equal to one,
and the array is flattened. Just normalising based on vector magnitude
isn't enough to fully fix the gaug... | 102 | 4,411 |
openvino | src/bindings/python/src/openvino/properties/intel_cpu/__init__.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# Enums
from openvino._pyopenvino.properties.intel_cpu import TbbPartitioner
# Properties
import openvino._pyopenvino.properties.intel_cpu as __intel_cpu
from openvino.properties._properties import __make_propert... | 12 | 365 |
rq | rq/dependency.py | .py | from collections.abc import Iterable
from redis.client import Pipeline
from redis.exceptions import WatchError
from .job import Job
class Dependency:
@classmethod
def get_jobs_with_met_dependencies(cls, jobs: Iterable['Job'], pipeline: Pipeline):
jobs_with_met_dependencies = []
jobs_with_unm... | 28 | 1,000 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/fast_gelu.py | .py | import numpy as np
import onnx
from onnx import OperatorSetIdProto, TensorProto, helper, numpy_helper
# Gelu formula: x * 0.5 * (1.0 + tanh(0.7978845608028654 * x * (1.0 + 0.044715 * x * x)))
has_bias = True # change it to True to generate fast_gelu_with_bias.onnx
gelu_use_graph_input = True # change it to False to... | 111 | 3,944 |
pyomo | pyomo/contrib/preprocessing/tests/test_equality_propagate.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... | 242 | 9,055 |
sqlmap | thirdparty/chardet/mbcsgroupprober.py | .py | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Universal charset detector code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 2001
# the Initial Developer. All R... | 55 | 2,012 |
funcy | tests/test_funcolls.py | .py | from whatever import _
from funcy import lfilter
from funcy.funcolls import *
def test_all_fn():
assert lfilter(all_fn(_ > 3, _ % 2), range(10)) == [5, 7, 9]
def test_any_fn():
assert lfilter(any_fn(_ > 3, _ % 2), range(10)) == [1, 3, 4, 5, 6, 7, 8, 9]
def test_none_fn():
assert lfilter(none_fn(_ > 3, ... | 29 | 640 |
cvxpy | cvxpy/reductions/cone2cone/cone_tree.py | .py | """
Copyright 2025, 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, soft... | 97 | 2,833 |
clearml | clearml/backend_interface/task/populate.py | .py | import inspect
import json
import os
import re
import tempfile
from functools import reduce
from logging import getLogger
from sys import platform
from typing import Optional, Sequence, Union, Tuple, List, Callable, Dict, Any
from pathlib2 import Path
from six.moves.urllib.parse import urlparse
from .args import _Arg... | 1,269 | 59,728 |
beam | learning/katas/python/Core Transforms/GroupByKey/GroupByKey/tests/test_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 not... | 38 | 1,343 |
cvxpy | cvxpy/tests/test_einsum.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
... | 302 | 11,876 |
onnxruntime | onnxruntime/test/python/transformers/profile_skip_layer_norm.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
"""
Profiling script for SkipLayerNormalization CUDA kernel.
Usage:
... | 177 | 6,681 |
hatch | src/hatch/utils/metadata.py | .py | from __future__ import annotations
import re
def normalize_project_name(name: str) -> str:
# https://peps.python.org/pep-0503/#normalized-names
return re.sub(r"[-_.]+", "-", name).lower()
| 9 | 199 |
metrics | src/torchmetrics/nominal/theils_u.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... | 144 | 5,798 |
metrics | src/torchmetrics/functional/clustering/calinski_harabasz_score.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... | 62 | 2,432 |
onnxruntime | onnxruntime/core/flatbuffers/ort_flatbuffers_py/fbs/EdgeEnd.py | .py | # automatically generated by the FlatBuffers compiler, do not modify
# namespace: fbs
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class EdgeEnd(object):
__slots__ = ['_tab']
@classmethod
def SizeOf(cls):
return 12
# EdgeEnd
def Init(self, buf, pos)... | 33 | 1,105 |
omegaconf | omegaconf/dictconfig.py | .py | import copy
import difflib
from enum import Enum
from typing import (
Any,
Dict,
ItemsView,
Iterable,
Iterator,
KeysView,
List,
MutableMapping,
Optional,
Sequence,
Tuple,
Type,
Union,
)
from ._utils import (
_DEFAULT_MARKER_,
ValueKind,
_get_value,
_i... | 824 | 29,919 |
mlflow | tests/pydantic_ai/test_pydanticai_autolog.py | .py | from unittest import mock
import pytest
from packaging.version import Version
import mlflow
from mlflow.pydantic_ai import autolog as pydantic_ai_autolog
from mlflow.pydantic_ai import autolog_v2
def _call_autolog(**kwargs):
# Exercise version dispatch directly, independent of global autologging configuration s... | 93 | 3,040 |
onnxruntime | onnxruntime/test/python/quantization/test_mixed_prec_quant_overrides_fixer.py | .py | #!/usr/bin/env python
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------------------------... | 172 | 7,746 |
onnx | onnx/reference/ops/op_random_normal_like.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from onnx.helper import np_dtype_to_tensor_dtype
from onnx.reference.ops._op_common_random import _CommonRandom
class RandomNormalLike(_CommonRandom):
def _run(self, x, dtype=None, mean=None, scale... | 20 | 628 |
wandb | wandb/sdk/lib/json_util.py | .py | """JSON helpers backed by pydantic-core, with stdlib fallback.
The wrapper mirrors the stdlib `json` surface (`dumps`/`dump`/`loads`/`load`)
and routes the hot path through `pydantic_core` for speed. Anything pydantic
cannot do — unrecognized kwargs, unserializable objects without a fallback,
etc. — is caught and re-t... | 55 | 1,697 |
astropy | astropy/units/astrophys.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package defines the astrophysics-specific units. They are also
available in (and should be used through) the `astropy.units` namespace.
"""
# avoid ruff complaints about undefined names defined by def_unit
# ruff: noqa: F821
import numpy as np
... | 227 | 5,302 |
jupytext | tests/data/notebooks/outputs/ipynb_to_script_vim_folding_markers/jupyter_with_raw_cell_in_body.py | .py | # ---
# jupyter:
# jupytext:
# cell_markers: '{{{,}}}'
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
1+2+3
# {{{ active=""
# This is a raw cell
# }}}
# This is a markdown cell
| 18 | 233 |
django-cms | cms/toolbar_base.py | .py | from django.forms import MediaDefiningClass
from cms.exceptions import LanguageError
from cms.utils import get_current_site, get_language_from_request
from cms.utils.i18n import get_language_code
class CMSToolbar(metaclass=MediaDefiningClass):
supported_apps = None
def __init__(self, request, toolbar, is_cu... | 40 | 1,227 |
wagtail | wagtail/snippets/api/v3/registry.py | .py | from wagtail.api import APIField
from wagtail.api.v3.registry import ContentTypeRegistration, registry
from wagtail.api.v3.schemas import create_generator, patch_generator, read_generator
from wagtail.models import DraftStateMixin
from wagtail.snippets.api.v3.schemas import (
PUBLISH_ACTION_META_FIELD,
BaseSnip... | 48 | 1,857 |
clearml | clearml/backend_interface/datasets/save_frames_request_no_validate.py | .py | # do not import this file directly, as dereferncing datasets will result in a server call
# import from save_frames_request_no_validate_wrapped
from ...backend_api.services import datasets
_SaveFramesRequest = datasets.SaveFramesRequest if getattr(datasets, "SaveFramesRequest", None) else object
class _SaveFramesRe... | 12 | 407 |
openvino | tools/ovc/openvino/tools/ovc/moc_frontend/pytorch_frontend_utils.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import logging as log
import pathlib
import sys
import numpy as np
# pylint: disable=no-name-in-module,import-error
from openvino import Tensor, PartialShape
from openvino.tools.ovc.cli_parser import input_to_input_cut_info, single_inp... | 439 | 17,879 |
openvino | tests/layer_tests/tensorflow_lite_tests/test_tfl_Conv2D.py | .py | import numpy as np
import pytest
import tensorflow as tf
from common.tflite_layer_test_class import TFLiteLayerTest
np.random.seed(42)
test_params = [
{'shape': [1, 22, 22, 8], 'ksize': [32, 3, 4, 4], 'strides': 2, 'padding': 'SAME', 'dilations': [1, 1, 1, 1]},
{'shape': [1, 22, 22, 9], 'ksize': [32, 3, 3, 3... | 40 | 1,807 |
django-cms | cms/tests/test_templatetags.py | .py | import os
from copy import deepcopy
from unittest.mock import patch
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.backends.base import SessionBase
from django.contrib.sites.models import Site
from django.core import mail
from django.core.exceptions i... | 914 | 42,267 |
black | tests/data/cases/fmtonoff.py | .py | #!/usr/bin/env python3
import asyncio
import sys
from third_party import X, Y, Z
from library import some_connection, \
some_decorator
# fmt: off
from third_party import (X,
Y, Z)
# fmt: on
f'trigger 3.6 mode'
# Comment 1
# Comment 2
# fmt: off
def func_no_args():
a; b... | 522 | 11,187 |
openvino | tests/layer_tests/tensorflow_lite_tests/test_tfl_Unpack.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import tensorflow as tf
from common.tflite_layer_test_class import TFLiteLayerTest
np.random.seed(42)
test_params = [
{'shape': [3, 4, 3], 'axis': 0},
{'shape': [3, 4, 3], 'axis': -1},
{'sh... | 42 | 1,372 |
lemur | lemur/plugins/lemur_aws/sts.py | .py | """
.. module: lemur.plugins.lemur_aws.sts
:platform: Unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from functools import wraps
import boto3
from botocore.config import Config
from b... | 66 | 2,663 |
readthedocs.org | readthedocs/projects/querysets.py | .py | """Project model QuerySet classes."""
from django.conf import settings
from django.db import models
from django.db.models import Count
from django.db.models import Exists
from django.db.models import OuterRef
from django.db.models import Prefetch
from django.db.models import Q
from readthedocs.core.permissions import... | 289 | 9,967 |
django-cms | cms/utils/urlutils.py | .py | import re
from collections.abc import Sequence
from typing import Any
from urllib.parse import urlparse
from django.conf import settings
from django.urls import reverse
from django.utils.encoding import force_str
from django.utils.http import urlencode
import cms
from cms.utils.conf import get_cms_setting
# checks v... | 113 | 2,961 |
astropy | astropy/wcs/tests/test_celprm.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from copy import copy, deepcopy
import numpy as np
import pytest
from astropy import wcs
_WCS_UNDEFINED = 987654321.0e99
def test_celprm_init():
# test Celprm_cnew
assert wcs.WCS().wcs.cel
# test Celprm_new
assert wcs.Celprm()
wi... | 144 | 2,758 |
saleor | saleor/graphql/product/mutations/product_variant/product_variant_delete.py | .py | import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Exists, OuterRef
from .....attribute import AttributeInputType
from .....attribute import models as attribute_models
from .....attribute.lock_objects import attribute_value_qs_select_for_up... | 184 | 7,291 |
scikit-bio | skbio/stats/gradient.py | .py | r"""Gradient analyses (:mod:`skbio.stats.gradient`)
===============================================
.. currentmodule:: skbio.stats.gradient
This module provides functionality for performing gradient analyses.
The algorithms included in this module mainly allows performing analysis of
volatility on time series data, b... | 914 | 32,311 |
wagtail | wagtail/admin/tests/test_privacy.py | .py | from django.contrib.auth.models import Group
from django.test import TestCase, override_settings
from django.urls import reverse
from wagtail.admin.staticfiles import versioned_static
from wagtail.models import PageViewRestriction
from wagtail.test.testapp.models import SimplePage
from wagtail.test.utils import Page, ... | 686 | 24,827 |
luigi | luigi/configuration/toml_parser.py | .py | # -*- coding: utf-8 -*-
#
# Copyright 2018 Vote Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | 98 | 2,917 |
probability | spinoffs/inference_gym/inference_gym/internal/datasets/synthetic_log_gaussian_cox_process.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... | 472 | 5,386 |
hatch | backend/src/hatchling/version/source/regex.py | .py | from hatchling.version.core import VersionFile
from hatchling.version.source.plugin.interface import VersionSourceInterface
class RegexSource(VersionSourceInterface):
PLUGIN_NAME = "regex"
def get_version_data(self) -> dict:
relative_path = self.config.get("path", "")
if not relative_path:
... | 30 | 1,065 |
luigi | test/scheduler_message_test.py | .py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | 119 | 3,832 |
black | tests/data/cases/function_trailing_comma.py | .py | def f(a,):
d = {'key': 'value',}
tup = (1,)
def f2(a,b,):
d = {'key': 'value', 'key2': 'value2',}
tup = (1,2,)
def f(a:int=1,):
call(arg={'explode': 'this',})
call2(arg=[1,2,3],)
x = {
"a": 1,
"b": 2,
}["a"]
if a == {"a": 1,"b": 2,"c": 3,"d": 4,"e": 5,"f": 6,"g": 7,... | 309 | 5,318 |
mlflow | mlflow/tracing/assessment.py | .py | from typing import Any
from mlflow.entities.assessment import (
DEFAULT_FEEDBACK_NAME,
Assessment,
AssessmentError,
Expectation,
Feedback,
FeedbackValueType,
IssueReference,
)
from mlflow.entities.assessment_source import AssessmentSource
from mlflow.exceptions import MlflowException
from m... | 482 | 17,212 |
onnxruntime | onnxruntime/python/tools/quantization/qdq_loss_debug.py | .py | # --------------------------------------------------------------------------
# Copyright (c) Microsoft, Intel Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"... | 390 | 15,440 |
mlflow | examples/gateway/ai21_labs/example.py | .py | from mlflow.deployments import get_deploy_client
def main():
client = get_deploy_client("http://localhost:7000")
print(f"AI21 Labs endpoints: {client.list_endpoints()}\n")
print(f"AI21 Labs completions endpoint info: {client.get_endpoint(endpoint='completions')}\n")
# Completions request
respons... | 23 | 659 |
sqlmap | tamper/charunicodeescape.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
import string
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.LOWEST
def tamper(payload, **kwargs):
"""
Unicode-escapes non-encoded characters in a given pa... | 46 | 1,550 |
scikit-bio | skbio/io/format/tests/test_phylip_dm.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.
# --------------------------------------------... | 346 | 15,279 |
ipython | tests/test_async_helpers.py | .py | """
Test for async helpers.
Should only trigger on python 3.5+ or will have syntax errors.
"""
import contextlib
import sys
from itertools import chain, repeat
from textwrap import dedent, indent
from typing import TYPE_CHECKING
import pytest
from IPython.core.async_helpers import _should_be_async
from IPython.test... | 474 | 10,208 |
textual | tests/snapshot_tests/snapshot_apps/placeholder_disabled.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Placeholder
class DisabledPlaceholderApp(App[None]):
CSS = """
Placeholder {
height: 1fr;
}
"""
def compose(self) -> ComposeResult:
yield Placeholder()
yield Placeholder(disabled=True)
if __name__ == "... | 19 | 367 |
textual | tests/footer/test_footer.py | .py | from textual.app import App, ComposeResult
from textual.binding import Binding
from textual.widget import Widget
from textual.widgets import Button, Footer
async def test_footer_bindings() -> None:
app_binding_count = 0
class TestWidget(Widget, can_focus=True):
BINDINGS = [
Binding("b", "... | 67 | 1,908 |
openvino | src/bindings/python/src/openvino/properties/intel_gpu/__init__.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# Properties
import openvino._pyopenvino.properties.intel_gpu as __intel_gpu
from openvino.properties._properties import __make_properties
__make_properties(__intel_gpu, __name__)
# Classes
from openvino._pyopenv... | 13 | 431 |
probability | tensorflow_probability/python/experimental/nn/convolutional_layers_v2_test.py | .py | # Copyright 2019 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 166 | 6,266 |
saleor | saleor/graphql/product/tests/deprecated/test_product_channel_listing_update.py | .py | import datetime
from unittest.mock import patch
import graphene
from freezegun import freeze_time
from .....product.error_codes import ProductErrorCode
from .....product.models import ProductChannelListing
from .....product.utils.costs import get_product_costs_data
from ....tests.utils import get_graphql_content
PRO... | 500 | 17,643 |
pymc | pymc/gp/cov.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... | 1,245 | 42,328 |
mkdocs | mkdocs/structure/nav.py | .py | from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Iterator, TypeVar
from urllib.parse import urlsplit
from mkdocs.exceptions import BuildError
from mkdocs.structure import StructureItem
from mkdocs.structure.files import file_sort_key
from mkdocs.structure.pages import Page, _Absolut... | 252 | 9,033 |
cvxpy | cvxpy/utilities/coeff_extractor.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
... | 489 | 21,241 |
hatch | tests/backend/builders/test_wheel.py | .py | from __future__ import annotations
import os
import platform
import sys
import zipfile
from typing import TYPE_CHECKING
import packaging.tags
import pytest
from hatchling.builders.plugin.interface import BuilderInterface
from hatchling.builders.utils import get_known_python_major_versions
from hatchling.builders.whe... | 4,029 | 151,467 |
confluent-kafka-python | src/confluent_kafka/schema_registry/rules/encryption/localkms/local_driver.py | .py | # Copyright 2024 Confluent Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | 45 | 1,478 |
cvxpy | cvxpy/reductions/dqcp2dcp/dqcp2dcp.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
... | 237 | 9,570 |
probability | tensorflow_probability/python/experimental/mcmc/windowed_sampling_test.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 ... | 933 | 33,907 |
pyomo | pyomo/contrib/appsi/cmodel/__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... | 44 | 1,385 |
mlflow | dev/clint/src/clint/rules/mock_patch_dict_environ.py | .py | import ast
from clint.resolver import Resolver
from clint.rules.base import Rule
class MockPatchDictEnviron(Rule):
def _message(self) -> str:
return (
"Do not use `mock.patch.dict` to modify `os.environ` in tests; "
"use pytest's monkeypatch fixture (monkeypatch.setenv / monkeypat... | 47 | 1,482 |
gunicorn | gunicorn/http/__init__.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.http.message import Message, Request
from gunicorn.http.parser import RequestParser
def get_parser(cfg, source, source_addr, http2_connection=False):
"""Get appropriate parser based on protocol ... | 37 | 1,162 |
beam | learning/katas/python/Streaming/Triggers/Event Time Triggers/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 not... | 58 | 2,010 |
deap | examples/es/cma_1+l_minfct.py | .py | # This file is part of DEAP.
#
# DEAP 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.
#
# DEAP is distributed ... | 56 | 1,996 |
scikit-bio | skbio/metadata/tests/test_metadata_column.py | .py | import os.path
import tempfile
import unittest
from packaging.version import Version
import pandas as pd
import numpy as np
from skbio.metadata._metadata import (MetadataColumn, CategoricalMetadataColumn,
NumericMetadataColumn)
PANDAS_3 = Version(pd.__version__) >= Version("3.0.... | 900 | 34,099 |
readthedocs.org | readthedocs/config/exceptions.py | .py | from readthedocs.doc_builder.exceptions import BuildUserError
class ConfigError(BuildUserError):
GENERIC = "config:generic"
DEFAULT_PATH_NOT_FOUND = "config:path:default-not-found"
CONFIG_PATH_NOT_FOUND = "config:path:not-found"
KEY_NOT_SUPPORTED_IN_VERSION = "config:key:not-supported-in-version"
... | 51 | 2,873 |
loguru | tests/exceptions/source/modern/grouped_nested.py | .py | from loguru import logger
import sys
def divide_by_zero():
1 / 0
def raise_value_error(value):
raise ValueError(value)
@logger.catch
def main():
try:
try:
divide_by_zero()
except Exception as err:
error_1 = err
try:
raise_value_error(100)
... | 41 | 844 |
pyomo | doc/OnlineDocs/src/data/table0.ul.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... | 19 | 752 |
saleor | saleor/app/tests/fixtures/app.py | .py | import pytest
from django.utils import timezone
from ....app.models import App
from ....app.types import AppType
from ....webhook.event_types import WebhookEventSyncType
from ....webhook.models import Webhook, WebhookEvent
@pytest.fixture
def app(db):
app = App.objects.create(
name="Sample app objects",
... | 213 | 5,825 |
onnxruntime | onnxruntime/python/tools/quantization/operators/argmax.py | .py | from .base_operator import QuantOperatorBase
# Use the quantized tensor as input without DQ.
class QArgMax(QuantOperatorBase):
def __init__(self, onnx_quantizer, onnx_node):
super().__init__(onnx_quantizer, onnx_node)
def quantize(self):
node = self.node
quantized_input_value = self.... | 19 | 571 |
pdm | src/pdm/cli/commands/lock.py | .py | import argparse
import re
import sys
from typing import cast
from pdm import termui
from pdm.cli.commands.base import BaseCommand
from pdm.cli.filters import GroupSelection
from pdm.cli.hooks import HookManager
from pdm.cli.options import (
config_setting_option,
groups_group,
lock_strategy_group,
lock... | 137 | 5,035 |
python-prompt-toolkit | src/prompt_toolkit/cache.py | .py | from __future__ import annotations
from collections import deque
from collections.abc import Callable, Hashable
from functools import wraps
from typing import Any, Generic, TypeVar, cast
__all__ = [
"SimpleCache",
"FastDictCache",
"memoized",
]
_T = TypeVar("_T", bound=Hashable)
_U = TypeVar("_U")
clas... | 129 | 3,837 |
saleor | saleor/tests/e2e/channel/utils/channel_create.py | .py | import uuid
from ...utils import get_graphql_content
CHANNEL_CREATE_MUTATION = """
mutation ChannelCreate($input: ChannelCreateInput!) {
channelCreate(input: $input) {
errors {
field
message
code
}
channel {
id
name
slug
currencyCode
defaultCountry {
... | 118 | 2,807 |
textual | docs/examples/styles/width_comparison.py | .py | from textual.app import App
from textual.containers import Horizontal
from textual.widgets import Label, Placeholder, Static
class Ruler(Static):
def compose(self):
ruler_text = "····•" * 100
yield Label(ruler_text)
class WidthComparisonApp(App):
CSS_PATH = "width_comparison.tcss"
def c... | 33 | 796 |
saleor | saleor/graphql/attribute/mutations/attribute_update.py | .py | import graphene
from django.core.exceptions import ValidationError
from ....attribute import models as models
from ....attribute.error_codes import AttributeErrorCode
from ....page.utils import mark_pages_search_vector_as_dirty_in_batches
from ....product.utils.search_helpers import (
mark_products_search_vector_a... | 206 | 8,543 |
biopython | Bio/SearchIO/HHsuiteIO/__init__.py | .py | # Copyright 2019 by Jens Thomas. 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.SearchIO support for ... | 18 | 639 |
ipython | tools/tests/embed/embed_no_flufl.py | .py | """This tests that future compiler flags are passed to the embedded IPython."""
from IPython import embed
import __future__
embed(banner1='', header='check 1 <> 2 cause SyntaxError')
embed(banner1='', header='check 1 <> 2 == True',
compile_flags=__future__.barry_as_FLUFL.compiler_flag)
| 7 | 293 |
saleor | saleor/warehouse/tests/fixtures/warehouse.py | .py | import pytest
from ... import WarehouseClickAndCollectOption
from ...models import Stock, Warehouse
@pytest.fixture
def warehouse(address, shipping_zone, channel_USD):
warehouse = Warehouse.objects.create(
address=address,
name="Example Warehouse",
slug="example-warehouse",
email=... | 166 | 5,172 |
readthedocs.org | readthedocs/rtd_tests/tests/test_version.py | .py | from django.test import TestCase
from django.test.utils import override_settings
from django_dynamic_fixture import get
from readthedocs.builds.constants import BRANCH, EXTERNAL, LATEST, STABLE, TAG
from readthedocs.builds.models import Version
from readthedocs.projects.models import Project
class VersionMixin:
... | 158 | 5,657 |
hydra | examples/configure_hydra/workdir/my_app.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import os
from omegaconf import DictConfig
import hydra
@hydra.main(config_path="conf", config_name="config")
def experiment(_cfg: DictConfig) -> None:
print(os.getcwd())
if __name__ == "__main__":
experiment()
| 16 | 296 |
hatch | backend/src/hatchling/metadata/plugin/interface.py | .py | from __future__ import annotations
from abc import ABC, abstractmethod
class MetadataHookInterface(ABC): # no cov
"""
Example usage:
```python tab="plugin.py"
from hatchling.metadata.plugin.interface import MetadataHookInterface
class SpecialMetadataHook(MetadataHookInterface):
PLUGIN... | 67 | 1,500 |
probability | tensorflow_probability/python/experimental/mcmc/step.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... | 105 | 4,365 |
clearml | clearml/utilities/process/mp.py | .py | import os
import pickle
import struct
import sys
from functools import partial
from multiprocessing import Process, Semaphore, Event as ProcessEvent
from threading import Thread, Event as TrEvent, RLock as ThreadRLock
from time import sleep, time
from types import TracebackType
from typing import List, Dict, Optional, ... | 912 | 31,897 |
coremltools | coremltools/converters/mil/mil/ops/tests/iOS14/test_linear.py | .py | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
import itertools
import platform
import numpy as np
import pytest
import coremltools as ct
from core... | 462 | 17,591 |
metrics | tests/unittests/audio/test_c_si_snr.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... | 96 | 3,963 |
beam | sdks/python/apache_beam/typehints/sharded_key_type.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... | 87 | 3,155 |
pyomo | pyomo/contrib/trustregion/__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... | 15 | 930 |
mlflow | dev/extract_deps.py | .py | import ast
import re
from pathlib import Path
from typing import cast
def parse_dependencies(content: str) -> list[str]:
pattern = r"dependencies\s*=\s*(\[[\s\S]*?\])\n"
match = re.search(pattern, content)
if match is None:
raise ValueError("Could not find dependencies in pyproject.toml")
deps... | 24 | 590 |
python-prompt-toolkit | src/prompt_toolkit/layout/mouse_handlers.py | .py | from __future__ import annotations
from collections import defaultdict
from collections.abc import Callable
from typing import TYPE_CHECKING
from prompt_toolkit.mouse_events import MouseEvent
if TYPE_CHECKING:
from prompt_toolkit.key_binding.key_bindings import NotImplementedOrNone
__all__ = [
"MouseHandler... | 58 | 1,616 |
mlflow | mlflow/genai/scorers/deepeval/scorers/safety_metrics.py | .py | """Safety and responsible AI metrics for content evaluation."""
from __future__ import annotations
from typing import ClassVar
from mlflow.genai.judges.builtin import _MODEL_API_DOC
from mlflow.genai.scorers.deepeval import DeepEvalScorer
from mlflow.utils.docstring_utils import format_docstring
@format_docstring(... | 185 | 5,776 |
black | tests/data/cases/pattern_matching_simple.py | .py | # flags: --minimum-version=3.10
# Cases sampled from PEP 636 examples
match command.split():
case [action, obj]:
... # interpret action, obj
match command.split():
case [action]:
... # interpret single-verb action
case [action, obj]:
... # interpret action, obj
match command.sp... | 94 | 2,673 |
beam | sdks/python/apache_beam/options/pipeline_options.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... | 2,358 | 92,106 |
loguru | tests/exceptions/source/backtrace/no_tb.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="{message}", colorize=False, backtrace=True, diagnose=False)
def f():
try:
1 / 0
except ZeroDivisionError:
ex_type, ex, tb = sys.exc_info()
tb = None
logger.opt(exception=(ex_type, ex, tb)).debug(... | 20 | 335 |
astropy | astropy/modeling/tests/test_rotations.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# pylint: disable=invalid-name
import unittest.mock as mk
from math import cos, sin
import numpy as np
import pytest
from numpy.testing import assert_allclose
import astropy.units as u
from astropy.modeling import models, rotations
from astropy.table im... | 479 | 16,121 |
pyomo | examples/pyomo/tutorials/set.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... | 249 | 6,856 |
mlflow | tests/utils/test_file_utils.py | .py | import filecmp
import hashlib
import io
import os
import shutil
import stat
import tarfile
from pathlib import Path
import pytest
from pyspark.sql import SparkSession
import mlflow
from mlflow.exceptions import MlflowException
from mlflow.pyfunc.dbconnect_artifact_cache import extract_archive_to_dir
from mlflow.utils... | 393 | 14,825 |
loguru | tests/exceptions/source/modern/positional_only_argument.py | .py | # fmt: off
import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True)
def foo(a, /, b, *, c, **d): 1 / 0
def main():
foo(1, 2, c=3)
with logger.catch():
main()
| 19 | 251 |
hatch | tests/cli/python/test_install.py | .py | import json
import secrets
import pytest
from hatch.errors import PythonDistributionResolutionError
from hatch.python.core import InstalledDistribution
from hatch.python.distributions import ORDERED_DISTRIBUTIONS
from hatch.python.resolve import get_distribution
def test_unknown(hatch, helpers, path_append, mocker)... | 291 | 10,226 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.