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 |
|---|---|---|---|---|---|
cvxpy | cvxpy/atoms/axis_atom.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... | 212 | 7,264 |
wandb | wandb/apis/attrs.py | .py | from __future__ import annotations
from collections.abc import Mapping
from typing import Any
import wandb
from ..sdk.lib import ipython
class Attrs:
def __init__(self, attrs: Mapping[str, Any]):
self._attrs = dict(attrs)
def snake_to_camel(self, string):
camel = "".join([i.title() for i i... | 54 | 1,477 |
wandb | wandb/_filters/operators.py | .py | """Types that represent operators in MongoDB filter expressions."""
from __future__ import annotations
from abc import ABC
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any, TypeAlias, TypeVar, final, get_args
from pydantic import ConfigDict, Field, StrictBool, StrictFloat, StrictInt, Strict... | 309 | 8,517 |
conda | conda/plugins/reporter_backends/json.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""
Defines a JSON reporter backend
This reporter backend is used to provide JSON strings for output rendering. It is
essentially just a wrapper around ``conda.common.serialize.json.dumps``.
"""
from __future__ import annotations
import sys
f... | 136 | 3,552 |
saleor | saleor/core/db/filters.py | .py | from django.db.models.lookups import IContains
class PostgresILike(IContains):
lookup_name = "ilike"
def as_postgresql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + r... | 12 | 400 |
onnx | onnx/backend/test/case/node/bitwiseand.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
from onnx.numpy_helper import create_random_int
class BitwiseAnd(Base):
... | 56 | 1,673 |
python-prompt-toolkit | src/prompt_toolkit/filters/utils.py | .py | from __future__ import annotations
from .base import Always, Filter, FilterOrBool, Never
__all__ = [
"to_filter",
"is_true",
]
_always = Always()
_never = Never()
_bool_to_filter: dict[bool, Filter] = {
True: _always,
False: _never,
}
def to_filter(bool_or_filter: FilterOrBool) -> Filter:
""... | 42 | 859 |
wandb | tests/system_tests/test_core/test_wandb_login.py | .py | import os
from unittest import mock
import pytest
import wandb
from wandb.sdk.lib.wbauth import wbnetrc
def test_login_valid_key(user):
logged_in = wandb.login(verify=True)
assert logged_in
def test_login_invalid_key_from_environment_raises(user):
with mock.patch.dict("os.environ", {"WANDB_API_KEY": "I... | 54 | 1,439 |
jupytext | tests/data/notebooks/outputs/ipynb_to_marimo/text_outputs_and_images.py | .py | import marimo
__generated_with = "0.17.8"
app = marimo.App()
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
This notebook contains outputs of many different types: text, HTML, plots and errors.
""")
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""
# Text outputs
Using `print`, `... | 127 | 1,987 |
onnxruntime | orttraining/orttraining/python/training/utils/torch_io_helper.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import copy
import warnings
from collections import OrderedDict, abc
fro... | 314 | 12,930 |
saleor | saleor/order/models.py | .py | from decimal import Decimal
from operator import attrgetter
from re import match
from typing import TYPE_CHECKING, cast
from uuid import uuid4
from django.conf import settings
from django.contrib.postgres.indexes import BTreeIndex, GinIndex
from django.contrib.postgres.search import SearchVectorField
from django.core.... | 997 | 34,037 |
saleor | saleor/plugins/webhook/tests/subscription_webhooks/filterable_webhooks/test_order_refunded.py | .py | import json
from unittest.mock import patch
import graphene
from django.test import override_settings
from ......core.models import EventDelivery
from ......graphql.webhook.subscription_query import SubscriptionQuery
from ......webhook.event_types import WebhookEventAsyncType
from .....manager import get_plugins_mana... | 230 | 6,986 |
probability | discussion/robust_inverse_graphics/saving.py | .py | # Copyright 2024 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 73 | 2,211 |
confluent-kafka-python | examples/protobuf/user_pb2.py | .py | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: user.proto
"""Generated protocol buffer code."""
from google.protobuf.internal import builder as _builder
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
fro... | 32 | 1,302 |
hydra | plugins/hydra_ray_launcher/examples/upload_download/model/my_model.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
from datetime import datetime
from pathlib import Path
log = logging.getLogger(__name__)
class MyModel:
def __init__(self, random_seed: int):
self.random_seed = random_seed
log.info("Init my model")
def sav... | 20 | 670 |
onnx | onnx/reference/ops/op_gather_elements.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import numpy as np
from onnx.reference.op_run import OpRun
def gather_numpy_2(self: np.ndarray, index: np.ndarray) -> np.ndarray:
res = []
for a, b in zip(self, index, strict=True):
re... | 48 | 1,598 |
probability | tensorflow_probability/python/distributions/chi2_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... | 182 | 6,812 |
hydra | plugins/hydra_rq_launcher/tests/test_rq_launcher.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from base64 import b64encode
from pickle import UnpicklingError
from typing import List
import pytest
from hydra.core.plugins import Plugins
from hydra.errors import CompactHydraException
from hydra.plugins.launcher import Launcher
from hydra.test_... | 140 | 4,264 |
clearml | clearml/backend_api/session/jsonmodels/utilities.py | .py | from __future__ import absolute_import
from typing import Any
import re
from collections import namedtuple
SCALAR_TYPES = (str, int, float, bool)
ECMA_TO_PYTHON_FLAGS = {
"i": re.I,
"m": re.M,
}
PYTHON_TO_ECMA_FLAGS = dict((value, key) for key, value in ECMA_TO_PYTHON_FLAGS.items())
PythonRegex = namedtup... | 144 | 3,774 |
saleor | saleor/tests/e2e/checkout/test_logged_in_customer_should_be_able_to_order_physical_product.py | .py | import pytest
from ..product.utils.preparing_product import prepare_product
from ..shop.utils.preparing_shop import prepare_default_shop
from ..utils import assign_permissions
from .utils import (
checkout_complete,
checkout_create,
checkout_delivery_method_update,
checkout_dummy_payment_create,
)
@p... | 95 | 2,756 |
lemur | lemur/plugins/bases/__init__.py | .py | from .destination import DestinationPlugin, ExportDestinationPlugin # noqa
from .issuer import IssuerPlugin # noqa
from .source import SourcePlugin # noqa
from .notification import NotificationPlugin, ExpirationNotificationPlugin # noqa
from .export import ExportPlugin # noqa
from .tls import TLSPlugin # noqa
fro... | 10 | 482 |
mlflow | mlflow/artifacts/__init__.py | .py | """
APIs for interacting with artifacts in MLflow
"""
import json
import pathlib
import posixpath
import tempfile
from typing import Any
from mlflow.entities.file_info import FileInfo
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import BAD_REQUEST, INVALID_PARAMETER_VALUE
from mlflo... | 273 | 9,974 |
conda | tests/plugins/test_config.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""
Tests for plugin configuration
"""
from pathlib import Path
from conda.auxlib.ish import dals
from conda.common.configuration import (
Configuration,
EnvRawParameter,
)
from conda.plugins.config import PluginConfig
def test_plugi... | 158 | 4,432 |
lemur | lemur/plugins/lemur_statsd/setup.py | .py | """Basic package information"""
from setuptools import setup, find_packages
install_requires = ["lemur", "datadog"]
setup(
name="lemur_statsd",
version="1.0.0",
author="Cloudflare Security Engineering",
author_email="",
include_package_data=True,
packages=find_packages(),
zip_safe=False,
... | 17 | 449 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_elementwise_ops.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# elementwise paddle model generator
#
import numpy as np
import sys
from save_model import saveModel
import paddle
if paddle.__version__ >= '2.6.0':
import paddle.base as fluid
else:
import paddle.fluid as fluid
def elementw... | 403 | 15,295 |
pyomo | pyomo/repn/tests/ampl/test_ampl_repn.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 37 | 1,479 |
saleor | saleor/discount/tests/test_tasks.py | .py | import datetime
from decimal import Decimal
from unittest.mock import ANY, patch
import graphene
import pytest
from django.db.models import Exists, OuterRef
from django.utils import timezone
from freezegun import freeze_time
from ...order.models import Order
from ...product.models import ProductChannelListing, Produc... | 477 | 17,387 |
black | tests/data/cases/conditional_expression.py | .py | long_kwargs_single_line = my_function(
foo="test, this is a sample value",
bar=some_long_value_name_foo_bar_baz if some_boolean_variable else some_fallback_value_foo_bar_baz,
baz="hello, this is a another value",
)
multiline_kwargs_indented = my_function(
foo="test, this is a sample value",
bar=som... | 205 | 4,910 |
beam | sdks/python/apache_beam/dataframe/doctests.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... | 755 | 25,104 |
probability | spinoffs/inference_gym/inference_gym/targets/ground_truth/stochastic_volatility_log_sp500_small.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... | 372 | 9,300 |
httpie | extras/packaging/linux/scripts/http_cli.py | .py | from httpie.__main__ import main
if __name__ == '__main__':
import sys
sys.exit(main())
| 6 | 97 |
loguru | tests/exceptions/source/backtrace/tail_recursion.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=False, backtrace=True, diagnose=False)
@logger.catch()
def a(n):
1 / n
a(n - 1)
def b(n):
1 / n
with logger.catch():
b(n - 1)
def c(n):
1 / n
try:
c(n - 1)
except ZeroDivis... | 40 | 408 |
luigi | examples/top_artists.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... | 267 | 8,851 |
probability | tensorflow_probability/python/math/psd_kernels/hypothesis_testlib.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,078 | 40,514 |
beam | sdks/python/apache_beam/io/hadoopfilesystem.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... | 453 | 14,464 |
beam | sdks/python/apache_beam/examples/snippets/transforms/elementwise/tostring_element.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");... | 60 | 1,795 |
astropy | astropy/cosmology/_src/tests/traits/test_trait_hubble.py | .py | import numpy as np
import pytest
import astropy.units as u
from astropy.cosmology._src.traits.hubble import HubbleParameter
from astropy.tests.helper import assert_quantity_allclose
class DummyHubble(HubbleParameter):
H0 = 70 * u.km / (u.s * u.Mpc)
def efunc(self, z):
return np.ones_like(np.asarray(... | 32 | 737 |
sqlmap | tamper/substring2leftright.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
import re
from lib.core.enums import PRIORITY
__priority__ = PRIORITY.NORMAL
def dependencies():
pass
def tamper(payload, **kwargs):
"""
Replaces PostgreSQL SUBSTR... | 48 | 1,210 |
confluent-kafka-python | examples/consumer.py | .py | #!/usr/bin/env python
#
# Copyright 2016 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... | 123 | 3,885 |
clearml | examples/reporting/media_reporting.py | .py | # ClearML - Example reporting video or audio links/file
#
import os
from clearml import Task, Logger
# Connecting ClearML with the current process,
# from here on everything is logged automatically
task = Task.init(project_name="examples", task_name="Audio and video reporting")
print('reporting audio and video sampl... | 27 | 977 |
astropy | astropy/modeling/separable.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Functions to determine if a model is separable, i.e.
if the model outputs are independent.
It analyzes ``n_inputs``, ``n_outputs`` and the operators
in a compound model by stepping through the transforms
and creating a ``coord_matrix`` of shape (``n_... | 325 | 9,876 |
textual | docs/examples/guide/css/nesting02.py | .py | from textual.app import App, ComposeResult
from textual.containers import Horizontal
from textual.widgets import Static
class NestingDemo(App):
"""App with nested CSS."""
CSS_PATH = "nesting02.tcss"
def compose(self) -> ComposeResult:
with Horizontal(id="questions"):
yield Static("Ye... | 20 | 479 |
pyomo | doc/OnlineDocs/src/data/table2.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 22 | 837 |
saleor | saleor/tests/e2e/vouchers/utils/prepare_voucher.py | .py | from ...vouchers.utils import create_voucher, create_voucher_channel_listing
def prepare_voucher(
e2e_staff_api_client,
channel_id,
voucher_code,
voucher_discount_type,
voucher_discount_value,
voucher_type,
products_list=None,
usage_limit=2,
single_use=True,
apply_once_per_orde... | 41 | 1,037 |
hatch | src/hatch/env/internal/__init__.py | .py | from __future__ import annotations
from typing import Any
from hatch.env.utils import ensure_valid_environment
def get_internal_env_config() -> dict[str, Any]:
from hatch.env.internal import build, static_analysis, test, type_check, uv
internal_config = {}
for env_name, env_config in (
("hatch-... | 61 | 2,436 |
deap | deap/tools/__init__.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 ... | 32 | 1,338 |
pyomo | pyomo/mpec/plugins/mpec4.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... | 209 | 7,409 |
openvino | tests/layer_tests/tensorflow_tests/test_tf_ToBool.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import tensorflow as tf
from common.tf_layer_test_class import CommonTFLayerTest
class TestToBool(CommonTFLayerTest):
def _prepare_input(self, inputs_info):
assert 'x:0' in inputs_info
... | 52 | 1,995 |
wagtail | wagtail/admin/panels/base.py | .py | from django.core.exceptions import ImproperlyConfigured
from django.utils.safestring import mark_safe
from wagtail.admin.forms.models import (
WagtailAdminDraftStateFormMixin,
WagtailAdminModelForm,
)
from wagtail.admin.telepath import register as register_telepath_adapter
from wagtail.admin.ui.components impo... | 340 | 12,827 |
onnxruntime | onnxruntime/test/python/onnxruntime_test_distributed.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import unittest
import numpy as np
import onnxscript
from mpi4py import MPI
from onnxscript import FLOAT, FLOAT16, INT64
import onnxruntime as ort
MICROSOFT_OPSET = onnxscript.values.Opset(domain="com.microsoft", version=1... | 1,673 | 63,582 |
astropy | astropy/io/fits/tests/test_image.py | .py | # Licensed under a 3-clause BSD style license - see PYFITS.rst
import math
import os
import time
import numpy as np
import pytest
from numpy.testing import assert_equal
from astropy.io import fits
from astropy.utils.compat import NUMPY_LT_2_5
from astropy.utils.data import get_pkg_data_filename
from astropy.utils.ex... | 1,215 | 46,962 |
rq | tests/test_intermediate_queue.py | .py | from datetime import datetime, timedelta, timezone
from unittest.mock import patch
import pytest
from rq import Queue, Worker
from rq.intermediate_queue import IntermediateQueue
from rq.job import JobStatus
from rq.maintenance import clean_intermediate_queue
from tests import RQTestCase, min_redis_version
from tests.... | 220 | 10,857 |
loguru | tests/exceptions/source/backtrace/chaining_second.py | .py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=False, backtrace=True, diagnose=False)
def a_decorator():
b_decorated()
def a_context_manager():
with logger.catch():
b_not_decorated()
def a_explicit():
try:
b_not_decorated()
except ... | 41 | 516 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/gemm_transpose_gen.py | .py | import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
onnxdomain = OperatorSetIdProto()
onnxdomain.version = 12
# The empty string ("") or absence of this field implies the operator set that is defined as part of the ONNX specification.
onnxdomain.domain = ""
msdomain = OperatorSetIdProto()
msdomain.ver... | 100 | 3,493 |
cvxpy | cvxpy/reductions/eliminate_pwl/canonicalizers/__init__.py | .py | """
Copyright 2017 Robin Verschueren
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, softw... | 52 | 2,000 |
coveragepy | tests/modules/pkg1/p1c.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
a = 1
b = 2
c = 3
| 7 | 176 |
openvino | src/bindings/python/src/openvino/test_utils/test_api.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from .test_utils_api import compare_functions as compare_functions_base
from openvino import Model
def compare_functions(lhs: Model, rhs: Model, compare_tensor_names: bool = True) -> tuple:
return compare_fu... | 11 | 393 |
beam | sdks/python/apache_beam/ml/gcp/recommendations_ai_test_it.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... | 133 | 4,450 |
scikit-bio | skbio/io/format/tests/test_blast6.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.
# --------------------------------------------... | 124 | 6,399 |
sqlmap | lib/core/data.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.datatype import AttribDict
from lib.core.log import LOGGER
# sqlmap paths
paths = AttribDict()
# object to store original command line options
cmdLineOptions = Att... | 32 | 727 |
httpie | extras/packaging/linux/scripts/hooks/hook-pip.py | .py | from pathlib import Path
from PyInstaller.utils.hooks import collect_all
def hook(hook_api):
for pkg in [
'pip',
'setuptools',
'distutils',
'pkg_resources'
]:
datas, binaries, hiddenimports = collect_all(pkg)
hook_api.add_datas(datas)
hook_api.add_binarie... | 15 | 377 |
python-prompt-toolkit | examples/full-screen/simple-demos/horizontal-split.py | .py | #!/usr/bin/env python
"""
Horizontal split example.
"""
from prompt_toolkit.application import Application
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout.containers import HSplit, Window
from prompt_toolkit.layout.controls import FormattedTextControl
from prompt_toolkit.layout.layout imp... | 46 | 948 |
openvino | src/frontends/onnx/tests/tests_python/utils/onnx_helpers.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import onnx
from openvino import Core, Tensor, Model
def import_onnx_model(model: onnx.ModelProto) -> Model:
onnx.checker.check_model(model)
model_byte_string = model.SerializeToStrin... | 18 | 447 |
metrics | docs/source/pyplots/binary_accuracy_multistep.py | .py | import matplotlib.pyplot as plt
import torch
import torchmetrics
N = 10
num_updates = 10
num_steps = 5
w = torch.tensor([0.2, 0.8])
target = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
preds = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
fig, ax = p... | 25 | 635 |
cvxpy | cvxpy/reductions/solvers/nlp_solvers/diff_engine/helpers.py | .py | """
Copyright 2025, the CVXPY 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 law or agreed to in writing, s... | 108 | 3,841 |
hatch | backend/src/hatchling/ouroboros.py | .py | from __future__ import annotations
import os
import re
from ast import literal_eval
from typing import Any
from hatchling.build import * # noqa: F403
def read_dependencies() -> list[str]:
pattern = r"^dependencies = (\[.*?\])$"
with open(os.path.join(os.getcwd(), "pyproject.toml"), encoding="utf-8") as f:... | 53 | 1,507 |
coveragepy | tests/test_context.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
"""Tests for context support."""
from __future__ import annotations
import inspect
import os.path
from typing import Any
from unittest import mock
import pyte... | 312 | 10,605 |
sqlmap | plugins/dbms/mssqlserver/__init__.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.enums import DBMS
from lib.core.settings import MSSQL_SYSTEM_DBS
from lib.core.unescaper import unescaper
from plugins.dbms.mssqlserver.enumeration import Enumeratio... | 30 | 949 |
sphinx | tests/test_transforms/test_unreferenced_footnotes.py | .py | """Test the ``UnreferencedFootnotesDetector`` transform."""
from __future__ import annotations
from typing import TYPE_CHECKING
from sphinx._cli.util.errors import strip_escape_sequences
from sphinx.testing.util import SphinxTestApp
if TYPE_CHECKING:
from pathlib import Path
from sphinx.testing.util import... | 51 | 1,698 |
black | tests/data/cases/format_unicode_escape_seq.py | .py | x = "\x1F"
x = "\\x1B"
x = "\\\x1B"
x = "\U0001F60E"
x = "\u0001F60E"
x = r"\u0001F60E"
x = "don't format me"
x = "\xA3"
x = "\u2717"
x = "\uFaCe"
x = "\N{ox}\N{OX}"
x = "\N{lAtIn smaLL letteR x}"
x = "\N{CYRILLIC small LETTER BYELORUSSIAN-UKRAINIAN I}"
x = b"\x1Fdon't byte"
x = rb"\x1Fdon't format"
# output
x = "\x1... | 34 | 613 |
mlflow | tests/genai/judges/test_builtin.py | .py | import json
from unittest import mock
import pytest
from mlflow.entities.assessment import (
AssessmentError,
AssessmentSource,
AssessmentSourceType,
Feedback,
)
from mlflow.exceptions import MlflowException
from mlflow.genai import judges
from mlflow.genai.evaluation.entities import EvalItem, EvalRes... | 737 | 26,811 |
saleor | saleor/graphql/meta/schema.py | .py | import graphene
from .mutations import (
DeleteMetadata,
DeletePrivateMetadata,
UpdateMetadata,
UpdatePrivateMetadata,
)
class MetaMutations(graphene.ObjectType):
delete_metadata = DeleteMetadata.Field()
delete_private_metadata = DeletePrivateMetadata.Field()
update_metadata = UpdateMetad... | 16 | 392 |
pyomo | pyomo/contrib/pynumero/examples/sensitivity.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... | 153 | 4,617 |
qutip | qutip/tests/core/data/test_csr.py | .py | import numpy as np
import scipy.sparse
import pytest
from qutip.core import data
from qutip.core.data import csr
from qutip import qeye, CoreOptions
from . import conftest
# We only choose a small subset of dtypes to test so it isn't crazy.
_dtype_complex = ['complex128']
_dtype_float = ['float64']
_dtype_int = ['in... | 418 | 17,017 |
coremltools | deps/pybind11/tests/test_embed/test_interpreter.py | .py | from __future__ import annotations
import sys
from widget_module import Widget
class DerivedWidget(Widget):
def __init__(self, message):
super().__init__(message)
def the_answer(self):
return 42
def argv0(self):
return sys.argv[0]
| 17 | 273 |
coremltools | coremltools/converters/mil/mil/ops/defs/iOS16/tensor_operation.py | .py | # Copyright (c) 2022, 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-Clausefrom
import numpy as np
from coremltools.converters.mil.mil import types
from coremltools.converters.... | 116 | 3,931 |
beam | sdks/python/apache_beam/runners/dataflow/test_dataflow_runner.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... | 107 | 4,214 |
textual | tests/option_list/test_option_list_mouse_hover.py | .py | """Unit tests aimed at checking the OptionList mouse hover handing."""
from __future__ import annotations
from textual.app import App, ComposeResult
from textual.geometry import Offset
from textual.widgets import Label, OptionList
from textual.widgets.option_list import Option
class OptionListApp(App[None]):
""... | 66 | 2,703 |
clearml | clearml/utilities/pigar/log.py | .py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import logging.handlers
logger = logging.getLogger("pigar")
logger.setLevel(logging.WARNING)
| 9 | 185 |
saleor | saleor/settings.py | .py | import datetime
import importlib.metadata
import json
import logging
import os
import os.path
import warnings
from typing import cast
from urllib.parse import urlparse
import dj_database_url
import dj_email_url
import django_cache_url
import django_stubs_ext
import sentry_sdk
import sentry_sdk.utils
from celery.schedu... | 1,294 | 49,581 |
mlflow | mlflow/store/model_registry/abstract_store.py | .py | import json
import logging
import re
import threading
from abc import ABCMeta, abstractmethod
from time import sleep, time
from typing import Any
from pydantic import BaseModel
from mlflow.entities.logged_model_tag import LoggedModelTag
from mlflow.entities.model_registry import ModelVersionTag, RegisteredModelTag
fr... | 1,313 | 48,103 |
qutip | qutip/legacy/rcsolve.py | .py | """
This module provides exact solvers for a system-bath setup using the
reaction coordinate method.
"""
# Author: Neill Lambert, Anubhav Vardhan
# Contact: nwlambert@gmail.com
__all__ = ['rcsolve']
import warnings
import numpy as np
import scipy.sparse as sp
from numpy import matrix
from numpy import linalg
from ..... | 121 | 3,707 |
cvxpy | cvxpy/tests/test_qp_solvers.py | .py | """
Copyright 2013 Steven Diamond, 2017 Robin Verschueren
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 agree... | 937 | 33,509 |
biopython | Bio/SeqUtils/lcc.py | .py | # Copyright 2003, 2007 by Sebastian Bassi. sbassi@genesdigitales.com
# 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
#... | 153 | 5,502 |
pyomo | pyomo/contrib/latex_printer/latex_printer.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 1,354 | 46,960 |
clearml | clearml/utilities/__init__.py | .py | from .dicts import Logs
__all__ = ["Logs"]
| 4 | 44 |
wandb | wandb/apis/public/registries/_members.py | .py | """Types and helpers for managing registry members."""
from __future__ import annotations
from collections import defaultdict
from collections.abc import Iterable
from enum import Enum
from functools import singledispatchmethod
from typing import Literal, Union
from pydantic.dataclasses import dataclass as pydantic_... | 112 | 3,374 |
pyomo | pyomo/dataportal/parse_datacmds.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... | 589 | 14,526 |
saleor | saleor/graphql/core/tests/garbage_collection/utils.py | .py | import gc
def disable_gc_for_garbage_collection_test():
# Disable automatic garbage collection. To have control over when
# garbage collection is performed. This is necessary to ensure that another
# that thread doesn't accidentally trigger it by simply executing code.
gc.disable()
# Delete the g... | 28 | 1,063 |
returns | tests/test_contrib/test_hypothesis/test_type_resolution.py | .py | from collections.abc import Callable, Sequence
from typing import Any, TypeVar
import pytest
from hypothesis import given
from hypothesis import strategies as st
from returns.context import (
Reader,
RequiresContext,
RequiresContextFutureResult,
RequiresContextFutureResultE,
RequiresContextIOResul... | 306 | 9,303 |
saleor | saleor/graphql/core/filters/where_input.py | .py | import graphene
from ..scalars import UUID, Date, DateTime, Decimal
from ..types import NonNullList
from ..types.common import (
DateRangeInput,
DateTimeRangeInput,
DecimalRangeInput,
IntRangeInput,
)
from .filter_input import FilterInputObjectType
class WhereInputObjectType(FilterInputObjectType):
... | 205 | 6,679 |
onnx | onnx/backend/test/case/node/atanh.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 Atanh(Base):
@staticmethod
def export() -> None:
node ... | 29 | 798 |
kafka | docker/common.py | .py | #!/usr/bin/env python
# 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 "Lice... | 82 | 3,231 |
saleor | saleor/tests/e2e/account/utils/user.py | .py | from ...utils import get_graphql_content
from .fragments import ADDRESS_FRAGMENT
USER_QUERY = (
"""
query User($id: ID!) {
user(id: $id) {
id
email
firstName
lastName
isStaff
isActive
isConfirmed
addresses {... | 53 | 1,087 |
astropy | astropy/stats/sigma_clipping.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import warnings
from collections.abc import Callable
from typing import Literal
import numpy as np
from numpy.lib.array_utils import normalize_axis_index
from numpy.typing import ArrayLike, NDArray
from astropy.stats._fast_sigma_clip import _sigma_clip_... | 1,359 | 50,741 |
probability | tensorflow_probability/python/math/psd_kernels/changepoint_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 o... | 136 | 5,326 |
onnx | tests/python/parser_test.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import locale
import platform
import pytest
import onnx
from onnx import GraphProto, OperatorSetIdProto, TensorProto, checker
class TestBasicFunctions:
def check_graph(self, graph: GraphProto) ->... | 411 | 14,717 |
clearml | examples/frameworks/scikit-learn/sklearn_matplotlib_example.py | .py | import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import ShuffleSplit
from sklearn.model_selection import learning_curve
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from clearml import Task
def plot_learning_curve(estim... | 156 | 6,221 |
coremltools | coremltools/converters/mil/mil/types/annotate.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
class delay_type_cls:
def __getattr__(self, t):
return t
# this delay type thingee is ... | 116 | 3,411 |
wandb | wandb/automations/scopes.py | .py | """Scopes in which a W&B Automation can be triggered."""
from __future__ import annotations
from typing import Annotated, Literal
from pydantic import BeforeValidator, Discriminator, Field
from wandb._pydantic import GQLBase
from ._generated import (
ArtifactPortfolioScopeFields,
ArtifactSequenceScopeField... | 122 | 3,417 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.