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 | ansible__ansible | lib/ansible/executor/powershell/module_manifest.py | {
"start": 1453,
"end": 1643
} | class ____:
name: str
params: dict[str, object] = dataclasses.field(default_factory=dict)
secure_params: dict[str, object] = dataclasses.field(default_factory=dict)
| _ManifestAction |
python | FactoryBoy__factory_boy | factory/declarations.py | {
"start": 25109,
"end": 26665
} | class ____(PostGenerationDeclaration):
"""Calls a method of the generated object.
Attributes:
method_name (str): the method to call
method_args (list): arguments to pass to the method
method_kwargs (dict): keyword arguments to pass to the method
Example:
class UserFactory(f... | PostGenerationMethodCall |
python | gevent__gevent | src/greentest/3.12/test_interpreters.py | {
"start": 2011,
"end": 4011
} | class ____(TestBase):
def test_in_main(self):
interp = interpreters.create()
self.assertIsInstance(interp, interpreters.Interpreter)
self.assertIn(interp, interpreters.list_all())
def test_in_thread(self):
lock = threading.Lock()
interp = None
def f():
... | CreateTests |
python | pytorch__pytorch | test/test_indexing.py | {
"start": 87998,
"end": 98299
} | class ____(TestCase):
def test_index_no_floats(self, device):
a = torch.tensor([[[5.0]]], device=device)
self.assertRaises(IndexError, lambda: a[0.0])
self.assertRaises(IndexError, lambda: a[0, 0.0])
self.assertRaises(IndexError, lambda: a[0.0, 0])
self.assertRaises(IndexErr... | NumpyTests |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/_textfont.py | {
"start": 233,
"end": 11099
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d"
_path_str = "scatter3d.textfont"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"size",
"sizesrc",
"style",
"stylesrc",
"variant",
"variantsrc",
... | Textfont |
python | ray-project__ray | python/ray/train/v2/_internal/execution/worker_group/worker_group.py | {
"start": 3177,
"end": 32622
} | class ____(BaseWorkerGroup):
_worker_cls = RayTrainWorker
@classmethod
def create(
cls,
train_run_context: TrainRunContext,
worker_group_context: WorkerGroupContext,
callbacks: Optional[
List[Union[WorkerGroupCallback, WorkerCallback, TrainContextCallback]]
... | WorkerGroup |
python | neetcode-gh__leetcode | python/0064-minimum-path-sum.py | {
"start": 0,
"end": 490
} | class ____:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
prev = [float("inf")] * n
prev[-1] = 0
for row in range(m - 1, -1, -1):
dp = [float("inf")] * n
for col in range(n - 1, -1, -1):
if col < n - 1:
... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-gcp/tests/test_secret_manager.py | {
"start": 2125,
"end": 2939
} | class ____:
@pytest.fixture
def gcp_secret(self, gcp_credentials):
_gcp_secret = GcpSecret(
gcp_credentials=gcp_credentials, secret_name="my_secret_name"
)
return _gcp_secret
def test_write_secret(self, gcp_secret):
expected = "projects/gcp_credentials_project/se... | TestGcpSecret |
python | dask__distributed | distributed/client.py | {
"start": 3782,
"end": 4341
} | class ____(CancelledError):
key: str
reason: str
msg: str | None
def __init__(self, key: str, reason: str | None, msg: str | None = None):
self.key = key
self.reason = reason if reason else "unknown"
self.msg = msg
def __str__(self) -> str:
result = f"{self.key} can... | FutureCancelledError |
python | scipy__scipy | scipy/stats/tests/test_sampling.py | {
"start": 50070,
"end": 51908
} | class ____:
# pdf with piecewise linear function as transformed density
# with T = -1/sqrt with shift. Taken from UNU.RAN test suite
# (from file t_srou.c)
class dist:
def __init__(self, shift):
self.shift = shift
self.mode = shift
def pdf(self, x):
x... | TestSimpleRatioUniforms |
python | pypa__hatch | tests/backend/metadata/test_core.py | {
"start": 25290,
"end": 28270
} | class ____:
def test_dynamic(self, isolation):
metadata = ProjectMetadata(
str(isolation), None, {"project": {"license-files": 9000, "dynamic": ["license-files"]}}
)
with pytest.raises(
ValueError,
match=(
"Metadata field `license-files` c... | TestLicenseFiles |
python | protocolbuffers__protobuf | python/google/protobuf/internal/descriptor_test.py | {
"start": 25861,
"end": 26054
} | class ____(DescriptorTest):
"""Redo the same tests as above, but with a separate DescriptorPool."""
def GetDescriptorPool(self):
return descriptor_pool.DescriptorPool()
| NewDescriptorTest |
python | apache__airflow | providers/snowflake/tests/unit/snowflake/operators/test_snowpark.py | {
"start": 1402,
"end": 6659
} | class ____:
@mock.patch("airflow.providers.snowflake.operators.snowpark.SnowflakeHook")
def test_snowpark_operator_no_param(self, mock_snowflake_hook, dag_maker):
number = 11
with dag_maker(dag_id=TEST_DAG_ID) as dag:
def func1(session: Session):
assert session == m... | TestSnowparkOperator |
python | getsentry__sentry | tests/sentry/codecov/test_client.py | {
"start": 338,
"end": 4261
} | class ____(TestCase):
def setUp(self) -> None:
self.test_git_provider_org = "test-org"
self.test_secret = "test-secret-" + "a" * 20
self.test_timestamp = datetime.datetime.now(datetime.UTC)
self._mock_now = patch("datetime.datetime.now", return_value=self.test_timestamp)
wi... | TestCodecovApiClient |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-slack/llama_index/readers/slack/base.py | {
"start": 375,
"end": 12412
} | class ____(BasePydanticReader):
"""
Slack reader.
Reads conversations from channels. If an earliest_date is provided, an
optional latest_date can also be provided. If no latest_date is provided,
we assume the latest date is the current timestamp.
Args:
slack_token (Optional[str]): Slac... | SlackReader |
python | pytorch__pytorch | torch/_jit_internal.py | {
"start": 51307,
"end": 53544
} | class ____(pickle.Pickler):
def __init__(self, *args, tensors: list[torch.Tensor], **kwargs):
super().__init__(*args, **kwargs)
self.tensors = tensors
def persistent_id(self, obj):
if isinstance(obj, torch.Tensor):
self.tensors.append(obj)
return ""
# Sin... | _TensorExtractor |
python | pyparsing__pyparsing | examples/TAP.py | {
"start": 2055,
"end": 2540
} | class ____:
def __init__(self, results):
self.num = results.testNumber
self.passed = results.passed == "ok"
self.skipped = self.todo = False
if results.directive:
self.skipped = results.directive[0][0] == "SKIP"
self.todo = results.directive[0][0] == "TODO"
... | TAPTest |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_checkbox05.py | {
"start": 350,
"end": 5146
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("checkbox05.xlsx")
def test_create_file_with_insert_checkbox(self):
"""Test the creation of a simple XlsxWriter file."""
workbook =... | TestCompareXLSXFiles |
python | etianen__django-reversion | tests/test_app/models.py | {
"start": 1892,
"end": 2141
} | class ____(models.Model):
test_model_inline = models.ForeignKey(
TestModelInline,
on_delete=models.CASCADE,
)
nested_inline_name = models.CharField(
max_length=191,
default="v1",
)
| TestModelNestedInline |
python | facelessuser__soupsieve | tests/test_level4/test_paused.py | {
"start": 51,
"end": 931
} | class ____(util.TestCase):
"""Test paused selectors."""
MARKUP = """
<!DOCTYPE html>
<html>
<body>
<video id="vid" width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video ta... | TestPaused |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-looker/source_looker/components.py | {
"start": 289,
"end": 1910
} | class ____(NoAuth):
"""
Authenticator that sets the Authorization header on the HTTP requests sent using access token which is updated upon expiration.
The header is of the form:
`"Authorization": "token <access_token>"`
Attributes:
config (Config): The user-provided configuration as speci... | LookerAuthenticator |
python | django__django | tests/one_to_one/models.py | {
"start": 2089,
"end": 2209
} | class ____(models.Model):
other = models.OneToOneField(Target, models.CASCADE, related_name="second_pointer")
| Pointer2 |
python | ansible__ansible | test/units/module_utils/facts/test_collectors.py | {
"start": 16610,
"end": 16819
} | class ____(BaseFactsTest):
__test__ = True
gather_subset = ['!all', 'virtual']
valid_subsets = ['virtual']
fact_namespace = 'ansible_virtual'
collector_class = VirtualCollector
| TestVirtualFacts |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 73558,
"end": 74902
} | class ____(PreTrainedModel):
config = Qwen3OmniMoeTextConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen3OmniMoeThinkerTextDecoderLayer"]
_skip_keys_device_placement = ["past_key_values"]
_supports_flash_attn = True
_supports_sdpa = True
... | Qwen3OmniMoeThinkerTextPreTrainedModel |
python | apache__airflow | airflow-core/tests/unit/models/test_deadline.py | {
"start": 25929,
"end": 30483
} | class ____:
def setup_method(self):
self.original_dagrun_created = DeadlineReference.TYPES.DAGRUN_CREATED
self.original_dagrun_queued = DeadlineReference.TYPES.DAGRUN_QUEUED
self.original_dagrun = DeadlineReference.TYPES.DAGRUN
self.original_attrs = set(dir(ReferenceModels))
def... | TestDeadlineReferenceDecorator |
python | huggingface__transformers | tests/models/resnet/test_modeling_resnet.py | {
"start": 5504,
"end": 9459
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as ResNet does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (
(
ResNetModel,
Res... | ResNetModelTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/asyncio/engine.py | {
"start": 6660,
"end": 34035
} | class ____( # type:ignore[misc]
ProxyComparable[Connection],
StartableContext["AsyncConnection"],
AsyncConnectable,
):
"""An asyncio proxy for a :class:`_engine.Connection`.
:class:`_asyncio.AsyncConnection` is acquired using the
:meth:`_asyncio.AsyncEngine.connect`
method of :class:`_asyn... | AsyncConnection |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/multi_client_input_util_test.py | {
"start": 10617,
"end": 19586
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
logging.info('Check per client log in Test artifacts.')
self.server_ports = [
multi_client_test_util.pick_unused_port() for _ in range(NUM_CLIENTS)
]
self.worker_ports = [
multi_client_test_util.pick_unused... | MultiClientDTensorDatasetTest |
python | tox-dev__tox | src/tox/tox_env/errors.py | {
"start": 152,
"end": 228
} | class ____(Exception): # noqa: N818
"""Skip this tox environment."""
| Skip |
python | spyder-ide__spyder | external-deps/python-lsp-server/test/plugins/test_symbols.py | {
"start": 461,
"end": 4062
} | class ____:
def __init__(self):
x = 2
self.y = x
def main(x):
y = 2 * x
return y
"""
DOC_IMPORTS = """from . import something
from ..module import something
from module import (a, b)
def main():
# import ignored
print("from module import x") # string with import
return somet... | B |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 10457,
"end": 10687
} | class ____(_GenerativeProvider):
module_config: Optional[Dict[str, Any]]
def _to_dict(self) -> Dict[str, Any]:
if self.module_config is None:
return {}
return self.module_config
| _GenerativeCustom |
python | numba__numba | numba/cuda/tests/cudadrv/test_cuda_array_slicing.py | {
"start": 2821,
"end": 8015
} | class ____(CUDATestCase):
def test_prefix_1d(self):
arr = np.arange(5)
darr = cuda.to_device(arr)
for i in range(arr.size):
expect = arr[i:]
got = darr[i:].copy_to_host()
self.assertTrue(np.all(expect == got))
def test_prefix_2d(self):
arr = n... | CudaArraySlicing |
python | sympy__sympy | sympy/physics/optics/medium.py | {
"start": 3869,
"end": 4484
} | class ____(Medium):
"""
Represents an optical medium for which only the refractive index is known.
Useful for simple ray optics.
This class should never be instantiated directly.
Instead it should be instantiated indirectly by instantiating Medium with
only n specified.
Examples
=====... | MediumN |
python | PyCQA__pycodestyle | testing/data/W29.py | {
"start": 337,
"end": 403
} | class ____(object):
def __repr__(self):
return 'test'
| Test |
python | huggingface__transformers | tests/models/oneformer/test_modeling_oneformer.py | {
"start": 19400,
"end": 25602
} | class ____(unittest.TestCase):
@cached_property
def model_checkpoints(self):
return "shi-labs/oneformer_ade20k_swin_tiny"
@cached_property
def default_processor(self):
return OneFormerProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None
def test_infe... | OneFormerModelIntegrationTest |
python | lepture__authlib | authlib/oauth2/rfc6749/errors.py | {
"start": 6708,
"end": 6826
} | class ____(OAuth2Error):
error = "missing_code"
description = "Missing 'code' in response."
| MissingCodeException |
python | ansible__ansible | test/lib/ansible_test/_internal/commands/integration/cloud/galaxy.py | {
"start": 5094,
"end": 6211
} | class ____(CloudEnvironment):
"""Galaxy environment plugin. Updates integration test environment after delegation."""
def get_environment_config(self) -> CloudEnvironmentConfig:
"""Return environment configuration for use in the test environment after delegation."""
pulp_user = str(self._get_cl... | GalaxyEnvironment |
python | falconry__falcon | falcon/redirects.py | {
"start": 4820,
"end": 5564
} | class ____(HTTPStatus):
"""308 Permanent Redirect.
The 308 (Permanent Redirect) status code indicates that the target
resource has been assigned a new permanent URI.
Note:
This status code is similar to 301 (Moved Permanently), except
that it does not allow changing the request method ... | HTTPPermanentRedirect |
python | sphinx-doc__sphinx | sphinx/errors.py | {
"start": 860,
"end": 977
} | class ____(SphinxError):
"""Warning, treated as error."""
category = 'Warning, treated as error'
| SphinxWarning |
python | huggingface__transformers | src/transformers/models/gpt_oss/modular_gpt_oss.py | {
"start": 13695,
"end": 15570
} | class ____(LlamaDecoderLayer):
def __init__(self, config: GptOssConfig, layer_idx: int):
super().__init__(config, layer_idx)
self.hidden_size = config.hidden_size
self.self_attn = GptOssAttention(config=config, layer_idx=layer_idx)
self.mlp = GptOssMLP(config)
self.input_laye... | GptOssDecoderLayer |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 165901,
"end": 166494
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("enterprise_id", "setting_value", "client_mutation_id")
enterprise_id = sgqlc.types.Field(
sgqlc.types.non_null(ID), graphql_name="enterpriseId"
)
setting_value =... | UpdateEnterpriseMembersCanMakePurchasesSettingInput |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/nn_functional.py | {
"start": 39031,
"end": 44749
} | class ____(Operator):
"""Operator for torch.nn.functional.multi_head_attention_forward."""
def __init__(self):
super().__init__("torch.nn.functional.multi_head_attention_forward")
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "to... | MultiHeadAttentionForwardOperator |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 5900,
"end": 14967
} | class ____(TimeSeriesBaseModel, ObjectBaseModel, Generic[R]):
"""
The state of a run.
"""
type: StateType
name: Optional[str] = Field(default=None)
timestamp: datetime.datetime = Field(default_factory=lambda: now("UTC"))
message: Optional[str] = Field(default=None, examples=["Run started"])... | State |
python | pandas-dev__pandas | asv_bench/benchmarks/categoricals.py | {
"start": 7082,
"end": 7409
} | class ____:
def setup(self):
N = 10**5
self.ci = pd.CategoricalIndex(np.arange(N))
self.c = self.ci.values
self.key = self.ci.categories[0]
def time_categorical_index_contains(self):
self.key in self.ci
def time_categorical_contains(self):
self.key in self.c... | Contains |
python | realpython__materials | python-unittest/test_prime_v1.py | {
"start": 49,
"end": 664
} | class ____(unittest.TestCase):
def test_prime_numbers(self):
for num in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]:
with self.subTest(num=num):
self.assertTrue(is_prime(num))
def test_non_prime_numbers(self):
for num in [-1, 0, 1, 4, 6, 8, 9, 10, 12, 15]:
with ... | TestIsPrime |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/config_types.py | {
"start": 3859,
"end": 4981
} | class ____(graphene.ObjectType):
class Meta:
interfaces = (GrapheneConfigType,)
description = "Regular is an odd name in this context. It really means Scalar or Any."
name = "RegularConfigType"
given_name = graphene.NonNull(graphene.String)
def __init__(
self,
get_c... | GrapheneRegularConfigType |
python | doocs__leetcode | solution/3300-3399/3307.Find the K-th Character in String Game II/Solution.py | {
"start": 0,
"end": 367
} | class ____:
def kthCharacter(self, k: int, operations: List[int]) -> str:
n, i = 1, 0
while n < k:
n *= 2
i += 1
d = 0
while n > 1:
if k > n // 2:
k -= n // 2
d += operations[i - 1]
n //= 2
i ... | Solution |
python | Netflix__metaflow | metaflow/plugins/cards/component_serializer.py | {
"start": 6184,
"end": 15873
} | class ____:
"""
This class manages the card's state for a single card.
- It uses the `ComponentStore` to manage the storage of the components
- It exposes methods to add, remove and access the components.
- It exposes a `refresh` method that will allow refreshing a card with new data
for realtim... | CardComponentManager |
python | huggingface__transformers | src/transformers/models/maskformer/modeling_maskformer.py | {
"start": 53088,
"end": 54543
} | class ____(nn.Module):
def __init__(self, in_features: int, out_features: int, kernel_size: int = 3, padding: int = 1):
"""
A basic module that executes conv - norm - in sequence used in MaskFormer.
Args:
in_features (`int`):
The number of input features (channel... | MaskFormerFPNConvLayer |
python | getsentry__sentry | src/sentry/apidocs/parameters.py | {
"start": 9330,
"end": 13852
} | class ____:
KEY = OpenApiParameter(
name="key",
location=OpenApiParameter.PATH,
type=OpenApiTypes.STR,
description="The tag key to look the values up for.",
required=True,
)
ISSUES_OR_GROUPS = OpenApiParameter(
name="var",
location="path",
req... | IssueParams |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_hash.py | {
"start": 606,
"end": 664
} | class ____:
def __hash__(self):
return 7741
| Hash |
python | falconry__falcon | falcon/util/sync.py | {
"start": 507,
"end": 1145
} | class ____:
def run(self, coro: Awaitable[Result]) -> Result: # pragma: nocover
# NOTE(vytas): Work around get_event_loop deprecation in 3.10 by going
# via get_event_loop_policy(). This should be equivalent for
# async_to_sync's use case as it is currently impossible to invoke
... | _DummyRunner |
python | openai__openai-python | src/openai/types/responses/response_in_progress_event.py | {
"start": 231,
"end": 518
} | class ____(BaseModel):
response: Response
"""The response that is in progress."""
sequence_number: int
"""The sequence number of this event."""
type: Literal["response.in_progress"]
"""The type of the event. Always `response.in_progress`."""
| ResponseInProgressEvent |
python | numpy__numpy | numpy/_core/tests/test_array_coercion.py | {
"start": 29462,
"end": 32504
} | class ____:
"""Test expected behaviors of ``asarray``."""
def test_dtype_identity(self):
"""Confirm the intended behavior for *dtype* kwarg.
The result of ``asarray()`` should have the dtype provided through the
keyword argument, when used. This forces unique array handles to be
... | TestAsArray |
python | python-openxml__python-docx | src/docx/oxml/simpletypes.py | {
"start": 2783,
"end": 3033
} | class ____(BaseStringType):
"""There's a regex in the spec this is supposed to meet...
but current assessment is that spending cycles on validating wouldn't be worth it
for the number of programming errors it would catch.
"""
| XsdAnyUri |
python | geekcomputers__Python | Sorting Algorithims/mergesort_linkedlist.py | {
"start": 144,
"end": 1770
} | class ____:
def __init__(self):
self.head = None
def insert(self, new_data: int) -> None:
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printLL(self) -> None:
temp = self.head
if temp == None:
return "Linked List is... | LinkedList |
python | kamyu104__LeetCode-Solutions | Python/separate-black-and-white-balls.py | {
"start": 406,
"end": 907
} | class ____(object):
def minimumSteps(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
left, right = 0, len(s)-1
while left < right:
if left < len(s) and s[left] != '1':
left += 1
continue
if right >=... | Solution2 |
python | coleifer__peewee | playhouse/sqlite_ext.py | {
"start": 9748,
"end": 11578
} | class ____(SchemaManager):
def _create_virtual_table(self, safe=True, **options):
options = self.model.clean_options(
merge_dict(self.model._meta.options, options))
# Structure:
# CREATE VIRTUAL TABLE <model>
# USING <extension_module>
# ([prefix_arguments, ...] ... | VirtualTableSchemaManager |
python | readthedocs__readthedocs.org | readthedocs/redirects/migrations/0008_alter_redirect_position.py | {
"start": 148,
"end": 625
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("redirects", "0007_migrate_to_new_syntax"),
]
operations = [
migrations.AlterField(
model_name="redirect",
name="position",
field=models.PositiveIntegerField(
... | Migration |
python | wandb__wandb | wandb/vendor/pygments/lexers/haskell.py | {
"start": 10763,
"end": 13366
} | class ____(RegexLexer):
"""
For the `Agda <http://wiki.portal.chalmers.se/agda/pmwiki.php>`_
dependently typed functional programming language and proof assistant.
.. versionadded:: 2.0
"""
name = 'Agda'
aliases = ['agda']
filenames = ['*.agda']
mimetypes = ['text/x-agda']
res... | AgdaLexer |
python | weaviate__weaviate-python-client | weaviate/users/base.py | {
"start": 3866,
"end": 7165
} | class ____(Generic[ConnectionType], _BaseExecutor[ConnectionType]):
def get_my_user(self) -> executor.Result[OwnUser]:
"""Get the currently authenticated user.
Returns:
A user object.
"""
path = "/users/own-info"
def resp(res: Response) -> OwnUser:
p... | _UsersExecutor |
python | spack__spack | lib/spack/spack/test/llnl/util/lock.py | {
"start": 9815,
"end": 10358
} | class ____:
def __init__(self, lock_path, start=0, length=0):
self.lock_path = lock_path
self.start = start
self.length = length
@property
def __name__(self):
return self.__class__.__name__
def __call__(self, barrier):
lock = lk.Lock(self.lock_path, start=self.s... | TimeoutWrite |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/migration/incoming/main.py | {
"start": 2208,
"end": 2688
} | class ____(webapp2.RequestHandler):
allowed_app_ids = ["other-app-id", "other-app-id-2"]
def get(self):
incoming_app_id = get_app_id(self.request)
if incoming_app_id is None:
self.abort(403)
if incoming_app_id not in self.allowed_app_ids:
self.abort(403)
... | MainPage |
python | ansible__ansible | lib/ansible/plugins/filter/core.py | {
"start": 21841,
"end": 23773
} | class ____(t.NamedTuple):
"""
Custom named tuple for the groupby filter with a public interface; silently ignored by unknown type checks.
This matches the internal implementation of the _GroupTuple returned by Jinja's built-in groupby filter.
"""
grouper: t.Any
list: list[t.Any]
def __repr... | GroupTuple |
python | ray-project__ray | doc/source/ray-overview/examples/mcp-ray-serve/multi_mcp_ray_serve.py | {
"start": 3515,
"end": 5855
} | class ____:
def __init__(self, brave_search: DeploymentHandle, fetch: DeploymentHandle) -> None:
self._mcps = {"brave_search": brave_search, "fetch": fetch}
@api.get("/{mcp_name}/tools")
async def list_tools_http(self, mcp_name: str):
handle = self._mcps.get(mcp_name)
if not handle:... | Router |
python | pypa__warehouse | tests/common/db/packaging.py | {
"start": 4420,
"end": 4702
} | class ____(WarehouseFactory):
class Meta:
model = Dependency
release = factory.SubFactory(ReleaseFactory)
kind = factory.Faker(
"random_element", elements=[int(kind) for kind in DependencyKind]
)
specifier = factory.Faker("word")
| DependencyFactory |
python | huggingface__transformers | src/transformers/models/cpmant/modeling_cpmant.py | {
"start": 2188,
"end": 6687
} | class ____(nn.Module):
def __init__(self, config: CpmAntConfig, layer_idx=None):
super().__init__()
self.dim_model = config.hidden_size
self.num_heads = config.num_attention_heads
self.dim_head = config.dim_head
self.layer_idx = layer_idx
self.project_q = nn.Linear(s... | CpmAntAttention |
python | kamyu104__LeetCode-Solutions | Python/minimum-subsequence-in-non-increasing-order.py | {
"start": 33,
"end": 393
} | class ____(object):
def minSubsequence(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result, total, curr = [], sum(nums), 0
nums.sort(reverse=True)
for i, x in enumerate(nums):
curr += x
if curr > total-curr:
... | Solution |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/services/public/variables.py | {
"start": 3265,
"end": 7770
} | class ____(BulkService[VariableBody]):
"""Service for handling bulk operations on variables."""
def categorize_keys(self, keys: set) -> tuple[set, set]:
"""Categorize the given keys into matched_keys and not_found_keys based on existing keys."""
existing_keys = {variable for variable in self.se... | BulkVariableService |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_daemon_health.py | {
"start": 1737,
"end": 6276
} | class ____(ExecutingGraphQLContextTestMatrix):
def test_get_individual_daemons(self, graphql_context):
if graphql_context.instance.is_ephemeral:
pytest.skip("The daemon isn't compatible with an in-memory instance")
graphql_context.instance.add_daemon_heartbeat(
DaemonHeartbea... | TestDaemonHealth |
python | Netflix__metaflow | test/unit/inheritance/flows/mutator_with_derived_config_flow.py | {
"start": 362,
"end": 2614
} | class ____(BaseC):
"""
Flow testing FlowMutator from base class using config from derived class.
Verifies:
- Base class mutator can access derived class config
- Parameters are injected based on derived config values
- All original parameters and configs remain accessible
"""
final_par... | MutatorWithDerivedConfigFlow |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typePrinter3.py | {
"start": 42,
"end": 290
} | class ____:
class Child1:
pass
class Child2:
pass
# This should generate an error that uses fully-qualified names.
v1: A.Child1 = B.Child1()
# This should generate an error that uses simple names.
v2: A.Child1 = B.Child2()
| B |
python | sqlalchemy__sqlalchemy | test/sql/test_metadata.py | {
"start": 2747,
"end": 30742
} | class ____(fixtures.TestBase, ComparesTables):
def test_metadata_contains(self):
metadata = MetaData()
t1 = Table("t1", metadata, Column("x", Integer))
t2 = Table("t2", metadata, Column("x", Integer), schema="foo")
t3 = Table("t2", MetaData(), Column("x", Integer))
t4 = Table... | MetaDataTest |
python | donnemartin__interactive-coding-challenges | sorting_searching/merge_into/test_merge_into.py | {
"start": 18,
"end": 788
} | class ____(unittest.TestCase):
def test_merge_into(self):
array = Array()
self.assertRaises(TypeError, array.merge_into, None, None, None, None)
self.assertRaises(ValueError, array.merge_into, [1], [2], -1, -1)
a = [1, 2, 3]
self.assertEqual(array.merge_into(a, [], len(a), 0... | TestArray |
python | tensorflow__tensorflow | tensorflow/python/framework/tensor_util_test.py | {
"start": 52542,
"end": 52946
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes
def testConversion(self):
"""Make sure fully known TensorShape objects convert to Tensors."""
shape = tensor_shape.TensorShape([1, tensor_shape.Dimension(2)])
shape_tensor = shape_util.shape_tensor(shape)
self.assertA... | ShapeTensorTest |
python | kamyu104__LeetCode-Solutions | Python/longest-continuous-increasing-subsequence.py | {
"start": 29,
"end": 414
} | class ____(object):
def findLengthOfLCIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result, count = 0, 0
for i in xrange(len(nums)):
if i == 0 or nums[i-1] < nums[i]:
count += 1
result = max(result, count)
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/binary-tree-inorder-traversal.py | {
"start": 182,
"end": 956
} | class ____(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result, curr = [], root
while curr:
if curr.left is None:
result.append(curr.val)
curr = curr.right
else:
... | Solution |
python | getsentry__sentry | tests/sentry/utils/test_services.py | {
"start": 477,
"end": 566
} | class ____(Operation):
def apply(self, x: int, y: int) -> int:
return x + y
| Add |
python | wandb__wandb | wandb/sdk/launch/agent/job_status_tracker.py | {
"start": 405,
"end": 1830
} | class ____:
run_queue_item_id: str
queue: str
saver: RunQueueItemFileSaver
run_id: Optional[str] = None
project: Optional[str] = None
entity: Optional[str] = None
run: Optional[AbstractRun] = None
failed_to_start: bool = False
completed_status: Optional[str] = None
is_scheduler: ... | JobAndRunStatusTracker |
python | django-haystack__django-haystack | test_haystack/test_query.py | {
"start": 34489,
"end": 35627
} | class ____(SearchQuerySetTestCase):
def test_values_sqs(self):
sqs = self.msqs.auto_query("test").values("id")
self.assertIsInstance(sqs, ValuesSearchQuerySet)
# We'll do a basic test to confirm that slicing works as expected:
self.assertIsInstance(sqs[0], dict)
self.assertI... | ValuesQuerySetTestCase |
python | mozilla__bleach | tests/test_clean.py | {
"start": 39521,
"end": 40603
} | class ____:
def test_basics(self):
TAGS = {"span", "br"}
ATTRS = {"span": ["style"]}
cleaner = Cleaner(tags=TAGS, attributes=ATTRS)
assert (
cleaner.clean('a <br/><span style="color:red">test</span>')
== 'a <br><span style="">test</span>'
)
def ... | TestCleaner |
python | huggingface__transformers | src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py | {
"start": 25147,
"end": 31760
} | class ____(RobertaPreLayerNormPreTrainedModel):
def __init__(self, config, add_pooling_layer=True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(config)
self.config = config
self.gradien... | RobertaPreLayerNormModel |
python | pytorch__pytorch | torch/ao/pruning/scheduler/lambda_scheduler.py | {
"start": 195,
"end": 2416
} | class ____(BaseScheduler):
"""Sets the sparsity level of each parameter group to the final sl
times a given function. When last_epoch=-1, sets initial sl as zero.
Args:
sparsifier (BaseSparsifier): Wrapped sparsifier.
sl_lambda (function or list): A function which computes a multiplicative
... | LambdaSL |
python | doocs__leetcode | solution/0700-0799/0767.Reorganize String/Solution2.py | {
"start": 0,
"end": 579
} | class ____:
def reorganizeString(self, s: str) -> str:
return self.rearrangeString(s, 2)
def rearrangeString(self, s: str, k: int) -> str:
h = [(-v, c) for c, v in Counter(s).items()]
heapify(h)
q = deque()
ans = []
while h:
v, c = heappop(h)
... | Solution |
python | scikit-learn__scikit-learn | sklearn/neural_network/_stochastic_optimizers.py | {
"start": 6085,
"end": 8838
} | class ____(BaseOptimizer):
"""Stochastic gradient descent optimizer with Adam
Note: All default values are from the original Adam paper
Parameters
----------
params : list, length = len(coefs_) + len(intercepts_)
The concatenated list containing coefs_ and intercepts_ in MLP model.
... | AdamOptimizer |
python | jazzband__django-oauth-toolkit | oauth2_provider/exceptions.py | {
"start": 422,
"end": 792
} | class ____(Exception):
"""
General class to derive from for all OIDC related errors.
"""
status_code = 400
error = None
def __init__(self, description=None):
if description is not None:
self.description = description
message = "({}) {}".format(self.error, self.desc... | OIDCError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/functions.py | {
"start": 56723,
"end": 56844
} | class ____(ReturnTypeFromArgs[_T]): # noqa: A001
"""The SQL SUM() aggregate function."""
inherit_cache = True
| sum |
python | PyCQA__bandit | tests/unit/core/test_config.py | {
"start": 8565,
"end": 9748
} | class ____(TestConfigCompat):
sample = textwrap.dedent(
"""
[tool.bandit.profiles.test_1]
include = [
"any_other_function_with_shell_equals_true",
"assert_used",
]
[tool.bandit.profiles.test_2]
include = ["blacklist_calls"]
[tool.band... | TestTomlConfig |
python | mlflow__mlflow | mlflow/tracing/client.py | {
"start": 2051,
"end": 30184
} | class ____:
"""
Client of an MLflow Tracking Server that creates and manages experiments and runs.
"""
def __init__(self, tracking_uri: str | None = None):
"""
Args:
tracking_uri: Address of local or remote tracking server.
"""
self.tracking_uri = _resolve_tr... | TracingClient |
python | jazzband__django-polymorphic | src/polymorphic/formsets/generic.py | {
"start": 1754,
"end": 4184
} | class ____(BaseGenericInlineFormSet, BasePolymorphicModelFormSet):
"""
Polymorphic formset variation for inline generic formsets
"""
def generic_polymorphic_inlineformset_factory(
model,
formset_children,
form=ModelForm,
formset=BaseGenericPolymorphicInlineFormSet,
ct_field="content_ty... | BaseGenericPolymorphicInlineFormSet |
python | apache__airflow | providers/sqlite/tests/unit/sqlite/hooks/test_sqlite.py | {
"start": 3202,
"end": 7081
} | class ____:
def setup_method(self):
self.cur = mock.MagicMock(rowcount=0)
self.conn = mock.MagicMock()
self.conn.cursor.return_value = self.cur
conn = self.conn
class UnitTestSqliteHook(SqliteHook):
conn_name_attr = "test_conn_id"
log = mock.MagicMock... | TestSqliteHook |
python | kamyu104__LeetCode-Solutions | Python/rearrange-array-elements-by-sign.py | {
"start": 44,
"end": 480
} | class ____(object):
def rearrangeArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
pos, neg = 0, 1
result = [0]*len(nums)
for x in nums:
if x > 0:
result[pos] = x
pos += 2
else:
... | Solution |
python | getsentry__sentry | tests/sentry/utils/sdk_crashes/test_sdk_crash_detection.py | {
"start": 5374,
"end": 6506
} | class ____(BaseSDKCrashDetectionMixin, SnubaTestCase):
@django_db_all
def test_sdk_crash_event_stored_to_sdk_crash_project(self) -> None:
cocoa_sdk_crashes_project = self.create_project(
name="Cocoa SDK Crashes",
slug="cocoa-sdk-crashes",
teams=[self.team],
... | SDKCrashReportTestMixin |
python | ray-project__ray | python/ray/serve/_private/request_router/request_router.py | {
"start": 6753,
"end": 14413
} | class ____:
"""Mixin for multiplex routing.
This mixin is used to route requests to replicas that are multiplexed.
It adds necessary attributes and methods to keep track of multiplexed
model IDs and offer the helpers to apply multiplex routing and rank
replicas based on multiplexed model IDs.
"... | MultiplexMixin |
python | pytorch__pytorch | torch/ao/nn/quantized/reference/modules/linear.py | {
"start": 161,
"end": 2254
} | class ____(nn.Linear, ReferenceQuantizedModule):
"""A reference quantized linear module that fits into the FX
Graph Mode Quantization workflow
activation will be floating point Tensor, we will store floating
point weight as well in the module, but in forward we'll quantize
and dequantize the weight ... | Linear |
python | keras-team__keras | keras/src/quantizers/gptq_core_test.py | {
"start": 566,
"end": 831
} | class ____(layers.Layer):
"""A block that contains no quantizable layers."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.ln = layers.LayerNormalization()
def call(self, inputs):
return self.ln(inputs)
| EmptyBlock |
python | scikit-learn__scikit-learn | sklearn/model_selection/tests/test_validation.py | {
"start": 3587,
"end": 4710
} | class ____(MockImprovingEstimator):
"""Dummy classifier that provides partial_fit"""
def __init__(self, n_max_train_sizes, expected_fit_params=None):
super().__init__(n_max_train_sizes)
self.x = None
self.expected_fit_params = expected_fit_params
def _is_training_data(self, X):
... | MockIncrementalImprovingEstimator |
python | pytorch__pytorch | test/distributed/checkpoint/test_async_process_executor.py | {
"start": 7318,
"end": 10939
} | class ____(DTensorTestBase):
"""Test suite for _ProcessGroupInitInfo."""
@with_comms
def test_process_group_init_info_with_default_pg(self) -> None:
"""Test that ProcessGroupInitInfo correctly initializes."""
with patch.dict(os.environ, {}, clear=False):
os.environ.pop("DCP_USE_... | TestProcessGroupInitInfo |
python | Textualize__textual | examples/color_command.py | {
"start": 1121,
"end": 1695
} | class ____(App):
"""Experiment with the command palette."""
COMMANDS = App.COMMANDS | {ColorCommands}
TITLE = "Press ctrl + p and type a color"
def compose(self) -> ComposeResult:
yield Header()
@on(SwitchColor)
def switch_color(self, event: SwitchColor) -> None:
"""Adds a col... | ColorApp |
python | prabhupant__python-ds | data_structures/deque/deque.py | {
"start": 0,
"end": 1435
} | class ____():
def __init__(self):
self.data = list()
def push_front(self, elem):
temp = list()
temp.append(elem)
for i in self.data:
temp.append(i)
self.data = temp
def push_back(self, elem):
self.data.append(elem)
def pop_front(se... | Deque |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.