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 |
|---|---|---|---|---|---|
onnxruntime | orttraining/orttraining/test/python/orttraining_test_ort_apis_py_bindings.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from __future__ import annotations
import os
import pathlib
import tempfile
from dataclasses import dataclass
import numpy as np
import onnx
import packaging.version as pv
import pytest
import torch
from orttraining_test_or... | 676 | 27,623 |
conda | tests/cli/test_main_update.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from conda.exceptions import CondaUpdatePackageError
from conda.testing.integration import package_is_installed
if TYPE_CHECKING:
from pathlib import Path
... | 52 | 1,482 |
pyomo | examples/pyomo/suffixes/ipopt_scaling.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... | 77 | 2,605 |
saleor | saleor/graphql/product/filters/product_variant.py | .py | import django_filters
import graphene
from django.db.models import Exists, OuterRef, Q
from django.db.models.query import QuerySet
from django.utils import timezone
from ....attribute.models import (
AssignedVariantAttribute,
AssignedVariantAttributeValue,
AttributeValue,
)
from ....product.models import P... | 187 | 5,993 |
astropy | astropy/nddata/mixins/tests/test_ndio.py | .py | from astropy.nddata import NDData, NDDataRef, NDIOMixin # noqa: F401
# Alias NDDataAllMixins in case this will be renamed ... :-)
NDDataIO = NDDataRef
def test_simple_write_read():
ndd = NDDataIO([1, 2, 3])
assert hasattr(ndd, "read")
assert hasattr(ndd, "write")
| 11 | 280 |
mlflow | tests/cli/test_traces.py | .py | import json
import logging
from unittest import mock
import pytest
from click.testing import CliRunner
from mlflow.cli.traces import commands
from mlflow.entities import (
AssessmentSourceType,
MlflowExperimentLocation,
Trace,
TraceData,
TraceInfo,
TraceLocation,
TraceLocationType,
Tra... | 229 | 7,221 |
jupytext | tests/functional/simple_notebooks/test_read_empty_text_notebook.py | .py | import pytest
from nbformat.notebooknode import NotebookNode
import jupytext
from jupytext.formats import NOTEBOOK_EXTENSIONS
from jupytext.myst import is_myst_available, myst_extensions
from jupytext.quarto import is_quarto_available
@pytest.mark.parametrize("ext", sorted(set(NOTEBOOK_EXTENSIONS) - {".ipynb"}))
def... | 24 | 778 |
pdm | src/pdm/models/search.py | .py | from __future__ import annotations
import functools
from collections.abc import Callable
from dataclasses import dataclass
from html.parser import HTMLParser
from pdm._types import SearchResult
@dataclass
class Result:
name: str = ""
version: str = ""
description: str = ""
def as_frozen(self) -> Se... | 64 | 2,314 |
beam | sdks/python/apache_beam/examples/snippets/transforms/aggregation/distinct_test.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");... | 50 | 1,484 |
mlflow | tests/data/test_http_dataset_source.py | .py | import json
import os
from unittest import mock
import pandas as pd
import pytest
from mlflow.data.dataset_source_registry import get_dataset_source_from_json, resolve_dataset_source
from mlflow.data.http_dataset_source import HTTPDatasetSource
from mlflow.exceptions import MlflowException
from mlflow.utils.os import... | 189 | 7,265 |
mlflow | mlflow/pmdarima/__init__.py | .py | """
The ``mlflow.pmdarima`` module provides an API for logging and loading ``pmdarima`` models.
This module exports univariate ``pmdarima`` models in the following formats:
Pmdarima format
Serialized instance of a ``pmdarima`` model using pickle.
:py:mod:`mlflow.pyfunc`
Produced for use by generic pyfunc-based... | 651 | 23,878 |
rq | rq/queue.py | .py | from __future__ import annotations
import logging
import sys
import uuid
import warnings
from collections import defaultdict, namedtuple
from collections.abc import Callable, Iterable, Sequence
from datetime import datetime, timedelta
from functools import total_ordering
from typing import (
TYPE_CHECKING,
Any... | 1,777 | 70,472 |
wagtail | wagtail/test/streamfield_migrations/testutils.py | .py | from django.db import connection
from django.db.migrations import Migration
from django.db.migrations.loader import MigrationLoader
from wagtail.blocks.migrations.migrate_operation import MigrateStreamData
class MigrationTestMixin:
model = None
default_operation_and_block_path = []
app_name = None
d... | 44 | 1,469 |
pyomo | examples/pyomobook/abstract-ch/param5a.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... | 24 | 839 |
saleor | saleor/graphql/app/dataloaders/app_extension.py | .py | from collections import defaultdict
from ....app.models import AppExtension
from ...core.dataloaders import DataLoader
class AppExtensionByIdLoader(DataLoader[str, AppExtension]):
context_key = "app_extension_by_id"
def batch_load(self, keys):
extensions = AppExtension.objects.using(self.database_co... | 30 | 1,060 |
probability | tensorflow_probability/python/experimental/auto_batching/frontend_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... | 680 | 24,776 |
saleor | saleor/tests/e2e/checkout/utils/query_checkout.py | .py | from ...utils import get_graphql_content
CHECKOUT_QUERY = """
query Checkout($checkoutId: ID!){
checkout(id: $checkoutId){
id
voucherCode
discount {
amount
}
totalPrice{
gross{
amount
}
net{
amount
}
tax{
amount
}
}
sub... | 72 | 1,016 |
saleor | saleor/tests/e2e/orders/utils/order_fulfillment_cancel.py | .py | from ...utils import get_graphql_content
ORDER_FULFILLMENT_CANCEL_MUTATION = """
mutation OrderFulfillmentCancel($id: ID!, $input: FulfillmentCancelInput!) {
orderFulfillmentCancel(id: $id, input: $input) {
errors {
message
field
code
}
order {
id
status
fulfillments {... | 45 | 860 |
clearml | clearml/utilities/pigar/modules.py | .py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import collections
from typing import Tuple, List, Any
# FIXME: Just a workaround, not a radical cure..
_special_cases = {
"dogpile.cache": "dogpile.cache",
"dogpile.core": "dogpile.core",
"ruamel.yaml": "ruamel.yaml... | 109 | 3,251 |
black | tests/data/cases/preview_hug_parens_with_braces_and_square_brackets.py | .py | # flags: --unstable
def foo_brackets(request):
return JsonResponse(
{
"var_1": foo,
"var_2": bar,
}
)
def foo_square_brackets(request):
return JsonResponse(
[
"var_1",
"var_2",
]
)
func({"a": 37, "b": 42, "c": 927, "aaaaaa... | 348 | 5,823 |
mkdocs-material | material/plugins/blog/structure/config.py | .py | # Copyright (c) 2016-2025 Martin Donath <martin.donath@squidfunk.com>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, c... | 40 | 1,810 |
textual | tests/test_signal.py | .py | import pytest
from textual.app import App, ComposeResult
from textual.signal import Signal, SignalError
from textual.widgets import Label
async def test_signal():
"""Test signal subscribe"""
called = 0
class TestLabel(Label):
def on_mount(self) -> None:
def signal_result(_):
... | 111 | 3,159 |
omegaconf | tests/__init__.py | .py | import re
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, Generic, List, NamedTuple, Optional, Tuple, TypeVar, Union
import attr
from pytest import warns
from omegaconf import II, MISSING
class IllegalType:
def __init__(self) -> None:
pass
def __eq__(sel... | 345 | 6,799 |
saleor | saleor/tests/e2e/orders/test_expired_order_is_deleted_after_specified_time.py | .py | import datetime
import pytest
from django.utils import timezone
from freezegun import freeze_time
from ....order.tasks import delete_expired_orders_task, expire_orders_task
from ..checkout.utils import checkout_create, checkout_delivery_method_update
from ..product.utils.preparing_product import prepare_product
from ... | 137 | 4,474 |
coremltools | coremltools/converters/mil/frontend/torch/ssa_passes/torch_upsample_to_core_upsample.py | .py | # Copyright (c) 2021, 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 numpy as np
from coremltools import _logger as logger
from coremltools.converters.mil.mil imp... | 198 | 7,041 |
onnxruntime | tools/python/util/onnx_model_utils.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from __future__ import annotations
import logging
import pathlib
import onnx
from onnx import version_converter
import onnxruntime as ort
def iterate_graph_per_node_func(graph, per_node_func, **func_args):
"""
Ite... | 417 | 16,402 |
cvxpy | cvxpy/tests/test_constant_atoms.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... | 408 | 19,110 |
lemur | lemur/authorities/schemas.py | .py | """
.. module: lemur.authorities.schemas
:platform: unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from flask import current_app
from marshmallow import fields, validates_schema, pre_l... | 154 | 5,291 |
textual | docs/examples/widgets/input_types.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Input
class InputApp(App):
def compose(self) -> ComposeResult:
yield Input(placeholder="An integer", type="integer")
yield Input(placeholder="A number", type="number")
if __name__ == "__main__":
app = InputApp()
app.r... | 14 | 325 |
sphinx | sphinx/ext/intersphinx/_load.py | .py | """This module contains the code for loading intersphinx inventories."""
from __future__ import annotations
import concurrent.futures
import dataclasses
import os.path
import posixpath
import time
from operator import itemgetter
from typing import TYPE_CHECKING
from urllib.parse import urlsplit, urlunsplit
from sphi... | 483 | 16,852 |
saleor | saleor/graphql/warehouse/tests/benchmark/test_stock_bulk_update.py | .py | import pytest
from django.db import connection
from .....warehouse.models import Stock
from ....tests.utils import get_graphql_content
STOCKS_BULK_UPDATE_MUTATION = """
mutation StockBulkUpdate($stocks: [StockBulkUpdateInput!]!){
stockBulkUpdate(stocks: $stocks){
results{
error... | 129 | 3,915 |
onnxruntime | orttraining/orttraining/python/training/api/__init__.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from onnxruntime.training.api.checkpoint_state import CheckpointState
from onnxruntime.training.api.lr_scheduler import LinearLRScheduler
from onnxruntime.training.api.module import Module
from onnxruntime.training.api.optimi... | 15 | 435 |
mlflow | mlflow/store/db_migrations/versions/d3e4f5a6b7c8_add_display_name_to_endpoint_bindings.py | .py | """add display_name to endpoint_bindings
Create Date: 2026-01-21 00:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "d3e4f5a6b7c8"
down_revision = "2c33131f4dae"
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table(... | 25 | 601 |
pyomo | pyomo/contrib/pynumero/sparse/base_block.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... | 305 | 9,573 |
probability | tensorflow_probability/python/bijectors/fill_triangular.py | .py | # Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 163 | 5,534 |
saleor | saleor/graphql/checkout/dataloaders/checkout_delivery.py | .py | from itertools import chain
from uuid import UUID
from promise import Promise
from ....checkout.delivery_context import get_or_fetch_checkout_deliveries
from ....checkout.models import CheckoutDelivery
from ....core.db.connection import allow_writer_in_context
from ...core.dataloaders import DataLoader
from ...utils ... | 61 | 2,344 |
saleor | saleor/tests/e2e/checkout/taxes/test_checkout_complete_return_tax_error.py | .py | import pytest
from ...apps.utils import add_app
from ...product.utils.preparing_product import prepare_product
from ...shop.utils import prepare_default_shop
from ...taxes.utils import get_tax_configurations, update_tax_configuration
from ...utils import assign_permissions
from ...webhooks.utils import create_webhook
... | 138 | 5,480 |
mlflow | tests/server/test_fastapi_app.py | .py | import pytest
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from starlette.testclient import TestClient
from starlette.websockets import WebSocketDisconnect
from mlflow.exceptions import MlflowException
from mlflow.gateway.constants import MLFLOW_GATEWAY_DURATION_HEADER
from mlflow.server.fast... | 86 | 3,164 |
django-cms | cms/middleware/language.py | .py | from django.conf import settings
from django.utils.translation import get_language
class LanguageCookieMiddleware:
def __init__(self, get_response):
self.get_response = get_response
super().__init__()
def __call__(self, request):
response = self.get_response(request)
return se... | 41 | 1,499 |
conda | tests/gateways/disk/test_delete.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from __future__ import annotations
import os
from errno import ENOENT
from os.path import isdir, isfile, join, lexists
from typing import TYPE_CHECKING
import pytest
from conda.common.compat import on_win
from conda.gateways.disk.create impor... | 210 | 6,295 |
saleor | saleor/graphql/payment/tests/queries/test_payments_filter.py | .py | import graphene
from .....payment.models import Payment
from ....tests.utils import get_graphql_content
PAYMENT_QUERY = """ query Payments($filter: PaymentFilterInput){
payments(first: 20, filter: $filter) {
edges {
node {
id
gateway
capturedAmou... | 169 | 4,962 |
beam | sdks/python/apache_beam/dataframe/convert.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... | 304 | 11,408 |
coveragepy | coverage/sqldata.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
"""SQLite coverage data."""
from __future__ import annotations
import base64
import collections
import datetime
import functools
import glob
import itertools
im... | 1,207 | 48,470 |
openvino | tests/layer_tests/py_frontend_tests/test_torch_frontend.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import glob
import itertools
import math
import os
import re
import sys
import logging
import platform
from pathlib import Path
import torch
import numpy as np
import pytest
from openvino.frontend import FrontEn... | 3,180 | 129,834 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/save_model.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import sys
import numpy as np
import paddle
#print numpy array like C structure
def print_alike(arr, separator_begin='{', separator_end='}', verbose=False):
shape = arr.shape
rank = len(shape)
#print("shape: ", sh... | 135 | 4,152 |
pyomo | pyomo/solvers/tests/checks/test_cbc.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... | 140 | 5,327 |
gunicorn | examples/embedding_service/embedding_app.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.dirty.app import DirtyApp
class EmbeddingApp(DirtyApp):
def init(self):
from sentence_transformers import SentenceTransformer
self.model = SentenceTransformer('all-MiniLM-L6-v2')... | 19 | 476 |
probability | tensorflow_probability/python/mcmc/sample_annealed_importance.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... | 296 | 11,467 |
saleor | saleor/graphql/product/tests/mutations/test_product_variant_preorder_deactivate.py | .py | from unittest.mock import patch
import graphene
from .....core.exceptions import PreorderAllocationError
from .....product.error_codes import ProductErrorCode
from .....warehouse.models import Allocation
from ....tests.utils import assert_no_permission, get_graphql_content
QUERY_VARIANT_DEACTIVATE_PREORDER = """
... | 177 | 5,506 |
astropy | astropy/cosmology/_src/core.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# Originally authored by Andrew Becker (becker@astro.washington.edu),
# and modified by Neil Crighton (neilcrighton@gmail.com), Roban Kramer
# (robanhk@gmail.com), and Nathaniel Starkman (n.starkman@mail.utoronto.ca).
# Many of these adapted from Hogg 199... | 661 | 24,655 |
pyomo | pyomo/dataportal/plugins/json_dict.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... | 269 | 8,521 |
hydra | hydra/_internal/grammar/grammar_functions.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import builtins
import decimal
import json
import random
from copy import copy
from typing import Any, Callable, Dict, List, Optional, Union
from hydra._internal.deprecation_warning import deprecation_warning
from hydra._internal.grammar.utils impo... | 448 | 14,522 |
readthedocs.org | readthedocs/rtd_tests/tests/test_version_config.py | .py | from django.test import TestCase
from django_dynamic_fixture import get
from readthedocs.builds.constants import BUILD_STATE_BUILDING, BUILD_STATE_FINISHED
from readthedocs.builds.models import Build, Version, BuildConfig
from readthedocs.projects.models import Project
class VersionConfigTests(TestCase):
def set... | 87 | 2,756 |
wandb | wandb/plot/scatter.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
from wandb.plot.custom_chart import plot_table
if TYPE_CHECKING:
import wandb
from wandb.plot.custom_chart import CustomChart
def scatter(
table: wandb.Table,
x: str,
y: str,
title: str = "",
split_table: bool = False,
... | 67 | 2,045 |
scikit-bio | skbio/table/tests/test_tabular.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.
# --------------------------------------------... | 528 | 20,364 |
clearml | clearml/backend_api/session/token_manager.py | .py | import sys
from abc import ABC, abstractmethod
from time import time
from typing import Optional, Any
import jwt
from jwt.algorithms import get_default_algorithms
class TokenManager(ABC):
@property
def token_expiration_threshold_sec(self) -> int:
return self.__token_expiration_threshold_sec
@tok... | 111 | 3,672 |
wagtail | wagtail/tests/test_page_privacy.py | .py | from django.contrib.auth.models import Group
from django.test import TestCase, override_settings
from wagtail.models import PageViewRestriction
from wagtail.test.utils import Page, PageFixturesMixin, WagtailTestUtils
class TestPagePrivacy(PageFixturesMixin, WagtailTestUtils, TestCase):
fixtures = ["test.json"]
... | 249 | 9,898 |
mlflow | mlflow/store/artifact/databricks_run_artifact_repo.py | .py | import re
from mlflow.store.artifact.databricks_tracking_artifact_repo import (
DatabricksTrackingArtifactRepository,
)
class DatabricksRunArtifactRepository(DatabricksTrackingArtifactRepository):
"""
Artifact repository for interacting with run artifacts in a Databricks workspace.
If operations usin... | 35 | 1,422 |
black | scripts/migrate-black.py | .py | #!/usr/bin/env python3
# check out every commit added by the current branch, blackify them,
# and generate diffs to reconstruct the original commits, but then
# blackified
import logging
import os
import sys
from subprocess import PIPE, Popen, check_output, run
def git(*args: str) -> str:
return check_output(["gi... | 97 | 2,979 |
metrics | src/torchmetrics/functional/__init__.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... | 254 | 9,825 |
scikit-bio | skbio/stats/ordination/_redundancy_analysis.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.
# --------------------------------------------... | 271 | 10,452 |
hatch | src/hatch/index/errors.py | .py | class ArtifactMetadataError(Exception):
pass
| 3 | 49 |
onnxruntime | onnxruntime/test/python/transformers/benchmark_gqa.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
"""
Benchmark performance of GroupQueryAttention.
"""
from dataclasses... | 331 | 12,407 |
wagtail | wagtail/tests/streamfield_migrations/test_old_list.py | .py | from django.test import TestCase
from wagtail.blocks.migrations.operations import (
ListChildrenToStructBlockOperation,
RenameStreamChildrenOperation,
RenameStructChildrenOperation,
)
from wagtail.blocks.migrations.utils import apply_changes_to_raw_data
from wagtail.test.streamfield_migrations import model... | 265 | 10,196 |
lemur | lemur/plugins/lemur_gcs/tests/test_gcs.py | .py | import os
import unittest
from unittest.mock import patch, Mock, MagicMock
from flask import Flask
from lemur.plugins.lemur_gcs import plugin
from lemur.exceptions import InvalidConfiguration
class TestGcsDestinationPlugin(unittest.TestCase):
def setUp(self):
"""Set up test fixtures"""
# Create F... | 215 | 8,807 |
openvino | tests/layer_tests/pytorch_tests/test_bucketize.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import torch
from pytorch_layer_test_class import PytorchLayerTest
class TestBucketize(PytorchLayerTest):
def _prepare_input(self, input_shape, boundaries_range, input_dtype, boundaries_dtype):
... | 54 | 2,355 |
pyomo | pyomo/core/tests/unit/kernel/test_objective.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... | 150 | 4,825 |
onnx | onnx/backend/test/case/node/argmax.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
def argmax_use_numpy(data: np.ndarray, axis: int = 0, keepdims: int = 1) -> ... | 257 | 8,360 |
pymc | pymc/model/transform/optimization.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... | 233 | 9,785 |
sqlmap | plugins/dbms/altibase/enumeration.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.data import logger
from plugins.generic.enumeration import Enumeration as GenericEnumeration
class Enumeration(GenericEnumeration):
def getStatements(self):
... | 21 | 588 |
probability | tensorflow_probability/python/experimental/mcmc/tracing_reducer_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... | 85 | 3,561 |
saleor | saleor/checkout/tests/webhooks/test_calculate_taxes.py | .py | import json
from unittest import mock
from unittest.mock import ANY
import pytest
from promise import Promise
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.webhooks import calculate_taxes as checkout_calculate_taxes
from ....core import EventDeliveryStatus
from ....core.mo... | 258 | 8,847 |
pdm | tests/test_utils.py | .py | import pathlib
import sys
from datetime import datetime, timezone
from pathlib import Path
from unittest import mock
import pytest
import tomlkit
from pdm import utils
from pdm._types import RepositoryConfig
from pdm.cli import utils as cli_utils
from pdm.cli.filters import GroupSelection
from pdm.exceptions import P... | 597 | 21,529 |
readthedocs.org | readthedocs/embed/v3/urls.py | .py | from django.urls import path
from .views import EmbedAPI
urlpatterns = [
path("", EmbedAPI.as_view(), name="embed_api_v3"),
]
| 9 | 133 |
coremltools | coremltools/optimize/torch/_utils/torch_utils.py | .py | # Copyright (c) 2024, 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
# Implementation for transform_to_ch_axis function has been adapted from
# https://github.com/pytorch... | 255 | 8,009 |
mlflow | mlflow/server/jobs/progress.py | .py | """Job tracking for MLflow jobs."""
from typing import Any
_job_tracker: "JobTracker | NoOpTracker | None" = None
class JobTracker:
"""Tracks job execution by writing directly to database (internal use)."""
def __init__(self, job_id: str):
self.job_id = job_id
def update(self, status_details: ... | 46 | 1,227 |
bazel | third_party/py/concurrent/futures/_compat.py | .py | from keyword import iskeyword as _iskeyword
from operator import itemgetter as _itemgetter
import sys as _sys
def namedtuple(typename, field_names):
"""Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', 'x y')
>>> Point.__doc__ # docstring for the new cla... | 102 | 4,645 |
pyomo | pyomo/contrib/cp/scheduling_expr/step_function_expressions.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... | 374 | 12,153 |
readthedocs.org | readthedocs/rtd_tests/storage.py | .py | from readthedocs.builds.storage import BuildMediaFileSystemStorage
class BuildMediaFileSystemStorageTest(BuildMediaFileSystemStorage):
internal_redirect_root_path = "proxito"
def exists(self, *args, **kargs):
return True
class StaticFileSystemStorageTest(BuildMediaFileSystemStorageTest):
intern... | 13 | 361 |
saleor | saleor/graphql/attribute/dataloaders/assigned_attributes.py | .py | from collections import defaultdict
from collections.abc import Iterable
from django.db.models import F, Window
from django.db.models.functions import RowNumber
from django.db.models.query import QuerySet
from promise import Promise
from ....attribute.models import Attribute, AttributeValue
from ....attribute.models.... | 810 | 34,167 |
mlflow | examples/mlflow-3/langchain_simple.py | .py | import mlflow
mlflow.langchain.autolog(log_models=True)
from langchain_core.runnables import RunnableLambda
with mlflow.start_run() as run:
r = RunnableLambda(lambda x: x + 1)
r.invoke(3)
trace = mlflow.search_traces(locations=[run.info.experiment_id], max_results=1).iloc[0]
assert "mlflow.modelId" in trace... | 20 | 559 |
wandb | tests/system_tests/test_functional/console_capture/patching_exception.py | .py | """Exits with code 0 if an exception patching stdout is rethrown."""
import io
import sys
from typing import TextIO
class _TestError(Exception):
pass
class MyStdout(io.TextIOBase):
def __init__(self, delegate: TextIO) -> None:
self._delegate = delegate
def __setattr__(self, name, value):
... | 58 | 1,708 |
clearml | clearml/utilities/gpu/pynvml.py | .py | #####
# Copyright (c) 2011-2023, NVIDIA Corporation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list... | 4,967 | 166,329 |
cvxpy | cvxpy/reductions/dcp2cone/canonicalizers/log_det_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... | 78 | 2,370 |
mlflow | mlflow/entities/model_registry/model_version_tag.py | .py | from mlflow.entities.model_registry._model_registry_entity import _ModelRegistryEntity
from mlflow.protos.model_registry_pb2 import ModelVersionTag as ProtoModelVersionTag
class ModelVersionTag(_ModelRegistryEntity):
"""Tag object associated with a model version."""
def __init__(self, key, value):
se... | 36 | 933 |
saleor | saleor/graphql/app/mutations/app_problem_create.py | .py | import datetime
from typing import Annotated, Any, cast
import graphene
from django.utils import timezone
from pydantic import BaseModel, ConfigDict, Field, StringConstraints, field_validator
from pydantic import ValidationError as PydanticValidationError
from ....app.error_codes import (
AppProblemCreateErrorCod... | 203 | 7,423 |
rq | tests/test_scheduler.py | .py | import os
from datetime import datetime, timedelta, timezone
from multiprocessing import Process
from unittest import mock
import pytest
import redis
from rq import Queue
from rq.defaults import DEFAULT_MAINTENANCE_TASK_INTERVAL
from rq.exceptions import NoSuchJobError, SchedulerNotFound
from rq.job import Job, Retry... | 609 | 28,058 |
biopython | Bio/SearchIO/HmmerIO/hmmer3_text.py | .py | # Copyright 2012 by Wibowo Arindrarto. 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 parser ... | 458 | 20,043 |
hydra | plugins/hydra_nevergrad_sweeper/setup.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# type: ignore
from pathlib import Path
from read_version import read_version
from setuptools import find_namespace_packages, setup
setup(
name="hydra-nevergrad-sweeper",
version=read_version("hydra_plugins/hydra_nevergrad_sweeper", "__ini... | 35 | 1,245 |
probability | tensorflow_probability/python/glm/proximal_hessian.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... | 504 | 21,510 |
readthedocs.org | readthedocs/builds/managers.py | .py | """Build and Version class model Managers."""
import hashlib
import json
import structlog
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from readthedocs.builds.constants import BRANCH
from readthedocs.builds.constants import EXTERNAL
from readthedocs.builds.constants import LATES... | 149 | 4,678 |
biopython | Tests/test_SCOP_Scop.py | .py | # Copyright 2001 by Gavin E. Crooks. All rights reserved.
# Modifications Copyright 2010 Jeffrey Finkelstein. All rights reserved.
#
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Unit test for ... | 155 | 5,423 |
pyro | tests/contrib/oed/test_ewma.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import math
import pytest
import torch
from pyro.contrib.oed.eig import EwmaLog
from tests.common import assert_equal
@pytest.mark.parametrize("alpha", [0.5, 0.9, 0.99])
def test_ewma(alpha, NS=10000, D=1):
ewma_log = EwmaL... | 51 | 1,464 |
jupytext | tests/functional/others/test_cell_markers.py | .py | from nbformat.v4.nbbase import new_raw_cell
from jupytext import reads, writes
from jupytext.cli import jupytext
def test_set_cell_markers_cli(tmpdir, cwd_tmpdir):
tmpdir.join("test.py").write("# %% [markdown]\n# A Markdown cell\n")
jupytext(["--format-options", 'cell_markers="""', "test.py"])
py = tmpdi... | 34 | 800 |
saleor | saleor/graphql/shop/tests/queries/test_gift_card_settings.py | .py | from .....core import TimePeriodType
from .....site import GiftCardSettingsExpiryType
from ....tests.utils import assert_no_permission, get_graphql_content
GIFT_CARD_SETTINGS_QUERY = """
query giftCardSettings {
giftCardSettings {
expiryType
expiryPeriod {
type
... | 102 | 2,911 |
mlflow | tests/genai/scorers/ragas/test_utils.py | .py | import pytest
from langchain_core.documents import Document
from ragas.dataset_schema import MultiTurnSample, SingleTurnSample
from ragas.messages import AIMessage, HumanMessage, ToolCall
import mlflow
from mlflow.entities.span import SpanType
from mlflow.genai.scorers.ragas.utils import (
create_mlflow_error_mess... | 249 | 8,297 |
gunicorn | examples/http2_features/gunicorn_conf.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
# Gunicorn configuration for HTTP/2 features example
bind = "0.0.0.0:8443"
workers = 2
worker_class = "asgi"
# SSL configuration (required for HTTP/2)
certfile = "/app/certs/server.crt"
keyfile = "/app/certs/serv... | 25 | 535 |
mlflow | mlflow/tracking/artifact_utils.py | .py | """
Utilities for dealing with artifacts in the context of a Run.
"""
import os
import pathlib
import posixpath
import tempfile
import urllib.parse
import uuid
from typing import Any
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
from mlflow.store.artifa... | 184 | 8,632 |
mlflow | mlflow/genai/prompts/utils.py | .py | import re
from typing import Any
def format_prompt(prompt: str, **values: Any) -> str:
"""Format double-curly variables in the prompt template."""
for key, value in values.items():
# Escape backslashes in the replacement string to prevent re.sub from interpreting
# them as escape sequences (e.... | 13 | 508 |
kafka | tests/kafkatest/services/verifiable_producer.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 use ... | 332 | 15,686 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.