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
langchain-ai__langchain
libs/core/langchain_core/language_models/fake.py
{ "start": 2137, "end": 3732 }
class ____(FakeListLLM): """Fake streaming list LLM for testing purposes. An LLM that will return responses from a list in order. This model also supports optionally sleeping between successive chunks in a streaming implementation. """ error_on_chunk_number: int | None = None """If set, w...
FakeStreamingListLLM
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_trace_meta.py
{ "start": 319, "end": 5071 }
class ____(OrganizationEventsTraceEndpointBase): url_name = "sentry-api-0-organization-trace-meta" def client_get(self, data, url=None): if url is None: url = self.url return self.client.get( url, data, format="json", ) def test_no_pr...
OrganizationEventsTraceMetaEndpointTest
python
mlflow__mlflow
tests/sagemaker/mock/__init__.py
{ "start": 28394, "end": 30326 }
class ____(TimestampedResource): """ Object representing a SageMaker transform job. The SageMakerBackend will create and manage transform jobs. """ STATUS_IN_PROGRESS = "InProgress" STATUS_FAILED = "Failed" STATUS_COMPLETED = "Completed" STATUS_STOPPING = "Stopping" STATUS_STOPPED =...
TransformJob
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/linear_operator_block_lower_triangular_test.py
{ "start": 2202, "end": 14071 }
class ____( linear_operator_test_util.SquareLinearOperatorDerivedClassTest): """Most tests done in the base class LinearOperatorDerivedClassTest.""" def tearDown(self): config.enable_tensor_float_32_execution(self.tf32_keep_) def setUp(self): self.tf32_keep_ = config.tensor_float_32_execution_enable...
SquareLinearOperatorBlockLowerTriangularTest
python
PrefectHQ__prefect
src/prefect/utilities/schema_tools/hydration.py
{ "start": 3151, "end": 3354 }
class ____(HydrationError): @property def message(self) -> str: message = "Invalid JSON" if self.detail: message += f": {self.detail}" return message
InvalidJSON
python
dask__dask
dask/array/_array_expr/random.py
{ "start": 36204, "end": 37059 }
class ____(IO): _parameters = [ "array", "chunks", "_meta", "_state", "replace", "p", "axis", "shuffle", ] _defaults = {"axis": None, "shuffle": None} _funcname = "da.random.choice-" @cached_property def chunks(self): retur...
RandomChoice
python
sympy__sympy
doc/ext/docscrape.py
{ "start": 13120, "end": 14716 }
class ____(NumpyDocString): def __init__(self, func, role='func', doc=None, config={}): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: if func is None: raise ValueError("No function or docstring given") doc = inspect.getdoc(...
FunctionDoc
python
pytorch__pytorch
torch/_dynamo/source.py
{ "start": 33329, "end": 33523 }
class ____(Source): def name(self) -> str: return "" def guard_source(self) -> GuardSource: return GuardSource.GLOBAL @dataclasses.dataclass(frozen=True)
GlobalStateSource
python
viewflow__viewflow
tests/workflow/test_nodes__join.py
{ "start": 141, "end": 1138 }
class ____(TestCase): # noqa: D101 def test_join_async(self): process = TestASyncWorkflow.start.run() first_task = process.task_set.filter(flow_task=TestASyncWorkflow.first).first() second_task = process.task_set.filter(flow_task=TestASyncWorkflow.second).first() TestASyncWorkflow...
Test
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/unique_fragment_names.py
{ "start": 69, "end": 1002 }
class ____(ValidationRule): __slots__ = 'known_fragment_names', def __init__(self, context): super(UniqueFragmentNames, self).__init__(context) self.known_fragment_names = {} def enter_OperationDefinition(self, node, key, parent, path, ancestors): return False def enter_Fragme...
UniqueFragmentNames
python
ansible__ansible
lib/ansible/module_utils/facts/network/netbsd.py
{ "start": 845, "end": 1643 }
class ____(GenericBsdIfconfigNetwork): """ This is the NetBSD Network Class. It uses the GenericBsdIfconfigNetwork """ platform = 'NetBSD' def parse_media_line(self, words, current_if, ips): # example of line: # $ ifconfig # ne0: flags=8863<UP,BROADCAST,NOTRAILERS,RUNNIN...
NetBSDNetwork
python
great-expectations__great_expectations
great_expectations/datasource/fluent/interfaces.py
{ "start": 9952, "end": 23620 }
class ____(GenericBaseModel, ABC, Generic[DatasourceT, PartitionerT]): """ A Data Asset is a collection of records within a Data Source, which is usually named based on the underlying data system and sliced to correspond to a desired specification. Data Assets are used to specify how Great Expectations...
DataAsset
python
anthropics__anthropic-sdk-python
src/anthropic/types/tool_use_block.py
{ "start": 212, "end": 331 }
class ____(BaseModel): id: str input: Dict[str, object] name: str type: Literal["tool_use"]
ToolUseBlock
python
huggingface__transformers
src/transformers/models/efficientloftr/image_processing_efficientloftr.py
{ "start": 5140, "end": 21626 }
class ____(BaseImageProcessor): r""" Constructs a EfficientLoFTR image processor. Args: do_resize (`bool`, *optional*, defaults to `True`): Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by `do_resize` in the `pre...
EfficientLoFTRImageProcessor
python
huggingface__transformers
src/transformers/pipelines/document_question_answering.py
{ "start": 3743, "end": 25202 }
class ____(ChunkPipeline): # TODO: Update task_summary docs to include an example with document QA and then update the first sentence """ Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`. The inputs/outputs are similar to the (extractive) question answering pipeline...
DocumentQuestionAnsweringPipeline
python
davidhalter__parso
parso/python/tree.py
{ "start": 3259, "end": 3889 }
class ____: """ Some Python specific utilities. """ __slots__ = () def get_name_of_position(self, position): """ Given a (line, column) tuple, returns a :py:class:`Name` or ``None`` if there is no name at that position. """ for c in self.children: ...
PythonMixin
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 25146, "end": 26099 }
class ____(Operation): def call(self, x): return backend.numpy.arcsinh(x) def compute_output_spec(self, x): dtype = backend.standardize_dtype(getattr(x, "dtype", backend.floatx())) if dtype == "int64": dtype = backend.floatx() else: dtype = dtypes.result_...
Arcsinh
python
pytorch__pytorch
torch/_inductor/distributed_autotune.py
{ "start": 820, "end": 1240 }
class ____: """ State used to track autotuning during a graph_context() """ # This is the next operator index. Used to figure out which rank should do # the autotuning. autotuned_index: int = 0 # For debugging - used to make sure that we autotune the same number of # local operators th...
_DistributedAutotuneState
python
wandb__wandb
wandb/sdk/lib/service/service_token.py
{ "start": 3673, "end": 5107 }
class ____(ServiceToken): """Connects to the service using TCP over a localhost socket.""" def __init__(self, *, parent_pid: int, port: int) -> None: self._parent_pid = parent_pid self._port = port @override def connect( self, *, asyncer: asyncio_manager.Asyncio...
TCPServiceToken
python
pytorch__pytorch
torchgen/api/python.py
{ "start": 23440, "end": 23851 }
class ____: name: str type_str: str is_out_arg: bool # To pass PyObjects arguments to C++ function (via the lambda wrapper), # we need first convert PyObjects into simple C++ objects. This work # is done by PythonArgParser. # This data model is used to represent the output of PythonArgParser. # It has 1-1...
DispatchLambdaArgument
python
pypa__pipenv
pipenv/patched/pip/_vendor/distlib/database.py
{ "start": 18563, "end": 32115 }
class ____(BaseInstalledDistribution): """ Created with the *path* of the ``.dist-info`` directory provided to the constructor. It reads the metadata contained in ``pydist.json`` when it is instantiated., or uses a passed in Metadata instance (useful for when dry-run mode is being used). """ ...
InstalledDistribution
python
getsentry__sentry
src/sentry/search/events/fields.py
{ "start": 34764, "end": 35470 }
class ____(FunctionArg): def __init__(self, name: str): super().__init__(name) def normalize(self, value: str, params: ParamsType, combinator: Combinator | None) -> datetime: if not params or not params.get("start") or not params.get("end"): raise InvalidFunctionArgument("function c...
TimestampArg
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/supers.py
{ "start": 228, "end": 523 }
class ____: def __init__(self): self.attribute = _test_source() def f1(self): _test_sink(self.attribute) def f2(self, x): _test_sink(x) def f3(self): return _test_source() def f4(self): return "1" def f5(self, x): pass
A
python
FactoryBoy__factory_boy
factory/django.py
{ "start": 6786, "end": 6965 }
class ____(declarations.Transformer): def __init__(self, password, transform=make_password, **kwargs): super().__init__(password, transform=transform, **kwargs)
Password
python
pytest-dev__pytest-asyncio
docs/reference/markers/class_scoped_loop_with_fixture_strict_mode_example.py
{ "start": 96, "end": 440 }
class ____: loop: asyncio.AbstractEventLoop @pytest_asyncio.fixture(loop_scope="class") async def my_fixture(self): TestClassScopedLoop.loop = asyncio.get_running_loop() async def test_runs_is_same_loop_as_fixture(self, my_fixture): assert asyncio.get_running_loop() is TestClassScopedL...
TestClassScopedLoop
python
milvus-io__pymilvus
pymilvus/client/types.py
{ "start": 38153, "end": 39095 }
class ____: """ Represents the information of a database. Atributes: name (str): The name of the database. properties (dict): The properties of the database. Example: DatabaseInfo(name="test_db", id=1, properties={"key": "value"}) """ @property def name(self) -> str:...
DatabaseInfo
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_table_column_count_to_be_between.py
{ "start": 2252, "end": 13634 }
class ____(BatchExpectation): __doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION} ExpectTableColumnCountToBeBetween is a \ Batch Expectation. BatchExpectations are one of the most common types of Expectation. They are evaluated for an entire Batch, and answer a semantic question about the Batch itself. ...
ExpectTableColumnCountToBeBetween
python
jina-ai__jina
jina/logging/formatter.py
{ "start": 673, "end": 1558 }
class ____(Formatter): """Format the log message as a JSON object so that it can be later used/parsed in browser with javascript.""" KEYS = { 'created', 'filename', 'funcName', 'levelname', 'lineno', 'msg', 'module', 'name', 'pathname', ...
JsonFormatter
python
pytorch__pytorch
torch/_dynamo/variables/ctx_manager.py
{ "start": 33937, "end": 36384 }
class ____(ContextWrappingVariable): @staticmethod def create( func: torch.amp.autocast_mode.autocast, args: Sequence[Any], kwargs: dict[str, Any], ) -> "AutocastModeVariable": assert func in [ torch.amp.autocast_mode.autocast, torch.cuda.amp.autocast,...
AutocastModeVariable
python
dagster-io__dagster
python_modules/libraries/dagster-dbt/dagster_dbt_tests/cloud_v2/test_asset_decorator.py
{ "start": 1463, "end": 2270 }
class ____(DagsterDbtTranslator): # DagsterDbtTranslator doesn't have a `get_asset_spec` method yet. def get_metadata(self, dbt_resource_props: Mapping[str, Any]) -> Mapping[str, Any]: default_metadata = super().get_metadata(dbt_resource_props) return {**default_metadata, "custom": "metadata"} ...
MyCustomTranslator
python
ansible__ansible
lib/ansible/galaxy/collection/gpg.py
{ "start": 5460, "end": 5812 }
class ____(GpgBaseError): """No data has been found. Codes for WHAT are: - 1 :: No armored data. - 2 :: Expected a packet but did not find one. - 3 :: Invalid packet found, this may indicate a non OpenPGP message. - 4 :: Signature expected but not found. """ what: str @dataclas...
GpgNoData
python
HypothesisWorks__hypothesis
hypothesis-python/tests/nocover/test_drypython_returns.py
{ "start": 891, "end": 954 }
class ____(Generic[_InstanceType, _TypeArgType1]): pass
KindN
python
huggingface__transformers
src/transformers/models/roberta/tokenization_roberta.py
{ "start": 1059, "end": 7805 }
class ____(TokenizersBackend): r""" Construct a RoBERTa tokenizer (backed by HuggingFace's tokenizers library). Based on Byte-Pair-Encoding. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will be encoded differently whether it is at the beg...
RobertaTokenizer
python
pytorch__pytorch
test/test_sympy_utils.py
{ "start": 33503, "end": 34464 }
class ____(TestCase): def test_expand_identity(self): """ Test removing an identity via expansion. """ x = sympy.Symbol("x") arg = x + sympy.S.One expr = Identity(arg) expanded = expr.expand(identity=True) self.assertEqual(expanded.count(Identity), 0) ...
TestIdentity
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol9.py
{ "start": 686, "end": 751 }
class ____(Protocol): def method1(self) -> "ProtoA": ...
ProtoA
python
PrefectHQ__prefect
tests/runner/test_runner.py
{ "start": 7097, "end": 8777 }
class ____: async def test_runner_respects_limit_setting(self): runner = Runner() assert runner.limit == PREFECT_RUNNER_PROCESS_LIMIT.value() runner = Runner(limit=50) assert runner.limit == 50 with temporary_settings({PREFECT_RUNNER_PROCESS_LIMIT: 100}): runner...
TestInit
python
scipy__scipy
scipy/signal/tests/test_fir_filter_design.py
{ "start": 5332, "end": 13058 }
class ____: """Different author, different style, different tests...""" def test_lowpass(self, xp): width = 0.04 ntaps, beta = kaiserord(120, width) cutoff = xp.asarray(0.5) kwargs = dict(cutoff=cutoff, window=('kaiser', beta), scale=False) taps = firwin(ntaps, **kwargs)...
TestFirWinMore
python
ray-project__ray
python/ray/data/_internal/logical/operators/from_operators.py
{ "start": 501, "end": 2656 }
class ____(LogicalOperator, SourceOperator, metaclass=abc.ABCMeta): """Abstract logical operator for `from_*`.""" def __init__( self, input_blocks: List[ObjectRef[Block]], input_metadata: List[BlockMetadataWithSchema], ): super().__init__( name=self.__class__.__n...
AbstractFrom
python
getsentry__sentry
src/sentry/projectoptions/manager.py
{ "start": 956, "end": 2822 }
class ____: """Project options used to be implemented in a relatively ad-hoc manner in the past. The project manager still uses the functionality of the project model and just dispatches to it. Options can be used without declaring defaults, but if defaults are declared they are returned without h...
ProjectOptionsManager
python
TheAlgorithms__Python
data_structures/binary_tree/binary_tree_path_sum.py
{ "start": 250, "end": 504 }
class ____: """ A Node has value variable and pointers to Nodes to its left and right. """ def __init__(self, value: int) -> None: self.value = value self.left: Node | None = None self.right: Node | None = None
Node
python
pydata__xarray
xarray/util/deprecation_helpers.py
{ "start": 5538, "end": 7982 }
class ____: """Object that handles deprecation cycle for kwarg default values. Similar to ReprObject """ _old: str _new: str | None _name: str def __init__(self, *, name: str, old: str, new: str | None): self._name = name self._old = old self._new = new def __...
CombineKwargDefault
python
agronholm__apscheduler
tests/test_marshalling.py
{ "start": 569, "end": 619 }
class ____(DummyClass): pass
InheritedDummyClass
python
optuna__optuna
optuna/samplers/_lazy_random_state.py
{ "start": 57, "end": 729 }
class ____: """Lazy Random State class. This is a class to initialize the random state just before use to prevent duplication of the same random state when deepcopy is applied to the instance of sampler. """ def __init__(self, seed: int | None = None) -> None: self._rng: np.random.RandomS...
LazyRandomState
python
viewflow__viewflow
viewflow/workflow/flow/views/list.py
{ "start": 4901, "end": 5547 }
class ____(WorkflowTaskListView): """List of current user assigned tasks from all viewset registered flows.""" columns = ("task_id", "flow_task", "brief", "process_brief", "created") bulk_actions = ( Action(name=_("Unassign selected tasks"), viewname="tasks_unassign"), ) title = _("Inbox") ...
WorkflowInboxListView
python
plotly__plotly.py
plotly/graph_objs/scatterpolargl/marker/colorbar/_tickfont.py
{ "start": 233, "end": 9989 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "scatterpolargl.marker.colorbar" _path_str = "scatterpolargl.marker.colorbar.tickfont" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant",...
Tickfont
python
h5py__h5py
h5py/_hl/base.py
{ "start": 8297, "end": 11537 }
class ____(CommonStateObject): """ Base class for high-level interface objects. """ @property def file(self): """ Return a File instance associated with this object """ from . import files with phil: return files.File(self.id) @property @with_phil ...
HLObject
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 13476, "end": 13819 }
class ____(VegaLiteSchema): """ Root schema wrapper. A Vega-Lite top-level specification. This is the root class for all Vega-Lite specifications. (The json schema is generated from this type.) """ _schema = VegaLiteSchema._rootschema def __init__(self, *args, **kwds): super().__i...
Root
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/property_with_parameters.py
{ "start": 730, "end": 1063 }
class ____: @property def attribute_var_args(self, *args): # [property-with-parameters] return sum(args) @property def attribute_var_kwargs(self, **kwargs): #[property-with-parameters] return {key: value * 2 for key, value in kwargs.items()} from functools import cached_property
VariadicParameters
python
ApeWorX__ape
src/ape/contracts/base.py
{ "start": 64359, "end": 66380 }
class ____: """ A class that bridges contract containers in a namespace. For example, if you have an interface structure like this:: contracts: accounts: - interface.json mocks: - interface.json You can interact with them like this:: account...
ContractNamespace
python
pandas-dev__pandas
pandas/tests/indexes/timedeltas/methods/test_astype.py
{ "start": 262, "end": 6331 }
class ____: def test_astype_object(self): idx = timedelta_range(start="1 days", periods=4, freq="D", name="idx") expected_list = [ Timedelta("1 days"), Timedelta("2 days"), Timedelta("3 days"), Timedelta("4 days"), ] result = idx.astype...
TestTimedeltaIndex
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-qianfan/llama_index/llms/qianfan/base.py
{ "start": 3942, "end": 15360 }
class ____(CustomLLM): """ The LLM supported by Baidu Intelligent Cloud's QIANFAN LLM Platform. """ access_key: str = Field( description="The Access Key obtained from the Security Authentication Center of Baidu Intelligent Cloud Console." ) secret_key: str = Field(description="The Secr...
Qianfan
python
spack__spack
lib/spack/spack/package_base.py
{ "start": 19929, "end": 95350 }
class ____(WindowsRPath, PackageViewMixin, metaclass=PackageMeta): """This is the universal base class for all Spack packages. At its core, a package consists of a set of software to be installed. A package may focus on a piece of software and its associated software dependencies or it may simply be a set,...
PackageBase
python
h5py__h5py
h5py/tests/test_dataset.py
{ "start": 29753, "end": 30153 }
class ____(BaseDataset): """ Feature: Datasets created with LZF compression """ def test_szip(self): """ Create with explicit szip """ dset = self.f.create_dataset(make_name(), (20, 30), compression='szip', compression_opts=('ec', 16)) @ut.ski...
TestCreateSZIP
python
facelessuser__pymdown-extensions
pymdownx/details.py
{ "start": 6341, "end": 6728 }
class ____(Extension): """Add Details extension.""" def extendMarkdown(self, md): """Add Details to Markdown instance.""" md.registerExtension(self) md.parser.blockprocessors.register(DetailsProcessor(md.parser), "details", 105) def makeExtension(*args, **kwargs): """Return exten...
DetailsExtension
python
huggingface__transformers
src/transformers/models/granite_speech/feature_extraction_granite_speech.py
{ "start": 1145, "end": 7395 }
class ____(FeatureExtractionMixin): model_input_names = ["input_features"] def __init__( self, sampling_rate: int = 16000, n_fft: int = 512, win_length: int = 400, hop_length: int = 160, n_mels: int = 80, projector_window_size: int = 15, projector...
GraniteSpeechFeatureExtractor
python
PrefectHQ__prefect
tests/server/orchestration/test_rules.py
{ "start": 69639, "end": 81362 }
class ____: @pytest.mark.parametrize( "intended_transition", list(product([*states.StateType], [*states.StateType])), ids=transition_names, ) async def test_null_rejects_fizzle_all_prior_rules( self, session, initialize_orchestration, intended_transition, run_type ): ...
TestNullRejection
python
python-attrs__attrs
src/attr/validators.py
{ "start": 4993, "end": 6057 }
class ____: validator = attrib() def __call__(self, inst, attr, value): if value is None: return self.validator(inst, attr, value) def __repr__(self): return f"<optional validator for {self.validator!r} or None>" def optional(validator): """ A validator that ...
_OptionalValidator
python
huggingface__transformers
src/transformers/models/levit/modeling_levit.py
{ "start": 18150, "end": 18387 }
class ____(PreTrainedModel): config: LevitConfig base_model_prefix = "levit" main_input_name = "pixel_values" input_modalities = ("image",) _no_split_modules = ["LevitResidualLayer"] @auto_docstring
LevitPreTrainedModel
python
pytorch__pytorch
torch/distributed/elastic/multiprocessing/errors/error_handler.py
{ "start": 451, "end": 6675 }
class ____: """ Write the provided exception object along with some other metadata about the error in a structured way in JSON format to an error file specified by the environment variable: ``TORCHELASTIC_ERROR_FILE``. If this environment variable is not set, then simply logs the contents of what wo...
ErrorHandler
python
getsentry__sentry
src/sentry/release_health/metrics_sessions_v2.py
{ "start": 3321, "end": 3657 }
class ____(TypedDict): series: dict[SessionsQueryFunction, list[SessionsQueryValue]] totals: dict[SessionsQueryFunction, SessionsQueryValue] def default_for(field: SessionsQueryFunction) -> SessionsQueryValue: return 0 if field in ("sum(session)", "count_unique(user)") else None GroupedData = Mapping[Gr...
Group
python
pydata__xarray
xarray/tests/test_backends.py
{ "start": 99576, "end": 100831 }
class ____: engine: T_NetcdfEngine | None def test_roundtrip_via_memoryview(self) -> None: original = create_test_data() result = original.to_netcdf(engine=self.engine) roundtrip = load_dataset(result, engine=self.engine) assert_identical(roundtrip, original) def test_round...
InMemoryNetCDF
python
coleifer__peewee
tests/regressions.py
{ "start": 25475, "end": 26961 }
class ____(ModelTestCase): requires = [Product, Sku] def test_fk_composite_pk_regression(self): Product.insert_many([ (1, 'red'), (1, 'blue'), (2, 'red'), (2, 'green'), (3, 'white')]).execute() Sku.insert_many([ ('1-red', 1...
TestFKCompositePK
python
Lightning-AI__lightning
src/lightning/pytorch/utilities/exceptions.py
{ "start": 1179, "end": 1511 }
class ____(Exception): """Exception used to exit early while tuning.""" def _augment_message(exception: BaseException, pattern: str, new_message: str) -> None: exception.args = tuple( new_message if isinstance(arg, str) and re.match(pattern, arg, re.DOTALL) else arg for arg in exception.args )
_TunerExitException
python
python-attrs__attrs
tests/test_dunders.py
{ "start": 9268, "end": 12574 }
class ____: """ Tests for `_add_repr`. """ def test_repr(self, slots): """ If `repr` is False, ignore that attribute. """ C = make_class( "C", {"a": attr.ib(repr=False), "b": attr.ib()}, slots=slots ) assert "C(b=2)" == repr(C(1, 2)) @py...
TestAddRepr
python
aio-libs__aiohttp
aiohttp/client_reqrep.py
{ "start": 2418, "end": 2536 }
class ____(NamedTuple): url: URL method: str headers: "CIMultiDictProxy[str]" real_url: URL
_RequestInfo
python
getsentry__sentry
src/sentry/workflow_engine/handlers/detector/base.py
{ "start": 1237, "end": 2643 }
class ____: issue_title: str subtitle: str evidence_data: Mapping[str, Any] = dataclasses.field(default_factory=dict) evidence_display: Sequence[IssueEvidence] = dataclasses.field(default_factory=list) type: type[GroupType] level: str culprit: str resource_id: str | None = None assig...
DetectorOccurrence
python
huggingface__transformers
src/transformers/models/video_llama_3/modular_video_llama_3.py
{ "start": 8186, "end": 9598 }
class ____(VisionRotaryEmbedding): def forward(self, grid_thw, merge_sizes) -> tuple[torch.Tensor, torch.Tensor]: pos_ids = [] for (t, h, w), merge_size in zip(grid_thw, merge_sizes): hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w) hpos_ids = hpos_ids.reshape( ...
VideoLlama3VisionRotaryEmbedding
python
huggingface__transformers
src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py
{ "start": 6836, "end": 44438 }
class ____(TokenizersBackend): r""" Construct a "fast" LayoutLMv2 tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece. This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to this superclass for more information re...
LayoutLMv2Tokenizer
python
bokeh__bokeh
src/bokeh/models/widgets/inputs.py
{ "start": 2503, "end": 3258 }
class ____(Widget): ''' Abstract base class for input widgets. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) title = Either(String, Instance(HTML), default="", help=""" Widget's label. ""...
InputWidget
python
realpython__materials
tic-tac-toe-ai-python/source_code_final/tic-tac-toe/frontends/console/players.py
{ "start": 163, "end": 1005 }
class ____(Player): def get_move(self, game_state: GameState) -> Move | None: while not game_state.game_over: try: index = grid_to_index(input(f"{self.mark}'s move: ").strip()) except ValueError: print("Please provide coordinates in the form of A1 or 1...
ConsolePlayer
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 231331, "end": 240649 }
class ____(ThreadedTCPSocketTest): """ Test the send() implementation of socket.sendfile(). """ FILESIZE = (10 * 1024 * 1024) # 10 MiB BUFSIZE = 8192 FILEDATA = b"" TIMEOUT = support.LOOPBACK_TIMEOUT @classmethod def setUpClass(cls): def chunks(total, step): as...
SendfileUsingSendTest
python
pallets__jinja
src/jinja2/filters.py
{ "start": 34797, "end": 54599 }
class ____(t.NamedTuple): grouper: t.Any list: list[t.Any] # Use the regular tuple repr to hide this subclass if users print # out the value during debugging. def __repr__(self) -> str: return tuple.__repr__(self) def __str__(self) -> str: return tuple.__str__(self) @pass_env...
_GroupTuple
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dataplex.py
{ "start": 4787, "end": 6047 }
class ____: @mock.patch(HOOK_STR) @mock.patch(TASK_STR) def test_execute(self, task_mock, hook_mock): op = DataplexCreateTaskOperator( task_id="create_dataplex_task", project_id=PROJECT_ID, region=REGION, lake_id=LAKE_ID, body=BODY, ...
TestDataplexCreateTaskOperator
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/kinesis_analytics.py
{ "start": 1554, "end": 5199 }
class ____(AwsBaseOperator[KinesisAnalyticsV2Hook]): """ Creates an AWS Managed Service for Apache Flink application. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:KinesisAnalyticsV2CreateApplicationOperator` :param applic...
KinesisAnalyticsV2CreateApplicationOperator
python
pypa__warehouse
tests/unit/admin/views/test_organizations.py
{ "start": 28848, "end": 33822 }
class ____: def test_update_role(self, db_request, monkeypatch): organization = OrganizationFactory.create(name="pypi") user = UserFactory.create(username="testuser") role = OrganizationRoleFactory.create( organization=organization, user=user, role_name=OrganizationRoleType.Membe...
TestUpdateOrganizationRole
python
doocs__leetcode
solution/1800-1899/1845.Seat Reservation Manager/Solution.py
{ "start": 0, "end": 386 }
class ____: def __init__(self, n: int): self.q = list(range(1, n + 1)) def reserve(self) -> int: return heappop(self.q) def unreserve(self, seatNumber: int) -> None: heappush(self.q, seatNumber) # Your SeatManager object will be instantiated and called as such: # obj = SeatManage...
SeatManager
python
django__django
tests/delete_regress/models.py
{ "start": 397, "end": 527 }
class ____(models.Model): award = models.ForeignKey(Award, models.CASCADE) note = models.CharField(max_length=100)
AwardNote
python
PyCQA__pylint
tests/functional/s/slots_checks.py
{ "start": 814, "end": 963 }
class ____: """Multiple __slots__ declared in the class""" x = 1 if x: __slots__: str else: __slots__ = ("y",)
EigthGood
python
pytorch__pytorch
test/dynamo/cpython/3_13/typinganndata/ann_module8.py
{ "start": 67, "end": 177 }
class ____: class Inner: x: int def NoTypeCheck_function(arg: int) -> int: ...
NoTypeCheck_Outer
python
PrefectHQ__prefect
src/prefect/futures.py
{ "start": 953, "end": 4632 }
class ____(abc.ABC, Generic[R]): """ Abstract base class for Prefect futures. A Prefect future is a handle to the asynchronous execution of a run. It provides methods to wait for the to complete and to retrieve the result of the run. """ def __init__(self, task_run_id: uuid.UUID): warni...
PrefectFuture
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modular_mm_grounding_dino.py
{ "start": 14384, "end": 15215 }
class ____(GroundingDinoContrastiveEmbedding): def __init__(self, config): super().__init__(config) self.bias = nn.Parameter(torch.tensor(0.0)) def forward( self, vision_hidden_state: torch.FloatTensor, text_hidden_state: torch.FloatTensor, text_token_mask: torch...
MMGroundingDinoContrastiveEmbedding
python
tensorflow__tensorflow
tensorflow/lite/tools/convert_image_to_csv_test.py
{ "start": 1108, "end": 3384 }
class ____(test_util.TensorFlowTestCase): def testGetImageRaisesMissingFile(self): image_path = os.path.join(PREFIX_PATH, "jpeg", "testdata", "no_such.jpg") with self.assertRaises(NotFoundError): _ = convert_image_to_csv.get_image(64, 96, False, image_path) def testGetImageSizeIsCorrect(self): i...
ConvertImageToCsvTest
python
FactoryBoy__factory_boy
tests/test_faker.py
{ "start": 599, "end": 5836 }
class ____(unittest.TestCase): def setUp(self): self._real_fakers = factory.Faker._FAKER_REGISTRY factory.Faker._FAKER_REGISTRY = {} def tearDown(self): factory.Faker._FAKER_REGISTRY = self._real_fakers def _setup_mock_faker(self, locale=None, **definitions): if locale is N...
FakerTests
python
redis__redis-py
redis/commands/bf/commands.py
{ "start": 13405, "end": 18862 }
class ____: def create(self, key, compression=100): """ Allocate the memory and initialize the t-digest. For more information see `TDIGEST.CREATE <https://redis.io/commands/tdigest.create>`_. """ # noqa return self.execute_command(TDIGEST_CREATE, key, "COMPRESSION", compress...
TDigestCommands
python
PyCQA__pylint
tests/functional/b/bad_staticmethod_argument.py
{ "start": 64, "end": 321 }
class ____: def method1(self): # [bad-staticmethod-argument] pass method1 = staticmethod(method1) def method2(cls): # [bad-staticmethod-argument] pass method2 = staticmethod(method2) def __init__(self): pass
Abcd
python
walkccc__LeetCode
solutions/1734. Decode XORed Permutation/1734.py
{ "start": 0, "end": 955 }
class ____: def decode(self, encoded: list[int]) -> list[int]: # Our goal is to find the value of a1, which will allow us to decode a2, a3, # ..., an. This can be achieved by performing XOR operation between each # element in `encoded` and a1. # # e.g. n = 3, perm = [a1, a2, a3] is a permutation o...
Solution
python
celery__celery
celery/app/utils.py
{ "start": 8914, "end": 13171 }
class ____: """Old application pickler/unpickler (< 3.1).""" def __call__(self, cls, *args): kwargs = self.build_kwargs(*args) app = self.construct(cls, **kwargs) self.prepare(app, **kwargs) return app def prepare(self, app, **kwargs): app.conf.update(kwargs['change...
AppPickler
python
huggingface__transformers
src/transformers/models/efficientloftr/modular_efficientloftr.py
{ "start": 232, "end": 3295 }
class ____(SuperGlueImageProcessorFast): def post_process_keypoint_matching( self, outputs: "EfficientLoFTRKeypointMatchingOutput", target_sizes: Union[TensorType, list[tuple]], threshold: float = 0.0, ) -> list[dict[str, torch.Tensor]]: """ Converts the raw outpu...
EfficientLoFTRImageProcessorFast
python
walkccc__LeetCode
solutions/2092. Find All People With Secret/2092.py
{ "start": 0, "end": 681 }
class ____: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self._find(u) j = self._find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: se...
UnionFind
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 128881, "end": 131792 }
class ____(torch.nn.Module): """An implementation of the speaker embedding model in a paper. "ECAPA-TDNN: Emphasized Channel Attention, Propagation and Aggregation in TDNN Based Speaker Verification" (https://huggingface.co/papers/2005.07143). """ def __init__(self, config: Qwen2_5OmniDiTConfig): ...
ECAPA_TimeDelayNet
python
django__django
django/template/library.py
{ "start": 10068, "end": 10678 }
class ____(TagHelperNode): child_nodelists = () def __init__(self, func, takes_context, args, kwargs, target_var): super().__init__(func, takes_context, args, kwargs) self.target_var = target_var def render(self, context): resolved_args, resolved_kwargs = self.get_resolved_argument...
SimpleNode
python
openai__openai-python
src/openai/types/chat/completion_create_params.py
{ "start": 15887, "end": 16186 }
class ____(TypedDict, total=False): approximate: Required[WebSearchOptionsUserLocationApproximate] """Approximate location parameters for the search.""" type: Required[Literal["approximate"]] """The type of location approximation. Always `approximate`."""
WebSearchOptionsUserLocation
python
walkccc__LeetCode
solutions/2927. Distribute Candies Among Children III/2927.py
{ "start": 0, "end": 803 }
class ____: def distributeCandies(self, n: int, limit: int) -> int: def ways(n: int) -> int: """Returns the number of ways to distribute n candies to 3 children.""" if n < 0: return 0 # Stars and bars method: # e.g. '**|**|*' means to distribute 5 candies to 3 children, where ...
Solution
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/utils/bricks.py
{ "start": 2900, "end": 7542 }
class ____(queue.Queue): """Thread-safe implementation of an ordered set queue. Disallows adding a duplicate item while maintaining the order of items in the queue. The implementation leverages locking already implemented in the base class redefining only the primitives. Since the internal queue ...
OrderedSetQueue
python
sqlalchemy__sqlalchemy
test/dialect/oracle/test_reflection.py
{ "start": 12118, "end": 18054 }
class ____(AssertsCompiledSQL, fixtures.TestBase): __only_on__ = "oracle" __sparse_driver_backend__ = True @testing.fixture def plain_foo_table(self, metadata, connection): foo = Table("foo", metadata, Column("id", Integer, primary_key=True)) foo.create(connection) return foo ...
ConstraintTest
python
scipy__scipy
scipy/integrate/_quadpack_py.py
{ "start": 52820, "end": 54603 }
class ____: def __init__(self, func, ranges, opts, full_output): self.abserr = 0 self.func = func self.ranges = ranges self.opts = opts self.maxdepth = len(ranges) self.full_output = full_output if self.full_output: self.out_dict = {'neval': 0} ...
_NQuad
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-mcp/llama_index/tools/mcp/client.py
{ "start": 1815, "end": 2854 }
class ____(TokenStorage): """ Simple in-memory token storage implementation for OAuth authentication. This is the default storage used when none is provided to with_oauth(). Not suitable for production use across restarts as tokens are only stored in memory. """ def __init__(self): ...
DefaultInMemoryTokenStorage
python
huggingface__transformers
src/transformers/models/markuplm/modeling_markuplm.py
{ "start": 17069, "end": 18560 }
class ____(GradientCheckpointingLayer): def __init__(self, config): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = MarkupLMAttention(config) self.intermediate = MarkupLMIntermediate(config) self.o...
MarkupLMLayer
python
scipy__scipy
benchmarks/benchmarks/stats.py
{ "start": 13305, "end": 15433 }
class ____(Benchmark): # though there is a new version of this benchmark that runs all the # distributions, at the time of writing there was odd behavior on # the asv for this benchmark, so it is retained. # https://pv.github.io/scipy-bench/#stats.Distribution.time_distribution param_names = ['dist...
Distribution
python
readthedocs__readthedocs.org
readthedocs/core/mixins.py
{ "start": 669, "end": 724 }
class ____(LoginRequiredMixin): pass
PrivateViewMixin