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/sam3_tracker/configuration_sam3_tracker.py
{ "start": 3378, "end": 6703 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Sam3TrackerMaskDecoder`]. It is used to instantiate a SAM3_TRACKER memory encoder according to the specified arguments, defining the model architecture. Configuration objects inherit from [`PreTrainedCo...
Sam3TrackerMaskDecoderConfig
python
apache__airflow
providers/openlineage/tests/unit/openlineage/extractors/test_base.py
{ "start": 3018, "end": 3397 }
class ____(BaseExtractor): @classmethod def get_operator_classnames(cls): return ["AnotherOperator"] def _execute_extraction(self) -> OperatorLineage | None: return OperatorLineage( inputs=INPUTS, outputs=OUTPUTS, run_facets=RUN_FACETS, job_fa...
ExtractorWithExecuteExtractionOnly
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/via_type_of.py
{ "start": 1798, "end": 1836 }
class ____: ... @dataclass
Test3_Foo
python
airbytehq__airbyte
airbyte-integrations/connectors/source-klaviyo/components.py
{ "start": 4328, "end": 5762 }
class ____(ArchivedToPerPartitionStateMigration): """ Campaigns stream has 2 partition field: archived and campaign_type(email, sms). Previous API version didn't return sms in campaigns output so we need to migrate only email partition. Example input state: { "updated_at": "2020-10-10T00:00...
CampaignsStateMigration
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/generator2.py
{ "start": 215, "end": 281 }
class ____: def shouldContinue(self): return True
ClassB
python
apache__airflow
task-sdk/tests/task_sdk/definitions/test_mixins.py
{ "start": 7595, "end": 11710 }
class ____: def test_set_upstream(self): with DAG("test_set_upstream"): op_a = BaseOperator(task_id="a") op_b = BaseOperator(task_id="b") op_c = BaseOperator(task_id="c") op_d = BaseOperator(task_id="d") op_d << op_c << op_b << op_a asser...
TestDependencyMixin
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/comms.py
{ "start": 18692, "end": 18895 }
class ____(BaseModel): """Response containing previous Dag run information.""" dag_run: DagRun | None = None type: Literal["PreviousDagRunResult"] = "PreviousDagRunResult"
PreviousDagRunResult
python
ray-project__ray
rllib/utils/replay_buffers/tests/test_prioritized_episode_buffer.py
{ "start": 272, "end": 14310 }
class ____(unittest.TestCase): @staticmethod def _get_episode(episode_len=None, id_=None, with_extra_model_outs=False): eps = SingleAgentEpisode(id_=id_, observations=[0.0], infos=[{}]) ts = np.random.randint(1, 200) if episode_len is None else episode_len for t in range(ts): ...
TestPrioritizedEpisodeReplayBuffer
python
ray-project__ray
python/ray/train/_internal/state/schema.py
{ "start": 822, "end": 910 }
class ____(str, Enum): DEAD = "DEAD" ALIVE = "ALIVE" @DeveloperAPI
ActorStatusEnum
python
sqlalchemy__sqlalchemy
test/orm/test_versioning.py
{ "start": 56048, "end": 59654 }
class ____(fixtures.MappedTest): # test for #4193, see also #4194 for related notes __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( "version_table", metadata, Column( "id", Integer, primary_key=True, tes...
VersioningMappedSelectTest
python
mlflow__mlflow
dev/clint/tests/rules/test_no_class_based_tests.py
{ "start": 628, "end": 1551 }
class ____: def helper_function(self): return 42 def setup_something(self): pass def test_something(self): pass # Good - function-based test def test_valid_function(): assert True # Good - regular function def helper_function(): return 42 """ config = Config(select={N...
HelperClass
python
catalyst-team__catalyst
catalyst/contrib/losses/triplet.py
{ "start": 440, "end": 6671 }
class ____(nn.Module): """Triplet loss with hard positive/negative mining. Adapted from: https://github.com/NegatioN/OnlineMiningTripletLoss """ def __init__(self, margin: float = 0.3): """ Args: margin: margin for triplet """ super().__init__() self...
TripletLoss
python
getsentry__sentry
tests/sentry/api/serializers/test_activity.py
{ "start": 452, "end": 8044 }
class ____(TestCase): def test_pr_activity(self) -> None: self.org = self.create_organization(name="Rowdy Tiger") user = self.create_user() group = self.create_group(status=GroupStatus.UNRESOLVED) repo = self.create_repo(self.project, name="organization-bar") pr = PullRequest...
GroupActivityTestCase
python
pypa__pip
src/pip/_internal/metadata/base.py
{ "start": 2615, "end": 21347 }
class ____(Protocol): @classmethod def from_directory(cls, directory: str) -> BaseDistribution: """Load the distribution from a metadata directory. :param directory: Path to a metadata directory, e.g. ``.dist-info``. """ raise NotImplementedError() @classmethod def from...
BaseDistribution
python
google__jax
tests/multiprocess/array_test.py
{ "start": 18432, "end": 35541 }
class ____(jt_multiprocess.MultiProcessTest): def test_create_nonaddressable_array(self): y, x = create_nonaddressable_array((8, 8)) # The array is non-addressable in at least one process. self.assertLess(len(y.sharding._internal_device_list.process_indices), jax.process_count()) ...
NonaddressableArrayTestMultiHost
python
ray-project__ray
python/ray/_private/thirdparty/dacite/exceptions.py
{ "start": 1560, "end": 2028 }
class ____(DaciteFieldError): def __init__(self, union_matches: Dict[Type, Any], field_path: Optional[str] = None) -> None: super().__init__(field_path=field_path) self.union_matches = union_matches def __str__(self) -> str: conflicting_types = ", ".join(_name(type_) for type_ in self.u...
StrictUnionMatchError
python
pytorch__pytorch
torch/fx/graph.py
{ "start": 10230, "end": 35503 }
class ____: # This is an override hook so we can customize the SymNode printer. _sym_repr: Callable[["torch.types.PySymType"], str] = lambda x: repr(x) def __init__(self): self._body_transformer: Optional[TransformCodeFunc] = None self._func_name: str = "forward" def _format_multiline_...
CodeGen
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta/beta_code_execution_result_block_param.py
{ "start": 348, "end": 620 }
class ____(TypedDict, total=False): content: Required[Iterable[BetaCodeExecutionOutputBlockParam]] return_code: Required[int] stderr: Required[str] stdout: Required[str] type: Required[Literal["code_execution_result"]]
BetaCodeExecutionResultBlockParam
python
keras-team__keras
keras/src/layers/pooling/global_max_pooling1d.py
{ "start": 261, "end": 2357 }
class ____(BaseGlobalPooling): """Global max pooling operation for temporal data. Args: data_format: string, either `"channels_last"` or `"channels_first"`. The ordering of the dimensions in the inputs. `"channels_last"` corresponds to inputs with shape `(batch, steps, features)...
GlobalMaxPooling1D
python
spack__spack
lib/spack/spack/test/error_messages.py
{ "start": 3811, "end": 10745 }
class ____(Package): version("2.1") version("2.0") variant("v1", default=True) """, ) all_pkgs = [ _pkgx1, _pkgx2, _pkgx3, _pkgx4, _pkgy1, _pkgy2, _pkgy3, _pkgy4, _pkgz1, _pkgz2, _pkgz3, _pkgw1, _pkgw2, _pkgw3, _pkgw4, _pkgt1, _pkgt2, ...
T1
python
scipy__scipy
scipy/io/wavfile.py
{ "start": 642, "end": 2115 }
class ____: """ Tracks stream position, provides tell(), and emulates only those seeks that can be supported by reading forward. Other seeks raise io.UnsupportedOperation. Note that this class implements only the minimum necessary to keep wavfile.read() happy. """ def __init__(self, reader):...
SeekEmulatingReader
python
walkccc__LeetCode
solutions/471. Encode String with Shortest Length/471-2.py
{ "start": 0, "end": 982 }
class ____: def encode(self, s: str) -> str: n = len(s) # dp[i][j] := the shortest encoded string of s[i..j] dp = [[''] * n for _ in range(n)] for d in range(n): for i in range(n - d): j = i + d curr = s[i:j + 1] dp[i][j] = curr if len(dp[i][j]) < 5: c...
Solution
python
PrefectHQ__prefect
tests/server/orchestration/api/test_block_types.py
{ "start": 11725, "end": 14972 }
class ____: async def test_update_block_type(self, client, block_type_x): response = await client.patch( f"/block_types/{block_type_x.id}", json=BlockTypeUpdate( logo_url="http://foo.com/bar.png", documentation_url="http://foo.com/bar.html", ...
TestUpdateBlockType
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor24.py
{ "start": 1848, "end": 1988 }
class ____(Generic[T]): def __init__(self, c: Callable[[], T]): ... def func2(cls: type[T_A] = A) -> Callable[[], T_A]: ... B(func2())
B
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-lines-to-cover-points.py
{ "start": 102, "end": 1819 }
class ____(object): def minimumLines(self, points): """ :type points: List[List[int]] :rtype: int """ def gcd(a, b): # Time: O(log(a + b)) while b: a, b = b, a % b return abs(a) def popcount(x): result = 0 ...
Solution
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF028.py
{ "start": 743, "end": 1767 }
class ____: @classmethod # fmt: off def cls_method_a( # fmt: off cls, ) -> None: # noqa: test # fmt: skip pass def fmt_on_trailing(): # fmt: off val = 5 # fmt: on pass # fmt: on # all of these should be fine def match_case_and_elif(): string = "hello" matc...
Test
python
kamyu104__LeetCode-Solutions
Python/maximize-the-beauty-of-the-garden.py
{ "start": 29, "end": 566 }
class ____(object): def maximumBeauty(self, flowers): """ :type flowers: List[int] :rtype: int """ lookup = {} prefix = [0] result = float("-inf") for i, f in enumerate(flowers): prefix.append(prefix[-1]+f if f > 0 else prefix[-1]) ...
Solution
python
kamyu104__LeetCode-Solutions
Python/basic-calculator-iv.py
{ "start": 2236, "end": 3859 }
class ____(object): def basicCalculatorIV(self, expression, evalvars, evalints): """ :type expression: str :type evalvars: List[str] :type evalints: List[int] :rtype: List[str] """ ops = {'+':operator.add, '-':operator.sub, '*':operator.mul} def comput...
Solution
python
kamyu104__LeetCode-Solutions
Python/add-and-search-word-data-structure-design.py
{ "start": 209, "end": 1293 }
class ____(object): def __init__(self): self.root = TrieNode() # @param {string} word # @return {void} # Adds a word into the data structure. def addWord(self, word): curr = self.root for c in word: if c not in curr.leaves: curr.leaves[c] = TrieNo...
WordDictionary
python
django__django
tests/admin_utils/admin.py
{ "start": 543, "end": 658 }
class ____(admin.TabularInline): model = Article fields = ["title"] form = ArticleAdminForm
ArticleInline
python
huggingface__transformers
src/transformers/models/pegasus_x/modeling_pegasus_x.py
{ "start": 33356, "end": 42236 }
class ____(PegasusXPreTrainedModel): """ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a [`PegasusXEncoderLayer`]. Args: config: PegasusXConfig embed_tokens (nn.Embedding): output embedding """ def __init__(self, config: PegasusX...
PegasusXEncoder
python
PyCQA__pylint
tests/functional/n/nonlocal_without_binding.py
{ "start": 772, "end": 1396 }
class ____: nonlocal x # [nonlocal-without-binding] def func(self): nonlocal some_attr # [nonlocal-without-binding] def func2(): nonlocal_ = None local = None class Class: nonlocal nonlocal_ nonlocal_ = 1 local = 1 return local + nonlocal_ def function(...
SomeClass
python
getsentry__sentry
src/sentry/api/serializers/models/organization_member/expand/roles.py
{ "start": 1209, "end": 3468 }
class ____(OrganizationMemberWithTeamsSerializer): def __init__( self, allowed_roles: Iterable[Role], expand: Sequence[str] | None = None, ) -> None: super().__init__(expand) self.allowed_roles = allowed_roles def get_attrs( self, item_list: Sequence[...
OrganizationMemberWithRolesSerializer
python
pytorch__pytorch
torch/distributed/checkpoint/default_planner.py
{ "start": 1784, "end": 10846 }
class ____(SavePlanner): mappings: FLATTEN_MAPPING def __init__( self, flatten_state_dict: bool = True, flatten_sharded_tensors: bool = True, dedup_replicated_tensors: Optional[bool] = None, dedup_save_to_lowest_rank: bool = False, enable_plan_caching: bool = Fal...
DefaultSavePlanner
python
encode__django-rest-framework
tests/test_filters.py
{ "start": 13592, "end": 13780 }
class ____(models.Model): title = models.CharField(max_length=20) text = models.CharField(max_length=100) attributes = models.ManyToManyField(AttributeModel)
SearchFilterModelM2M
python
kubernetes-client__python
kubernetes/client/models/v1_security_context.py
{ "start": 383, "end": 17245 }
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...
V1SecurityContext
python
automl__auto-sklearn
test/test_pipeline/components/feature_preprocessing/test_select_percentile_regression.py
{ "start": 255, "end": 1944 }
class ____(unittest.TestCase): def test_default_configuration(self): transformation, original = _test_preprocessing( dataset="boston", Preprocessor=SelectPercentileRegression, ) self.assertEqual(transformation.shape[0], original.shape[0]) self.assertEqual(tran...
SelectPercentileRegressionTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/instigation.py
{ "start": 2503, "end": 2653 }
class ____(graphene.Enum): RUNNING = "RUNNING" STOPPED = "STOPPED" class Meta: name = "InstigationStatus"
GrapheneInstigationStatus
python
great-expectations__great_expectations
great_expectations/render/renderer_configuration.py
{ "start": 4144, "end": 4351 }
class ____(_RendererValueBase): """Represents each value within a row of a header_row or a table.""" renderer_schema: RendererSchema = Field(alias="schema") value: Optional[Any]
RendererTableValue
python
pyinstaller__pyinstaller
tests/functional/modules/pyi_testmod_relimp/B/D.py
{ "start": 542, "end": 589 }
class ____: name = 'pyi_testmod_relimp.B.D.X'
X
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 62057, "end": 63652 }
class ____(WebTestCase): class Handler(RequestHandler): def initialize(self, reply): self.reply = reply def get(self): self.write(self.reply) def get_handlers(self): return [("/foo", HostMatchingTest.Handler, {"reply": "wildcard"})] def test_host_matching(s...
HostMatchingTest
python
redis__redis-py
tests/test_asyncio/test_pubsub.py
{ "start": 2607, "end": 12170 }
class ____: async def _test_subscribe_unsubscribe( self, p, sub_type, unsub_type, sub_func, unsub_func, keys ): for key in keys: assert await sub_func(key) is None # should be a message for each channel/pattern we just subscribed to for i, key in enumerate(keys): ...
TestPubSubSubscribeUnsubscribe
python
Netflix__metaflow
test/core/tests/s3_failure.py
{ "start": 67, "end": 1500 }
class ____(MetaflowTest): """ Test that S3 failures are handled correctly. """ PRIORITY = 1 SKIP_GRAPHS = [ "simple_switch", "nested_switch", "branch_in_switch", "foreach_in_switch", "switch_in_branch", "switch_in_foreach", "recursive_switch",...
S3FailureTest
python
PrefectHQ__prefect
src/prefect/server/events/schemas/automations.py
{ "start": 21849, "end": 22055 }
class ____(AutomationCore, ActionBaseModel, extra="forbid"): owner_resource: Optional[str] = Field( default=None, description="The resource to which this automation belongs" )
AutomationCreate
python
pandas-dev__pandas
pandas/io/parsers/c_parser_wrapper.py
{ "start": 1209, "end": 12915 }
class ____(ParserBase): low_memory: bool _reader: parsers.TextReader def __init__(self, src: ReadCsvBuffer[str], **kwds) -> None: super().__init__(kwds) self.kwds = kwds kwds = kwds.copy() self.low_memory = kwds.pop("low_memory", False) # #2442 kwds["allow_...
CParserWrapper
python
walkccc__LeetCode
solutions/418. Sentence Screen Fitting/418.py
{ "start": 0, "end": 356 }
class ____: def wordsTyping(self, sentence: list[str], rows: int, cols: int) -> int: combined = ' '.join(sentence) + ' ' n = len(combined) i = 0 for _ in range(rows): i += cols if combined[i % n] == ' ': i += 1 else: while i > 0 and combined[(i - 1) % n] != ' ': ...
Solution
python
ansible__ansible
lib/ansible/_internal/_json/_profiles/_legacy.py
{ "start": 1048, "end": 3081 }
class ____(_json.AnsibleVariableVisitor): """Variable visitor that supports optional trust inversion for legacy serialization.""" def __init__( self, *, trusted_as_template: bool = False, invert_trust: bool = False, origin: _tags.Origin | None = None, convert_map...
_LegacyVariableVisitor
python
html5lib__html5lib-python
html5lib/html5parser.py
{ "start": 18101, "end": 24176 }
class ____(Phase): __slots__ = tuple() def processSpaceCharacters(self, token): pass def processComment(self, token): self.tree.insertComment(token, self.tree.document) def processDoctype(self, token): name = token["name"] publicId = token["publicId"] systemId ...
InitialPhase
python
keras-team__keras
keras/src/legacy/saving/json_utils_test.py
{ "start": 204, "end": 1343 }
class ____(testing.TestCase): def test_encode_decode_tuple(self): metadata = {"key1": (3, 5), "key2": [(1, (3, 4)), (1,)]} string = json_utils.Encoder().encode(metadata) loaded = json_utils.decode(string) self.assertEqual(set(loaded.keys()), {"key1", "key2"}) self.assertAllE...
JsonUtilsTestAllBackends
python
PrefectHQ__prefect
src/prefect/client/schemas/filters.py
{ "start": 15697, "end": 16341 }
class ____(PrefectBaseModel, OperatorMixin): """Filter by `Deployment.tags`.""" all_: Optional[List[str]] = Field( default=None, examples=[["tag-1", "tag-2"]], description=( "A list of tags. Deployments will be returned only if their tags are a" " superset of the...
DeploymentFilterTags
python
tiangolo__fastapi
fastapi/security/http.py
{ "start": 1918, "end": 3247 }
class ____(SecurityBase): def __init__( self, *, scheme: str, scheme_name: Optional[str] = None, description: Optional[str] = None, auto_error: bool = True, ): self.model: HTTPBaseModel = HTTPBaseModel( scheme=scheme, description=description ...
HTTPBase
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 446925, "end": 449564 }
class ____(Response): """ Response of tasks.get_hyper_params endpoint. :param params: Hyper parameters (keyed by task ID) :type params: Sequence[dict] """ _service = "tasks" _action = "get_hyper_params" _version = "2.23" _schema = { "definitions": { "params_ite...
GetHyperParamsResponse
python
pytorch__pytorch
test/distributed/test_functional_api.py
{ "start": 2659, "end": 6309 }
class ____(MultiThreadedTestCase): @property def world_size(self): return 4 def setUp(self): super().setUp() self._spawn_threads() def test_expand_1d_rank_list(self): tag, rankset, group_size = ft_c._expand_group([0, 1, 2, 3]) self.assertEqual("", tag) s...
TestExpand
python
getsentry__sentry
src/sentry/api/authentication.py
{ "start": 10904, "end": 13226 }
class ____(QuietBasicAuthentication): """ Authenticates a Sentry Application using its Client ID and Secret This will be the method by which we identify which Sentry Application is making the request, for any requests not scoped to an installation. For example, the request to exchange a Grant Code...
ClientIdSecretAuthentication
python
coleifer__peewee
playhouse/dataset.py
{ "start": 10674, "end": 11705 }
class ____(Exporter): def __init__(self, query, iso8601_datetimes=False): super(JSONExporter, self).__init__(query) self.iso8601_datetimes = iso8601_datetimes def _make_default(self): datetime_types = (datetime.datetime, datetime.date, datetime.time) if self.iso8601_datetimes: ...
JSONExporter
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/regex.py
{ "start": 6726, "end": 21668 }
class ____(CharactersBuilder): def __init__(self, *, negate=False, flags=0): self._whitelist_chars = set() self._blacklist_chars = set() self._negate = negate self._alphabet = None self._ignorecase = flags & re.IGNORECASE self.code_to_char = int_to_byte @property...
BytesBuilder
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_heapq.py
{ "start": 10870, "end": 10979 }
class ____(_TestHeap, __TestCase): module = py_heapq @skipUnless(c_heapq, 'requires _heapq')
TestHeapPython
python
python__mypy
mypy/stubgenc.py
{ "start": 956, "end": 3218 }
class ____(SignatureGenerator): def __init__( self, func_sigs: dict[str, str] | None = None, class_sigs: dict[str, str] | None = None ) -> None: """ Takes a mapping of function/method names to signatures and class name to class signatures (usually corresponds to __init__). ...
ExternalSignatureGenerator
python
google__pytype
pytype/rewrite/flow/conditions.py
{ "start": 168, "end": 274 }
class ____: """A condition that must be satisified for a binding to apply.""" @_frozen_dataclass
Condition
python
pytorch__pytorch
torch/_inductor/analysis/profile_analysis.py
{ "start": 12092, "end": 12308 }
class ____: flops: int bw: float latency: float # us achieved_flops: float achieved_bandwidth: float KernelNameMap = defaultdict[str, OrderedSet[KernelStats]] @dataclass(frozen=False)
KernelStats
python
wandb__wandb
wandb/sdk/interface/interface_shared.py
{ "start": 382, "end": 18888 }
class ____(InterfaceBase, abc.ABC): """Partially implemented InterfaceBase. There is little reason for this to exist separately from InterfaceBase, which itself is not a pure abstract class and has no other direct subclasses. Most methods are implemented in this class in terms of the protected _pub...
InterfaceShared
python
django__django
django/contrib/postgres/operations.py
{ "start": 6505, "end": 7979 }
class ____(Operation): def __init__(self, name, locale, *, provider="libc", deterministic=True): self.name = name self.locale = locale self.provider = provider self.deterministic = deterministic def state_forwards(self, app_label, state): pass def deconstruct(self):...
CollationOperation
python
fabric__fabric
fabric/tunnels.py
{ "start": 3905, "end": 5415 }
class ____(ExceptionHandlingThread): """ Bidirectionally forward data between an SSH channel and local socket. .. versionadded:: 2.0 """ def __init__(self, channel, sock, finished): self.channel = channel self.sock = sock self.finished = finished self.socket_chunk_s...
Tunnel
python
conda__conda
conda/auxlib/entity.py
{ "start": 17398, "end": 17571 }
class ____(Field): _type = bool def box(self, instance, instance_type, val): return None if val is None else bool(val) BoolField = BooleanField
BooleanField
python
django__django
tests/migrations/migrations_test_apps/conflicting_app_with_dependencies/migrations/0002_second.py
{ "start": 43, "end": 573 }
class ____(migrations.Migration): dependencies = [ ("conflicting_app_with_dependencies", "0001_initial"), ("migrated_app", "0001_initial"), ] operations = [ migrations.DeleteModel("Tribble"), migrations.RemoveField("Author", "silly_field"), migrations.AddField("Autho...
Migration
python
numpy__numpy
numpy/linalg/_linalg.py
{ "start": 1975, "end": 2066 }
class ____(NamedTuple): eigenvalues: NDArray[Any] eigenvectors: NDArray[Any]
EigResult
python
doocs__leetcode
solution/3500-3599/3598.Longest Common Prefix Between Adjacent Strings After Removals/Solution.py
{ "start": 0, "end": 927 }
class ____: def longestCommonPrefix(self, words: List[str]) -> List[int]: @cache def calc(s: str, t: str) -> int: k = 0 for a, b in zip(s, t): if a != b: break k += 1 return k def add(i: int, j: int): ...
Solution
python
sympy__sympy
sympy/stats/stochastic_process_types.py
{ "start": 61470, "end": 65766 }
class ____(DiscreteTimeStochasticProcess): """ The Bernoulli process consists of repeated independent Bernoulli process trials with the same parameter `p`. It's assumed that the probability `p` applies to every trial and that the outcomes of each trial are independent of all the rest. Therefore ...
BernoulliProcess
python
google__jax
jax/_src/custom_batching.py
{ "start": 1618, "end": 6630 }
class ____: """Customize the vmap behavior of a JAX-transformable function. This decorator is used to customize the behavior of a JAX function under the :func:`jax.vmap` transformation. A ``custom_vmap``-decorated function will mostly (see below for caveats) have the same behavior as the underlying function,...
custom_vmap
python
sympy__sympy
sympy/combinatorics/coset_table.py
{ "start": 419, "end": 43316 }
class ____(DefaultPrinting): # coset_table: Mathematically a coset table # represented using a list of lists # alpha: Mathematically a coset (precisely, a live coset) # represented by an integer between i with 1 <= i <= n # alpha in c # x: Mathematically an element of "...
CosetTable
python
pallets__jinja
src/jinja2/lexer.py
{ "start": 9013, "end": 13030 }
class ____: """A token stream is an iterable that yields :class:`Token`\\s. The parser however does not iterate over it but calls :meth:`next` to go one token ahead. The current active token is stored as :attr:`current`. """ def __init__( self, generator: t.Iterable[Token], ...
TokenStream
python
dask__dask
dask/dataframe/dask_expr/_groupby.py
{ "start": 14917, "end": 16516 }
class ____(GroupbyAggregationBase): """Groupby aggregation for decomposable aggregates The results may be calculated via tree or shuffle reduction. """ chunk = staticmethod(_groupby_apply_funcs) @classmethod def combine(cls, inputs, **kwargs): return _groupby_apply_funcs(_concat(input...
DecomposableGroupbyAggregation
python
pytorch__pytorch
tools/experimental/torchfuzz/multi_process_fuzzer.py
{ "start": 1423, "end": 23771 }
class ____: seed: int success: bool output: str duration: float ignored_pattern_idx: int operation_stats: dict[str, int] # New field for operation statistics def is_ignored_output(output: str) -> int: """ Check if the output matches any ignore pattern. Args: output: The c...
FuzzerResult
python
streamlit__streamlit
lib/streamlit/errors.py
{ "start": 13071, "end": 13293 }
class ____(LocalizableStreamlitException): """Exception raised when a number exceeds the Javascript limits.""" def __init__(self, message: str) -> None: super().__init__(message)
StreamlitJSNumberBoundsError
python
pytorch__pytorch
torch/_export/serde/schema.py
{ "start": 4572, "end": 4673 }
class ____: name: Annotated[str, 10] class_fqn: Annotated[str, 20] @dataclass
CustomObjArgument
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/ruff/RUF012.py
{ "start": 1516, "end": 1760 }
class ____(F): mutable_default: list[int] = [] immutable_annotation: Sequence[int] = [] without_annotation = [] class_variable: ClassVar[list[int]] = [] final_variable: Final[list[int]] = [] from pydantic import BaseConfig
G
python
tornadoweb__tornado
tornado/http1connection.py
{ "start": 30323, "end": 33072 }
class ____(httputil.HTTPMessageDelegate): """Wraps an `HTTPMessageDelegate` to decode ``Content-Encoding: gzip``.""" def __init__(self, delegate: httputil.HTTPMessageDelegate, chunk_size: int) -> None: self._delegate = delegate self._chunk_size = chunk_size self._decompressor = None # ...
_GzipMessageDelegate
python
encode__django-rest-framework
tests/authentication/test_authentication.py
{ "start": 902, "end": 988 }
class ____(TokenAuthentication): keyword = 'Bearer'
CustomKeywordTokenAuthentication
python
ray-project__ray
python/ray/util/placement_group.py
{ "start": 1344, "end": 20584 }
class ____: """A handle to a placement group.""" @staticmethod def empty() -> "PlacementGroup": return PlacementGroup(PlacementGroupID.nil()) def __init__( self, id: "ray._raylet.PlacementGroupID", bundle_cache: Optional[List[Dict]] = None, ): self.id = id ...
PlacementGroup
python
Textualize__textual
src/textual/widgets/_markdown.py
{ "start": 16348, "end": 16684 }
class ____(Static): """Widget for table cells. A shim over a Static which responds to links. """ async def action_link(self, href: str) -> None: """Pass a link action on to the MarkdownTable parent.""" self.post_message(Markdown.LinkClicked(self.query_ancestor(Markdown), href))
MarkdownTableCellContents
python
huggingface__transformers
src/transformers/models/t5gemma/modeling_t5gemma.py
{ "start": 3875, "end": 10595 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: T5GemmaConfig, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self...
T5GemmaRotaryEmbedding
python
spack__spack
lib/spack/spack/test/oci/mock_registry.py
{ "start": 2028, "end": 2768 }
class ____: def __init__(self, domain: str) -> None: # The domain of the server, e.g. "registry.example.com" self.domain = domain # List of (method, url) tuples self.requests: List[Tuple[str, str]] = [] # Dispatches requests to handlers self.router = Router() ...
DummyServer
python
huggingface__transformers
src/transformers/cache_utils.py
{ "start": 2642, "end": 6016 }
class ____(CacheLayerMixin): """ A cache layer that grows dynamically as more tokens are generated. This is the default for generative models. It stores the key and value states as tensors of shape `[batch_size, num_heads, seq_len, head_dim]`. """ is_sliding = False def lazy_initialization(sel...
DynamicLayer
python
numba__numba
numba/tests/test_lists.py
{ "start": 30277, "end": 37227 }
class ____(ManagedListTestCase): def compile_and_test(self, pyfunc, *args): from copy import deepcopy expect_args = deepcopy(args) expect = pyfunc(*expect_args) njit_args = deepcopy(args) cfunc = jit(nopython=True)(pyfunc) got = cfunc(*njit_args) self.asser...
TestListOfList
python
pytorch__pytorch
torch/_inductor/augmented_graph_helper.py
{ "start": 150, "end": 7057 }
class ____: """ Graph helper that augments the original graph with additional dependencies and uses, plus tracks node equivalences for coalescing. TODO: if this becomes too large of compile time, consider binding graphcycles.cc """ def __init__( self, graph: fx.Graph, ...
AugmentedGraphHelper
python
google__jax
tests/compilation_cache_test.py
{ "start": 1918, "end": 2667 }
class ____(CacheInterface): """An in-memory cache for testing purposes.""" # not used, but required by `CacheInterface` _path = pathlib.Path() def __init__(self): self._cache: dict[str, bytes] = {} def get(self, key: str) -> bytes | None: return self._cache.get(key) def put(s...
InMemoryCache
python
mlflow__mlflow
mlflow/entities/trace_location.py
{ "start": 1455, "end": 2289 }
class ____(TraceLocationBase): """ Represents the location of a Databricks inference table. Args: full_table_name: The fully qualified name of the inference table where the trace is stored, in the format of `<catalog>.<schema>.<table>`. """ full_table_name: str def to_prot...
InferenceTableLocation
python
Lightning-AI__lightning
src/lightning/pytorch/plugins/precision/precision.py
{ "start": 1174, "end": 7399 }
class ____(FabricPrecision, CheckpointHooks): """Base class for all plugins handling the precision-specific parts of the training. The class attribute precision must be overwritten in child classes. The default value reflects fp32 training. """ def connect( self, model: Module, optimizers: li...
Precision
python
pytorch__pytorch
test/test_fx_passes.py
{ "start": 20536, "end": 21124 }
class ____: @staticmethod def forward(x): x = x + 1 # target subgraph to match x = x.relu() y = x.sigmoid() y1 = x.sigmoid() return y, y1 @staticmethod def pattern(a): a = a.relu() b = a.sigmoid() b1 = a.sigmoid() return ...
MultipleOutputsIdenticalAnchor
python
django-haystack__django-haystack
test_haystack/elasticsearch_tests/test_elasticsearch_query.py
{ "start": 8719, "end": 9810 }
class ____(TestCase): def setUp(self): super().setUp() self.backend = connections["elasticsearch"].get_backend() self._elasticsearch_version = elasticsearch.VERSION elasticsearch.VERSION = (0, 9, 9) def tearDown(self): elasticsearch.VERSION = self._elasticsearch_version ...
ElasticsearchSearchQuerySpatialBeforeReleaseTestCase
python
astropy__astropy
astropy/convolution/kernels.py
{ "start": 27652, "end": 29680 }
class ____(Kernel1D): """ Create kernel from 1D model. The model has to be centered on x = 0. Parameters ---------- model : `~astropy.modeling.Fittable1DModel` Kernel response function model x_size : int, optional Size in x direction of the kernel array. Default = ⌊8*width ...
Model1DKernel
python
openai__openai-python
src/openai/resources/responses/input_items.py
{ "start": 4328, "end": 7816 }
class ____(AsyncAPIResource): @cached_property def with_raw_response(self) -> AsyncInputItemsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www...
AsyncInputItems
python
kamyu104__LeetCode-Solutions
Python/minimum-division-operations-to-make-array-non-decreasing.py
{ "start": 483, "end": 893 }
class ____(object): def minOperations(self, nums): """ :type nums: List[int] :rtype: int """ result = 0 for i in reversed(xrange(len(nums)-1)): if nums[i] <= nums[i+1]: continue if SPF[nums[i]] > nums[i+1]: retur...
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/components/resolved/core_models.py
{ "start": 9042, "end": 9235 }
class ____(SharedAssetKwargs): """The attributes of an AssetSpec that can be updated after the AssetsDefinition is created, done via map_asset_specs. """ @record
AssetsDefUpdateKwargs
python
gevent__gevent
src/gevent/tests/test__greenlet.py
{ "start": 7007, "end": 7086 }
class ____(TestReturn_link): link_method = 'link_value'
TestReturn_link_value
python
spyder-ide__spyder
spyder/plugins/outlineexplorer/widgets.py
{ "start": 2209, "end": 5730 }
class ____: def __init__(self, name, kind, position, path, node=None): self.name = name self.position = position self.kind = kind self.node = node self.path = path self.id = str(uuid.uuid4()) self.index = None self.children = [] self.status = F...
SymbolStatus
python
kamyu104__LeetCode-Solutions
Python/minimum-window-substring.py
{ "start": 91, "end": 772 }
class ____(object): def minWindow(self, s, t): """ :type s: str :type t: str :rtype: str """ count, remain = collections.Counter(t), len(t) i, left, right = 0, -1, -1 for j, c in enumerate(s): remain -= count[c] > 0 count[c] -= ...
Solution
python
paramiko__paramiko
paramiko/channel.py
{ "start": 48989, "end": 49222 }
class ____(ChannelFile): """ A file-like wrapper around `.Channel` stdin. See `Channel.makefile_stdin` for details. """ def close(self): super().close() self.channel.shutdown_write()
ChannelStdinFile
python
streamlit__streamlit
lib/tests/streamlit/watcher/folder_black_list_test.py
{ "start": 775, "end": 2192 }
class ____(unittest.TestCase): def test_do_blacklist(self): """ miniconda, anaconda, and .*/ folders should be blacklisted. """ folder_black_list = FolderBlackList([]) is_blacklisted = folder_black_list.is_blacklisted assert is_blacklisted("/foo/miniconda2/script.py"...
FileIsInFolderTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 92462, "end": 92897 }
class ____(sgqlc.types.Enum): """The repository's visibility level. Enumeration Choices: * `INTERNAL`: The repository is visible only to users in the same business. * `PRIVATE`: The repository is visible only to those with explicit access. * `PUBLIC`: The repository is visible to every...
RepositoryVisibility