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
sqlalchemy__sqlalchemy
test/orm/test_mapper.py
{ "start": 86296, "end": 88207 }
class ____(fixtures.TestBase): def setup_test(self): self.mapper = registry().map_imperatively def test_doc_propagate(self): metadata = MetaData() t1 = Table( "t1", metadata, Column( "col1", Integer, primary_key=True, doc="primary key ...
DocumentTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeAlias21.py
{ "start": 210, "end": 262 }
class ____(Generic[D]): pass GenAlias = Gen[E]
Gen
python
dagster-io__dagster
python_modules/libraries/dagster-census/dagster_census/components/census_scaffolder.py
{ "start": 349, "end": 818 }
class ____(Scaffolder[CensusScaffolderParams]): @classmethod def get_scaffold_params(cls) -> type[CensusScaffolderParams]: return CensusScaffolderParams def scaffold(self, request: ScaffoldRequest[CensusScaffolderParams]) -> None: scaffold_component( request, { ...
CensusComponentScaffolder
python
walkccc__LeetCode
solutions/1109. Corporate Flight Bookings/1109.py
{ "start": 0, "end": 317 }
class ____: def corpFlightBookings(self, bookings: list[list[int]], n: int) -> list[int]: ans = [0] * n for booking in bookings: ans[booking[0] - 1] += booking[2] if booking[1] < n: ans[booking[1]] -= booking[2] for i in range(1, n): ans[i] += ans[i - 1] return ans
Solution
python
getsentry__sentry
tests/sentry/integrations/utils/test_scope.py
{ "start": 586, "end": 2300 }
class ____(TestCase): def test_finds_single_org(self) -> None: org = self.create_organization(slug="dogsaregreat") with assume_test_silo_mode(SiloMode.CONTROL): integration = self.create_provider_integration(name="squirrelChasers") integration.add_organization(org) a...
GetOrgsFromIntegrationTest
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 41520, "end": 43475 }
class ____(burr_gen): r"""A Fisk continuous random variable. The Fisk distribution is also known as the log-logistic distribution. %(before_notes)s See Also -------- burr Notes ----- The probability density function for `fisk` is: .. math:: f(x, c) = \frac{c x^{c-1}...
fisk_gen
python
pytorch__pytorch
test/torch_np/numpy_tests/lib/test_twodim_base.py
{ "start": 16977, "end": 17260 }
class ____(TestCase): def test_exceptions(self): assert_raises(ValueError, tril_indices_from, np.ones((2,))) assert_raises(ValueError, tril_indices_from, np.ones((2, 2, 2))) # assert_raises(ValueError, tril_indices_from, np.ones((2, 3)))
TestTrilIndicesFrom
python
sqlalchemy__sqlalchemy
test/orm/test_session.py
{ "start": 44144, "end": 49843 }
class ____(_fixtures.FixtureTest): run_inserts = None run_deletes = "each" @classmethod def setup_mappers(cls): users, Address, addresses, User = ( cls.tables.users, cls.classes.Address, cls.tables.addresses, cls.classes.User, ) c...
DeferredRelationshipExpressionTest
python
chroma-core__chroma
chromadb/types.py
{ "start": 7793, "end": 7976 }
class ____(TypedDict): id: str embedding: Optional[Vector] encoding: Optional[ScalarEncoding] metadata: Optional[UpdateMetadata] operation: Operation
OperationRecord
python
matplotlib__matplotlib
lib/mpl_toolkits/axisartist/axislines.py
{ "start": 15622, "end": 16214 }
class ____(Axes): def clear(self): super().clear() new_floating_axis = self.get_grid_helper().new_floating_axis self._axislines.update( xzero=new_floating_axis( nth_coord=0, value=0., axis_direction="bottom", axes=self), yzero=new_floating_axis( ...
AxesZero
python
PrefectHQ__prefect
src/prefect/context.py
{ "start": 26420, "end": 34706 }
class ____(ContextModel): """ The context for a Prefect settings. This allows for safe concurrent access and modification of settings. Attributes: profile: The profile that is in use. settings: The complete settings model. """ profile: Profile settings: Settings __var...
SettingsContext
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/data.py
{ "start": 14377, "end": 17050 }
class ____: """A lazy collection of ``Span`` objects, derived from the record of recorded behaviour in ``SpanRecord``. Behaves logically as if it were a list of ``Span`` objects, but actually mostly exists as a compact store of information for them to reference into. All properties on here are best...
Spans
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 87440, "end": 96374 }
class ____(Loops): # Sorts a tuple of key, value pairs sort_ranges: list[Integer] size: list[Integer] reindex: Callable[[Sequence[Expr], Sequence[Expr]], Sequence[Expr]] reduction_hint: ReductionHint output_index: int # output_index indexes the following tuples dtypes: tuple[torch.dtype,...
Sort
python
mlflow__mlflow
mlflow/gateway/schemas/completions.py
{ "start": 1426, "end": 1521 }
class ____(ResponseModel): role: str | None = None content: str | None = None
StreamDelta
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/overrides.py
{ "start": 3579, "end": 3671 }
class ____(TooManyOverrides): def return_source(self): pass
TooManyOverridesChild1
python
tiangolo__fastapi
docs_src/schema_extra_example/tutorial004_an.py
{ "start": 150, "end": 965 }
class ____(BaseModel): name: str description: Union[str, None] = None price: float tax: Union[float, None] = None @app.put("/items/{item_id}") async def update_item( *, item_id: int, item: Annotated[ Item, Body( examples=[ { "...
Item
python
apache__airflow
providers/google/tests/unit/google/cloud/triggers/test_cloud_run.py
{ "start": 1721, "end": 5508 }
class ____: def test_serialization(self, trigger): classpath, kwargs = trigger.serialize() assert classpath == "airflow.providers.google.cloud.triggers.cloud_run.CloudRunJobFinishedTrigger" assert kwargs == { "project_id": PROJECT_ID, "operation_name": OPERATION_NAME,...
TestCloudBatchJobFinishedTrigger
python
qdrant__qdrant-client
tests/congruence_tests/test_query.py
{ "start": 1097, "end": 62458 }
class ____: __test__ = False def __init__(self): # group by self.group_by = "city.geo" self.group_size = 3 self.limit = 2 # number of groups # dense query vectors self.dense_vector_query_text = np.random.random(text_vector_size).tolist() self.dense_vect...
TestSimpleSearcher
python
getsentry__sentry
src/sentry/replays/usecases/ingest/types.py
{ "start": 79, "end": 230 }
class ____(TypedDict): has_sent_replays_cache: AutoCache[int, bool] | None options_cache: AutoCache[int, tuple[bool, bool]] | None
ProcessorContext
python
huggingface__transformers
tests/utils/import_structures/import_structure_raw_register_with_versions.py
{ "start": 1574, "end": 1696 }
class ____: def __init__(self): pass @requires(backends=("torch>=2.5", "accelerate<0.20")) def d6(): pass
D6
python
getsentry__sentry
src/sentry/sentry_apps/models/sentry_app_installation_token.py
{ "start": 2430, "end": 3177 }
class ____(ControlOutboxProducingModel): __relocation_scope__ = RelocationScope.Excluded api_token = FlexibleForeignKey("sentry.ApiToken") sentry_app_installation = FlexibleForeignKey("sentry.SentryAppInstallation") objects: ClassVar[SentryAppInstallationTokenManager] = SentryAppInstallationTokenManag...
SentryAppInstallationToken
python
huggingface__transformers
tests/utils/import_structures/import_structure_register_with_duplicates.py
{ "start": 882, "end": 1072 }
class ____: def __init__(self): pass @requires(backends=("torch", "torch")) # That's a statement def c1(): pass @requires(backends=("torch", "torch")) # That's a statement
C1
python
facebook__pyre-check
client/backend_arguments.py
{ "start": 1059, "end": 1568 }
class ____: logger: str identifier: str = "" @staticmethod def create( logger: Optional[str] = None, identifier: Optional[str] = None ) -> "Optional[RemoteLogging]": return ( RemoteLogging(logger=logger, identifier=identifier or "") if logger is not None ...
RemoteLogging
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_hyperlink12.py
{ "start": 315, "end": 1632 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("hyperlink12.xlsx") def test_create_file(self): """ Test the creation of a simple XlsxWriter file with hyperlinks. This exam...
TestCompareXLSXFiles
python
pytorch__pytorch
torch/cuda/__init__.py
{ "start": 13183, "end": 18480 }
class ____(Exception): pass AcceleratorError = torch._C.AcceleratorError OutOfMemoryError = torch._C.OutOfMemoryError def init(): r"""Initialize PyTorch's CUDA state. You may need to call this explicitly if you are interacting with PyTorch via its C API, as Python bindings for CUDA functionality ...
DeferredCudaCallError
python
Textualize__textual
tests/tree/test_tree_availability.py
{ "start": 161, "end": 4240 }
class ____(App[None]): """Test tree app.""" def __init__(self, disabled: bool, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.disabled = disabled self.messages: list[tuple[str, str]] = [] def compose(self) -> ComposeResult: """Compose the child w...
TreeApp
python
explosion__spaCy
spacy/schemas.py
{ "start": 16080, "end": 17198 }
class ____(BaseModel): # fmt: off lang: StrictStr = Field(..., title="The base language to use") pipeline: List[StrictStr] = Field(..., title="The pipeline component names in order") disabled: List[StrictStr] = Field(..., title="Pipeline components to disable by default") tokenizer: Callable = Field...
ConfigSchemaNlp
python
scikit-learn__scikit-learn
sklearn/base.py
{ "start": 42057, "end": 42284 }
class ____: """Mixin to mark estimators that support multioutput.""" def __sklearn_tags__(self): tags = super().__sklearn_tags__() tags.target_tags.multi_output = True return tags
MultiOutputMixin
python
getsentry__sentry-python
sentry_sdk/integrations/wsgi.py
{ "start": 7706, "end": 10809 }
class ____: """ Users a separate scope for each response chunk. This will make WSGI apps more tolerant against: - WSGI servers streaming responses from a different thread/from different threads than the one that called start_response - close() not being called - WSGI servers streaming res...
_ScopedResponse
python
prabhupant__python-ds
data_structures/bst/range_sum.py
{ "start": 0, "end": 674 }
class ____(): def __init__(self, val): self.val = val self.left = None self.right = None def range_sum_preorder(root, L, R): stack = [root] sum = 0 while stack: node = stack.pop() if node: if L <= node.val <= R: sum += node.val ...
Node
python
pyca__cryptography
.github/bin/merge_rust_coverage.py
{ "start": 670, "end": 4473 }
class ____(coverage.FileReporter): def __init__( self, filename: str, coverage_data: collections.abc.Mapping[int, int] ) -> None: super().__init__(filename) self._data = coverage_data def lines(self) -> set[int]: return set(self._data) def arcs(self) -> set[tuple[int, i...
RustCoverageFileReporter
python
sqlalchemy__sqlalchemy
test/base/test_warnings.py
{ "start": 397, "end": 1331 }
class ____(fixtures.TestBase): __backend__ = False def test_warn_deprecated_limited_text(self): with expect_deprecated("foo has been deprecated"): warn_deprecated_limited( "%s has been deprecated [%d]", ("foo", 1), "1.3" ) def test_warn_deprecated_limited_ca...
WarnDeprecatedLimitedTest
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modular_qwen2_5_omni.py
{ "start": 77691, "end": 85311 }
class ____(Qwen2_5OmniPreTrainedModel): config: Qwen2_5OmniAudioEncoderConfig main_input_name = "input_features" input_modalities = "audio" _no_split_modules = ["Qwen2_5OmniAudioEncoderLayer"] _supports_sdpa = True def __init__(self, config: Qwen2_5OmniAudioEncoderConfig): super().__ini...
Qwen2_5OmniAudioEncoder
python
networkx__networkx
networkx/exception.py
{ "start": 3235, "end": 3787 }
class ____(ExceededMaxIterations): """Raised when the power iteration method fails to converge within a specified iteration limit. `num_iterations` is the number of iterations that have been completed when this exception was raised. """ def __init__(self, num_iterations, *args, **kw): ...
PowerIterationFailedConvergence
python
django__django
tests/admin_changelist/test_date_hierarchy.py
{ "start": 334, "end": 3765 }
class ____(TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", email="a@b.com", password="xxx" ) def assertDateParams(self, query, expected_from_date, expected_to_date): query = ...
DateHierarchyTests
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-sheets/unit_tests/integration/test_exception_description.py
{ "start": 1930, "end": 9761 }
class ____(GoogleSheetsBaseTest): @HttpMocker() def test_invalid_link_error_message_when_check(self, http_mocker: HttpMocker) -> None: GoogleSheetsBaseTest.get_spreadsheet_info_and_sheets(http_mocker, "invalid_link", status_codes.NOT_FOUND) error_message = exception_description_by_status_code(st...
TestExceptionDescriptionByStatusCode
python
huggingface__transformers
tests/models/ernie4_5_moe/test_modeling_ernie4_5_moe.py
{ "start": 5391, "end": 7118 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls): cls.model = None @classmethod def tearDownClass(cls): del cls.model cleanup(torch_device, gc_collect=True) def tearDown(self): cleanup(torch_device, gc_collect=True) @classmethod def get_model...
Ernie4_5_MoeIntegrationTest
python
scipy__scipy
scipy/io/arff/tests/test_arffread.py
{ "start": 6023, "end": 8097 }
class ____: def setup_method(self): self.data, self.meta = loadarff(test7) def test_year_attribute(self): expected = np.array([ '1999', '2004', '1817', '2100', '2013', '1631' ], dtype='datetime64[Y]') asser...
TestDateAttribute
python
aio-libs__aiohttp
aiohttp/client_exceptions.py
{ "start": 5847, "end": 6151 }
class ____(ServerConnectionError): """Server disconnected.""" def __init__(self, message: RawResponseMessage | str | None = None) -> None: if message is None: message = "Server disconnected" self.args = (message,) self.message = message
ServerDisconnectedError
python
kamyu104__LeetCode-Solutions
Python/determine-if-a-cell-is-reachable-at-a-given-time.py
{ "start": 61, "end": 426 }
class ____(object): def isReachableAtTime(self, sx, sy, fx, fy, t): """ :type sx: int :type sy: int :type fx: int :type fy: int :type t: int :rtype: bool """ diff1, diff2 = abs(sx-fx), abs(sy-fy) mn = min(diff1, diff2)+abs(diff1-diff2) ...
Solution
python
getsentry__sentry-python
scripts/init_serverless_sdk.py
{ "start": 732, "end": 2765 }
class ____: DIR_PATH_REGEX = r"^(.+)\/([^\/]+)$" def __init__(self, sentry_initial_handler): try: module_path, self.handler_name = sentry_initial_handler.rsplit(".", 1) except ValueError: raise ValueError("Incorrect AWS Handler path (Not a path)") self.extract_a...
AWSLambdaModuleLoader
python
walkccc__LeetCode
solutions/2448. Minimum Cost to Make Array Equal/2448.py
{ "start": 0, "end": 443 }
class ____: def minCost(self, nums: list[int], cost: list[int]) -> int: ans = 0 l = min(nums) r = max(nums) def getCost(target: int) -> int: return sum(abs(num - target) * c for num, c in zip(nums, cost)) while l < r: m = (l + r) // 2 cost1 = getCost(m) cost2 = getCost(m ...
Solution
python
keras-team__keras
keras/src/callbacks/model_checkpoint.py
{ "start": 325, "end": 18570 }
class ____(MonitorCallback): """Callback to save the Keras model or model weights at some frequency. `ModelCheckpoint` callback is used in conjunction with training using `model.fit()` to save a model or weights (in a checkpoint file) at some interval, so the model or weights can be loaded later to con...
ModelCheckpoint
python
etianen__django-reversion
tests/test_app/tests/test_api.py
{ "start": 5532, "end": 5973 }
class ____(TestModelMixin, TestBase): databases = {"default", "mysql", "postgres"} def testCreateRevisionMultiDb(self): with reversion.create_revision(using="mysql"), reversion.create_revision(using="postgres"): obj = TestModel.objects.create() self.assertNoRevision() self.a...
CreateRevisionDbTest
python
tensorflow__tensorflow
tensorflow/python/checkpoint/checkpoint.py
{ "start": 43673, "end": 47857 }
class ____(_LoadStatus): """Status for loading a name-based training checkpoint.""" # Ideally this deprecation decorator would be on the class, but that # interferes with isinstance checks. @deprecation.deprecated( date=None, instructions=_DEPRECATED_RESTORE_INSTRUCTIONS) def __init__(self, checkpoint,...
NameBasedSaverStatus
python
dagster-io__dagster
python_modules/libraries/dagster-k8s/dagster_k8s/job.py
{ "start": 1831, "end": 2786 }
class ____(Enum): SHALLOW = ( # Top-level keys in each of 'container_config' / 'pod_spec_config' are replaced "SHALLOW" ) DEEP = ( # Dictionaries are deep-merged, lists are appended after removing values that are already present "DEEP" ) USER_DEFINED_K8S_CONFIG_KEY = "dagster-k8s/con...
K8sConfigMergeBehavior
python
realpython__materials
tic-tac-toe-ai-python/source_code_bonus/tic-tac-toe/frontends/window/renderers.py
{ "start": 797, "end": 1526 }
class ____(Renderer): def __init__(self, window: Window) -> None: self.window = window def render(self, game_state: GameState) -> None: for label, button in zip( game_state.grid.cells, self.window.buttons, strict=False ): button.config(text=label) if game...
WindowRenderer
python
celery__celery
t/unit/worker/test_consumer.py
{ "start": 28639, "end": 30075 }
class ____(ConsumerTestCase): def test_start_raises_connection_error(self, broker_connection_retry_on_startup, is_connection_loss_on_startup, caplog, subtests): c = self.get_cons...
test_Consumer_WorkerShutdown
python
pyca__cryptography
tests/x509/test_x509_ext.py
{ "start": 87885, "end": 88740 }
class ____: def test_eq(self): crl_number = x509.CRLNumber(15) assert crl_number == x509.CRLNumber(15) def test_ne(self): crl_number = x509.CRLNumber(15) assert crl_number != x509.CRLNumber(14) assert crl_number != object() def test_repr(self): crl_number = ...
TestCRLNumber
python
doocs__leetcode
lcci/04.08.First Common Ancestor/Solution.py
{ "start": 164, "end": 526 }
class ____: def lowestCommonAncestor( self, root: TreeNode, p: TreeNode, q: TreeNode ) -> TreeNode: if root is None or root in [p, q]: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) return root...
Solution
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modular_mm_grounding_dino.py
{ "start": 15590, "end": 15657 }
class ____(GroundingDinoConvModel): pass
MMGroundingDinoConvModel
python
openai__openai-python
src/openai/resources/containers/files/content.py
{ "start": 612, "end": 3033 }
class ____(SyncAPIResource): @cached_property def with_raw_response(self) -> ContentWithRawResponse: """ 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.github.c...
Content
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 333158, "end": 334029 }
class ____(sgqlc.types.Input): """Autogenerated input type of UpdateEnterpriseAdministratorRole""" __schema__ = github_schema __field_names__ = ("enterprise_id", "login", "role", "client_mutation_id") enterprise_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="enterpriseId") """The ID...
UpdateEnterpriseAdministratorRoleInput
python
pytorch__pytorch
torch/_inductor/compiler_bisector.py
{ "start": 2401, "end": 2882 }
class ____: """ backend: torch.compile backend responsible for failure subsystem: optional, registered component identified for failure bisect_number: optional, number of times the subsystem needed to be applied to trigger failure debug_info: associated info of the triggering bisect application of s...
BisectionResult
python
readthedocs__readthedocs.org
readthedocs/projects/migrations/0047_webhook_url_set_blank_default.py
{ "start": 149, "end": 512 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("projects", "0046_domain_hsts_fields"), ] operations = [ migrations.AlterField( model_name="webhook", name="url", field=models.URLField(help_text="URL to send the webhook t...
Migration
python
getsentry__sentry
tests/sentry/tasks/test_post_process.py
{ "start": 67567, "end": 74467 }
class ____(BasePostProgressGroupMixin): @patch("sentry.signals.issue_unignored.send_robust") @patch("sentry.rules.processing.processor.RuleProcessor") def test_invalidates_snooze( self, mock_processor: MagicMock, mock_send_unignored_robust: MagicMock ) -> None: event = self.create_event(...
SnoozeTestMixin
python
walkccc__LeetCode
solutions/3560. Find Minimum Log Transportation Cost/3560.py
{ "start": 0, "end": 112 }
class ____: def minCuttingCost(self, n: int, m: int, k: int) -> int: return max(0, max(n, m) - k) * k
Solution
python
pypa__installer
src/installer/sources.py
{ "start": 4546, "end": 11791 }
class ____(WheelSource): """Implements `WheelSource`, for an existing file from the filesystem. Example usage:: >>> with WheelFile.open("sampleproject-2.0.0-py3-none-any.whl") as source: ... installer.install(source, destination) """ validation_error = _WheelFileValidationError ...
WheelFile
python
ipython__ipython
IPython/terminal/pt_inputhooks/__init__.py
{ "start": 438, "end": 3606 }
class ____(KeyError): def __init__(self, name): self.name = name def __str__(self): return ("No event loop integration for {!r}. " "Supported event loops are: {}").format(self.name, ', '.join(backends + sorted(registered))) def set_qt_api(gu...
UnknownBackend
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/kubernetes_engine.py
{ "start": 29368, "end": 34781 }
class ____(GKEOperatorMixin, KubernetesJobOperator): """ Executes a Kubernetes job in the specified Google Kubernetes Engine cluster. This Operator assumes that the system has gcloud installed and has configured a connection id with a service account. The **minimum** required to define a cluster t...
GKEStartJobOperator
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_ordered_dict.py
{ "start": 43376, "end": 43666 }
class ____(SimpleLRUCacheTests, __TestCase): @classmethod def setUpClass(cls): class type2test(SimpleLRUCache, c_coll.OrderedDict): pass cls.type2test = type2test super().setUpClass() if __name__ == "__main__": run_tests()
CSimpleLRUCacheTests
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 511172, "end": 512242 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "done_count", "done_percentage", "enabled", "in_progress_count", "in_progress_percentage", "todo_count", "todo_percentage", ...
ProjectProgress
python
django__django
tests/db_functions/text/test_sha384.py
{ "start": 228, "end": 2152 }
class ____(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ...
SHA384Tests
python
Netflix__metaflow
metaflow/plugins/kubernetes/kubernetes_job.py
{ "start": 399, "end": 1736 }
class ____(MetaflowException): headline = "Kubernetes job error" # Implements truncated exponential backoff from # https://cloud.google.com/storage/docs/retry-strategy#exponential-backoff def k8s_retry(deadline_seconds=60, max_backoff=32): def decorator(function): from functools import wraps ...
KubernetesJobException
python
ray-project__ray
rllib/evaluation/observation_function.py
{ "start": 311, "end": 3182 }
class ____: """Interceptor function for rewriting observations from the environment. These callbacks can be used for preprocessing of observations, especially in multi-agent scenarios. Observation functions can be specified in the multi-agent config by specifying ``{"observation_fn": your_obs_func...
ObservationFunction
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-rungpt/llama_index/llms/rungpt/base.py
{ "start": 781, "end": 11790 }
class ____(LLM): """ RunGPT LLM. The opengpt of Jina AI models. Examples: `pip install llama-index-llms-rungpt` ```python from llama_index.llms.rungpt import RunGptLLM llm = RunGptLLM(model="rungpt", endpoint="0.0.0.0:51002") response = llm.complete("What pub...
RunGptLLM
python
run-llama__llama_index
llama-index-packs/llama-index-packs-code-hierarchy/tests/test_code_hierarchy_no_skeleton.py
{ "start": 534, "end": 5000 }
class ____: def bar() -> None: print("bar") async def baz(): print("baz")""" text_node = TextNode( text=text, metadata={ "module": "example.foo", }, ) chunks: List[TextNode] = code_splitter.get_nodes_from_documents([text_node]) # This is th...
Foo
python
vyperlang__vyper
vyper/builtins/functions.py
{ "start": 4086, "end": 5027 }
class ____(BuiltinFunctionT): _id = "ceil" _inputs = [("value", DecimalT())] # TODO: maybe use int136? _return_type = INT256_T def _try_fold(self, node): validate_call_args(node, 1) value = node.args[0].get_folded_value() if not isinstance(value, vy_ast.Decimal): ...
Ceil
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/multi_asset_sensor_definition.py
{ "start": 4998, "end": 7310 }
class ____: # Tracks the state of the cursor within the tick, created for utility purposes. # Must call MultiAssetSensorEvaluationContext._update_cursor_after_evaluation at end of tick # to serialize the cursor. def __init__(self, cursor: Optional[str], context: "MultiAssetSensorEvaluationContext"): ...
MultiAssetSensorContextCursor
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_checks.py
{ "start": 4990, "end": 5268 }
class ____(graphene.Enum): class Meta: name = "AssetCheckCanExecuteIndividually" CAN_EXECUTE = "CAN_EXECUTE" REQUIRES_MATERIALIZATION = "REQUIRES_MATERIALIZATION" NEEDS_USER_CODE_UPGRADE = "NEEDS_USER_CODE_UPGRADE"
GrapheneAssetCheckCanExecuteIndividually
python
pytorch__pytorch
torch/ao/quantization/experimental/linear.py
{ "start": 301, "end": 5933 }
class ____(WeightedQuantizedModule): r""" A quantized linear module with quantized tensor as inputs and outputs to support APoT quantization. We adopt the same interface as `torch.nn.Linear`, see https://pytorch.org/docs/stable/nn.html#torch.nn.Linear for documentation. Similar to :class:`~torc...
LinearAPoT
python
scipy__scipy
scipy/sparse/tests/test_spfuncs.py
{ "start": 340, "end": 3258 }
class ____: def test_scale_rows_and_cols(self): D = array([[1, 0, 0, 2, 3], [0, 4, 0, 5, 0], [0, 0, 6, 7, 0]]) #TODO expose through function S = csr_matrix(D) v = array([1,2,3]) csr_scale_rows(3,5,S.indptr,S.indices,S.data,v) ass...
TestSparseFunctions
python
numba__numba
numba/tests/test_typeof.py
{ "start": 20837, "end": 21678 }
class ____(TestCase): def test_memcpy_typeof_buffer(self): # https://github.com/numba/numba/issues/9097 # bug is fixed if the code below compiles random.seed(0) chars = string.ascii_letters n = 256 field = "".join([chars[random.randint(0, len(chars) - 1)] for x in ra...
TestTypeOfMemCpy
python
dask__dask
dask/dataframe/dask_expr/io/parquet.py
{ "start": 25085, "end": 28772 }
class ____(PartitionsFiltered, BlockwiseIO): _pickle_functools_cache = False _absorb_projections = True _filter_passthrough = False def _filter_passthrough_available(self, parent, dependents): return ( super()._filter_passthrough_available(parent, dependents) and (isinst...
ReadParquet
python
Textualize__textual
docs/examples/guide/widgets/checker02.py
{ "start": 145, "end": 1155 }
class ____(Widget): """Render an 8x8 checkerboard.""" COMPONENT_CLASSES = { "checkerboard--white-square", "checkerboard--black-square", } DEFAULT_CSS = """ CheckerBoard .checkerboard--white-square { background: #A5BAC9; } CheckerBoard .checkerboard--black-square { ...
CheckerBoard
python
huggingface__transformers
src/transformers/optimization.py
{ "start": 28676, "end": 38403 }
class ____(Optimizer): """ AdaFactor pytorch implementation can be used as a drop in replacement for Adam original fairseq code: https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py Paper: *Adafactor: Adaptive Learning Rates with Sublinear Memory Cost* https://huggingface.co/papers...
Adafactor
python
getsentry__sentry
src/sentry/plugins/config.py
{ "start": 468, "end": 2500 }
class ____: def __init__(self, config, data=None, initial=None, context=None): self.errors = {} self.result = {} self.context = context or {} self.config = {f["name"]: f for f in config} self._data = data or {} self._initial = initial or {} self._validated =...
ConfigValidator
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-scrapegraph/tests/test_integration.py
{ "start": 5029, "end": 8587 }
class ____: """Test Pydantic schema validation and integration.""" @pytest.fixture def mock_tool_spec(self): """Create a mocked tool spec for schema testing.""" with patch("llama_index.tools.scrapegraph.base.Client") as mock_client_class: mock_client = Mock() mock_cl...
TestSchemaValidation
python
PyCQA__pylint
doc/data/messages/m/multiple-constructor-doc/good.py
{ "start": 0, "end": 214 }
class ____: def __init__(self, x, y): """Represents a point in the xy-coordinate plane. :param x: x coordinate :param y: y coordinate """ self.x = x self.y = y
Point
python
apache__airflow
providers/apache/beam/src/airflow/providers/apache/beam/operators/beam.py
{ "start": 38236, "end": 40561 }
class ____(_GoArtifact): def __init__(self, launcher: str, worker: str) -> None: self.launcher = launcher self.worker = worker def is_located_on_gcs(self) -> bool: return any(_object_is_located_on_gcs(path) for path in (self.launcher, self.worker)) def download_from_gcs(self, gcs_h...
_GoBinary
python
streamlit__streamlit
lib/streamlit/runtime/caching/storage/cache_storage_protocol.py
{ "start": 2765, "end": 2959 }
class ____(CacheStorageError): """Raised if the cache storage manager is not able to work with provided CacheStorageContext. """ @dataclass(frozen=True)
InvalidCacheStorageContextError
python
rq__rq
rq/cron.py
{ "start": 734, "end": 5461 }
class ____: """Represents a function to be run on a time interval""" def __init__( self, queue_name: str, func: Optional[Callable] = None, func_name: Optional[str] = None, args: Optional[Tuple] = None, kwargs: Optional[Dict] = None, interval: Optional[int...
CronJob
python
google__jax
jax/_src/core.py
{ "start": 98962, "end": 99357 }
class ____(AbstractValue): def str_short(self, short_dtypes=False, mesh_axis_types=False): return 'Tok' def to_tangent_aval(self): return self abstract_token: AbstractToken = AbstractToken() # Singleton shaped array used by all abstract tokens when shape/dtype is needed. def get_token_aval(): return ShapedArray(...
AbstractToken
python
sympy__sympy
sympy/functions/elementary/miscellaneous.py
{ "start": 26788, "end": 27944 }
class ____(DefinedFunction): """Returns the remainder when ``p`` is divided by ``q`` where ``p`` is finite and ``q`` is not equal to zero. The result, ``p - int(p/q)*q``, has the same sign as the divisor. Parameters ========== p : Expr Dividend. q : Expr Divisor. Note...
Rem
python
google__pytype
pytype/tests/test_containers.py
{ "start": 102, "end": 14696 }
class ____(test_base.BaseTest): """Tests for containers.""" def test_tuple_pass_through(self): self.Check(""" from typing import Tuple def f(x): return x assert_type(f((3, "str")), Tuple[int, str]) """) def test_tuple(self): self.Check(""" def f(x): return x[0...
ContainerTest
python
rapidsai__cudf
python/cudf_polars/cudf_polars/experimental/rapidsmpf/collectives/allgather.py
{ "start": 697, "end": 2599 }
class ____: """ AllGather manager. Parameters ---------- context: Context The streaming context. op_id: int Pre-allocated operation ID for this operation. """ def __init__(self, context: Context, op_id: int): self.context = context self.allgather = AllGa...
AllGatherManager
python
davidhalter__parso
test/test_cache.py
{ "start": 4071, "end": 6751 }
class ____(file_io.KnownContentFileIO): def __init__(self, path, content, last_modified): super().__init__(path, content) self._last_modified = last_modified def get_last_modified(self): return self._last_modified @pytest.mark.parametrize('diff_cache', [False, True]) @pytest.mark.para...
_FixedTimeFileIO
python
pallets__werkzeug
tests/test_http.py
{ "start": 22852, "end": 26198 }
class ____: def test_if_range_parsing(self): rv = http.parse_if_range_header('"Test"') assert rv.etag == "Test" assert rv.date is None assert rv.to_header() == '"Test"' # weak information is dropped rv = http.parse_if_range_header('W/"Test"') assert rv.etag =...
TestRange
python
pytorch__pytorch
test/jit/test_backends.py
{ "start": 22062, "end": 24602 }
class ____(JitBackendTestCase): """ Tests for CompModule, which is a module with two lowered submodules """ class BasicModuleSub(torch.nn.Module): """ A simple subtraction Module to be used in CompModule. """ def forward(self, x, h): return x - h class ...
CompModuleTestWithCompiler
python
bokeh__bokeh
src/bokeh/models/widgets/groups.py
{ "start": 3039, "end": 3364 }
class ____(ToggleInputGroup): ''' A group of check boxes. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) active = List(Int, help=""" The list of indices of selected check boxes. """)
CheckboxGroup
python
bokeh__bokeh
src/bokeh/document/json.py
{ "start": 2452, "end": 2796 }
class ____(TypedDict): kind: Literal["ColumnsPatched"] model: Ref attr: str patches: Patches DocumentPatched: TypeAlias = ( MessageSent | ModelChanged | ColumnDataChanged | ColumnsStreamed | ColumnsPatched | TitleChanged | RootAdded | RootRemoved ) DocumentChanged = Doc...
ColumnsPatched
python
huggingface__transformers
src/transformers/models/gemma3/modeling_gemma3.py
{ "start": 22099, "end": 27799 }
class ____(Gemma3PreTrainedModel): config: Gemma3TextConfig input_modalities = ("text",) def __init__(self, config: Gemma3TextConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size # Gemma3 downcasts the below to bfloat1...
Gemma3TextModel
python
getsentry__sentry
tests/sentry/incidents/models/test_incidents.py
{ "start": 5262, "end": 7288 }
class ____(TestCase): def setUp(self) -> None: self.alert_rule = self.create_alert_rule() self.trigger = self.create_alert_rule_trigger(self.alert_rule) self.incident = self.create_incident(alert_rule=self.alert_rule, projects=[self.project]) def test_deleted_incident(self) -> None: ...
IncidentTriggerClearCacheTest
python
django__django
tests/template_tests/test_loaders.py
{ "start": 325, "end": 4455 }
class ____(SimpleTestCase): def setUp(self): self.engine = Engine( dirs=[TEMPLATE_DIR], loaders=[ ( "django.template.loaders.cached.Loader", [ "django.template.loaders.filesystem.Loader", ...
CachedLoaderTests
python
mitmproxy__pdoc
test/testdata/with_pydantic.py
{ "start": 67, "end": 333 }
class ____(pydantic.BaseModel): """Foo class documentation.""" model_config = pydantic.ConfigDict( use_attribute_docstrings=True, ) a: int = pydantic.Field(default=1, description="Docstring for a") b: int = 2 """Docstring for b."""
Foo
python
pytorch__pytorch
test/distributed/elastic/agent/server/test/api_test.py
{ "start": 15185, "end": 35440 }
class ____(unittest.TestCase): def _get_worker_spec( self, max_restarts=1, monitor_interval=0.1, role="test_trainer", local_world_size=8, local_addr=None, event_log_handler="null", ): run_id = str(uuid.uuid4().int) port = get_free_port() ...
SimpleElasticAgentTest
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/behavior_id_utils.py
{ "start": 169, "end": 2134 }
class ____(NamedTuple): """ BehaviorIdentifiers is a named tuple of the identifiers that uniquely distinguish an agent encountered in the trainer_controller. The named tuple consists of the fully qualified behavior name, the name of the brain name (corresponds to trainer in the trainer controller) a...
BehaviorIdentifiers
python
jazzband__django-pipeline
pipeline/forms.py
{ "start": 7847, "end": 9287 }
class ____(metaclass=PipelineFormMediaMetaClass): """Base class for form or widget Media classes that use Pipeline packages. Forms or widgets that need custom CSS or JavaScript media on a page can define a standard :py:class:`Media` class that subclasses this class, listing the CSS or JavaScript packag...
PipelineFormMedia
python
tensorflow__tensorflow
tensorflow/python/keras/metrics.py
{ "start": 37965, "end": 39545 }
class ____(_ConfusionMatrixConditionCount): """Calculates the number of false negatives. If `sample_weight` is given, calculates the sum of the weights of false negatives. This metric creates one local variable, `accumulator` that is used to keep track of the number of false negatives. If `sample_weight` is...
FalseNegatives
python
arrow-py__arrow
tests/test_locales.py
{ "start": 77266, "end": 79108 }
class ____: def test_timeframes(self): # single assert self.locale._format_timeframe("minute", 1) == "دقيقة" assert self.locale._format_timeframe("hour", 1) == "ساعة" assert self.locale._format_timeframe("day", 1) == "يوم" assert self.locale._format_timeframe("week", 1) == "ا...
TestArabicLocale