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 |
|---|---|---|---|---|---|
loguru | tests/exceptions/source/ownership/decorated_callback.py | .py | import sys
import _init
from somelib import callme, divide
from loguru import logger
def test(*, backtrace, colorize, diagnose):
logger.remove()
logger.add(sys.stderr, format="", colorize=colorize, backtrace=backtrace, diagnose=diagnose)
@logger.catch
def callback():
a, b = 1, 0
a /... | 26 | 609 |
python-prompt-toolkit | src/prompt_toolkit/lexers/base.py | .py | """
Base classes for prompt_toolkit lexers.
"""
from __future__ import annotations
from abc import ABCMeta, abstractmethod
from collections.abc import Callable, Hashable
from prompt_toolkit.document import Document
from prompt_toolkit.formatted_text.base import StyleAndTextTuples
__all__ = [
"Lexer",
"Simpl... | 86 | 2,359 |
beam | sdks/python/apache_beam/transforms/create_source.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... | 91 | 3,407 |
mkdocs | mkdocs/localization.py | .py | from __future__ import annotations
import logging
import os
from typing import TYPE_CHECKING, Sequence
from jinja2.ext import Extension, InternationalizationExtension
from mkdocs.config.base import ValidationError
if TYPE_CHECKING:
import jinja2
try:
from babel.core import Locale, UnknownLocaleError
fr... | 93 | 3,049 |
saleor | saleor/order/webhooks/exclude_shipping.py | .py | import json
import logging
from typing import TYPE_CHECKING, Union
from promise import Promise
from ...core.db.connection import allow_writer
from ...core.prices import quantize_price
from ...core.utils.json_serializer import CustomJsonEncoder
from ...shipping.interface import ExcludedShippingMethod, ShippingMethodDa... | 130 | 4,120 |
sphinx | sphinx/cmd/make_mode.py | .py | """sphinx-build -M command-line handling.
This replaces the old, platform-dependent and once-generated content
of Makefile / make.bat.
This is in its own module so that importing it is fast. It should not
import the main Sphinx modules (like sphinx.applications, sphinx.builders).
"""
from __future__ import annotati... | 224 | 8,482 |
coremltools | coremltools/proto/CustomModel_pb2.py | .py | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: CustomModel.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _message
from ... | 60 | 3,174 |
saleor | saleor/graphql/product/tests/queries/variants_where/test_over_references_collections.py | .py | import pytest
from ......attribute import AttributeEntityType, AttributeInputType, AttributeType
from ......attribute.models import Attribute, AttributeValue
from ......attribute.utils import associate_attribute_values_to_instance
from .....core.utils import to_global_id_or_none
from .....tests.utils import get_graphq... | 300 | 10,128 |
pdm | src/pdm/project/workspace.py | .py | from __future__ import annotations
import hashlib
from collections.abc import Collection, Iterable
from functools import cached_property
from pathlib import Path
from typing import TYPE_CHECKING
import tomlkit
from pdm.exceptions import PdmUsageError
from pdm.models.requirements import Requirement, parse_requirement... | 177 | 7,339 |
mlflow | mlflow/gateway/providers/openai.py | .py | import json
import os
import warnings
from typing import TYPE_CHECKING, Any, AsyncIterable
from urllib.parse import urlparse, urlunparse
from mlflow.environment_variables import MLFLOW_ENABLE_UC_FUNCTIONS
from mlflow.exceptions import MlflowException
from mlflow.gateway.config import EndpointConfig, OpenAIAPIType, Ope... | 676 | 26,250 |
mlflow | mlflow/llama_index/pyfunc_wrapper.py | .py | import asyncio
import threading
import uuid
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from llama_index.core import QueryBundle
from mlflow.models.utils import _convert_llm_input_data
CHAT_ENGINE_NAME = "chat"
QUERY_ENGINE_NAME = "query"
RETRIEVER_ENGINE_NAME = "retriever"
SUPPORTED_ENGINES = {CHAT_... | 331 | 12,676 |
mlflow | tests/genai/discovery/test_clustering.py | .py | import json
from unittest.mock import MagicMock, patch
from mlflow.entities.issue import IssueSeverity, IssueStatus
from mlflow.genai.discovery.clustering import (
cluster_by_llm,
summarize_cluster,
)
from mlflow.genai.discovery.constants import build_cluster_summary_prompt
from mlflow.genai.discovery.entities... | 194 | 5,985 |
probability | tensorflow_probability/python/optimizer/bfgs_utils.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... | 410 | 17,130 |
mlflow | tests/statsmodels/test_statsmodels_autolog.py | .py | from unittest import mock
import numpy as np
import pytest
from statsmodels.tsa.base.tsa_model import TimeSeriesModel
import mlflow
import mlflow.statsmodels
from mlflow import MlflowClient
from tests.statsmodels.model_fixtures import (
arma_model,
failing_logit_model,
gee_model,
glm_model,
gls_m... | 239 | 7,735 |
textual | docs/examples/how-to/containers04.py | .py | from textual.app import App, ComposeResult
from textual.containers import Horizontal
from textual.widgets import Placeholder
class Box(Placeholder):
"""Example widget."""
DEFAULT_CSS = """
Box {
width: 16;
height: 8;
}
"""
class ContainerApp(App):
"""Simple app to pl... | 40 | 769 |
mlflow | mlflow/tracking/context/system_environment_context.py | .py | import json
from mlflow.environment_variables import MLFLOW_RUN_CONTEXT
from mlflow.tracking.context.abstract_context import RunContextProvider
# The constant MLFLOW_RUN_CONTEXT_ENV_VAR is marked as @developer_stable
MLFLOW_RUN_CONTEXT_ENV_VAR = MLFLOW_RUN_CONTEXT.name
class SystemEnvironmentContext(RunContextProvi... | 16 | 467 |
onnxruntime | orttraining/orttraining/test/python/orttraining_test_ort_pipeline_module.py | .py | import argparse
import deepspeed
import torch
from deepspeed.pipe import LayerSpec
from torch import nn, utils
from onnxruntime.training.ortmodule.experimental.pipe import ORTPipelineModule
# This script demonstrates how to set up a pipeline parallel training session
# using DeepSpeed's ORTPipelineModule for a simpl... | 135 | 4,645 |
hydra | tools/configen/tests/test_modules/default_flags/noflags.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Generated by configen, do not edit.
# See https://github.com/hydra-ecosystem/hydra/tree/main/tools/configen
# fmt: off
# isort:skip_file
# flake8: noqa
from dataclasses import dataclass, field
@dataclass
class EmptyConf:
_target_: str = "te... | 14 | 344 |
mlflow | mlflow/dspy/load.py | .py | import inspect
import json
import logging
import os
import cloudpickle
from mlflow.dspy.save import (
_DSPY_SETTINGS_FILE_NAME,
_MODEL_CONFIG_FILE_NAME,
_MODEL_DATA_PATH,
)
from mlflow.dspy.wrapper import DspyChatModelWrapper, DspyModelWrapper
from mlflow.environment_variables import MLFLOW_ALLOW_PICKLE_D... | 162 | 6,374 |
conda | conda/plugins/subcommands/doctor/health_checks/file_locking.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Health check: File locking support."""
from __future__ import annotations
from typing import TYPE_CHECKING
from .....base.constants import OK_MARK, X_MARK
from .....base.context import context
from .....gateways.disk.lock import locking_su... | 40 | 1,202 |
python-prompt-toolkit | src/prompt_toolkit/key_binding/bindings/page_navigation.py | .py | """
Key bindings for extra page navigation: bindings for up/down scrolling through
long pages, like in Emacs or Vi.
"""
from __future__ import annotations
from prompt_toolkit.filters import buffer_has_focus, emacs_mode, vi_mode
from prompt_toolkit.key_binding.key_bindings import (
ConditionalKeyBindings,
KeyB... | 86 | 2,392 |
python-prompt-toolkit | src/prompt_toolkit/enums.py | .py | from __future__ import annotations
from enum import Enum
class EditingMode(Enum):
# The set of key bindings that is active.
VI = "VI"
EMACS = "EMACS"
#: Name of the search buffer.
SEARCH_BUFFER = "SEARCH_BUFFER"
#: Name of the default buffer.
DEFAULT_BUFFER = "DEFAULT_BUFFER"
#: Name of the system bu... | 20 | 358 |
deap | doc/conf.py | .py | # -*- coding: utf-8 -*-
#
# DEAP documentation build configuration file, created by
# sphinx-quickstart on Sat Jan 30 13:21:43 2010.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All co... | 254 | 8,400 |
beam | sdks/python/apache_beam/examples/snippets/transforms/aggregation/max_test.py | .py | # coding=utf-8
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License");... | 65 | 1,996 |
sqlmap | thirdparty/chardet/chardistribution.py | .py | ######################## BEGIN LICENSE BLOCK ########################
# The Original Code is Mozilla Communicator client code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights R... | 234 | 9,411 |
pymc | pymc/step_methods/hmc/base_hmc.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... | 303 | 10,589 |
openvino | src/bindings/python/tests/test_runtime/test_properties.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import numpy as np
import os
from pathlib import Path
import openvino as ov
import openvino.properties as props
import openvino.properties.hint as hints
import openvino.properties.intel_cpu as intel... | 754 | 25,529 |
saleor | saleor/giftcard/const.py | .py | GIFT_CARD_PAYMENT_GATEWAY_ID = "saleor.io.gift-card-payment-gateway"
GIFT_CARD_PAYMENT_GATEWAY_NAME = "Gift Card Payment Gateway"
SALEOR_GIFT_CARD_PAYMENT_METHOD_NAME = "Saleor Gift Card"
SALEOR_GIFT_CARD_BRAND = "Saleor"
| 5 | 222 |
openvino | src/bindings/python/src/openvino/frontend/pytorch/torchdynamo/decompositions.py | .py | # -*- coding: utf-8 -*-
# Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# mypy: ignore-errors
import torch
from torch._decomp.decompositions import aten, pw_cast_for_opmath
from torch._decomp import register_decomposition, get_decompositions
@register_decomposition(aten.convolution... | 390 | 13,216 |
sphinx | tests/test_ext_autodoc/test_ext_autodoc_typehints.py | .py | """Test the autodoc extension."""
from __future__ import annotations
from contextlib import contextmanager
from typing import TYPE_CHECKING
import pytest
from sphinx.ext.autodoc._shared import _AutodocConfig
from sphinx.testing import restructuredtext
from tests.test_ext_autodoc.autodoc_util import do_autodoc
if ... | 843 | 25,064 |
textual | tests/tree/test_tree_cursor.py | .py | from __future__ import annotations
from typing import Any
from textual import on
from textual.app import App, ComposeResult
from textual.widgets import Tree
from textual.widgets.tree import NodeID, TreeNode
class TreeApp(App[None]):
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__... | 103 | 3,614 |
pynacl | tests/test_exc.py | .py | # Copyright 2013 Donald Stufft and individual contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | 53 | 1,415 |
mlflow | mlflow/protos/databricks_artifacts_pb2.py | .py |
import google.protobuf
from packaging.version import Version
if Version(google.protobuf.__version__).major >= 5:
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: databricks_artifacts.proto
# Protobuf Python Version: 5.26.0
"""Generated protocol buffer code."""
fr... | 490 | 47,378 |
onnx | onnx/backend/test/case/node/ai_onnx_ml/array_feature_extractor.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 ArrayFeatureExtractor(Base):
@staticmethod
def export() -> None... | 32 | 826 |
saleor | saleor/order/tests/fixtures/order.py | .py | import datetime
from datetime import timedelta
from decimal import Decimal
import graphene
import pytest
from django.utils import timezone
from freezegun import freeze_time
from prices import Money, TaxedMoney
from ....checkout.utils import get_prices_of_discounted_specific_product
from ....core import JobStatus
from... | 1,157 | 38,538 |
pyomo | pyomo/common/tests/test_config.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... | 3,937 | 141,159 |
astropy | astropy/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 astropy test suite
from the installed astropy. It makes use of the |pytest| testing framework.
"""
import os
import pickle
import sys
import pytest
from astropy.units import allclose as quan... | 151 | 5,183 |
wandb | wandb/sdk/launch/builder/docker_builder.py | .py | """Implementation of the docker builder."""
from __future__ import annotations
import logging
import os
from typing import Any
import wandb
import wandb.docker as docker
from wandb.sdk.launch.agent.job_status_tracker import JobAndRunStatusTracker
from wandb.sdk.launch.builder.abstract import AbstractBuilder, registr... | 180 | 6,331 |
onnxruntime | onnxruntime/python/tools/quantization/onnx_quantizer.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 log... | 1,175 | 49,827 |
deap | examples/pso/basic_numpy.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 ... | 91 | 3,160 |
saleor | saleor/core/utils/tests/test_serializer.py | .py | import json
from measurement.measures import Weight
from ...taxes import zero_money
from ..json_serializer import CustomJsonEncoder
def test_custom_json_encoder_dumps_money_objects():
# given
currency = "usd"
input = {"money": zero_money(currency)}
# when
serialized_data = json.dumps(input, cls... | 34 | 795 |
coremltools | coremltools/test/optimize/torch/pruning/test_pruning_scheduler.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 sys
import pytest
import torch
from coremltools.optimize.torch.pruning import (
Constant... | 88 | 3,421 |
coremltools | coremltools/converters/sklearn/_random_forest_regressor.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
from ..._deps import _HAS_SKLEARN
from ...models import MLModel as _MLModel
from ._tree_ensemble import ... | 59 | 1,710 |
beam | sdks/python/apache_beam/ml/inference/utils_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... | 104 | 3,536 |
mlflow | tests/server/test_security_integration.py | .py | import json
import pytest
from werkzeug.test import Client
@pytest.mark.parametrize(
("host", "origin", "expected_status", "should_block"),
[
("evil.attacker.com:5000", "http://evil.attacker.com:5000", 403, True),
("localhost:5000", None, None, False),
],
)
def test_dns_rebinding_and_cors... | 124 | 3,973 |
mlflow | tests/gateway/test_cli.py | .py | import pytest
from click.testing import CliRunner
from mlflow.gateway import cli as gateway_cli
from mlflow.gateway.cli import start
def test_start_help():
runner = CliRunner()
res = runner.invoke(
start,
["--help"],
catch_exceptions=False,
)
assert res.exit_code == 0
def te... | 71 | 1,831 |
mlflow | tests/utils/test_time.py | .py | import time
from mlflow.utils.time import Timer
def test_timer():
with Timer() as t:
time.sleep(0.1)
assert f"{t}" == f"{t.elapsed}"
assert f"{t:.3f}" == f"{t.elapsed:.3f}"
| 12 | 197 |
onnxruntime | onnxruntime/python/tools/transformers/models/gpt2/gpt2_tester.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# This s... | 502 | 19,570 |
funcy | tests/test_interface.py | .py | import funcy
def test_docs():
exports = [(name, getattr(funcy, name)) for name in funcy.__all__
if name not in ('print_errors', 'print_durations', 'ErrorRateExceeded')
and getattr(funcy, name).__module__ not in ('funcy.types', 'funcy.primitives')]
# NOTE: we are testing thi... | 11 | 543 |
pyomo | examples/pyomobook/gdp-ch/scont_script.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... | 27 | 828 |
clearml | clearml/router/route.py | .py | import inspect
from typing import Optional, Callable, Dict, Any
from .endpoint_telemetry import EndpointTelemetry
class Route:
def __init__(
self,
target_url: str,
request_callback: Optional[Callable[[Any, Dict[str, Any]], Any]] = None,
response_callback: Optional[Callable[[Any, A... | 103 | 3,888 |
beam | playground/infrastructure/test_verify.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 ... | 89 | 3,188 |
voila | tests/app/image_inlining_test.py | .py | # tests the --template argument of voila
import base64
import os
import pytest
NOTEBOOK_PATH = "images.ipynb"
@pytest.fixture
def voila_notebook(notebook_directory):
return os.path.join(notebook_directory, NOTEBOOK_PATH)
async def test_image_inlining(http_server_client, base_url, notebook_directory):
resp... | 29 | 803 |
onnxruntime | onnxruntime/test/python/transformers/dit_model_generator.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Synt... | 222 | 9,584 |
pynacl | src/nacl/pwhash/scrypt.py | .py | # Copyright 2013 Donald Stufft and individual contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | 210 | 6,958 |
biopython | Bio/SearchIO/ExonerateIO/exonerate_text.py | .py | # Copyright 2012 by Wibowo Arindrarto. All rights reserved.
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Bio.SearchIO parser ... | 535 | 20,463 |
astropy | astropy/io/ascii/daophot.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
An extensible ASCII table reader and writer.
Classes to read DAOphot table format
:Copyright: Smithsonian Astrophysical Observatory (2011)
:Author: Tom Aldcroft (aldcroft@head.cfa.harvard.edu)
"""
import itertools as itt
import re
from collections i... | 395 | 14,751 |
omegaconf | tests/structured_conf/data/dataclasses.py | .py | import dataclasses
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional, Tuple, Union, cast
from pytest import importorskip
from omegaconf import II, MISSING, SI
from tests import Color, Enum1
if sys.version_info >= (3, 8): # pragma: no c... | 944 | 23,625 |
httpie | httpie/output/formatters/headers.py | .py | from ...plugins import FormatterPlugin
class HeadersFormatter(FormatterPlugin):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.enabled = self.format_options['headers']['sort']
def format_headers(self, headers: str) -> str:
"""
Sorts headers by name while retain... | 19 | 552 |
beam | sdks/python/apache_beam/ml/rag/ingestion/spanner.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 ... | 645 | 21,650 |
probability | tensorflow_probability/python/vi/csiszar_divergence.py | .py | # Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | 1,302 | 44,926 |
kafka | tests/kafkatest/sanity_checks/test_console_share_consumer.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 ... | 71 | 3,437 |
mlflow | mlflow/anthropic/chat.py | .py | import json
from typing import Any
from pydantic import BaseModel
from mlflow.exceptions import MlflowException
from mlflow.types.chat import (
ChatMessage,
ChatTool,
Function,
FunctionToolDefinition,
ImageContentPart,
ImageUrl,
TextContentPart,
ToolCall,
)
def convert_message_to_mlf... | 138 | 5,256 |
pyomo | pyomo/solvers/tests/__init__.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... | 12 | 572 |
beam | learning/katas/python/Common Transforms/Aggregation/Mean/task.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"); y... | 36 | 1,238 |
cvxpy | cvxpy/constraints/cones.py | .py | """
Copyright, the CVXPY authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software... | 78 | 2,788 |
owasp-mstg | demos/android/MASVS-PLATFORM/MASTG-DEMO-0030/server.py | .py | import http.server
import socketserver
import json
class Handler(http.server.BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers.get('Content-Length', 0))
data = self.rfile.read(length)
text = data.decode('utf-8')
print(f'\n\n[*] Received POST data from {self.clie... | 30 | 906 |
mlflow | mlflow/types/__init__.py | .py | """
The :py:mod:`mlflow.types` module defines data types and utilities to be used by other mlflow
components to describe interface independent of other frameworks or languages.
"""
from mlflow.version import IS_TRACING_SDK_ONLY
if not IS_TRACING_SDK_ONLY:
try:
import numpy as _np # noqa: F401
_H... | 38 | 949 |
conda | tests/models/test_enums.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Tests for conda.models.enums module."""
from __future__ import annotations
from contextlib import nullcontext
from dataclasses import dataclass
from typing import TYPE_CHECKING
import pytest
from conda.exceptions import CondaUpgradeError
... | 111 | 3,152 |
pyro | tests/ops/test_streaming.py | .py | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import functools
import pytest
import torch
from pyro.ops.streaming import (
CountMeanStats,
CountMeanVarianceStats,
CountStats,
StackStats,
StatsOfDict,
)
from tests.common import assert_close
def generate_data... | 110 | 3,172 |
saleor | saleor/tests/e2e/orders/discounts/test_manual_total_discount_applied_on_draft_order.py | .py | import pytest
from ... import DEFAULT_ADDRESS
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 (
draft_order_complete,
draft_order_... | 407 | 13,832 |
conda | conda/plugins/previews.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Built-in plugin hooks for opt-in preview features."""
from __future__ import annotations
from typing import TYPE_CHECKING
from ..base.context import context
from . import hookimpl
if TYPE_CHECKING:
from .types import CondaSubcommand
... | 37 | 1,095 |
conda | conda/gateways/streams.py | .py | # Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
"""Helper functions for streaming output to stdout and stderr."""
import re
import sys
_TOKEN_URL_PATTERN = re.compile(
r"(|https?://)" # \1 scheme
r"(|\s" # \2 space, or
r"|(?:(?:\d{1,3}\.){3}\d{1,3})" # ipv4, or
r"|(?:" ... | 50 | 1,379 |
beam | sdks/python/apache_beam/examples/inference/anomaly_detection/anomaly_detection_pipeline/main.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... | 145 | 5,204 |
sphinx | sphinx/ext/autodoc/_dynamic/_member_finder.py | .py | from __future__ import annotations
import operator
import re
from enum import Enum
from typing import TYPE_CHECKING, Literal, NewType, TypeVar
from sphinx.errors import PycodeError
from sphinx.events import EventManager
from sphinx.ext.autodoc._directive_options import _AutoDocumenterOptions
from sphinx.ext.autodoc._... | 872 | 31,491 |
coremltools | deps/protobuf/python/google/protobuf/internal/json_format_test.py | .py | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... | 1,277 | 51,723 |
black | tests/data/cases/typed_params_trailing_comma.py | .py | def long_function_name_goes_here(
x: Callable[List[int]]
) -> Union[List[int], float, str, bytes, Tuple[int]]:
pass
def long_function_name_goes_here(
x: Callable[[str, Any], int]
) -> Union[List[int], float, str, bytes, Tuple[int]]:
pass
# output
def long_function_name_goes_here(
x: Callable[Lis... | 24 | 525 |
onnxruntime | onnxruntime/test/python/quantization/test_op_softmax.py | .py | #!/usr/bin/env python
"""
Softmax quantization test case
"""
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------... | 292 | 10,721 |
saleor | saleor/order/fetch.py | .py | from collections.abc import Iterable
from dataclasses import dataclass
from typing import Optional, cast
from uuid import UUID
from django.db.models import prefetch_related_objects
from ..channel.models import Channel
from ..core.db.connection import allow_writer
from ..core.prices import quantize_price
from ..core.p... | 286 | 9,513 |
kafka | tests/kafkatest/tests/core/round_trip_fault_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 use ... | 127 | 6,448 |
textual | src/textual/scrollbar.py | .py | """
Contains the widgets that manage Textual scrollbars.
!!! note
You will not typically need this for most apps.
"""
from __future__ import annotations
from math import ceil
from typing import ClassVar, Type
import rich.repr
from rich.color import Color
from rich.console import Console, ConsoleOptions, Rende... | 412 | 13,956 |
sphinx | sphinx/domains/std/__init__.py | .py | """The standard domain."""
from __future__ import annotations
import operator
import re
from copy import copy
from typing import TYPE_CHECKING, cast
from docutils import nodes
from docutils.parsers.rst import directives
from docutils.statemachine import StringList
from sphinx import addnodes
from sphinx.addnodes im... | 1,474 | 53,447 |
beam | sdks/python/apache_beam/runners/interactive/extensions/apache-beam-jupyterlab-sidepanel/apache_beam_jupyterlab_sidepanel/__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"); y... | 20 | 966 |
wandb | wandb/sdk/launch/agent/__init__.py | .py | from .agent import LaunchAgent
LaunchAgent = LaunchAgent
__all__ = ["LaunchAgent"]
| 6 | 85 |
onnx | onnx/reference/ops/aionnx_preview_training/_op_run_training.py | .py | # Copyright (c) ONNX Project Contributors
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from onnx.reference.op_run import OpRun
class OpRunTraining(OpRun):
op_domain = "ai.onnx.preview.training"
| 11 | 230 |
python-prompt-toolkit | examples/prompts/auto-completion/colored-completions.py | .py | #!/usr/bin/env python
"""
Demonstration of a custom completer class and the possibility of styling
completions independently.
"""
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.output.color_depth import ColorDepth
from prompt_toolkit.shortcuts import CompleteStyle, prompt
colors = [
... | 80 | 1,938 |
mlflow | tests/genai/judges/test_judge_tool_registry.py | .py | import inspect
import json
import pytest
import mlflow
from mlflow.entities.span import SpanType
from mlflow.entities.trace import Trace
from mlflow.entities.trace_info import TraceInfo
from mlflow.entities.trace_location import TraceLocation
from mlflow.entities.trace_state import TraceState
from mlflow.exceptions i... | 218 | 6,602 |
mlflow | tests/autologging/test_autologging_utils.py | .py | import importlib
import inspect
import sys
import time
from typing import Any, NamedTuple
from unittest import mock
import pytest
import mlflow
from mlflow import MlflowClient
from mlflow.ml_package_versions import FLAVOR_TO_MODULE_NAME
from mlflow.utils import gorilla
from mlflow.utils.autologging_utils import (
... | 945 | 34,883 |
slimit | setup.py | .py | import os, sys
from setuptools import setup, find_packages
try:
from distutils.command.build_py import build_py_2to3 as build_py
except ImportError:
from distutils.command.build_py import build_py
classifiers = """\
Intended Audience :: Developers
License :: OSI Approved :: MIT License
Programming Language :: ... | 58 | 1,651 |
coveragepy | coverage/report_core.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
"""Reporter foundation for coverage.py."""
from __future__ import annotations
import sys
from collections.abc import Callable, Iterable
from typing import IO, T... | 124 | 4,334 |
hydra | tests/test_apps/app_with_multiple_config_dirs/my_app.py | .py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from omegaconf import DictConfig, OmegaConf
import hydra
@hydra.main(config_path=".")
def my_app(cfg: DictConfig) -> None:
print(OmegaConf.to_yaml(cfg))
if __name__ == "__main__":
my_app()
| 14 | 273 |
wandb | wandb/plot/bar.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
from wandb.plot.custom_chart import plot_table
if TYPE_CHECKING:
import wandb
from wandb.plot.custom_chart import CustomChart
def bar(
table: wandb.Table,
label: str,
value: str,
title: str = "",
split_table: bool = Fal... | 72 | 2,036 |
python-prompt-toolkit | tests/test_widgets.py | .py | from __future__ import annotations
from prompt_toolkit.formatted_text import fragment_list_to_text
from prompt_toolkit.layout import to_window
from prompt_toolkit.widgets import Button
def _to_text(button: Button) -> str:
control = to_window(button).content
return fragment_list_to_text(control.text())
def ... | 21 | 554 |
saleor | saleor/tests/e2e/orders/test_draft_order_update_uses_denormalized_prices.py | .py | from decimal import Decimal
import pytest
from ....core.prices import quantize_price
from ....discount.models import PromotionRule
from ....product.models import Product
from ....product.utils.variant_prices import update_discounted_prices_for_promotion
from ....product.utils.variants import fetch_variants_for_promot... | 354 | 13,693 |
black | tests/data/cases/remove_parens.py | .py | x = (1)
x = (1.2)
data = (
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
).encode()
async def show_status():
while True:
try:
if report_host:
data = (
f"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... | 143 | 3,493 |
django-cms | cms/test_utils/project/app_with_feature_not_implemented/cms_config.py | .py | from cms.app_base import CMSAppExtension
class CMSSomeFeatureConfig(CMSAppExtension):
pass
| 6 | 97 |
openvino | tests/layer_tests/pytorch_tests/test_rrelu.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
import torch.nn.functional as F
from pytorch_layer_test_class import PytorchLayerTest, skip_if_export
class aten_rrelu(torch.nn.Module):
def __init__(self, lower, upper, dtype, inplace):
super().... | 50 | 1,520 |
beam | sdks/python/apache_beam/version.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... | 21 | 870 |
omegaconf | subprojects/omegaconf-pydevd/examples/debug_demo.py | .py | from omegaconf import OmegaConf
cfg = OmegaConf.create(
{
"name": "OmegaConf",
"release": "???",
"greeting": "Hello ${name}",
"subprojects": {
"omegaconf-pydevd": {
"version": "???",
"status": "debugger plugin",
}
},
... | 24 | 502 |
textual | docs/examples/how-to/containers07.py | .py | from textual.app import App, ComposeResult
from textual.containers import HorizontalScroll
from textual.widgets import Placeholder
class Box(Placeholder):
"""Example widget."""
DEFAULT_CSS = """
Box {
width: 16;
height: 8;
}
"""
class ContainerApp(App):
"""Simple app... | 35 | 667 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.