language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | joke2k__faker | tests/providers/test_automotive.py | {
"start": 1949,
"end": 2103
} | class ____(_SimpleAutomotiveTestMixin):
"""Test ar_BH automotive provider methods"""
license_plate_pattern: Pattern = re.compile(r"\d{6}")
| TestArBh |
python | mlflow__mlflow | mlflow/gateway/providers/mlflow.py | {
"start": 2065,
"end": 8694
} | class ____(BaseProvider):
NAME = "MLflow Model Serving"
CONFIG_TYPE = MlflowModelServingConfig
def __init__(self, config: EndpointConfig) -> None:
super().__init__(config)
if config.model.config is None or not isinstance(
config.model.config, MlflowModelServingConfig
):
... | MlflowModelServingProvider |
python | ahupp__python-magic | test/libmagic_test.py | {
"start": 298,
"end": 1732
} | class ____(unittest.TestCase):
filename = os.path.join(TESTDATA_DIR, "test.pdf")
expected_mime_type = "application/pdf"
expected_encoding = "us-ascii"
expected_name = (
"PDF document, version 1.2",
"PDF document, version 1.2, 2 pages",
"PDF document, version 1.2, 2 page(s)",
... | MagicTestCase |
python | django__django | tests/migrations2/test_migrations_2/0001_initial.py | {
"start": 43,
"end": 559
} | class ____(migrations.Migration):
dependencies = [("migrations", "0002_second")]
operations = [
migrations.CreateModel(
"OtherAuthor",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
("slug... | Migration |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/workspace.py | {
"start": 12398,
"end": 19625
} | class ____:
def __init__(
self,
uri,
workspace,
source=None,
version=None,
local=True,
extra_sys_path=None,
rope_project_builder=None,
) -> None:
self.uri = uri
self.version = version
self.path = uris.to_fs_path(uri)
... | Document |
python | SmileyChris__easy-thumbnails | easy_thumbnails/files.py | {
"start": 27511,
"end": 28589
} | class ____(ImageFieldFile, ThumbnailerFieldFile):
"""
A field file which provides some methods for generating (and returning)
thumbnail images.
"""
def save(self, name, content, *args, **kwargs):
"""
Save the image.
The image will be resized down using a ``ThumbnailField`` ... | ThumbnailerImageFieldFile |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 101790,
"end": 102284
} | class ____(fixtures.TestBase):
"""Test of test things"""
@testing.variation("foo", ["foo", "bar", "baz"])
def test_variations(self, foo):
match foo:
case "foo":
is_true(foo.foo)
is_false(foo.bar)
case "bar":
is_true(foo.bar)
... | TestTest |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/cache.py | {
"start": 941,
"end": 4864
} | class ____:
"""A static class to manage the global secret cache."""
__manager: multiprocessing.managers.SyncManager | None = None
_cache: dict[str, _CacheValue] | None = None
_ttl: datetime.timedelta
class NotPresentException(Exception):
"""Raised when a key is not present in the cache."""... | SecretCache |
python | great-expectations__great_expectations | tests/integration/data_sources_and_expectations/expectations/test_expect_column_values_to_not_match_like_pattern.py | {
"start": 4394,
"end": 5659
} | class ____:
@pytest.mark.parametrize(
"expectation",
[
pytest.param(
gxe.ExpectColumnValuesToNotMatchLikePattern(column=COL_A, like_pattern="a[xzy]"),
id="bracket_notation",
),
],
)
@parameterize_batch_for_data_sources(
... | TestMSSQL |
python | lazyprogrammer__machine_learning_examples | hmm_class/hmmc_theano.py | {
"start": 764,
"end": 6490
} | class ____:
def __init__(self, M, K):
self.M = M # number of hidden states
self.K = K # number of Gaussians
def fit(self, X, learning_rate=1e-2, max_iter=10):
# train the HMM model using gradient descent
N = len(X)
D = X[0].shape[1] # assume each x is organized (T, ... | HMM |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol1.py | {
"start": 1863,
"end": 1990
} | class ____(Protocol[_A, _B]): ...
# This should generate an error because Protocol must
# include all of the TypeVars.
| ProtoBase1 |
python | RaRe-Technologies__gensim | gensim/models/ldamulticore.py | {
"start": 4050,
"end": 17462
} | class ____(LdaModel):
"""An optimized implementation of the LDA algorithm, able to harness the power of multicore CPUs.
Follows the similar API as the parent class :class:`~gensim.models.ldamodel.LdaModel`.
"""
def __init__(self, corpus=None, num_topics=100, id2word=None, workers=None,
... | LdaMulticore |
python | huggingface__transformers | tests/models/dinov2/test_modeling_dinov2.py | {
"start": 7486,
"end": 10819
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as Dinov2 does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
test_torch_exportable = True
all_model_classes = (
(
... | Dinov2ModelTest |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/fail_defaults.py | {
"start": 40,
"end": 813
} | class ____(BaseModel):
# Required
undefined_default_no_args: int = Field()
undefined_default: int = Field(description='my desc')
positional_ellipsis_default: int = Field(...)
named_ellipsis_default: int = Field(default=...)
# Not required
positional_default: int = Field(1)
named_default... | Model |
python | django__django | tests/fixtures_regress/models.py | {
"start": 1981,
"end": 2091
} | class ____(models.Manager):
def get_by_natural_key(self, key):
return self.get(name=key)
| TestManager |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/components.py | {
"start": 2506,
"end": 4445
} | class ____(RecordTransformation):
"""
Implements a custom transformation which adds the legacy field equivalent of v2 fields for streams which contain Deals and Contacts entities.
This custom implmentation was developed in lieu of the AddFields component due to the dynamic-nature of the record properties f... | NewtoLegacyFieldTransformation |
python | gevent__gevent | src/gevent/tests/test__close_backend_fd.py | {
"start": 523,
"end": 3865
} | class ____(unittest.TestCase):
# NOTE that we extend unittest.TestCase, not greentest.TestCase
# Extending the later causes the wrong hub to get used.
BACKENDS_THAT_SUCCEED_WHEN_FD_CLOSED = (
'kqueue',
'epoll',
'linux_aio',
'linux_iouring',
)
BACKENDS_THAT_WILL_FAIL... | Test |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/_execution.py | {
"start": 9592,
"end": 14202
} | class ____(BaseExecutionPolicy):
"""Run the shell inside a dedicated Docker container.
Choose this policy when commands originate from untrusted users or you require
strong isolation between sessions. By default the workspace is bind-mounted only
when it refers to an existing non-temporary directory; e... | DockerExecutionPolicy |
python | scipy__scipy | scipy/stats/_multicomp.py | {
"start": 579,
"end": 16917
} | class ____:
"""Result object returned by `scipy.stats.dunnett`.
Attributes
----------
statistic : float ndarray
The computed statistic of the test for each comparison. The element
at index ``i`` is the statistic for the comparison between
groups ``i`` and the control.
pvalue... | DunnettResult |
python | tornadoweb__tornado | tornado/test/gen_test.py | {
"start": 8002,
"end": 17433
} | class ____(AsyncTestCase):
def setUp(self):
# Stray StopIteration exceptions can lead to tests exiting prematurely,
# so we need explicit checks here to make sure the tests run all
# the way through.
self.finished = False
super().setUp()
def tearDown(self):
super... | GenCoroutineTest |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-openai/tests/test_openai.py | {
"start": 606,
"end": 19367
} | class ____:
"""
Saves the users' OpenAI API key and OpenAI API type either in
the environment variable or set to the library itself.
This allows us to run tests by setting it without plowing over
the local environment.
"""
def __init__(
self,
set_env_key_to: Optional[str] = ... | CachedOpenAIApiKeys |
python | pallets__werkzeug | src/werkzeug/serving.py | {
"start": 31259,
"end": 39826
} | class ____(ForkingMixIn, BaseWSGIServer):
"""A WSGI server that handles concurrent requests in separate forked
processes.
Use :func:`make_server` to create a server instance.
"""
multiprocess = True
def __init__(
self,
host: str,
port: int,
app: WSGIApplication... | ForkingWSGIServer |
python | RaRe-Technologies__gensim | gensim/test/test_fasttext.py | {
"start": 74089,
"end": 75197
} | class ____(unittest.TestCase):
def test_add_vector(self):
wv = FastTextKeyedVectors(vector_size=2, min_n=3, max_n=6, bucket=2000000)
wv.add_vector("test_key", np.array([0, 0]))
self.assertEqual(wv.key_to_index["test_key"], 0)
self.assertEqual(wv.index_to_key[0], "test_key")
... | FastTextKeyedVectorsTest |
python | scikit-learn__scikit-learn | sklearn/model_selection/_split.py | {
"start": 63871,
"end": 67559
} | class ____(_UnsupportedGroupCVMixin, _RepeatedSplits):
"""Repeated class-wise stratified K-Fold cross validator.
Repeats Stratified K-Fold n times with different randomization in each
repetition.
Read more in the :ref:`User Guide <repeated_k_fold>`.
.. note::
Stratification on the class ... | RepeatedStratifiedKFold |
python | django__django | tests/update_only_fields/models.py | {
"start": 94,
"end": 367
} | class ____(models.Model):
GENDER_CHOICES = (
("M", "Male"),
("F", "Female"),
)
name = models.CharField(max_length=20)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
pid = models.IntegerField(null=True, default=None)
| Person |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 650714,
"end": 651540
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for EnterpriseServerInstallation."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("EnterpriseServerInstallationMembershipEdge"), graphql_name="ed... | EnterpriseServerInstallationMembershipConnection |
python | Lightning-AI__lightning | tests/tests_pytorch/loops/test_loops.py | {
"start": 1790,
"end": 25315
} | class ____(Exception):
pass
def test_loop_restore():
class Simple(_Loop):
def __init__(self, trainer, dataset: Iterator):
super().__init__(trainer)
self.iteration_count = 0
self.dataset = dataset
def run(self):
self.reset()
while not... | CustomException |
python | numba__numba | numba/cuda/cudadrv/devicearray.py | {
"start": 26643,
"end": 31123
} | class ____(DeviceNDArrayBase, np.ndarray):
"""
A host array that uses CUDA managed memory.
"""
def device_setup(self, gpu_data, stream=0):
self.gpu_data = gpu_data
self.stream = stream
def from_array_like(ary, stream=0, gpu_data=None):
"Create a DeviceNDArray object that is like a... | ManagedNDArray |
python | langchain-ai__langchain | libs/core/tests/unit_tests/language_models/chat_models/test_base.py | {
"start": 16278,
"end": 30162
} | class ____(FakeTracer):
def __init__(self) -> None:
super().__init__()
self.messages: list = []
def on_chat_model_start(self, *args: Any, **kwargs: Any) -> Run:
_, messages = args
self.messages.append(messages)
return super().on_chat_model_start(
*args,
... | FakeChatModelStartTracer |
python | huggingface__transformers | src/transformers/models/beit/configuration_beit.py | {
"start": 847,
"end": 10980
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`BeitModel`]. It is used to instantiate an BEiT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield... | BeitConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 156994,
"end": 157767
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of ClearProjectV2ItemFieldValue"""
__schema__ = github_schema
__field_names__ = ("project_id", "item_id", "field_id", "client_mutation_id")
project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId")
"""The ID of the ... | ClearProjectV2ItemFieldValueInput |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 28696,
"end": 30522
} | class ____(TestCase):
"""
Tests for auth backend that supports object level permissions
"""
@classmethod
def setUpTestData(cls):
cls.user1 = User.objects.create_user("test", "test@example.com", "test")
cls.user2 = User.objects.create_user("test2", "test2@example.com", "test")
... | RowlevelBackendTest |
python | charliermarsh__ruff | crates/ruff_python_ast/generate.py | {
"start": 6600,
"end": 34440
} | class ____:
rule: str
name: str
inner: str
seq: bool = False
optional: bool = False
slice_: bool = False
def __init__(self, rule: str) -> None:
self.rule = rule
self.name = ""
self.inner = extract_type_argument(rule)
# The following cases are the limitations... | FieldType |
python | huggingface__transformers | tests/models/dinov3_convnext/test_modeling_dinov3_convnext.py | {
"start": 5456,
"end": 9071
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as ConvNext does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (DINOv3ConvNextModel,) if is_torch_available() els... | DINOv3ConvNextModelTest |
python | walkccc__LeetCode | solutions/1822. Sign of the Product of an Array/1822.py | {
"start": 0,
"end": 190
} | class ____:
def arraySign(self, nums: list[int]) -> int:
sign = 1
for num in nums:
if num == 0:
return 0
if num < 0:
sign = -sign
return sign
| Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 572365,
"end": 572956
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("ReactorEdge"), graphql_name="edges")
nodes = sgqlc.types.Field(sgqlc.t... | ReactorConnection |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E30.py | {
"start": 5369,
"end": 5512
} | class ____:
"""Class for minimal repo."""
columns = []
@classmethod
def cls_method(cls) -> None:
pass
# end
# E301
| Class |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/asset_execution_context.py | {
"start": 3526,
"end": 22405
} | class ____:
def __init__(self, op_execution_context: OpExecutionContext) -> None:
self._op_execution_context = check.inst_param(
op_execution_context, "op_execution_context", OpExecutionContext
)
self._step_execution_context = self._op_execution_context._step_execution_context #... | AssetExecutionContext |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/control_flow_ops_test.py | {
"start": 85408,
"end": 87294
} | class ____(type_spec.BatchableTypeSpec):
def __init__(self, mass, velocity):
self.shape = array_ops.broadcast_static_shape(
mass.shape, velocity.shape)
self.mass = mass
self.velocity = velocity
def _serialize(self):
return (self.mass, self.velocity)
@property
def value_type(self):
... | ParticleSpec |
python | fluentpython__example-code-2e | 24-class-metaprog/tinyenums/nanoenum.py | {
"start": 830,
"end": 879
} | class ____(metaclass=NanoEnumMeta):
pass
| NanoEnum |
python | fluentpython__example-code | 06-dp-1class-func/classic_strategy.py | {
"start": 2054,
"end": 2228
} | class ____(ABC): # the Strategy: an Abstract Base Class
@abstractmethod
def discount(self, order):
"""Return discount as a positive dollar amount"""
| Promotion |
python | doocs__leetcode | solution/0400-0499/0459.Repeated Substring Pattern/Solution.py | {
"start": 0,
"end": 116
} | class ____:
def repeatedSubstringPattern(self, s: str) -> bool:
return (s + s).index(s, 1) < len(s)
| Solution |
python | jazzband__django-pipeline | pipeline/finders.py | {
"start": 1455,
"end": 1863
} | class ____(BaseFinder):
def find(self, path, **kwargs):
"""
Work out the uncached name of the file and look that up instead
"""
try:
start, _, extn = path.rsplit(".", 2)
except ValueError:
return []
path = ".".join((start, extn))
return... | CachedFileFinder |
python | openai__openai-python | src/openai/types/realtime/realtime_response_create_mcp_tool_param.py | {
"start": 550,
"end": 1051
} | class ____(TypedDict, total=False):
read_only: bool
"""Indicates whether or not a tool modifies data or is read-only.
If an MCP server is
[annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint),
it will match this filter.
"""... | AllowedToolsMcpToolFilter |
python | django__django | tests/custom_migration_operations/operations.py | {
"start": 1767,
"end": 1951
} | class ____(ArgsKwargsOperation):
def __init__(self, arg1, arg2, *, kwarg1, kwarg2):
super().__init__(arg1, arg2, kwarg1=kwarg1, kwarg2=kwarg2)
| ArgsAndKeywordOnlyArgsOperation |
python | getsentry__sentry | tests/sentry/middleware/integrations/parsers/test_google.py | {
"start": 365,
"end": 1456
} | class ____(TestCase):
factory = RequestFactory()
google_dummy_requests = [
factory.get("/extensions/google/setup/"),
# Unsure how these requests are getting generated, but they shouldn't fail in the middleware
factory.get("/extensions/google/setup/null/"),
factory.get("/extension... | GoogleRequestParserTest |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/api_tests/schedule_tests/test_business_logic.py | {
"start": 13374,
"end": 19850
} | class ____:
"""Test processing of schedule data structures.
This class tests pure functions and domain model functionality
without requiring external dependencies.
"""
def test_schedule_creation_with_all_fields(self, snapshot):
"""Test creating schedule with all possible fields."""
... | TestScheduleDataProcessing |
python | getsentry__sentry | src/sentry/preprod/api/endpoints/project_preprod_artifact_install_details.py | {
"start": 1020,
"end": 4414
} | class ____(PreprodArtifactEndpoint):
owner = ApiOwner.EMERGE_TOOLS
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
def get(
self,
request: Request,
project: Project,
head_artifact_id: int,
head_artifact: PreprodArtifact,
) -> HttpResponseBa... | ProjectPreprodInstallDetailsEndpoint |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 68676,
"end": 69100
} | class ____(BiffRecord):
"""
This record is part of the Calculation Settings Block.
It stores if iterations are allowed while calculating recursive formulas.
Record ITERATION, BIFF2-BIFF8:
Offset Size Contents
0 2 0 = Iterations off; 1 = Iterations on
"""
_REC_ID = 0x011... | IterationRecord |
python | bokeh__bokeh | src/bokeh/models/widgets/sliders.py | {
"start": 10379,
"end": 12179
} | class ____(NumericalSlider):
""" Slider-based datetime range selection widget. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@property
def value_as_datetime(self) -> tuple[datetime, datetime] | No... | DatetimeRangeSlider |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 40664,
"end": 45086
} | class ____(Response):
"""
Response of queues.get_all endpoint.
:param queues: Queues list
:type queues: Sequence[Queue]
"""
_service = "queues"
_action = "get_all"
_version = "2.13"
_schema = {
"definitions": {
"entry": {
"properties": {
... | GetAllResponse |
python | joke2k__faker | faker/providers/date_time/hr_HR/__init__.py | {
"start": 46,
"end": 881
} | class ____(DateTimeProvider):
def day_of_week(self) -> str:
day = self.date("%w")
DAY_NAMES = {
"0": "Nedjelja",
"1": "Ponedjeljak",
"2": "Utorak",
"3": "Srijeda",
"4": "Četvrtak",
"5": "Petak",
"6": "Subota",
... | Provider |
python | sympy__sympy | sympy/stats/drv_types.py | {
"start": 6579,
"end": 8709
} | class ____(SingleDiscreteDistribution):
_argnames = ('a1', 'a2')
set = S.Naturals0
@staticmethod
def check(a1, a2):
_value_check(a1.is_nonnegative, 'Parameter a1 must be >= 0.')
_value_check(a2.is_nonnegative, 'Parameter a2 must be >= 0.')
def pdf(self, k):
a1, a2 = self.a1... | HermiteDistribution |
python | run-llama__llama_index | llama-index-integrations/storage/index_store/llama-index-storage-index-store-couchbase/llama_index/storage/index_store/couchbase/base.py | {
"start": 184,
"end": 1519
} | class ____(KVIndexStore):
"""Couchbase Index store."""
def __init__(
self,
couchbase_kvstore: CouchbaseKVStore,
namespace: Optional[str] = None,
collection_suffix: Optional[str] = None,
) -> None:
"""
Initialize a CouchbaseIndexStore.
Args:
c... | CouchbaseIndexStore |
python | pytorch__pytorch | torch/_inductor/config.py | {
"start": 74294,
"end": 79504
} | class ____:
"""Settings for cuda backend, today this consists of cutlass"""
# CUDA arch to use for CUDA template kernel compilation.
# e.g. "70", "75", "80", "90", etc.
# When arch is None, Inductor uses torch.cuda.get_device_capability(0).
arch: Optional[str] = None
# CUDA version to use for ... | cuda |
python | run-llama__llama_index | llama-index-integrations/program/llama-index-program-evaporate/llama_index/program/evaporate/extractor.py | {
"start": 571,
"end": 2378
} | class ____(Exception):
pass
@contextmanager
def time_limit(seconds: int) -> Any:
"""
Time limit context manager.
NOTE: copied from https://github.com/HazyResearch/evaporate.
"""
def signal_handler(signum: Any, frame: Any) -> Any:
raise TimeoutException("Timed out!")
signal.sign... | TimeoutException |
python | kamyu104__LeetCode-Solutions | Python/stone-game-v.py | {
"start": 33,
"end": 1286
} | class ____(object):
def stoneGameV(self, stoneValue):
"""
:type stoneValue: List[int]
:rtype: int
"""
n = len(stoneValue)
prefix = [0]
for v in stoneValue:
prefix.append(prefix[-1] + v)
mid = range(n)
dp = [[0]*n for _ in xrange(n... | Solution |
python | walkccc__LeetCode | solutions/1573. Number of Ways to Split a String/1573.py | {
"start": 0,
"end": 722
} | class ____:
def numWays(self, s: str) -> int:
MOD = 1_000_000_007
ones = s.count('1')
if ones % 3 != 0:
return 0
if ones == 0:
n = len(s)
return (n - 1) * (n - 2) // 2 % MOD
s1End = -1
s2Start = -1
s2End = -1
s3Start = -1
onesSoFar = 0
for i, c in enumerate(... | Solution |
python | scrapy__scrapy | tests/test_spidermiddleware_referer.py | {
"start": 23088,
"end": 23876
} | class ____(TestRefererMiddleware):
settings = {"REFERRER_POLICY": CustomPythonOrgPolicy}
scenarii = [
("https://example.com/", "https://scrapy.org/", b"https://python.org/"),
("http://example.com/", "http://scrapy.org/", b"http://python.org/"),
("http://example.com/", "https://scrapy.org... | TestSettingsCustomPolicy |
python | kamyu104__LeetCode-Solutions | Python/finding-3-digit-even-numbers.py | {
"start": 1600,
"end": 3135
} | class ____(object):
def findEvenNumbers(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
k = 3
def backtracking(curr, dummy, result):
if len(curr) == k:
result.append(reduce(lambda x, y: x*10+y, curr))
return... | Solution3 |
python | vyperlang__vyper | vyper/semantics/analysis/base.py | {
"start": 2990,
"end": 3209
} | class ____(StringEnum):
NO_OWNERSHIP = enum.auto() # readable
USES = enum.auto() # writeable
INITIALIZES = enum.auto() # initializes
# base class for things that are the "result" of analysis
| ModuleOwnership |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-pebblo/llama_index/readers/pebblo/utility.py | {
"start": 1754,
"end": 2369
} | class ____(BaseModel):
"""
This class represents an AI application.
Args:
name (str): Name of the app.
owner (str): Owner of the app.
description (Optional[str]): Description of the app.
load_id (str): Unique load_id of the app instance.
runtime (Runtime): Runtime de... | App |
python | numba__numba | numba/tests/test_typedlist.py | {
"start": 37898,
"end": 40944
} | class ____(MemoryLeakMixin, TestCase):
def setUp(self):
super(TestListSort, self).setUp()
np.random.seed(0)
def make(self, ctor, data):
lst = ctor()
lst.extend(data)
return lst
def make_both(self, data):
return {
'py': self.make(list, data),
... | TestListSort |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 98364,
"end": 98489
} | class ____(PythonPrinter):
def _print_Float(self, expr: sympy.Float) -> str:
return str(float(expr))
| SymExprPrinter |
python | sympy__sympy | sympy/simplify/hyperexpand.py | {
"start": 40120,
"end": 40389
} | class ____(Operator):
""" Decrement an upper a index. """
def __init__(self, bi):
bi = sympify(bi)
self._poly = Poly(1 - bi + _x, _x)
def __str__(self):
return '<Decrement upper a=%s.>' % (1 - self._poly.all_coeffs()[1])
| MeijerShiftB |
python | getsentry__sentry | src/sentry/deletions/defaults/group.py | {
"start": 6904,
"end": 7141
} | class ____(EventsBaseDeletionTask):
"""
Deletes nodestore data, EventAttachment and UserReports for requested groups.
This class uses the old Snuba deletion method.
"""
dataset = Dataset.Events
| ErrorEventsDeletionTask |
python | huggingface__transformers | src/transformers/models/vits/modeling_vits.py | {
"start": 46122,
"end": 47502
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: VitsConfig):
super().__init__()
self.attention = VitsAttention(config)
self.dropout = nn.Dropout(config.hidden_dropout)
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
self.feed_f... | VitsEncoderLayer |
python | has2k1__plotnine | plotnine/themes/theme_538.py | {
"start": 140,
"end": 1088
} | class ____(theme_gray):
"""
Theme in the likeness of fivethirtyeight.com plots
Parameters
----------
base_size : int
Base font size. All text sizes are a scaled versions of
the base font size.
base_family : str
Base font family.
"""
def __init__(self, base_size=... | theme_538 |
python | django__django | tests/custom_managers/models.py | {
"start": 1952,
"end": 2262
} | class ____(models.QuerySet):
# QuerySet with an __init__() method that takes an additional argument.
def __init__(
self, custom_optional_arg=None, model=None, query=None, using=None, hints=None
):
super().__init__(model=model, query=query, using=using, hints=hints)
| CustomInitQuerySet |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_bigtable.py | {
"start": 1341,
"end": 5315
} | class ____:
@pytest.mark.parametrize(
("missing_attribute", "project_id", "instance_id", "table_id"),
[
("instance_id", PROJECT_ID, "", TABLE_ID),
("table_id", PROJECT_ID, INSTANCE_ID, ""),
],
)
@mock.patch("airflow.providers.google.cloud.sensors.bigtable.Bigt... | BigtableWaitForTableReplicationTest |
python | pydata__xarray | xarray/tests/test_datatree.py | {
"start": 17137,
"end": 21685
} | class ____:
def test_setitem_new_child_node(self) -> None:
john = DataTree(name="john")
mary = DataTree(name="mary")
john["mary"] = mary
grafted_mary = john["mary"]
assert grafted_mary.parent is john
assert grafted_mary.name == "mary"
def test_setitem_unnamed_ch... | TestSetItem |
python | doocs__leetcode | solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution2.py | {
"start": 95,
"end": 1295
} | class ____:
def __init__(self, nums):
n = len(nums)
self.nums = nums
self.tr = [Node() for _ in range(4 * n)]
self.build(1, 1, n)
def build(self, u, l, r):
self.tr[u].l = l
self.tr[u].r = r
if l == r:
self.tr[u].v = self.nums[l - 1]
... | SegmentTree |
python | joke2k__faker | tests/providers/test_automotive.py | {
"start": 13977,
"end": 14160
} | class ____(_SimpleAutomotiveTestMixin):
"""Test vi_VN automotive provider methods"""
license_plate_pattern: Pattern = re.compile(r"\d{2}[ABCDĐEFGHKLMNPSTUVXYZ]-\d{5}")
| TestViVn |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/value_parsers.py | {
"start": 4400,
"end": 4956
} | class ____(ChoicesParser):
"""Composite argument parser for "{platform}/{version}" formatted choices."""
def __init__(self, choices: list[str]) -> None:
super().__init__(choices, conditions=MatchConditions.CHOICE | MatchConditions.ANY)
def parse(self, state: ParserState) -> t.Any:
"""Parse... | PlatformParser |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/svd_op_test.py | {
"start": 12134,
"end": 13914
} | class ____(test.TestCase):
pass # Filled in below
def _GetSvdGradGradOpTest(dtype_, shape_, compute_uv_, full_matrices_):
@test_util.run_v1_only("b/120545219")
def Test(self):
np.random.seed(42)
a = np.random.uniform(low=-1.0, high=1.0, size=shape_).astype(dtype_)
if dtype_ in [np.complex64, np.co... | SvdGradGradOpTest |
python | apache__airflow | providers/slack/src/airflow/providers/slack/operators/slack.py | {
"start": 3972,
"end": 6123
} | class ____(SlackAPIOperator):
"""
Post messages to a Slack channel.
.. code-block:: python
slack = SlackAPIPostOperator(
task_id="post_hello",
dag=dag,
text="hello there!",
channel="#random",
)
:param channel: channel in which to post me... | SlackAPIPostOperator |
python | kamyu104__LeetCode-Solutions | Python/high-five.py | {
"start": 67,
"end": 510
} | class ____(object):
def highFive(self, items):
"""
:type items: List[List[int]]
:rtype: List[List[int]]
"""
min_heaps = collections.defaultdict(list)
for i, val in items:
heapq.heappush(min_heaps[i], val)
if len(min_heaps[i]) > 5:
... | Solution |
python | facebook__pyre-check | tools/upgrade/tests/upgrade_test.py | {
"start": 299,
"end": 1314
} | class ____(unittest.TestCase):
def test_filter_errors(self) -> None:
error7 = {
"line": 2,
"column": 4,
"path": "local.py",
"code": 7,
"name": "Kind",
"concise_description": "Error",
"ignore_error": False,
"exter... | FilterErrorTest |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/constructor.py | {
"start": 13816,
"end": 28327
} | class ____(BaseConstructor):
def construct_scalar(self, node):
# type: (Any) -> Any
if isinstance(node, MappingNode):
for key_node, value_node in node.value:
if key_node.tag == 'tag:yaml.org,2002:value':
return self.construct_scalar(value_node)
... | SafeConstructor |
python | bokeh__bokeh | src/bokeh/models/glyphs.py | {
"start": 22785,
"end": 24893
} | class ____(ImageBase):
''' Render images given as scalar data together with a color mapper.
In addition to the defined model properties, ``Image`` also can accept
a keyword argument ``palette`` in place of an explicit ``color_mapper``.
The value should be a list of colors, or the name of one of the bui... | Image |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 2901,
"end": 3024
} | class ____(IsTrainingCheck):
def __init__(self) -> None:
super().__init__()
self.train(False)
| IsEvalCheck |
python | oauthlib__oauthlib | tests/oauth1/rfc5849/test_client.py | {
"start": 9985,
"end": 12907
} | class ____(TestCase):
def test_case_insensitive_headers(self):
client = Client('client_key')
# Uppercase
_, h, _ = client.sign('http://i.b/path', http_method='POST', body='',
headers={'Content-Type': 'application/x-www-form-urlencoded'})
self.assertEqual(h['Content-T... | SigningTest |
python | kamyu104__LeetCode-Solutions | Python/strings-differ-by-one-character.py | {
"start": 54,
"end": 928
} | class ____(object):
def differByOne(self, dict):
"""
:type dict: List[str]
:rtype: bool
"""
MOD, P = 10**9+7, 113
hashes = [0]*len(dict)
for i, word in enumerate(dict):
for c in word:
hashes[i] = (P*hashes[i] + (ord(c)-ord('a'))) %... | Solution |
python | spack__spack | lib/spack/spack/vendor/macholib/mach_o.py | {
"start": 28252,
"end": 29889
} | class ____(Structure):
_fields_ = (
("ilocalsym", p_uint32),
("nlocalsym", p_uint32),
("iextdefsym", p_uint32),
("nextdefsym", p_uint32),
("iundefsym", p_uint32),
("nundefsym", p_uint32),
("tocoff", p_uint32),
("ntoc", p_uint32),
("modtaboff", ... | dysymtab_command |
python | huggingface__transformers | src/transformers/models/edgetam_video/modeling_edgetam_video.py | {
"start": 3530,
"end": 5399
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: EdgeTamVideoConfig):
super().__init__()
self.depthwise_conv = nn.Conv2d(
config.memory_fuser_embed_dim,
config.memory_fuser_embed_dim,
kernel_size=config.memory_fuser_kernel_size,
paddi... | EdgeTamVideoMemoryFuserCXBlock |
python | pytorch__pytorch | test/dynamo/test_pgo.py | {
"start": 501,
"end": 15786
} | class ____(torch._dynamo.test_case.TestCase):
def setUp(self):
super().setUp()
self._test_stack = contextlib.ExitStack()
self._test_stack.enter_context(torch.compiler.config.patch(job_id=self.id()))
self._test_stack.enter_context(
torch._dynamo.config.patch(automatic_dyna... | PgoTest |
python | crytic__slither | slither/vyper_parsing/variables/structure_variable.py | {
"start": 186,
"end": 672
} | class ____:
def __init__(self, variable: StructureVariable, variable_data: AnnAssign):
self._variable: StructureVariable = variable
self._variable.name = variable_data.target.id
self._elem_to_parse = variable_data.annotation
@property
def underlying_variable(self) -> StructureVariab... | StructureVariableVyper |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 29027,
"end": 30050
} | class ____(StateMachineEvent):
__slots__ = ("key", "compute_duration")
key: Key
compute_duration: float
# {TaskState -> finish: TaskStateState | (finish: TaskStateState, transition *args)}
# Not to be confused with distributed.scheduler.Recs
Recs: TypeAlias = dict[TaskState, TaskStateState | tuple]
Instru... | SecedeEvent |
python | allegroai__clearml | clearml/backend_api/services/v2_9/tasks.py | {
"start": 122953,
"end": 128235
} | class ____(Response):
"""
Response of tasks.delete endpoint.
:param deleted: Indicates whether the task was deleted
:type deleted: bool
:param updated_children: Number of child tasks whose parent property was
updated
:type updated_children: int
:param updated_models: Number of model... | DeleteResponse |
python | skorch-dev__skorch | skorch/callbacks/logging.py | {
"start": 1714,
"end": 9733
} | class ____(Callback):
"""Logs model metadata and training metrics to Neptune.
Neptune is a lightweight experiment-tracking tool.
You can read more about it here: https://neptune.ai
Use this callback to automatically log all interesting values from
your net's history to Neptune.
The best way t... | NeptuneLogger |
python | great-expectations__great_expectations | great_expectations/execution_engine/partition_and_sample/sparkdf_data_sampler.py | {
"start": 495,
"end": 6751
} | class ____(DataSampler):
"""Methods for sampling a Spark dataframe."""
def sample_using_limit(self, df: pyspark.DataFrame, batch_spec: BatchSpec) -> pyspark.DataFrame:
"""Sample the first n rows of data.
Args:
df: Spark dataframe.
batch_spec: Should contain key `n` in s... | SparkDataSampler |
python | getsentry__sentry | src/sentry/backup/findings.py | {
"start": 6652,
"end": 7224
} | class ____:
"""A wrapper type for a list of 'ComparatorFinding' which enables pretty-printing in asserts."""
def __init__(self, findings: list[ComparatorFinding]):
self.findings = findings
def append(self, finding: ComparatorFinding) -> None:
self.findings.append(finding)
def empty(se... | ComparatorFindings |
python | django__django | django/core/exceptions.py | {
"start": 731,
"end": 849
} | class ____(SuspiciousOperation):
"""Suspect MIME request in multipart form data"""
pass
| SuspiciousMultipartForm |
python | sqlalchemy__sqlalchemy | test/orm/test_utils.py | {
"start": 32989,
"end": 41896
} | class ____(_poly_fixtures._Polymorphic):
run_setup_mappers = "once"
run_inserts = None
run_deletes = None
def test_plain(self):
Person = _poly_fixtures.Person
Engineer = _poly_fixtures.Engineer
pmapper = inspect(Person)
emapper = inspect(Engineer)
p1 = PathRegis... | PathRegistryInhTest |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 2992,
"end": 9716
} | class ____(metaclass=NodeType):
"""Baseclass for all Jinja nodes. There are a number of nodes available
of different types. There are four major types:
- :class:`Stmt`: statements
- :class:`Expr`: expressions
- :class:`Helper`: helper nodes
- :class:`Template`: the outermost wrapper n... | Node |
python | FactoryBoy__factory_boy | tests/test_alchemy.py | {
"start": 1291,
"end": 1633
} | class ____(SQLAlchemyModelFactory):
class Meta:
model = models.StandardModel
sqlalchemy_get_or_create = ('foo',)
sqlalchemy_session = models.session
sqlalchemy_session_persistence = 'commit'
id = factory.Sequence(lambda n: n)
foo = factory.Sequence(lambda n: 'foo%d' % n)
| WithGetOrCreateFieldFactory |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-sheets/unit_tests/integration/conftest/google_sheets_base_test.py | {
"start": 965,
"end": 7565
} | class ____(TestCase, ABC):
def setUp(self) -> None:
self._config = deepcopy(_CONFIG)
self._service_config = deepcopy(_SERVICE_CONFIG)
@staticmethod
def _check(config: Dict[str, Any], expecting_exception: bool = True) -> EntrypointOutput:
return check_helper(config, stream_name=_STRE... | GoogleSheetsBaseTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-tasks-you-can-assign.py | {
"start": 2694,
"end": 3985
} | class ____(object):
def maxTaskAssign(self, tasks, workers, pills, strength):
"""
:type tasks: List[int]
:type workers: List[int]
:type pills: int
:type strength: int
:rtype: int
"""
def check(tasks, workers, pills, strength, x):
t = tasks[... | Solution3 |
python | openai__openai-python | src/openai/types/responses/tool_param.py | {
"start": 3257,
"end": 5321
} | class ____(TypedDict, total=False):
server_label: Required[str]
"""A label for this MCP server, used to identify it in tool calls."""
type: Required[Literal["mcp"]]
"""The type of the MCP tool. Always `mcp`."""
allowed_tools: Optional[McpAllowedTools]
"""List of allowed tool names or a filter ... | Mcp |
python | sphinx-doc__sphinx | sphinx/transforms/post_transforms/__init__.py | {
"start": 1848,
"end": 11256
} | class ____(SphinxPostTransform):
"""Resolves cross-references on doctrees."""
default_priority = 10
def run(self, **kwargs: Any) -> None:
for node in self.document.findall(addnodes.pending_xref):
content = self.find_pending_xref_condition(node, ('resolved', '*'))
if content... | ReferencesResolver |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.