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 |
|---|---|---|---|---|---|
gunicorn | tests/test_logger.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import datetime
from types import SimpleNamespace
import pytest
from gunicorn.config import Config
from gunicorn.glogging import Logger
def test_atoms_defaults():
response = SimpleNamespace(
status=... | 96 | 3,246 |
wagtail | wagtail/contrib/redirects/management/commands/import_redirects.py | .py | import os
from django.core.management.base import BaseCommand
from wagtail.contrib.redirects.base_formats import Dataset
from wagtail.contrib.redirects.forms import RedirectForm
from wagtail.contrib.redirects.utils import (
get_format_cls_by_extension,
get_supported_extensions,
)
from wagtail.models import Si... | 204 | 6,095 |
jupytext | tests/data/notebooks/outputs/ipynb_to_sphinx/jupyter.py | .py | # ---
# jupyter:
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
"""
# Jupyter notebook
This notebook is a simple jupyter notebook. It only has markdown and code cells. And it does not contain consecutive markdown cells. We start with an addition:
"""
a = 1
b = 2
a + b
... | 29 | 576 |
wandb | tests/system_tests/test_functional/test_tensorboard/test_tf_summary.py | .py | """Test that the TensorFlow summary API works with W&B.
Used https://www.tensorflow.org/api_docs/python/tf/summary as reference."""
import os
import numpy as np
import pytest
import tensorboard.plugins.pr_curve.summary as pr_curve_plugins_summary
import tensorboard.summary.v1 as tensorboard_summary_v1
import tensorfl... | 285 | 10,396 |
saleor | saleor/tests/race_condition.py | .py | from functools import wraps
from unittest.mock import patch
class RaceConditionTrigger:
def __init__(self, target, callback):
self.target = target
self.callback = callback
self.has_been_called = False
def __enter__(self):
self.patched_function = patch(self.target)
orig... | 53 | 1,892 |
sqlmap | plugins/dbms/postgresql/syntax.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from lib.core.convert import getOrds
from plugins.generic.syntax import Syntax as GenericSyntax
class Syntax(GenericSyntax):
@staticmethod
def escape(expression, quote=Tr... | 26 | 1,015 |
biopython | Bio/Phylo/__init__.py | .py | # Copyright (C) 2009 by Eric Talevich (eric.talevich@gmail.com)
#
# 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.
"""Package for wo... | 22 | 683 |
rq | rq/local.py | .py | # ruff: noqa: E731
"""
werkzeug.local
~~~~~~~~~~~~~~
This module implements context-local objects.
:copyright: (c) 2011 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
# Since each thread has its own greenlet we can just use those as identifiers
# for the context.... | 433 | 12,808 |
eve | tests/methods/get.py | .py | import base64
import time
from datetime import datetime, timedelta
from io import BytesIO
import simplejson as json
from bson import ObjectId
from bson.dbref import DBRef
from bson.son import SON
from werkzeug.datastructures import ImmutableMultiDict, MultiDict
from eve.methods.get import get_internal, getitem_intern... | 2,445 | 98,080 |
mlflow | mlflow/sklearn/__init__.py | .py | """
The ``mlflow.sklearn`` module provides an API for logging and loading scikit-learn models. This
module exports scikit-learn models with the following flavors:
Python (native) `pickle <https://scikit-learn.org/stable/modules/model_persistence.html>`_ format
This is the main flavor that can be loaded back into s... | 2,100 | 90,635 |
saleor | saleor/tests/e2e/account/account/test_staff_login_disabled_mode.py | .py | from unittest.mock import patch
import pytest
from .....site import PasswordLoginMode
from ...account.utils.token_create import raw_token_create
from ...conftest import E2eApiClient
from ...product.utils.category import create_category
from ...product.utils.product import PRODUCT_CREATE_MUTATION
from ...product.utils... | 110 | 3,805 |
probability | discussion/turnkey_inference_candidate/window_tune_nuts_sampling.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... | 571 | 24,543 |
jupytext | tests/data/notebooks/outputs/ipynb_to_script/jupyter_with_raw_cell_with_invalid_yaml.py | .py | # ---
# title: Exception: Test
# jupyter:
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
1 + 2 + 3
| 11 | 159 |
bazel | src/test/py/bazel/bazel_windows_cpp_test.py | .py | # Copyright 2017 The Bazel Authors. All rights reserved.
#
# 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 la... | 1,359 | 47,071 |
onnxruntime | onnxruntime/test/testdata/nnapi_reshape_flatten_test.py | .py | import onnx
from onnx import TensorProto, helper
# Since NNAPI EP handles Reshape and Flatten differently,
# Please see ReshapeOpBuilder::CanSkipReshape in <repo_root>/onnxruntime/core/providers/nnapi/nnapi_builtin/builders/op_builder.cc
# We have a separated test for these skip reshape scenarios
def GenerateModel(mo... | 50 | 1,944 |
saleor | saleor/graphql/account/tests/queries/test_user.py | .py | from unittest import mock
from unittest.mock import MagicMock
import graphene
import pytest
from django.core.files import File
from .....account.models import Group
from .....channel.models import Channel
from .....order import OrderStatus
from .....order.models import FulfillmentStatus, Order
from .....thumbnail.mod... | 1,460 | 43,142 |
probability | tensorflow_probability/python/distributions/joint_distribution_auto_batched_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... | 1,078 | 43,847 |
saleor | saleor/warehouse/lock_objects.py | .py | from .models import Allocation, Stock
def stock_select_for_update_for_existing_qs(qs):
return qs.order_by("pk").select_for_update(of=(["self"]))
def stock_qs_select_for_update():
return stock_select_for_update_for_existing_qs(Stock.objects.all())
def allocation_with_stock_qs_select_for_update():
retur... | 23 | 530 |
saleor | saleor/core/db/tests/test_postgres_json_concatenate.py | .py | import pytest
from django.db.models import CharField, F, JSONField, Value
from ....checkout.models import CheckoutMetadata
from ..expressions import PostgresJsonConcatenate
TEST_KEY = "test-key"
TEST_VALUE = "test_value"
TEST_DICT = {TEST_KEY: TEST_VALUE}
@pytest.fixture
def checkout_metadata_qs(checkout):
retu... | 223 | 6,507 |
gunicorn | tests/test_util.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import os
import pytest
from gunicorn import util
from gunicorn.errors import AppImportError
from urllib.parse import SplitResult
@pytest.mark.parametrize('test_input, expected', [
('unix://var/run/test.sock... | 132 | 4,345 |
wandb | tests/system_tests/test_sweep/test_wandb_agent_full.py | .py | """Agent tests."""
import queue
import threading
import time
from concurrent.futures import ThreadPoolExecutor
import wandb
import wandb.agents.pyagent as pyagent
from wandb.apis.public import Api
from .test_wandb_sweep import SWEEP_CONFIG_GRID
def test_public_api_sweep_agent_retrieves_running_agent(user):
"""... | 142 | 4,899 |
saleor | saleor/graphql/payment/resolvers.py | .py | from django.db.models import Q
from ...app import models as app_models
from ...checkout import models as checkout_models
from ...order import models as order_models
from ...payment import models
from ...permission.enums import OrderPermissions
from ..account.utils import get_user_accessible_channels
from ..core.contex... | 74 | 2,697 |
hydra | tools/landscape/build_public_landscape.py | .py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""Generate public Hydra Landscape data from maintainer decisions."""
from __future__ import annotations
import argparse
import json
import re
from pathlib import Path
from typing import Any, Iterable
ROOT = Path(__file__... | 218 | 7,692 |
tqdm | tqdm/contrib/logging.py | .py | """
Helper functionality for interoperability with stdlib `logging`.
"""
import logging
import sys
from contextlib import contextmanager
try:
from typing import Iterator, List, Optional, Type # noqa: F401, pylint: disable=unused-import
except ImportError:
pass
from ..std import tqdm as std_tqdm
class _Tqdm... | 129 | 3,902 |
saleor | saleor/webhook/tests/test_models.py | .py | import pytest
from django.db import IntegrityError
from django.db.transaction import atomic
from ...app.models import App
from ..models import Webhook
TARGET_URL = "http://www.example.com/test"
def test_webhook_identifier_must_be_unique_per_app(app):
# given
identifier = "order-created-handler"
Webhook.... | 50 | 1,826 |
attrs | src/attr/exceptions.py | .py | # SPDX-License-Identifier: MIT
from __future__ import annotations
class FrozenError(AttributeError):
"""
A frozen/immutable instance or attribute have been attempted to be
modified.
It mirrors the behavior of ``namedtuples`` by using the same error message
and subclassing `AttributeError`.
... | 96 | 1,990 |
pyomo | examples/pyomo/concrete/knapsack-abstract.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... | 52 | 1,550 |
hatch | tests/backend/utils/test_fs.py | .py | import os
from hatchling.utils.fs import path_to_uri
class TestPathToURI:
def test_unix(self, isolation, uri_slash_prefix):
bad_path = f"{isolation}{os.sep}"
normalized_path = str(isolation).replace(os.sep, "/")
assert path_to_uri(bad_path) == f"file:{uri_slash_prefix}{normalized_path}"
... | 16 | 580 |
pynacl | tests/test_hashlib_scrypt.py | .py | # Copyright 2013 Donald Stufft and individual contributors
#
# 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... | 143 | 4,270 |
rq | tests/test_dependencies.py | .py | from multiprocessing import Process
from rq import Queue, SimpleWorker, Worker
from rq.connections import get_connection_kwargs
from rq.job import Dependency, Job, JobStatus
from rq.utils import current_timestamp
from tests import RQTestCase
from tests.fixtures import check_dependencies_are_met, div_by_zero, kill_hors... | 310 | 13,873 |
scikit-bio | skbio/io/format/tests/test_newick.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.
# --------------------------------------------... | 370 | 12,594 |
jupytext | tests/data/notebooks/outputs/ipynb_to_percent/Notebook with function and cell metadata 164.py | .py | # ---
# jupyter:
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %%
1 + 1
# %% [markdown]
# A markdown cell
# And below, the cell for function f has non trivial cell metadata. And the next cell as well.
# %% attributes={"classes": [], "id": "", "n": "10"}
def f(x):
... | 30 | 432 |
mlflow | mlflow/store/db_migrations/versions/97727af70f4d_creation_time_last_update_time_experiments.py | .py | """Add creation_time and last_update_time to experiments table
Create Date: 2022-08-26 21:16:59.164858
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "97727af70f4d"
down_revision = "cc1f77228345"
branch_labels = None
depends_on = None
def upgrade():
op.a... | 24 | 529 |
httpie | httpie/output/formatters/json.py | .py | import json
from ...plugins import FormatterPlugin
class JSONFormatter(FormatterPlugin):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.enabled = self.format_options['json']['format']
def format_body(self, body: str, mime: str) -> str:
maybe_json = [
'json... | 35 | 1,123 |
beam | sdks/python/apache_beam/runners/worker/statesampler_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... | 362 | 12,437 |
flit | flit/install.py | .py | """Install packages locally for development
"""
import logging
import os
import os.path as osp
import csv
import json
import pathlib
import random
import shutil
import site
import sys
import tempfile
from subprocess import check_call, check_output
import sysconfig
from flit_core import common
from .config import read_... | 432 | 16,771 |
black | tests/data/cases/comments_in_blocks.py | .py | # Test cases from:
# - https://github.com/psf/black/issues/1798
# - https://github.com/psf/black/issues/1499
# - https://github.com/psf/black/issues/1211
# - https://github.com/psf/black/issues/563
(
lambda
# a comment
: None
)
(
lambda:
# b comment
None
)
(
lambda
# a comment
:
... | 112 | 2,150 |
onnx | onnx/reference/ops/op_floor.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 Floor(OpRunUnaryNum):
def _run(self, x):
return (np.floor(x),)
| 14 | 269 |
mlflow | tests/store/artifact/utils/test_model_utils.py | .py | from unittest import mock
import pytest
from mlflow import MlflowClient
from mlflow.entities.model_registry import ModelVersion
from mlflow.exceptions import MlflowException
from mlflow.store.artifact.utils.models import _parse_model_uri, get_model_name_and_version
from mlflow.tracking._model_registry.client import M... | 256 | 9,894 |
sphinx | sphinx/ext/todo.py | .py | """Allow todos to be inserted into your documentation.
Inclusion of todos can be switched of by a configuration variable.
The todolist directive collects all todos of your project and lists them along
with a backlink to the original location.
"""
from __future__ import annotations
import functools
import operator
fr... | 251 | 8,019 |
mlflow | mlflow/system_metrics/metrics/rocm_monitor.py | .py | """Class for monitoring GPU stats on HIP devices.
Inspired by GPUMonitor, but with the pynvml method
named replaced by pyrsmi method names
"""
import contextlib
import io
import logging
import sys
from mlflow.system_metrics.metrics.base_metrics_monitor import BaseMetricsMonitor
_logger = logging.getLogger(__name__)
... | 124 | 4,426 |
textual | tests/command_palette/test_declare_sources.py | .py | from textual.app import App
from textual.command import CommandPalette, Hit, Hits, Provider
from textual.screen import Screen
from textual.system_commands import SystemCommandsProvider
async def test_sources_with_no_known_screen() -> None:
"""A command palette with no known screen should have an empty source set.... | 101 | 3,288 |
openvino | tests/layer_tests/onnx_tests/test_pad.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
pytest.importorskip("openvino.tools.mo", reason="Ticket - 157136")
from common.layer_test_class import check_ir_version
from common.onnx_layer_test_class import OnnxRuntimeLayerTest, onnx_make_model
fro... | 218 | 9,044 |
saleor | saleor/order/tests/test_order_utils.py | .py | import datetime
from decimal import Decimal
import graphene
import pytest
from django.utils import timezone
from prices import Money, TaxedMoney
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...checkout.models import Checkout
from ...discount import DiscountType, DiscountValueType
from ... | 804 | 24,613 |
hydra | plugins/hydra_submitit_launcher/hydra_plugins/hydra_submitit_launcher/submitit_launcher.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import os
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence
from hydra.core.singleton import Singleton
from hydra.core.utils import JobReturn, filter_overrides, run_job, setup_globals
from hydra.plugins.... | 154 | 5,017 |
black | src/black/report.py | .py | """
Summarize Black runs to users.
"""
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from black.output import err, out, style_output
from black.parsing import InvalidInput
class Changed(Enum):
NO = 0
CACHED = 1
YES = 2
class NothingChanged(UserWarning):
"""Raised... | 123 | 3,973 |
saleor | saleor/graphql/webhook/mutations/webhook_create.py | .py | import graphene
from django.core.exceptions import ValidationError
from ....permission.auth_filters import AuthorizationFilters
from ....permission.enums import AppPermission
from ....webhook import models
from ....webhook.const import MAX_FILTERABLE_CHANNEL_SLUGS_LIMIT
from ....webhook.error_codes import WebhookError... | 207 | 8,078 |
jupytext | tests/functional/others/test_auto_ext.py | .py | import pytest
from jupytext import read, reads, writes
from jupytext.formats import JupytextFormatError, auto_ext_from_metadata
def test_auto_in_fmt(ipynb_py_R_file):
nb = read(ipynb_py_R_file)
auto_ext = auto_ext_from_metadata(nb.metadata)
fmt = auto_ext[1:] + ":percent"
text = writes(nb, "auto:perc... | 68 | 2,340 |
python-prompt-toolkit | src/prompt_toolkit/input/vt100.py | .py | from __future__ import annotations
import sys
assert sys.platform != "win32"
import contextlib
import io
import termios
import tty
from asyncio import AbstractEventLoop, get_running_loop
from collections.abc import Callable, Generator
from contextlib import AbstractContextManager
from typing import TextIO
from ..ke... | 316 | 10,765 |
wagtail | wagtail/test/customuser/fields.py | .py | import random
from django.db import models
LOWER_BOUND = -2147483648
UPPER_BOUND = 2147483647
SHIFT = 92147483647
class ConvertedValue(str):
def __new__(cls, value):
value = int(value)
if UPPER_BOUND < value:
display_value = value
db_value = value - SHIFT
else:
... | 83 | 2,307 |
textual | tests/text_area/test_textarea_cut_copy_paste.py | .py | from textual.app import App, ComposeResult
from textual.widgets import TextArea
class TextAreaApp(App):
def compose(self) -> ComposeResult:
yield TextArea()
async def test_cut():
"""Check that cut removes text and places it in the clipboard."""
app = TextAreaApp()
async with app.run_test() a... | 53 | 1,780 |
cvxpy | cvxpy/tests/nlp_tests/test_abs.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
... | 136 | 5,078 |
saleor | saleor/product/tests/test_get_variant_selection_attributes.py | .py | from ...attribute import AttributeInputType
from ..utils.variants import get_variant_selection_attributes
def test_get_variant_selection_attributes(
product_type_attribute_list,
numeric_attribute,
swatch_attribute,
file_attribute_with_file_input_type_without_values,
product_type_page_reference_att... | 40 | 1,251 |
conda | conda/auxlib/collection.py | .py | """Common collection classes."""
from functools import reduce
from collections.abc import Mapping, Set
from frozendict import frozendict
from ..deprecations import deprecated
from ..common.compat import isiterable
# http://stackoverflow.com/a/14620633/2127762
class AttrDict(dict):
"""Sub-classes dict, and furth... | 63 | 1,941 |
saleor | saleor/account/throttling.py | .py | import datetime
import logging
from math import ceil
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.utils import timezone
from ..core.utils import get_client_ip
from . import models
from .error_codes import AccountErrorCode
from .utils import retrieve_user_by_email
... | 146 | 4,691 |
clearml | clearml/backend_api/services/v2_9/events.py | .py | """
events service
Provides an API for running tasks to report events collected by the system.
"""
from typing import List, Optional, Any
import enum
import six
from ....backend_api.session import (
BatchRequest,
CompoundRequest,
NonStrictDataModel,
Request,
Response,
schema_property,
Strin... | 3,195 | 103,110 |
hydra | hydra/experimental/callback.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
from typing import Any
from omegaconf import DictConfig
from hydra.core.utils import JobReturn
from hydra.types import TaskFunction
logger = logging.getLogger(__name__)
class Callback:
def on_run_start(self, config: DictConfi... | 66 | 2,378 |
saleor | saleor/graphql/checkout/mutations/checkout_create.py | .py | from typing import TYPE_CHECKING, Optional
import graphene
from django.conf import settings
from django.core.exceptions import ValidationError
from ....checkout import AddressType, models
from ....checkout.actions import call_checkout_event
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.util... | 565 | 21,279 |
sphinx | tests/roots/test-ext-autodoc/target/callable.py | .py | class Callable:
"""A callable object that behaves like a function."""
def __call__(self, arg1, arg2, **kwargs):
pass
def method(self, arg1, arg2):
"""docstring of Callable.method()."""
pass
function = Callable()
method = function.method
| 14 | 277 |
mlflow | mlflow/genai/scorers/registry.py | .py | """
Registered scorer functionality for MLflow GenAI.
This module provides functions to manage registered scorers that automatically
evaluate traces in MLflow experiments.
"""
import json
import warnings
from abc import ABCMeta, abstractmethod
from base64 import urlsafe_b64encode
from collections.abc import Callable
... | 1,127 | 43,824 |
mkdocs | mkdocs/commands/serve.py | .py | from __future__ import annotations
import logging
import shutil
import tempfile
from os.path import isdir, isfile, join
from typing import TYPE_CHECKING
from urllib.parse import urlsplit
from mkdocs.commands.build import build
from mkdocs.config import load_config
from mkdocs.livereload import LiveReloadServer, _serv... | 111 | 3,245 |
onnx | onnx/reference/ops/aionnxml/op_binarizer.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from onnx.reference.ops.aionnxml._op_run_aionnxml import OpRunAiOnnxMl
def compute_binarizer(x, threshold=None):
return ((x > threshold).astype(x.dtype),)
class Binarizer(OpRunAiOnnxMl):
def ... | 16 | 398 |
saleor | saleor/graphql/account/tests/bulk_mutations/test_staff_bulk_delete.py | .py | from unittest.mock import patch
import graphene
from django.conf import settings
from .....account.error_codes import AccountErrorCode
from .....account.models import Group, User
from .....attribute.models import AssignedUserAttributeValue, AttributeValue
from .....permission.enums import AccountPermissions, OrderPer... | 439 | 14,107 |
astropy | astropy/cosmology/tests/test_scalar_inv_efuncs.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Tests for the scalar_inv_efuncs Cython extension in astropy.cosmology."""
from numpy.testing import assert_allclose
from astropy.cosmology._src.flrw.scalar_inv_efuncs import (
flcdm_inv_efunc_nomnu,
flcdm_inv_efunc_norel,
fwcdm_inv_efunc_n... | 129 | 4,313 |
openvino | tests/layer_tests/pytorch_tests/test_stft.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
from packaging import version
from pytorch_layer_test_class import PytorchLayerTest
# stft with return_complex=False is deprecated in PyTorch 2.9.
# return_complex=True is already tested in TestSTFTAttrs.
_ST... | 162 | 7,424 |
sqlmap | thirdparty/chardet/utf8prober.py | .py | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Con... | 83 | 2,766 |
mlflow | mlflow/genai/simulators/simulator.py | .py | from __future__ import annotations
import inspect
import logging
import math
import time
import uuid
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor, as_completed
from contextlib import contextmanager
from dataclasses import dataclass, field
from threading import Lock
from typing ... | 852 | 33,644 |
coremltools | coremltools/converters/mil/mil/ops/tests/iOS14/test_normalization.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 cor... | 857 | 30,287 |
beam | sdks/python/apache_beam/examples/snippets/transforms/aggregation/tolist.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");... | 52 | 1,492 |
mlflow | mlflow/prophet/__init__.py | .py | """
The ``mlflow.prophet`` module provides an API for logging and loading Prophet models.
This module exports univariate Prophet models in the following flavors:
Prophet (native) format
This is the main flavor that can be accessed with Prophet APIs.
:py:mod:`mlflow.pyfunc`
Produced for use by generic pyfunc-ba... | 405 | 14,768 |
mlflow | tests/tracking/test_log_figure.py | .py | import os
import posixpath
import uuid
import pytest
import mlflow
from mlflow.utils.file_utils import local_file_uri_to_path
from mlflow.utils.os import is_windows
@pytest.mark.parametrize("subdir", [None, ".", "dir", "dir1/dir2", "dir/.."])
def test_log_figure_matplotlib(subdir):
import matplotlib.pyplot as p... | 105 | 3,517 |
hydra | examples/tutorials/structured_configs/5.1_structured_config_schema_same_config_group/my_app.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from dataclasses import dataclass
from omegaconf import MISSING, OmegaConf
import hydra
from hydra.core.config_store import ConfigStore
@dataclass
class DBConfig:
driver: str = MISSING
host: str = "localhost"
port: int = MISSING
@d... | 53 | 1,071 |
saleor | saleor/graphql/warehouse/mutations/__init__.py | .py | from .warehouse_create import WarehouseCreate
from .warehouse_delete import WarehouseDelete
from .warehouse_shipping_zone_assign import WarehouseShippingZoneAssign
from .warehouse_shipping_zone_unassign import WarehouseShippingZoneUnassign
from .warehouse_update import WarehouseUpdate
__all__ = [
"WarehouseCreate"... | 14 | 442 |
onnxruntime | onnxruntime/test/testdata/transform/qdq_conv_gen.py | .py | import onnx
from onnx import TensorProto, helper
# Generate a basic QDQ Conv model with `num_convs` Conv nodes and their surrounding DQ/Q nodes
def GenerateModel(model_path, num_convs): # noqa: N802
nodes = []
initializers = []
inputs = []
outputs = []
for i in range(num_convs):
def nam... | 83 | 2,834 |
saleor | saleor/graphql/shop/tests/mutations/test_shop_address_update.py | .py | from .....account.models import Address
from ....tests.utils import get_graphql_content
MUTATION_SHOP_ADDRESS_UPDATE = """
mutation updateShopAddress($input: AddressInput){
shopAddressUpdate(input: $input){
errors{
field
message
}
}
}
"""
... | 122 | 3,538 |
saleor | saleor/tests/e2e/checkout/utils/checkout_remove_promo_code.py | .py | from ...utils import get_graphql_content
CHECKOUT_REMOVE_PROMO_CODE_MUTATION = """
mutation CheckoutRemovePromoCode($id: ID, $promoCode: String) {
checkoutRemovePromoCode(
id: $id
promoCode: $promoCode
) {
errors {
message
field
code
}
... | 44 | 937 |
beam | sdks/python/apache_beam/examples/snippets/transforms/aggregation/cogroupbykey.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");... | 72 | 1,982 |
cvxpy | cvxpy/reductions/eliminate_pwl/canonicalizers/sum_largest_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... | 58 | 2,033 |
sphinx | sphinx/search/nl.py | .py | """Dutch search language."""
from __future__ import annotations
import snowballstemmer
from sphinx.search import SearchLanguage
from sphinx.search._stopwords.nl import DUTCH_STOPWORDS
class SearchDutch(SearchLanguage):
lang = 'nl'
language_name = 'Dutch'
js_stemmer_rawcode = 'dutch-stemmer.js'
stop... | 23 | 582 |
pyomo | pyomo/core/plugins/transform/lp_dual.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... | 299 | 11,079 |
sphinx | sphinx/util/template.py | .py | """Templates utility functions for Sphinx."""
from __future__ import annotations
import os
from functools import partial
from pathlib import Path
from typing import TYPE_CHECKING
from jinja2 import TemplateNotFound
from jinja2.loaders import BaseLoader
from jinja2.sandbox import SandboxedEnvironment
from sphinx imp... | 164 | 5,365 |
biopython | Tests/test_PDB_parse_pdb_header.py | .py | # Copyright 2017 by Bernhard Thiel. All rights reserved.
# Revisions copyright 2024 James Krieger.
# 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... | 198 | 8,512 |
wagtail | wagtail/images/fields.py | .py | import os
from io import BytesIO
import willow
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import FileExtensionValidator
from django.forms.fields import FileField, ImageField
from django.forms.widgets import FileInput
from django.template.defaultfilte... | 216 | 8,548 |
ipython | tests/test_storemagic.py | .py | import tempfile, os
from pathlib import Path
import pytest
from traitlets.config.loader import Config
from IPython.core.error import UsageError
def setup_module():
ip.run_line_magic("load_ext", "storemagic")
def test_store_restore():
assert "bar" not in ip.user_ns, "Error: some other test leaked `bar` in ... | 207 | 7,030 |
astropy | astropy/tests/figures/helpers.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from functools import wraps
import pytest
from astropy.utils.compat.optional_deps import HAS_PYTEST_MPL
def figure_test(*args, **kwargs):
"""
A decorator that defines a figure test.
This automatically decorates tests with mpl_image_compar... | 47 | 1,516 |
scikit-optimize | skopt/acquisition.py | .py | import numpy as np
import warnings
from scipy.stats import norm
def gaussian_acquisition_1D(X, model, y_opt=None, acq_func="LCB",
acq_func_kwargs=None, return_grad=True):
"""
A wrapper around the acquisition function that is called by fmin_l_bfgs_b.
This is because lbfgs allo... | 322 | 11,160 |
onnx | onnx/backend/test/case/node/rnn.py | .py | # Copyright (c) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from typing import Any
import numpy as np
import onnx
from onnx.backend.test.case.base import Base
from onnx.backend.test.case.node import expect
class RNNHelper:
def __init__(self, **params: An... | 327 | 9,587 |
saleor | saleor/graphql/meta/tests/queries/utils.py | .py | import graphene
from django.http import HttpResponse
from .....core.models import ModelWithMetadata
from .....permission.models import Permission
from ....tests.fixtures import ApiClient
from ....tests.utils import get_graphql_content
PRIVATE_KEY = "private_key"
PRIVATE_VALUE = "private_vale"
PUBLIC_KEY = "key"
PUBL... | 45 | 1,329 |
scikit-bio | skbio/io/format/tests/test_biom.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.
# --------------------------------------------... | 67 | 2,371 |
sqlmap | plugins/dbms/snowflake/takeover.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.exception import SqlmapUnsupportedFeatureException
from plugins.generic.takeover import Takeover as GenericTakeover
class Takeover(GenericTakeover):
def osCmd(s... | 29 | 982 |
astropy | astropy/io/ascii/tests/test_write.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import copy
import os
import pathlib
from contextlib import nullcontext
from io import StringIO
from string import Template
import numpy as np
import pytest
from astropy import table
from astropy import units as u
from astropy.io import ascii
from astro... | 1,005 | 31,785 |
clearml | examples/hyperdatasets/create_image_entries.py | .py | """Create a HyperDataset populated with local image files.
The script demonstrates how to use `DataEntryImage` along with
optional vector embeddings computed from each image. Ten sample images are
shipped under `examples/hyperdatasets/sample_images`, but you can point the
script at any directory of JPEG/PNG assets.
E... | 208 | 7,426 |
beam | sdks/python/apache_beam/io/debezium.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... | 206 | 7,974 |
mlflow | tests/tracing/test_trace_archival_config.py | .py | from unittest.mock import patch
import pytest
import mlflow.tracing.trace_archival_config as trace_archival_config_module
from mlflow.environment_variables import MLFLOW_TRACE_ARCHIVAL_CONFIG
from mlflow.exceptions import MlflowException
from mlflow.tracing.trace_archival_config import get_trace_archival_server_confi... | 167 | 5,865 |
metrics | src/torchmetrics/functional/regression/log_cosh.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,500 |
sphinx | sphinx/search/en.py | .py | """English search language."""
from __future__ import annotations
import snowballstemmer
from sphinx.search import SearchLanguage
from sphinx.search._stopwords.en import ENGLISH_STOPWORDS
class SearchEnglish(SearchLanguage):
lang = 'en'
language_name = 'English'
js_stemmer_rawcode = 'english-stemmer.js... | 23 | 596 |
pyomo | doc/OnlineDocs/src/kernel/examples/kernel_containers.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... | 17 | 702 |
python-prompt-toolkit | src/prompt_toolkit/history.py | .py | """
Implementations for the history of a `Buffer`.
NOTE: There is no `DynamicHistory`:
This doesn't work well, because the `Buffer` needs to be able to attach
an event handler to the event when a history entry is loaded. This
loading can be done asynchronously and making the history swappable would
... | 308 | 9,486 |
saleor | saleor/graphql/app/resolvers.py | .py | from urllib.parse import urljoin, urlparse
from django.db.models import Exists, OuterRef
from graphql import GraphQLError
from ...app import models
from ...app.types import DEFAULT_APP_TARGET, POPUP_EXTENSION_TARGET
from ...core.jwt import (
create_access_token_for_app,
create_access_token_for_app_extension,
... | 112 | 3,500 |
mlflow | examples/spacy/train.py | .py | import random
import spacy
from packaging.version import Version
from spacy.training import Example
from spacy.util import compounding, minibatch
import mlflow.spacy
IS_SPACY_VERSION_NEWER_THAN_OR_EQUAL_TO_3_0_0 = Version(spacy.__version__).major >= 3
# training data
TRAIN_DATA = [
("Who is Shaka Khan?", {"enti... | 66 | 2,246 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.