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
coremltools
coremltools/__init__.py
.py
# Copyright (c) 2017, 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 """ Core ML is an Apple framework which allows developers to simply and easily integrate machine learnin...
155
5,720
metrics
tests/unittests/image/test_dists.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...
107
3,704
kombu
t/unit/transport/test_sqlalchemy.py
.py
from __future__ import annotations from unittest.mock import Mock, patch import pytest from kombu import Connection from kombu.exceptions import OperationalError pytest.importorskip('sqlalchemy') class test_SqlAlchemy: def test_url_parser(self): with patch('kombu.transport.sqlalchemy.Channel._open'):...
66
2,013
onnx
onnx/reference/ops/op_sqrt.py
.py
# Copyright (c) ONNX Project Contributors # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations from warnings import catch_warnings, simplefilter import numpy as np from onnx.reference.ops._op import OpRunUnaryNum class Sqrt(OpRunUnaryNum): def _run(self, x): with catch_warnings(): ...
18
404
astropy
astropy/cosmology/_src/tests/helper.py
.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ This module provides the tools used to internally run the cosmology test suite from the installed astropy. It makes use of the |pytest| testing framework. """ __all__ = ("clean_registry", "get_redshift_methods") import inspect import pytest from ...
108
3,482
pyomo
pyomo/solvers/tests/piecewise_linear/kernel_problems/step_var.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...
53
1,661
metrics
src/torchmetrics/functional/pairwise/cosine.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...
92
3,499
wandb
wandb/apis/public/artifacts.py
.py
"""W&B Public API for Artifact objects. This module provides classes for interacting with W&B artifacts and their collections. """ from __future__ import annotations from collections.abc import Collection, Iterable, Mapping, Sequence from copy import copy from functools import lru_cache from typing import ( # noqa:...
1,216
41,817
omegaconf
omegaconf/grammar_parser.py
.py
import re import threading from typing import Any from .errors import GrammarParseError # Import from visitor in order to check the presence of generated grammar files # files in a single place. from .grammar_visitor import ( # type: ignore OmegaConfGrammarLexer, OmegaConfGrammarParser, ) from .typing import...
149
5,691
saleor
saleor/graphql/menu/tests/deprecated/test_menu.py
.py
import warnings import graphene from .....channel.utils import DEPRECATION_WARNING_MESSAGE from .....menu.models import MenuItem from ....tests.utils import get_graphql_content def test_menu_items_collection_without_providing_channel( user_api_client, menu_item, published_collection ): query = """ query...
60
1,686
saleor
saleor/core/utils/events.py
.py
from django.db import transaction from ...webhook.event_types import WebhookEventAsyncType def get_is_deferred_payload(event_name: str) -> bool: """Return True if the event has deferred payload. When the event has deferred payload, the payload will be generated in the Celery task during webhook delivery...
29
979
pyomo
pyomo/solvers/tests/models/QP_constant_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...
57
2,060
wandb
wandb/sdk/wandb_require.py
.py
"""Feature Flags Module. This module implements a feature flag system for the wandb library to require experimental features and notify the user when features have been deprecated. Example: import wandb wandb.require("wandb-service@beta") wandb.require("incremental-artifacts@beta") """ from __future__ im...
89
2,722
textual
tests/snapshot_tests/snapshot_apps/loading.py
.py
from rich.console import RenderableType from textual.app import App, ComposeResult from textual.containers import Horizontal from textual.widget import Widget from textual.widgets import OptionList class SimpleLoadingIndicator(Widget): """A loading indicator that doesn't animate.""" DEFAULT_CSS = """ Si...
57
1,402
confluent-kafka-python
tests/avro/test_util.py
.py
#!/usr/bin/env python # # Copyright 2016 Confluent Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
45
1,395
openvino
tools/ovc/unit_tests/moc_tf_fe/conversion_incorrect_models_test.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import tempfile import unittest from openvino.tools.ovc.convert import convert_model class TestMoFreezePlaceholderTFFE(unittest.TestCase): def test_conversion_fake_pb_model(self): # TODO: Should FEs give detailed...
18
624
ipython
tests/test_ipunittest.py
.py
"""Tests for IPython's test support utilities. These are decorators that allow standalone functions and docstrings to be seen as tests by unittest, replicating some of nose's functionality. Additionally, IPython-syntax docstrings can be auto-converted to '>>>' so that ipython sessions can be copy-pasted as tests. Th...
136
3,365
kafka
tests/kafkatest/services/__init__.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 ...
15
780
pyro
pyro/contrib/funsor/handlers/enum_messenger.py
.py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 """ This file contains reimplementations of some of Pyro's core enumeration machinery, which should eventually be drop-in replacements for the current versions. """ import functools import math from collections import OrderedDict imp...
267
9,728
mkdocs-material
material/plugins/projects/builder/watcher/handler.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...
106
3,874
black
tests/data/cases/docstring.py
.py
class MyClass: """ Multiline class docstring """ def method(self): """Multiline method docstring """ pass def foo(): """This is a docstring with some lines of text here """ return def bar(): '''This is another docstring with more lines of text ''' return def b...
458
7,926
lemur
lemur/plugins/lemur_acme/tests/test_nsone.py
.py
""" Unit Tests for NSone DNS provider """ import unittest from unittest.mock import patch, Mock from flask import Flask from lemur.plugins.lemur_acme import plugin, nsone class TestNsone(unittest.TestCase): """ Class for testing NSone plugin """ @patch("lemur.plugins.lemur_acme.plugin.dns_provider_s...
268
9,812
mlflow
mlflow/genai/judges/prompts/conversational_tool_call_efficiency.py
.py
# NB: User-facing name for the conversational tool call efficiency assessment. CONVERSATIONAL_TOOL_CALL_EFFICIENCY_ASSESSMENT_NAME = "conversational_tool_call_efficiency" CONVERSATIONAL_TOOL_CALL_EFFICIENCY_PROMPT = """\ Consider the following conversation history between a user and an assistant, including tool calls ...
27
1,541
saleor
saleor/graphql/core/federation/__init__.py
.py
from .entities import federated_entity from .resolvers import resolve_federation_references __all__ = ["federated_entity", "resolve_federation_references"]
5
157
pyomo
pyomo/core/plugins/transform/expand_connectors.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...
293
11,992
pyomo
pyomo/solvers/tests/checks/test_GAMS.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...
520
20,266
clearml
clearml/backend_interface/routers.py
.py
from typing import Any, Dict, List, Optional from .base import InterfaceBase from ..backend_api import Session class RouterService(InterfaceBase): """ Interface to the ``routers`` backend service, used to query router routes. """ def get_routes(self, name: Optional[str] = None) -> List[Dict[str, Any...
93
3,146
wagtail
wagtail/images/tests/test_blocks.py
.py
import unittest.mock from django.apps import apps from django.test import TestCase from django.utils.safestring import SafeString from wagtail.admin import compare from wagtail.admin.telepath import JSContext from wagtail.blocks.stream_block import StreamValue from wagtail.blocks.struct_block import StructBlockValida...
556
18,915
kombu
examples/simple_task_queue/client.py
.py
from __future__ import annotations from kombu.pools import producers from .queues import task_exchange priority_to_routing_key = { 'high': 'hipri', 'mid': 'midpri', 'low': 'lopri', } def send_as_task(connection, fun, args=(), kwargs={}, priority='mid'): payload = {'fun': fun, 'args': args, 'kwargs'...
35
994
wandb
wandb/sdk/internal/profiler.py
.py
"""Integration with pytorch profiler.""" import os import wandb from wandb.errors import Error, UsageError from wandb.sdk.lib import telemetry PYTORCH_MODULE = "torch" PYTORCH_PROFILER_MODULE = "torch.profiler" def torch_trace_handler(): """Create a trace handler for traces generated by the profiler. Pro...
80
2,391
onnxruntime
onnxruntime/python/tools/transformers/models/torch_export_patches/onnx_export_serialization.py
.py
from typing import Any import torch from transformers.cache_utils import DynamicCache, MambaCache ############ # MambaCache ############ # self.conv_states: torch.Tensor = torch.zeros( # config.num_hidden_layers, # self.max_batch_size, # self.intermediate_size, # self.conv_kernel_size, # device=...
125
3,757
mlflow
mlflow/genai/utils/gateway_utils.py
.py
from __future__ import annotations import base64 from dataclasses import dataclass from mlflow.environment_variables import MLFLOW_GATEWAY_URI from mlflow.exceptions import MlflowException from mlflow.tracking import get_tracking_uri from mlflow.utils.credentials import read_mlflow_creds from mlflow.utils.uri import ...
114
4,114
colorama
colorama/win32.py
.py
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file. # from winbase.h STDOUT = -11 STDERR = -12 ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 try: import ctypes from ctypes import LibraryLoader windll = LibraryLoader(ctypes.WinDLL) from ctypes import wintypes except (AttributeErro...
181
6,181
saleor
saleor/celeryconf.py
.py
import logging import os from celery import Celery from celery.signals import setup_logging, worker_process_init from django.conf import settings from .core.telemetry import initialize_telemetry from .plugins import discover_plugins_modules CELERY_LOGGER_NAME = "celery" @setup_logging.connect def setup_celery_logg...
71
1,968
conda
tests/plugins/test_lazy_types.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """Verify ``conda.plugins.types`` loads lazily and its deprecated re-exports.""" from __future__ import annotations import os import subprocess import sys import textwrap import pytest _DEPRECATED_NAMES = ( "CondaAuthHandler", "Conda...
96
2,749
biopython
Bio/SeqUtils/ProtParam.py
.py
# Copyright 2003 Yair Benita. 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. """Simple protein analysis. Exa...
351
13,174
openvino
src/frontends/paddle/tests/test_models/gen_scripts/generate_eye.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # # fill_const paddle model generator # import numpy as np from save_model import saveModel import paddle import sys def eye(name : str, rows, cols = None, dtype = None): paddle.enable_static() with paddle.static.program_guard(...
42
1,406
textual
tests/snapshot_tests/snapshot_apps/dynamic_bindings.py
.py
from __future__ import annotations from textual.app import App, ComposeResult from textual.widgets import Footer class BindingsApp(App): """Check dynamic actions are displayed in the footer.""" BINDINGS = [ ("a", "a", "A"), ("b", "b", "B"), ("c", "c", "C"), ] def compose(self...
42
985
attrs
src/attr/__init__.py
.py
# SPDX-License-Identifier: MIT """ Classes Without Boilerplate """ import sys from functools import partial from typing import Callable, Literal, Protocol from . import exceptions, setters from ._cmp import cmp_using from ._config import get_run_validators, set_run_validators from ._funcs import asdict, assoc, astu...
121
2,386
onnx
onnx/reference/ops/op_less.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 OpRunBinaryComparison class Less(OpRunBinaryComparison): def _run(self, a, b): return (np.less(a, b),)
14
289
hydra
setup.py
.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # type: ignore import pathlib from setuptools import find_namespace_packages, setup from build_helpers.build_helpers import ( ANTLRCommand, BuildPyCommand, CleanCommand, Develop, SDistCommand, find_version, ) with pathlib....
63
2,152
conda
conda/common/__init__.py
.py
# Copyright (C) 2012 Anaconda, Inc # SPDX-License-Identifier: BSD-3-Clause """ Code in ``conda.common`` is not conda-specific. Technically, it sits *aside* the application stack and not *within* the stack. It is able to stand independently on its own. The *only* allowed imports of conda code in ``conda.common`` modul...
12
494
openvino
src/bindings/python/src/openvino/properties/device/__init__.py
.py
# -*- coding: utf-8 -*- # Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # Enums from openvino._pyopenvino.properties.device import Type # Properties import openvino._pyopenvino.properties.device as __device from openvino.properties._properties import __make_properties __make_properti...
15
416
saleor
saleor/webhook/observability/exceptions.py
.py
from .payload_schema import ObservabilityEventTypes class ObservabilityError(Exception): pass class ConnectionNotConfigured(ObservabilityError): pass class TruncationError(ObservabilityError): _event_type: ObservabilityEventTypes | None = None def __init__(self, operation: str, bytes_limit: int, ...
38
1,027
metrics
tests/unittests/regression/test_cosine_similarity.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...
102
3,570
biopython
Bio/KEGG/KGML/KGML_parser.py
.py
# Copyright 2013 by Leighton Pritchard. 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. """Classes and func...
194
6,347
wandb
tests/unit_tests/test_analytics/test_sentry.py
.py
import os from unittest import mock import pytest import wandb import wandb.analytics import wandb.env from sentry_sdk.utils import sentry_sdk from .sentry_relay import MetricRelayServer, SentryResponse SENTRY_DSN_FORMAT = "http://{key}@127.0.0.1:{port}/{project}" @pytest.fixture(scope="module") def relay(): r...
598
21,977
saleor
saleor/graphql/account/mutations/account/send_confirmation_email.py
.py
from typing import cast from urllib.parse import urlencode import graphene from django.conf import settings from django.core.exceptions import ValidationError from django.utils import timezone from .....account import models from .....account.error_codes import SendConfirmationEmailErrorCode from .....account.notific...
128
4,621
confluent-kafka-python
examples/share_consumer_commit_sync.py
.py
#!/usr/bin/env python # # Copyright 2026 Confluent Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
115
4,203
gunicorn
tests/docker/dirty_arbiter/test_parent_death.py
.py
#!/usr/bin/env python # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. """ Docker-based integration tests for dirty arbiter process lifecycle. These tests verify: 1. Dirty arbiter self-terminates when main arbiter dies unexpectedly (SIGKILL) 2. Orphan cleanup wo...
528
18,623
hatch
src/hatch/env/virtual.py
.py
from __future__ import annotations import os import sys import sysconfig from contextlib import contextmanager, nullcontext, suppress from functools import cached_property from os.path import isabs from typing import TYPE_CHECKING from hatch.config.constants import AppEnvVars from hatch.env.plugin.interface import En...
550
21,818
beam
sdks/python/apache_beam/examples/sinks/test_write_bounded.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...
99
3,557
probability
tensorflow_probability/python/experimental/joint_distribution_layers/__init__.py
.py
# Copyright 2021 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
21
937
astropy
astropy/coordinates/tests/test_sites.py
.py
import shutil from pathlib import Path from threading import Lock import pytest from astropy import units as u from astropy.config import set_temp_cache from astropy.coordinates import EarthLocation, Latitude, Longitude, UnknownSiteException from astropy.coordinates.sites import SiteRegistry from astropy.tests.helper...
157
5,100
mlflow
examples/xgboost/xgboost_native/train.py
.py
import argparse import matplotlib as mpl import xgboost as xgb from sklearn import datasets from sklearn.metrics import accuracy_score, log_loss from sklearn.model_selection import train_test_split import mlflow import mlflow.xgboost mpl.use("Agg") def parse_args(): parser = argparse.ArgumentParser(description...
79
2,084
textual
src/textual/widgets/_tabs.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import ClassVar import rich.repr from rich.style import Style from rich.text import Text from textual import events from textual.app import ComposeResult, RenderResult from textual.await_complete import AwaitComplete from textual.bindin...
875
27,190
cvxpy
cvxpy/reductions/cone2cone/affine2direct.py
.py
""" Copyright 2020 the CVXPY developers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, so...
443
19,231
textual
tests/snapshot_tests/snapshot_apps/vertical_max_height.py
.py
from textual.app import App, ComposeResult from textual.containers import Vertical from textual.widgets import Placeholder class VerticalApp(App): CSS = """ #top { height: 1fr; border: white; } #bottom { height:3fr; border: white; max-height: 10; } ...
27
529
mlflow
mlflow/genai/scorers/llm_backend.py
.py
"""Shared LLM client for scorer packages and simulator. Provides a single routing layer so that DeepEval, RAGAS, Phoenix, TruLens scorers and the conversation simulator all resolve model URIs and make chat completion calls through the same code path. Note: This is NOT intended for judge adapters, which need lower-lev...
293
10,785
pyro
pyro/infer/enum.py
.py
# Copyright (c) 2017-2019 Uber Technologies, Inc. # SPDX-License-Identifier: Apache-2.0 import numbers from functools import partial from queue import LifoQueue from pyro import poutine from pyro.infer.util import is_validation_enabled from pyro.poutine import Trace from pyro.poutine.enum_messenger import enumerate_s...
221
8,063
saleor
saleor/graphql/core/descriptions.py
.py
from graphql import DEFAULT_DEPRECATION_REASON as DEFAULT_DEPRECATION_REASON from .const import DEFAULT_NESTED_LIST_LIMIT # Deprecation message for input fields and query arguments. Use it, when # deprecation message needs to be included in the field description. DEPRECATED_IN_3X_INPUT = "\n\nDEPRECATED: this field w...
46
1,542
wandb
wandb/sdk/launch/_project_spec.py
.py
"""Convert launch arguments into a runnable wandb launch script. Arguments can come from a launch spec or call to wandb launch. """ from __future__ import annotations import enum import json import logging import os import shlex import shutil import tempfile from copy import deepcopy from typing import TYPE_CHECKING...
606
22,792
jupytext
tests/functional/round_trip/test_jupytext_nbconvert_round_trip.py
.py
import pytest import jupytext from jupytext.header import header_to_metadata_and_cell @pytest.mark.requires_nbconvert def test_markdown_jupytext_nbconvert_is_identity(md_file): """Test that a Markdown file, converted to a notebook, then exported back to Markdown with nbconvert, yields the original file""" ...
84
2,991
astropy
astropy/io/ascii/rst.py
.py
# Licensed under a 3-clause BSD style license """ :Author: Simon Gibbons (simongibbons@gmail.com). """ from .core import DefaultSplitter from .fixedwidth import ( FixedWidth, FixedWidthData, FixedWidthHeader, FixedWidthTwoLineDataSplitter, ) class SimpleRSTHeader(FixedWidthHeader): position_line ...
100
2,826
gunicorn
tests/conftest.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. """Pytest configuration for gunicorn tests.""" import os import sys import pytest # Add the tests directory to sys.path so test support modules can be imported # as 'tests.module_name' (e.g., 'tests.support_dirt...
32
1,193
openvino
tests/layer_tests/tensorflow2_keras_tests/test_tf2_keras_activity_regularization.py
.py
# Copyright (C) 2018-2026 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import pytest import tensorflow as tf from common.tf2_layer_test_class import CommonTF2LayerTest class TestKerasActivityRegularization(CommonTF2LayerTest): def create_keras_activity_regularization_net(self, l1_param, l2_param, inp...
62
3,056
pyro
pyro/infer/inspect.py
.py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import itertools import os from collections import defaultdict from pathlib import Path from types import SimpleNamespace from typing import Callable, Collection, Dict, List, Optional, Union import torch import pyro import pyro.distr...
672
23,950
readthedocs.org
readthedocs/rtd_tests/tests/test_extend.py
.py
from django.test import TestCase, override_settings from readthedocs.core.utils.extend import SettingsOverrideObject, get_override_class # Top level to ensure module name is correct class FooBase: def bar(self): return 1 @classmethod def baz(cls): return 1 class NewFoo(FooBase): de...
103
2,927
dirty-equals
tests/test_boolean.py
.py
import platform import pytest from dirty_equals import IsFalseLike, IsTrueLike @pytest.mark.parametrize( 'other, expected', [ (False, IsFalseLike), (True, ~IsFalseLike), ([], IsFalseLike), ([1], ~IsFalseLike), ((), IsFalseLike), ('', IsFalseLike), ('',...
86
2,401
pyomo
pyomo/contrib/gjh/plugins.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...
21
895
mlflow
mlflow/utils/download_cloud_file_chunk.py
.py
""" This script should be executed in a fresh python interpreter process using `subprocess`. """ import argparse import importlib.util import json import os import sys def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--range-start", required=True, type=int) parser.add_argument("-...
44
1,241
beam
sdks/python/apache_beam/testing/benchmarks/nexmark/queries/query8.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...
74
2,834
readthedocs.org
readthedocs/builds/urls.py
.py
"""URL configuration for builds app.""" from django.urls import path from django.views.generic.base import RedirectView urlpatterns = [ path( "<slug:project_slug>/<int:build_pk>/", RedirectView.as_view(pattern_name="builds_detail", permanent=True), name="old_builds_detail", ), pat...
19
486
readthedocs.org
readthedocs/embed/views.py
.py
"""Views for the embed app.""" import structlog from rest_framework import status from rest_framework.permissions import AllowAny from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView from readthedocs.api.mixins import EmbedAPIMixin l...
30
900
readthedocs.org
readthedocs/projects/ordering.py
.py
"""Utilities to manage the position of items in a project.""" from django.db.models import F class ProjectItemPositionManager: def __init__(self, position_field_name): self.position_field_name = position_field_name def change_position_before_save(self, item): """ Re-order the positio...
141
6,363
beam
sdks/python/apache_beam/typehints/pandas_type_compatibility.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...
303
10,389
saleor
saleor/core/cleaners/__init__.py
.py
from .urls import ( URL_SCHEME_CLEANERS, URLCleanerError, clean_mailto, clean_tel, normalize_host, ) __all__ = ( "URL_SCHEME_CLEANERS", "URLCleanerError", "clean_tel", "clean_mailto", "normalize_host", )
16
245
onnxruntime
onnxruntime/test/python/onnxruntime_test_python_dmlgraph.py
.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import unittest import numpy as np from helper import get_name import onnxruntime as onnxrt class DmlGraphHelper: def __init__( self, ort_session: onnxrt.InferenceSession, input_and_output_shap...
185
8,006
onnxruntime
onnxruntime/python/tools/quantization/operators/conv.py
.py
import numpy as np import onnx from onnx import onnx_pb as onnx_proto from ..quant_utils import ( TENSOR_NAME_QUANT_SUFFIX, QuantizedValue, QuantizedValueType, attribute_to_kwarg, find_by_name, get_mul_node, ) from .base_operator import QuantOperatorBase from .qdq_base_operator import QDQOperat...
261
9,943
pyomo
pyomo/contrib/solver/common/base.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...
714
26,039
wandb
tests/unit_tests/test_wandb_agent_teardown.py
.py
"""Unit tests for agent teardown behavior. These tests verify that after wandb.agent() exits (normally or by exception), global state is cleared so a subsequent wandb.init() creates a normal run, not a sweep run. Open-source developers can use these to ensure changes around agent teardown do not break this functionali...
57
2,247
qutip
qutip/simdiag.py
.py
__all__ = ['simdiag'] import numpy as np import scipy.linalg as la from . import Qobj from .core import data as _data def _degen(tol, vecs, ops, i=0): """ Private function that finds eigen vals and vecs for degenerate matrices.. """ if len(ops) == i: return vecs # New eigenvectors are so...
135
4,334
onnxruntime
onnxruntime/python/tools/transformers/fusion_attention.py
.py
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -------------------------------------------------------------------------- from logging import getLogger import numpy as np from fusion_base impor...
1,199
50,927
django-cms
cms/models/fields.py
.py
from itertools import chain from django.contrib.contenttypes.fields import GenericRelation from django.db import models from cms.forms.fields import PageSelectFormField from cms.models.placeholdermodel import Placeholder class PageField(models.ForeignKey): """ This is a foreign key field to the :class:`cms....
103
3,691
jupytext
tests/external/round_trip/test_mirror_external.py
.py
import pytest from jupytext.compare import assert_conversion_same_as_mirror """--------------------------------------------------------------------------------- Part I: ipynb -> fmt -> ipynb ---------------------------------------------------------------------------------""" @pytest.mark.requires_pandoc def test_...
54
1,708
pyro
pyro/distributions/coalescent.py
.py
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import functools import weakref from collections import namedtuple import torch from torch.distributions import constraints from pyro.distributions.util import broadcast_shape, is_validation_enabled from pyro.ops.special import safe_...
527
20,914
black
tests/data/cases/context_managers_autodetect_39.py
.py
# This file uses parenthesized context managers introduced in Python 3.9. with \ make_context_manager1() as cm1, \ make_context_manager2() as cm2, \ make_context_manager3() as cm3, \ make_context_manager4() as cm4 \ : pass with ( new_new_new1() as cm1, new_new_new2() ): pass ...
35
623
wandb
wandb/apis/_generated/get_sweeps.py
.py
# Generated by ariadne-codegen # Source: tools/graphql_codegen/api/ from __future__ import annotations from pydantic import Field from wandb._pydantic import GQLResult from .fragments import PageInfoFragment, SweepFragment class GetSweeps(GQLResult): project: GetSweepsProject | None class GetSweepsProject(G...
35
786
beam
sdks/python/apache_beam/examples/snippets/transforms/elementwise/flatmap_tuple.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");...
65
1,828
probability
tensorflow_probability/python/optimizer/proximal_hessian_sparse.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...
571
25,566
cvxpy
cvxpy/atoms/elementwise/huber.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...
311
10,764
tqdm
tests/tests_tqdm.py
.py
# Advice: use repr(our_file.read()) to print the full output of tqdm # (else '\r' will replace the previous lines and you'll see only the latest. import csv import os import re import sys from contextlib import contextmanager from functools import wraps from warnings import catch_warnings, simplefilter from pytest imp...
1,986
67,858
ipython
tests/test_contexts.py
.py
"""Tests for IPython.utils.contexts.""" import pytest from IPython.utils.contexts import preserve_keys def test_preserve_keys_restores_existing_key(): d = {"a": 1, "b": 2} with preserve_keys(d, "a"): d["a"] = 99 assert d["a"] == 1 def test_preserve_keys_deletes_new_key(): d = {"a": 1} ...
73
1,677
pyomo
pyomo/contrib/mpc/data/series_data.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...
267
10,123
wandb
wandb/apis/public/__init__.py
.py
__all__ = ( "Api", "ArtifactCollection", "ArtifactCollections", "ProjectArtifactCollections", "ArtifactFiles", "Artifacts", "ArtifactType", "ArtifactTypes", "DownloadHistoryResult", "RunArtifacts", "Automations", # doc:exclude "File", "Files", "HistoryScan", # d...
92
2,488
saleor
saleor/account/tests/fixtures/__init__.py
.py
from .customer_type import * # noqa: F403 from .user import * # noqa: F403
3
77
gunicorn
tests/requests/valid/012.py
.py
# # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. request = { "method": "POST", "uri": uri("/chunked_w_trailing_headers"), "version": (1, 1), "headers": [ ("TRANSFER-ENCODING", "chunked") ], "body": b"hello world", "trailers": [...
18
391
readthedocs.org
readthedocs/subscriptions/products.py
.py
""" Read the Docs products. This module contains the dataclasses that represent the products available. The available products are defined in the ``RTD_PRODUCTS`` setting. """ import copy from dataclasses import dataclass from django.conf import settings from readthedocs.subscriptions.constants import FEATURE_TYPES...
156
5,463
coremltools
coremltools/optimize/torch/_utils/report_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 import logging as _logging from typing import Tuple, Type import torch from coremltools.optimize.to...
103
3,872
saleor
saleor/graphql/discount/tests/test_utils.py
.py
from decimal import Decimal import graphene import pytest from ....discount import PromotionType, RewardValueType from ....discount.models import Promotion, PromotionRule from ..mutations.utils import promotion_rule_should_be_marked_with_dirty_variants from ..utils import ( _predicate_to_snake_case, convert_m...
508
15,233