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
src/transformers/models/dpt/modeling_dpt.py
{ "start": 38216, "end": 42566 }
class ____(DPTPreTrainedModel): def __init__(self, config): super().__init__(config) self.backbone = None if config.is_hybrid is False and (config.backbone_config is not None or config.backbone is not None): self.backbone = load_backbone(config) else: self.dp...
DPTForDepthEstimation
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-redis/llama_index/vector_stores/redis/base.py
{ "start": 2362, "end": 28375 }
class ____(BasePydanticVectorStore): """ RedisVectorStore. The RedisVectorStore takes a user-defined schema object and a Redis connection client or URL string. The schema is optional, but useful for: - Defining a custom index name, key prefix, and key separator. - Defining *additional* metadata...
RedisVectorStore
python
PrefectHQ__prefect
src/integrations/prefect-gcp/prefect_gcp/workers/vertex.py
{ "start": 8693, "end": 15398 }
class ____(BaseJobConfiguration): """ Configuration class used by the Vertex AI Worker to create a Job. An instance of this class is passed to the Vertex AI Worker's `run` method for each flow run. It contains all information necessary to execute the flow run as a Vertex AI Job. Attributes: ...
VertexAIWorkerJobConfiguration
python
uqfoundation__dill
dill/_dill.py
{ "start": 7601, "end": 11906 }
class ____(object): """ Create a unique sentinel object that is pickled as a constant. """ def __init__(self, name, module_name=None): self.name = name if module_name is None: # Use the calling frame's module self.__module__ = inspect.currentframe().f_back.f_globa...
Sentinel
python
getsentry__sentry
tests/sentry/seer/explorer/test_tools.py
{ "start": 1558, "end": 21096 }
class ____(APITransactionTestCase, SnubaTestCase, SpanTestCase): default_span_fields = [ "id", "span.op", "span.description", "span.duration", "transaction", "timestamp", "project", "trace", ] def setUp(self): super().setUp() s...
TestSpansQuery
python
urllib3__urllib3
src/urllib3/exceptions.py
{ "start": 2910, "end": 3271 }
class ____(RequestError): """Raised when an existing pool gets a request for a foreign host.""" def __init__( self, pool: ConnectionPool, url: str, retries: Retry | int = 3 ) -> None: message = f"Tried to open a foreign host with url: {url}" super().__init__(pool, url, message) ...
HostChangedError
python
scipy__scipy
scipy/linalg/tests/test_basic.py
{ "start": 40501, "end": 43458 }
class ____: def test_simple(self): """ solve_triangular on a simple 2x2 matrix. """ A = array([[1, 0], [1, 2]]) b = [1, 1] sol = solve_triangular(A, b, lower=True) assert_array_almost_equal(sol, [1, 0]) # check that it works also for non-contiguous m...
TestSolveTriangular
python
crytic__slither
slither/tools/mutator/mutators/ROR.py
{ "start": 407, "end": 2318 }
class ____(AbstractMutator): # pylint: disable=too-few-public-methods NAME = "ROR" HELP = "Relational Operator Replacement" def _mutate(self) -> Dict: result: Dict = {} for ( # pylint: disable=too-many-nested-blocks function ) in self.contract.functions_and_modifiers_...
ROR
python
scikit-image__scikit-image
benchmarks/benchmark_exposure.py
{ "start": 269, "end": 1445 }
class ____: """Benchmark for exposure routines in scikit-image.""" def setup(self): self.image_u8 = data.moon() self.image = img_as_float(self.image_u8) self.image = rescale(self.image, 2.0, anti_aliasing=False) # for Contrast stretching self.p2, self.p98 = np.percentile...
ExposureSuite
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_from_tensor_op_test.py
{ "start": 1189, "end": 20905 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def testDocStringExamples(self): # The examples from RaggedTensor.from_tensor.__doc__. dt = constant_op.constant([[5, 7, 0], [0, 3, 0], [6, 0, 0]]) self.assertAllEqual( RaggedTensor.from_tensor(dt...
RaggedTensorFromTensorOpTest
python
getsentry__sentry
src/sentry/integrations/msteams/card_builder/block.py
{ "start": 2840, "end": 2929 }
class ____(TypedDict): type: Literal["Container"] items: list[Block]
ContainerBlock
python
scipy__scipy
benchmarks/benchmarks/fft_basic.py
{ "start": 6202, "end": 7477 }
class ____(Benchmark): params = [ [100, 256, 313, 512, 1000, 1024, 2048, 2048*2, 2048*4], ['real', 'cmplx'], ['pocketfft', 'pyfftw', 'numpy', 'direct'] ] param_names = ['size', 'type', 'backend'] def setup(self, size, cmplx, backend): import scipy.fft if cmplx ==...
FftBackends
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-motherduck/unit_tests/test_unit_test.py
{ "start": 1053, "end": 6012 }
class ____: """Test the UnicodeAwareNormalizer that preserves Unicode characters.""" def setup_method(self): self.normalizer = UnicodeAwareNormalizer() self.old_normalizer = LowerCaseNormalizer() @pytest.mark.parametrize( "input_name, expected_output", [ # ASCII...
TestUnicodeAwareNormalizer
python
kamyu104__LeetCode-Solutions
Python/find-if-path-exists-in-graph.py
{ "start": 84, "end": 1241 }
class ____(object): def validPath(self, n, edges, start, end): """ :type n: int :type edges: List[List[int]] :type start: int :type end: int :rtype: bool """ def bi_bfs(adj, start, target): left, right = {start}, {target} lookup...
Solution
python
scrapy__scrapy
tests/test_spidermiddleware.py
{ "start": 18572, "end": 19745 }
class ____(TestBuiltinMiddlewareSimple): async def _callback(self) -> Any: for item in super()._callback(): yield item @deferred_f_from_coro_f async def test_just_builtin(self): await self._test_asyncgen_base() @deferred_f_from_coro_f async def test_builtin_simple(self)...
TestBuiltinMiddlewareAsyncGen
python
pypa__pipenv
pipenv/patched/pip/_internal/commands/help.py
{ "start": 252, "end": 1192 }
class ____(Command): """Show help for commands""" usage = """ %prog <command>""" ignore_require_venv = True def run(self, options: Values, args: List[str]) -> int: from pipenv.patched.pip._internal.commands import ( commands_dict, create_command, get_s...
HelpCommand
python
numba__numba
numba/tests/test_moved_modules.py
{ "start": 110, "end": 1319 }
class ____(TestCase): """Testing moved modules in Q1 2020 but were decided to kept as public API """ def tests_numba_types(self): import numba.types import numba.core.types as types # The old module IS NOT the new module self.assertIsNot(numba.types, types) # Attribut...
TestMovedModule
python
huggingface__transformers
src/transformers/models/kosmos2_5/modeling_kosmos2_5.py
{ "start": 15298, "end": 19104 }
class ____(ModelOutput): """ Model output class for `Kosmos2_5ForConditionalGeneration`. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(b...
Kosmos2_5ForConditionalGenerationModelOutput
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/menus.py
{ "start": 22718, "end": 24819 }
class ____(HSplit): """ Container that displays the completions in several columns. When `show_meta` (a :class:`~prompt_toolkit.filters.Filter`) evaluates to True, it shows the meta information at the bottom. """ def __init__( self, min_rows: int = 3, suggested_max_colum...
MultiColumnCompletionsMenu
python
astropy__astropy
astropy/units/tests/test_quantity_non_ufuncs.py
{ "start": 49994, "end": 50618 }
class ____: def test_bincount(self): i = np.array([1, 1, 2, 3, 2, 4]) weights = np.arange(len(i)) * u.Jy out = np.bincount(i, weights) expected = np.bincount(i, weights.value) * weights.unit assert_array_equal(out, expected) with pytest.raises(TypeError): ...
TestBincountDigitize
python
kamyu104__LeetCode-Solutions
Python/sequence-reconstruction.py
{ "start": 99, "end": 1038 }
class ____(object): def sequenceReconstruction(self, org, seqs): """ :type org: List[int] :type seqs: List[List[int]] :rtype: bool """ if not seqs: return False pos = [0] * (len(org) + 1) for i in xrange(len(org)): pos[org[i]] =...
Solution
python
Lightning-AI__lightning
src/lightning/fabric/accelerators/cuda.py
{ "start": 906, "end": 7256 }
class ____(Accelerator): """Accelerator for NVIDIA CUDA devices.""" @override def setup_device(self, device: torch.device) -> None: """ Raises: ValueError: If the selected device is not of type CUDA. """ if device.type != "cuda": raise...
CUDAAccelerator
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0048_add_build_data.py
{ "start": 149, "end": 641 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0047_build_default_triggered"), ] operations = [ migrations.AddField( model_name="version", name="build_data", field=models.JSONField( default=No...
Migration
python
doocs__leetcode
solution/3400-3499/3438.Find Valid Pair of Adjacent Digits in String/Solution.py
{ "start": 0, "end": 286 }
class ____: def findValidPair(self, s: str) -> str: cnt = [0] * 10 for x in map(int, s): cnt[x] += 1 for x, y in pairwise(map(int, s)): if x != y and cnt[x] == x and cnt[y] == y: return f"{x}{y}" return ""
Solution
python
sympy__sympy
sympy/polys/polyoptions.py
{ "start": 17703, "end": 18133 }
class ____(BooleanOption, Flag, metaclass=OptionType): """``auto`` flag to polynomial manipulation functions. """ option = 'auto' after = ['field', 'domain', 'extension', 'gaussian'] @classmethod def default(cls): return True @classmethod def postprocess(cls, options): if...
Auto
python
django__django
tests/model_regress/models.py
{ "start": 1617, "end": 1732 }
class ____(models.Model): model2 = models.ForeignKey(Model2, models.CASCADE, unique=True, to_field="model1")
Model3
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 95384, "end": 116319 }
class ____(Request): """ Clone an existing task :param task: ID of the task :type task: str :param new_task_name: The name of the cloned task. If not provided then taken from the original task :type new_task_name: str :param new_task_comment: The comment of the cloned task. If not p...
CloneRequest
python
pytorch__pytorch
test/distributed/test_c10d_pypg.py
{ "start": 5255, "end": 7621 }
class ____(TestCase): def test_attr_overrides(self): pg = DummyAttrProcessGroup(0, 1) self.assertEqual(pg.name(), "dummy-attr") self.assertEqual(pg.rank(), 123) self.assertEqual(pg.size(), 456) pg._set_group_name("name") self.assertEqual(pg.group_name, "py:name") ...
TestPyProcessGroup
python
oauthlib__oauthlib
tests/oauth2/rfc6749/endpoints/test_error_responses.py
{ "start": 399, "end": 22688 }
class ____(TestCase): def set_client(self, request): request.client = mock.MagicMock() request.client.client_id = 'mocked' return True def setUp(self): self.validator = mock.MagicMock(spec=RequestValidator) self.validator.get_default_redirect_uri.return_value = None ...
ErrorResponseTest
python
sqlalchemy__sqlalchemy
test/base/test_utils.py
{ "start": 16183, "end": 18732 }
class ____(fixtures.TestBase): def test_wrapping_update_wrapper_fn(self): def my_fancy_default(): """run the fancy default""" return 10 c = util.wrap_callable(lambda: my_fancy_default, my_fancy_default) eq_(c.__name__, "my_fancy_default") eq_(c.__doc__, "run...
WrapCallableTest
python
mlflow__mlflow
tests/utils/test_annotations.py
{ "start": 954, "end": 1139 }
class ____: """ A deprecated dataclass. """ x: int y: int def add(self): return self.x + self.y @deprecated(since="1.0.0") @dataclass
DeprecatedDataClass
python
wandb__wandb
wandb/_pydantic/v1_compat.py
{ "start": 6456, "end": 9772 }
class ____(metaclass=V1MixinMetaclass): # Internal compat helpers @classmethod def _dump_json_vals(cls, values: dict[str, Any], by_alias: bool) -> dict[str, Any]: """Reserialize values from `Json`-typed fields after dumping the model to dict.""" # Get the expected keys (after `.model_dump()`...
V1Mixin
python
ray-project__ray
python/ray/serve/tests/test_target_capacity.py
{ "start": 13710, "end": 14009 }
class ____(BaseModel): num_replicas: int def create_controlled_app(config: ControllerAppConfig) -> Application: num_replicas = config.num_replicas return ControlledLifecycleDeployment.options( name="controlled", num_replicas=num_replicas, ).bind()
ControllerAppConfig
python
PrefectHQ__prefect
src/prefect/_result_records.py
{ "start": 2044, "end": 7789 }
class ____(BaseModel, Generic[R]): """ A record of a result. """ metadata: ResultRecordMetadata result: R @property def expiration(self) -> DateTime | None: return self.metadata.expiration @property def serializer(self) -> Serializer: return self.metadata.serialize...
ResultRecord
python
py-pdf__pypdf
pypdf/constants.py
{ "start": 22239, "end": 23007 }
class ____: """ Associated file relationship types, defining the relationship between the PDF component and the associated file. Defined in table 43 of the PDF 2.0 reference. """ SOURCE = "/Source" # Original content source DATA = "/Data" # Base data for visual presentation ALTERNATI...
AFRelationship
python
django__django
tests/migrations/models.py
{ "start": 561, "end": 671 }
class ____: """ An object that migration doesn't know how to serialize. """ pass
Unserializable
python
spyder-ide__spyder
spyder/widgets/browser.py
{ "start": 13731, "end": 18539 }
class ____(QWidget): """ Web browser widget. """ def __init__(self, parent=None, options_button=None, handle_links=True): QWidget.__init__(self, parent) self.home_url = None self.webview = WebView(self, handle_links=handle_links) self.webview.setup() self.webvie...
WebBrowser
python
bokeh__bokeh
src/bokeh/models/widgets/tables.py
{ "start": 17900, "end": 18132 }
class ____(CellEditor): ''' Multi-line string cell editor. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs)
TextEditor
python
davidhalter__jedi
jedi/plugins/stdlib.py
{ "start": 29997, "end": 31470 }
class ____(LazyValueWrapper): def __init__(self, cls, name): self.inference_state = cls.inference_state self._cls = cls # Corresponds to super().__self__ self._name = name self.tree_node = self._name.tree_name @safe_property def name(self): return ValueName(self, se...
EnumInstance
python
spack__spack
var/spack/test_repos/spack_repo/duplicates_test/packages/cycle_a/package.py
{ "start": 216, "end": 578 }
class ____(Package): """Package that would lead to cycles if default variant values are used""" homepage = "http://www.example.com" url = "http://www.example.com/tdep-1.0.tar.gz" version("2.0", md5="0123456789abcdef0123456789abcdef") variant("cycle", default=True, description="activate cycles") ...
CycleA
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/inputs.py
{ "start": 9526, "end": 9902 }
class ____(graphene.InputObjectType): repositoryName = graphene.NonNull(graphene.String) repositoryLocationName = graphene.NonNull(graphene.String) scheduleName = graphene.NonNull(graphene.String) class Meta: description = """This type represents the fields necessary to identify a schedule.""" ...
GrapheneScheduleSelector
python
spack__spack
lib/spack/spack/solver/asp.py
{ "start": 167444, "end": 167789 }
class ____(spack.error.UnsatisfiableSpecError): """There was an issue with the spec that was requested (i.e. a user error).""" def __init__(self, msg): super(spack.error.UnsatisfiableSpecError, self).__init__(msg) self.provided = None self.required = None self.constraint_type = ...
UnsatisfiableSpecError
python
huggingface__transformers
src/transformers/models/esm/modeling_esmfold.py
{ "start": 40831, "end": 41239 }
class ____(nn.Module): def __init__(self, embed_dim, inner_dim, dropout=0): super().__init__() self.mlp = nn.Sequential( nn.LayerNorm(embed_dim), nn.Linear(embed_dim, inner_dim), nn.ReLU(), nn.Linear(inner_dim, embed_dim), nn.Dropout(dropo...
EsmFoldResidueMLP
python
astropy__astropy
astropy/table/tests/test_column.py
{ "start": 17213, "end": 21989 }
class ____: """Bunch of tests originally from ATpy that test the attrs_equal method.""" def test_5(self, Column): c1 = Column(name="a", dtype=int, unit="mJy") c2 = Column(name="a", dtype=int, unit="mJy") assert c1.attrs_equal(c2) def test_6(self, Column): c1 = Column( ...
TestAttrEqual
python
celery__celery
celery/beat.py
{ "start": 22945, "end": 24613 }
class ____(Thread): """Embedded task scheduler using threading.""" def __init__(self, app, **kwargs): super().__init__() self.app = app self.service = Service(app, **kwargs) self.daemon = True self.name = 'Beat' def run(self): self.app.set_current() ...
_Threaded
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/execution/experimental/fragment.py
{ "start": 2931, "end": 3251 }
class ____(object): __slots__ = ('fn', 'args', 'context', 'info') def __init__(self, fn, args, context, info): self.fn = fn self.args = args self.context = context self.info = info def execute(self, root): return self.fn(root, self.args, self.context, self.info)
Field
python
PyCQA__pylint
doc/data/messages/n/no-method-argument/good.py
{ "start": 0, "end": 67 }
class ____: def print_greeting(self): print("hello")
Person
python
bokeh__bokeh
tests/unit/bokeh/core/test_properties.py
{ "start": 3255, "end": 15605 }
class ____: def test_simple_class(self) -> None: class Foo(HasProps): x = Int(12) y = String("hello") z = List(Int, default=[1, 2, 3]) zz = Dict(String, Int) s = Nullable(String(None)) f = Foo() assert f.x == 12 assert f.y ...
TestBasic
python
redis__redis-py
tests/test_asyncio/test_connection_pool.py
{ "start": 8407, "end": 12746 }
class ____: @asynccontextmanager async def get_pool(self, connection_kwargs=None, max_connections=10, timeout=20): connection_kwargs = connection_kwargs or {} pool = redis.BlockingConnectionPool( connection_class=DummyConnection, max_connections=max_connections, ...
TestBlockingConnectionPool
python
python__mypy
test-data/unit/plugins/method_in_decorator.py
{ "start": 172, "end": 801 }
class ____(Plugin): def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: if "Foo.a" in fullname: return method_decorator_callback return None def method_decorator_callback(ctx: MethodContext) -> Type: default = get_proper_type(ctx.default_return_type)...
MethodDecoratorPlugin
python
great-expectations__great_expectations
great_expectations/expectations/row_conditions.py
{ "start": 1064, "end": 1260 }
class ____(ValueError): """Raised when OR groups contain nested OR conditions.""" def __init__(self): super().__init__("OR groups cannot contain nested OR conditions")
NestedOrError
python
fastai__fastai
fastai/data/transforms.py
{ "start": 11122, "end": 11939 }
class ____(DisplayedTransform): "Reversible transform of category string to `vocab` id" loss_func,order=CrossEntropyLossFlat(),1 def __init__(self, vocab=None, sort=True, add_na=False): if vocab is not None: vocab = CategoryMap(vocab, sort=sort, add_na=add_na) store_attr() def setups(se...
Categorize
python
streamlit__streamlit
lib/streamlit/runtime/uploaded_file_manager.py
{ "start": 1770, "end": 2842 }
class ____(io.BytesIO): """A mutable uploaded file. This class extends BytesIO, which has copy-on-write semantics when initialized with `bytes`. """ def __init__(self, record: UploadedFileRec, file_urls: FileURLsProto) -> None: # BytesIO's copy-on-write semantics doesn't seem to be mention...
UploadedFile
python
getsentry__sentry
tests/sentry/issue_detection/test_n_plus_one_db_span_detector.py
{ "start": 755, "end": 12491 }
class ____(unittest.TestCase): def setUp(self) -> None: super().setUp() self._settings = get_detection_settings() def find_problems( self, event: dict[str, Any], setting_overides: dict[str, Any] | None = None ) -> list[PerformanceProblem]: if setting_overides: fo...
NPlusOneDbDetectorTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_select.py
{ "start": 5533, "end": 19881 }
class ____(fixtures.TablesTest): __backend__ = True @classmethod def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("x", Integer), Column("y", Integer), ) @classmet...
FetchLimitOffsetTest
python
pypa__pipenv
pipenv/patched/pip/_internal/exceptions.py
{ "start": 25169, "end": 25713 }
class ____(DiagnosticPipError): reference = "uninstall-distutils-installed-package" def __init__(self, *, distribution: "BaseDistribution") -> None: super().__init__( message=Text(f"Cannot uninstall {distribution}"), context=( "It is a distutils installed project...
LegacyDistutilsInstall
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/security.py
{ "start": 18181, "end": 19051 }
class ____(OrmClause[set[str]]): """A parameter that filters the permitted teams for the user.""" def to_orm(self, select: Select) -> Select: return select.where(Team.name.in_(self.value or set())) def permitted_team_filter_factory() -> Callable[[BaseUser, BaseAuthManager], PermittedTeamFilter]: ...
PermittedTeamFilter
python
pydantic__pydantic
pydantic/_internal/_generate_schema.py
{ "start": 131608, "end": 132016 }
class ____: __slots__ = ('_stack',) def __init__(self) -> None: self._stack: list[str] = [] @contextmanager def push(self, field_name: str) -> Iterator[None]: self._stack.append(field_name) yield self._stack.pop() def get(self) -> str | None: if self._stack...
_FieldNameStack
python
fsspec__filesystem_spec
fsspec/implementations/tar.py
{ "start": 260, "end": 4111 }
class ____(AbstractArchiveFileSystem): """Compressed Tar archives as a file-system (read-only) Supports the following formats: tar.gz, tar.bz2, tar.xz """ root_marker = "" protocol = "tar" cachable = False def __init__( self, fo="", index_store=None, ta...
TarFileSystem
python
django__django
tests/db_functions/text/test_md5.py
{ "start": 225, "end": 1585 }
class ____(TestCase): @classmethod def setUpTestData(cls): Author.objects.bulk_create( [ Author(alias="John Smith"), Author(alias="Jordan Élena"), Author(alias="皇帝"), Author(alias=""), Author(alias=None), ...
MD5Tests
python
scipy__scipy
scipy/stats/tests/test_distributions.py
{ "start": 22922, "end": 25145 }
class ____: # "Exact" value of chi.sf(10, 4), as computed by Wolfram Alpha with # 1 - CDF[ChiDistribution[4], 10] CHI_SF_10_4 = 9.83662422461598e-21 # "Exact" value of chi.mean(df=1000) as computed by Wolfram Alpha with # Mean[ChiDistribution[1000]] CHI_MEAN_1000 = 31.614871896980 ...
TestChi
python
astropy__astropy
astropy/io/fits/tests/test_diff.py
{ "start": 591, "end": 890 }
class ____(NonstandardExtHDU): def __init__(self, data=None, *args, **kwargs): super().__init__(self, *args, **kwargs) self._buffer = np.asarray(data).tobytes() self._data_offset = 0 @property def size(self): return len(self._buffer)
DummyNonstandardExtHDU
python
mlflow__mlflow
tests/pyfunc/test_pyfunc_model_with_type_hints.py
{ "start": 17455, "end": 18534 }
class ____(NamedTuple): type_hint: str input_example: Any extra_def: str = "" @pytest.mark.parametrize( "type_hint_example", [ TypeHintExample("list[int]", [123]), TypeHintExample("list[str]", ["string"]), TypeHintExample("list[bool]", [True]), TypeHintExample("list...
TypeHintExample
python
psf__black
tests/data/cases/fmtskip8.py
{ "start": 404, "end": 1705 }
class ____( Unformatted, SuperClasses ): # fmt: skip def some_method( self, unformatted, args ): # fmt: skip print("I am some_method") return 0 async def some_async_method( self, unformatted, args ): # fmt: skip print("I am some_async_method") await asyncio.sleep(1...
SomeClass
python
mkdocs__mkdocs
mkdocs/config/defaults.py
{ "start": 1202, "end": 8948 }
class ____(base.Config): """The configuration of MkDocs itself (the root object of mkdocs.yml).""" config_file_path: str = c.Type(str) # type: ignore[assignment] """The path to the mkdocs.yml config file. Can't be populated from the config.""" site_name = c.Type(str) """The title to use for the d...
MkDocsConfig
python
celery__celery
t/unit/worker/test_state.py
{ "start": 4486, "end": 5367 }
class ____: def test_accepted(self, requests=[SimpleReq('foo'), SimpleReq('bar'), SimpleReq('baz'), SimpleReq('baz')]): for request in requests: state.task_accepted(request) ...
test_state
python
django__django
tests/model_fields/models.py
{ "start": 3795, "end": 3887 }
class ____(models.Model): value = models.PositiveBigIntegerField()
PositiveBigIntegerModel
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 197929, "end": 203929 }
class ____(test_util.TensorFlowTestCase): """Tests the function total_variation() in image_ops. We test a few small handmade examples, as well as some larger examples using an equivalent numpy implementation of the total_variation() function. We do NOT test for overflows and invalid / edge-case arguments. ...
TotalVariationTest
python
bokeh__bokeh
src/bokeh/models/glyph.py
{ "start": 4025, "end": 4760 }
class ____(HasProps): ''' Glyphs with Hatch properties ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) #----------------------------------------------------------------------------- # Dev API #--------...
HatchGlyph
python
airbytehq__airbyte
airbyte-ci/connectors/live-tests/src/live_tests/commons/backends/file_backend.py
{ "start": 765, "end": 6358 }
class ____(BaseBackend): RELATIVE_CATALOGS_PATH = "catalog.jsonl" RELATIVE_CONNECTION_STATUS_PATH = "connection_status.jsonl" RELATIVE_RECORDS_PATH = "records.jsonl" RELATIVE_SPECS_PATH = "spec.jsonl" RELATIVE_STATES_PATH = "states.jsonl" RELATIVE_TRACES_PATH = "traces.jsonl" RELATIVE_LOGS_P...
FileBackend
python
huggingface__transformers
src/transformers/modeling_outputs.py
{ "start": 97022, "end": 102231 }
class ____(ModelOutput): """ Base class for time series model's encoder outputs that also contains pre-computed hidden states that can speed up sequential decoding. Args: last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidde...
Seq2SeqTSModelOutput
python
lepture__authlib
authlib/oauth2/rfc6749/requests.py
{ "start": 123, "end": 1241 }
class ____: @property def data(self): raise NotImplementedError() @property def datalist(self) -> defaultdict[str, list]: raise NotImplementedError() @property def client_id(self) -> str: """The authorization server issues the registered client a client identifi...
OAuth2Payload
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_compute.py
{ "start": 67194, "end": 77798 }
class ____: @mock.patch(IGM_PATH) @mock.patch(COMPUTE_ENGINE_HOOK_PATH) def test_update_igm_should_execute_successfully(self, mock_hook, igm): get_instance_group_manager_obj_mock = mock.MagicMock() get_instance_group_manager_obj_mock.__class__ = InstanceGroupManager mock_hook.return_...
TestGceInstanceGroupManagerUpdate
python
doocs__leetcode
solution/2800-2899/2871.Split Array Into Maximum Number of Subarrays/Solution.py
{ "start": 0, "end": 266 }
class ____: def maxSubarrays(self, nums: List[int]) -> int: score, ans = -1, 1 for num in nums: score &= num if score == 0: score = -1 ans += 1 return 1 if ans == 1 else ans - 1
Solution
python
sympy__sympy
sympy/sets/sets.py
{ "start": 25075, "end": 29987 }
class ____(Set): """ Represents a Cartesian Product of Sets. Explanation =========== Returns a Cartesian product given several sets as either an iterable or individual arguments. Can use ``*`` operator on any sets for convenient shorthand. Examples ======== >>> from sympy im...
ProductSet
python
doocs__leetcode
solution/1600-1699/1640.Check Array Formation Through Concatenation/Solution2.py
{ "start": 0, "end": 380 }
class ____: def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool: d = {p[0]: p for p in pieces} i, n = 0, len(arr) while i < n: if arr[i] not in d: return False p = d[arr[i]] if arr[i : i + len(p)] != p: r...
Solution
python
numpy__numpy
benchmarks/benchmarks/bench_strings.py
{ "start": 223, "end": 1233 }
class ____(Benchmark): # Basic string comparison speed tests params = [ [100, 10000, (1000, 20)], ['U', 'S'], [True, False], ['==', '!=', '<', '<=', '>', '>=']] param_names = ['shape', 'dtype', 'contig', 'operator'] int64 = np.dtype(np.int64) def setup(self, shape, d...
StringComparisons
python
lepture__authlib
authlib/oauth2/rfc8628/endpoint.py
{ "start": 151, "end": 7123 }
class ____: """This OAuth 2.0 [RFC6749] protocol extension enables OAuth clients to request user authorization from applications on devices that have limited input capabilities or lack a suitable browser. Such devices include smart TVs, media consoles, picture frames, and printers, which lack an ea...
DeviceAuthorizationEndpoint
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/interfaces.py
{ "start": 48401, "end": 49336 }
class ____(ORMOption): """Describe a modification to a Query""" __slots__ = () _is_legacy_option = True propagate_to_loaders = False """if True, indicate this option should be carried along to "secondary" Query objects produced during lazy loads or refresh operations. """ def pr...
MapperOption
python
pypa__pip
tests/unit/test_configuration.py
{ "start": 312, "end": 3830 }
class ____(ConfigurationMixin): def test_global_loading(self) -> None: self.patch_configuration(kinds.GLOBAL, {"test.hello": "1"}) self.configuration.load() assert self.configuration.get_value("test.hello") == "1" def test_user_loading(self) -> None: self.patch_configuration(ki...
TestConfigurationLoading
python
pydantic__pydantic
tests/mypy/modules/plugin_success.py
{ "start": 1154, "end": 1345 }
class ____(Model): pass ForwardReferencingModel.model_rebuild() future_model = FutureModel(x=1, y='a') forward_model = ForwardReferencingModel(x=1, y='a', future=future_model)
FutureModel
python
qdrant__qdrant-client
qdrant_client/http/api/points_api.py
{ "start": 16182, "end": 23372 }
class ____(_PointsApi): async def batch_update( self, collection_name: str, wait: bool = None, ordering: WriteOrdering = None, update_operations: m.UpdateOperations = None, ) -> m.InlineResponse20014: """ Apply a series of update operations for points, vec...
AsyncPointsApi
python
mlflow__mlflow
dev/clint/tests/rules/test_redundant_test_docstring.py
{ "start": 3119, "end": 3192 }
class ____: """ Multi Line """ pass
TestWithMultilineDoc
python
huggingface__transformers
src/transformers/models/ovis2/modeling_ovis2.py
{ "start": 4516, "end": 5239 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Ovis2RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_...
Ovis2RMSNorm
python
pytorch__pytorch
torch/cuda/_device_limits.py
{ "start": 68, "end": 5500 }
class ____: r"""Utility class that provides the theoretical limits of Nvidia GPU devices. The limits don't take into account thermal throttling (assume that the GPU run at its peak rated frequency). This is because user hardware configuration may influence power behavior. """ def __init__(self,...
GPULimits
python
django__django
tests/admin_filters/tests.py
{ "start": 9493, "end": 9705 }
class ____(ModelAdmin): list_filter = [ ("author", EmptyFieldListFilter), ("title", EmptyFieldListFilter), ("improvedbook", EmptyFieldListFilter), ]
BookAdminWithEmptyFieldListFilter
python
jazzband__django-model-utils
tests/models.py
{ "start": 13165, "end": 13397 }
class ____(models.Model): weight = models.IntegerField() belonging = models.ForeignKey( BoxJoinModel, null=True, on_delete=models.CASCADE ) objects = JoinQueryset.as_manager()
JoinItemForeignKey
python
huggingface__transformers
tests/models/kosmos2_5/test_image_processing_kosmos2_5.py
{ "start": 3101, "end": 14271 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = Kosmos2_5ImageProcessor if is_vision_available() else None fast_image_processing_class = Kosmos2_5ImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processo...
Kosmos2_5ImageProcessingTest
python
pandas-dev__pandas
asv_bench/benchmarks/groupby.py
{ "start": 9374, "end": 9887 }
class ____: def setup(self): n = 2 * 10**5 alpha = list(map("".join, product(ascii_letters, repeat=4))) data = np.random.choice(alpha, (n // 5, 4), replace=False) data = np.repeat(data, 5, axis=0) self.df = DataFrame(data, columns=list("abcd")) self.df["joe"] = (np.ra...
GroupStrings
python
readthedocs__readthedocs.org
readthedocs/projects/forms.py
{ "start": 30019, "end": 30575 }
class ____(forms.Form): """Project email notification form.""" email = forms.EmailField() def __init__(self, *args, **kwargs): self.project = kwargs.pop("project", None) super().__init__(*args, **kwargs) def clean_email(self): self.email = EmailHook.objects.get_or_create( ...
EmailHookForm
python
readthedocs__readthedocs.org
readthedocs/gold/migrations/0003_add_missing_model_change_migrations.py
{ "start": 150, "end": 894 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("gold", "0002_rename_last_4_digits"), ] operations = [ migrations.AlterField( model_name="golduser", name="level", field=models.CharField( choices=[ ...
Migration
python
huggingface__transformers
src/transformers/models/megatron_bert/modeling_megatron_bert.py
{ "start": 12395, "end": 15590 }
class ____(GradientCheckpointingLayer): def __init__(self, config, layer_idx=None): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = MegatronBertAttention(config, layer_idx=layer_idx) self.is_decoder = conf...
MegatronBertLayer
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 46955, "end": 47889 }
class ____(sgqlc.types.Enum): """The reason a member was removed from an Organization. Enumeration Choices: * `SAML_EXTERNAL_IDENTITY_MISSING`: SAML external identity missing * `SAML_SSO_ENFORCEMENT_REQUIRES_EXTERNAL_IDENTITY`: SAML SSO enforcement requires an external identity * `TWO_FACTOR...
OrgRemoveMemberAuditEntryReason
python
scipy__scipy
scipy/io/_harwell_boeing/tests/test_fortran_format.py
{ "start": 1297, "end": 1825 }
class ____: def test_to_fortran(self): f = [IntFormat(10), IntFormat(12, 10), IntFormat(12, 10, 3)] res = ["(I10)", "(I12.10)", "(3I12.10)"] for i, j in zip(f, res): assert_equal(i.fortran_format, j) def test_from_number(self): f = [10, -12, 123456789] r_f =...
TestIntFormat
python
kamyu104__LeetCode-Solutions
Python/find-x-value-of-array-i.py
{ "start": 38, "end": 515 }
class ____(object): def resultArray(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ result = [0]*k dp = [0]*k for x in nums: new_dp = [0]*k new_dp[x%k] += 1 for i, c in enumerate(dp): ...
Solution
python
h5py__h5py
h5py/tests/test_group.py
{ "start": 3970, "end": 4577 }
class ____(BaseGroup): """ Feature: Named types can be created by direct assignment of dtypes """ def test_dtype(self): """ Named type creation """ name = make_name() dtype = np.dtype('|S10') self.f[name] = dtype self.assertIsInstance(self.f[name], Datatype)...
TestDtypeAssignment
python
dagster-io__dagster
python_modules/libraries/dagster-deltalake/dagster_deltalake/io_manager.py
{ "start": 903, "end": 1026 }
class ____: table_uri: str storage_options: dict[str, str] table_config: Optional[dict[str, str]]
TableConnection
python
huggingface__transformers
src/transformers/models/tvp/image_processing_tvp.py
{ "start": 1492, "end": 3115 }
class ____(ImagesKwargs, total=False): r""" do_flip_channel_order (`bool`, *optional*): Whether to flip the channel order of the image from RGB to BGR. constant_values (`float` or `List[float]`, *optional*): Value used to fill the padding area when `pad_mode` is `'constant'`. pad_mode (`...
TvpImageProcessorKwargs
python
conda__conda
conda/models/match_spec.py
{ "start": 34009, "end": 34431 }
class ____: def __str__(self): return self._raw_value def __repr__(self): return f"{self.__class__.__name__}('{self._raw_value}')" def __eq__(self, other): return isinstance(other, self.__class__) and self._raw_value == other._raw_value def __hash__(self): return hash(...
_StrMatchMixin
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/plan/external_step.py
{ "start": 1913, "end": 11075 }
class ____(StepLauncher): """Launches each step in its own local process, outside the plan process.""" def __init__(self, scratch_dir: str): self.scratch_dir = check.str_param(scratch_dir, "scratch_dir") def launch_step( self, step_context: StepExecutionContext, ) -> Iterator[D...
LocalExternalStepLauncher