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
tests/utils/test_audio_utils.py
{ "start": 1050, "end": 79942 }
class ____(unittest.TestCase): # will be set in `def _load_datasamples` _dataset = None def test_hertz_to_mel(self): self.assertEqual(hertz_to_mel(0.0), 0.0) self.assertAlmostEqual(hertz_to_mel(100), 150.48910241) inputs = np.array([100, 200]) expected = np.array([150.48910...
AudioUtilsFunctionTester
python
apache__airflow
providers/google/src/airflow/providers/google/ads/hooks/ads.py
{ "start": 1746, "end": 14554 }
class ____(BaseHook): """ Interact with Google Ads API. This hook offers two flows of authentication. 1. OAuth Service Account Flow (requires two connections) - gcp_conn_id - provides service account details (like any other GCP connection) - google_ads_conn_id - which contains informa...
GoogleAdsHook
python
allegroai__clearml
clearml/backend_api/services/v2_9/models.py
{ "start": 74474, "end": 75603 }
class ____(Request): """ Convert company models to public :param ids: IDs of the models to convert :type ids: Sequence[str] """ _service = "models" _action = "make_public" _version = "2.9" _schema = { "definitions": {}, "properties": { "ids": { ...
MakePublicRequest
python
FactoryBoy__factory_boy
tests/test_using.py
{ "start": 10457, "end": 32259 }
class ____(unittest.TestCase): def test_attribute(self): class TestObjectFactory(factory.Factory): class Meta: model = TestObject one = 'one' test_object = TestObjectFactory.build() self.assertEqual(test_object.one, 'one') def test_inheriting_mo...
UsingFactoryTestCase
python
great-expectations__great_expectations
contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_pair_values_lat_lng_matches_geohash.py
{ "start": 524, "end": 927 }
class ____(ColumnPairMapMetricProvider): condition_metric_name = "column_pair_values.lat_lng_matches_geohash" # noinspection PyPep8Naming @column_pair_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column_A, column_B, **kwargs): df = pd.DataFrame(column_A).join(column_B) ...
ColumnPairValuesLatLngMatchesGeohash
python
Textualize__textual
src/textual/css/_style_properties.py
{ "start": 9238, "end": 12031 }
class ____: """Descriptor for getting and setting outlines and borders along a single edge. For example "border-right", "outline-bottom", etc. """ def __init__(self, default_color: Color) -> None: self._default_color = default_color def __set_name__(self, owner: StylesBase, name: str) -> N...
BoxProperty
python
ray-project__ray
python/ray/serve/tests/test_deployment_scheduler.py
{ "start": 952, "end": 5243 }
class ____: @pytest.mark.parametrize( "placement_group_config", [ {}, {"bundles": [{"CPU": 3}]}, { "bundles": [{"CPU": 1}, {"CPU": 1}, {"CPU": 1}], "strategy": "STRICT_PACK", }, ], ) def test_spread_deplo...
TestSpreadScheduling
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_async_job.py
{ "start": 18595, "end": 24765 }
class ____: def test_start(self, parent_job, grouped_jobs, api_limit): # should attempt to start every child (DummyAPILimit never limits) parent_job.start(api_limit) for job in grouped_jobs: job.start.assert_called_once_with(api_limit) def test_completed(self, parent_job, gr...
TestParentAsyncJob
python
huggingface__transformers
src/transformers/models/qwen3_moe/modeling_qwen3_moe.py
{ "start": 31948, "end": 32059 }
class ____(GenericForSequenceClassification, Qwen3MoePreTrainedModel): pass
Qwen3MoeForSequenceClassification
python
viewflow__viewflow
tests/json/test_json__json.py
{ "start": 240, "end": 838 }
class ____(TestCase): def test_crud(self): model = JsonFieldModel(json_field={"test": "value"}) self.assertIsInstance(model._meta.get_field("json_field"), models.JSONField) self.assertEqual( model.data, { "json_field": {"test": "value"}, },...
Test
python
anthropics__anthropic-sdk-python
src/anthropic/types/metadata_param.py
{ "start": 222, "end": 594 }
class ____(TypedDict, total=False): user_id: Optional[str] """An external identifier for the user who is associated with the request. This should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as nam...
MetadataParam
python
getsentry__sentry
src/sentry/deletions/base.py
{ "start": 6043, "end": 9343 }
class ____(BaseDeletionTask[ModelT]): DEFAULT_QUERY_LIMIT: int | None = None manager_name = "objects" def __init__( self, manager: DeletionTaskManager, model: type[ModelT], query: Mapping[str, Any], query_limit: int | None = None, order_by: str | None = None,...
ModelDeletionTask
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDict15.py
{ "start": 203, "end": 290 }
class ____(Protocol): def clear(self) -> None: ... _T = TypeVar("_T")
SupportsClear
python
django__django
django/core/checks/registry.py
{ "start": 155, "end": 613 }
class ____: """ Built-in tags for internal checks. """ admin = "admin" async_support = "async_support" caches = "caches" commands = "commands" compatibility = "compatibility" database = "database" files = "files" models = "models" security = "security" signals = "sig...
Tags
python
pypa__pipenv
pipenv/vendor/dotenv/ipython.py
{ "start": 300, "end": 1303 }
class ____(Magics): @magic_arguments() @argument( '-o', '--override', action='store_true', help="Indicate to override existing variables" ) @argument( '-v', '--verbose', action='store_true', help="Indicate function calls to be verbose" ) @argument('dotenv_path', ...
IPythonDotEnv
python
pypa__warehouse
tests/unit/manage/views/test_teams.py
{ "start": 19777, "end": 23812 }
class ____: def test_get(self, db_request, user_service): team = TeamFactory.create() older_event = TeamEventFactory.create( source=team, tag="fake:event", time=datetime.datetime(2017, 2, 5, 17, 18, 18, 462_634), ) newer_event = TeamEventFactory.cr...
TestManageTeamHistory
python
MongoEngine__mongoengine
tests/test_datastructures.py
{ "start": 425, "end": 5690 }
class ____: @staticmethod def _get_basedict(dict_items): """Get a BaseList bound to a fake document instance""" fake_doc = DocumentStub() base_list = BaseDict(dict_items, instance=None, name="my_name") base_list._instance = ( fake_doc # hack to inject the mock, it do...
TestBaseDict
python
pypa__pip
tests/unit/test_utils.py
{ "start": 17223, "end": 19223 }
class ____: @pytest.mark.skipif("sys.platform == 'win32'") def test_glibc_version_string(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr( os, "confstr", lambda x: "glibc 2.20", raising=False, ) assert glibc_version_strin...
TestGlibc
python
ray-project__ray
python/ray/autoscaler/_private/aliyun/node_provider.py
{ "start": 831, "end": 12726 }
class ____(NodeProvider): def __init__(self, provider_config, cluster_name): NodeProvider.__init__(self, provider_config, cluster_name) self.cache_stopped_nodes = provider_config.get("cache_stopped_nodes", True) self.acs = AcsClient( access_key=provider_config["access_key"], ...
AliyunNodeProvider
python
catalyst-team__catalyst
catalyst/contrib/losses/dice.py
{ "start": 137, "end": 1723 }
class ____(nn.Module): """The Dice loss. DiceLoss = 1 - dice score dice score = 2 * intersection / (intersection + union)) = \ = 2 * tp / (2 * tp + fp + fn) """ def __init__( self, class_dim: int = 1, mode: str = "macro", weights: List[float] = None, eps:...
DiceLoss
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_organization_integration_channels.py
{ "start": 5921, "end": 6608 }
class ____(OrganizationIntegrationChannelsTest): def test_integration_not_found(self): response = self.get_error_response(self.organization.slug, 9999, status_code=404) assert response.status_code == 404 def test_unsupported_provider(self): integration = self.create_integration( ...
OrganizationIntegrationChannelsErrorTest
python
run-llama__llama_index
llama-index-packs/llama-index-packs-diff-private-simple-dataset/examples/symptom_2_disease/event_handler.py
{ "start": 362, "end": 2138 }
class ____(BaseEventHandler): num_splits: int t_max: int synthetic_example_starts: int = 0 synthetic_example_ends: int = 0 llm_empty_responses: int = 0 empty_intersections: int = 0 critical_threshold: int = 0.025 # ~2.5% error rate with OpenAI API calls @classmethod def class_name(...
DiffPrivacyEventHandler
python
PrefectHQ__prefect
src/prefect/client/orchestration/_artifacts/client.py
{ "start": 1258, "end": 1514 }
class ____(BaseArtifactReadParams, total=False): artifact_filter: Annotated[ Optional["ArtifactCollectionFilter"], Field(default=None) ] sort: Annotated[Optional["ArtifactCollectionSort"], Field(default=None)]
ArtifactCollectionReadParams
python
pyca__cryptography
tests/doubles.py
{ "start": 1200, "end": 1298 }
class ____( serialization.KeySerializationEncryption ): pass
DummyKeySerializationEncryption
python
astropy__astropy
astropy/units/tests/test_quantity_info.py
{ "start": 3195, "end": 3768 }
class ____: @classmethod def setup_class(cls): value = np.array([(1.0, 2.0), (3.0, 4.0)], dtype=[("p", "f8"), ("v", "f8")]) cls.q = u.Quantity(value, "m, m/s") cls.q.info.name = "pv" cls.q.info.description = "Location and speed" def test_keying(self): q_p = self.q["p...
TestStructuredQuantity
python
tensorflow__tensorflow
tensorflow/python/compat/disable_v2_behavior_test.py
{ "start": 993, "end": 1500 }
class ____(test.TestCase): def test_basic(self): t = constant_op.constant([1, 2, 3]) # creates a hidden context self.assertTrue(isinstance(t, ops.EagerTensor)) t = _pywrap_tf2.is_enabled() self.assertTrue(t) v2_compat.disable_v2_behavior() t = constant_op.constant([1, 2, 3]) self.assertF...
DisableV2BehaviorTest
python
ray-project__ray
ci/ray_ci/windows_container.py
{ "start": 148, "end": 1812 }
class ____(Container): def install_ray( self, build_type: Optional[str] = None, mask: Optional[str] = None ) -> List[str]: assert not build_type, f"Windows does not support build type: {build_type}" assert not mask, f"Windows does not support install mask: {mask}" bazel_cache = ...
WindowsContainer
python
scikit-learn__scikit-learn
sklearn/ensemble/_forest.py
{ "start": 35801, "end": 41346 }
class ____(RegressorMixin, BaseForest, metaclass=ABCMeta): """ Base class for forest of trees-based regressors. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__( self, estimator, n_estimators=100, ...
ForestRegressor
python
getsentry__sentry-python
sentry_sdk/integrations/google_genai/utils.py
{ "start": 885, "end": 22499 }
class ____(TypedDict): """Structure for token usage data.""" input_tokens: int input_tokens_cached: int output_tokens: int output_tokens_reasoning: int total_tokens: int def extract_usage_data(response): # type: (Union[GenerateContentResponse, dict[str, Any]]) -> UsageData """Extract ...
UsageData
python
streamlit__streamlit
lib/tests/streamlit/web/server/oauth_authlib_routes_test.py
{ "start": 1044, "end": 1619 }
class ____(dict): def to_dict(self): return self SECRETS_MOCK = SecretMock( { "redirect_uri": "http://localhost:8501/oauth2callback", "google": { "client_id": "CLIENT_ID", "client_secret": "CLIENT_SECRET", "server_metadata_url": "https://accounts.goo...
SecretMock
python
huggingface__transformers
src/transformers/integrations/executorch.py
{ "start": 6637, "end": 17536 }
class ____(torch.nn.Module): """ A recipe module designed to make a `PreTrainedModel` exportable with `torch.export`, specifically for decoder-only LM with cache. This module ensures that the exported model is compatible with further lowering and execution in `ExecuTorch`. """ def __init__( ...
TorchExportableModuleForDecoderOnlyLM
python
huggingface__transformers
src/transformers/models/swiftformer/modeling_swiftformer.py
{ "start": 7800, "end": 8950 }
class ____(nn.Module): """ Local Representation module for SwiftFormer that is implemented by 3*3 depth-wise and point-wise convolutions. Input: tensor of shape `[batch_size, channels, height, width]` Output: tensor of shape `[batch_size, channels, height, width]` """ def __init__(self, confi...
SwiftFormerLocalRepresentation
python
bokeh__bokeh
src/bokeh/models/tools.py
{ "start": 66078, "end": 66464 }
class ____(EditTool): ''' A base class for polygon draw/edit tools. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) vertex_renderer = Nullable(GlyphRendererOf(XYGlyph), help=""" The renderer used to...
PolyTool
python
django__django
tests/template_tests/filter_tests/test_capfirst.py
{ "start": 879, "end": 1010 }
class ____(SimpleTestCase): def test_capfirst(self): self.assertEqual(capfirst("hello world"), "Hello world")
FunctionTests
python
crytic__slither
slither/detectors/reentrancy/token.py
{ "start": 1747, "end": 3692 }
class ____(AbstractDetector): ARGUMENT = "token-reentrancy" HELP = "Tokens that are reentrancies unsafe" IMPACT = DetectorClassification.MEDIUM CONFIDENCE = DetectorClassification.MEDIUM WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#token-reentrant" WIKI_TITLE = "Token ...
TokenReentrancy
python
getsentry__sentry
src/sentry/workflow_engine/utils/log_context.py
{ "start": 1841, "end": 4908 }
class ____(logging.LoggerAdapter[logging.Logger]): def debug(self, msg: str, *args: Any, **kwargs: Any) -> None: # type: ignore[override] if _log_context_state.get().verbose: self.info(msg, *args, **kwargs) else: self.log(logging.DEBUG, msg, *args, **kwargs) @override ...
_Adapter
python
getsentry__sentry
src/sentry/models/eventattachment.py
{ "start": 1514, "end": 1931 }
class ____: content_type: str size: int sha1: str blob_path: str | None = None def can_store_inline(data: bytes) -> bool: """ Determines whether `data` can be stored inline That is the case when it is shorter than 192 bytes, and all the bytes are non-NULL ASCII. """ return len...
PutfileResult
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py
{ "start": 95561, "end": 95855 }
class ____(Qwen3Attention): def __init__(self, config: Qwen3OmniMoeCode2WavConfig, layer_idx): super().__init__(config, layer_idx) self.q_norm = nn.Identity() self.k_norm = nn.Identity() self.sliding_window = config.sliding_window
Qwen3OmniMoeCode2WavAttention
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_project_forms.py
{ "start": 44688, "end": 48835 }
class ____(TestCase): def setUp(self): self.project = get(Project) def test_addonsconfig_form(self): data = { "enabled": True, "options_root_selector": "main", "analytics_enabled": False, "doc_diff_enabled": False, "filetreediff_enable...
TestAddonsConfigForm
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/tests/test_incremental.py
{ "start": 6013, "end": 27302 }
class ____(BaseTest): async def test_two_sequential_reads( self, connector_config: SecretDict, configured_catalog_for_incremental: ConfiguredAirbyteCatalog, docker_runner: ConnectorRunner, client_container: Optional[dagger.Container], client_container_config: Optional...
TestIncremental
python
ray-project__ray
rllib/utils/metrics/window_stat.py
{ "start": 87, "end": 2553 }
class ____: """Handles/stores incoming dataset and provides window-based statistics. .. testcode:: :skipif: True win_stats = WindowStat("level", 3) win_stats.push(5.0) win_stats.push(7.0) win_stats.push(7.0) win_stats.push(10.0) # Expect 8.0 as the mean ...
WindowStat
python
eth-brownie__brownie
brownie/utils/docopt.py
{ "start": 4090, "end": 4193 }
class ____(Exception): """Error in construction of usage-message by developer."""
DocoptLanguageError
python
django__django
django/db/backends/ddl_references.py
{ "start": 4311, "end": 5815 }
class ____(TableColumns): """Hold a reference to a foreign key name.""" def __init__( self, from_table, from_columns, to_table, to_columns, suffix_template, create_fk_name, ): self.to_reference = TableColumns(to_table, to_columns) self...
ForeignKeyName
python
sqlalchemy__sqlalchemy
test/ext/asyncio/test_session.py
{ "start": 28913, "end": 34149 }
class ____(AsyncFixture): @async_test async def test_get_connection_engine_bound(self, async_session): c1 = await async_session.connection() c2 = await async_session.connection() is_(c1, c2) is_(c1.engine, c2.engine) @async_test async def test_get_connection_kws(self, ...
AsyncProxyTest
python
pandas-dev__pandas
pandas/tests/indexes/datetimes/test_scalar_compat.py
{ "start": 516, "end": 16187 }
class ____: def test_dti_no_millisecond_field(self): msg = "type object 'DatetimeIndex' has no attribute 'millisecond'" with pytest.raises(AttributeError, match=msg): DatetimeIndex.millisecond msg = "'DatetimeIndex' object has no attribute 'millisecond'" with pytest.rais...
TestDatetimeIndexOps
python
urllib3__urllib3
src/urllib3/exceptions.py
{ "start": 8053, "end": 8601 }
class ____(HTTPError, httplib_IncompleteRead): """Invalid chunk length in a chunked response.""" def __init__(self, response: HTTPResponse, length: bytes) -> None: self.partial: int = response.tell() # type: ignore[assignment] self.expected: int | None = response.length_remaining self....
InvalidChunkLength
python
dagster-io__dagster
python_modules/dagster/dagster/_daemon/asset_daemon.py
{ "start": 14283, "end": 58282 }
class ____(DagsterDaemon): def __init__(self, settings: Mapping[str, Any], pre_sensor_interval_seconds: int): self._pre_sensor_interval_seconds = pre_sensor_interval_seconds self._last_pre_sensor_submit_time = None self._checked_migrations = False self._settings = settings ...
AssetDaemon
python
apache__airflow
airflow-core/src/airflow/utils/log/logging_mixin.py
{ "start": 7507, "end": 10183 }
class ____(StreamHandler): """ Custom StreamHandler that uses current sys.stderr/stdout as the stream for logging. This class is like a StreamHandler using sys.stderr/stdout, but uses whatever sys.stderr/stdout is currently set to rather than the value of sys.stderr/stdout at handler construction t...
RedirectStdHandler
python
django__django
tests/migrations/test_migrations_squashed_complex_multi_apps/app1/2_auto.py
{ "start": 35, "end": 182 }
class ____(migrations.Migration): dependencies = [("app1", "1_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
Migration
python
django-guardian__django-guardian
example_project/articles/admin.py
{ "start": 89, "end": 243 }
class ____(admin.ModelAdmin): list_display = ("title", "slug", "created_at") list_filter = ("created_at",) search_fields = ("title",)
ArticleAdmin
python
getsentry__sentry
src/sentry/tasks/email.py
{ "start": 1757, "end": 3022 }
class ____(Exception): """ SMTPDataError with a 4xx code, and thus is temporary and retriable. """ def __init__(self, code: int, msg: str | bytes) -> None: self.smtp_code = code self.smtp_error = msg self.args = (code, msg) def _send_email(message: dict[str, Any]) -> None: ...
TemporaryEmailError
python
getsentry__sentry
src/sentry/api/endpoints/project_statistical_detectors.py
{ "start": 573, "end": 2148 }
class ____(ProjectEndpoint): owner = ApiOwner.PROFILING publish_status = { "GET": ApiPublishStatus.PRIVATE, } enforce_rate_limit = True def get(self, request: Request, project: Project) -> Response: try: timestamp = parse_datetime_string(request.GET["end"]) excep...
ProjectStatisticalDetectors
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 211277, "end": 211747 }
class ____(sgqlc.types.Input): """Autogenerated input type of DeleteDeployment""" __schema__ = github_schema __field_names__ = ("id", "client_mutation_id") id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="id") """The Node ID of the deployment to be deleted.""" client_mutation_id ...
DeleteDeploymentInput
python
ansible__ansible
test/units/_internal/templating/fixtures/valid_collection/ansible_collections/valid/also_valid/plugins/lookup/also_also_valid.py
{ "start": 84, "end": 194 }
class ____(LookupBase): def run(self, terms, variables=None, **kwargs) -> list: return []
LookupModule
python
sqlalchemy__sqlalchemy
test/orm/test_composites.py
{ "start": 58709, "end": 62188 }
class ____(fixtures.TestBase): @testing.fixture def edge_point_fixture(self, decl_base): @dataclasses.dataclass class Point: x: Optional[int] y: Optional[int] def go(return_none_on): class Edge(decl_base): __tablename__ = "edge" ...
NoneReturnTest
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py
{ "start": 12116, "end": 13207 }
class ____(BaseConfig): """ Config that is used to verify that a connector and its streams uphold certain behavior and features that are required to maintain enterprise-level standard of quality. Attributes: streams_without_primary_key: A list of streams where a primary key is not available fro...
ConnectorAttributesConfig
python
spack__spack
lib/spack/spack/compilers/libraries.py
{ "start": 12121, "end": 12985 }
class ____: """Deserialized cache entry for a compiler""" __slots__ = ("c_compiler_output",) def __init__(self, c_compiler_output: Optional[str]): self.c_compiler_output = c_compiler_output @property def empty(self) -> bool: """Sometimes the compiler is temporarily broken, prevent...
CompilerCacheEntry
python
astropy__astropy
astropy/table/meta.py
{ "start": 857, "end": 12238 }
class ____(dict): """ Specialized dict subclass to represent attributes of a Column and return items() in a preferred order. This is only for use in generating a YAML map representation that has a fixed order. """ def items(self): """ Return items as a ColumnOrderList, which so...
ColumnDict
python
dagster-io__dagster
python_modules/libraries/dagster-mlflow/dagster_mlflow/resources.py
{ "start": 2352, "end": 12206 }
class ____(metaclass=MlflowMeta): """Class for setting up an mlflow resource for dagster runs. This takes care of all the configuration required to use mlflow tracking and the complexities of mlflow tracking dagster parallel runs. """ def __init__(self, context): # Context associated attrib...
MlFlow
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 3573, "end": 3664 }
class ____(Protocol): def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
ReplaceFn
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/decl_base.py
{ "start": 9210, "end": 10490 }
class ____(_ORMClassConfigurator): """Configurator that configures a class that's potentially going to be mapped, and optionally turned into a dataclass as well.""" __slots__ = ( "properties", "declared_attr_reg", ) properties: util.OrderedDict[ str, Union[ ...
_MapperConfig
python
Pylons__pyramid
tests/test_url.py
{ "start": 47629, "end": 48383 }
class ____(unittest.TestCase): def _callFUT(self, request, *elements, **kw): from pyramid.url import current_route_path return current_route_path(request, *elements, **kw) def _makeRequest(self): class Request: def current_route_path(self, *elements, **kw): ...
Test_current_route_path
python
getsentry__sentry
src/sentry/integrations/pagerduty/client.py
{ "start": 1140, "end": 3335 }
class ____(ApiClient): allow_redirects = False integration_name = IntegrationProviderSlug.PAGERDUTY.value base_url = "https://events.pagerduty.com/v2/enqueue" def __init__(self, integration_key: str, integration_id: int | None) -> None: self.integration_key = integration_key super().__i...
PagerDutyClient
python
mlflow__mlflow
tests/pyfunc/test_chat_model.py
{ "start": 4915, "end": 21901 }
class ____(mlflow.pyfunc.ChatModel): def predict( self, context, messages: list[ChatMessage], params: ChatParams ) -> ChatCompletionResponse: tools = params.tools # call the first tool with some value for all the required params tool_name = tools[0].function.name tool_pa...
ChatModelWithToolCalling
python
kamyu104__LeetCode-Solutions
Python/graph-valid-tree.py
{ "start": 118, "end": 947 }
class ____(object): # @param {integer} n # @param {integer[][]} edges # @return {boolean} def validTree(self, n, edges): if len(edges) != n - 1: # Check number of edges. return False # init node's neighbors in dict neighbors = collections.defaultdict(list) f...
Solution
python
PyCQA__pylint
pylint/testutils/checker_test_case.py
{ "start": 590, "end": 3325 }
class ____: """A base testcase class for unit testing individual checker classes.""" # TODO: Figure out way to type this as type[BaseChecker] while also # setting self.checker correctly. CHECKER_CLASS: Any CONFIG: dict[str, Any] = {} def setup_method(self) -> None: self.linter = Unitte...
CheckerTestCase
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/partitions/mapping/partition_mapping.py
{ "start": 572, "end": 1384 }
class ____: """Represents the result of mapping a PartitionsSubset to the corresponding partitions in another PartitionsDefinition. partitions_subset (PartitionsSubset): The resulting partitions subset that was mapped to. Only contains partitions for existent partitions, filtering out nonexistent p...
UpstreamPartitionsResult
python
python-visualization__folium
folium/plugins/draw.py
{ "start": 119, "end": 6337 }
class ____(JSCSSMixin, MacroElement): ''' Vector drawing and editing plugin for Leaflet. Parameters ---------- export : bool, default False Add a small button that exports the drawn shapes as a geojson file. feature_group : FeatureGroup, optional The FeatureGroup object that wil...
Draw
python
numba__numba
numba/core/types/iterators.py
{ "start": 1771, "end": 2326 }
class ____(SimpleIteratorType): """ Type class for `enumerate` objects. Type instances are parametered with the underlying source type. """ def __init__(self, iterable_type): from numba.core.types import Tuple, intp self.source_type = iterable_type.iterator_type yield_type =...
EnumerateType
python
scipy__scipy
scipy/interpolate/tests/test_fitpack.py
{ "start": 7923, "end": 10551 }
class ____: def setup_method(self): # non-uniform grid, just to make it sure x = np.linspace(0, 1, 100)**3 y = np.sin(20 * x) self.spl = splrep(x, y) # double check that knots are non-uniform assert np.ptp(np.diff(self.spl[0])) > 0 def test_inverse(self): ...
TestSplder
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingLiteralMember1.py
{ "start": 2644, "end": 2864 }
class ____: @property def type(self) -> Literal[1]: return 1 def test(x: E | F) -> None: if x.type == 1: reveal_type(x, expected_type="F") else: reveal_type(x, expected_type="E")
F
python
numba__numba
numba/tests/test_datamodel.py
{ "start": 694, "end": 757 }
class ____(test_factory()): fe_type = types.uint16
TestUInt16
python
PyCQA__pylint
tests/functional/u/unnecessary/unnecessary_dunder_call.py
{ "start": 1214, "end": 1282 }
class ____: def __init__(self): super().__init__(self)
Foo2
python
django__django
tests/forms_tests/tests/test_input_formats.py
{ "start": 4644, "end": 8759 }
class ____(SimpleTestCase): @classmethod def setUpClass(cls): cls.enterClassContext(translation.override(None)) super().setUpClass() def test_timeField(self): "TimeFields can parse dates in the default format" f = forms.TimeField() # Parse a time in an unaccepted for...
CustomTimeInputFormatsTests
python
ray-project__ray
release/ray_release/tests/test_state_machine.py
{ "start": 2762, "end": 11158 }
class ____: def builds(self): return MockBuildkiteBuild() def jobs(self): return MockBuildkiteJob() TestStateMachine.ray_repo = MockRepo() TestStateMachine.ray_buildkite = MockBuildkite() def test_ci_empty_results(): test = Test(name="w00t", team="ci", state=TestState.FLAKY) test.te...
MockBuildkite
python
huggingface__transformers
src/transformers/models/granitemoeshared/modeling_granitemoeshared.py
{ "start": 4775, "end": 6466 }
class ____(nn.Module): def __init__(self, num_experts: int, input_size: int, output_size: int) -> None: """ Initialize the GraniteMoeSharedParallelExperts module. The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with many MoE ...
GraniteMoeSharedParallelExperts
python
django-haystack__django-haystack
test_haystack/test_indexes.py
{ "start": 2973, "end": 3349 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField( document=True, use_template=True, index_fieldname="more_content" ) author = indexes.CharField(model_attr="author", index_fieldname="name_s") hello = indexes.CharField(model_attr="hello") def get_model(self): ...
GoodOverriddenFieldNameMockSearchIndex
python
mlflow__mlflow
mlflow/deployments/__init__.py
{ "start": 1550, "end": 4763 }
class ____(dict): """ Represents the predictions and metadata returned in response to a scoring request, such as a REST API request sent to the ``/invocations`` endpoint of an MLflow Model Server. """ def get_predictions(self, predictions_format="dataframe", dtype=None): """Get the predicti...
PredictionsResponse
python
wandb__wandb
wandb/vendor/pygments/lexers/templates.py
{ "start": 40092, "end": 40643 }
class ____(DelegatingLexer): """ Subclass of the `SmartyLexer` that highlights unlexed data with the `XmlLexer`. """ name = 'XML+Smarty' aliases = ['xml+smarty'] alias_filenames = ['*.xml', '*.tpl'] mimetypes = ['application/xml+smarty'] def __init__(self, **options): super...
XmlSmartyLexer
python
pytorch__pytorch
torch/serialization.py
{ "start": 25219, "end": 25460 }
class ____(_opener[IO[bytes]]): def __init__(self, name: Union[str, os.PathLike[str]], mode: str) -> None: super().__init__(open(name, mode)) # noqa: SIM115 def __exit__(self, *args): self.file_like.close()
_open_file
python
getsentry__sentry
tests/sentry/integrations/test_base.py
{ "start": 560, "end": 2531 }
class ____(TestCase): def setUp(self) -> None: self.user = self.create_user() self.organization = self.create_organization() self.project = self.create_project() ( self.model, self.org_integration, self.identity, identity_provider, ...
IntegrationTestCase
python
bokeh__bokeh
tests/unit/bokeh/application/handlers/test_script.py
{ "start": 1440, "end": 2980 }
class ____: # Public methods ---------------------------------------------------------- def test_runner_uses_source_from_filename(self) -> None: doc = Document() source = "# Test contents for script" result = {} def load(filename): handler = bahs.ScriptHandler(filena...
Test_ScriptHandler
python
pydata__xarray
xarray/core/common.py
{ "start": 8361, "end": 12725 }
class ____: """Mixin class that allows getting keys with attribute access""" __slots__ = () def __init_subclass__(cls, **kwargs): """Verify that all subclasses explicitly define ``__slots__``. If they don't, raise error in the core xarray module and a FutureWarning in third-party e...
AttrAccessMixin
python
django__django
tests/schema/models.py
{ "start": 4749, "end": 4942 }
class ____(models.Model): year = models.IntegerField() slug = models.SlugField(unique=False) class Meta: apps = new_apps unique_together = ["year", "slug"]
UniqueTest
python
lazyprogrammer__machine_learning_examples
rl/linear_rl_trader.py
{ "start": 6206, "end": 9829 }
class ____(object): def __init__(self, state_size, action_size): self.state_size = state_size self.action_size = action_size self.gamma = 0.95 # discount rate self.epsilon = 1.0 # exploration rate self.epsilon_min = 0.01 self.epsilon_decay = 0.995 self.model = LinearModel(state_size, act...
DQNAgent
python
scipy__scipy
benchmarks/benchmarks/integrate.py
{ "start": 7767, "end": 9941 }
class ____(Benchmark): params = ( # rule [ "genz-malik", "gk15", "gk21", ], # input dimension of integrand (ndim) [1, 3, 5], # output dimension of integrand (fdim) [1, 8], # rtol [1e-10, 1e-11], ) ...
CubatureOscillatory
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 29224, "end": 29613 }
class ____(BaseModel): """ Variable serializer for responses. """ key: Annotated[str, Field(title="Key")] value: Annotated[str, Field(title="Value")] description: Annotated[str | None, Field(title="Description")] = None is_encrypted: Annotated[bool, Field(title="Is Encrypted")] team_id:...
VariableResponse
python
django-extensions__django-extensions
tests/test_runscript.py
{ "start": 1556, "end": 2595 }
class ____(RunScriptTests): def test_prints_error_on_nonexistent_script(self): cmd = self.get_command() with self.assertRaises(CommandError): call_command(cmd, "non_existent_script", verbosity=2) self.assertIn( "No (valid) module for script 'non_existent_script' found...
NonExistentScriptsTests
python
crytic__slither
slither/detectors/reentrancy/reentrancy_benign.py
{ "start": 583, "end": 7600 }
class ____(Reentrancy): ARGUMENT = "reentrancy-benign" HELP = "Benign reentrancy vulnerabilities" IMPACT = DetectorClassification.LOW CONFIDENCE = DetectorClassification.MEDIUM WIKI = ( "https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities-2" ) W...
ReentrancyBenign
python
keon__algorithms
algorithms/stack/ordered_stack.py
{ "start": 110, "end": 991 }
class ____: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push_t(self, item): self.items.append(item) # push method to maintain order when pushing new elements def push(self, item): temp_stack = OrderedStack() if self.i...
OrderedStack
python
kamyu104__LeetCode-Solutions
Python/maximum-depth-of-n-ary-tree.py
{ "start": 29, "end": 146 }
class ____(object): def __init__(self, val, children): self.val = val self.children = children
Node
python
realpython__materials
python-type-checking/game_003.py
{ "start": 806, "end": 1139 }
class ____: def __init__(self, name, hand): self.name = name self.hand = hand def play_card(self): """Play a card from the player's hand""" card = random.choice(self.hand.cards) self.hand.cards.remove(card) print(f"{self.name}: {card!r:<3} ", end="") ret...
Player
python
Textualize__textual
src/textual/widgets/_tree.py
{ "start": 1389, "end": 1533 }
class ____(Exception): """Exception raised when trying to remove the root of a [`TreeNode`][textual.widgets.tree.TreeNode]."""
RemoveRootError
python
scipy__scipy
scipy/fft/_pocketfft/tests/test_basic.py
{ "start": 13070, "end": 13229 }
class ____(_TestIRFFTBase): def setup_method(self): self.cdt = np.complex128 self.rdt = np.float64 self.ndec = 14
TestIRFFTLongDouble
python
scikit-image__scikit-image
src/skimage/util/_backends.py
{ "start": 5067, "end": 5195 }
class ____(RuntimeWarning): """Notification issued when a function is dispatched to a backend.""" pass
DispatchNotification
python
fastapi__sqlmodel
docs_src/tutorial/select/tutorial004.py
{ "start": 100, "end": 1085 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): ...
Hero
python
pytorch__pytorch
torch/_export/serde/schema.py
{ "start": 11142, "end": 11218 }
class ____: field_names: Annotated[list[str], 10] @dataclass
NamedTupleDef
python
readthedocs__readthedocs.org
readthedocs/audit/filters.py
{ "start": 247, "end": 1416 }
class ____(FilterSet): """Filter for user security logs.""" allowed_actions = [ (AuditLog.AUTHN, AuditLog.AUTHN_TEXT), (AuditLog.AUTHN_FAILURE, AuditLog.AUTHN_FAILURE_TEXT), (AuditLog.LOGOUT, AuditLog.LOGOUT_TEXT), (AuditLog.INVITATION_SENT, AuditLog.INVITATION_SENT_TEXT), ...
UserSecurityLogFilter
python
django__django
tests/lookup/tests.py
{ "start": 964, "end": 67259 }
class ____(TestCase): @classmethod def setUpTestData(cls): # Create a few Authors. cls.au1 = Author.objects.create(name="Author 1", alias="a1", bio="x" * 4001) cls.au2 = Author.objects.create(name="Author 2", alias="a2") # Create a few Articles. cls.a1 = Article.objects.c...
LookupTests
python
Lightning-AI__lightning
examples/fabric/kfold_cv/train_fabric.py
{ "start": 1071, "end": 7504 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout(0.25) self.dropout2 = nn.Dropout(0.5) self.fc1 = nn.Linear(9216, 128) self.fc2 = nn.Linear...
Net