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 |
|---|---|---|---|---|---|
wagtail | wagtail/admin/urls/workflows.py | .py | from django.urls import path
from wagtail.admin.views import workflows
app_name = "wagtailadmin_workflows"
urlpatterns = [
path("list/", workflows.Index.as_view(), name="index"),
path(
"list/results/",
workflows.Index.as_view(results_only=True),
name="index_results",
),
path("a... | 59 | 2,163 |
sphinx | sphinx/domains/javascript.py | .py | """The JavaScript domain."""
from __future__ import annotations
import contextlib
from types import NoneType
from typing import TYPE_CHECKING
from docutils import nodes
from docutils.parsers.rst import directives
from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.domains import ... | 596 | 20,565 |
probability | tensorflow_probability/python/distributions/doublesided_maxwell.py | .py | # Copyright 2019 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... | 251 | 9,164 |
ipython | tests/fake_llm.py | .py | import asyncio
from time import sleep
try:
from jupyter_ai_magics.providers import BaseProvider
from langchain_community.llms import FakeListLLM
except ImportError:
class BaseProvider:
pass
class FakeListLLM:
pass
FIBONACCI = """\
def fib(n):
if n < 2: return n
return fib(n ... | 103 | 2,947 |
clearml | examples/reporting/matplotlib_automatic_reporting.py | .py | # ClearML - Example of Matplotlib and Seaborn integration and reporting
#
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from clearml import Task
# Connecting ClearML with the current process,
# from here on everything is logged automatically
task = Task.init(project_name='examples', task_nam... | 59 | 1,705 |
readthedocs.org | readthedocs/rtd_tests/utils.py | .py | """Utility functions for use in tests."""
import subprocess
import textwrap
from os import chdir, environ, mkdir
from os.path import abspath
from os.path import join as pjoin
from shutil import copytree
from tempfile import mkdtemp
import structlog
from django.contrib.auth.models import User
from django_dynamic_fixtu... | 248 | 6,825 |
saleor | saleor/tests/dummy_password_hasher.py | .py | from collections import OrderedDict
from django.contrib.auth.hashers import BasePasswordHasher
class DummyHasher(BasePasswordHasher):
"""Dummy password hasher used only for unit tests purpose.
Overwriting default Django password hasher significantly reduces the time
of test execution.
"""
algor... | 30 | 851 |
saleor | saleor/graphql/account/tests/mutations/staff/test_staff_update.py | .py | import json
from unittest.mock import MagicMock, patch
import graphene
import pytest
from django.core.files import File
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from ......account.error_codes import AccountErrorCode
from ......account.models import Group, User
from ......... | 655 | 21,301 |
textual | tests/test_gc.py | .py | import asyncio
import gc
import pytest
from textual.app import App, ComposeResult
from textual.containers import Vertical
from textual.widgets import Footer, Header, Label
def count_nodes() -> int:
"""Count number of references to DOMNodes."""
dom_nodes = [
obj
for obj in gc.get_objects()
... | 88 | 2,072 |
readthedocs.org | readthedocs/api/v2/client.py | .py | """Simple client to access our API with Slumber credentials."""
import requests
import structlog
from django.conf import settings
from rest_framework.renderers import JSONRenderer
from slumber import API
from slumber import serialize
from urllib3.util.retry import Retry
from .adapters import TimeoutHostHeaderSSLAdapt... | 67 | 2,011 |
saleor | saleor/tests/e2e/promotions/test_unable_to_have_promotion_rule_with_mixed_predicates.py | .py | import pytest
from ..product.utils import (
create_collection,
create_collection_channel_listing,
)
from ..shop.utils.preparing_shop import prepare_default_shop
from ..utils import assign_permissions
from .utils import create_promotion, raw_create_promotion, raw_update_promotion_rule
def prepare_collection(
... | 114 | 3,690 |
probability | tensorflow_probability/python/internal/backend/numpy/tensor_spec.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... | 42 | 1,309 |
textual | tests/layouts/test_content_dimensions.py | .py | import pytest
from textual.geometry import Size
from textual.layouts.grid import GridLayout
from textual.layouts.horizontal import HorizontalLayout
from textual.layouts.vertical import VerticalLayout
from textual.widget import Widget
LAYOUTS = [GridLayout, HorizontalLayout, VerticalLayout]
@pytest.mark.parametrize(... | 28 | 1,063 |
ipython | docs/sphinxext/configtraits.py | .py | """Directives and roles for documenting traitlets config options.
::
.. configtrait:: Application.log_datefmt
Description goes here.
Cross reference like this: :configtrait:`Application.log_datefmt`.
"""
def setup(app):
app.add_object_type("configtrait", "configtrait", objname="Config option")... | 17 | 414 |
onnx | onnx/reference/ops/op_not.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 OpRunUnary
class Not(OpRunUnary):
def _run(self, x):
return (np.logical_not(x),)
| 14 | 267 |
wandb | tests/unit_tests/test_public_api/test_history.py | .py | import json
from collections.abc import Callable
from types import SimpleNamespace
from wandb.apis.public.history import HistoryScan
from wandb.proto import wandb_api_pb2 as apb
class FakeServiceApi:
def __init__(self, pages):
self.pages = list(pages)
self.scan_ranges = []
def send_api_reque... | 77 | 2,253 |
saleor | saleor/account/tests/test_notifications.py | .py | from unittest import mock
from urllib.parse import urlencode
import pytest
from ...core.notify import NotifyEventType, UserNotifyEvent
from ...core.tests.utils import get_site_context_payload
from ...core.utils.url import prepare_url
from ...graphql.core.utils import to_global_id_or_none
from ...plugins.manager impor... | 151 | 5,047 |
kombu | kombu/transport/pyamqp.py | .py | """pyamqp transport module for Kombu.
Pure-Python amqp transport using py-amqp library.
Features
========
* Type: Native
* Supports Direct: Yes
* Supports Topic: Yes
* Supports Fanout: Yes
* Supports Priority: Yes
* Supports TTL: Yes
Connection String
=================
Connection string can have the following format... | 266 | 8,324 |
pyomo | doc/OnlineDocs/src/data/import2.tab.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 | 880 |
wagtail | wagtail/test/basepage/apps.py | .py | from django.apps import AppConfig
class BasepageConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "wagtail.test.basepage"
label = "basepage"
| 8 | 184 |
pynacl | tests/utils.py | .py | # Copyright 2013-2018 Donald Stufft and individual contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | 93 | 3,027 |
clearml | clearml/router/fastapi_proxy.py | .py | import functools
import threading
from multiprocessing import Process
from typing import Optional, Callable, Awaitable, AsyncGenerator, Union
import fastapi
import httpx
import uvicorn
from fastapi import FastAPI, Request, Response
from fastapi.responses import StreamingResponse
from starlette.middleware.base import B... | 265 | 10,008 |
saleor | saleor/graphql/shop/mutations/staff_notification_recipient_create.py | .py | import graphene
from django.core.exceptions import ValidationError
from ....account import models as account_models
from ....core.error_codes import ShopErrorCode
from ....permission.enums import SitePermissions
from ...account.types import StaffNotificationRecipient
from ...core.mutations import DeprecatedModelMutati... | 85 | 3,134 |
voila | tests/app/conftest.py | .py | import os
import pytest
import voila.app
BASE_DIR = os.path.dirname(__file__)
class VoilaTest(voila.app.Voila):
def listen(self):
pass # the ioloop is taken care of by the pytest-tornado framework
@pytest.fixture
def voila_config():
return lambda app: None
@pytest.fixture
def voila_args_extra(... | 85 | 1,994 |
python-prompt-toolkit | examples/full-screen/text-editor.py | .py | #!/usr/bin/env python
"""
A simple example of a Notepad-like text editor.
"""
import datetime
from asyncio import Future, ensure_future
from prompt_toolkit.application import Application
from prompt_toolkit.application.current import get_app
from prompt_toolkit.completion import PathCompleter
from prompt_toolkit.filt... | 382 | 9,177 |
openvino | tests/e2e_tests/config.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
from common import config
""" TT_PRODUCT_VERSION_SUFFIX - Environment version suffix provided by user"""
product_version_suffix = os.environ.get("TT_PRODUCT_VERSION_SUFFIX", "e2e_tests")
config.product_version_suffix = produc... | 15 | 523 |
probability | tensorflow_probability/python/optimizer/linesearch/__init__.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... | 26 | 966 |
readthedocs.org | readthedocs/search/tests/test_parsers.py | .py | import json
from contextlib import contextmanager
from pathlib import Path
from unittest import mock
import pytest
from django_dynamic_fixture import get
from readthedocs.builds.storage import BuildMediaFileSystemStorage
from readthedocs.projects.constants import GENERIC, MKDOCS, SPHINX
from readthedocs.projects.mode... | 385 | 14,255 |
openvino | tests/e2e_tests/common/comparator/provider.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import inspect
from e2e_tests.common.common.base_provider import BaseProvider
class ClassProvider(BaseProvider):
__step_name__ = "compare"
registry = {}
@classmethod
def validate(cls):
methods = [
f... | 21 | 623 |
astropy | astropy/visualization/tests/test_interval.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
import pytest
from numpy.testing import assert_allclose
from astropy.utils import NumpyRNGContext
from astropy.utils.masked import Masked
from astropy.visualization.interval import (
AsymmetricPercentileInterval,
ManualInterval... | 188 | 6,086 |
saleor | saleor/plugins/tests/test_manager.py | .py | import json
from decimal import Decimal
from functools import partial
from unittest import mock
from unittest.mock import patch
import pytest
from django.http import HttpResponseNotFound, JsonResponse
from django.test import override_settings
from prices import Money, TaxedMoney
from ...channel import TransactionFlow... | 1,627 | 52,804 |
saleor | saleor/graphql/core/tests/__init__.py | .py | from enum import Enum
import graphene
from ..types.common import Error
class ErrorCodeTest(Enum):
INVALID = "invalid"
ErrorCodeTest = graphene.Enum.from_enum(ErrorCodeTest)
class ErrorTest(Error):
code = ErrorCodeTest()
| 17 | 236 |
python-prompt-toolkit | tools/debug_vt100_input.py | .py | #!/usr/bin/env python
"""
Parse vt100 input and print keys.
For testing terminal input.
(This does not use the `Input` implementation, but only the `Vt100Parser`.)
"""
import sys
from prompt_toolkit.input.vt100 import raw_mode
from prompt_toolkit.input.vt100_parser import Vt100Parser
from prompt_toolkit.key_binding ... | 35 | 717 |
mlflow | mlflow/server/asgi_utils.py | .py | from __future__ import annotations
import os
from starlette.requests import Request as StarletteRequest
def get_routed_asgi_path(request: StarletteRequest) -> str:
"""Return the routed ASGI path for a FastAPI request.
Prefer ``request.scope["path"]`` because Starlette reconstructs
``request.url.path`` ... | 33 | 1,208 |
pyfilesystem2 | tests/test_walk.py | .py | from __future__ import unicode_literals
import six
import unittest
from fs import walk
from fs.errors import FSError
from fs.memoryfs import MemoryFS
from fs.wrap import read_only
class TestWalker(unittest.TestCase):
def setUp(self):
self.walker = walk.Walker()
def test_repr(self):
repr(sel... | 412 | 13,348 |
wandb | tests/unit_tests/test_wandb_agent/scripts/train_with_import_readline.py | .py | import sys
import wandb
# For use with test_pyagent.py::test_agent_subprocess_with_import_readline
def main() -> None:
with wandb.init() as run:
print("Importing readline...")
# `import readline` causes deadlock if parent launches subprocess using
# progress_group=0 without a pty
... | 40 | 976 |
saleor | saleor/graphql/tests/test_error.py | .py | from typing import Annotated
import pytest
from pydantic import BaseModel, Field, StringConstraints, field_validator
from pydantic import ValidationError as PydanticValidationError
from pydantic_core import PydanticCustomError
from ..error import pydantic_to_validation_error
class SampleModel(BaseModel):
name: ... | 122 | 3,608 |
saleor | saleor/tests/e2e/checkout/test_unlogged_customer_should_be_able_to_order_physical_product.py | .py | import pytest
from ..product.utils.preparing_product import prepare_product
from ..shop.utils.preparing_shop import prepare_default_shop
from ..utils import assign_permissions
from .utils import (
checkout_complete,
checkout_create,
checkout_delivery_method_update,
checkout_dummy_payment_create,
ch... | 106 | 3,056 |
pyro | tests/distributions/dist_fixture.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import math
import numpy as np
import torch
from torch.distributions.utils import logits_to_probs
from pyro.distributions.util import broadcast_shape
SINGLE_TEST_DATUM_IDX = [0]
BATCH_TEST_DATA_IDX = [-1]
class Fixture:
de... | 178 | 6,500 |
openvino | src/bindings/python/src/openvino/preprocess/torchvision/__init__.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
"""
Package: openvino
Torchvision to OpenVINO preprocess converter.
"""
# flake8: noqa
from openvino._pyopenvino import get_version as _get_version
__version__ = _get_version()
from .preprocess_converter import PreprocessConverter
| 16 | 318 |
beam | website/append_index_html_to_internal_links.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... | 128 | 4,461 |
django-cms | menus/models.py | .py | from django.db import models
class CacheKeyManager(models.Manager):
def get_keys(self, site_id=None, language=None):
"""
Get cache keys based on optional site ID and language.
Args:
site_id: The ID of the site (optional).
language: The language (optional).
... | 39 | 1,326 |
onnxruntime | onnxruntime/test/python/onnxruntime_test_python_symlink_data.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import shutil
import struct
import tempfile
import unittest
import numpy as np
from onnx import TensorProto, helper, save
import onnxruntime as ort
class TestSymLinkOnnxModelExternalData(unittest.TestCase):
... | 260 | 11,558 |
bazel | examples/py/lib.py | .py | def Fib(n):
if n == 0 or n == 1:
return 1
else:
return Fib(n-1) + Fib(n-2)
| 6 | 87 |
flit | flit_core/flit_core/common.py | .py | import ast
from contextlib import contextmanager
import hashlib
import logging
import os
import sys
from pathlib import Path
import re
log = logging.getLogger(__name__)
from .versionno import normalise_version
class Module:
"""This represents the module/package that we are going to distribute
"""
in_nam... | 510 | 16,717 |
openvino | src/bindings/python/src/openvino/opset15/__init__.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# New operations added in Opset15
from openvino.opset15.ops import col2im
from openvino.opset15.ops import embedding_bag_offsets
from openvino.opset15.ops import embedding_bag_packed
from openvino.opset15.ops impo... | 205 | 8,727 |
black | tests/data/cases/context_managers_autodetect_38.py | .py | # This file doesn't use any Python 3.9+ only grammars.
# Make sure parens around a single context manager don't get autodetected as
# Python 3.9+.
with (a):
pass
with \
make_context_manager1() as cm1, \
make_context_manager2() as cm2, \
make_context_manager3() as cm3, \
make_context_manager4... | 47 | 1,058 |
saleor | saleor/graphql/shipping/mutations/shipping_price_exclude_products.py | .py | import graphene
from ....permission.enums import ShippingPermissions
from ....product import models as product_models
from ....shipping import models
from ...core import ResolveInfo
from ...core.context import ChannelContext
from ...core.doc_category import DOC_CATEGORY_SHIPPING
from ...core.mutations import BaseMutat... | 73 | 2,532 |
probability | discussion/adaptive_malt/grid_search_runner_experiments.py | .py | # Copyright 2022 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... | 488 | 16,330 |
hydra | plugins/hydra_joblib_launcher/tests/apps/multiprocessing_app.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import os
from functools import wraps
from pathlib import Path
from types import ModuleType
from typing import Any, Callable, NoReturn
import hydra
from hydra.core.hydra_config import HydraConfig
from omegaconf import DictConfig, OmegaConf
class ... | 51 | 1,371 |
pyro | pyro/poutine/handlers.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
"""
Poutine is a library of composable effect handlers for recording and modifying the
behavior of Pyro programs. These lower-level ingredients simplify the implementation
of new inference algorithms and behavior.
Handlers can be ... | 678 | 18,457 |
mlflow | mlflow/store/tracking/rest_store.py | .py | import functools
import json
import logging
from typing import TYPE_CHECKING, Any
from mlflow.entities.model_registry.prompt_version import PromptVersion
if TYPE_CHECKING:
from mlflow.entities import DatasetRecord, EvaluationDataset
from mlflow.genai.scorers.online.entities import OnlineScoringConfig
from op... | 2,495 | 93,489 |
conda | conda/core/link.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Package installation implemented as a series of link/unlink transactions."""
from __future__ import annotations # noqa: I001
from dataclasses import dataclass, fields
import itertools
import os
import sys
import warnings
from collections i... | 1,747 | 66,758 |
readthedocs.org | readthedocs/domains/tasks.py | .py | """Tasks related to custom domains."""
from django.conf import settings
from django.urls import reverse
from django.utils import timezone
from readthedocs.core.permissions import AdminPermission
from readthedocs.domains.notifications import MESSAGE_DOMAIN_VALIDATION_PENDING
from readthedocs.domains.notifications impo... | 54 | 1,988 |
lemur | lemur/plugins/lemur_gcs/__init__.py | .py | try:
VERSION = __import__("pkg_resources").get_distribution(__name__).version
except Exception as e:
VERSION = "unknown"
| 5 | 129 |
biopython | Bio/SearchIO/BlastIO/blast_tab.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 pars... | 896 | 33,824 |
wandb | wandb/_pydantic/base.py | .py | """Base classes and other customizations for generated pydantic types."""
from __future__ import annotations
from abc import ABC
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, ClassVar, Literal, overload
from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_... | 147 | 5,542 |
pyomo | pyomo/dataportal/factory.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... | 49 | 1,601 |
beam | sdks/python/apache_beam/runners/worker/statecache.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... | 371 | 12,286 |
coremltools | coremltools/converters/mil/mil/ops/defs/iOS17/elementwise_unary.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
from coremltools.converters.mil.mil import types
from coremltools.converters.mil.mil.input_type impo... | 203 | 6,178 |
onnx | onnx/backend/test/case/node/sum.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
class Sum(Base):
@staticmethod
def export() -> None:
data_0 ... | 48 | 1,345 |
bazel | tools/build_defs/proguard/wrapper.py | .py | # Copyright 2026 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... | 155 | 4,665 |
wagtail | wagtail/management/commands/rebuild_references_index.py | .py | from django.apps import apps
from django.core.management.base import BaseCommand
from django.db import transaction
from wagtail.models import ReferenceIndex
from wagtail.signal_handlers import disable_reference_index_auto_update
DEFAULT_CHUNK_SIZE = 1000
class Command(BaseCommand):
def write(self, *args, **kwar... | 107 | 3,437 |
python-dotenv | tests/test_fifo_dotenv.py | .py | import os
import pathlib
import sys
import threading
import pytest
from dotenv import load_dotenv
pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="FIFOs are Unix-only")
def test_load_dotenv_from_fifo(tmp_path: pathlib.Path, monkeypatch):
fifo = tmp_path / ".env"
os.mkfifo(fifo) # create na... | 32 | 743 |
mlflow | mlflow/genai/judges/adapters/databricks_managed_judge_adapter.py | .py | from __future__ import annotations
import inspect
import json
import logging
from typing import TYPE_CHECKING, Any, Callable, TypeVar
if TYPE_CHECKING:
from mlflow.entities.trace import Trace
from mlflow.types.llm import ChatMessage, ToolDefinition
T = TypeVar("T") # Generic type for agentic loop return val... | 393 | 13,539 |
pymc | pymc/distributions/transforms.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... | 735 | 25,057 |
deap | doc/code/benchmarks/griewank.py | .py | from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
try:
import numpy as np
except:
exit()
from deap import benchmarks
def griewank_arg0(sol):
return benchmarks.griewank(sol)[0]
fig = plt.figure()
ax = Axes3D(fig, azim = -29, elev = 40)
# ax = Axes3D(fig)
X ... | 28 | 634 |
pyro | pyro/contrib/bnn/__init__.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
from pyro.contrib.bnn.hidden_layer import HiddenLayer
__all__ = [
"HiddenLayer",
]
| 9 | 177 |
ipython | IPython/utils/openpy.py | .py | """
Tools to open .py files as Unicode, using the encoding specified within the file,
as per PEP 263.
Much of the code is taken from the tokenize module in Python 3.2.
"""
from __future__ import annotations
import io
from collections.abc import Generator, Iterable
from io import TextIOWrapper, BytesIO
from pathlib im... | 107 | 3,605 |
biopython | Bio/phenotype/phen_micro.py | .py | # Copyright 2014-2016 by Marco Galardini. 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 to work... | 1,210 | 37,710 |
confluent-kafka-python | tests/integration/schema_registry/_sync/test_avro_serializers.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2020 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... | 362 | 11,730 |
python-prompt-toolkit | examples/full-screen/scrollable-panes/simple-example.py | .py | #!/usr/bin/env python
"""
A simple example of a scrollable pane.
"""
from prompt_toolkit.application import Application
from prompt_toolkit.application.current import get_app
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.key_binding.bindings.focus import focus_next, focus_previous
from prompt_... | 47 | 1,276 |
python-prompt-toolkit | examples/dialogs/styled_messagebox.py | .py | #!/usr/bin/env python
"""
Example of a style dialog window.
All dialog shortcuts take a `style` argument in order to apply a custom
styling.
This also demonstrates that the `title` argument can be any kind of formatted
text.
"""
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.shortcuts import messa... | 39 | 932 |
coremltools | coremltools/optimize/torch/_utils/graph_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 operator as _operator
from typing import Any as _Any
from typing import Dict as _Dict
from typ... | 558 | 23,075 |
returns | returns/contrib/hypothesis/containers.py | .py | from __future__ import annotations
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, TypeVar
from hypothesis import strategies as st
if TYPE_CHECKING:
from returns.primitives.laws import Lawful
def strategy_from_container(
container_type: type[Lawful],
*,
use_init: bool = ... | 76 | 2,429 |
scikit-bio | skbio/sequence/transition.py | .py | r"""Transition probability models (:mod:`skbio.sequence.tpm`)
==========================================================
.. currentmodule:: skbio.sequence.transition
This module provides functions for calculating transition probability
matrices (TPMs) under several substitution models for a specified
evolutionary dis... | 693 | 20,733 |
sqlmap | plugins/generic/custom.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from __future__ import print_function
import re
import sys
from lib.core.common import Backend
from lib.core.common import dataToStdout
from lib.core.common import getSQLSnippet... | 160 | 5,404 |
readthedocs.org | readthedocs/embed/v3/tests/test_external_pages.py | .py | from unittest import mock
import docutils
import pytest
import sphinx
from django.core.cache import cache
from django.urls import reverse
from packaging.version import Version
from .utils import compare_content_without_blank_lines, get_anchor_link_title, srcdir
@pytest.mark.django_db
@pytest.mark.embed_api
class Te... | 377 | 19,987 |
jupytext | tests/unit/test_header.py | .py | from nbformat.v4.nbbase import new_markdown_cell, new_notebook, new_raw_cell
import jupytext
from jupytext.compare import compare
from jupytext.formats import get_format_implementation
from jupytext.header import (
header_to_metadata_and_cell,
metadata_and_cell_to_header,
recursive_update,
uncomment_li... | 206 | 5,200 |
coveragepy | coverage/bytecode.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
"""Bytecode analysis for coverage.py"""
from __future__ import annotations
import dis
from collections.abc import Iterable, Mapping
from types import CodeType
... | 209 | 7,378 |
saleor | saleor/graphql/product/tests/deprecated/test_product_variant_bulk_create.py | .py | import datetime
from unittest.mock import ANY, patch
from uuid import uuid4
import graphene
from .....attribute import AttributeInputType
from .....product.error_codes import ProductVariantBulkErrorCode
from .....product.models import ProductChannelListing, ProductVariant
from ....tests.utils import get_graphql_conte... | 1,085 | 40,799 |
wagtail | wagtail/users/permission_order.py | .py | from django.contrib.contenttypes.models import ContentType
from wagtail.coreutils import resolve_model_string
content_types_to_register = []
CONTENT_TYPE_ORDER = {}
def register(model, **kwargs):
"""
Registers order against the model content_type, used to
control the order the models and its permissions... | 32 | 1,130 |
clearml | examples/cicd/compare_models.py | .py | import os
from clearml import Task
from task_stats_to_comment import get_clearml_task_of_current_commit
def compare_and_tag_task(commit_hash):
"""Compare current performance to best previous performance and only allow equal or better."""
current_task = get_clearml_task_of_current_commit(commit_hash)
best... | 31 | 1,286 |
confluent-kafka-python | tools/wheels/install-macos-python-required-by-cibuildwheel.py | .py | #!/usr/bin/env python3
#
#
# Get python versions required for cibuildwheel from their config and
# install them. This implementation is based on cibuildwheel 3.2.1
# version. Might need tweak if something changes in cibuildwheel.
#
# This was added as there is a permission issue when cibuildwheel
# tries to install the... | 74 | 2,483 |
wandb | wandb/sdk/launch/builder/abstract.py | .py | """Abstract plugin class defining the interface needed to build container images for W&B Launch."""
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any
from wandb.sdk.launch.environment.abstract import AbstractEnvironment
from wandb.sdk.launch.registry.abstrac... | 159 | 5,089 |
wagtail | wagtail/images/templatetags/wagtailimages_tags.py | .py | from django import template
from django.core.exceptions import ImproperlyConfigured
from django.urls import NoReverseMatch
from wagtail.images.models import Filter, Picture, ResponsiveImage
from wagtail.images.shortcuts import (
get_rendition_or_not_found,
get_renditions_or_not_found,
)
from wagtail.images.vie... | 221 | 7,128 |
saleor | saleor/graphql/shop/mutations/return_reason_reference_type_clear.py | .py | import graphene
from ....permission.enums import SitePermissions
from ...core import ResolveInfo
from ...core.descriptions import ADDED_IN_323
from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.mutations import BaseMutation
from ...core.types.common import ReturnReasonReferenceTypeClearError
from ...sit... | 38 | 1,438 |
jupytext | tests/unit/test_markdown_in_code_cells.py | .py | """Issue #712"""
import pytest
from nbformat.v4.nbbase import new_code_cell, new_notebook
from jupytext import reads, writes
from jupytext.cell_to_text import three_backticks_or_more
from jupytext.compare import compare, compare_notebooks
def test_three_backticks_or_more():
assert three_backticks_or_more([""]) ... | 125 | 2,305 |
black | scripts/release.py | .py | #!/usr/bin/env python3
"""
Tool to help automate changes needed in commits during and after releases
"""
from __future__ import annotations
import argparse
import logging
import re
import sys
from datetime import datetime
from pathlib import Path
from subprocess import run
LOG = logging.getLogger(__name__)
NEW_VERS... | 249 | 7,654 |
beam | sdks/python/apache_beam/io/gcp/bigquery_read_it_test.py | .py | #!/usr/bin/env python
# -*- 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,... | 850 | 30,206 |
onnxruntime | onnxruntime/test/testdata/ort_github_issue_26272.py | .py | import onnx
from onnx import TensorProto, helper
# Create a simple ONNX model with DDS output
input = helper.make_tensor_value_info("data", TensorProto.FLOAT, ["d1", "d2"])
output = helper.make_tensor_value_info("output", TensorProto.FLOAT, ["nzr"])
nonzeros_node = helper.make_node("NonZero", ["data"], ["nonzeros"], ... | 27 | 946 |
openvino | tests/layer_tests/tensorflow_tests/test_tf_Conv3D.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from common.tf_layer_test_class import CommonTFLayerTest
# Testing operation Conv3D
# Documentation: https://www.tensorflow.org/api_docs/python/tf/raw_ops/Conv3D
class TestConv3D(CommonTFLayerTest):
# input_shape - ... | 82 | 3,778 |
funcy | funcy/debug.py | .py | import re
import traceback
from itertools import chain
from functools import partial
from timeit import default_timer as timer
from .decorators import decorator, wraps, Call
__all__ = [
'tap',
'log_calls', 'print_calls',
'log_enters', 'print_enters',
'log_exits', 'print_exits',
'log_errors', 'pri... | 244 | 7,675 |
confluent-kafka-python | tests/integration/consumer/test_consumer_upgrade_downgrade.py | .py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2025 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... | 128 | 4,835 |
probability | tensorflow_probability/python/glm/__init__.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... | 66 | 2,901 |
textual | src/textual/highlight.py | .py | from __future__ import annotations
import os
from typing import Tuple
from pygments.lexer import Lexer
from pygments.lexers import get_lexer_by_name, guess_lexer_for_filename
from pygments.token import Token
from pygments.util import ClassNotFound
from textual.content import Content, Span
TokenType = Tuple[str, ...... | 239 | 7,952 |
sphinx | tests/test_ext_autodoc/test_ext_autodoc_private_members.py | .py | """Test the autodoc extension. This tests mainly for private-members option."""
from __future__ import annotations
import pytest
from sphinx.ext.autodoc._shared import _AutodocConfig
from tests.test_ext_autodoc.autodoc_util import do_autodoc
pytestmark = pytest.mark.usefixtures('inject_autodoc_root_into_sys_path'... | 165 | 4,507 |
onnx | onnx/reference/ops_optimized/op_conv_optimized.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 _make_ind(dim, shape):
m = np.empty(shape, dtype=np.int64)
ind = [slice(0, shape[i]) for i in range(len(shape))]
new_shape = ... | 190 | 6,398 |
readthedocs.org | readthedocs/notifications/querysets.py | .py | from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils import timezone
from readthedocs.core.permissions import AdminPermission
from readthedocs.core.querysets import NoReprQuerySet
from .constants import CANCELLED
from .co... | 158 | 6,029 |
hydra | examples/patterns/specializing_config/example.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
import sys
from omegaconf import DictConfig, OmegaConf
import hydra
log = logging.getLogger(__name__)
@hydra.main(config_path="conf", config_name="config")
def experiment(cfg: DictConfig) -> None:
print(OmegaConf.to_yaml(cfg)... | 19 | 378 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.