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 |
|---|---|---|---|---|---|
gunicorn | gunicorn/uwsgi/message.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
from gunicorn.http.body import LengthReader, Body
from gunicorn.uwsgi.errors import (
InvalidUWSGIHeader,
UnsupportedModifier,
ForbiddenUWSGIRequest,
)
# Maximum number of variables to prevent DoS
MAX... | 241 | 8,189 |
hatch | tests/dep/test_core.py | .py | from hatch.dep.core import Dependency
from hatch.utils.fs import Path
class TestPath:
def test_no_url(self):
assert Dependency("foo").path is None
def test_non_file_scheme(self):
assert Dependency("foo @ https://example.com/foo.tgz").path is None
def test_file_url(self):
dep = De... | 44 | 1,325 |
deap | doc/code/tutorials/part_3/3_7_variations.py | .py | ## 3.7 Variations
import random
from deap import base
from deap import creator
from deap import tools
## Data structure and initializer creation
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
toolbox = base.Toolbox()
toolbox.register("attr_f... | 49 | 1,598 |
wandb | tests/system_tests/test_launch/test_launch_local_container.py | .py | from unittest.mock import MagicMock
import pytest
from wandb.apis.internal import Api
from wandb.sdk.launch import loader
from wandb.sdk.launch._project_spec import EntryPoint
@pytest.mark.asyncio
async def test_local_container_entrypoint(use_local_wandb_backend, monkeypatch):
_ = use_local_wandb_backend
de... | 88 | 2,857 |
biopython | Bio/PDB/PDBIO.py | .py | # Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk)
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Output of PDB files."""
import os
import warnings
from Bio.Data.IUPACData import atom... | 486 | 16,441 |
mlflow | mlflow/store/fs2db/_utils.py | .py | import logging
from collections.abc import Iterator
from dataclasses import dataclass, fields
from pathlib import Path
from typing import Any
import yaml
from mlflow.store.tracking.file_store import FileStore
_logger = logging.getLogger(__name__)
@dataclass
class MigrationStats:
experiments: int = 0
experi... | 136 | 4,051 |
pyomo | examples/pyomobook/mpec-ch/ex1d.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... | 30 | 994 |
python-prompt-toolkit | examples/full-screen/calculator.py | .py | #!/usr/bin/env python
"""
A simple example of a calculator program.
This could be used as inspiration for a REPL.
"""
from prompt_toolkit.application import Application
from prompt_toolkit.document import Document
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.layout.containers import HSplit, W... | 97 | 2,725 |
pyomo | pyomo/contrib/interior_point/tests/test_realloc.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... | 102 | 4,010 |
beam | sdks/python/apache_beam/io/gcp/internal/clients/bigquery/__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 us... | 35 | 1,382 |
metrics | tests/unittests/text/test_bertscore.py | .py | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | 353 | 12,977 |
kombu | t/unit/test_connection.py | .py | from __future__ import annotations
import pickle
import socket
from copy import copy, deepcopy
from unittest.mock import Mock, patch
import pytest
from kombu import Connection, Consumer, Producer, parse_url
from kombu.connection import Resource
from kombu.exceptions import OperationalError
from kombu.utils.functiona... | 1,192 | 41,173 |
saleor | saleor/graphql/account/tests/mutations/authentication/test_external_logout.py | .py | import json
from unittest.mock import Mock
from .....tests.utils import get_graphql_content
MUTATION_EXTERNAL_LOGOUT = """
mutation externalLogout($pluginId: String!, $input: JSONString!){
externalLogout(pluginId: $pluginId, input: $input){
logoutData
errors{
field
... | 43 | 1,447 |
metrics | src/torchmetrics/detection/panoptic_qualities.py | .py | # Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | 477 | 22,057 |
onnx | onnx/reference/ops/op_elu.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 OpRunUnaryNum
class Elu(OpRunUnaryNum):
def _run(self, x, alpha=None):
alpha = alpha or self.alpha
return (np.where(x > 0, x, ... | 15 | 363 |
openvino | tests/layer_tests/onnx_tests/test_scatter.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import pytest
pytest.importorskip("openvino.tools.mo", reason="Ticket - 157136")
from common.layer_test_class import check_ir_version
from common.onnx_layer_test_class import OnnxRuntimeLayerTest, onnx_make_model
fro... | 135 | 5,081 |
pyro | tests/contrib/test_util.py | .py | # Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
from collections import OrderedDict
import pytest
import torch
from pyro.contrib.util import (
get_indices,
lexpand,
rdiag,
rexpand,
rmv,
rtril,
rvv,
tensor_to_dict,
)
from tests.common import asse... | 99 | 3,036 |
wandb | wandb/sdk/launch/sweeps/scheduler_sweep.py | .py | """Scheduler for classic wandb Sweeps."""
from __future__ import annotations
import logging
from pprint import pformat as pf
from typing import Any
import wandb
from wandb.sdk.launch.sweeps import SweepNotFoundError
from wandb.sdk.launch.sweeps.scheduler import LOG_PREFIX, RunState, Scheduler, SweepRun
_logger = lo... | 101 | 3,302 |
textual | docs/examples/themes/colored_text.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Label
COLORS = ("primary", "secondary", "accent", "warning", "error", "success")
class ColoredText(App[None]):
CSS = "\n".join(f".text-{color} {{color: $text-{color};}}" for color in COLORS)
def compose(self) -> ComposeResult:
fo... | 18 | 469 |
cvxpy | cvxpy/tests/nlp_tests/test_broadcast.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
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
... | 97 | 3,189 |
onnx | onnx/backend/test/case/node/concat.py | .py | # Copyright (c) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import numpy as np
import onnx
from onnx.backend.test.case.base import Base
from onnx.backend.test.case.node import expect
if TYPE_CHECKING:
from collections... | 57 | 1,928 |
wagtail | wagtail/snippets/tests/test_create_view.py | .py | import datetime
from unittest import mock
from django.contrib.admin.utils import quote
from django.contrib.auth.models import Permission
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpRequest, HttpResponse, JsonResponse
from d... | 1,196 | 45,496 |
biopython | Tests/test_PAML_codeml.py | .py | # Copyright (C) 2011, 2015, 2016 by Brandon Invergo (b.invergo@gmail.com)
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Tests for PAML codeml module."""
import itertools
import os
import os.path... | 578 | 26,828 |
onnxruntime | onnxruntime/test/python/quantization/test_op_transpose.py | .py | #!/usr/bin/env python
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------------------------... | 166 | 6,207 |
ipython | docs/source/conf.py | .py | # IPython documentation build configuration file.
# NOTE: This file has been edited manually from the auto-generated one from
# sphinx. Do NOT delete and re-generate. If any changes from sphinx are
# needed, generate a scratch one and merge by hand any new fields needed.
import sys, os
from pathlib import Path
fro... | 206 | 5,952 |
tablib | src/tablib/formats/_csv.py | .py | """ Tablib - *SV Support.
"""
__lazy_modules__ = {"csv", "io"}
import csv
from io import StringIO
class CSVFormat:
title = 'csv'
extensions = ('csv',)
DEFAULT_DELIMITER = ','
@classmethod
def export_stream_set(cls, dataset, **kwargs):
"""Returns CSV representation of Dataset as file-li... | 64 | 1,719 |
saleor | saleor/graphql/giftcard/tests/mutations/test_gift_card_resend.py | .py | import datetime
import json
from unittest import mock
import graphene
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
from .....core.utils.json_serializer import CustomJsonEncoder
from .....giftcard.error_codes import GiftCardErrorCode
from .....giftcard.models import GiftCardEv... | 351 | 9,105 |
readthedocs.org | readthedocs/core/tests/test_permissions.py | .py | from django.contrib.auth.models import User
from django.test import TestCase, override_settings
from django_dynamic_fixture import get
from readthedocs.core.permissions import AdminPermission
from readthedocs.organizations.constants import ADMIN_ACCESS, READ_ONLY_ACCESS
from readthedocs.organizations.models import Org... | 99 | 3,760 |
pymc | tests/test_root_namespace.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... | 144 | 4,931 |
beam | sdks/python/apache_beam/testing/benchmarks/nexmark/models/field_name.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... | 41 | 1,273 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/layer_norm_shared_input.py | .py | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import onnx
from onnx import OperatorSetIdProto, TensorProto, helper
# in gpt_j_residual, there will be 2 LN share the same input
def GenerateModel(model_name): # noqa: N802
nodes = [
# LN1 subgraph
help... | 72 | 3,578 |
onnxruntime | onnxruntime/test/python/transformers/test_mha.py | .py | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
"""
Test MultiHeadAttention operator for CUDA and CPU.
"""
import conc... | 912 | 38,713 |
textual | src/textual/color.py | .py | """
This module contains a powerful [Color][textual.color.Color] class which Textual uses to manipulate colors.
## Named colors
The following named colors are used by the [parse][textual.color.Color.parse] method.
```{.rich columns="80" title="colors"}
from textual._color_constants import COLOR_NAME_TO_RGB
from tex... | 857 | 28,040 |
pdm | tests/test_synchronizer_base.py | .py | from __future__ import annotations
import dataclasses
import pytest
from pdm.exceptions import BuildError
from pdm.installers.base import BaseSynchronizer, editables_candidate
from pdm.models.candidates import Candidate
from pdm.models.requirements import parse_requirement
def make_synchronizer(mocker):
synchr... | 213 | 8,466 |
mlflow | examples/paddle/train_low_level_api.py | .py | import numpy as np
import paddle
import paddle.nn.functional as F
from paddle.nn import Linear
from sklearn import preprocessing
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
import mlflow.paddle
def load_data():
X, y = load_diabetes(return_X_y=True)
min_max... | 82 | 2,542 |
mlflow | dev/run_dev_server.py | .py | """Launch the MLflow dev backend and the React dev server for local development.
Cleans up child process groups on exit/SIGINT/SIGTERM so we don't leave zombies.
"""
from __future__ import annotations
import argparse
import atexit
import os
import shlex
import shutil
import signal
import socket
import subprocess
imp... | 183 | 6,450 |
openvino | src/frontends/tensorflow/tests/test_models/gen_scripts/generate_saved_model_malicious_overflow.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import os
import struct
import sys
def encode_varint(value):
"""Encode an integer as a protobuf varint."""
result = bytearray()
while value > 0x7F:
result.append((value & 0x7F) | 0x80)
value >>= 7
result... | 220 | 8,190 |
coveragepy | tests/test_report_common.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
"""Tests of behavior common to all reporting."""
from __future__ import annotations
import textwrap
import coverage
from coverage.files import abs_file
from t... | 303 | 10,484 |
loguru | loguru/_filters.py | .py | def filter_none(record):
return record["name"] is not None
def filter_by_name(record, parent, length):
name = record["name"]
if name is None:
return False
return (name + ".")[:length] == parent
def filter_by_level(record, level_per_module):
name = record["name"]
while True:
... | 25 | 618 |
biopython | Bio/Align/AlignInfo.py | .py | # Copyright 2000 Brad Chapman. 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.
"""Extract information from a... | 55 | 1,713 |
coremltools | coremltools/converters/mil/frontend/tensorflow/ssa_passes/__init__.py | .py | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from . import backfill_make_list_elem_type, expand_tf_lstm, tf_lstm_to_core_lstm
| 7 | 300 |
coveragepy | coverage/lcovreport.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
"""LCOV reporting for coverage.py."""
from __future__ import annotations
import base64
import hashlib
import sys
from typing import IO, TYPE_CHECKING
from cove... | 238 | 8,527 |
deap | examples/coev/coop_base.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 ... | 108 | 3,822 |
readthedocs.org | readthedocs/core/utils/requests.py | .py | import structlog
log = structlog.get_logger(__name__) # noqa
def is_suspicious_request(request) -> bool:
"""
Returns True if the request is suspicious.
This function is used to detect bots and spammers,
we use Cloudflare to detect them.
"""
# This header is set from Cloudflare,
# it go... | 26 | 740 |
dirty-equals | docs/plugins.py | .py | import logging
import os
import re
from mkdocs.config import Config
from mkdocs.structure.files import Files
from mkdocs.structure.pages import Page
try:
import pytest
except ImportError:
pytest = None
logger = logging.getLogger('mkdocs.test_examples')
def on_pre_build(config: Config):
pass
def on_fi... | 77 | 2,526 |
probability | tensorflow_probability/python/math/custom_gradient.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... | 131 | 4,891 |
sqlmap | tests/_testutils.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
Shared bootstrap for the sqlmap unit/regression test suite.
Brings sqlmap's global state (conf/kb, the 'reversible' codec, cross-references,
option defaults) up far enough that pure/... | 209 | 8,660 |
mlflow | tests/spark/test_spark_model_export.py | .py | import inspect
import json
import logging
import os
from pathlib import Path
from typing import Any, NamedTuple
from unittest import mock
import numpy as np
import pandas as pd
import pyspark
import pytest
import yaml
from packaging.version import Version
from pyspark.ml.classification import LogisticRegression
from p... | 1,086 | 42,959 |
openvino | tests/layer_tests/onnx_tests/test_softplus.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
pytest.importorskip("openvino.tools.mo", reason="Ticket - 157136")
from common.layer_test_class import check_ir_version
from common.onnx_layer_test_class import OnnxRuntimeLayerTest, onnx_make_model
from unit_tests.utils.... | 188 | 6,263 |
httpie | httpie/output/ui/rich_progress.py | .py | from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional
from httpie.context import Environment
if TYPE_CHECKING:
from rich.console import Console
@dataclass
class BaseDisplay:
env: Environment
def start(
self, *, total: Optional[float], at: float, description: str
) -> ... | 142 | 3,980 |
pyomo | pyomo/contrib/parmest/examples/reactor_design/confidence_region_example.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... | 50 | 1,594 |
astropy | astropy/nddata/nddata.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# This module implements the base NDData class.
from copy import deepcopy
import numpy as np
from astropy import log
from astropy.units import Quantity, Unit
from astropy.utils.compat.optional_deps import HAS_DASK
from astropy.utils.masked import Maske... | 448 | 16,581 |
saleor | saleor/core/db/expressions.py | .py | from django.db.models import Case, F, JSONField, Value, When
from django.db.models.expressions import Expression
class PostgresJsonConcatenate(Expression):
"""Implementation of PostgreSQL concatenation for JSON fields.
Inserts or updates specific keys provided in the database for `jsonb` field type.
If a... | 86 | 3,085 |
pyomo | pyomo/contrib/alternative_solutions/tests/test_cases.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... | 437 | 14,414 |
biopython | Tests/test_AlignIO_FastaIO.py | .py | # Copyright 2011 by Peter Cock. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Unit tests for the Bio.AlignIO.FastaIO module."""
import unittest
from Bio.AlignIO import Fas... | 877 | 43,895 |
probability | spinoffs/autobnn/autobnn/estimators_test.py | .py | # Copyright 2024 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... | 131 | 4,267 |
qutip | qutip/tests/solver/test_qubit_evolution.py | .py | import numpy as np
import pytest
from qutip import (
sigmax, sigmay, sigmaz, sigmam, mesolve, mcsolve, basis,
)
def _qubit_integrate(tlist, psi0, epsilon, delta, g1, g2, solver):
H = epsilon / 2.0 * sigmaz() + delta / 2.0 * sigmax()
c_op_list = []
rate = g1
if rate > 0.0:
c_op_list.appe... | 125 | 3,608 |
clearml | examples/frameworks/fastai/legacy/fastai_with_tensorboard_example.py | .py | # ClearML - Fastai with Tensorboard example code, automatic logging the model and Tensorboard outputs
#
import argparse
from clearml import Task
import fastai
try:
from fastai.vision import (
untar_data,
URLs,
ImageDataBunch,
rand_pad,
imagenet_stats,
cnn_learner,
... | 48 | 1,328 |
cvxpy | cvxpy/atoms/affine/conj.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... | 82 | 2,284 |
biopython | Tests/test_seq.py | .py | # This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Tests for seq module."""
import copy
import unittest
import warnings
try:
import numpy as np
except ImportError:
np = None
from Bio impor... | 1,359 | 51,821 |
metrics | tests/unittests/clustering/test_homogeneity_completeness_v_measure.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... | 99 | 3,744 |
sqlmap | extra/esperanto/oracle.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
"""
from contextlib import contextmanager
from .records import OracleUndecided
from .records import QueryBudgetExceeded
class _OracleCore(object):
"""_OracleCore
the boole... | 137 | 6,471 |
metrics | src/torchmetrics/text/cer.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... | 141 | 5,307 |
black | tests/data/cases/pattern_matching_trailing_comma.py | .py | # flags: --minimum-version=3.10
match maybe, multiple:
case perhaps, 5:
pass
case perhaps, 6,:
pass
match more := (than, one), indeed,:
case _, (5, 6):
pass
case [[5], (6)], [7],:
pass
case _:
pass
# output
match maybe, multiple:
case perhaps, 5:
... | 39 | 547 |
lemur | lemur/default.conf.py | .py | # This is just Python which means you can inherit and tweak settings
import os
_basedir = os.path.abspath(os.path.dirname(__file__))
THREADS_PER_PAGE = 8
# General
# These will need to be set to `True` if you are developing locally
CORS = False
DEBUG = False
# Logging
LOG_LEVEL = "DEBUG"
LOG_FILE = "lemur.log"
L... | 36 | 1,524 |
mlflow | examples/langchain/chain_as_code.py | .py | # This example demonstrates defining a model directly from code.
# This feature allows for defining model logic within a python script, module, or notebook that is stored
# directly as serialized code, as opposed to object serialization that would otherwise occur when saving
# or logging a model object.
# This script d... | 65 | 2,123 |
returns | returns/_internal/futures/_reader_future_result.py | .py | from __future__ import annotations
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, TypeVar
from returns.primitives.hkt import Kind3, dekind
from returns.result import Result, Success
if TYPE_CHECKING:
from returns.context import RequiresContextFutureResult
_ValueType_co = TypeV... | 62 | 1,907 |
wandb | tests/unit_tests/test_lib/test_identity.py | .py | import pytest
import wandb
from wandb.proto.wandb_api_pb2 import AuthenticateResponse
from wandb.sdk.lib import identity
from wandb.sdk.lib.service.service_connection import WandbApiFailedError
_RESPONSE = AuthenticateResponse(
default_entity="my-entity",
username="my-user",
email="me@example.com",
tea... | 81 | 2,661 |
saleor | saleor/graphql/warehouse/dataloaders.py | .py | import sys
from collections import defaultdict
from collections.abc import Iterable
from typing import TYPE_CHECKING, TypedDict
from uuid import UUID
from django.contrib.sites.models import Site
from django.db.models import Exists, OuterRef, Q, QuerySet
from django.db.models.aggregates import Sum
from django.db.models... | 903 | 37,331 |
openvino | src/frontends/paddle/tests/test_models/gen_scripts/generate_top_k_v2.py | .py | #
# top_k_v2 paddle model generator
#
import numpy as np
from save_model import saveModel
import paddle
import sys
data_type = 'float32'
def top_k_v2(name: str, x, k: int, axis=None, largest=True, sorted=True, k_is_var=True):
paddle.enable_static()
k = np.array([k], dtype='int32') if k_is_var else k
w... | 55 | 2,016 |
jupytext | tests/data/notebooks/outputs/ipynb_to_marimo/notebook_with_complex_metadata.py | .py | import marimo
__generated_with = "0.17.8"
app = marimo.App()
@app.cell
def _():
return
if __name__ == "__main__":
app.run()
| 14 | 137 |
cvxpy | cvxpy/atoms/affine/add_expr.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... | 159 | 5,396 |
pyomo | pyomo/solvers/tests/piecewise_linear/problems/convex_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... | 93 | 3,216 |
sphinx | tests/roots/test-ext-autodoc/target/methods.py | .py | from functools import partialmethod
class Base:
def meth(self):
pass
@staticmethod
def staticmeth():
pass
@classmethod
def classmeth(cls):
pass
@property
def prop(self):
pass
partialmeth = partialmethod(meth)
async def coroutinemeth(self):
... | 30 | 420 |
lemur | lemur/notifications/views.py | .py | """
.. module: lemur.notifications.views
:platform: Unix
:synopsis: This module contains all of the accounts view code.
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from flask import ... | 483 | 16,937 |
saleor | saleor/graphql/app/mutations/app_install.py | .py | import graphene
from ....app import models
from ....app.manifest_validations import clean_manifest_url
from ....app.tasks import install_app_task
from ....permission.enums import AppPermission, get_permissions
from ....webhook.event_types import WebhookEventAsyncType
from ...core.doc_category import DOC_CATEGORY_APPS
... | 87 | 3,259 |
biopython | Doc/examples/fasta_iterator.py | .py | # This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
"""Example using Bio.SeqIO to parse a FASTA file."""
from Bio import SeqIO
def extract_organisms(file_to_parse, fmt):
"""Extract species names... | 31 | 940 |
beam | sdks/python/apache_beam/examples/snippets/transforms/elementwise/flatmap_generator.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");... | 61 | 1,773 |
confluent-kafka-python | tests/schema_registry/_sync/test_avro.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... | 301 | 11,154 |
eve | eve/versioning.py | .py | from flask import abort
from flask import current_app as app
from werkzeug.exceptions import BadRequestKeyError
from eve.utils import ParsedRequest, config, debug_error_message
def versioned_id_field(resource_settings):
"""Shorthand to add two commonly added versioning parameters.
.. versionadded: 0.4
"... | 408 | 15,287 |
mlflow | tests/genai/judges/optimizers/conftest.py | .py | """Shared test fixtures for optimizer tests."""
import json
import time
from typing import Any
from unittest.mock import Mock
import dspy
import pytest
from opentelemetry.sdk.trace import ReadableSpan as OTelReadableSpan
from mlflow.entities.assessment import Feedback
from mlflow.entities.assessment_source import As... | 675 | 22,803 |
bazel | src/test/py/bazel/test_wrapper_test.py | .py | # Copyright 2018 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | 800 | 26,596 |
textual | docs/examples/widgets/option_list_options.py | .py | from textual.app import App, ComposeResult
from textual.widgets import Footer, Header, OptionList
from textual.widgets.option_list import Option
class OptionListApp(App[None]):
CSS_PATH = "option_list.tcss"
def compose(self) -> ComposeResult:
yield Header()
yield OptionList(
Optio... | 37 | 1,022 |
beam | sdks/python/apache_beam/io/gcp/healthcare/dicomio_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");... | 500 | 18,391 |
probability | tensorflow_probability/python/distributions/gamma.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... | 879 | 35,363 |
sqlmap | extra/esperanto/wordlist.py | .py | #!/usr/bin/env python
"""
Copyright (c) 2006-2026 sqlmap developers (https://sqlmap.org)
See the file 'LICENSE' for copying permission
Common table/column names for the brute-force fallback used when the system catalog
is unreadable or unknown (permission wall, exotic/Frankenstein engine, CTF). This is
the "know noth... | 78 | 4,194 |
onnxruntime | onnxruntime/test/testdata/transform/fusion/label_encoder.py | .py | from onnx import OperatorSetIdProto, TensorProto, helper, save
opsets = []
onnxdomain = OperatorSetIdProto()
onnxdomain.version = 19
onnxdomain.domain = "" # The empty string ("") or absence of this field implies the operator set that is defined as part of the ONNX specification.
opsets.append(onnxdomain)
msdomain =... | 164 | 5,010 |
sphinx | tests/roots/test-ext-autosummary-module_all/autosummary_dummy_package_all/__init__.py | .py | from .autosummary_dummy_module import Bar, PublicBar, foo, public_foo
def baz():
"""Baz function"""
pass
def public_baz():
"""Public Baz function"""
__all__ = ['PublicBar', 'public_foo', 'public_baz', 'extra_dummy_module'] # NoQA: F822
| 14 | 255 |
django-cms | cms/test_utils/project/second_cms_urls_for_apphook_tests.py | .py | from django.conf import settings
from django.urls import include, re_path
from cms.apphook_pool import apphook_pool
from cms.views import details
if settings.APPEND_SLASH:
reg = re_path(r'^(?P<slug>[0-9A-Za-z-_.//]+)/$', details, name='pages-details-by-slug')
else:
reg = re_path(r'^(?P<slug>[0-9A-Za-z-_.//]+)... | 26 | 939 |
openvino | tests/layer_tests/pytorch_tests/test_squeeze.py | .py | # Copyright (C) 2018-2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
from pytorch_layer_test_class import PytorchLayerTest
class TestSqueeze(PytorchLayerTest):
def _prepare_input(self):
return (self.random.randn(1, 1, 32),)
def create_model(self, dim):
import torc... | 73 | 2,734 |
biopython | Tests/test_SCOP_Cla.py | .py | # Copyright 2001 by Gavin E. Crooks. All rights reserved.
# Modifications Copyright 2010 Jeffrey Finkelstein. All rights reserved.
#
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Unit test for ... | 91 | 3,408 |
pyomo | pyomo/contrib/doe/tests/experiment_class_example_flags.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... | 73 | 2,703 |
hatch | tests/backend/utils/test_context.py | .py | import os
import pytest
from hatch.utils.structures import EnvVars
from hatchling.utils.context import Context
def test_normal(isolation):
context = Context(isolation)
assert context.format("foo {0} {key}", "arg", key="value") == "foo arg value"
class TestStatic:
def test_directory_separator(self, iso... | 142 | 5,356 |
textual | docs/examples/how-to/inline02.py | .py | from datetime import datetime
from textual.app import App, ComposeResult
from textual.widgets import Digits
class ClockApp(App):
CSS = """
Screen {
align: center middle;
&:inline {
border: none;
height: 50vh;
Digits {
color: $success;
... | 39 | 782 |
mlflow | tests/pyfunc/custom_model/transitive_test/transitive_dependency.py | .py | def some_function():
return "test"
| 3 | 39 |
lemur | lemur/authorities/views.py | .py | """
.. module: lemur.authorities.views
:platform: Unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from flask import Blueprint, g
from flask_restful import reqparse, Api
from lemur.comm... | 575 | 20,493 |
astropy | astropy/samp/tests/test_errors.py | .py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
# By default, tests should not use the internet.
from astropy.samp import conf
from astropy.samp.errors import SAMPClientError, SAMPHubError, SAMPProxyError
def setup_module(module):
conf.use_internet = False
def test_SAMPHubError():
"""Test t... | 25 | 617 |
gunicorn | tests/requests/valid/007.py | .py | #
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
request = {
"method": "GET",
"uri": uri("/get_one_header_no_body"),
"version": (1, 1),
"headers": [
("ACCEPT", "*/*")
],
"body": b""
}
| 14 | 273 |
mkdocs | mkdocs/tests/utils/babel_stub_tests.py | .py | import unittest
from mkdocs.utils.babel_stub import Locale, UnknownLocaleError
class BabelStubTests(unittest.TestCase):
def test_locale_language_only(self):
locale = Locale('es')
self.assertEqual(locale.language, 'es')
self.assertEqual(locale.territory, '')
self.assertEqual(str(lo... | 56 | 1,931 |
kombu | t/unit/test_matcher.py | .py | from __future__ import annotations
import pytest
from kombu.matcher import (MatcherNotInstalled, fnmatch, match, register,
registry, rematch, unregister)
class test_Matcher:
def test_register_match_unregister_matcher(self):
register("test_matcher", rematch)
registry.m... | 31 | 1,133 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.