repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
saleor | saleor/checkout/tests/webhooks/test_exclude_shipping.py | .py | import json
import uuid
from decimal import Decimal
from unittest import mock
import graphene
import pytest
from measurement.measures import Weight
from prices import Money
from promise import Promise
from ....graphql.core.utils import to_global_id_or_none
from ....graphql.tests.utils import get_graphql_content
from ... | 449 | 13,824 |
saleor | saleor/graphql/core/types/user_or_app.py | .py | import graphene
from ....account import models as account_models
from ....app import models as app_models
from ...account import types as account_types
from ...app import types as app_types
# The file hasn't been attached to the __init__ file as it generates the circular
# graphql import. Graphene for Union types re... | 23 | 795 |
coremltools | coremltools/converters/mil/frontend/tensorflow/tf_graph_pass/quantization_pass.py | .py | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from ..basic_graph_ops import delete_node
def delete_fakequant_node_and_repair_graph(g, node):
... | 64 | 2,966 |
httpie | httpie/internal/update_warnings.py | .py | import json
from contextlib import nullcontext, suppress
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Optional, Callable
import requests
import httpie
from httpie.context import Environment, LogLevel
from httpie.internal.__build_channel__ import BUILD_CHANNEL
from httpie.i... | 172 | 5,178 |
astropy | astropy/cosmology/_src/tests/test_parameters.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from types import MappingProxyType
import numpy as np
import pytest
from astropy.cosmology import parameters, realizations
def test_realizations_in_dir():
"""Test the realizations are in ``dir`` of :mod:`astropy.cosmology.parameters`."""
d = d... | 45 | 1,406 |
saleor | saleor/graphql/giftcard/tests/mutations/test_gift_card_balance_adjust.py | .py | from decimal import Decimal
import graphene
from .....giftcard import GiftCardEvents
from .....giftcard.error_codes import GiftCardErrorCode
from .....giftcard.models import GiftCardEvent
from ....tests.utils import assert_no_permission, get_graphql_content
MUTATION = """
mutation GiftCardBalanceAdjust($id: ID!,... | 144 | 4,769 |
mlflow | mlflow/pyfunc/_mlflow_pyfunc_backend_predict.py | .py | """
This script should be executed in a fresh python interpreter process using `subprocess`.
"""
import argparse
from mlflow.pyfunc.scoring_server import _predict
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--model-uri", required=True)
parser.add_argument("--input-path", re... | 62 | 1,928 |
onnxruntime | onnxruntime/python/tools/transformers/fusion_skip_group_norm.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
from logging import getLogger
from fusion_base import Fusion
from fusio... | 255 | 10,601 |
httpie | httpie/plugins/base.py | .py | from typing import Tuple
class BasePlugin:
# The name of the plugin, eg. "My auth".
name = None
# Optional short description. It will be shown in the help
# under --auth-type.
description = None
# This be set automatically once the plugin has been loaded.
package_name = None
class Auth... | 166 | 4,529 |
saleor | saleor/graphql/payment/mutations/payment/payment_initialize.py | .py | import graphene
from django.core.exceptions import ValidationError
from .....channel.models import Channel
from .....payment import PaymentError
from .....payment.error_codes import PaymentErrorCode
from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_PAYMENTS
from ....core.fields import JSO... | 85 | 3,012 |
omegaconf | tests/test_update.py | .py | from typing import Any, Union
from pytest import mark, param, raises
from omegaconf import DictConfig, ListConfig, OmegaConf, ValidationError
from omegaconf._utils import _ensure_container, is_primitive_container
from omegaconf.errors import (
ConfigAttributeError,
ConfigKeyError,
ConfigTypeError,
Int... | 556 | 16,483 |
biopython | Bio/PDB/HSExposure.py | .py | # Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk)
#
# 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.
"""Half-sphere expos... | 328 | 11,337 |
cvxpy | cvxpy/atoms/elementwise/sqrt.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... | 26 | 805 |
clearml | clearml/backend_api/services/v2_23/auth.py | .py | """
auth service
This service provides authentication management and authorization
validation for the entire system.
"""
from typing import List, Optional, Any
import six
from datetime import datetime
from dateutil.parser import parse as parse_datetime
from clearml.backend_api.session import (
Request,
Respons... | 748 | 22,785 |
pyro | pyro/infer/reparam/reparam.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import warnings
from abc import ABC
from typing import Callable, Optional
import torch
from typing_extensions import TypedDict
class ReparamMessage(TypedDict):
name: str
fn: Callable
value: Optional[torch.Tensor]
... | 83 | 2,505 |
beam | sdks/python/apache_beam/io/iobase_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... | 73 | 2,603 |
beam | sdks/python/apache_beam/runners/portability/sdk_container_builder_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... | 169 | 6,643 |
sqlmap | lib/utils/pivotdumptable.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.agent import agent
from lib.core.bigarray import BigArray
from lib.core.common import Backend
from lib.core.common import filterNone
from lib.core.common ... | 216 | 8,769 |
confluent-kafka-python | setup.py | .py | #!/usr/bin/env python
import os
import platform
from setuptools import Extension, setup
work_dir = os.path.dirname(os.path.realpath(__file__))
mod_dir = os.path.join(work_dir, 'src', 'confluent_kafka')
ext_dir = os.path.join(mod_dir, 'src')
# On Un*x the library is linked as -lrdkafka,
# while on windows we need th... | 34 | 922 |
openvino | tests/layer_tests/tensorflow2_keras_tests/test_tf2_keras_attention.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import tensorflow as tf
from common.tf2_layer_test_class import CommonTF2LayerTest
class TestKerasAttention(CommonTF2LayerTest):
def create_keras_attention_net(self, dropout, use_scale, input_names, input_shapes,
... | 70 | 3,400 |
pymc | pymc/step_methods/state.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... | 122 | 4,975 |
saleor | saleor/tests/e2e/gift_cards/utils/gift_card_bulk_create.py | .py | from ...utils import get_graphql_content
GIFT_CARD_BULK_CREATE_MUTATION = """
mutation GiftCardBulkCreate($input: GiftCardBulkCreateInput!) {
giftCardBulkCreate(input: $input) {
giftCards {
id
code
initialBalance{
amount
}
}
errors {
code
field
message
... | 50 | 1,039 |
lemur | lemur/policies/cli.py | .py | """
.. module: lemur.policies.cli
: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>
"""
import click
from flask.cli import with_appcontext
from lemur.policies import service as po... | 35 | 952 |
confluent-kafka-python | src/confluent_kafka/_util/librdkafka_string_parser.py | .py | # Copyright 2026 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... | 166 | 6,366 |
mlflow | tests/tracing/utils/test_prompt.py | .py | import json
import pytest
from mlflow.entities.model_registry import PromptVersion
from mlflow.exceptions import MlflowException
from mlflow.tracing.utils.prompt import update_linked_prompts_tag
def test_update_linked_prompts_tag():
pv1 = PromptVersion(name="test_prompt", version=1, template="Test template")
... | 42 | 1,804 |
saleor | saleor/order/tests/webhooks/static_payloads/test_order_calculate_taxes.py | .py | import datetime
import json
from decimal import Decimal
from unittest.mock import patch
import graphene
import pytest
from freezegun import freeze_time
from .....core.prices import quantize_price
from .....discount import DiscountType, DiscountValueType, VoucherType
from .....webhook.serializers import serialize_vari... | 366 | 13,543 |
probability | tensorflow_probability/python/experimental/bayesopt/acquisition/acquisition_function_test.py | .py | # Copyright 2023 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 74 | 2,615 |
hypercorn | tests/middleware/test_dispatcher.py | .py | from __future__ import annotations
from collections.abc import Callable
from typing import cast
import pytest
from hypercorn.middleware.dispatcher import AsyncioDispatcherMiddleware, TrioDispatcherMiddleware
from hypercorn.typing import HTTPScope, Scope
@pytest.mark.asyncio
async def test_dispatcher_middleware(htt... | 92 | 3,194 |
structlog | tests/test_generic.py | .py | # SPDX-License-Identifier: MIT OR Apache-2.0
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the MIT License. See the LICENSE file in the root of this
# repository for complete details.
import pickle
import pytest
import time_machine
from structlog._config import _CONFIG
from ... | 66 | 1,676 |
sphinx | sphinx/builders/html/_build_info.py | .py | """Record metadata for the build process."""
from __future__ import annotations
from typing import TYPE_CHECKING
from sphinx.locale import __
from sphinx.util._serialise import stable_hash
if TYPE_CHECKING:
from collections.abc import Set
from pathlib import Path
from sphinx.config import Config, _Conf... | 80 | 2,642 |
pyomo | pyomo/contrib/mpc/data/tests/test_find_nearest_index.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 | 8,635 |
ipython | IPython/utils/data.py | .py | """Utilities for working with data structures like lists, dicts and tuples.
"""
from __future__ import annotations
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full licen... | 51 | 1,689 |
openvino | tests/layer_tests/tensorflow_lite_tests/test_tfl_ScatterND.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 = [
{'indices_shape': [4, 1], 'indices_value': [4, 3, 1, 7], 'updates_dtype': np.int32, 'updates_shape': [4],
'shape_shape': [1], 'shape_value': [8]},
{'indi... | 75 | 3,825 |
gunicorn | tests/requests/valid/028.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.config import Config
cfg = Config()
cfg.set("strip_header_spaces", True)
request = {
"method": "GET",
"uri": uri("/stuff/here?foo=bar"),
"version": (1, 1),
"headers": [
("CON... | 18 | 367 |
saleor | saleor/graphql/account/tests/mutations/customer_type/test_customer_type_delete.py | .py | from unittest.mock import patch
import graphene
from ......account.error_codes import CustomerTypeDeleteErrorCode
from ......account.models import CustomerType
from .....tests.utils import assert_no_permission, get_graphql_content
CUSTOMER_TYPE_DELETE_MUTATION = """
mutation CustomerTypeDelete($id: ID!) {
... | 135 | 4,176 |
beam | sdks/python/apache_beam/transforms/external_transform_provider_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... | 415 | 16,228 |
saleor | saleor/tests/e2e/promotions/test_staff_can_change_catalog_predicate.py | .py | import pytest
from ....product.tasks import recalculate_discounted_price_for_products_task
from ..product.utils import (
create_collection,
create_collection_channel_listing,
create_product_variant,
create_product_variant_channel_listing,
get_product,
)
from ..product.utils.collection_add_products ... | 140 | 4,555 |
pyomo | pyomo/core/tests/unit/test_kkt.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... | 519 | 19,217 |
wandb | wandb/automations/_generated/operations.py | .py | # Generated by ariadne-codegen
# Source: tools/graphql_codegen/automations/
__all__ = [
"CREATE_AUTOMATION_GQL",
"CREATE_GENERIC_WEBHOOK_INTEGRATION_GQL",
"DELETE_AUTOMATION_GQL",
"GET_AUTOMATIONS_LEGACY_GQL",
"GET_ENTITY_AUTOMATIONS_GQL",
"GET_ENTITY_AUTOMATIONS_LEGACY_GQL",
"GET_ORG_AUTOM... | 813 | 13,509 |
beam | sdks/python/apache_beam/examples/inference/tfx_bsl/tensorflow_image_classification.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... | 194 | 7,030 |
gunicorn | tests/test_dirty_protocol.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
"""Tests for dirty worker binary protocol module."""
import asyncio
import os
import socket
import struct
import pytest
from gunicorn.dirty.protocol import (
BinaryProtocol,
DirtyProtocol,
make_reques... | 568 | 20,754 |
onnxruntime | onnxruntime/python/tools/quantization/registry.py | .py | from .operators.activation import QDQRemovableActivation, QLinearActivation
from .operators.argmax import QArgMax
from .operators.attention import AttentionQuant
from .operators.base_operator import QuantOperatorBase
from .operators.binary_op import QLinearBinaryOp
from .operators.concat import QLinearConcat
from .oper... | 113 | 3,807 |
metrics | src/torchmetrics/functional/text/squad.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... | 253 | 9,843 |
sqlmap | lib/request/keepalive.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
import socket
import threading
import time
from lib.core.settings import KEEPALIVE_IDLE_TIMEOUT
from lib.core.settings import KEEPALIVE_MAX_REQUESTS
from thirdparty.six.moves imp... | 348 | 12,982 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_unstack.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
# unstack paddle model generator
#
import paddle
import numpy as np
from save_model import saveModel
import sys
def unstack(name: str, x, axis):
paddle.enable_static()
with paddle.static.program_guard(paddle.static.Program()... | 47 | 1,362 |
readthedocs.org | readthedocs/analytics/utils.py | .py | """Utilities related to analytics."""
import hashlib
import ipaddress
import structlog
from django.conf import settings
from django.utils.crypto import get_random_string
from django.utils.encoding import force_bytes
from django.utils.encoding import force_str
from user_agents import parse
log = structlog.get_logger... | 90 | 2,856 |
jupytext | tests/data/notebooks/outputs/ipynb_to_script_vim_folding_markers/Line_breaks_in_LateX_305.py | .py | # ---
# jupyter:
# jupytext:
# cell_markers: '{{{,}}}'
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# This cell uses no particular cell marker
#
# $$
# \begin{align}
# \dot{x} & = \sigma(y-x)\\
# \dot{y} & = \rho x - y - xz \\
# \dot{z} & = -\beta z + xy
# \end{al... | 44 | 802 |
beam | learning/katas/python/Common Transforms/Aggregation/Smallest/task.py | .py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); y... | 36 | 1,223 |
mlflow | tests/server/test_workspace_endpoints.py | .py | from __future__ import annotations
import json
from unittest import mock
import pytest
from flask import Flask
from mlflow.entities.workspace import Workspace, WorkspaceDeletionMode
from mlflow.server.handlers import get_endpoints
@pytest.fixture(autouse=True)
def enable_workspaces(monkeypatch):
monkeypatch.se... | 493 | 18,132 |
readthedocs.org | readthedocs/oauth/apps.py | .py | """OAuth app config."""
from django.apps import AppConfig
class OAuthConfig(AppConfig):
name = "readthedocs.oauth"
def ready(self):
import readthedocs.oauth.signals # noqa
| 11 | 193 |
openvino | src/bindings/python/src/openvino/frontend/pytorch/__init__.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""Package: openvino.
Low level wrappers for the FrontEnd C++ API.
"""
try:
from openvino.frontend.pytorch.py_pytorch_frontend import _FrontEndPytorchDecoder as Decoder
from openvino.frontend.pytorch.py_... | 19 | 869 |
attrs | typing_tests/baseline.py | .py | # SPDX-License-Identifier: MIT
# pyright: strict
"""
Baseline features that should be supported by all type checkers.
"""
from __future__ import annotations
from typing import Any, Generator
import attrs
@attrs.define(order=True)
class NGClass:
x: int = attrs.field(default=42)
ngc = NGClass(1)
ngc = attrs.... | 228 | 4,329 |
beam | sdks/python/apache_beam/io/gcp/bigquery_read_internal_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... | 171 | 7,026 |
pdm | src/pdm/models/repositories/pypi.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, cast
from pdm.exceptions import CandidateInfoNotFound, CandidateNotFound
from pdm.models.candidates import Candidate
from pdm.models.repositories.base import BaseRepository, CandidateMetadata, cache_result
from pdm.models.requirements import Require... | 96 | 4,165 |
ipython | tools/gen_latex_symbols.py | .py | # coding: utf-8
# This script autogenerates `IPython.core.latex_symbols.py`, which contains a
# single dict , named `latex_symbols`. The keys in this dict are latex symbols,
# such as `\\alpha` and the values in the dict are the unicode equivalents for
# those. Most importantly, only unicode symbols that are valid ide... | 100 | 2,939 |
probability | tensorflow_probability/python/distributions/jax_transformation_test.py | .py | # Copyright 2020 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 465 | 17,279 |
wagtail | wagtail/api/v3/errors.py | .py | from http import HTTPStatus
from typing import Any
from django.core.exceptions import PermissionDenied
from django.core.exceptions import ValidationError as DjangoValidationError
from django.http import Http404, HttpRequest, HttpResponse
from ninja import NinjaAPI, Schema
from ninja.errors import HttpError
from ninja.... | 172 | 5,763 |
onnxruntime | onnxruntime/test/python/quantization/test_quant_util.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.
# ---------------------------------------------------------------... | 235 | 11,095 |
sphinx | tests/roots/test-latex-babel/conf.py | .py | numfig_format = {
'figure': 'Fig. %s',
'table': 'Table. %s',
'code-block': 'List.',
}
| 6 | 98 |
cvxpy | cvxpy/tests/test_solver_inverse_data.py | .py | """
Copyright 2025 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... | 45 | 1,619 |
sphinx | tests/test_builders/test_build_html_highlight.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import ANY, call, patch
import pytest
from sphinx.builders.html import StandaloneHTMLBuilder
if TYPE_CHECKING:
from sphinx.testing.util import SphinxTestApp
@pytest.mark.sphinx('html', testroot='basic', confoverrides={'html... | 132 | 3,797 |
metrics | tests/unittests/segmentation/test_dice.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... | 216 | 8,273 |
onnx | onnx/reference/ops/op_asinh.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import numpy as np
from onnx.reference.ops._op import OpRunUnaryNum
class Asinh(OpRunUnaryNum):
def _run(self, x):
return (np.arcsinh(x),)
| 14 | 271 |
lemur | lemur/plugins/lemur_acme/tests/test_ultradns.py | .py | import unittest
from unittest.mock import patch, Mock
from flask import Flask
from lemur.plugins.lemur_acme import plugin, ultradns
from requests.models import Response
class TestUltradns(unittest.TestCase):
@patch("lemur.plugins.lemur_acme.plugin.dns_provider_service")
def setUp(self, mock_dns_provider_serv... | 150 | 7,050 |
jupytext | tests/data/notebooks/outputs/ipynb_to_script_vscode_folding_markers/raw_cell_with_complex_yaml_like_content.py | .py | # ---
#
# This is a complex paragraph
# that is split over multiple lines.
#
# It also includes blank lines.
#
#
# jupyter:
# jupytext:
# cell_markers: region,endregion
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
print("Hello, World!")
| 19 | 293 |
kafka | docker/prepare_docker_official_image_source.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... | 70 | 3,473 |
black | tests/test_tokenize.py | .py | """Tests for the blib2to3 tokenizer."""
import sys
import textwrap
from dataclasses import dataclass
import black
from blib2to3.pgen2 import token, tokenize
@dataclass
class Token:
type: str
string: str
start: tokenize.Coord
end: tokenize.Coord
def get_tokens(text: str) -> list[Token]:
"""Retu... | 108 | 3,571 |
wandb | wandb/sdk/artifacts/artifact_file_cache.py | .py | """Artifact cache."""
from __future__ import annotations
import contextlib
import errno
import hashlib
import os
import shutil
import subprocess
import sys
from collections.abc import Generator
from contextlib import AbstractContextManager
from functools import lru_cache
from pathlib import Path
from tempfile import ... | 258 | 10,033 |
saleor | saleor/graphql/product/tests/mutations/test_product_type_delete.py | .py | import json
from unittest import mock
from unittest.mock import patch
import graphene
import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from prices import Money, TaxedMoney
from .....attribute.utils import associate_attribute_values_to_instance
from .....core.utils.j... | 224 | 8,039 |
pyro | pyro/poutine/equalize_messenger.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import re
from typing import List, Optional, Union
from typing_extensions import Self
from pyro.distributions import Delta
from pyro.poutine.messenger import Messenger
from pyro.poutine.runtime import Message
class EqualizeMessenge... | 105 | 4,520 |
saleor | saleor/tests/e2e/orders/taxes/test_order_calculate_simple_taxes_based_on_shipping_tax_class.py | .py | import pytest
from ... import DEFAULT_ADDRESS
from ...product.utils.preparing_product import prepare_product
from ...shipping_zone.utils import update_shipping_price
from ...shop.utils import prepare_shop
from ...taxes.utils import update_country_tax_rates
from ...utils import assign_permissions
from ..utils import (
... | 176 | 5,814 |
mlflow | mlflow/store/tracking/utils/trace_archival.py | .py | from __future__ import annotations
import logging
from dataclasses import dataclass
from enum import Enum
from mlflow.entities import TraceInfo
from mlflow.exceptions import MlflowException
from mlflow.tracing.constant import TraceExperimentTagKey
from mlflow.utils.validation import (
_parse_trace_archival_durati... | 179 | 5,142 |
wagtail | wagtail/admin/tests/test_views.py | .py | from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
from wagtail.admin.forms.auth import PasswordResetForm
from wagtail.admin.tests.test_forms import CustomLoginForm, CustomPasswordResetForm
from wagtail.test.utils import Page, PageFixtures... | 248 | 9,475 |
saleor | saleor/tax/utils.py | .py | import logging
from collections import defaultdict
from collections.abc import Iterable
from decimal import Decimal
from typing import TYPE_CHECKING, Optional
from django.conf import settings
from prices import TaxedMoney
from ..core.utils.country import get_active_country
from ..tax.models import TaxClass, TaxClassC... | 403 | 14,348 |
beam | sdks/python/apache_beam/testing/analyzers/perf_analysis.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... | 294 | 11,922 |
conda | conda/_private/shards/__init__.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from . import cache, subset
from .shards import (
ShardBase,
ShardLike,
Shards,
fetch_channels,
fetch_shards_index,
)
__all__ = [
"cache",
"subset",
"ShardBase",
"ShardLike",
"Shards",
"fetch_shards_i... | 21 | 351 |
onnxruntime | onnxruntime/python/tools/transformers/models/llama/llama_torch.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import l... | 48 | 1,685 |
toolz | toolz/recipes.py | .py | import itertools
from .itertoolz import frequencies, pluck, getter
__all__ = ('countby', 'partitionby')
def countby(key, seq):
""" Count elements of a collection by a key function
>>> countby(len, ['cat', 'mouse', 'dog'])
{3: 2, 5: 1}
>>> def iseven(x): return x % 2 == 0
>>> countby(iseven, [1... | 47 | 1,256 |
conda | tests/cli/test_main_run.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import os
import stat
import subprocess
import uuid
from logging import WARNING, getLogger
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from conda.auxlib.ish import dals
from conda... | 516 | 16,209 |
biopython | Bio/PDB/Selection.py | .py | # Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk)
#
# 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.
"""Selection of atom... | 86 | 2,589 |
wandb | tests/unit_tests/test_launch/test_agent/test_run_queue_item_saver.py | .py | import os
from unittest.mock import MagicMock
import wandb
from wandb.sdk.launch.agent.run_queue_item_file_saver import RunQueueItemFileSaver
def test_no_run():
saver = RunQueueItemFileSaver(None, "test_run_queue_item_id")
assert saver.save_contents("contents", "fname", "error") is None
def test_run():
... | 32 | 965 |
mlflow | mlflow/store/db_migrations/versions/1971f2d9a75b_add_trace_archival_candidate_index.py | .py | """add trace archival candidate index
Revision ID: 1971f2d9a75b
Revises: 6f8d9c3b2a1e
Create Date: 2026-08-09 00:00:00.000000
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "1971f2d9a75b"
down_revision = "6f8d9c3b2a1e"
branch_labels = None
depends_on = None
def upgrade():
op.c... | 29 | 559 |
mlflow | mlflow/tracking/metric_value_conversion_utils.py | .py | import sys
from mlflow.exceptions import INVALID_PARAMETER_VALUE, MlflowException
def _is_module_imported(module_name: str) -> bool:
return module_name in sys.modules
def _try_get_item(x):
try:
return x.item()
except Exception as e:
raise MlflowException(
f"Failed to convert... | 94 | 2,249 |
luigi | test/task_bulk_complete_test.py | .py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2016 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... | 57 | 2,166 |
python-prompt-toolkit | examples/prompts/autocorrection.py | .py | #!/usr/bin/env python
"""
Example of implementing auto correction while typing.
The word "impotr" will be corrected when the user types a space afterwards.
"""
from prompt_toolkit import prompt
from prompt_toolkit.key_binding import KeyBindings
# Database of words to be replaced by typing.
corrections = {
"impot... | 46 | 1,095 |
conda | tests/gateways/test_streams.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
from conda.gateways.logging import TokenURLFilter
from conda.gateways.streams import redact_token_urls, stderr, stdout
if TYPE_CHECKING:
from pytest import CaptureFixture... | 28 | 963 |
biopython | Bio/SearchIO/InfernalIO/__init__.py | .py | # Copyright 2024 by Samuel Prince. 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 ... | 234 | 15,555 |
cvxpy | cvxpy/reductions/complex2real/canonicalizers/abs_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... | 32 | 1,087 |
beam | learning/tour-of-beam/learning-content/core-transforms/composite/python-example/task.py | .py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); y... | 59 | 1,945 |
jupytext | tests/data/notebooks/outputs/ipynb_to_percent/notebook_with_complex_metadata.py | .py | # ---
# jupyter:
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %%
| 10 | 117 |
jupytext | tests/data/notebooks/outputs/ipynb_to_script_vim_folding_markers/frozen_cell.py | .py | # ---
# jupyter:
# jupytext:
# cell_markers: '{{{,}}}'
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# This is an unfrozen cell. Works as usual.
print("I'm a regular cell so I run and print!")
# {{{ deletable=false editable=false run_control={"frozen": true}
# # T... | 18 | 392 |
hydra | plugins/hydra_ray_launcher/tests/ray_aws_launcher_tests_disabled.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""Legacy Ray AWS tests disabled from automatic pytest collection.
Hydra no longer has the AWS test infrastructure required to run these tests.
"""
import logging
import os
import random
import string
import subprocess
import sys
import tempfile
f... | 353 | 11,390 |
black | tests/data/cases/module_docstring_3.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
| 8 | 181 |
onnxruntime | orttraining/orttraining/test/python/orttraining_test_ortmodule_bert_classifier_autocast.py | .py | import argparse
import datetime
import logging
import os
import random
import time
import zipfile
import numpy as np
import pandas as pd
import torch
import wget
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from transforme... | 482 | 19,274 |
jupyterlab | jupyterlab/browser_check.py | .py | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""
This module is meant to run JupyterLab in a headless browser, making sure
the application launches and starts up without errors.
"""
import asyncio
import inspect
import logging
import os
import shutil
import subp... | 233 | 8,033 |
pyomo | pyomo/contrib/mpc/interfaces/tests/test_var_linker.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... | 142 | 5,762 |
openvino | tests/layer_tests/pytorch_tests/test_if.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import pytest
import numpy as np
from pytorch_layer_test_class import PytorchLayerTest
class TestIf(PytorchLayerTest):
def _prepare_input(self):
return (self.random.randn(1, 3, 224, 224), self.y)
def create_... | 41 | 1,218 |
probability | tensorflow_probability/python/distributions/normal_inverse_gaussian_test.py | .py | # Copyright 2020 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 246 | 9,785 |
sqlmap | tamper/varnish.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 PRIORITY
__priority__ = PRIORITY.NORMAL
def dependencies():
pass
def tamper(payload, **kwargs):
"""
Appends a HTTP header 'X-originating-... | 34 | 962 |
textual | src/textual/compose.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from textual.app import App, ComposeResult
from textual.widget import Widget
__all__ = ["compose"]
def compose(
node: App | Widget, compose_result: ComposeResult | None = None
) -> list[Widget]:
"""Compose child w... | 100 | 3,129 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.