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
pytest-dev__pytest
src/_pytest/capture.py
{ "start": 9807, "end": 10198 }
class ____(CaptureBase[str]): EMPTY_BUFFER = "" def __init__(self, fd: int) -> None: pass def start(self) -> None: pass def done(self) -> None: pass def suspend(self) -> None: pass def resume(self) -> None: pass def snap(self) -> str: ret...
NoCapture
python
ray-project__ray
python/ray/data/_internal/operator_event_exporter.py
{ "start": 3166, "end": 5231 }
class ____(OperatorEventExporter): """Operator event exporter implementation that uses the Ray export event logger. This exporter writes operator event to log files using Ray's export event system. """ def __init__(self, logger: logging.Logger): """Initialize with a configured export event log...
LoggerOperatorEventExporter
python
pandas-dev__pandas
pandas/tests/arithmetic/test_timedelta64.py
{ "start": 26940, "end": 53513 }
class ____: # Tests for timedelta64[ns] __add__, __sub__, __radd__, __rsub__ def test_sub_nat_retain_unit(self): ser = pd.to_timedelta(Series(["00:00:01"])).astype("m8[s]") result = ser - NaT expected = Series([NaT], dtype="m8[s]") tm.assert_series_equal(result, expected) ...
TestTimedeltaArraylikeAddSubOps
python
openai__openai-python
src/openai/types/realtime/session_update_event_param.py
{ "start": 579, "end": 1160 }
class ____(TypedDict, total=False): session: Required[Session] """Update the Realtime session. Choose either a realtime session or a transcription session. """ type: Required[Literal["session.update"]] """The event type, must be `session.update`.""" event_id: str """Optional client-ge...
SessionUpdateEventParam
python
kamyu104__LeetCode-Solutions
Python/count-collisions-on-a-road.py
{ "start": 52, "end": 465 }
class ____(object): def countCollisions(self, directions): """ :type directions: str :rtype: int """ result = cnt = 0 smooth = 1 for x in directions: if x == 'R': cnt += 1 elif x == 'S' or (cnt or not smooth): ...
Solution
python
facebook__pyre-check
client/language_server/connections.py
{ "start": 9427, "end": 14359 }
class ____(AsyncBytesWriter): """ An implementation of `AsyncBytesWriter` based on `asyncio.StreamWriter`. """ stream_writer: asyncio.StreamWriter def __init__(self, stream_writer: asyncio.StreamWriter) -> None: self.stream_writer = stream_writer async def write(self, data: bytes) -> ...
StreamBytesWriter
python
numba__numba
numba/cuda/errors.py
{ "start": 416, "end": 1724 }
class ____(LoweringError): pass _launch_help_url = ("https://numba.readthedocs.io/en/stable/cuda/" "kernels.html#kernel-invocation") missing_launch_config_msg = """ Kernel launch configuration was not specified. Use the syntax: kernel_function[blockspergrid, threadsperblock](arg0, arg1, ..., ...
CudaLoweringError
python
pandas-dev__pandas
asv_bench/benchmarks/rolling.py
{ "start": 5794, "end": 6754 }
class ____: params = ( [({"window": 10}, "rolling"), ({"window": 1000}, "rolling"), ({}, "expanding")], ["corr", "cov"], [True, False], ) param_names = ["window_kwargs", "method", "pairwise"] def setup(self, kwargs_window, method, pairwise): N = 10**4 n_groups = ...
Pairwise
python
dask__dask
dask/_expr.py
{ "start": 39384, "end": 39839 }
class ____(Expr): _parameters = ["expr"] def _simplify_down(self): return self.expr.finalize_compute() def _convert_dask_keys(keys): from dask._task_spec import List, TaskRef assert isinstance(keys, list) new_keys = [] for key in keys: if isinstance(key, list): ne...
FinalizeCompute
python
kamyu104__LeetCode-Solutions
Python/rotate-array.py
{ "start": 1874, "end": 2314 }
class ____(object): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. """ def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. ...
Solution4
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/list_files_test.py
{ "start": 10954, "end": 12814 }
class ____( ListFilesTest, checkpoint_test_base.CheckpointTestBase, parameterized.TestCase): def setUp(self): super().setUp() # Bypasses the default value for `warm_start`, which is not supported for # global shuffling: # https://github.com/tensorflow/tensorflow/blob/29561af231863afb3b6b8...
ListFilesGlobalShuffleCheckpointTest
python
ray-project__ray
python/ray/tests/test_resource_demand_scheduler.py
{ "start": 59423, "end": 134727 }
class ____(unittest.TestCase): def setUp(self): _NODE_PROVIDERS["mock"] = lambda config: self.create_provider self.provider = None self.tmpdir = tempfile.mkdtemp() def tearDown(self): self.provider = None del _NODE_PROVIDERS["mock"] _clear_provider_cache() ...
AutoscalingTest
python
pytest-dev__pytest
src/_pytest/logging.py
{ "start": 14030, "end": 23308 }
class ____: """Provides access and control of log capturing.""" def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None: check_ispytest(_ispytest) self._item = item self._initial_handler_level: int | None = None # Dict of log name -> log level. self._ini...
LogCaptureFixture
python
plotly__plotly.py
plotly/graph_objs/scatterternary/marker/_gradient.py
{ "start": 233, "end": 4928 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterternary.marker" _path_str = "scatterternary.marker.gradient" _valid_props = {"color", "colorsrc", "type", "typesrc"} @property def color(self): """ Sets the final color of the gradient fill: the center color for ...
Gradient
python
openai__openai-python
src/openai/_module_client.py
{ "start": 3805, "end": 5033 }
class ____(LazyProxy["Conversations"]): @override def __load__(self) -> Conversations: return _load_client().conversations chat: Chat = ChatProxy().__as_proxied__() beta: Beta = BetaProxy().__as_proxied__() files: Files = FilesProxy().__as_proxied__() audio: Audio = AudioProxy().__as_proxied__() evals...
ConversationsProxy
python
huggingface__transformers
src/transformers/models/chinese_clip/modeling_chinese_clip.py
{ "start": 2098, "end": 4152 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`): Contrastive loss for image-text similarity. logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`): The scaled dot product scores betwee...
ChineseCLIPOutput
python
pytorch__pytorch
test/profiler/test_profiler_tree.py
{ "start": 2141, "end": 2763 }
class ____(torch.Tensor): @staticmethod def __new__(cls, elem): t = torch.Tensor._make_subclass(cls, elem, elem.requires_grad) t.elem = elem return t @classmethod def __torch_dispatch__(cls, func, types, args=(), kwargs=None): def unwrap(x): return x.elem if ...
TorchDispatchTensor
python
tensorflow__tensorflow
tensorflow/python/checkpoint/checkpoint_management_test.py
{ "start": 1601, "end": 5192 }
class ____(test.TestCase): @staticmethod @contextlib.contextmanager def tempWorkingDir(temppath): cwd = os.getcwd() os.chdir(temppath) try: yield finally: os.chdir(cwd) @staticmethod @contextlib.contextmanager def tempDir(): tempdir = tempfile.mkdtemp() try: yield...
LatestCheckpointWithRelativePaths
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pyflakes/F821_26.py
{ "start": 1352, "end": 1483 }
class ____(list["Tree | Leaf"]): ... # always okay # Annotations are treated as assignments in .pyi files, but not in .py files
Tree2
python
zarr-developers__zarr-python
tests/package_with_entrypoint/__init__.py
{ "start": 1149, "end": 1588 }
class ____(CodecPipeline): def __init__(self, batch_size: int = 1) -> None: pass async def encode( self, chunks_and_specs: Iterable[tuple[CodecInput | None, ArraySpec]] ) -> Iterable[Buffer | None]: return [None] async def decode( self, chunks_and_specs: Iterable[tuple[...
TestEntrypointCodecPipeline
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_embedding_for_serving.py
{ "start": 2055, "end": 23825 }
class ____(tpu_embedding_base.TPUEmbeddingBase): """The TPUEmbedding mid level API running on CPU for serving. Note: This class is intended to be used for embedding tables that are trained on TPU and to be served on CPU. Therefore the class should be only initialized under non-TPU strategy. Otherwise an error ...
TPUEmbeddingForServing
python
ray-project__ray
python/ray/tune/utils/log.py
{ "start": 163, "end": 1462 }
class ____(Enum): V0_MINIMAL = 0 V1_EXPERIMENT = 1 V2_TRIAL_NORM = 2 V3_TRIAL_DETAILS = 3 def __int__(self): return self.value verbosity: Union[int, Verbosity] = Verbosity.V3_TRIAL_DETAILS @DeveloperAPI def set_verbosity(level: Union[int, Verbosity]): global verbosity if isinst...
Verbosity
python
facebook__pyre-check
client/libcst_vendored_visitors/_apply_type_annotations.py
{ "start": 17792, "end": 18331 }
class ____: global_annotations: int = 0 attribute_annotations: int = 0 parameter_annotations: int = 0 return_annotations: int = 0 classes_added: int = 0 typevars_and_generics_added: int = 0 def any_changes_applied(self) -> bool: return ( self.global_annotations ...
AnnotationCounts
python
pennersr__django-allauth
allauth/account/stages.py
{ "start": 1576, "end": 4317 }
class ____: def __init__(self, request, login): self.request = request self.login = login self.state = self.login.state.setdefault("stages", {}) @classmethod def enter(cls, request, stage_key): from allauth.account.internal.stagekit import unstash_login login = unst...
LoginStageController
python
arrow-py__arrow
tests/test_locales.py
{ "start": 51710, "end": 55022 }
class ____: def test_couple_of_timeframe(self): # Now assert self.locale._format_timeframe("now", 0) == "הרגע" # Second(s) assert self.locale._format_timeframe("second", 1) == "שנייה" assert self.locale._format_timeframe("seconds", 2) == "2 שניות" assert self.locale....
TestHebrewLocale
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_stackdriver.py
{ "start": 8613, "end": 9147 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.stackdriver.StackdriverHook") def test_execute(self, mock_hook): operator = StackdriverDisableNotificationChannelsOperator(task_id=TEST_TASK_ID, filter_=TEST_FILTER) operator.execute(context=mock.MagicMock()) mock_hook.ret...
TestStackdriverDisableNotificationChannelsOperator
python
mlflow__mlflow
mlflow/prompt/promptlab_model.py
{ "start": 132, "end": 7095 }
class ____: import pandas as pd def __init__(self, prompt_template, prompt_parameters, model_parameters, model_route): self.prompt_parameters = prompt_parameters self.model_parameters = model_parameters self.model_route = model_route self.prompt_template = prompt_template d...
_PromptlabModel
python
encode__django-rest-framework
tests/test_routers.py
{ "start": 26360, "end": 26509 }
class ____(BasenameTestCase, TestCase): def setUp(self): self.router = SimpleRouter(trailing_slash=False)
TestDuplicateBasenameSimpleRouter
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/traversals.py
{ "start": 5929, "end": 6358 }
class ____(HasShallowCopy): """Supplies Generative behavior but making use of traversals to shallow copy. .. seealso:: :class:`sqlalchemy.sql.base.Generative` """ __slots__ = () def _generate(self) -> Self: cls = self.__class__ s = cls.__new__(cls) self._sha...
GenerativeOnTraversal
python
numpy__numpy
numpy/_core/tests/test_unicode.py
{ "start": 12671, "end": 12830 }
class ____(ByteorderValues): """Check the byteorder in unicode (size 1009, UCS2 values)""" ulen = 1009 ucs_value = ucs2_value
TestByteorder_1009_UCS2
python
FactoryBoy__factory_boy
tests/test_regression.py
{ "start": 356, "end": 467 }
class ____(T.NamedTuple): book: Book published_on: datetime.date countries: T.List[str]
PublishedBook
python
fluentpython__example-code
21-class-metaprog/bulkfood/model_v8.py
{ "start": 1023, "end": 1309 }
class ____(Validated): """a string with at least one non-space character""" def validate(self, instance, value): value = value.strip() if len(value) == 0: raise ValueError('value cannot be empty or blank') return value # BEGIN MODEL_V8
NonBlank
python
huggingface__transformers
src/transformers/models/qwen3_vl/modular_qwen3_vl.py
{ "start": 13609, "end": 14121 }
class ____(PatchEmbed): def __init__(self, config) -> None: super().__init__() self.patch_size = config.patch_size self.temporal_patch_size = config.temporal_patch_size self.in_channels = config.in_channels self.embed_dim = config.hidden_size kernel_size = [self.temp...
Qwen3VLVisionPatchEmbed
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 23179, "end": 23305 }
class ____(models.Model): name = models.CharField(max_length=150) log = HistoricalRecords(related_name="history")
Street
python
numpy__numpy
numpy/lib/tests/test_function_base.py
{ "start": 23432, "end": 23943 }
class ____: def test_basic(self): a = np.array([3, 4, 5, 10, -3, -5, 6.0]) assert_equal(np.ptp(a, axis=0), 15.0) b = np.array([[3, 6.0, 9.0], [4, 10.0, 5.0], [8, 3.0, 2.0]]) assert_equal(np.ptp(b, axis=0), [5.0, 7.0, 7.0]) assert_e...
TestPtp
python
tensorflow__tensorflow
tensorflow/python/tpu/tests/tpu_embedding_v2_enqueue_mode_test.py
{ "start": 1259, "end": 8496 }
class ____(tpu_embedding_base_test.TPUEmbeddingBaseTest): @parameterized.parameters([True, False]) def test_enqueue_with_outside_compilation(self, use_mlir): if use_mlir: config.enable_mlir_bridge() strategy, mid_level_api, _ = self._create_strategy_and_mid_level('sgd') mid_level_api.build([ ...
TPUEmbeddingTest
python
Netflix__metaflow
metaflow/_vendor/click/core.py
{ "start": 53560, "end": 54653 }
class ____(MultiCommand): """A command collection is a multi command that merges multiple multi commands together into one. This is a straightforward implementation that accepts a list of different multi commands as sources and provides all the commands for each of them. """ def __init__(self,...
CommandCollection
python
huggingface__transformers
tests/models/video_llama_3/test_video_processing_video_llama_3.py
{ "start": 1345, "end": 4936 }
class ____: def __init__( self, parent, batch_size=5, num_frames=8, num_channels=3, min_resolution=30, max_resolution=80, do_resize=True, size=None, do_center_crop=True, crop_size=None, do_normalize=True, image_m...
VideoLlama3VideoProcessingTester
python
django__django
tests/backends/postgresql/test_operations.py
{ "start": 355, "end": 2836 }
class ____(SimpleTestCase): def test_sql_flush(self): self.assertEqual( connection.ops.sql_flush( no_style(), [Person._meta.db_table, Tag._meta.db_table], ), ['TRUNCATE "backends_person", "backends_tag";'], ) def test_sql_flush...
PostgreSQLOperationsTests
python
getsentry__sentry
src/sentry/workflow_engine/migrations/0068_migrate_anomaly_detection_alerts.py
{ "start": 1512, "end": 2046 }
class ____(Enum): EMAIL = 0 PAGERDUTY = 1 SLACK = 2 MSTEAMS = 3 SENTRY_APP = 4 SENTRY_NOTIFICATION = 5 # Use personal notification platform (src/sentry/notifications) OPSGENIE = 6 DISCORD = 7 MAX_ACTIONS = 3 ACTION_TYPE_TO_STRING = { AlertRuleTriggerActionType.PAGERDUTY.value: "P...
AlertRuleTriggerActionType
python
pennersr__django-allauth
allauth/socialaccount/providers/zoho/provider.py
{ "start": 310, "end": 1194 }
class ____(OAuth2Provider): id = "zoho" name = "Zoho" account_class = ZohoAccount oauth2_adapter_class = ZohoOAuth2Adapter def get_default_scope(self): return ["aaaserver.profile.READ"] def extract_uid(self, data): return str(data["ZUID"]) def extract_common_fields(self, d...
ZohoProvider
python
python__mypy
mypy/nodes.py
{ "start": 134397, "end": 136393 }
class ____(TypeInfo): __slots__ = ("msg",) # types.py defines a single instance of this class, called types.NOT_READY. # This instance is used as a temporary placeholder in the process of de-serialization # of 'Instance' types. The de-serialization happens in two steps: In the first step, # Instanc...
FakeInfo
python
pdm-project__pdm
src/pdm/models/session.py
{ "start": 1272, "end": 4480 }
class ____(PyPIClient): def __init__(self, *, sources: list[RepositoryConfig], cache_dir: Path | None = None, **kwargs: Any) -> None: from httpx._utils import URLPattern from unearth.fetchers.sync import LocalFSTransport if cache_dir is None: def cache_transport(transport: http...
PDMPyPIClient
python
psf__requests
src/requests/auth.py
{ "start": 3095, "end": 10186 }
class ____(AuthBase): """Attaches HTTP Digest Authentication to the given Request object.""" def __init__(self, username, password): self.username = username self.password = password # Keep state in per-thread local storage self._thread_local = threading.local() def init_pe...
HTTPDigestAuth
python
ray-project__ray
python/ray/train/v2/_internal/execution/worker_group/worker.py
{ "start": 1566, "end": 2519 }
class ____: hostname: str node_id: str node_ip: str pid: int accelerator_ids: Dict[str, List[Union[int, str]]] @property def gpu_ids(self) -> List[Union[int, str]]: return self.accelerator_ids.get("GPU", []) @cached_property def _repr(self) -> str: indent = " " ...
ActorMetadata
python
plotly__plotly.py
plotly/graph_objs/choropleth/colorbar/_tickformatstop.py
{ "start": 233, "end": 8529 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "choropleth.colorbar" _path_str = "choropleth.colorbar.tickformatstop" _valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"} @property def dtickrange(self): """ range [*min*, *max*], where "min", "ma...
Tickformatstop
python
PyCQA__pylint
tests/functional/d/dataclass/dataclass_parameter.py
{ "start": 179, "end": 333 }
class ____: """Simple dataclass with a KW_ONLY parameter.""" _: dataclasses.KW_ONLY data: str MyDataClass(data="test") @dataclass
MyDataClass
python
tensorflow__tensorflow
tensorflow/python/checkpoint/checkpoint.py
{ "start": 9599, "end": 16368 }
class ____: """Holds the status of an object-based checkpoint load.""" def __init__(self, object_graph_proto, save_path, save_path_tensor, reader, restore_op_cache, graph_view, options, saveables_cache): """Specify the checkpoint being loaded. Args: object_graph_proto: The TrackableOb...
_CheckpointRestoreCoordinator
python
automl__auto-sklearn
autosklearn/pipeline/components/data_preprocessing/rescaling/abstract_rescaling.py
{ "start": 423, "end": 1444 }
class ____(object): # Rescaling does not support fit_transform (as of 0.19.1)! def __init__( self, random_state: Optional[Union[int, np.random.RandomState]] = None ) -> None: self.preprocessor: Optional[BaseEstimator] = None def fit( self, X: PIPELINE_DATA_DTYPE, y: Optional[PIP...
Rescaling
python
scrapy__scrapy
tests/test_request_attribute_binding.py
{ "start": 341, "end": 492 }
class ____: def process_response(self, request, response): return response.replace(request=Request(OVERRIDDEN_URL))
ProcessResponseMiddleware
python
airbytehq__airbyte
airbyte-integrations/connectors/source-microsoft-sharepoint/source_microsoft_sharepoint/spec.py
{ "start": 2624, "end": 5751 }
class ____(AbstractFileBasedSpec, BaseModel): """ SourceMicrosoftSharePointSpec class for Microsoft SharePoint Source Specification. This class combines the authentication details with additional configuration for the SharePoint API. """ class Config: title = "Microsoft SharePoint Source Sp...
SourceMicrosoftSharePointSpec
python
coleifer__peewee
playhouse/apsw_ext.py
{ "start": 4813, "end": 4861 }
class ____(_DateField): db_value = nh
DateField
python
numba__numba
numba/cuda/cudadrv/driver.py
{ "start": 36598, "end": 36854 }
class ____(int): """ Dummy object for _PendingDeallocs when *size* is not set. """ def __new__(cls, *args, **kwargs): return super().__new__(cls, 0) def __str__(self): return '?' _SizeNotSet = _SizeNotSet()
_SizeNotSet
python
realpython__materials
python-microservices-with-grpc/marketplace/recommendations_pb2_grpc.py
{ "start": 656, "end": 1644 }
class ____(object): """Missing associated documentation comment in .proto file""" def Recommend(self, request, context): """Missing associated documentation comment in .proto file""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") r...
RecommendationsServicer
python
ansible__ansible
test/units/_internal/templating/test_jinja_bits.py
{ "start": 20956, "end": 22043 }
class ____(NotifiableAccessContextBase): def __init__(self) -> None: self._type_interest = frozenset(Marker._concrete_subclasses) self._markers: list[Marker] = [] def _notify(self, o: Marker) -> None: self._markers.append(o) @pytest.mark.parametrize("template", ( '{{ adict["bogus"...
ExampleMarkerAccessTracker
python
Farama-Foundation__Gymnasium
gymnasium/envs/phys2d/pendulum.py
{ "start": 1013, "end": 7549 }
class ____( FuncEnv[StateType, jax.Array, int, float, bool, RenderStateType, PendulumParams] ): """Pendulum but in jax and functional structure.""" max_torque: float = 2.0 observation_space = gym.spaces.Box(-np.inf, np.inf, shape=(3,), dtype=np.float32) action_space = gym.spaces.Box(-max_torque, m...
PendulumFunctional
python
pytorch__pytorch
test/export/test_export.py
{ "start": 611297, "end": 640391 }
class ____(torch.nn.Module): def forward(self, x: "f32[2, 4]", y: "f32[4]"): add: "f32[2, 4]" = torch.ops.aten.add.Tensor(x, y); x = None hints_wrapper_body_graph_0 = self.hints_wrapper_body_graph_0 hints_wrapper = torch.ops.higher_order.hints_wrapper(hints_wrapper_body_graph_0, (add, y), ...
GraphModule
python
tensorflow__tensorflow
tensorflow/python/ops/structured/structured_tensor_test.py
{ "start": 3183, "end": 70739 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def assertAllEqual(self, a, b, msg=None): if not (isinstance(a, structured_tensor.StructuredTensor) or isinstance(b, structured_tensor.StructuredTensor)): return super(StructuredTensorTest, self).assert...
StructuredTensorTest
python
ansible__ansible
lib/ansible/_internal/_ssh/_ssh_agent.py
{ "start": 5618, "end": 6891 }
class ____(str, VariableSized, enum.Enum): RSA = "ssh-rsa" DSA = "ssh-dss" ECDSA256 = "ecdsa-sha2-nistp256" SKECDSA256 = "sk-ecdsa-sha2-nistp256@openssh.com" ECDSA384 = "ecdsa-sha2-nistp384" ECDSA521 = "ecdsa-sha2-nistp521" ED25519 = "ssh-ed25519" SKED25519 = "sk-ssh-ed25519@openssh.com"...
KeyAlgo
python
jina-ai__jina
tests/integration/instrumentation/__init__.py
{ "start": 1557, "end": 2569 }
class ____(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.meter: self.request_counter = self.meter.create_counter('request_counter') else: self.request_counter = None @requests(on='/search') def empty(self, docs: Doc...
ExecutorTestWithTracing
python
scrapy__scrapy
tests/test_dependencies.py
{ "start": 147, "end": 962 }
class ____: def test_pinned_twisted_version(self): """When running tests within a Tox environment with pinned dependencies, make sure that the version of Twisted is the pinned version. See https://github.com/scrapy/scrapy/pull/4814#issuecomment-706230011 """ if not o...
TestScrapyUtils
python
ansible__ansible
lib/ansible/_internal/_ssh/_ssh_agent.py
{ "start": 3429, "end": 3832 }
class ____: @classmethod def from_blob(cls, blob: memoryview | bytes) -> t.Self: raise NotImplementedError @classmethod def consume_from_blob(cls, blob: memoryview | bytes) -> tuple[t.Self, memoryview | bytes]: length = uint32.from_blob(blob[:4]) blob = blob[4:] data, re...
VariableSized
python
getsentry__sentry
src/sentry/types/condition_activity.py
{ "start": 491, "end": 820 }
class ____: group_id: int type: ConditionActivityType timestamp: datetime data: dict[str, Any] = field(default_factory=dict) def round_to_five_minute(time: datetime) -> datetime: return time - timedelta( minutes=time.minute % 5, seconds=time.second, microseconds=time.microsecond )
ConditionActivity
python
django__django
tests/check_framework/test_urls.py
{ "start": 376, "end": 8088 }
class ____(SimpleTestCase): @override_settings(ROOT_URLCONF="check_framework.urls.no_warnings") def test_no_warnings(self): result = check_url_config(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF="check_framework.urls.no_warnings_i18n") def test_no_warnings_i18n(sel...
CheckUrlConfigTests
python
apache__avro
lang/py/avro/protocol.py
{ "start": 1358, "end": 1510 }
class ____(TypedDict, total=False): protocol: str namespace: str types: Sequence[str] messages: Mapping[str, MessageObject]
ProtocolObject
python
pandas-dev__pandas
pandas/errors/__init__.py
{ "start": 31592, "end": 32046 }
class ____(Warning): """ Warning raised by to_stata the column contains a non-valid stata name. Because the column name is an invalid Stata variable, the name needs to be converted. See Also -------- DataFrame.to_stata : Export DataFrame object to Stata dta format. Examples ------...
InvalidColumnName
python
apache__airflow
airflow-core/tests/unit/ti_deps/deps/fake_models.py
{ "start": 1183, "end": 1342 }
class ____: def __init__(self, **kwds): self.__dict__.update(kwds) def get_running_dagruns(self, _): return self.running_dagruns
FakeDag
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/conversational_retrieval/base.py
{ "start": 9672, "end": 18609 }
class ____(BaseConversationalRetrievalChain): r"""Chain for having a conversation based on retrieved documents. This class is deprecated. See below for an example implementation using `create_retrieval_chain`. Additional walkthroughs can be found at https://python.langchain.com/docs/use_cases/question_...
ConversationalRetrievalChain
python
PyCQA__pylint
tests/pyreverse/functional/class_diagrams/relationships_filtering/all.py
{ "start": 148, "end": 228 }
class ____: def __init__(self): self._x = P("protected")
ProtectedAttr
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/metaclass7.py
{ "start": 885, "end": 1080 }
class ____(metaclass=MetaClass3): def __new__(cls, *args, **kwargs): raise RuntimeError("You cannot instantiate BaseFactory") v3 = Class3() reveal_type(v3, expected_text="Any")
Class3
python
tensorflow__tensorflow
tensorflow/python/data/experimental/kernel_tests/service/test_base.py
{ "start": 3114, "end": 5059 }
class ____: """A tf.data service worker.""" def __init__( self, dispatcher_address, shutdown_quiet_period_ms, protocol=PROTOCOL, data_transfer_protocol=None, port=0, worker_tags=None, cross_trainer_cache_size_bytes=None, snapshot_max_chunk_size_bytes=TEST_SNAPS...
TestWorker
python
pytorch__pytorch
torch/jit/_state.py
{ "start": 295, "end": 3803 }
class ____: """Stores whether the JIT is enabled or not. This is just a wrapper for a bool, so that we get reference semantics """ def __init__(self) -> None: self.enabled = self.parse_env( "PYTORCH_JIT", True, "> Using PyTorch JIT", "> PyTorch JIT DISABLED" ) def pars...
EnabledProxy
python
python-openxml__python-docx
src/docx/oxml/simpletypes.py
{ "start": 5496, "end": 5887 }
class ____(BaseIntType): @classmethod def convert_from_xml(cls, str_value: str) -> Length: if "i" in str_value or "m" in str_value or "p" in str_value: return ST_UniversalMeasure.convert_from_xml(str_value) return Emu(int(str_value)) @classmethod def validate(cls, value: Any...
ST_Coordinate
python
keon__algorithms
tests/test_graph.py
{ "start": 11259, "end": 11689 }
class ____(unittest.TestCase): def test_kosaraju_algorithm(self): V = 6 adj = [ [2], [0], [3], [1, 4], [5], [4] ] result = strongly_connected_components_kosaraju.Kosaraju().kosaraju(V, adj) # Expected r...
TestStronglyConnectedComponentsKosaraju
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/scaffold/branch/models.py
{ "start": 1226, "end": 1466 }
class ____: """Record of AI interaction with Claude.""" correlation_id: str timestamp: str prompt: str response: str token_count: Optional[int] allowed_tools: list[str] duration_ms: float @record
AIInteraction
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/organization_data_condition_index.py
{ "start": 1040, "end": 2775 }
class ____(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } owner = ApiOwner.ISSUES @extend_schema( operation_id="Fetch Data Conditions", parameters=[ GlobalParams.ORG_ID_OR_SLUG, ], responses={ 201: inline...
OrganizationDataConditionIndexEndpoint
python
apache__airflow
airflow-core/tests/unit/cli/commands/test_rotate_fernet_key_command.py
{ "start": 1315, "end": 5715 }
class ____: @classmethod def setup_class(cls): cls.parser = cli_parser.get_parser() def setup_method(self) -> None: clear_db_connections(add_default_connections_back=False) clear_db_variables() def teardown_method(self) -> None: clear_db_connections(add_default_connecti...
TestRotateFernetKeyCommand
python
scipy__scipy
scipy/fft/tests/test_helper.py
{ "start": 8863, "end": 14718 }
class ____: def test_py_0d_defaults(self, xp): x = xp.asarray(4) shape = None axes = None shape_expected = () axes_expected = [] shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes) assert shape_res == shape_expected assert axes_res == axe...
Test_init_nd_shape_and_axes
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py
{ "start": 88375, "end": 107907 }
class ____(MMGroundingDinoPreTrainedModel): def __init__(self, config: MMGroundingDinoConfig): super().__init__(config) # Create backbone + positional encoding backbone = MMGroundingDinoConvEncoder(config) position_embeddings = build_position_encoding(config) self.backbone =...
MMGroundingDinoModel
python
ray-project__ray
python/ray/util/collective/types.py
{ "start": 4098, "end": 4222 }
class ____: dst_rank = 0 dst_gpu_index = 0 n_elements = 0 timeout_ms = unset_timeout_ms @dataclass
SendOptions
python
streamlit__streamlit
lib/streamlit/errors.py
{ "start": 1110, "end": 1221 }
class ____(Error): """Exceptions thrown in the custom components code path.""" pass
CustomComponentError
python
ansible__ansible
lib/ansible/cli/galaxy.py
{ "start": 5940, "end": 94348 }
class ____(CLI): """Command to manage Ansible roles and collections. None of the CLI tools are designed to run concurrently with themselves. Use an external scheduler and/or locking to ensure there are no clashing operations. """ name = 'ansible-galaxy' SKIP_INFO_KEYS = ("name", "descri...
GalaxyCLI
python
getsentry__sentry
tests/sentry/integrations/vsts/test_issues.py
{ "start": 6529, "end": 22470 }
class ____(VstsIssueBase): def tearDown(self) -> None: responses.reset() @responses.activate def test_create_issue(self) -> None: responses.add( responses.PATCH, "https://fabrikam-fiber-inc.visualstudio.com/0987654321/_apis/wit/workitems/$Microsoft.VSTS.WorkItemTypes...
VstsIssueSyncTest
python
pydantic__pydantic
pydantic/_internal/_utils.py
{ "start": 13208, "end": 14156 }
class ____: """Wrapper redirecting `__getitem__` to `get` with a sentinel value as default This makes is safe to use in `operator.itemgetter` when some keys may be missing """ # Define __slots__manually for performances # @dataclasses.dataclass() only support slots=True in python>=3.10 __slots...
SafeGetItemProxy
python
yaml__pyyaml
lib/yaml/cyaml.py
{ "start": 692, "end": 891 }
class ____(CParser, FullConstructor, Resolver): def __init__(self, stream): CParser.__init__(self, stream) FullConstructor.__init__(self) Resolver.__init__(self)
CFullLoader
python
pytorch__pytorch
test/test_overrides.py
{ "start": 11854, "end": 12440 }
class ____: """A class that overrides the full torch API This class is used to explicitly test that the full torch.tensor API can be overridden with a class that defines __torch_function__. """ @classmethod def __torch_function__(cls, func, types, args=(), kwargs=None): if kwargs is Non...
TensorLike
python
spack__spack
lib/spack/spack/graph.py
{ "start": 16472, "end": 16863 }
class ____(DotGraphBuilder): """Simple DOT graph, with nodes colored uniformly and edges without properties""" def node_entry(self, node): format_option = "{name}{@version}{/hash:7}{%compiler}" return node.dag_hash(), f'[label="{node.format(format_option)}"]' def edge_entry(self, edge): ...
SimpleDAG
python
joke2k__faker
tests/providers/test_ssn.py
{ "start": 33851, "end": 34820 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("nl_BE") Faker.seed(0) def test_ssn(self): for _ in range(1000): ssn = self.fake.ssn() assert len(ssn) == 11 gen_seq = ssn[6:9] gen_chksum = ssn[9:11] gen_seq_as...
TestNlBE
python
lepture__authlib
authlib/jose/errors.py
{ "start": 1367, "end": 1654 }
class ____(JoseError): error = "invalid_algorithm_for_multiple_recipients_mode" def __init__(self, alg): description = f"{alg} algorithm cannot be used in multiple recipients mode" super().__init__(description=description)
InvalidAlgorithmForMultipleRecipientsMode
python
pytorch__pytorch
test/dynamo/test_global.py
{ "start": 700, "end": 7291 }
class ____(torch._dynamo.test_case.TestCase): def test_store_global_1(self): def fn(x): global g_counter val = x + g_counter g_counter += 1 return val x = torch.randn(10) cnts = torch._dynamo.testing.CompileCounter() opt_fn = torch.com...
TestGlobals
python
aio-libs__aiohttp
aiohttp/client_reqrep.py
{ "start": 30774, "end": 31433 }
class ____(TypedDict, total=False): params: Query headers: CIMultiDict[str] skip_auto_headers: Iterable[str] | None data: Any cookies: BaseCookie[str] auth: BasicAuth | None version: HttpVersion compress: str | bool chunked: bool | None expect100: bool loop: asyncio.AbstractE...
ClientRequestArgs
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 6617, "end": 6792 }
class ____(PollParentWithManyToMany): books = models.ManyToManyField("Book", related_name="books_poll_child") _history_m2m_fields = ["books"]
PollChildBookWithManyToMany
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_cond_format12.py
{ "start": 315, "end": 1344 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("cond_format12.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with conditional formatting.""" ...
TestCompareXLSXFiles
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/long_access_path_taint.py
{ "start": 280, "end": 1031 }
class ____: def __init__( self, id: int, params: Dict[str, Any], kind: str, request: str ) -> None: self.id = id self.timestamp = params.get("timestamp") or 0 self.app_id = params.get("app_id") self.kind = kind self.request = request @classmethod async de...
C
python
PyCQA__pylint
tests/functional/a/arguments_differ.py
{ "start": 3282, "end": 3487 }
class ____(Positional): def test(self, *args): """ Acceptable use of vararg in subclass because it does not violate LSP. """ super().test(args[0], args[1])
PositionalChild
python
kamyu104__LeetCode-Solutions
Python/nth-digit.py
{ "start": 32, "end": 489 }
class ____(object): def findNthDigit(self, n): """ :type n: int :rtype: int """ digit_len = 1 while n > digit_len * 9 * (10 ** (digit_len-1)): n -= digit_len * 9 * (10 ** (digit_len-1)) digit_len += 1 num = 10 ** (digit_len-1) + (n-1)...
Solution
python
python-pillow__Pillow
src/PIL/IcnsImagePlugin.py
{ "start": 4621, "end": 7902 }
class ____: SIZES = { (512, 512, 2): [(b"ic10", read_png_or_jpeg2000)], (512, 512, 1): [(b"ic09", read_png_or_jpeg2000)], (256, 256, 2): [(b"ic14", read_png_or_jpeg2000)], (256, 256, 1): [(b"ic08", read_png_or_jpeg2000)], (128, 128, 2): [(b"ic13", read_png_or_jpeg2000)], ...
IcnsFile
python
pytorch__pytorch
benchmarks/inductor_backends/cutlass.py
{ "start": 2374, "end": 2921 }
class ____(ExperimentConfig): cutlass_instantiation_level: str def name(self) -> str: level_name = ( self.cutlass_instantiation_level if self.cutlass_instantiation_level != "0" else "default" ) return f"cutlass_lvl_{level_name}" def to_options(se...
CutlassExperimentConfig
python
python-poetry__poetry
tests/types.py
{ "start": 3215, "end": 3327 }
class ____(Protocol): def __call__(self, content: str, base_url: str | None = None) -> str: ...
HTMLPageGetter
python
sympy__sympy
sympy/physics/quantum/spin.py
{ "start": 41242, "end": 48954 }
class ____(SpinState): """Base class for coupled angular momentum states.""" def __new__(cls, j, m, jn, *jcoupling): # Check j and m values using SpinState SpinState(j, m) # Build and check coupling scheme from arguments if len(jcoupling) == 0: # Use default coupling...
CoupledSpinState