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 | huggingface__transformers | src/transformers/models/vitpose_backbone/modeling_vitpose_backbone.py | {
"start": 13863,
"end": 15101
} | class ____(PreTrainedModel):
config: VitPoseBackboneConfig
base_model_prefix = "vit"
main_input_name = "pixel_values"
input_modalities = ("image",)
supports_gradient_checkpointing = True
_no_split_modules = ["VitPoseBackboneEmbeddings", "VitPoseBackboneLayer"]
_supports_sdpa = True
_supp... | VitPoseBackbonePreTrainedModel |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/cached_property.py | {
"start": 40,
"end": 219
} | class ____:
@cached_property
def prop(self) -> int:
return 1
@cached_property
def prop_with_type_comment(self):
# type: () -> int
return 1
| Foo |
python | getsentry__sentry | tests/sentry/integrations/github/test_installation.py | {
"start": 499,
"end": 2591
} | class ____(APITestCase):
base_url = "https://api.github.com"
def setUp(self) -> None:
self.login_as(self.user)
self.url = "/extensions/github/webhook/"
self.secret = "b3002c3e321d4b7880360d397db2ccfd"
options.set("github-app.webhook-secret", self.secret)
@responses.activate... | InstallationEndpointTest |
python | sqlalchemy__sqlalchemy | test/ext/test_baked.py | {
"start": 28460,
"end": 33026
} | class ____(testing.AssertsCompiledSQL, BakedTest):
run_setup_mappers = "each"
def _o2m_fixture(self, lazy="select", **kw):
User = self.classes.User
Address = self.classes.Address
self.mapper_registry.map_imperatively(
User,
self.tables.users,
propert... | CustomIntegrationTest |
python | doocs__leetcode | solution/1300-1399/1306.Jump Game III/Solution.py | {
"start": 0,
"end": 395
} | class ____:
def canReach(self, arr: List[int], start: int) -> bool:
q = deque([start])
while q:
i = q.popleft()
if arr[i] == 0:
return True
x = arr[i]
arr[i] = -1
for j in (i + x, i - x):
if 0 <= j < len(arr)... | Solution |
python | PrefectHQ__prefect | src/prefect/server/events/actions.py | {
"start": 53829,
"end": 54274
} | class ____(WorkPoolCommandAction):
"""Resumes a Work Pool"""
type: Literal["resume-work-pool"] = "resume-work-pool"
_action_description: ClassVar[str] = "Resuming work pool"
async def command(
self,
orchestration: "OrchestrationClient",
work_pool: WorkPool,
triggered_a... | ResumeWorkPool |
python | kamyu104__LeetCode-Solutions | Python/alert-using-same-key-card-three-or-more-times-in-a-one-hour-period.py | {
"start": 71,
"end": 915
} | class ____(object):
def alertNames(self, keyName, keyTime):
"""
:type keyName: List[str]
:type keyTime: List[str]
:rtype: List[str]
"""
THRESHOLD = 3
name_to_times = collections.defaultdict(list)
for name, hour_minute in itertools.izip(keyName, keyTime... | Solution |
python | pandas-dev__pandas | pandas/tests/series/test_api.py | {
"start": 230,
"end": 9452
} | class ____:
def test_tab_completion(self):
# GH 9910
s = Series(list("abcd"))
# Series of str values should have .str but not .dt/.cat in __dir__
assert "str" in dir(s)
assert "dt" not in dir(s)
assert "cat" not in dir(s)
def test_tab_completion_dt(self):
... | TestSeriesMisc |
python | PrefectHQ__prefect | tests/cli/test_work_pool.py | {
"start": 20354,
"end": 21228
} | class ____:
async def test_ls(self, prefect_client, work_pool):
res = await run_sync_in_worker_thread(
invoke_and_assert,
"work-pool ls",
)
assert res.exit_code == 0
async def test_verbose(self, prefect_client, work_pool):
res = await run_sync_in_worker_t... | TestLS |
python | doocs__leetcode | solution/0000-0099/0057.Insert Interval/Solution2.py | {
"start": 0,
"end": 604
} | class ____:
def insert(
self, intervals: List[List[int]], newInterval: List[int]
) -> List[List[int]]:
st, ed = newInterval
ans = []
insert = False
for s, e in intervals:
if ed < s:
if not insert:
ans.append([st, ed])
... | Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-mysql/dagster_mysql_tests/test_daemon_cursor_storage.py | {
"start": 258,
"end": 551
} | class ____(TestDaemonCursorStorage):
__test__ = True
@pytest.fixture(scope="function", name="storage")
def cursor_storage(self, conn_string):
storage = MySQLRunStorage.create_clean_storage(conn_string)
assert storage
return storage
| TestMySQLDaemonCursorStorage |
python | getsentry__sentry | src/sentry/auth/providers/dummy.py | {
"start": 532,
"end": 1120
} | class ____(AuthView):
def dispatch(self, request: HttpRequest, pipeline: AuthHelper) -> HttpResponseBase:
if "email" in request.POST:
if "id" in request.POST:
pipeline.bind_state("id", request.POST.get("id"))
pipeline.bind_state("email", request.POST.get("email"))
... | AskEmail |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/cfg_test.py | {
"start": 878,
"end": 1203
} | class ____(cfg.GraphVisitor):
def __init__(self, graph):
super(CountingVisitor, self).__init__(graph)
self.counts = {}
def init_state(self, _):
return None
def visit_node(self, node):
self.counts[node.ast_node] = self.counts.get(node.ast_node, 0) + 1
return False # visit only once
| CountingVisitor |
python | ansible__ansible | test/units/module_utils/basic/test_argument_spec.py | {
"start": 11136,
"end": 17560
} | class ____:
"""Test with a more complex arg_spec"""
@pytest.mark.parametrize('stdin', [{'foo': 'hello'}, {'dup': 'hello'}], indirect=['stdin'])
def test_complex_required(self, stdin, complex_argspec):
"""Test that the complex argspec works if we give it its required param as either the canonical or... | TestComplexArgSpecs |
python | urllib3__urllib3 | test/test_response.py | {
"start": 56196,
"end": 56368
} | class ____(MockChunkedEncodingResponse):
def _encode_chunk(self, chunk: bytes) -> bytes:
return f"9999\r\n{chunk.decode()}\r\n".encode()
| MockChunkedIncompleteRead |
python | cython__cython | tests/run/withstat_py27.py | {
"start": 2476,
"end": 2590
} | class ____(object):
def __enter__(self): raise RuntimeError()
def __exit__(self, *exc_info): pass
| EnterRaises |
python | davidhalter__jedi | jedi/api/errors.py | {
"start": 214,
"end": 1253
} | class ____:
"""
Syntax errors are generated by :meth:`.Script.get_syntax_errors`.
"""
def __init__(self, parso_error):
self._parso_error = parso_error
@property
def line(self):
"""The line where the error starts (starting with 1)."""
return self._parso_error.start_pos[0]... | SyntaxError |
python | vyperlang__vyper | tests/evm_backends/base_env.py | {
"start": 1023,
"end": 8309
} | class ____:
"""
Base class for EVM backends.
It provides a common interface for deploying contracts and interacting with them.
"""
DEFAULT_CHAIN_ID = 1
def __init__(self, gas_limit: int, account_keys: list[PrivateKey]) -> None:
self.gas_limit = gas_limit
self._keys = account_ke... | BaseEnv |
python | kamyu104__LeetCode-Solutions | Python/minimum-common-value.py | {
"start": 44,
"end": 468
} | class ____(object):
def getCommon(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: int
"""
i = j = 0
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
i += 1
elif nums1[i] > n... | Solution |
python | getsentry__sentry | tests/sentry/utils/test_audit.py | {
"start": 942,
"end": 21383
} | class ____(TestCase):
def setUp(self) -> None:
self.user = self.create_user(username=username)
self.req = fake_http_request(self.user)
self.org = self.create_organization(owner=self.user)
self.team = self.create_team(organization=self.org)
self.project = self.create_project(t... | CreateAuditEntryTest |
python | automl__auto-sklearn | autosklearn/pipeline/components/regression/extra_trees.py | {
"start": 582,
"end": 6625
} | class ____(
IterativeComponent,
AutoSklearnRegressionAlgorithm,
):
def __init__(
self,
criterion,
min_samples_leaf,
min_samples_split,
max_features,
bootstrap,
max_leaf_nodes,
max_depth,
min_weight_fraction_leaf,
min_impurity_de... | ExtraTreesRegressor |
python | huggingface__transformers | src/transformers/models/timm_wrapper/image_processing_timm_wrapper.py | {
"start": 1194,
"end": 5348
} | class ____(BaseImageProcessor):
"""
Wrapper class for timm models to be used within transformers.
Args:
pretrained_cfg (`dict[str, Any]`):
The configuration of the pretrained model used to resolve evaluation and
training transforms.
architecture (`Optional[str]`, *op... | TimmWrapperImageProcessor |
python | ray-project__ray | python/ray/data/preprocessors/discretizer.py | {
"start": 7217,
"end": 16408
} | class ____(_AbstractKBinsDiscretizer):
"""Bin values into discrete intervals (bins) of uniform width.
Columns must contain numerical values.
Examples:
Use :class:`UniformKBinsDiscretizer` to bin continuous features.
>>> import pandas as pd
>>> import ray
>>> from ray.data.... | UniformKBinsDiscretizer |
python | pytorch__pytorch | test/profiler/test_memory_profiler.py | {
"start": 1780,
"end": 2350
} | class ____(torch.nn.Module):
def __init__(self, in_features: int, out_features: int):
super().__init__()
self.in_features = in_features
self.out_features = out_features
def forward(self, x) -> torch.Tensor:
if getattr(self, "weight", None) is None:
self.weight = torc... | LazyLinear |
python | django-import-export__django-import-export | tests/core/tests/test_forms.py | {
"start": 2989,
"end": 9664
} | class ____(AdminTestMixin, TestCase):
@classmethod
def setUpTestData(cls) -> None:
cls.resources = (BookResource, BookResourceWithStoreInstance)
cls.form = forms.SelectableFieldsExportForm(
formats=(CSV,),
resources=cls.resources,
)
def test_create_boolean_fi... | SelectableFieldsExportFormTest |
python | astropy__astropy | astropy/visualization/stretch.py | {
"start": 14520,
"end": 18017
} | class ____(BaseStretch):
r"""
A log stretch.
The stretch is given by:
.. math::
y = \frac{\log{(a x + 1)}}{\log{(a + 1)}}
Parameters
----------
a : float
The ``a`` parameter used in the above formula. The stretch
becomes more linear for small ``a`` values. ``a`` mu... | LogStretch |
python | kubernetes-client__python | kubernetes/client/models/v1_endpoint_subset.py | {
"start": 383,
"end": 6047
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1EndpointSubset |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/state_changes.py | {
"start": 784,
"end": 888
} | class ____(_StateChangeState):
ANY = 1
NO_CHANGE = 2
CHANGE_IN_PROGRESS = 3
| _StateChangeStates |
python | huggingface__transformers | src/transformers/models/qwen3_moe/modular_qwen3_moe.py | {
"start": 2759,
"end": 2820
} | class ____(Qwen2MoeDecoderLayer):
pass
| Qwen3MoeDecoderLayer |
python | Textualize__textual | src/textual/messages.py | {
"start": 1542,
"end": 1766
} | class ____(Message, verbose=True):
"""Sent by Textual when a scroll update is required."""
def can_replace(self, message: Message) -> bool:
return isinstance(message, UpdateScroll)
@rich.repr.auto
| UpdateScroll |
python | ray-project__ray | rllib/env/multi_agent_env.py | {
"start": 17949,
"end": 26795
} | class ____(BaseEnv):
"""Internal adapter of MultiAgentEnv to BaseEnv.
This also supports vectorization if num_envs > 1.
"""
def __init__(
self,
make_env: Callable[[int], EnvType],
existing_envs: List["MultiAgentEnv"],
num_envs: int,
restart_failed_sub_environmen... | MultiAgentEnvWrapper |
python | huggingface__transformers | src/transformers/models/rt_detr/modeling_rt_detr.py | {
"start": 85583,
"end": 94455
} | class ____(RTDetrPreTrainedModel):
# When using clones, all layers > 0 will be clones, but layer 0 *is* required
# We can't initialize the model on meta device as some weights are modified during the initialization
_no_split_modules = None
def __init__(self, config: RTDetrConfig):
super().__ini... | RTDetrForObjectDetection |
python | django__django | django/contrib/auth/password_validation.py | {
"start": 3148,
"end": 5195
} | class ____:
"""
Validate that the password is of a minimum length.
"""
def __init__(self, min_length=8):
self.min_length = min_length
def validate(self, password, user=None):
if len(password) < self.min_length:
raise ValidationError(
self.get_error_messa... | MinimumLengthValidator |
python | pytorch__pytorch | test/dynamo/test_sources.py | {
"start": 281,
"end": 2058
} | class ____(torch._dynamo.test_case.TestCase):
def test_is_local(self):
x_src = LocalSource("x")
y_src = GlobalSource("y")
attr_x_a = AttrSource(x_src, "a")
attr_y_b = AttrSource(y_src, "b")
self.assertTrue(is_from_local_source(attr_x_a))
self.assertEqual(is_from_loc... | SourceTests |
python | huggingface__transformers | tests/models/oneformer/test_processing_oneformer.py | {
"start": 6984,
"end": 34355
} | class ____(unittest.TestCase):
processing_class = OneFormerProcessor if (is_vision_available() and is_torch_available()) else None
# only for test_feat_extracttion_common.test_feat_extract_to_json_string
feature_extraction_class = processing_class
def setUp(self):
self.processing_tester = OneFo... | OneFormerProcessingTest |
python | FactoryBoy__factory_boy | tests/test_alchemy.py | {
"start": 951,
"end": 1291
} | class ____(SQLAlchemyModelFactory):
class Meta:
model = models.MultiFieldModel
sqlalchemy_get_or_create = ('slug',)
sqlalchemy_session = models.session
sqlalchemy_session_persistence = 'commit'
id = factory.Sequence(lambda n: n)
foo = factory.Sequence(lambda n: 'foo%d' % n)
... | MultifieldModelFactory |
python | cython__cython | Cython/Compiler/ParseTreeTransforms.py | {
"start": 85631,
"end": 87580
} | class ____(CythonTransform):
"""
Declare all global cdef names that we allow referencing in other places,
before declaring everything (else) in source code order.
"""
def visit_CompilerDirectivesNode(self, node):
env = self.module_scope
old = env.directives
env.directives = ... | ForwardDeclareTypes |
python | pypa__pipenv | tests/integration/conftest.py | {
"start": 5654,
"end": 11025
} | class ____:
"""An instance of a Pipenv Project..."""
def __init__(self, pipfile=True, capfd=None, index_url=None):
self.index_url = index_url
self.pypi = None
self.env = {}
self.capfd = capfd
if self.index_url is not None:
self.pypi, _, _ = self.index_url.rpa... | _PipenvInstance |
python | getsentry__sentry | tests/sentry/issues/escalating/test_escalating.py | {
"start": 10093,
"end": 15402
} | class ____(BaseGroupCounts):
def save_mock_escalating_group_forecast(
self, group: Group, forecast_values: list[int], date_added: datetime
) -> None:
"""Save mock data for escalating group forecast in nodestore"""
escalating_forecast = EscalatingGroupForecast(
project_id=grou... | DailyGroupCountsEscalating |
python | getsentry__sentry | src/sentry/web/frontend/debug/debug_resolved_email.py | {
"start": 217,
"end": 384
} | class ____(ActivityMailDebugView):
def get_activity(self, request: HttpRequest, event):
return {"type": ActivityType.SET_RESOLVED.value}
| DebugResolvedEmailView |
python | getsentry__sentry | tests/sentry/tempest/endpoints/test_tempest_credentials_details.py | {
"start": 146,
"end": 2482
} | class ____(APITestCase):
endpoint = "sentry-api-0-project-tempest-credentials-details"
def setUp(self) -> None:
super().setUp()
self.tempest_credentials = self.create_tempest_credentials(self.project)
def test_cant_access_endpoint_if_feature_flag_is_disabled(self) -> None:
self.log... | TestTempestCredentialsDetails |
python | PrefectHQ__prefect | tests/utilities/test_annotations.py | {
"start": 160,
"end": 351
} | class ____:
def test_always_returns_same_value(self):
thing = unmapped("hello")
for _ in range(10):
assert thing[random.randint(0, 100)] == "hello"
| TestUnmapped |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 72142,
"end": 72490
} | class ____(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
actions: Annotated[
list[
BulkCreateActionBulkTaskInstanceBody
| BulkUpdateActionBulkTaskInstanceBody
| BulkDeleteActionBulkTaskInstanceBody
],
Field(title="Actions"),
... | BulkBodyBulkTaskInstanceBody |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 141932,
"end": 143318
} | class ____:
def test_ordinal_number(self):
assert self.locale.ordinal_number(1) == "1."
def test_define(self):
assert self.locale.describe("minute", only_distance=True) == "eng Minutt"
assert self.locale.describe("minute", only_distance=False) == "an enger Minutt"
assert self.lo... | TestLuxembourgishLocale |
python | ZoranPandovski__al-go-rithms | data_structures/Linked_list/Python/Odd_Even_Linked_List.py | {
"start": 166,
"end": 709
} | class ____(object):
def oddEvenList(self, head):
if head is None: return None
if head.next is None: return head
o = head
p = o.next
ehead = p
while p.next is not None:
o.next = p.next
p.next = p.next.next
o = o.next
... | Solution |
python | getsentry__sentry | src/sentry/snuba/events.py | {
"start": 294,
"end": 30145
} | class ____(Enum):
"""
Value is a tuple of (internal Events name, internal Transaction name, internal
Discover name, external alias)
None means the column is not available in that dataset.
Always use keyword arguments to declare columns for legibility.
"""
EVENT_ID = Column(
group_na... | Columns |
python | mlflow__mlflow | tests/models/test_artifacts.py | {
"start": 717,
"end": 4402
} | class ____:
def __init__(self):
self.test = 1
@pytest.mark.parametrize(
("is_file", "artifact", "artifact_type", "ext"),
[
(True, lambda path: Figure().savefig(path), ImageEvaluationArtifact, "png"),
(True, lambda path: Figure().savefig(path), ImageEvaluationArtifact, "jpg"),
... | __DummyClass |
python | protocolbuffers__protobuf | python/google/protobuf/text_format.py | {
"start": 1909,
"end": 2510
} | class ____(Error):
"""Thrown in case of text parsing or tokenizing error."""
def __init__(self, message=None, line=None, column=None):
if message is not None and line is not None:
loc = str(line)
if column is not None:
loc += ':{0}'.format(column)
message = '{0} : {1}'.format(loc, mes... | ParseError |
python | PyCQA__pylint | tests/regrtest_data/special_attr_scope_lookup_crash.py | {
"start": 0,
"end": 52
} | class ____(object):
"""A"""
__doc__ += "B"
| Klass |
python | openai__openai-python | src/openai/types/beta/realtime/transcription_session_update.py | {
"start": 6344,
"end": 6694
} | class ____(BaseModel):
session: Session
"""Realtime transcription session object configuration."""
type: Literal["transcription_session.update"]
"""The event type, must be `transcription_session.update`."""
event_id: Optional[str] = None
"""Optional client-generated ID used to identify this ev... | TranscriptionSessionUpdate |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/metadata.py | {
"start": 5084,
"end": 5317
} | class ____(graphene.ObjectType):
codeReferences = non_null_list(GrapheneSourceLocation)
class Meta:
interfaces = (GrapheneMetadataEntry,)
name = "CodeReferencesMetadataEntry"
| GrapheneCodeReferencesMetadataEntry |
python | facebookresearch__faiss | tests/test_fast_scan_ivf.py | {
"start": 13280,
"end": 13338
} | class ____(TestIVFImplem12):
IMPLEM = 15
| TestIVFImplem15 |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0094_auto_20221221_1045.py | {
"start": 182,
"end": 1066
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0093_migrate_null_fields"),
]
operations = [
migrations.AlterField(
model_name="projectrelationship",
name="child",
field=models.ForeignKey(
on... | Migration |
python | paramiko__paramiko | paramiko/server.py | {
"start": 25190,
"end": 26562
} | class ____:
"""
A query (set of prompts) for a user during interactive authentication.
"""
def __init__(self, name="", instructions="", *prompts):
"""
Create a new interactive query to send to the client. The name and
instructions are optional, but are generally displayed to th... | InteractiveQuery |
python | google__pytype | pytype/overlays/special_builtins.py | {
"start": 16775,
"end": 19014
} | class ____(BuiltinClass):
"""Implementation of builtins.object."""
_NAME = "object"
def is_object_new(self, func):
"""Whether the given function is object.__new__.
Args:
func: A function.
Returns:
True if func equals either of the pytd definitions for object.__new__,
False otherw... | Object |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/__init__.py | {
"start": 4206,
"end": 4535
} | class ____:
def __init__(self):
"""Create a new `CustomIter`."""
self.values = range(10)
def __iter__(self):
"""Iterate squares of each value."""
for i in self.values:
yield i**2
def snafucate(self):
"""Makes this snafucated."""
print('snafucated... | CustomIter |
python | numba__numba | numba/tests/test_listimpl.py | {
"start": 292,
"end": 5294
} | class ____(object):
"""A wrapper around the C-API to provide a minimal list object for
testing.
"""
def __init__(self, tc, item_size, allocated):
"""
Parameters
----------
tc : TestCase instance
item_size : int
byte size for the items
allocated... | List |
python | tensorflow__tensorflow | tensorflow/python/ops/linalg/sparse/sparse_csr_matrix_ops.py | {
"start": 8914,
"end": 10556
} | class ____(metaclass=abc.ABCMeta):
"""Abstract class for sparse matrix types."""
@abc.abstractmethod
def __init__(self):
self._eager_mode = context.executing_eagerly()
@abc.abstractproperty
def _matrix(self):
pass
@abc.abstractmethod
def _from_matrix(self, matrix, handle_data=None):
pass
... | SparseMatrix |
python | django__django | tests/auth_tests/test_context_processors.py | {
"start": 2087,
"end": 5762
} | class ____(TestCase):
"""
Tests for the ``django.contrib.auth.context_processors.auth`` processor
"""
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
@override_setti... | AuthContextProcessorTests |
python | django__django | tests/no_models/tests.py | {
"start": 70,
"end": 309
} | class ____(SimpleTestCase):
def test_no_models(self):
"""It's possible to load an app with no models.py file."""
app_config = apps.get_app_config("no_models")
self.assertIsNone(app_config.models_module)
| NoModelTests |
python | spyder-ide__spyder | spyder/config/tests/test_user.py | {
"start": 13436,
"end": 14669
} | class ____:
def test_spyderconfig_apply_configuration_patches_42(
self, spyderconfig_patches_42):
# Check that the value is updated
value = spyderconfig_patches_42.get('ipython_console',
'startup/run_lines')
expected_value = 'value1; v... | TestSpyderConfigApplyPatches |
python | walkccc__LeetCode | solutions/739. Daily Temperatures/739.py | {
"start": 0,
"end": 366
} | class ____:
def dailyTemperatures(self, temperatures: list[int]) -> list[int]:
ans = [0] * len(temperatures)
stack = [] # a decreasing stack
for i, temperature in enumerate(temperatures):
while stack and temperature > temperatures[stack[-1]]:
index = stack.pop()
ans[index] = i - in... | Solution |
python | facebook__pyre-check | client/commands/tests/expression_level_coverage_test.py | {
"start": 516,
"end": 26966
} | class ____(testslide.TestCase):
def test_make_expression_level_coverage_response(self) -> None:
self.assertEqual(
expression_level_coverage._make_expression_level_coverage_response(
daemon_query.Response(
{
"response": [
... | ExpressionLevelTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-aws-datalake/destination_aws_datalake/aws.py | {
"start": 2979,
"end": 3880
} | class ____(object):
METHOD = "assume-role"
def __init__(self, fetcher):
self._fetcher = fetcher
def load(self):
return DeferredRefreshableCredentials(self._fetcher.fetch_credentials, self.METHOD)
@staticmethod
def assume_role_refreshable(
session: botocore.session.Session,... | AssumeRoleProvider |
python | pytorch__pytorch | torch/distributed/checkpoint/planner.py | {
"start": 947,
"end": 1835
} | class ____:
"""Dataclass which holds information about what needs to be written to storage."""
index: MetadataIndex
type: WriteItemType
# Size of bytesIO data to be written.
bytes_io_data: Optional[BytesIOWriteData] = None
# Value present if it's a tensor write
tensor_data: Optional[Tenso... | WriteItem |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/host_info_utils.py | {
"start": 946,
"end": 2683
} | class ____(Enum):
X86_64 = "x86_64"
X86 = "x86"
PPC = "ppc"
ARM = "arm"
def get_host_user_id() -> str:
from airflow_breeze.utils.run_utils import run_command
host_user_id = ""
os = get_host_os()
if os == "linux" or os == "darwin":
host_user_id = run_command(
cmd=["... | Architecture |
python | walkccc__LeetCode | solutions/874. Walking Robot Simulation/874.py | {
"start": 0,
"end": 668
} | class ____:
def robotSim(self, commands: list[int], obstacles: list[list[int]]) -> int:
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
ans = 0
d = 0 # 0 := north, 1 := east, 2 := south, 3 := west
x = 0 # the start x
y = 0 # the start y
obstaclesSet = {(x, y) for x, y in obstacles}
for comma... | Solution |
python | huggingface__transformers | tests/models/seggpt/test_modeling_seggpt.py | {
"start": 5688,
"end": 13788
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Here we also overwrite some of the tests of test_modeling_common.py, as SegGpt does not use input_ids, inputs_embeds,
attention_mask and seq_length.
"""
all_model_classes = (SegGptModel, SegGptForImageSegmentation) if is_torc... | SegGptModelTest |
python | numba__numba | numba/tests/support.py | {
"start": 43717,
"end": 46877
} | class ____(CompilerBase):
""" Same as the standard pipeline, but preserves the func_ir into the
metadata store after legalisation, useful for testing IR changes"""
def define_pipelines(self):
pipeline = DefaultPassBuilder.define_nopython_pipeline(
self.state, "ir_preserving_custom_pipe"... | IRPreservingTestPipeline |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 48823,
"end": 48894
} | class ____:
xlCreatorCode = 1480803660 # from enum XlCreator
| Creator |
python | apache__thrift | test/py/TestClient.py | {
"start": 14619,
"end": 15197
} | class ____(MultiplexedOptionalTest):
def get_protocol(self, transport):
wrapped_proto = make_pedantic(TBinaryProtocol.TBinaryProtocolAcceleratedFactory(fallback=False).getProtocol(transport))
return TMultiplexedProtocol.TMultiplexedProtocol(wrapped_proto, "ThriftTest")
def get_protocol2(self, t... | MultiplexedAcceleratedBinaryTest |
python | pytorch__pytorch | torchgen/operator_versions/gen_mobile_upgraders.py | {
"start": 418,
"end": 12381
} | class ____(Enum):
instructions = 1
constants = 2
types = 3
operators = 4
register_size = 5
EXCLUDED_OP_SET = [
"aten::full.names",
"aten::full.out",
"aten::full",
]
EXCLUE_UPGRADER_SET = ["full_0_4", "full_out_0_4"]
ONE_INSTRUCTION = CodeTemplate(
"""
Instruction{OpCode::${op... | ByteCode |
python | plotly__plotly.py | plotly/graph_objs/layout/_grid.py | {
"start": 235,
"end": 18443
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout"
_path_str = "layout.grid"
_valid_props = {
"columns",
"domain",
"pattern",
"roworder",
"rows",
"subplots",
"xaxes",
"xgap",
"xside",
"yaxes",
"ygap",
... | Grid |
python | tornadoweb__tornado | tornado/test/template_test.py | {
"start": 10075,
"end": 10689
} | class ____(unittest.TestCase):
def test_details(self):
loader = DictLoader({"foo.html": "\n\n{{"})
with self.assertRaises(ParseError) as cm:
loader.load("foo.html")
self.assertEqual("Missing end expression }} at foo.html:3", str(cm.exception))
self.assertEqual("foo.html",... | ParseErrorDetailTest |
python | psf__black | src/black/trans.py | {
"start": 11019,
"end": 11609
} | class ____:
"""A custom (i.e. manual) string split.
A single CustomSplit instance represents a single substring.
Examples:
Consider the following string:
```
"Hi there friend."
" This is a custom"
f" string {split}."
```
This string will correspond ... | CustomSplit |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 213429,
"end": 225648
} | class ____(io.BytesIO):
def __enter__(self):
return self
def __exit__(self, *args):
pass
# Tentative value for nondet_tol for gradcheck when backward implementation
# relies on nondeterministic operations, i.e., those listed here:
# https://pytorch.org/docs/stable/generated/torch.use_determini... | BytesIOContext |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 14651,
"end": 14947
} | class ____(DagsterUserCodeExecutionError):
"""Indicates that an unexpected error occurred while executing the body of a config mapping
function defined in a :py:class:`~dagster.JobDefinition` or `~dagster.GraphDefinition` during
config parsing.
"""
| DagsterConfigMappingFunctionError |
python | getsentry__sentry | src/sentry/integrations/models/external_issue.py | {
"start": 2217,
"end": 3523
} | class ____(Model):
__relocation_scope__ = RelocationScope.Excluded
# The foreign key here is an `int`, not `bigint`.
organization = FlexibleForeignKey("sentry.Organization", db_constraint=False)
integration_id = HybridCloudForeignKey("sentry.Integration", on_delete="CASCADE")
key = models.CharFie... | ExternalIssue |
python | getsentry__sentry | tests/sentry/integrations/cursor/test_webhook.py | {
"start": 293,
"end": 11171
} | class ____(APITestCase):
endpoint = "sentry-extensions-cursor-webhook"
def setUp(self):
super().setUp()
# Create a Cursor integration linked to this organization
self.integration = self.create_integration(
organization=self.organization,
provider="cursor",
... | TestCursorWebhook |
python | spack__spack | lib/spack/spack/vendor/pyrsistent/_pclass.py | {
"start": 8057,
"end": 9767
} | class ____(object):
__slots__ = ('_pclass_evolver_original', '_pclass_evolver_data', '_pclass_evolver_data_is_dirty', '_factory_fields')
def __init__(self, original, initial_dict):
self._pclass_evolver_original = original
self._pclass_evolver_data = initial_dict
self._pclass_evolver_dat... | _PClassEvolver |
python | GoogleCloudPlatform__python-docs-samples | logging/redaction/log_redaction.py | {
"start": 1752,
"end": 4841
} | class ____(DoFn):
"""Ingest payloads into destination log"""
def __init__(self, destination_log_name):
self.destination_log_name = destination_log_name
self.logger = None
def _replace_log_name(self, entry):
# update log name in the entry with destination log
entry["logName"... | IngestLogs |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_video_intelligence.py | {
"start": 1462,
"end": 4850
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.video_intelligence.CloudVideoIntelligenceHook")
def test_detect_video_labels_green_path(self, mock_hook):
mocked_operation = mock.Mock()
mocked_operation.result = mock.Mock(return_value=AnnotateVideoResponse(annotation_results=[])... | TestCloudVideoIntelligenceOperators |
python | pytorch__pytorch | torch/onnx/_internal/exporter/_schemas.py | {
"start": 2979,
"end": 3542
} | class ____:
"""A formal parameter of an operator."""
name: str
type_constraint: TypeConstraintParam
required: bool
variadic: bool
default: Any = _EMPTY_DEFAULT
# TODO: Add other properties too
def __str__(self) -> str:
type_str = self.type_constraint.name
if self.has_de... | Parameter |
python | astropy__astropy | astropy/io/fits/column.py | {
"start": 8768,
"end": 10639
} | class ____(_BaseColumnFormat):
"""
Represents a FITS binary table column format.
This is an enhancement over using a normal string for the format, since the
repeat count, format code, and option are available as separate attributes,
and smart comparison is used. For example 1J == J.
"""
d... | _ColumnFormat |
python | getsentry__sentry | src/sentry/auth/access.py | {
"start": 12856,
"end": 13384
} | class ____:
access: RpcBackedAccess
def maybe_singular_rpc_access_org_context(
access: Access, org_ids: set[int]
) -> SingularRpcAccessOrgOptimization | None:
if (
isinstance(access, RpcBackedAccess)
and len(org_ids) == 1
and access.rpc_user_organization_context.organization.id in ... | SingularRpcAccessOrgOptimization |
python | getsentry__sentry | tests/sentry/tasks/test_auth.py | {
"start": 2012,
"end": 3557
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(email="bar@example.com")
self.organization = self.create_organization(name="Test")
with assume_test_silo_mode(SiloMode.CONTROL):
self.provider = AuthProvider.objects.create(
... | EmailMissingLinksTest |
python | huggingface__transformers | src/transformers/models/sew/modeling_sew.py | {
"start": 28863,
"end": 34585
} | class ____(SEWPreTrainedModel):
def __init__(self, config: SEWConfig):
super().__init__(config)
self.config = config
self.feature_extractor = SEWFeatureEncoder(config)
self.layer_norm = nn.LayerNorm(config.conv_dim[-1], eps=config.layer_norm_eps)
self.project_features = conf... | SEWModel |
python | numba__numba | numba/cuda/tests/cudadrv/test_select_device.py | {
"start": 511,
"end": 987
} | class ____(ContextResettingTestCase):
def test_select_device(self):
exception_queue = Queue()
for i in range(10):
t = threading.Thread(target=newthread, args=(exception_queue,))
t.start()
t.join()
exceptions = []
while not exception_queue.empty():... | TestSelectDevice |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 542507,
"end": 542985
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of CreateRepositoryRuleset"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "ruleset")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing th... | CreateRepositoryRulesetPayload |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeatures.py | {
"start": 14384,
"end": 15489
} | class ____(MetaFeature):
def _calculate(self, X, y, logger, feat_type):
occurence_dict = helper_functions.get_value("ClassOccurences")
if len(y.shape) == 2:
stds = []
for i in range(y.shape[1]):
std = np.array(
[occurrence for occurrence i... | ClassProbabilitySTD |
python | pypa__virtualenv | src/virtualenv/discovery/builtin.py | {
"start": 9581,
"end": 9724
} | class ____(PythonInfo):
"""python info from path."""
__all__ = [
"Builtin",
"PathPythonInfo",
"get_interpreter",
]
| PathPythonInfo |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/vertex_ai/test_generative_model.py | {
"start": 16970,
"end": 18174
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("generative_model.GenerativeModelHook"))
def test_execute(self, mock_hook):
cached_content_name = "test"
contents = ["what are in these papers"]
with pytest.warns(AirflowProviderDeprecationWarning):
op = GenerateFromCachedContentO... | TestVertexAIGenerateFromCachedContentOperator |
python | mahmoud__boltons | boltons/socketutils.py | {
"start": 28346,
"end": 28808
} | class ____(NetstringProtocolError):
"""NetstringInvalidSize is raised when the ``:``-delimited size prefix
of the message does not contain a valid integer.
Message showing valid size::
5:hello,
Here the ``5`` is the size. Anything in this prefix position that
is not parsable as a Python int... | NetstringInvalidSize |
python | allegroai__clearml | clearml/debugging/log.py | {
"start": 12253,
"end": 12358
} | class ____(logging.handlers.RotatingFileHandler, ClearmlLoggerHandler):
pass
| ClearmlRotatingFileHandler |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataflow.py | {
"start": 38385,
"end": 42402
} | class ____(GoogleCloudBaseOperator):
"""
Stops the job with the specified name prefix or Job ID.
All jobs with provided name prefix will be stopped.
Streaming jobs are drained by default.
Parameter ``job_name_prefix`` and ``job_id`` are mutually exclusive.
.. seealso::
For more detail... | DataflowStopJobOperator |
python | astropy__astropy | astropy/modeling/rotations.py | {
"start": 12568,
"end": 15004
} | class ____(_SkyRotation):
"""
Transform from Celestial to Native Spherical Coordinates.
Parameters
----------
lon : float or `~astropy.units.Quantity` ['angle']
Celestial longitude of the fiducial point.
lat : float or `~astropy.units.Quantity` ['angle']
Celestial latitude of th... | RotateCelestial2Native |
python | getsentry__sentry | src/sentry/models/options/option.py | {
"start": 395,
"end": 2005
} | class ____(OverwritableConfigMixin, Model):
"""
Global options which apply in most situations as defaults,
and generally can be overwritten by per-project options.
Options which are specific to a plugin should namespace
their key. e.g. key='myplugin:optname'
"""
# Subclasses should overwri... | BaseOption |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 844924,
"end": 845652
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for ProjectV2."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("ProjectV2Edge"), graphql_name="edges")
"""A list of edges."""
nodes = sg... | ProjectV2Connection |
python | huggingface__transformers | src/transformers/tokenization_utils_tokenizers.py | {
"start": 2859,
"end": 54191
} | class ____(PreTrainedTokenizerBase):
"""
Base class for all fast tokenizers (wrapping HuggingFace tokenizers library).
Inherits from [`~tokenization_utils_base.PreTrainedTokenizerBase`].
Handles all the shared methods for tokenization and special tokens, as well as methods for
downloading/caching/... | TokenizersBackend |
python | getsentry__sentry | tests/sentry/integrations/slack/utils/test_channel.py | {
"start": 9507,
"end": 10673
} | class ____(TestCase):
def test_behavior_for_known_slack_identifiers(self) -> None:
# User IDs
assert is_input_a_user_id("U12345678")
assert is_input_a_user_id("W12345678")
# Non-user IDs
assert not is_input_a_user_id("C12345678") # Channel ID
assert not is_input_a_us... | IsInputAUserIdTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.