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
falconry__falcon
tests/test_inspect.py
{ "start": 1678, "end": 9629 }
class ____: def test_empty_app(self, asgi): ai = inspect.inspect_app(get_app(asgi, False)) assert ai.routes == [] assert ai.middleware.middleware_tree.request == [] assert ai.middleware.middleware_tree.resource == [] assert ai.middleware.middleware_tree.response == [] ...
TestInspectApp
python
ansible__ansible
test/units/module_utils/common/test_utils.py
{ "start": 287, "end": 1783 }
class ____: class Base: pass class BranchI(Base): pass class BranchII(Base): pass class BranchIA(BranchI): pass class BranchIB(BranchI): pass class BranchIIA(BranchII): pass class BranchIIB(BranchII): pass class MultipleInher...
TestGetAllSubclasses
python
huggingface__transformers
src/transformers/models/distilbert/modeling_distilbert.py
{ "start": 16819, "end": 21693 }
class ____(DistilBertPreTrainedModel): _tied_weights_keys = {"vocab_projector.weight": "distilbert.embeddings.word_embeddings.weight"} def __init__(self, config: PreTrainedConfig): super().__init__(config) self.activation = get_activation(config.activation) self.distilbert = DistilBer...
DistilBertForMaskedLM
python
tensorflow__tensorflow
tensorflow/python/distribute/combinations_test.py
{ "start": 8286, "end": 9497 }
class ____(test.TestCase, parameterized.TestCase): def setUp(self): super().setUp() if combinations.in_main_process(): num_gpus = combinations.env().total_phsyical_gpus if num_gpus != 2 and num_gpus != 4: self.skipTest("requires 2 or 4 GPUs") # Test cases are annotated with required_gp...
ShareGPUTest
python
PyCQA__pylint
tests/functional/i/invalid/invalid_metaclass.py
{ "start": 823, "end": 890 }
class ____(metaclass=2): # [invalid-metaclass] pass
ThirdInvalid
python
numba__numba
numba/tests/test_tracing.py
{ "start": 1013, "end": 1596 }
class ____(object): @tracing.trace @classmethod def class_method(cls): pass @tracing.trace @staticmethod def static_method(): pass __test = None def _test_get(self): return self.__test def _test_set(self, value): self.__test = value test = tr...
Class
python
Lightning-AI__lightning
tests/tests_pytorch/test_cli.py
{ "start": 26311, "end": 27833 }
class ____(BoringModel): def __init__( self, optimizer: OptimizerCallable = torch.optim.Adam, ): super().__init__() self.save_hyperparameters() self.optimizer = optimizer def configure_optimizers(self): optimizer = self.optimizer(self.parameters()) re...
DeepLinkTargetModel
python
wandb__wandb
wandb/vendor/pygments/lexers/configs.py
{ "start": 19823, "end": 20636 }
class ____(RegexLexer): """ Lexer for `Docker <http://docker.io>`_ configuration files. .. versionadded:: 2.0 """ name = 'Docker' aliases = ['docker', 'dockerfile'] filenames = ['Dockerfile', '*.docker'] mimetypes = ['text/x-dockerfile-config'] _keywords = (r'(?:FROM|MAINTAINER|CMD...
DockerLexer
python
pandas-dev__pandas
asv_bench/benchmarks/tslibs/offsets.py
{ "start": 1183, "end": 1582 }
class ____: params = offset_objs param_names = ["offset"] def setup(self, offset): self.dates = [ datetime(2016, m, d) for m in [10, 11, 12] for d in [1, 2, 3, 28, 29, 30, 31] if not (m == 11 and d == 31) ] def time_on_offset(self, offset...
OnOffset
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor28.py
{ "start": 979, "end": 1346 }
class ____(Generic[S]): @overload def __new__(cls, item: S, /) -> ClassD[S]: ... @overload def __new__(cls, item: S, __item2: S, /) -> ClassD[tuple[S, S]]: ... def __new__(cls, *items: Any) -> Any: ... def __call__(self, obj: Any) -> Any: ... func3(ClassD(""), ClassD("")) def func4(a: Ite...
ClassD
python
getsentry__sentry
src/sentry/api/endpoints/event_attachments.py
{ "start": 619, "end": 2567 }
class ____(ProjectEndpoint): owner = ApiOwner.OWNERS_INGEST publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, project, event_id) -> Response: """ Retrieve attachments for an event ````````````````````````````````` :pparam stri...
EventAttachmentsEndpoint
python
huggingface__transformers
tests/models/convnextv2/test_modeling_convnextv2.py
{ "start": 4813, "end": 10287 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as ConvNextV2 does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = ( ( ConvNextV2Model, ...
ConvNextV2ModelTest
python
getsentry__sentry
tests/sentry/core/endpoints/scim/test_scim_team_index.py
{ "start": 7857, "end": 10043 }
class ____(SCIMTestCase): endpoint = "sentry-api-0-organization-scim-team-index" method = "post" def setUp(self) -> None: super().setUp() self.post_data = { "schemas": ["urn:ietf:params:scim:schemas:core:2.0:Group"], "displayName": "Test SCIMv2", "members...
SCIMIndexCreateTest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/external.py
{ "start": 19897, "end": 20151 }
class ____(graphene.Union): class Meta: types = ( GrapheneRepositoryConnection, GrapheneRepositoryNotFoundError, GraphenePythonError, ) name = "RepositoriesOrError"
GrapheneRepositoriesOrError
python
getsentry__sentry
fixtures/safe_migrations_apps/good_flow_delete_field_pending_with_fk_constraint_app/models.py
{ "start": 166, "end": 322 }
class ____(models.Model): field = models.IntegerField(default=0, null=False) fk_table = FlexibleForeignKey(FkTable, null=True, db_index=False)
TestTable
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 166208, "end": 168717 }
class ____(Response): """ Response of tasks.completed endpoint. :param updated: Number of tasks updated (0 or 1) :type updated: int :param fields: Updated fields names and values :type fields: dict :param published: Number of tasks published (0 or 1) :type published: int """ _s...
CompletedResponse
python
Lightning-AI__lightning
tests/tests_pytorch/plugins/test_async_checkpoint.py
{ "start": 215, "end": 1884 }
class ____(CheckpointIO): def __init__(self) -> None: self.saved: Optional[dict[str, Any]] = None def save_checkpoint(self, checkpoint: dict[str, Any], path: str, storage_options: Optional[Any] = None) -> None: # Simulate some delay to increase race window time.sleep(0.05) # Sto...
_CaptureCheckpointIO
python
django__django
django/contrib/messages/test.py
{ "start": 121, "end": 421 }
class ____: def assertMessages(self, response, expected_messages, *, ordered=True): request_messages = list(get_messages(response.wsgi_request)) assertion = self.assertEqual if ordered else self.assertCountEqual assertion(request_messages, expected_messages)
MessagesTestMixin
python
tensorflow__tensorflow
tensorflow/tools/tensorflow_builder/compat_checker/compat_checker_test.py
{ "start": 1810, "end": 4074 }
class ____(unittest.TestCase): def setUp(self): """Set up test.""" super(CompatCheckerTest, self).setUp() self.test_file = os.path.join(PATH_TO_DIR, "test_config.ini") def testWithUserConfigInRange(self): """Test a set of configs that are supported. Testing with the following combination shou...
CompatCheckerTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/resolved_asset_deps.py
{ "start": 520, "end": 9321 }
class ____: """An asset can depend on another asset without specifying the full asset key for the upstream asset, if the name and groups match. ResolvedAssetDependencies maps these flexible dependencies to precise key-based dependencies. """ def __init__( self, assets_defs: Iterable[Assets...
ResolvedAssetDependencies
python
redis__redis-py
redis/asyncio/client.py
{ "start": 2184, "end": 2377 }
class ____(Protocol): async def __call__(self, response: Any, **kwargs): ... ResponseCallbackT = Union[ResponseCallbackProtocol, AsyncResponseCallbackProtocol]
AsyncResponseCallbackProtocol
python
wandb__wandb
tests/fixtures/mock_wandb_log.py
{ "start": 1340, "end": 3096 }
class ____: """Helper to test wandb.term*() calls. See the `mock_wandb_log` fixture. """ def __init__( self, termlog: unittest.mock.MagicMock, termwarn: unittest.mock.MagicMock, termerror: unittest.mock.MagicMock, ): self._termlog = termlog self._ter...
MockWandbLog
python
ansible__ansible
test/lib/ansible_test/_internal/commands/sanity/__init__.py
{ "start": 27899, "end": 32948 }
class ____(metaclass=abc.ABCMeta): """Sanity test base class.""" ansible_only = False def __init__(self, name: t.Optional[str] = None) -> None: if not name: name = self.__class__.__name__ name = re.sub(r'Test$', '', name) # drop Test suffix name = re.sub(r'(.)(...
SanityTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/collective_ops_test.py
{ "start": 54185, "end": 55868 }
class ____(test.TestCase, parameterized.TestCase): def setUp(self): _setup_context() super().setUp() def testInvalidGroupKey(self, collective_op, device, communication): dev0 = '/device:%s:0' % device group_size = 2 group_key = [100] instance_key = 100 in_tensor = constant_op.constant(...
InvalidInputTest
python
google__jax
jax/_src/core.py
{ "start": 151295, "end": 152472 }
class ____: def __init__(self, trace_ref): self._trace_ref = trace_ref def __eq__(self, other): if isinstance(other, OpaqueTraceState): return self._trace_ref == other._trace_ref else: return False def get_opaque_trace_state(convention=None): del convention return OpaqueTraceState(trac...
OpaqueTraceState
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 186217, "end": 186915 }
class ____: _col_type = TSTZRANGE _col_str = "TSTZRANGE" def tstzs(self): tz = datetime.timezone(-datetime.timedelta(hours=5, minutes=30)) return ( datetime.datetime(2013, 3, 23, 14, 30, tzinfo=tz), datetime.datetime(2013, 3, 30, 23, 30, tzinfo=tz), ) d...
_DateTimeTZRangeTests
python
allegroai__clearml
clearml/utilities/requests_toolbelt/multipart/encoder.py
{ "start": 286, "end": 364 }
class ____(Exception): """File not supported error."""
FileNotSupportedError
python
django-import-export__django-import-export
tests/core/tests/admin_integration/test_action_export.py
{ "start": 9206, "end": 14812 }
class ____(AdminTestMixin, TestCase): """ Test cases for issue #2097: Admin filters are lost during export actions. Tests that admin changelist filters are properly preserved when exporting selected items through the export action using the AuthorBirthdayListFilter. """ def setUp(self): ...
TestExportFilterPreservation
python
PyCQA__pylint
tests/functional/t/too/too_many_ancestors_ignored_parents.py
{ "start": 523, "end": 555 }
class ____(F): """1 parent"""
E
python
realpython__materials
wordcount/tests/task_02.py
{ "start": 708, "end": 1782 }
class ____: def test_reports_zeros_on_an_empty_stream(self, wc): assert_equals(b"0 0 0\n", wc()) def test_handles_a_short_word_without_trailing_newline(self, wc): assert_equals_if(b"0 1 5\n", wc(stdin=b"caffe")) def test_handles_a_short_word_with_trailing_newline(self, wc): assert_...
Test
python
pytorch__pytorch
test/inductor/test_decompose_mem_bound_mm.py
{ "start": 655, "end": 984 }
class ____(torch.nn.Module): def __init__( self, n_input: int, n_output: int, has_bias: bool, device=GPU_TYPE ) -> None: super().__init__() self.linear = torch.nn.Linear(n_input, n_output, bias=has_bias) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.linear(...
MyModule
python
scikit-learn__scikit-learn
sklearn/tests/test_base.py
{ "start": 2122, "end": 2188 }
class ____(DiamondOverwriteTag): pass
InheritDiamondOverwriteTag
python
pypa__warehouse
tests/unit/subscriptions/test_services.py
{ "start": 996, "end": 2801 }
class ____: def test_verify_service(self): assert verifyClass(IBillingService, StripeBillingService) def test_basic_init(self): api = pretend.stub() billing_service = StripeBillingService( api=api, publishable_key="secret_to_everybody", webhook_secre...
TestStripeBillingService
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1144816, "end": 1145091 }
class ____(VegaLiteSchema): """ScaleInvalidDataShowAsstrokeDash schema wrapper.""" _schema = {"$ref": '#/definitions/ScaleInvalidDataShowAs<"strokeDash">'} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
ScaleInvalidDataShowAsstrokeDash
python
davidhalter__parso
parso/tree.py
{ "start": 15614, "end": 16153 }
class ____(Leaf): """ A leaf that is either completely invalid in a language (like `$` in Python) or is invalid at that position. Like the star in `1 +* 1`. """ __slots__ = ('token_type',) type = 'error_leaf' def __init__(self, token_type, value, start_pos, prefix=''): super().__ini...
ErrorLeaf
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 122675, "end": 123068 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field( sgqlc.types.non_null(ProjectV2OrderField), graphql_name="field" ) direction = sgqlc.types.Field( sgqlc.ty...
ProjectV2Order
python
airbytehq__airbyte
airbyte-integrations/connectors/source-tiktok-marketing/components.py
{ "start": 3703, "end": 4218 }
class ____(RecordTransformation): empty_value = "-" def transform( self, record: Mapping[str, Any], config: Optional[Config] = None, stream_state: Optional[StreamState] = None, stream_slice: Optional[StreamSlice] = None, ) -> Mapping[str, Any]: for metric_key...
TransformEmptyMetrics
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/api.py
{ "start": 34228, "end": 39240 }
class ____: """Utility class to consolidate execution logic. This is a class and not a function because, e.g., in constructing a `scoped_pipeline_context` for `JobExecutionResult`, we need to pull out the `pipeline_context` after we're done yielding events. This broadly follows a pattern we make use of...
ExecuteRunWithPlanIterable
python
scipy__scipy
scipy/signal/tests/test_filter_design.py
{ "start": 64774, "end": 69079 }
class ____: """Tests for function `signal.bilinear`. """ def test_exceptions(self): """Raise all exceptions in `bilinear()`. """ with pytest.raises(ValueError, match="Parameter a is not .*"): bilinear(1., np.array([[1, 2, 3]])) with pytest.raises(ValueError, match="Parameter...
TestBilinear
python
pytorch__pytorch
test/dynamo/test_subclasses.py
{ "start": 6482, "end": 6927 }
class ____(torch.Tensor): @classmethod def __torch_function__(cls, func, types, args=(), kwargs=None): if func == torch.Tensor.sigmoid: return super().__torch_function__(torch.Tensor.exp, types, args, kwargs) return super().__torch_function__(func, types, args, kwargs) # Wrapper s...
SigmoidToExpSubclass
python
tensorflow__tensorflow
tensorflow/python/keras/layers/pooling.py
{ "start": 42054, "end": 43953 }
class ____(GlobalPooling2D): """Global max pooling operation for spatial data. Examples: >>> input_shape = (2, 4, 5, 3) >>> x = tf.random.normal(input_shape) >>> y = tf.keras.layers.GlobalMaxPool2D()(x) >>> print(y.shape) (2, 3) Args: data_format: A string, one of `channels_last` (default) ...
GlobalMaxPooling2D
python
rapidsai__cudf
python/cudf/cudf/core/index.py
{ "start": 113405, "end": 152857 }
class ____(Index): """ Immutable , ordered and sliceable sequence of datetime64 data, represented internally as int64. Parameters ---------- data : array-like (1-dimensional), optional Optional datetime-like data to construct index with. copy : bool Make a copy of input. ...
DatetimeIndex
python
django-import-export__django-import-export
tests/core/tests/admin_integration/test_action_export.py
{ "start": 714, "end": 9206 }
class ____(AdminTestMixin, TestCase): def setUp(self): super().setUp() self.cat1 = Category.objects.create(name="Cat 1") self.cat2 = Category.objects.create(name="Cat 2") # fields payload for `CategoryResource` - # to export using `SelectableFieldsExportForm` self.res...
ExportActionAdminIntegrationTest
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_glue_databrew.py
{ "start": 1359, "end": 3558 }
class ____: def test_init(self): op = GlueDataBrewStartJobOperator( task_id="task_test", job_name=JOB_NAME, aws_conn_id="fake-conn-id", region_name="eu-central-1", verify="/spam/egg.pem", botocore_config={"read_timeout": 42}, ) ...
TestGlueDataBrewOperator
python
getsentry__sentry
tests/sentry/services/eventstore/test_query_preprocessing.py
{ "start": 395, "end": 2729 }
class ____(TestCase): def setUp(self) -> None: self.g1 = self.create_group(id=1) self.g2 = self.create_group(id=2) self.g3 = self.create_group(id=3) self.g4 = self.create_group(id=4) self.gr31 = GroupRedirect.objects.create( id=10001, organization_id=...
TestQueryPreprocessing
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/many_virtual_consumer/package.py
{ "start": 216, "end": 771 }
class ____(Package): """PAckage that depends on many virtual packages""" url = "http://www.example.com/" url = "http://www.example.com/2.0.tar.gz" version("1.0", md5="abcdef1234567890abcdef1234567890") depends_on("mpi") depends_on("lapack") # This directive is an example of imposing a co...
ManyVirtualConsumer
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py
{ "start": 95967, "end": 96032 }
class ____(MimiLayerScale): pass
Qwen3OmniMoeCode2WavLayerScale
python
dagster-io__dagster
python_modules/dagster/dagster_tests/logging_tests/test_logging.py
{ "start": 6715, "end": 6866 }
class ____(logging.Formatter): def format(self, record): record.msg = "I was formatted" return super().format(record)
CustomFormatter
python
tensorflow__tensorflow
tensorflow/python/keras/callbacks.py
{ "start": 99857, "end": 104246 }
class ____(Callback): """Reduce learning rate when a metric has stopped improving. Models often benefit from reducing the learning rate by a factor of 2-10 once learning stagnates. This callback monitors a quantity and if no improvement is seen for a 'patience' number of epochs, the learning rate is reduced....
ReduceLROnPlateau
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_reflection.py
{ "start": 2555, "end": 4733 }
class ____( ReflectionFixtures, fixtures.TablesTest, AssertsExecutionResults ): """Test reflection on foreign tables""" __requires__ = ("postgresql_test_dblink",) __only_on__ = "postgresql >= 9.3" __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): from ...
ForeignTableReflectionTest
python
ray-project__ray
release/nightly_tests/multimodal_inference_benchmarks/document_embedding/daft_main.py
{ "start": 2084, "end": 3945 }
class ____: def __init__(self): from sentence_transformers import SentenceTransformer device = "cuda" if torch.cuda.is_available() else "cpu" self.model = SentenceTransformer(EMBED_MODEL_ID, device=device) self.model.compile() def __call__(self, text_col): if len(text_c...
Embedder
python
ray-project__ray
python/ray/tune/examples/mnist_pytorch.py
{ "start": 530, "end": 5044 }
class ____(nn.Module): def __init__(self): super(ConvNet, self).__init__() self.conv1 = nn.Conv2d(1, 3, kernel_size=3) self.fc = nn.Linear(192, 10) def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 3)) x = x.view(-1, 192) x = self.fc(x) return ...
ConvNet
python
apache__airflow
airflow-core/tests/unit/utils/test_trigger_rule.py
{ "start": 890, "end": 1979 }
class ____: def test_valid_trigger_rules(self): assert TriggerRule.is_valid(TriggerRule.ALL_SUCCESS) assert TriggerRule.is_valid(TriggerRule.ALL_FAILED) assert TriggerRule.is_valid(TriggerRule.ALL_DONE) assert TriggerRule.is_valid(TriggerRule.ALL_SKIPPED) assert TriggerRule.i...
TestTriggerRule
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1252677, "end": 1252944 }
class ____(sgqlc.types.Type, Node, AuditEntry, OauthApplicationAuditEntryData, OrganizationAuditEntryData): """Audit log entry for a org.oauth_app_access_approved event.""" __schema__ = github_schema __field_names__ = ()
OrgOauthAppAccessApprovedAuditEntry
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/_psycopg_common.py
{ "start": 804, "end": 1886 }
class ____(sqltypes.NumericCommon): def bind_processor(self, dialect): return None def result_processor(self, dialect, coltype): if self.asdecimal: if coltype in _FLOAT_TYPES: return processors.to_decimal_processor_factory( decimal.Decimal, self._...
_PsycopgNumericCommon
python
dagster-io__dagster
python_modules/dagster/dagster/_core/scheduler/instigation.py
{ "start": 32404, "end": 33254 }
class ____(Generic[T_EntityKey]): id: int serialized_evaluation_body: str evaluation_id: int timestamp: float key: T_EntityKey @classmethod def from_db_row(cls, row) -> "AutoMaterializeAssetEvaluationRecord": return AutoMaterializeAssetEvaluationRecord( id=row["id"], ...
AutoMaterializeAssetEvaluationRecord
python
pytorch__pytorch
torch/nn/modules/activation.py
{ "start": 9663, "end": 10724 }
class ____(Module): r"""Applies the Hardsigmoid function element-wise. Hardsigmoid is defined as: .. math:: \text{Hardsigmoid}(x) = \begin{cases} 0 & \text{if~} x \le -3, \\ 1 & \text{if~} x \ge +3, \\ x / 6 + 1 / 2 & \text{otherwise} \end{cases} Ar...
Hardsigmoid
python
pytorch__pytorch
tools/experimental/torchfuzz/operators/registry.py
{ "start": 1699, "end": 7355 }
class ____: """Registry for managing operator instances.""" def __init__(self): """Initialize the registry with default operators.""" self._operators: dict[str, Operator] = {} self._register_default_operators() def _register_default_operators(self): """Register the default ...
OperatorRegistry
python
ipython__ipython
IPython/core/prefilter.py
{ "start": 22287, "end": 24931 }
class ____(PrefilterHandler): handler_name = Unicode('auto') esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) def handle(self, line_info): """Handle lines which can be auto-executed, quoting if requested.""" line = line_info.line ifun = line_info.ifun the_rest =...
AutoHandler
python
django__django
tests/auth_tests/test_mixins.py
{ "start": 795, "end": 866 }
class ____(AlwaysFalseMixin, EmptyResponseView): pass
AlwaysFalseView
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/fr_with_min.py
{ "start": 164, "end": 1129 }
class ____(App[None]): CSS = """ Horizontal { width: 1fr; } Vertical { width: 1fr; background: blue; min-width: 20; } #scroll1 { width: 1fr; background: $panel; } #scroll2 { width: 2fr; background: $panel; } ...
ScreenSplitApp
python
ray-project__ray
python/ray/data/_internal/datasource/json_datasource.py
{ "start": 745, "end": 6390 }
class ____(FileBasedDatasource): """JSON datasource, for reading and writing JSON and JSONL files.""" def __init__( self, paths: Union[str, List[str]], *, arrow_json_args: Optional[Dict[str, Any]] = None, **file_based_datasource_kwargs, ): from pyarrow import...
ArrowJSONDatasource
python
plotly__plotly.py
plotly/graph_objs/scatter/_fillpattern.py
{ "start": 233, "end": 15287 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatter" _path_str = "scatter.fillpattern" _valid_props = { "bgcolor", "bgcolorsrc", "fgcolor", "fgcolorsrc", "fgopacity", "fillmode", "path", "pathsrc", "shape", "shapesr...
Fillpattern
python
apache__airflow
providers/snowflake/src/airflow/providers/snowflake/decorators/snowpark.py
{ "start": 1138, "end": 5219 }
class ____(DecoratedOperator, SnowparkOperator): """ Wraps a Python callable that contains Snowpark code and captures args/kwargs when called for execution. :param snowflake_conn_id: Reference to :ref:`Snowflake connection id<howto/connection:snowflake>` :param python_callable: A reference to a...
_SnowparkDecoratedOperator
python
cython__cython
Cython/Compiler/FlowControl.py
{ "start": 2596, "end": 2668 }
class ____: def __init__(self): self.stats = []
AssignmentList
python
Textualize__textual
docs/examples/styles/align_all.py
{ "start": 120, "end": 894 }
class ____(App): """App that illustrates all alignments.""" CSS_PATH = "align_all.tcss" def compose(self) -> ComposeResult: yield Container(Label("left top"), id="left-top") yield Container(Label("center top"), id="center-top") yield Container(Label("right top"), id="right-top") ...
AlignAllApp
python
streamlit__streamlit
lib/tests/streamlit/external/langchain/capturing_callback_handler.py
{ "start": 1046, "end": 1687 }
class ____: ON_LLM_START = "on_llm_start" ON_LLM_NEW_TOKEN = "on_llm_new_token" ON_LLM_END = "on_llm_end" ON_LLM_ERROR = "on_llm_error" ON_TOOL_START = "on_tool_start" ON_TOOL_END = "on_tool_end" ON_TOOL_ERROR = "on_tool_error" ON_TEXT = "on_text" ON_CHAIN_START = "on_chain_start" ...
CallbackType
python
ray-project__ray
python/ray/data/_internal/execution/interfaces/op_runtime_metrics.py
{ "start": 1600, "end": 3949 }
class ____: """Metadata for a metric. Args: name: The name of the metric. description: A human-readable description of the metric, also used as the chart description on the Ray Data dashboard. metrics_group: The group of the metric, used to organize metrics into groups in ...
MetricDefinition
python
pytorch__pytorch
torch/_dynamo/side_effects.py
{ "start": 2907, "end": 53504 }
class ____: """ Maintain records of mutations and provide methods to apply them during code generation. Handles tracking and applying side effects during PyTorch Dynamo compilation, maintaining Python semantics by managing mutations, attribute modifications, and other side effects that occur during...
SideEffects
python
kamyu104__LeetCode-Solutions
Python/sell-diminishing-valued-colored-balls.py
{ "start": 88, "end": 925 }
class ____(object): def maxProfit(self, inventory, orders): """ :type inventory: List[int] :type orders: int :rtype: int """ MOD = 10**9+7 def check(inventory, orders, x): return count(inventory, x) > orders def count(inventory, x)...
Solution
python
getsentry__sentry
src/sentry/api/endpoints/seer_models.py
{ "start": 1037, "end": 1158 }
class ____(APIException): status_code = 502 default_detail = "Failed to fetch models from Seer"
SeerConnectionError
python
rapidsai__cudf
python/cudf/cudf/io/parquet.py
{ "start": 60113, "end": 69831 }
class ____: """ ParquetWriter lets you incrementally write out a Parquet file from a series of cudf tables Parameters ---------- filepath_or_buffer : str, io.IOBase, os.PathLike, or list File path or buffer to write to. The argument may also correspond to a list of file paths or...
ParquetWriter
python
lepture__authlib
tests/flask/test_oauth2/test_authorization_code_iss_parameter.py
{ "start": 614, "end": 2669 }
class ____(_IssuerParameter): def get_issuer(self) -> str: return "https://auth.test" @pytest.fixture(autouse=True) def server(server): server.register_grant(AuthorizationCodeGrant) return server @pytest.fixture(autouse=True) def client(client, db): client.set_client_metadata( { ...
IssuerParameter
python
dagster-io__dagster
examples/docs_projects/project_ml/src/project_ml/defs/resources.py
{ "start": 679, "end": 1994 }
class ____(ModelStoreResource): """Local file system model storage.""" models_path: str = "./models" def save_model(self, model_data: dict[str, Any], model_name: str): """Save model data to local filesystem.""" os.makedirs(self.models_path, exist_ok=True) model_path = os.path.join(...
LocalModelStoreResource
python
coleifer__peewee
tests/shortcuts.py
{ "start": 1852, "end": 1954 }
class ____(TestModel): id = IntegerField(primary_key=True) basket = ForeignKeyField(Basket)
Item
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 149348, "end": 150775 }
class ____(PositionToken): r"""Matches if current position is at the logical beginning of a line (after skipping whitespace) within the parse string Example: .. testcode:: test = '''\ AAA this line AAA and this line AAA and even this line B AAA but definitely...
LineStart
python
boto__boto3
boto3/crt.py
{ "start": 3818, "end": 7254 }
class ____: """ This wrapper keeps track of our underlying CRT client, the lock used to acquire it and the region we've used to instantiate the client. Due to limitations in the existing CRT interfaces, we can only make calls in a single region and does not support redirects. We track the region to...
CRTS3Client
python
joke2k__faker
faker/providers/color/uz_UZ/__init__.py
{ "start": 98, "end": 1940 }
class ____(ColorProvider): """Implement color provider for ``uz_UZ`` locale.""" # Source: https://uz.wiktionary.org/wiki/Vikilug%E2%80%98at:Ranglar all_colors = OrderedDict( ( ("Akvamarin", "#7FFFD4"), ("Anor", "#800000"), ("Apelsin", "#FFA000"), ("Be...
Provider
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 112179, "end": 112639 }
class ____(TestCase): def setUp(self): super().setUp() self.dataset = StringDataset() @unittest.skipIf(not TEST_CUDA, "CUDA unavailable") def test_shuffle_pin_memory(self): loader = DataLoader( self.dataset, batch_size=2, shuffle=True, num_workers=4, pin_memory=True ...
TestStringDataLoader
python
mlflow__mlflow
mlflow/genai/utils/enum_utils.py
{ "start": 34, "end": 303 }
class ____(EnumMeta): """Metaclass for Enum classes that allows to check if a value is a valid member of the Enum.""" def __contains__(cls, item): try: cls(item) except ValueError: return False return True
MetaEnum
python
google__jax
tests/state_test.py
{ "start": 38464, "end": 41309 }
class ____(NamedTuple): index_param: IndexParam ref_bdim: int | None non_slice_idx_bdims: tuple[int | None, ...] slice_bdim: int bat_ref_aval: shaped_array_ref bat_ref_shape: Shape bat_non_slice_idx_avals: tuple[core.ShapedArray, ...] bat_non_slice_idx_shapes: tuple[Shape, ...] bat_slice_aval: core.Sh...
VmappableIndexParam
python
sympy__sympy
sympy/integrals/transforms.py
{ "start": 47783, "end": 49441 }
class ____(HankelTypeTransform): """ Class representing unevaluated Hankel transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Hankel transforms, see the :func:`hankel_transform` docstring. """ _name = 'Hankel' def hankel_transform(f, r,...
HankelTransform
python
ijl__orjson
test/test_indent.py
{ "start": 153, "end": 3578 }
class ____: def test_equivalent(self): """ OPT_INDENT_2 is equivalent to indent=2 """ obj = {"a": "b", "c": {"d": True}, "e": [1, 2]} assert orjson.dumps(obj, option=orjson.OPT_INDENT_2) == json.dumps( obj, indent=2, ).encode("utf-8") def ...
TestIndentedOutput
python
lazyprogrammer__machine_learning_examples
cnn_class2/tf_resnet_convblock.py
{ "start": 482, "end": 1285 }
class ____: def __init__(self, d, mi, mo, stride=2, padding='VALID'): self.W = tf.Variable(init_filter(d, mi, mo, stride)) self.b = tf.Variable(np.zeros(mo, dtype=np.float32)) self.stride = stride self.padding = padding def forward(self, X): X = tf.nn.conv2d( X, self.W, stride...
ConvLayer
python
doocs__leetcode
solution/2200-2299/2287.Rearrange Characters to Make Target String/Solution.py
{ "start": 0, "end": 194 }
class ____: def rearrangeCharacters(self, s: str, target: str) -> int: cnt1 = Counter(s) cnt2 = Counter(target) return min(cnt1[c] // v for c, v in cnt2.items())
Solution
python
encode__starlette
starlette/datastructures.py
{ "start": 10162, "end": 12024 }
class ____(ImmutableMultiDict[Any, Any]): def __setitem__(self, key: Any, value: Any) -> None: self.setlist(key, [value]) def __delitem__(self, key: Any) -> None: self._list = [(k, v) for k, v in self._list if k != key] del self._dict[key] def pop(self, key: Any, default: Any = Non...
MultiDict
python
encode__django-rest-framework
tests/test_throttling.py
{ "start": 12626, "end": 12972 }
class ____(XffTestingBase): def test_accepts_request_under_limit(self): self.config_proxy(0) assert self.view(self.request).status_code == 200 def test_denies_request_over_limit(self): self.config_proxy(0) self.view(self.request) assert self.view(self.request).status_cod...
IdWithXffBasicTests
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_encode_password.py
{ "start": 301, "end": 1972 }
class ____(unittest.TestCase): """ Test the Worksheet _encode_password() methods. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test__encode_password(self): """Test the _encode_password() function...
TestEncodePassword
python
huggingface__transformers
tests/utils/test_hf_argparser.py
{ "start": 1890, "end": 2019 }
class ____: foo: BasicEnum = "toto" def __post_init__(self): self.foo = BasicEnum(self.foo) @dataclass
EnumExample
python
tensorflow__tensorflow
tensorflow/python/distribute/input_lib.py
{ "start": 54358, "end": 56861 }
class ____(object): """Iterator for a single `tf.data.Dataset`.""" def __init__(self, dataset, worker, devices, options=None): """Create iterator for the `dataset` to fetch data to worker's `devices` . A `MultiDeviceIterator` or `OwnedMultiDeviceIterator` is used to prefetch input to the devices on t...
_SingleWorkerDatasetIteratorBase
python
astropy__astropy
astropy/visualization/wcsaxes/tests/test_wcsapi.py
{ "start": 20247, "end": 24618 }
class ____(BaseLowLevelWCS): pixel_dim = 2 @property def pixel_n_dim(self): return self.pixel_dim @property def world_n_dim(self): return 5 @property def world_axis_physical_types(self): return [ "em.freq", "time", "pos.eq.ra", ...
LowLevelWCS5D
python
ansible__ansible
lib/ansible/playbook/role/definition.py
{ "start": 1545, "end": 9400 }
class ____(Base, Conditional, Taggable, CollectionSearch): role = NonInheritableFieldAttribute(isa='string') def __init__(self, play=None, role_basedir=None, variable_manager=None, loader=None, collection_list=None): super(RoleDefinition, self).__init__() self._play = play self._vari...
RoleDefinition
python
lxml__lxml
src/lxml/tests/test_classlookup.py
{ "start": 334, "end": 3000 }
class ____(HelperTestCase): """Basic tests for element proxy behaviour. """ etree = etree def test_proxy_reuse(self): root = etree.XML('<a><b><c/></b></a>') b = root.find('b') self.assertTrue(b is root[0]) def test_proxy_reuse_after_gc(self): root = etree.XML('<a><b...
ProxyTestCase
python
django__django
tests/admin_changelist/models.py
{ "start": 301, "end": 521 }
class ____(models.Model): parent = models.ForeignKey(Parent, models.SET_NULL, editable=False, null=True) name = models.CharField(max_length=30, blank=True) age = models.IntegerField(null=True, blank=True)
Child
python
tornadoweb__tornado
tornado/template.py
{ "start": 25557, "end": 26250 }
class ____(Exception): """Raised for template syntax errors. ``ParseError`` instances have ``filename`` and ``lineno`` attributes indicating the position of the error. .. versionchanged:: 4.3 Added ``filename`` and ``lineno`` attributes. """ def __init__( self, message: str, fi...
ParseError
python
sympy__sympy
sympy/solvers/ode/single.py
{ "start": 37868, "end": 41325 }
class ____(SinglePatternODESolver): r""" Solves 2nd order Liouville differential equations. The general form of a Liouville ODE is .. math:: \frac{d^2 y}{dx^2} + g(y) \left(\! \frac{dy}{dx}\!\right)^2 + h(x) \frac{dy}{dx}\text{.} The general solution is: >...
Liouville
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py
{ "start": 4836, "end": 5036 }
class ____(ParentD): def f(self): def x(): __class__ = 1 super # Python injects __class__ into scope builtins.super(ChildD10, self).f() # Must be ignored
ChildD10
python
donnemartin__interactive-coding-challenges
sorting_searching/rotated_array_search/test_search_sorted_array.py
{ "start": 18, "end": 745 }
class ____(unittest.TestCase): def test_search_sorted_array(self): array = Array() self.assertRaises(TypeError, array.search_sorted_array, None) self.assertEqual(array.search_sorted_array([3, 1, 2], 0), None) self.assertEqual(array.search_sorted_array([3, 1, 2], 0), None) da...
TestArray
python
tensorflow__tensorflow
tensorflow/python/framework/extension_type_field_test.py
{ "start": 1489, "end": 5637 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters([ # Without default values: ('x', int), ('f', float), ('t', tensor.Tensor), # With default values: ('x', int, 33), ('y', float, 33.8), ('t', tensor....
ExtensionTypeFieldTest
python
ray-project__ray
python/ray/data/collate_fn.py
{ "start": 6339, "end": 9251 }
class ____(ArrowBatchCollateFn): """Default collate function for converting Arrow batches to PyTorch tensors.""" _DEFAULT_NUM_WORKERS = env_integer( "RAY_DATA_DEFAULT_COLLATE_FN_THREADPOOL_MAX_WORKERS", 4, ) def __init__( self, dtypes: Optional[Union["torch.dtype", Dict...
DefaultCollateFn