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 |
|---|---|---|---|---|---|
pdm | src/pdm/installers/core.py | .py | from __future__ import annotations
from collections.abc import Iterable
from pdm.environments import BaseEnvironment
from pdm.models.requirements import Requirement
from pdm.resolver.reporters import LockReporter
def install_requirements(
reqs: Iterable[Requirement],
environment: BaseEnvironment,
clean:... | 46 | 1,473 |
coremltools | coremltools/converters/mil/mil/ops/defs/_utils.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 math
import numbers
from typing import List, Tuple
import numpy as np
from coremltools.conv... | 661 | 24,694 |
pyro | tests/common.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import contextlib
import numbers
import os
import re
import warnings
from itertools import product
import numpy as np
import pytest
import torch
import torch.cuda
from numpy.testing import assert_allclose
from pytest import approx... | 297 | 9,455 |
readthedocs.org | readthedocs/config/tests/utils.py | .py | def apply_fs(tmpdir, contents):
"""
Create the directory structure specified in ``contents``.
It's a dict of filenames as keys and the file contents as values. If the
value is another dict, it's a subdirectory.
"""
for filename, content in contents.items():
if hasattr(content, "items"):... | 15 | 480 |
metrics | docs/source/pyplots/collection_binary_together.py | .py | import matplotlib.pyplot as plt
import torch
import torchmetrics
N = 10
num_updates = 10
num_steps = 5
w = torch.tensor([0.2, 0.8])
target = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
preds = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
collection ... | 30 | 800 |
jupytext | tests/data/notebooks/outputs/ipynb_to_script/raw_cell_with_non_dict_yaml_content.py | .py | # ---
# Content.
# jupyter:
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
print("Hello, World!")
| 11 | 146 |
sphinx | sphinx/ext/autodoc/_dynamic/_preserve_defaults.py | .py | """Preserve function defaults.
Preserve the default argument values of function signatures in source code
and keep them not evaluated for readability.
"""
from __future__ import annotations
import ast
import inspect
import types
from typing import TYPE_CHECKING
from sphinx.ext.autodoc._shared import LOGGER
from sph... | 158 | 5,436 |
sphinx | tests/test_extensions/test_ext_inheritance_diagram.py | .py | """Test sphinx.ext.inheritance_diagram extension."""
from __future__ import annotations
import re
import sys
import zlib
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from docutils import nodes
from sphinx.ext.inheritance_diagram import (
InheritanceDiagram,
InheritanceException,
... | 387 | 14,626 |
astropy | astropy/utils/masked/core.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Built-in mask mixin class.
The design uses `Masked` as a factory class which automatically
generates new subclasses for any data class that is itself a
subclass of a predefined masked class, with `MaskedNDArray`
providing such a predefined class for `... | 1,463 | 56,361 |
confluent-kafka-python | src/confluent_kafka/deserializing_share_consumer.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 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 requi... | 162 | 7,817 |
astropy | astropy/convolution/tests/test_convolve_nddata.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
import pytest
from astropy.convolution.convolve import convolve, convolve_fft
from astropy.convolution.kernels import Gaussian2DKernel
from astropy.nddata import NDData
def test_basic_nddata():
arr = np.zeros((11, 11))
arr[5,... | 65 | 1,836 |
mlflow | tests/deployments/test_cli.py | .py | import json
import os
from unittest import mock
import pytest
from click.testing import CliRunner
from mlflow.deployments import cli
from mlflow.exceptions import MlflowException
f_model_uri = "fake_model_uri"
f_name = "fake_deployment_name"
f_flavor = "fake_flavor"
f_target = "faketarget"
runner = CliRunner()
def... | 154 | 4,731 |
saleor | saleor/tests/e2e/vouchers/utils/query_voucher.py | .py | from ...utils import get_graphql_content
VOUCHER_QUERY = """
query voucherQuery ($id:ID!){
voucher(id: $id) {
discountValue
discountValueType
id
name
onlyForStaff
singleUse
startDate
endDate
used
usageLimit
codes(first: 10) {
edges {
node {
code
... | 41 | 625 |
pyomo | pyomo/core/kernel/homogeneous_container.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... | 74 | 2,723 |
omegaconf | tests/structured_conf/test_structured_config.py | .py | import dataclasses
import inspect
import pathlib
import re
import sys
from contextlib import AbstractContextManager
from enum import Enum
from importlib import import_module
from pathlib import Path
from types import LambdaType
from typing import Any, Callable, Dict, Generic, List, Optional, Tuple, TypeVar, Union
from... | 2,664 | 92,265 |
saleor | saleor/graphql/checkout/mutations/checkout_language_code_update.py | .py | import graphene
from saleor.checkout.actions import call_checkout_event
from saleor.webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
from ...core.context import SyncWebhookControlContext
from ...core.descriptions import DEPRECATED_IN_3X_INPUT
from ...core.doc_category import DOC_CATEGO... | 79 | 2,594 |
wandb | tests/system_tests/test_sweep/test_launch_scheduler.py | .py | """Sweep tests."""
import asyncio
from unittest.mock import Mock, patch
import pytest
import wandb
from wandb.apis import internal, public
from wandb.errors import CommError
from wandb.sdk.launch.sweeps import SchedulerError, SweepNotFoundError, load_scheduler
from wandb.sdk.launch.sweeps.scheduler import (
RunSt... | 817 | 25,184 |
beam | sdks/python/apache_beam/examples/ml_transform/mltransform_generate_vocab_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... | 192 | 6,376 |
beam | sdks/python/apache_beam/testing/test_stream.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... | 723 | 26,826 |
astropy | astropy/io/votable/validator/html.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# STDLIB
import contextlib
import os
import re
from math import ceil
from astropy import online_docs_root
from astropy.io.votable import exceptions
from astropy.utils.xml.writer import XMLWriter, xml_escape
html_header = """<?xml version="1.0" encoding=... | 313 | 9,889 |
conda | conda/models/match_spec.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Implements the query language for conda packages (a.k.a, MatchSpec).
The MatchSpec is the conda package specification (e.g. `conda==23.3`, `python<3.7`,
`cryptography * *_0`) and is used to communicate the desired packages to install.
"""
f... | 1,688 | 62,430 |
saleor | saleor/plugins/models.py | .py | from django.db import models
from django.db.models import JSONField
from ..channel.models import Channel
from ..core.utils.json_serializer import CustomJsonEncoder
from ..permission.enums import PluginsPermissions
class PluginConfiguration(models.Model):
identifier = models.CharField(max_length=128)
name = m... | 36 | 1,176 |
python-prompt-toolkit | src/prompt_toolkit/output/win32.py | .py | from __future__ import annotations
import sys
assert sys.platform == "win32"
import os
from collections.abc import Callable
from ctypes import ArgumentError, byref, c_char, c_long, c_uint, c_ulong, pointer
from ctypes.wintypes import DWORD, HANDLE
from typing import TextIO, TypeVar
from prompt_toolkit.cursor_shapes... | 686 | 22,666 |
astropy | astropy/visualization/tests/test_units.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import io
import pytest
from astropy.utils.compat.optional_deps import HAS_PLT
if HAS_PLT:
from matplotlib.figure import Figure
from matplotlib.units import ConversionError
import numpy as np
from astropy import units as u
from astropy.coordi... | 233 | 7,084 |
metrics | src/torchmetrics/wrappers/__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... | 41 | 1,462 |
astropy | astropy/visualization/wcsaxes/tests/test_grid_paths.py | .py | import numpy as np
import pytest
from matplotlib.lines import Path
from astropy.visualization.wcsaxes.grid_paths import get_lon_lat_path
@pytest.mark.parametrize("step_in_degrees", [10, 1, 0.01])
def test_round_trip_visibility(step_in_degrees):
zero = np.zeros(100)
# The pixel values are irrelevant for this... | 29 | 1,050 |
loguru | tests/exceptions/source/backtrace/missing_lineno_frame_objects.py | .py | import sys
from collections import namedtuple
from loguru import logger
logger.remove()
logger.add(
sys.stderr,
format="{line}: {message}",
colorize=False,
backtrace=True,
diagnose=False,
)
# Regression since CPython 3.10: the `lineno` can be `None`: https://github.com/python/cpython/issues/89726... | 44 | 1,062 |
clearml | examples/frameworks/jsonargparse/pytorch_lightning_cli_old.py | .py | # Copyright The PyTorch 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 i... | 116 | 3,930 |
ipython | tests/simpleerr.py | .py | """Error script. DO NOT EDIT FURTHER! It will break exception doctests!!!"""
import sys
def div0():
"foo"
x = 1
y = 0
x / y
def sysexit(stat, mode):
raise SystemExit(stat, f"Mode = {mode}")
def bar(mode):
"bar"
if mode == "div":
div0()
elif mode == "exit":
try:
... | 38 | 593 |
deap | examples/es/cma_plotting.py | .py | # This file is part of DEAP.
#
# DEAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# DEAP is distributed ... | 128 | 4,286 |
openvino | tests/e2e_tests/common/postprocessors/__init__.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from . import YOLO
from . import classification
from . import common
from . import ctc
from . import filters
from . import image_modifications
from . import mask_rcnn
from . import object_detection
from . import semantic_segmentation
fro... | 14 | 352 |
beam | sdks/python/apache_beam/ml/rag/ingestion/mysql_common.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... | 434 | 15,163 |
astropy | astropy/coordinates/tests/test_finite_difference_velocities.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
import pytest
from astropy import constants
from astropy import units as u
from astropy.coordinates import (
CartesianDifferential,
CartesianRepresentation,
DynamicMatrixTransform,
FunctionTransformWithFiniteDifference... | 286 | 9,500 |
qutip | qutip/tests/core/data/test_scipy_sparse.py | .py | """
Tests for qutip.core.data._scipy_sparse, in particular the forward-compatible
"removal path": the behaviour once a future SciPy stops shipping the legacy
``csr_matrix`` / ``dia_matrix`` types.
qutip stores everything internally as the modern ``*_array`` types, so the only
place that needs the legacy matrices is th... | 136 | 5,187 |
mlflow | mlflow/entities/model_registry/prompt_version.py | .py | from __future__ import annotations
import json
import re
from typing import Any
from pydantic import BaseModel, Field, ValidationError
from mlflow.entities.model_registry._model_registry_entity import _ModelRegistryEntity
from mlflow.entities.model_registry.model_version_tag import ModelVersionTag
from mlflow.except... | 574 | 22,164 |
textual | tests/test_border_subtitle.py | .py | from textual.app import App, ComposeResult
from textual.widget import Widget
async def test_border_subtitle():
class BorderWidget(Widget):
BORDER_TITLE = "foo"
BORDER_SUBTITLE = "bar"
class SimpleApp(App):
def compose(self) -> ComposeResult:
yield BorderWidget()
empty... | 19 | 518 |
mlflow | tests/data/test_artifact_dataset_sources.py | .py | import json
import os
from unittest import mock
import pytest
from mlflow.data.dataset_source_registry import get_dataset_source_from_json, resolve_dataset_source
from mlflow.data.filesystem_dataset_source import FileSystemDatasetSource
from mlflow.store.artifact.s3_artifact_repo import S3ArtifactRepository
@pytest... | 138 | 5,771 |
mlflow | tests/tracing/test_assessment.py | .py | import os
from unittest import mock
import pytest
import mlflow
from mlflow.entities.assessment import (
AssessmentError,
Expectation,
Feedback,
IssueReference,
)
from mlflow.entities.assessment_source import AssessmentSource, AssessmentSourceType
from mlflow.entities.issue import IssueStatus
from mlf... | 1,088 | 38,795 |
pyomo | examples/gdp/strip_packing/strip_packing_8rect.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... | 116 | 3,896 |
sqlmap | plugins/dbms/informix/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 searchDb(self):
... | 39 | 1,021 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/embed_layer_norm_gen.py | .py | import onnx
from onnx import TensorProto, helper
from packaging import version
if version.parse(onnx.__version__) == version.parse("1.8.0"):
opset_version = 13
elif version.parse(onnx.__version__) == version.parse("1.6.0"):
opset_version = 11
else:
raise RuntimeError("Please pip install onnx==1.8.0 or 1.6.... | 989 | 33,312 |
conda | conda/auxlib/ish.py | .py | from logging import getLogger
from textwrap import dedent
log = getLogger(__name__)
def dals(string):
"""dedent and left-strip"""
return dedent(string).lstrip()
def _get_attr(obj, attr_name, aliases=()):
try:
return getattr(obj, attr_name)
except AttributeError:
for alias in aliases... | 66 | 1,964 |
astropy | astropy/constants/tests/test_pickle.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
from astropy import constants as const
from astropy.tests.helper import check_pickling_recovery, pickle_protocol # noqa: F401
originals = [
const.Constant("h_fake", "Not Planck", 0.0, "J s", 0.0, "fakeref", system="si"),
const.h,
... | 18 | 507 |
wagtail | wagtail/documents/tests/test_api_v3/test_delete.py | .py | from unittest import mock
from django.contrib.auth.models import Group, Permission
from django.db.models.signals import post_delete
from django.urls import reverse
from wagtail.documents import get_document_model
from wagtail.models import GroupCollectionPermission
from .base import TestV3DocumentsBase
Document = g... | 101 | 3,680 |
pyro | pyro/distributions/transforms/power.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import torch
from torch.distributions import Distribution, constraints
from torch.distributions.transforms import Transform
class PositivePowerTransform(Transform):
r"""
Transform via the mapping
:math:`y=\operatorname{si... | 62 | 2,139 |
sqlmap | plugins/generic/search.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.common import arrayizeValue
from lib.core.common import Backend
from lib.core.common import filterPairValues
from lib.cor... | 645 | 28,319 |
pyomo | pyomo/solvers/plugins/solvers/gurobi_direct.py | .py | # ____________________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright (c) 2008-2026 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and Engineering
# Solutions of... | 1,156 | 46,812 |
probability | tensorflow_probability/python/distributions/skellam_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... | 316 | 12,524 |
onnxruntime | orttraining/orttraining/python/training/utils/hooks/_subscriber_manager.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
import inspect
from contextlib import contextmanager
import onnx
impor... | 292 | 13,800 |
dirty-equals | tests/test_datetime.py | .py | from datetime import date, datetime, timedelta, timezone
from unittest.mock import Mock
from zoneinfo import ZoneInfo
import pytest
from dirty_equals import IsDate, IsDatetime, IsNow, IsToday
@pytest.mark.parametrize(
'value,dirty,expect_match',
[
pytest.param(datetime(2000, 1, 1), IsDatetime(approx... | 196 | 9,031 |
django-cms | cms/tests/test_menu_page_viewperm_staff.py | .py | from django.contrib.auth import get_user_model
from django.test.utils import override_settings
from cms.tests.test_menu_page_viewperm import ViewPermissionTests
__all__ = [
'ViewPermissionComplexMenuStaffNodeTests',
]
@override_settings(
CMS_PERMISSION=True,
CMS_PUBLIC_FOR='staff',
)
class ViewPermissio... | 446 | 17,944 |
sqlmap | plugins/dbms/firebird/filesystem.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.filesystem import Filesystem as GenericFilesystem
class Filesystem(GenericFilesystem):
d... | 19 | 674 |
onnx | onnx/reference/ops/op_one_hot.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
import numpy as np
from onnx.reference.op_run import OpRun
def _one_hot(indices, depth, axis=-1, dtype=np.float32):
values = np.asarray(indices)
rank = len(values.shape)
depth_range = np.a... | 33 | 1,057 |
sqlmap | plugins/dbms/sybase/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... | 25 | 898 |
coremltools | coremltools/converters/mil/mil/ops/defs/iOS18/compression.py | .py | # Copyright (c) 2023, 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 math
from typing import List, Optional
import numpy as np
from coremltools.converters.mil.mil... | 761 | 31,205 |
readthedocs.org | readthedocs/projects/tests/test_validators.py | .py | import pytest
from django.core.exceptions import ValidationError
from readthedocs.projects import validators
def test_repository_path_validator():
# Invalid stuff
with pytest.raises(ValidationError):
validators.validate_build_config_file("/absolute_path")
with pytest.raises(ValidationError):
... | 43 | 1,608 |
jupytext | tests/functional/others/test_active_cells.py | .py | import pytest
from nbformat import NotebookNode
import jupytext
from jupytext.compare import compare, compare_cells
HEADER = {
".py": """# ---
# jupyter:
# jupytext:
# main_language: python
# ---
""",
".R": """# ---
# jupyter:
# jupytext:
# main_language: python
# ---
""",
".md": """---
jupy... | 368 | 9,335 |
beam | sdks/python/apache_beam/ml/anomaly/detectors/offline.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... | 119 | 4,488 |
beam | sdks/python/apache_beam/testing/benchmarks/chicago_taxi/trainer/taxi.py | .py | # Copyright 2019 Google LLC. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | 193 | 5,707 |
coremltools | deps/protobuf/python/mox.py | .py | #!/usr/bin/python2.4
#
# Copyright 2008 Google 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 o... | 1,402 | 38,238 |
mlflow | tests/store/tracking/mcp_server_registry/test_rest_mixin.py | .py | from __future__ import annotations
import inspect
from pathlib import Path
from typing import Any
from unittest import mock
import pytest
from fastapi import FastAPI
from starlette.testclient import TestClient
from mlflow.entities.mcp_server import MCPStatus, MCPTool
from mlflow.exceptions import MlflowException
fro... | 783 | 30,021 |
lemur | lemur/plugins/lemur_aws/plugin.py | .py | """
.. module: lemur.plugins.lemur_aws.plugin
:platform: Unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
Terraform example to setup the destination bucket:
resource "aws_s3_bucket" "certs_log_bucket" {
bucket = "certs-log-acce... | 881 | 32,670 |
clearml | clearml/binding/fire_bind.py | .py | from typing import Optional, Callable, List, Dict, Tuple, TYPE_CHECKING, Any
try:
import fire
import fire.core
import fire.helptext
except ImportError:
fire = None
import inspect
from .frameworks import _patched_call_no_recursion_guard # noqa
from ..config import get_remote_task_id, running_remotely... | 391 | 15,791 |
readthedocs.org | readthedocs/proxito/constants.py | .py | from enum import Enum
from enum import auto
class RedirectType(Enum):
http_to_https = auto()
to_canonical_domain = auto()
subproject_to_main_domain = auto()
# Application defined redirect.
system = auto()
# User defined redirect.
user = auto()
| 13 | 274 |
saleor | saleor/order/tests/test_notifications.py | .py | from decimal import Decimal
from functools import partial
from unittest import mock
import graphene
from django.core.files import File
from measurement.measures import Weight
from prices import Money, fixed_discount
from ...attribute.tests.model_helpers import (
get_product_attribute_values,
get_product_attri... | 801 | 28,780 |
wandb | tests/system_tests/test_artifacts/test_artifact_public_api.py | .py | from __future__ import annotations
import os
import platform
import random
import string
from collections.abc import Callable
from contextlib import nullcontext
from itertools import islice
from pathlib import Path
import wandb
from pytest import MonkeyPatch, fixture, mark, raises, skip
from wandb import Api
from wan... | 790 | 25,913 |
coveragepy | coverage/pth_file.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
# pylint: disable=missing-module-docstring
# pragma: exclude file from coverage
# This will become the .pth file for subprocesses.
import os
if os.getenv("COVER... | 17 | 525 |
wandb | wandb/sdk/lib/config_util.py | .py | from __future__ import annotations
import json
import logging
import os
from typing import Any
import wandb
from wandb.errors import Error
from wandb.util import load_yaml
from . import filesystem
logger = logging.getLogger("wandb")
class ConfigError(Error):
pass
def dict_from_proto_list(obj_list):
d = ... | 106 | 2,931 |
mlflow | mlflow/tracking/registry.py | .py | import warnings
from abc import ABCMeta
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import INVALID_PARAMETER_VALUE
from mlflow.utils.plugins import get_entry_points
from mlflow.utils.uri import get_uri_scheme
class UnsupportedModelRegistryStoreURIException(MlflowException):
""... | 87 | 3,524 |
wagtail | wagtail/contrib/simple_translation/apps.py | .py | from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class SimpleTranslationAppConfig(AppConfig):
name = "wagtail.contrib.simple_translation"
label = "simple_translation"
verbose_name = _("Wagtail simple translation")
default_auto_field = "django.db.models.AutoField... | 10 | 322 |
openvino | tests/layer_tests/tensorflow_tests/test_tf_TruncateDiv.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import platform
import numpy as np
import pytest
import tensorflow as tf
from common.tf_layer_test_class import CommonTFLayerTest
class TestTruncateDiv(CommonTFLayerTest):
def _prepare_input(self, inputs_info):
assert 'x:0... | 56 | 2,392 |
probability | tensorflow_probability/python/math/psd_kernels/gamma_exponential.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... | 217 | 9,234 |
saleor | saleor/tests/e2e/checkout/taxes/test_checkout_calculate_simple_taxes_for_products_without_shipping.py | .py | import pytest
from ...product.utils.preparing_product import prepare_product
from ...shop.utils.preparing_shop import prepare_shop
from ...taxes.utils import update_country_tax_rates
from ...utils import assign_permissions
from ..utils import (
checkout_billing_address_update,
checkout_complete,
checkout_c... | 159 | 4,855 |
voila | tests/app/nbextensions_test.py | .py | # tests programmatic config of template system
import os
import pytest
BASE_DIR = os.path.dirname(__file__)
@pytest.fixture
def voila_config():
def config(app):
pass
os.environ["JUPYTER_CONFIG_DIR"] = os.path.join(BASE_DIR, "../configs/general")
yield config
del os.environ["JUPYTER_CONFIG_D... | 33 | 923 |
bazel | third_party/py/frozendict/frozendict/__init__.py | .py | import collections
import operator
import functools
import sys
try:
from collections import OrderedDict
except ImportError: # python < 2.7
OrderedDict = NotImplemented
iteritems = getattr(dict, 'iteritems', dict.items) # py2-3 compatibility
class frozendict(collections.abc.Mapping):
"""
An immuta... | 65 | 1,507 |
beam | sdks/python/apache_beam/typehints/opcodes.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... | 732 | 20,407 |
ipython | tests/test_utils_terminal.py | .py | """Tests for IPython.utils.terminal."""
import importlib
import os
import pytest
from IPython.testing.decorators import skip_win32
from IPython.utils import terminal
@pytest.fixture
def reload_with_term():
"""Reload the terminal module with a given TERM, then restore it."""
def reload(term_value):
... | 141 | 4,970 |
saleor | saleor/graphql/account/tests/mutations/permission_group/test_permission_group_create.py | .py | import json
from unittest.mock import patch
import graphene
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from ......account.error_codes import PermissionGroupErrorCode
from ......account.models import Group, User
from ......channel.models import Channel
from ......core.utils.... | 665 | 21,563 |
mlflow | mlflow/prompt/promptlab_model.py | .py | import os
import re
import yaml
from mlflow.exceptions import MlflowException
from mlflow.version import VERSION as __version__
class _PromptlabModel:
import pandas as pd
def __init__(self, prompt_template, prompt_parameters, model_parameters, model_route):
self.prompt_parameters = prompt_parameter... | 198 | 7,090 |
saleor | saleor/graphql/account/bulk_mutations/user_bulk_set_active.py | .py | import graphene
from django.core.exceptions import ValidationError
from ....account import models
from ....account.error_codes import AccountErrorCode
from ....permission.enums import AccountPermissions
from ...core import ResolveInfo
from ...core.doc_category import DOC_CATEGORY_USERS
from ...core.mutations import Ba... | 60 | 2,028 |
saleor | saleor/graphql/account/resolvers.py | .py | from itertools import chain
from django.db.models import Q
from graphql import GraphQLError
from i18naddress import get_validation_rules
from ...account import models
from ...core.exceptions import PermissionDenied
from ...graphql.core.context import get_database_connection_name
from ...payment import gateway
from ..... | 278 | 9,512 |
onnxruntime | onnxruntime/test/python/transformers/test_skip_layer_norm_fusion.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 ... | 465 | 19,248 |
openvino | tests/layer_tests/tensorflow_tests/test_tf_LeakyRelu.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
import tensorflow as tf
from common.tf_layer_test_class import CommonTFLayerTest
rng = np.random.default_rng(54654675)
class TestLeakyRelu(CommonTFLayerTest):
def _prepare_input(self, inputs_info):... | 43 | 1,742 |
saleor | saleor/tests/e2e/orders/test_order_fulfill_and_add_tracking.py | .py | import pytest
from .. import DEFAULT_ADDRESS
from ..product.utils.preparing_product import prepare_product
from ..shop.utils import prepare_shop
from ..utils import assign_permissions
from .utils import (
draft_order_complete,
draft_order_create,
draft_order_update,
mark_order_paid,
order_add_track... | 164 | 4,394 |
conda | conda/plugins/subcommands/__init__.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
from . import doctor as _doctor
from . import plugins as _plugins
plugins = [_doctor, _plugins]
| 7 | 172 |
saleor | saleor/tests/e2e/orders/test_unable_to_update_save_settings_after_order_completion.py | .py | import pytest
from .. import ADDRESS_DE, DEFAULT_ADDRESS
from ..account.utils import create_customer
from ..product.utils.preparing_product import prepare_product
from ..shop.utils.preparing_shop import prepare_default_shop
from ..utils import assert_address_data, assign_permissions
from .utils import (
draft_orde... | 129 | 3,959 |
probability | tensorflow_probability/python/internal/custom_gradient.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... | 151 | 5,618 |
hatch | tests/utils/test_auth.py | .py | from hatch.publish.auth import AuthenticationCredentials
from hatch.utils.fs import Path
def test_pypirc(tmp_path, mocker):
# Create a fake home directory
fake_home = tmp_path / "home"
fake_home.mkdir()
# Create .pypirc in the fake home
pypirc = fake_home / ".pypirc"
pypirc.write_text("""\
[o... | 49 | 1,278 |
mlflow | mlflow/genai/evaluation/telemetry.py | .py | import hashlib
import threading
import uuid
import mlflow
from mlflow.genai.scorers.base import Scorer
from mlflow.genai.scorers.builtin_scorers import BuiltInScorer
from mlflow.utils.databricks_utils import get_databricks_host_creds
from mlflow.utils.rest_utils import _REST_API_PATH_PREFIX, http_request
from mlflow.u... | 142 | 4,375 |
beam | sdks/python/apache_beam/examples/inference/tensorflow_mnist_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... | 127 | 4,410 |
mlflow | tests/server/jobs/test_online_scoring_jobs.py | .py | import json
import os
import uuid
from dataclasses import asdict
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from mlflow.entities._job_status import JobStatus
from mlflow.genai.judges import make_judge
from mlflow.genai.scorers.base import Scorer
from mlflo... | 278 | 10,296 |
beam | sdks/python/apache_beam/ml/transforms/tft.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... | 747 | 27,518 |
mlflow | tests/llama_index/sample_code/query_engine_with_reranker.py | .py | """
Sample code to define a query engine with post processors and save it with model-from-code logging.
Ref: https://qdrant.tech/documentation/quickstart/
"""
from llama_index.core import Document, QueryBundle, VectorStoreIndex
from llama_index.core.postprocessor import LLMRerank
from llama_index.core.postprocessor.t... | 42 | 1,093 |
saleor | saleor/checkout/problems.py | .py | import datetime
from collections import defaultdict
from collections.abc import Iterable
from dataclasses import dataclass
from ..graphql.core.context import ChannelContext
from ..product.models import ProductChannelListing, ProductVariant
from ..warehouse.models import Stock
from .fetch import CheckoutInfo, CheckoutL... | 230 | 6,831 |
onnxruntime | onnxruntime/test/testdata/transform/concat_slice_elimination.py | .py | import numpy as np
import onnx
from onnx import OperatorSetIdProto, TensorProto, helper, numpy_helper
batch = 3
hidden_size = 4
attention_head = 2
hidden_per_attention = 2
relative_attention_num_buckets = 32
input_len = 8
output_len = 8
X = helper.make_tensor_value_info("input", TensorProto.FLOAT, [batch, input_len,... | 186 | 5,999 |
probability | tensorflow_probability/python/internal/backend/numpy/tf_inspect.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... | 48 | 1,859 |
hatch | src/hatch/project/frontend/scripts/standard.py | .py | from __future__ import annotations
import json
import os
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
RUNNER: dict = {}
def main() -> int:
project_root: str = RUNNER["project_root"]
output_dir: str = RUNNER["output_dir"]
hook: str = RUNNER["hook"]
kwargs: dict[s... | 83 | 2,476 |
python-prompt-toolkit | examples/progress-bar/nested-progress-bars.py | .py | #!/usr/bin/env python
"""
Example of nested progress bars.
"""
import time
from prompt_toolkit import HTML
from prompt_toolkit.shortcuts import ProgressBar
def main():
with ProgressBar(
title=HTML('<b fg="#aa00ff">Nested progress bars</b>'),
bottom_toolbar=HTML(" <b>[Control-L]</b> clear <b>[Co... | 24 | 566 |
black | tests/data/cases/function.py | .py | #!/usr/bin/env python3
import asyncio
import sys
from third_party import X, Y, Z
from library import some_connection, \
some_decorator
f'trigger 3.6 mode'
def func_no_args():
a; b; c
if True: raise RuntimeError
if False: ...
for i in range(10):
print(i)
continue
exec("new-style e... | 245 | 6,408 |
pyomo | examples/performance/jump/lqcp.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... | 84 | 2,358 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.