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 | sphinx-doc__sphinx | sphinx/ext/autodoc/_legacy_class_based/_documenters.py | {
"start": 94901,
"end": 96598
} | class ____(DataDocumenterMixinBase):
"""Mixin for AttributeDocumenter to provide the feature for supporting __slots__."""
def isslotsattribute(self) -> bool:
"""Check the subject is an attribute in __slots__."""
try:
if parent___slots__ := inspect.getslots(self.parent):
... | SlotsMixin |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 122365,
"end": 122528
} | class ____(BaseModel, extra="forbid"):
target: "ShardKey" = Field(..., description="")
fallback: "ShardKey" = Field(..., description="")
| ShardKeyWithFallback |
python | pypa__warehouse | tests/unit/packaging/test_models.py | {
"start": 47282,
"end": 54219
} | class ____:
def test_upload_limit_size_with_no_limits(self, db_session):
project = DBProjectFactory.create(upload_limit=None)
assert project.upload_limit_size == MAX_FILESIZE
def test_upload_limit_size_with_project_limit(self, db_session):
project_limit = 50 * ONE_MIB
project ... | TestProjectLimitProperties |
python | pypa__pipenv | pipenv/vendor/click/shell_completion.py | {
"start": 10520,
"end": 11129
} | class ____(ShellComplete):
"""Shell completion for Zsh."""
name = "zsh"
source_template = _SOURCE_ZSH
def get_completion_args(self) -> t.Tuple[t.List[str], str]:
cwords = split_arg_string(os.environ["COMP_WORDS"])
cword = int(os.environ["COMP_CWORD"])
args = cwords[1:cword]
... | ZshComplete |
python | matplotlib__matplotlib | lib/matplotlib/units.py | {
"start": 3480,
"end": 4266
} | class ____:
"""
The minimal interface for a converter to take custom data types (or
sequences) and convert them to values Matplotlib can use.
"""
@staticmethod
def axisinfo(unit, axis):
"""Return an `.AxisInfo` for the axis with the specified units."""
return None
@staticme... | ConversionInterface |
python | gevent__gevent | src/greentest/3.14/test_ssl.py | {
"start": 114650,
"end": 193093
} | class ____(unittest.TestCase):
@support.requires_resource('walltime')
def test_echo(self):
"""Basic test of an SSL client connecting to a server"""
if support.verbose:
sys.stdout.write("\n")
client_context, server_context, hostname = testing_context()
with self.sub... | ThreadedTests |
python | great-expectations__great_expectations | great_expectations/exceptions/resource_freshness.py | {
"start": 3372,
"end": 3720
} | class ____(ResourceFreshnessError):
def __init__(self, name: str) -> None:
super().__init__(
f"Checkpoint '{name}' must be added to the DataContext before it can be updated. "
"Please call `context.checkpoints.add(<CHECKPOINT_OBJECT>)`, "
"then try your action again."
... | CheckpointNotAddedError |
python | fluentpython__example-code-2e | 05-data-classes/dataclass/resource.py | {
"start": 1280,
"end": 1787
} | class ____:
"""Media resource description."""
identifier: str # <2>
title: str = '<untitled>' # <3>
creators: list[str] = field(default_factory=list)
date: Optional[date] = None # <4>
type: ResourceType = Resource... | Resource |
python | Textualize__textual | examples/theme_sandbox.py | {
"start": 2169,
"end": 2206
} | class ____(Label):
pass
| ColorSample |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-microsoft-dataverse/source_microsoft_dataverse/dataverse.py | {
"start": 254,
"end": 733
} | class ____(Oauth2Authenticator):
def build_refresh_request_body(self) -> Mapping[str, Any]:
"""
Returns the request body to set on the refresh request
"""
payload: MutableMapping[str, Any] = {
"grant_type": "client_credentials",
"client_id": self.get_client_id... | MicrosoftOauth2Authenticator |
python | huggingface__transformers | src/transformers/models/xcodec/modeling_xcodec.py | {
"start": 9075,
"end": 9868
} | class ____(nn.Module):
"""
Vector quantization implementation. Currently supports only euclidean distance.
"""
def __init__(self, config: XcodecConfig):
super().__init__()
self.codebook = XcodecEuclideanCodebook(config)
# Copied from transformers.models.encodec.modeling_encodec.Enc... | XcodecVectorQuantization |
python | huggingface__transformers | tests/models/qwen2_audio/test_processing_qwen2_audio.py | {
"start": 887,
"end": 4395
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = Qwen2AudioProcessor
model_id = "Qwen/Qwen2-Audio-7B-Instruct"
@classmethod
def _setup_test_attributes(cls, processor):
cls.audio_token = processor.audio_token
def test_can_load_various_tokenizers(self):
processo... | Qwen2AudioProcessorTest |
python | ray-project__ray | python/ray/serve/tests/test_config_files/fastapi_deployment.py | {
"start": 127,
"end": 259
} | class ____:
@app.get("/hello")
def incr(self):
return "Hello world!"
node = FastAPIDeployment.bind()
| FastAPIDeployment |
python | ansible__ansible | test/units/module_utils/basic/test_run_command.py | {
"start": 345,
"end": 1054
} | class ____(BytesIO):
"""BytesIO with dummy close() method
So that you can inspect the content after close() was called.
"""
def close(self):
pass
@pytest.fixture
def mock_os(mocker):
def mock_os_abspath(path):
if path.startswith('/'):
return path
else:
... | OpenBytesIO |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets_tests/snippet_checks/guides/components/integrations/test_powerbi_utils.py | {
"start": 6256,
"end": 7333
} | class ____(PowerBIWorkspaceComponent):
@cached_property
def workspace_resource(self) -> MockPowerBIWorkspace:
return MockPowerBIWorkspace(**self.workspace.model_dump())
def test_mock_powerbi_workspace() -> None:
"""Test that the mock PowerBI workspace returns the expected data."""
workspace = ... | MockPowerBIComponent |
python | ray-project__ray | python/ray/data/iterator.py | {
"start": 1292,
"end": 1751
} | class ____(Iterable[T]):
def __init__(self, iterator_gen: Callable[[], Iterator[T]]):
"""Constructs an Iterable from an iterator generator.
Args:
iterator_gen: A function that returns an iterator each time it
is called. For example, this can be a generator function.
... | _IterableFromIterator |
python | django-import-export__django-import-export | import_export/forms.py | {
"start": 2314,
"end": 3257
} | class ____(ImportExportFormBase):
import_file = forms.FileField(label=_("File to import"))
# field ordered for usability:
# ensure that the 'file' select appears before 'format'
# so that the 'guess_format' js logic makes sense
field_order = ["resource", "import_file", "format"]
def __init__(s... | ImportForm |
python | pypa__pip | src/pip/_vendor/resolvelib/structs.py | {
"start": 5517,
"end": 6420
} | class ____(Iterable[RT]):
"""Wrap an iterable returned by find_matches().
This is essentially just a proxy to the underlying sequence that provides
the same interface as `_FactoryIterableView`.
"""
def __init__(self, sequence: Sequence[RT]):
self._sequence = sequence
def __repr__(self... | _SequenceIterableView |
python | pennersr__django-allauth | allauth/headless/base/views.py | {
"start": 1005,
"end": 1587
} | class ____(APIView):
stage_class: Optional[Type[LoginStage]] = None
def handle(self, request, *args, **kwargs):
self.stage = LoginStageController.enter(request, self.stage_class.key)
if not self.stage:
return response.UnauthorizedResponse(request)
return super().handle(reque... | AuthenticationStageAPIView |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 139298,
"end": 139861
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
alert_output: Optional[SqlAlertOutput] = Field(
None, description="The output of a SQL alert task, if available."
)
dashboard_output: Optional[SqlDashbo... | SqlOutput |
python | PyCQA__pylint | tests/functional/n/non/non_iterator_returned.py | {
"start": 197,
"end": 337
} | class ____:
""" yields in iterator. """
def __iter__(self):
for index in range(10):
yield index
| FirstGoodIterator |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 312735,
"end": 319073
} | class ____(ExternKernel):
predicate: Optional[IRNode] = None
operands: Optional[Sequence[IRNode]] = None
true_subgraph: Optional[Subgraph] = None
false_subgraph: Optional[Subgraph] = None
outputs: Optional[Sequence[MultiOutput]] = None
def __init__(
self,
predicate: IRNode,
... | Conditional |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/custom_nest_trace_type_test.py | {
"start": 991,
"end": 1655
} | class ____(trace.TraceType):
def __init__(self, obj):
self._object = obj
def is_subtype_of(self, other):
return self._object == 2 and other._object == 3
def most_specific_common_supertype(self, others):
if not others:
return self
if self._object == 2 and isinstance(others[0]._object, int... | MockSupertypes2With3 |
python | agronholm__apscheduler | src/apscheduler/_exceptions.py | {
"start": 1230,
"end": 1389
} | class ____(Exception):
"""
Raised by :meth:`~Scheduler.get_job_result` if the job failed to
start within the allotted time.
"""
| JobDeadlineMissed |
python | python-excel__xlwt | xlwt/Formatting.py | {
"start": 1680,
"end": 4865
} | class ____(object):
ESCAPEMENT_NONE = 0x00
ESCAPEMENT_SUPERSCRIPT = 0x01
ESCAPEMENT_SUBSCRIPT = 0x02
UNDERLINE_NONE = 0x00
UNDERLINE_SINGLE = 0x01
UNDERLINE_SINGLE_ACC = 0x21
UNDERLINE_DOUBLE = 0x02
UNDERLINE_DOUBLE_ACC = 0x22
FAMILY_NONE ... | Font |
python | etianen__django-reversion | tests/test_app/tests/test_models.py | {
"start": 5993,
"end": 6857
} | class ____(TestModelMixin, TestBase):
databases = {"default", "mysql", "postgres"}
def testGetForObjectReferenceModelDb(self):
with reversion.create_revision():
obj = TestModel.objects.db_manager("postgres").create()
self.assertEqual(Version.objects.get_for_object_reference(TestMode... | GetForObjectReferenceModelDbTest |
python | django__django | tests/model_formsets/models.py | {
"start": 6161,
"end": 6327
} | class ____(models.Model):
name = models.CharField(max_length=255, primary_key=True)
parent = models.ForeignKey(UUIDPKParent, models.CASCADE)
| ChildWithEditablePK |
python | ray-project__ray | python/ray/llm/tests/serve/cpu/deployments/test_prefix_aware_request_router.py | {
"start": 5544,
"end": 8970
} | class ____:
"""Tests that exercise actual prefix-aware request routing logic."""
@pytest.mark.asyncio
async def test_high_match_rate_selects_matching_replica(
self, prefix_request_router
):
"""High match rate → use matched replica instead of Pow2."""
r1 = FakeRunningReplica("r1"... | TestPrefixAwareLogic |
python | docker__docker-py | docker/api/daemon.py | {
"start": 77,
"end": 6008
} | class ____:
@utils.minimum_version('1.25')
def df(self):
"""
Get data usage information.
Returns:
(dict): A dictionary representing different resource categories
and their respective data usage.
Raises:
:py:class:`docker.errors.APIError`
... | DaemonApiMixin |
python | PrefectHQ__prefect | tests/test_settings.py | {
"start": 26977,
"end": 28051
} | class ____:
def test_setting_equality_with_value(self):
with temporary_settings({PREFECT_TEST_SETTING: "foo"}):
assert PREFECT_TEST_SETTING == "foo"
assert PREFECT_TEST_SETTING != "bar"
def test_setting_equality_with_self(self):
assert PREFECT_TEST_SETTING == PREFECT_TES... | TestSettingClass |
python | readthedocs__readthedocs.org | readthedocs/core/views/__init__.py | {
"start": 4952,
"end": 5820
} | class ____(View):
"""Just a 404 view that ignores all URL parameters."""
def get(self, request, *args, **kwargs):
raise Http404()
def do_not_track(request):
dnt_header = request.headers.get("Dnt")
# https://w3c.github.io/dnt/drafts/tracking-dnt.html#status-representation
return JsonRespo... | PageNotFoundView |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_assets.py | {
"start": 39639,
"end": 43275
} | class ____(TestAssets):
@provide_session
def test_should_respond_200(self, test_client, session):
self.create_assets(num=1)
assert session.query(AssetModel).count() == 1
tz_datetime_format = from_datetime_to_zulu_without_ms(DEFAULT_DATE)
with assert_queries_count(6):
... | TestGetAssetEndpoint |
python | astropy__astropy | astropy/cosmology/_src/tests/flrw/test_parameters.py | {
"start": 9018,
"end": 10919
} | class ____(ParameterTestMixin):
"""Tests for `astropy.cosmology.Parameter` Neff on a Cosmology.
Neff is a descriptor, which are tested by mixin, here with ``TestFLRW``.
These tests expect dicts ``_cls_args`` and ``cls_kwargs`` which give the
args and kwargs for the cosmology class, respectively. See ``... | ParameterNeffTestMixin |
python | huggingface__transformers | tests/models/hgnet_v2/test_modeling_hgnet_v2.py | {
"start": 1124,
"end": 6118
} | class ____:
def __init__(
self,
parent,
batch_size=3,
image_size=32,
num_channels=3,
embeddings_size=10,
hidden_sizes=[64, 128, 256, 512],
stage_in_channels=[16, 64, 128, 256],
stage_mid_channels=[16, 32, 64, 128],
stage_out_channels=[6... | HGNetV2ModelTester |
python | kamyu104__LeetCode-Solutions | Python/binary-tree-postorder-traversal.py | {
"start": 182,
"end": 1212
} | class ____(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
dummy = TreeNode(0)
dummy.left = root
result, cur = [], dummy
while cur:
if cur.left is None:
cur = cur.right
... | Solution |
python | astropy__astropy | astropy/modeling/tests/test_input.py | {
"start": 10982,
"end": 16303
} | class ____:
"""
A suite of tests to check various cases of parameter and input combinations
on models with n_input = n_output = 1 on a toy model with n_models=1.
Many of these tests mirror test cases in
``astropy.modeling.tests.test_parameters.TestParameterInitialization``,
except that this tes... | TestSingleInputSingleOutputSingleModel |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/random/random_index_shuffle_test.py | {
"start": 1392,
"end": 4802
} | class ____(test.TestCase, parameterized.TestCase):
@parameterized.parameters(
itertools.product(_SEEDS, _DTYPES, _MAX_INDEX, _DTYPES, _ROUNDS))
def testRawOp(self, seed, seed_dtype, max_index, index_dtype, rounds):
if max_index > 200:
self.skipTest('Too slow in graph mode.')
seen = (max_index +... | StatelessOpsTest |
python | keras-team__keras | keras/src/losses/losses_test.py | {
"start": 65610,
"end": 69780
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(
losses.CategoricalFocalCrossentropy(name="cfce")
)
def test_all_correct_unweighted(self):
y_true = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype="int64")
y_pred = np.array(
... | CategoricalFocalCrossentropyTest |
python | cython__cython | Cython/Debugger/libcython.py | {
"start": 26915,
"end": 32167
} | class ____(CythonCommand):
"""
Set a breakpoint for Cython code using Cython qualified name notation, e.g.:
cy break cython_modulename.ClassName.method_name...
or normal notation:
cy break function_or_method_name...
or for a line number:
cy break cython_module:lineno...
... | CyBreak |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_identity_test.py | {
"start": 11955,
"end": 23854
} | class ____(
linear_operator_test_util.SquareLinearOperatorDerivedClassTest):
"""Most tests done in the base class LinearOperatorDerivedClassTest."""
def tearDown(self):
config.enable_tensor_float_32_execution(self.tf32_keep_)
def setUp(self):
self.tf32_keep_ = config.tensor_float_32_execution_enable... | LinearOperatorScaledIdentityTest |
python | keras-team__keras | keras/src/backend/common/keras_tensor_test.py | {
"start": 246,
"end": 16398
} | class ____(testing.TestCase):
def test_attributes(self):
x = keras_tensor.KerasTensor(shape=(3,), dtype="float32", sparse=True)
self.assertEqual(x.dtype, "float32")
self.assertEqual(x.shape, (3,))
self.assertEqual(x.sparse, True)
# Raise error if trying to set attributes
... | KerasTensorTest |
python | pydantic__pydantic | pydantic/v1/networks.py | {
"start": 4554,
"end": 11890
} | class ____(str):
strip_whitespace = True
min_length = 1
max_length = 2**16
allowed_schemes: Optional[Collection[str]] = None
tld_required: bool = False
user_required: bool = False
host_required: bool = True
hidden_parts: Set[str] = set()
__slots__ = ('scheme', 'user', 'password', 'h... | AnyUrl |
python | keras-team__keras | keras/src/layers/merging/subtract.py | {
"start": 167,
"end": 2684
} | class ____(Merge):
"""Performs elementwise subtraction.
It takes as input a list of tensors of size 2 both of the
same shape, and returns a single tensor (inputs[0] - inputs[1])
of same shape.
Examples:
>>> input_shape = (2, 3, 4)
>>> x1 = np.random.rand(*input_shape)
>>> x2 = np.rand... | Subtract |
python | scipy__scipy | scipy/linalg/tests/test_decomp_update.py | {
"start": 47761,
"end": 66231
} | class ____(BaseQRdeltas):
def generate(self, type, mode='full', p=1):
a, q, r = super().generate(type, mode)
rng = np.random.default_rng(1234)
if p == 1:
u = rng.random(q.shape[0])
v = rng.random(r.shape[1])
else:
u = rng.random((q.shape[0], p))
... | BaseQRupdate |
python | optuna__optuna | tests/storages_tests/rdb_tests/test_models.py | {
"start": 9086,
"end": 10716
} | class ____:
@staticmethod
def test_find_by_trial_and_key(session: Session) -> None:
study = StudyModel(study_id=1, study_name="test-study")
trial = TrialModel(study_id=study.study_id)
session.add(
TrialSystemAttributeModel(trial_id=trial.trial_id, key="sample-key", value_jso... | TestTrialSystemAttributeModel |
python | getsentry__sentry | src/sentry/replays/_case_studies/INC_1184_consumer_backlog_from_increased_threads/report.py | {
"start": 978,
"end": 1242
} | class ____:
def __init__(self, step):
self.step = step
self.produced_count = 0
def submit(self):
self.step.submit(Message(Value(None, {}, None)))
self.produced_count += 1
def poll(self):
self.step.poll()
| Producer |
python | lepture__authlib | authlib/oauth2/rfc6749/errors.py | {
"start": 5307,
"end": 5752
} | class ____(OAuth2Error):
"""The resource owner or authorization server denied the request.
Used in authorization endpoint for "code" and "implicit". Defined in
`Section 4.1.2.1`_.
.. _`Section 4.1.2.1`: https://tools.ietf.org/html/rfc6749#section-4.1.2.1
"""
error = "access_denied"
descri... | AccessDeniedError |
python | google__jax | tests/multiprocess_gpu_test.py | {
"start": 7404,
"end": 19296
} | class ____(jtu.JaxTestCase):
def sorted_devices(self):
devices = sorted(jax.devices(), key=lambda d: (d.id, d.host_id))
if len(devices) != 16:
raise unittest.SkipTest(
"Test assumes that it runs on 16 devices (2 nodes)")
return devices
def create_2d_non_contiguous_mesh(self):
devic... | SlurmMultiNodeGpuTest |
python | eventlet__eventlet | eventlet/dagpool.py | {
"start": 273,
"end": 583
} | class ____(Exception):
"""
DAGPool raises Collision when you try to launch two greenthreads with the
same key, or post() a result for a key corresponding to a greenthread, or
post() twice for the same key. As with KeyError, str(collision) names the
key in question.
"""
pass
| Collision |
python | spack__spack | lib/spack/spack/relocate_text.py | {
"start": 1935,
"end": 3726
} | class ____:
"""Base class for applying a prefix to prefix map to a list of binaries or text files. Derived
classes implement _apply_to_file to do the actual work, which is different when it comes to
binaries and text files."""
def __init__(self, prefix_to_prefix: Dict[bytes, bytes]) -> None:
""... | PrefixReplacer |
python | pytorch__pytorch | test/quantization/jit/test_ondevice_quantization.py | {
"start": 935,
"end": 1481
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv2d(3, 5, 3)
weight = torch.nn.Parameter(torch.ones(5, 5))
self.weight1 = torch.nn.Parameter(torch.ones(5, 5))
self.mymod = myMod(weight)
def forward(self, x):
con... | MyConvLinearModule |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 115587,
"end": 115715
} | class ____:
xlSortColumns = 1 # from enum XlSortOrientation
xlSortRows = 2 # from enum XlSortOrientation
| SortOrientation |
python | encode__django-rest-framework | tests/test_api_client.py | {
"start": 4865,
"end": 5130
} | class ____(APIView):
parser_classes = [FileUploadParser]
def post(self, request):
return Response({
'method': request.method,
'files': _get_files(request),
'content_type': request.content_type
})
| UploadView |
python | mitmproxy__pdoc | test/testdata/top_level_reimports/_internal.py | {
"start": 0,
"end": 44
} | class ____:
class FooSub:
pass
| Foo |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 8115,
"end": 8248
} | class ____(BaseException):
"""
Base type for signal-like exceptions that should never be caught by users.
"""
| PrefectSignal |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_tp_integration.py | {
"start": 2412,
"end": 17714
} | class ____(FSDPTest):
def _get_params_and_sharding_info(
self,
model: SimpleModel,
sharded_param_names: list[str],
tensor_parallel_size: int,
) -> tuple[dict[str, int], dict[str, tuple[torch.Size, int]]]:
""" """
assert type(model) is SimpleModel, (
"E... | TestTPFSDPIntegration |
python | readthedocs__readthedocs.org | readthedocs/aws/tests/test_security_token_service.py | {
"start": 822,
"end": 10979
} | class ____(TestCase):
def setUp(self):
self.user = get(User)
self.project = get(
Project,
slug="project",
users=[self.user],
)
self.version = self.project.versions.first()
self.build = get(
Build,
version=self.versio... | TestSecurityTokenService |
python | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/hooks/test_kubernetes.py | {
"start": 2978,
"end": 33532
} | class ____:
# TODO: Potential performance issue, converted setup_class to a setup_connections function level fixture
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
"""Create test connections for Kubernetes hook tests."""
import json
connecti... | TestKubernetesHook |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_requests/users_request_builder.py | {
"start": 300,
"end": 1546
} | class ____(ZendeskSupportBaseRequestBuilder):
@classmethod
def endpoint(cls, authenticator: Authenticator) -> "UsersRequestBuilder":
return cls("d3v-airbyte", "incremental/users/cursor.json").with_authenticator(authenticator)
def __init__(self, subdomain: str, resource: str) -> None:
super(... | UsersRequestBuilder |
python | getsentry__sentry | src/sentry/api/endpoints/project_rule_details.py | {
"start": 2221,
"end": 4656
} | class ____(serializers.Serializer):
name = serializers.CharField(max_length=256, help_text="The name for the rule.")
actionMatch = serializers.ChoiceField(
choices=(
("all", "All conditions must evaluate to true."),
("any", "At least one of the conditions must evaluate to true.")... | ProjectRuleDetailsPutSerializer |
python | PrefectHQ__prefect | src/prefect/client/orchestration/_artifacts/client.py | {
"start": 8414,
"end": 9725
} | class ____(BaseClient):
def read_latest_artifacts(
self, **kwargs: Unpack["ArtifactCollectionReadParams"]
) -> list["ArtifactCollection"]:
response = self.request(
"POST",
"/artifacts/latest/filter",
json={
"artifacts": (
ar... | ArtifactCollectionClient |
python | huggingface__transformers | tests/models/perception_lm/test_modeling_perception_lm.py | {
"start": 5886,
"end": 14540
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
"""
Model tester for `PerceptionLMForConditionalGeneration`.
"""
all_model_classes = (
(
PerceptionLMModel,
PerceptionLMForConditionalGeneration,
)
if is_torch_available()
els... | PerceptionLMForConditionalGenerationModelTest |
python | doocs__leetcode | solution/0000-0099/0094.Binary Tree Inorder Traversal/Solution2.py | {
"start": 192,
"end": 560
} | class ____:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
ans, stk = [], []
while root or stk:
if root:
stk.append(root)
root = root.left
else:
root = stk.pop()
ans.append(root.val)
... | Solution |
python | pypa__setuptools | setuptools/command/install_scripts.py | {
"start": 205,
"end": 2490
} | class ____(orig.install_scripts):
"""Do normal script install, plus any egg_info wrapper scripts"""
distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
def initialize_options(self) -> None:
orig.install_scripts.initialize_options(self)
self.... | install_scripts |
python | davidhalter__jedi | jedi/inference/context.py | {
"start": 13203,
"end": 13350
} | class ____(ValueContext):
def get_filters(self, until_position=None, origin_scope=None):
return self._value.get_filters()
| CompiledContext |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 12753,
"end": 12939
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = ("COMMENTS", "CREATED_AT", "UPDATED_AT")
| IssueOrderField |
python | pallets__markupsafe | tests/test_escape.py | {
"start": 1044,
"end": 1635
} | class ____:
def __init__(self, value: t.Any) -> None:
self.__value = value
@property # type: ignore[misc]
def __class__(self) -> type[t.Any]:
# Make o.__class__ and isinstance(o, str) see the proxied object.
return self.__value.__class__ # type: ignore[no-any-return]
def __st... | Proxy |
python | doocs__leetcode | solution/1600-1699/1626.Best Team With No Conflicts/Solution2.py | {
"start": 0,
"end": 361
} | class ____:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
def update(self, x, val):
while x <= self.n:
self.c[x] = max(self.c[x], val)
x += x & -x
def query(self, x):
s = 0
while x:
s = max(s, self.c[x])
x -... | BinaryIndexedTree |
python | kamyu104__LeetCode-Solutions | Python/design-front-middle-back-queue.py | {
"start": 50,
"end": 1493
} | class ____(object):
def __init__(self):
self.__left, self.__right = collections.deque(), collections.deque()
def pushFront(self, val):
"""
:type val: int
:rtype: None
"""
self.__left.appendleft(val)
self.__balance()
def pushMiddle(self, v... | FrontMiddleBackQueue |
python | geekcomputers__Python | PongPong_Game/pongpong.py | {
"start": 523,
"end": 1833
} | class ____(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(PongPongWindow, self).__init__(*args, **kwargs)
self.win_size = (WIDTH, HEIGHT)
self.paddle_pos = (WIDTH / 2 - PWIDTH / 2, 0)
self.main_batch = pyglet.graphics.Batch()
self.walls = load.load_rectang... | PongPongWindow |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_constant_value_op_test.py | {
"start": 1114,
"end": 13214
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
@parameterized.parameters(
#=========================================================================
# 0-dimensional tensors.
dict(pylist='x', expected_shape=()),
#==============================... | RaggedConstantValueOpTest |
python | tensorflow__tensorflow | tensorflow/python/framework/ops.py | {
"start": 62180,
"end": 65601
} | class ____(object):
"""A decorator for registering the gradient function for an op type.
This decorator is only used when defining a new op type. For an op
with `m` inputs and `n` outputs, the gradient function is a function
that takes the original `Operation` and `n` `Tensor` objects
(representing the gradi... | RegisterGradient |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_column05.py | {
"start": 315,
"end": 1343
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_column05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.go... | TestCompareXLSXFiles |
python | huggingface__transformers | src/transformers/models/deepseek_v3/modular_deepseek_v3.py | {
"start": 13369,
"end": 13472
} | class ____(LlamaModel):
_keys_to_ignore_on_load_unexpected = [r"model\.layers\.61.*"]
| DeepseekV3Model |
python | ray-project__ray | python/ray/util/client/common.py | {
"start": 25777,
"end": 31367
} | class ____:
"""
Cache for blocking method calls. Needed to prevent retried requests from
being applied multiple times on the server, for example when the client
disconnects. This is used to cache requests/responses sent through
unary-unary RPCs to the RayletServicer.
Note that no clean up logic... | ResponseCache |
python | neetcode-gh__leetcode | python/0621-task-scheduler.py | {
"start": 0,
"end": 640
} | class ____:
def leastInterval(self, tasks: List[str], n: int) -> int:
count = Counter(tasks)
maxHeap = [-cnt for cnt in count.values()]
heapq.heapify(maxHeap)
time = 0
q = deque() # pairs of [-cnt, idleTime]
while maxHeap or q:
time += 1
if ... | Solution |
python | buildout__buildout | src/zc/buildout/testing.py | {
"start": 7042,
"end": 7250
} | class ____(zc.buildout.buildout.Options):
def __init__(self, *args):
zc.buildout.buildout.Options.__init__(self, *args)
self._created = []
def initialize(self):
pass
| TestOptions |
python | doocs__leetcode | solution/0300-0399/0320.Generalized Abbreviation/Solution2.py | {
"start": 0,
"end": 550
} | class ____:
def generateAbbreviations(self, word: str) -> List[str]:
n = len(word)
ans = []
for i in range(1 << n):
cnt = 0
s = []
for j in range(n):
if i >> j & 1:
cnt += 1
else:
if c... | Solution |
python | huggingface__transformers | src/transformers/models/esm/modeling_esm.py | {
"start": 16646,
"end": 17010
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.dense(hidden_states)
hidden_states = gelu(hidden_states... | EsmIntermediate |
python | allegroai__clearml | clearml/backend_api/services/v2_23/frames.py | {
"start": 111307,
"end": 114649
} | class ____(Request):
"""
Get a specific frame for a dataset version using the frame's id. Random Access API.
:param dataset: Dataset id
:type dataset: str
:param version: Version id
:type version: str
:param frame: Frame id
:type frame: str
:param projection: Used to select which pa... | GetByIdRequest |
python | charliermarsh__ruff | crates/ruff_python_parser/resources/valid/statement/class.py | {
"start": 171,
"end": 331
} | class ____(A, B):
def __init__(self):
pass
def method_with_default(self, arg='default'):
pass
# Class with generic types:
# TypeVar
| Test |
python | pypa__virtualenv | src/virtualenv/create/describe.py | {
"start": 2884,
"end": 3154
} | class ____(Describe, ABC):
@classmethod
def can_describe(cls, interpreter):
return interpreter.os == "nt" and super().can_describe(interpreter)
__all__ = [
"Describe",
"PosixSupports",
"Python3Supports",
"WindowsSupports",
]
| WindowsSupports |
python | tensorflow__tensorflow | tensorflow/python/framework/convert_to_constants.py | {
"start": 27144,
"end": 29514
} | class ____(object):
"""Container for constant conversion supporting data.
The data includes the graph being converted, and the pre-converted
tensors. This class will be specialized for ConcreteFunction and Session-based
conversions, as the means to obtain that data is different for each case.
"""
def __in... | _ConverterData |
python | astropy__astropy | astropy/io/ascii/html.py | {
"start": 462,
"end": 697
} | class ____(str):
"""
Allows for strings to hold BeautifulSoup data.
"""
def __new__(cls, *args, **kwargs):
return str.__new__(cls, *args, **kwargs)
def __init__(self, val):
self.soup = val
| SoupString |
python | faif__python-patterns | patterns/other/blackboard.py | {
"start": 1369,
"end": 2023
} | class ____:
"""The controller that manages the blackboard system."""
def __init__(self, blackboard: Blackboard) -> None:
self.blackboard = blackboard
def run_loop(self):
"""
This function is a loop that runs until the progress reaches 100.
It checks if an expert is eager to... | Controller |
python | huggingface__transformers | src/transformers/models/qwen3_next/modular_qwen3_next.py | {
"start": 27453,
"end": 27497
} | class ____(Qwen3MoeMLP):
pass
| Qwen3NextMLP |
python | conda__conda | conda/core/path_actions.py | {
"start": 26370,
"end": 27318
} | class ____(CompileMultiPycAction):
"""Bunch up all of our compile actions, so that they all get carried out at once.
This avoids clobbering and is faster when we have several individual packages requiring
compilation.
"""
def __init__(self, *individuals, **kw):
transaction_context = individ... | AggregateCompileMultiPycAction |
python | pypa__pipenv | pipenv/patched/pip/_vendor/distlib/locators.py | {
"start": 35003,
"end": 36706
} | class ____(Locator):
"""
This locator uses special extended metadata (not available on PyPI) and is
the basis of performant dependency resolution in distlib. Other locators
require archive downloads before dependencies can be determined! As you
might imagine, that can be slow.
"""
def get_d... | JSONLocator |
python | PrefectHQ__prefect | src/prefect/infrastructure/provisioners/ecs.py | {
"start": 29146,
"end": 34757
} | class ____:
def __init__(self, work_pool_name: str, repository_name: str = "prefect-flows"):
self._ecr_client = boto3.client("ecr")
self._repository_name = repository_name
self._requires_provisioning = None
self._work_pool_name = work_pool_name
self._next_steps: list[str | Pa... | ContainerRepositoryResource |
python | encode__django-rest-framework | tests/schemas/test_coreapi.py | {
"start": 18292,
"end": 18598
} | class ____(APIView):
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get(self, *args, **kwargs):
pass
@unittest.skipUnless(coreapi, 'coreapi is not installed')
@override_settings(REST_FRAMEWORK={'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.AutoSchema'})
| ExampleDetailView |
python | Textualize__textual | src/textual/app.py | {
"start": 6523,
"end": 6635
} | class ____(ScreenError):
"""Raised when trying to manipulate the screen stack incorrectly."""
| ScreenStackError |
python | pandas-dev__pandas | pandas/tests/arrays/test_ndarray_backed.py | {
"start": 260,
"end": 2332
} | class ____:
def test_empty_categorical(self):
ci = CategoricalIndex(["a", "b", "c"], ordered=True)
dtype = ci.dtype
# case with int8 codes
shape = (4,)
result = Categorical._empty(shape, dtype=dtype)
assert isinstance(result, Categorical)
assert result.shape ... | TestEmpty |
python | pennersr__django-allauth | allauth/mfa/recovery_codes/views.py | {
"start": 766,
"end": 1997
} | class ____(FormView):
form_class = GenerateRecoveryCodesForm
template_name = "mfa/recovery_codes/generate." + account_settings.TEMPLATE_EXTENSION
success_url = reverse_lazy("mfa_view_recovery_codes")
def form_valid(self, form):
flows.generate_recovery_codes(self.request)
return super().... | GenerateRecoveryCodesView |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-directory/source_google_directory/source.py | {
"start": 159,
"end": 226
} | class ____(BaseSource):
client_class = Client
| SourceGoogleDirectory |
python | simonw__datasette | datasette/views/special.py | {
"start": 21673,
"end": 27054
} | class ____(BaseView):
name = "create_token"
has_json_alternate = False
def check_permission(self, request):
if not self.ds.setting("allow_signed_tokens"):
raise Forbidden("Signed tokens are not enabled for this Datasette instance")
if not request.actor:
raise Forbidd... | CreateTokenView |
python | scrapy__scrapy | tests/test_dupefilters.py | {
"start": 756,
"end": 954
} | class ____(RFPDupeFilter):
@classmethod
def from_crawler(cls, crawler):
df = super().from_crawler(crawler)
df.method = "from_crawler"
return df
| FromCrawlerRFPDupeFilter |
python | huggingface__transformers | src/transformers/models/cohere/modeling_cohere.py | {
"start": 17772,
"end": 20923
} | class ____(CoherePreTrainedModel):
def __init__(self, config: CohereConfig):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self.lay... | CohereModel |
python | pytorch__pytorch | torch/_lazy/extract_compiled_graph.py | {
"start": 1853,
"end": 8453
} | class ____:
r"""
When ltc_sync_multi is called on multi tensors, the compiled graph
will contain output only for unique tensors - if a tensor appears multiple
times in the input to _ltc_sync_multi, only the first occurrence matters.
However from python level, we still expect multi tensors returned ... | ReturnValueHandler |
python | scipy__scipy | benchmarks/benchmarks/signal_filtering.py | {
"start": 278,
"end": 799
} | class ____(Benchmark):
param_names = ['q', 'ftype', 'zero_phase']
params = [
[2, 10, 30],
['iir', 'fir'],
[True, False]
]
def setup(self, q, ftype, zero_phase):
np.random.seed(123456)
sample_rate = 10000.
t = np.arange(int(1e6), dtype=np.float64) / sample... | Decimate |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1248721,
"end": 1248970
} | class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData):
"""Audit log entry for a org.config.enable_collaborators_only event."""
__schema__ = github_schema
__field_names__ = ()
| OrgConfigEnableCollaboratorsOnlyAuditEntry |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.