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
more-itertools__more-itertools
more_itertools/more.py
{ "start": 68093, "end": 80238 }
class ____(Sequence): """An extension of the built-in ``range()`` function whose arguments can be any orderable numeric type. With only *stop* specified, *start* defaults to ``0`` and *step* defaults to ``1``. The output items will match the type of *stop*: >>> list(numeric_range(3.5)) ...
numeric_range
python
psf__black
src/black/comments.py
{ "start": 1018, "end": 27409 }
class ____: """Describes a piece of syntax that is a comment. It's not a :class:`blib2to3.pytree.Leaf` so that: * it can be cached (`Leaf` objects should not be reused more than once as they store their lineno, column, prefix, and parent information); * `newlines` and `consumed` fields are kept ...
ProtoComment
python
mozilla__bleach
bleach/_vendor/parse.py
{ "start": 10926, "end": 11060 }
class ____(_SplitResultBase, _NetlocResultMixinStr): __slots__ = () def geturl(self): return urlunsplit(self)
SplitResult
python
google__pytype
pytype/overriding_checks.py
{ "start": 520, "end": 1089 }
class ____(enum.Enum): """Constants representing various signature mismatch errors.""" NO_ERROR = enum.auto() DEFAULT_PARAMETER_MISMATCH = enum.auto() DEFAULT_VALUE_MISMATCH = enum.auto() KWONLY_PARAMETER_COUNT_MISMATCH = enum.auto() KWONLY_PARAMETER_NAME_MISMATCH = enum.auto() KWONLY_PARAMETER_TYPE_MISM...
SignatureErrorType
python
bokeh__bokeh
src/bokeh/core/property/nothing.py
{ "start": 1270, "end": 2126 }
class ____(Property[NoReturn]): """ The bottom type of bokeh's type system. It doesn't accept any values. """ def __init__(self, *, help: str | None = None) -> None: super().__init__(default=Undefined, help=help) def validate(self, value: Any, detail: bool = True) -> None: raise ValueError...
Nothing
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vectorizers.py
{ "start": 10022, "end": 10509 }
class ____(_VectorizerConfigCreate): vectorizer: Union[Vectorizers, _EnumLikeStr] = Field( default=Vectorizers.TEXT2VEC_MISTRAL, frozen=True, exclude=True ) model: Optional[str] vectorizeClassName: bool baseURL: Optional[AnyHttpUrl] def _to_dict(self) -> Dict[str, Any]: ret_dict...
_Text2VecMistralConfig
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-aws-datalake/destination_aws_datalake/stream_writer.py
{ "start": 1120, "end": 17160 }
class ____: def __init__(self, aws_handler: AwsHandler, config: ConnectorConfig, configured_stream: ConfiguredAirbyteStream) -> None: self._aws_handler: AwsHandler = aws_handler self._config: ConnectorConfig = config self._configured_stream: ConfiguredAirbyteStream = configured_stream ...
StreamWriter
python
getsentry__sentry
src/sentry/api/serializers/models/plugin.py
{ "start": 1229, "end": 3998 }
class ____(Serializer): def __init__(self, project=None): self.project = project def serialize(self, obj, attrs, user, **kwargs): from sentry.releases.endpoints.project_releases_token import _get_webhook_url doc = "" if self.project is not None: release_token = Pro...
PluginSerializer
python
coleifer__peewee
tests/sqlite.py
{ "start": 2580, "end": 2702 }
class ____(FTSModel, TestModel): message = TextField() class Meta: options = {'tokenize': 'porter'}
Document
python
coleifer__peewee
tests/fields.py
{ "start": 43547, "end": 45631 }
class ____(ModelTestCase): offset_to_names = ( (-10, ()), (5, ('s1',)), (10, ('s1', 's10')), (11, ('s1', 's10')), (60, ('s1', 's10', 's60')), (61, ('s1', 's10', 's60'))) requires = [Schedule, Task] def setUp(self): super(TestDateTimeMath, self).setUp(...
TestDateTimeMath
python
realpython__materials
build-a-django-content-aggregator/source_code_step_1/podcasts/apps.py
{ "start": 36, "end": 91 }
class ____(AppConfig): name = "podcasts"
PodcastsConfig
python
airbytehq__airbyte
airbyte-integrations/connectors/source-monday/unit_tests/integrations/monday_requests/teams_requests_builder.py
{ "start": 184, "end": 569 }
class ____(MondayBaseRequestBuilder): @classmethod def teams_endpoint(cls, authenticator: Authenticator) -> "TeamsRequestBuilder": return cls().with_authenticator(authenticator) @property def request_body(self): params = super().query_params or {} params["query"] = "{teams{id,na...
TeamsRequestBuilder
python
kamyu104__LeetCode-Solutions
Python/shortest-distance-after-road-addition-queries-i.py
{ "start": 888, "end": 1737 }
class ____(object): def shortestDistanceAfterQueries(self, n, queries): """ :type n: int :type queries: List[List[int]] :rtype: List[int] """ def dijkstra(u, v): adj[u].append((v, 1)) min_heap = [(dist[u], u)] while min_heap: ...
Solution2
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/vertex_ai/custom_job.py
{ "start": 2233, "end": 178455 }
class ____(GoogleBaseHook, OperationHelper): """Hook for Google Cloud Vertex AI Custom Job APIs.""" def __init__( self, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__( ...
CustomJobHook
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/callable3.py
{ "start": 267, "end": 568 }
class ____(Generic[T]): def method1(self, val: Callable[[ClassA[R]], T]) -> R | None: return None b1: ClassB[tuple[int, ClassA[str]]] = ClassB() v1: Callable[[ClassA[str]], tuple[int, ClassA[str]]] = lambda r: (42, r) ret = b1.method1(v1) reveal_type(ret, expected_text="str | None")
ClassB
python
tensorflow__tensorflow
tensorflow/python/trackable/trackable_utils_test.py
{ "start": 822, "end": 1924 }
class ____(test.TestCase): def test_order_by_dependency(self): """Tests order_by_dependency correctness.""" # Visual graph (vertical lines point down, so 1 depends on 2): # 1 # / \ # 2 --> 3 <-- 4 # | # 5 # One possible order: [5, 3, 4, 2, 1] dependencies = {1: ...
TrackableUtilsTest
python
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 11438, "end": 11510 }
class ____(HTTPServerError): status_code = 505
HTTPVersionNotSupported
python
airbytehq__airbyte
airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_async_job_manager.py
{ "start": 943, "end": 12687 }
class ____: def test_jobs_empty(self, api, some_config): manager = InsightAsyncJobManager(api=api, jobs=[], account_id=some_config["account_ids"][0]) jobs = list(manager.completed_jobs()) assert not jobs def test_jobs_completed_immediately(self, api, mocker, time_mock, update_job_mock, ...
TestInsightAsyncManager
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/scatter_nd_ops_test.py
{ "start": 34350, "end": 34889 }
class ____(ScatterNdTest): def setUp(self): super().setUp() config.enable_op_determinism() def tearDown(self): super().tearDown() config.disable_op_determinism() def testDeterminism(self): indices = array_ops.zeros([100000, 1], dtypes.int32) values = np.random.randn(100000) shape = ...
ScatterNdDeterminismTest
python
huggingface__transformers
src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py
{ "start": 35835, "end": 43642 }
class ____(Qwen2_5OmniPreTrainedModel): config: Qwen2_5OmniAudioEncoderConfig main_input_name = "input_features" input_modalities = "audio" _no_split_modules = ["Qwen2_5OmniAudioEncoderLayer"] _supports_sdpa = True def __init__(self, config: Qwen2_5OmniAudioEncoderConfig): super().__ini...
Qwen2_5OmniAudioEncoder
python
scipy__scipy
scipy/signal/tests/test_spectral.py
{ "start": 911, "end": 7600 }
class ____: def test_real_onesided_even(self): x = np.zeros(16) x[0] = 1 f, p = periodogram(x) assert_allclose(f, np.linspace(0, 0.5, 9)) q = np.ones(9) q[0] = 0 q[-1] /= 2.0 q /= 8 assert_allclose(p, q) def test_real_onesided_odd(self): ...
TestPeriodogram
python
spack__spack
lib/spack/spack/test/hooks/absolutify_elf_sonames.py
{ "start": 525, "end": 2891 }
class ____: def __init__(self): self.calls = [] def __call__(self, *args, **kwargs): self.calls.append(args) @property def returncode(self): return 0 @pytest.mark.requires_executables("gcc") @skip_unless_linux def test_shared_libraries_visitor(tmp_path: pathlib.Path): """...
ExecutableIntercept
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/associationproxy.py
{ "start": 41899, "end": 44363 }
class ____(AssociationProxyInstance[_T]): """an :class:`.AssociationProxyInstance` that has an object as a target.""" _target_is_object: bool = True _is_canonical = True def adapt_to_entity( self, aliased_insp: AliasedInsp[Any] ) -> AliasedAssociationProxyInstance[_T]: return Alias...
ObjectAssociationProxyInstance
python
pandas-dev__pandas
asv_bench/benchmarks/io/csv.py
{ "start": 5569, "end": 6975 }
class ____(BaseIO): fname = "__test__.csv" @staticmethod def _create_df(rows, cols): index_cols = { "index1": np.random.randint(0, rows, rows), "index2": np.full(rows, 1, dtype=int), "index3": np.full(rows, 1, dtype=int), } data_cols = { ...
ToCSVIndexes
python
dagster-io__dagster
python_modules/libraries/dagster-shared/dagster_shared/serdes/objects/definition_metadata.py
{ "start": 708, "end": 772 }
class ____: name: str type: str @record
DgResourceMetadata
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_W.py
{ "start": 1889, "end": 3118 }
class ____(Benchmark): r""" Wavy objective function. This class defines the W / Wavy [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{Wavy}}(x) = 1 - \frac{1}{n} \sum_{i=1}^{n} \cos(kx_i)e^{-\f...
Wavy
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-operations-to-move-ones-to-the-end.py
{ "start": 38, "end": 413 }
class ____(object): def maxOperations(self, s): """ :type s: str :rtype: int """ result = curr = 0 for i in xrange(len(s)): if s[i] == '1': curr += 1 elif i+1 == len(s) or s[i+1] == '1': result += curr re...
Solution
python
davidhalter__jedi
jedi/inference/syntax_tree.py
{ "start": 35234, "end": 36373 }
class ____(ContextualizedNode): def infer(self): return _infer_subscript_list(self.context, self.node) def _infer_subscript_list(context, index): """ Handles slices in subscript nodes. """ if index == ':': # Like array[:] return ValueSet([iterable.Slice(context, None, None,...
ContextualizedSubscriptListNode
python
ansible__ansible
test/lib/ansible_test/_internal/become.py
{ "start": 2130, "end": 2516 }
class ____(Su): """Become using 'su' in ansible-test and then after bootstrapping use 'sudo' for other ansible commands.""" @classmethod def name(cls) -> str: """The name of this plugin.""" return 'su_sudo' @property def method(self) -> str: """The name of the Ansible becom...
SuSudo
python
spyder-ide__spyder
spyder/widgets/sidebardialog.py
{ "start": 2215, "end": 20121 }
class ____(QDialog, SpyderFontsMixin): """Sidebar dialog.""" # Constants ITEMS_MARGIN = 2 * AppStyle.MarginSize ITEMS_PADDING = ( AppStyle.MarginSize if (MAC or WIN) else 2 * AppStyle.MarginSize ) CONTENTS_WIDTH = 230 if MAC else (200 if WIN else 240) ICON_SIZE = 20 # To be set...
SidebarDialog
python
dagster-io__dagster
python_modules/libraries/dagster-dg-core/dagster_dg_core/utils/__init__.py
{ "start": 14163, "end": 25908 }
class ____(DgClickHelpMixin, ClickAliasedGroup): # pyright: ignore[reportIncompatibleMethodOverride] def __init__(self, *args, unlaunched: bool = False, **kwargs): """DgClickGroup with conditional hiding for unlaunched features. Args: unlaunched: If True, the group will be hidden unles...
DgClickGroup
python
django__django
django/contrib/sitemaps/__init__.py
{ "start": 5990, "end": 6951 }
class ____(Sitemap): priority = None changefreq = None def __init__(self, info_dict, priority=None, changefreq=None, protocol=None): self.queryset = info_dict["queryset"] self.date_field = info_dict.get("date_field") self.priority = self.priority or priority self.changefreq ...
GenericSitemap
python
scipy__scipy
benchmarks/benchmarks/lsq_problems.py
{ "start": 14178, "end": 15429 }
class ____(LSQBenchmarkProblem): """The problem of fitting kinetic parameters for an enzyme reaction, [1]_. Number of variables --- 4, number of residuals --- 11, no bounds. .. [1] Brett M. Averick et al. "The MINPACK-2 Test Problem Collection", p. 29 """ INITIAL_GUESSES = [ np....
EnzymeReaction
python
huggingface__transformers
src/transformers/models/vision_text_dual_encoder/processing_vision_text_dual_encoder.py
{ "start": 819, "end": 1668 }
class ____(ProcessorMixin): r""" Constructs a VisionTextDualEncoder processor which wraps an image processor and a tokenizer into a single processor. [`VisionTextDualEncoderProcessor`] offers all the functionalities of [`AutoImageProcessor`] and [`AutoTokenizer`]. See the [`~VisionTextDualEncoderPr...
VisionTextDualEncoderProcessor
python
mlflow__mlflow
mlflow/webhooks/types.py
{ "start": 4394, "end": 4953 }
class ____(TypedDict): """Payload sent when an alias is deleted from a model version. Example payload: .. code-block:: python { "name": "example_model", "alias": "example_alias", } """ name: str """The name of the registered model.""" alias: str ...
ModelVersionAliasDeletedPayload
python
PrefectHQ__prefect
src/prefect/server/database/orm_models.py
{ "start": 9915, "end": 11117 }
class ____(Base): """ SQLAlchemy model of artifacts. """ key: Mapped[Optional[str]] = mapped_column(index=True) task_run_id: Mapped[Optional[uuid.UUID]] = mapped_column(index=True) flow_run_id: Mapped[Optional[uuid.UUID]] = mapped_column(index=True) type: Mapped[Optional[str]] data: ...
Artifact
python
etianen__django-reversion
tests/test_app/tests/test_models.py
{ "start": 17321, "end": 17741 }
class ____(TestBase): def setUp(self): reversion.register(TestModelWithUniqueConstraint) def testTransactionInRollbackState(self): with reversion.create_revision(): try: TestModelWithUniqueConstraint.objects.create(name='A') TestModelWithUniqueConstr...
TransactionRollbackTest
python
kamyu104__LeetCode-Solutions
Python/koko-eating-bananas.py
{ "start": 33, "end": 534 }
class ____(object): def minEatingSpeed(self, piles, H): """ :type piles: List[int] :type H: int :rtype: int """ def possible(piles, H, K): return sum((pile-1)//K+1 for pile in piles) <= H left, right = 1, max(piles) while left <= right: ...
Solution
python
langchain-ai__langchain
libs/partners/perplexity/tests/integration_tests/test_chat_models_standard.py
{ "start": 237, "end": 927 }
class ____(ChatModelIntegrationTests): @property def chat_model_class(self) -> type[BaseChatModel]: return ChatPerplexity @property def chat_model_params(self) -> dict: return {"model": "sonar"} @pytest.mark.xfail(reason="TODO: handle in integration.") def test_double_messages_...
TestPerplexityStandard
python
tensorflow__tensorflow
tensorflow/python/framework/convert_to_constants.py
{ "start": 32928, "end": 33200 }
class ____(_FunctionConverterData): """Container for ConcreteFunction-based conversion data in Eager mode.""" def _eval(self, tensor): """Returns the value in the tensor. Must be implemented in sub-classes.""" return tensor.numpy()
_FunctionConverterDataInEager
python
joke2k__faker
faker/typing.py
{ "start": 931, "end": 1192 }
class ____: name: str timezones: Sequence[str] alpha_2_code: str alpha_3_code: str continent: str capital: str __all__ = ["OrderedDictType", "CreditCard", "CardType", "Country", "DateParseType", "HueType", "SexLiteral", "SeedType"]
Country
python
django__django
tests/defer/tests.py
{ "start": 11721, "end": 14620 }
class ____(AssertionMixin, TestCase): def test_defer_proxy(self): """ Ensure select_related together with only on a proxy model behaves as expected. See #17876. """ related = Secondary.objects.create(first="x1", second="x2") ChildProxy.objects.create(name="p1", value=...
TestDefer2
python
django__django
tests/i18n/test_compilation.py
{ "start": 915, "end": 2690 }
class ____(MessageCompilationTests): LOCALE = "es_AR" MO_FILE = "locale/%s/LC_MESSAGES/django.mo" % LOCALE MO_FILE_EN = "locale/en/LC_MESSAGES/django.mo" def test_bom_rejection(self): stderr = StringIO() with self.assertRaisesMessage( CommandError, "compilemessages generated...
PoFileTests
python
scikit-learn__scikit-learn
sklearn/externals/_arff.py
{ "start": 14924, "end": 15224 }
class ____: def __init__(self, values): self.values = {v: i for i, v in enumerate(values)} self.values[0] = 0 def __call__(self, value): try: return self.values[value] except KeyError: raise BadNominalValue(value)
EncodedNominalConversor
python
MongoEngine__mongoengine
tests/fields/test_enum_field.py
{ "start": 403, "end": 562 }
class ____(Document): status = EnumField(Status) statuses = ListField(EnumField(Status)) color_mapping = DictField(EnumField(Color))
ModelComplexEnum
python
pandas-dev__pandas
pandas/tests/io/excel/test_writers.py
{ "start": 2075, "end": 12228 }
class ____: @pytest.mark.parametrize( "header,expected", [(None, [np.nan] * 4), (0, {"Unnamed: 0": [np.nan] * 3})], ) def test_read_one_empty_col_no_header(self, tmp_excel, header, expected): # xref gh-12292 filename = "no_header" df = DataFrame([["", 1, 100], ["", 2,...
TestRoundTrip
python
scrapy__scrapy
tests/test_squeues_request.py
{ "start": 654, "end": 3319 }
class ____(ABC): @property @abstractmethod def is_fifo(self) -> bool: raise NotImplementedError @pytest.mark.parametrize("test_peek", [True, False]) def test_one_element(self, q: queuelib.queue.BaseQueue, test_peek: bool): if test_peek and not HAVE_PEEK: pytest.skip("The...
TestRequestQueueBase
python
huggingface__transformers
src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py
{ "start": 30083, "end": 30767 }
class ____(nn.Module): """XLM-RoBERTa-XL Head for masked language modeling.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.decode...
XLMRobertaXLLMHead
python
pandas-dev__pandas
pandas/tests/series/methods/test_unique.py
{ "start": 138, "end": 2219 }
class ____: def test_unique_uint64(self): ser = Series([1, 2, 2**63, 2**63], dtype=np.uint64) res = ser.unique() exp = np.array([1, 2, 2**63], dtype=np.uint64) tm.assert_numpy_array_equal(res, exp) def test_unique_data_ownership(self): # it works! GH#1807 Series(...
TestUnique
python
sqlalchemy__sqlalchemy
test/orm/inheritance/test_assorted_poly.py
{ "start": 1799, "end": 5342 }
class ____(fixtures.MappedTest): """test self-referential relationships on polymorphic mappers""" @classmethod def define_tables(cls, metadata): global people, managers people = Table( "people", metadata, Column( "person_id", ...
RelationshipTest1
python
python-pillow__Pillow
Tests/test_file_png.py
{ "start": 29644, "end": 30242 }
class ____(PillowLeakTestCase): mem_limit = 2 * 1024 # max increase in K iterations = 100 # Leak is 56k/iteration, this will leak 5.6megs def test_leak_load(self, monkeypatch: pytest.MonkeyPatch) -> None: with open("Tests/images/hopper.png", "rb") as f: DATA = BytesIO(f.read(16 * 1024...
TestTruncatedPngPLeaks
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassConverter1.py
{ "start": 268, "end": 811 }
class ____: ... def converter_simple(s: str) -> int: return int(s) def converter_with_param_before_args(s: str, *args: int, **kwargs: int) -> int: return int(s) def converter_with_args(*args: str) -> int: return int(args[0]) def converter_with_extra_defaulted_params( s: str, extra: int = 1, *, e...
ModelBase
python
getsentry__sentry
src/sentry/preprod/api/bases/preprod_artifact_endpoint.py
{ "start": 313, "end": 485 }
class ____(APIException): status_code = status.HTTP_404_NOT_FOUND default_detail = "The requested preprod artifact does not exist"
PreprodArtifactResourceDoesNotExist
python
django__django
django/db/models/aggregates.py
{ "start": 13082, "end": 13456 }
class ____(NumericOutputFieldMixin, Aggregate): name = "Variance" arity = 1 def __init__(self, expression, sample=False, **extra): self.function = "VAR_SAMP" if sample else "VAR_POP" super().__init__(expression, **extra) def _get_repr_options(self): return {**super()._get_repr_...
Variance
python
google__flatbuffers
tests/flatc/flatc_schema_tests.py
{ "start": 636, "end": 2233 }
class ____: def EnumValAttributes(self): # Generate .bfbs schema first flatc( ["--schema", "--binary", "--bfbs-builtins", "enum_val_attributes.fbs"] ) assert_file_exists("enum_val_attributes.bfbs") # Then turn it into JSON flatc([ "--json", "--strict-json", st...
SchemaTests
python
ray-project__ray
doc/source/serve/doc_code/app_builder.py
{ "start": 820, "end": 1383 }
class ____: def __init__(self, message: str): self._message = message print("Message:", self._message) def __call__(self, request): return self._message def typed_app_builder(args: HelloWorldArgs) -> Application: return HelloWorld.bind(args.message) # __end_typed_builder__ serv...
HelloWorld
python
pandas-dev__pandas
pandas/tests/tools/test_to_datetime.py
{ "start": 19341, "end": 66148 }
class ____: def test_to_datetime_mixed_string_resos(self): # GH#62801 vals = [ "2016-01-01 01:02:03", "2016-01-01 01:02:03.001", "2016-01-01 01:02:03.001002", "2016-01-01 01:02:03.001002003", ] expected = DatetimeIndex([Timestamp(x).as_...
TestToDatetime
python
getsentry__sentry
tests/sentry/lang/javascript/test_sourcemaps.py
{ "start": 3220, "end": 3442 }
class ____(TestCase): def test_basic(self) -> None: smap_view = SourceMapView.from_json_bytes(sourcemap) assert list(smap_view.iter_sources()) == [(0, "foo/file1.js"), (1, "foo/file2.js")]
IterSourcesTest
python
bokeh__bokeh
src/bokeh/core/property/numeric.py
{ "start": 5936, "end": 7009 }
class ____(Float): """ Accept floating point percentage values. ``Percent`` can be useful and semantically meaningful for specifying things like alpha values and extents. Args: default (float, optional) : A default value for attributes created from this property to have. h...
Percent
python
google__pytype
pytype/tests/test_attr2.py
{ "start": 1022, "end": 7751 }
class ____(test_base.BaseTest): """Tests for attr.ib with converters.""" def test_annotated_converter(self): self.Check(""" import attr def convert(input: str) -> int: return int(input) @attr.s class Foo: x = attr.ib(converter=convert) Foo(x='123') """) def ...
TestAttribConverters
python
spack__spack
lib/spack/spack/util/spack_yaml.py
{ "start": 11699, "end": 17515 }
class ____: """Handles the loading and dumping of Spack's YAML files.""" def __init__(self, yaml_type: YAMLType) -> None: self.yaml = YAML(typ="rt", pure=True) if yaml_type == YAMLType.GENERIC_YAML: self.yaml.Representer = SafeRepresenter elif yaml_type == YAMLType.ANNOTATED...
ConfigYAML
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 114955, "end": 115754 }
class ____(SimpleHandlerTestCase): class Handler(RequestHandler): def get(self): self.set_status(401) self.set_header("WWW-Authenticate", 'Basic realm="something"') if self.get_argument("finish_value", ""): raise Finish("authentication required") ...
FinishExceptionTest
python
ethereum__web3.py
web3/contract/contract.py
{ "start": 6859, "end": 7084 }
class ____(BaseContractEvents[ContractEvent]): def __init__( self, abi: ABI, w3: "Web3", address: ChecksumAddress | None = None ) -> None: super().__init__(abi, w3, ContractEvent, address)
ContractEvents
python
doocs__leetcode
solution/2300-2399/2351.First Letter to Appear Twice/Solution.py
{ "start": 0, "end": 185 }
class ____: def repeatedCharacter(self, s: str) -> str: cnt = Counter() for c in s: cnt[c] += 1 if cnt[c] == 2: return c
Solution
python
huggingface__transformers
tests/models/lfm2_moe/test_modeling_lfm2_moe.py
{ "start": 1641, "end": 6261 }
class ____(CausalLMModelTest, unittest.TestCase): all_model_classes = (Lfm2MoeModel, Lfm2MoeForCausalLM) if is_torch_available() else () pipeline_model_mapping = ( { "feature-extraction": Lfm2MoeModel, "text-generation": Lfm2MoeForCausalLM, } if is_torch_available...
Lfm2MoeModelTest
python
ionelmc__pytest-benchmark
src/pytest_benchmark/storage/elasticsearch.py
{ "start": 387, "end": 933 }
class ____(JSONSerializer): def default(self, data): if isinstance(data, (date, datetime)): return data.isoformat() elif isinstance(data, Decimal): return float(data) elif isinstance(data, uuid.UUID): return str(data) else: return f'UNS...
BenchmarkJSONSerializer
python
PrefectHQ__prefect
tests/infrastructure/provisioners/test_ecs.py
{ "start": 9360, "end": 13116 }
class ____: async def test_requires_provisioning_no_block(self, credentials_block_resource): needs_provisioning = await credentials_block_resource.requires_provisioning() assert needs_provisioning @pytest.mark.usefixtures("existing_credentials_block") async def test_requires_provisioning_w...
TestCredentialsBlockResource
python
neetcode-gh__leetcode
python/1603-design-parking-system.py
{ "start": 0, "end": 476 }
class ____: def __init__(self, big: int, medium: int, small: int): # [total_occupied, max_capacity] self.parking = { 1: [0 ,big], 2: [0, medium], 3: [0, small] } def addCar(self, carType: int) -> bool: new_total = self.parking[carTyp...
ParkingSystem
python
getsentry__sentry
src/sentry/rules/conditions/event_attribute.py
{ "start": 8465, "end": 9022 }
class ____(AttributeHandler): minimum_path_length = 2 @classmethod def _handle(cls, path: list[str], event: GroupEvent) -> list[str]: if path[1] not in ("type", "value"): return [] values = getattr(event.interfaces.get("exception"), "values", []) result = [] for...
ExceptionAttributeHandler
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_health/asset_materialization_health.py
{ "start": 3770, "end": 14489 }
class ____(LoadableBy[AssetKey]): """For tracking the materialization health of an asset, we only care about the most recent completed materialization attempt for each asset/partition. This record keeps track of the assets/partitions that have ever been successfully materialized and those that are currently...
AssetMaterializationHealthState
python
huggingface__transformers
src/transformers/models/llava_onevision/modeling_llava_onevision.py
{ "start": 6258, "end": 11808 }
class ____(nn.Module): def __init__(self, config: LlavaOnevisionConfig): super().__init__() # We have hidden_size * the number of vision feature layers num_feature_layers = 1 if isinstance(config.vision_feature_layer, int) else len(config.vision_feature_layer) self.linear_1 = nn.Line...
LlavaOnevisionMultiModalProjector
python
sphinx-doc__sphinx
sphinx/domains/c/_ast.py
{ "start": 11534, "end": 12524 }
class ____(ASTExpression): def __init__(self, expr: ASTExpression) -> None: self.expr = expr def __eq__(self, other: object) -> bool: if not isinstance(other, ASTParenExpr): return NotImplemented return self.expr == other.expr def __hash__(self) -> int: return h...
ASTParenExpr
python
getsentry__sentry
src/sentry/api/bases/organizationmember.py
{ "start": 1975, "end": 2411 }
class ____(serializers.IntegerField): """ Allow "me" in addition to integers """ def to_internal_value(self, data: float | int | str) -> Any: if data == "me": return data return super().to_internal_value(data) def run_validation(self, data: object | None = empty) -> obj...
MemberIdField
python
kamyu104__LeetCode-Solutions
Python/number-of-ways-to-select-buildings.py
{ "start": 52, "end": 495 }
class ____(object): def numberOfWays(self, s): """ :type s: str :rtype: int """ K = 3 dp = [[0]*2 for _ in xrange(K)] # dp[i][j]: number of ways of selecting i+1 buildings ending with type j for c in s: j = ord(c)-ord('0') dp[0][j] += ...
Solution
python
huggingface__transformers
src/transformers/models/pegasus_x/modeling_pegasus_x.py
{ "start": 5834, "end": 11436 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Opti...
PegasusXAttention
python
pytorch__pytorch
torch/_dynamo/exc.py
{ "start": 3129, "end": 3503 }
class ____(TorchDynamoException): def __init__(self) -> None: super().__init__( textwrap.dedent( """ Must call `torch._dynamo.reset()` before changing backends. Detected two calls to `torch.compile()` with a different backend compiler arguments. ...
ResetRequired
python
kubernetes-client__python
kubernetes/client/models/v1_api_resource.py
{ "start": 383, "end": 13876 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1APIResource
python
keon__algorithms
algorithms/linkedlist/kth_to_last.py
{ "start": 0, "end": 2707 }
class ____(): def __init__(self, val=None): self.val = val self.next = None def kth_to_last_eval(head, k): """ This is a suboptimal, hacky method using eval(), which is not safe for user input. We guard against danger by ensuring k in an int """ if not isinstance(k, int) or no...
Node
python
bokeh__bokeh
src/bokeh/resources.py
{ "start": 7713, "end": 7896 }
class ____: urls: UrlsFn messages: list[RuntimeMessage] = field(default_factory=list) hashes: HashesFn | None = None ResourceAttr = Literal["__css__", "__javascript__"]
Urls
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 929255, "end": 930034 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "actor", "created_at", "current_title", "previous_title", "subject", ) actor = sgqlc.types.Field(Actor, graphql_name="actor") ...
RenamedTitleEvent
python
Pylons__pyramid
docs/tutorials/wiki/src/tests/tests/test_views.py
{ "start": 30, "end": 350 }
class ____: def test_it_redirects_to_front_page(self): from tutorial.views.default import view_wiki context = testing.DummyResource() request = testing.DummyRequest() response = view_wiki(context, request) assert response.location == 'http://example.com/FrontPage'
Test_view_wiki
python
dask__dask
dask/dataframe/dask_expr/_indexing.py
{ "start": 10191, "end": 10703 }
class ____(LocList): _parameters = ["meta", "cindexer"] def _lower(self): return None @functools.cached_property def _meta(self): if self.cindexer is None: return self.operand("meta") else: return self.operand("meta").loc[:, self.cindexer] @functool...
LocEmpty
python
pytorch__pytorch
test/distributed/test_symmetric_memory.py
{ "start": 45962, "end": 49107 }
class ____(TestCase): @requires_cuda @skipIf( not TEST_WITH_ROCM and _get_torch_cuda_version() < (12, 0), "stream_write_value32 currently only supports cuda version>=12.0", ) @skipIf( not PLATFORM_SUPPORTS_SYMM_MEM, "SymmMem is not supported on this ROCm arch" ) def test_...
SymmMemSingleProcTest
python
modin-project__modin
modin/config/envvars.py
{ "start": 23498, "end": 23690 }
class ____(EnvironmentVariable, type=ExactStr): """What password to use for connecting to Redis.""" varname = "MODIN_REDIS_PASSWORD" default = secrets.token_hex(32)
RayRedisPassword
python
spyder-ide__spyder
spyder/widgets/collectionseditor.py
{ "start": 2807, "end": 3412 }
class ____: Close = 'close' Copy = 'copy_action' Duplicate = 'duplicate_action' Edit = 'edit_action' Histogram = 'histogram_action' Insert = 'insert_action' InsertAbove = 'insert_above_action' InsertBelow = 'insert_below_action' Paste = 'paste_action' Plot = 'plot_action' Ref...
CollectionsEditorActions
python
PrefectHQ__prefect
tests/server/models/test_logs.py
{ "start": 2085, "end": 4763 }
class ____: async def test_read_logs_timestamp_after_inclusive(self, session, logs, log_data): after = log_data[1].timestamp log_filter = LogFilter(timestamp={"after_": after}) logs = await models.logs.read_logs( session=session, log_filter=log_filter, sort=LogSort.TIMESTAMP_ASC ...
TestReadLogs
python
django__django
tests/managers_regress/models.py
{ "start": 1755, "end": 1893 }
class ____(AbstractBase1, AbstractBase3): data = models.CharField(max_length=25) def __str__(self): return self.data
Child3
python
walkccc__LeetCode
solutions/1043. Partition Array for Maximum Sum/1043.py
{ "start": 0, "end": 314 }
class ____: def maxSumAfterPartitioning(self, arr: list[int], k: int) -> int: n = len(arr) dp = [0] * (n + 1) for i in range(1, n + 1): mx = -math.inf for j in range(1, min(i, k) + 1): mx = max(mx, arr[i - j]) dp[i] = max(dp[i], dp[i - j] + mx * j) return dp[n]
Solution
python
huggingface__transformers
src/transformers/generation/logits_process.py
{ "start": 31819, "end": 35673 }
class ____(LogitsProcessor): """ [`LogitsProcessor`] that performs min-p, i.e. keeps all tokens that are above a minimum probability, scaled by the probability of the most likely token. As a result, the filter becomes more aggressive in the presence of high-probability tokens, which is a sign of a confi...
MinPLogitsWarper
python
modin-project__modin
modin/core/storage_formats/pandas/parsers.py
{ "start": 22672, "end": 23991 }
class ____(PandasParser): @staticmethod @doc(_doc_parse_func, parameters=_doc_parse_parameters_common) def parse(fname, **kwargs): num_splits = kwargs.pop("num_splits", None) start = kwargs.pop("start", None) end = kwargs.pop("end", None) if start is not None and end is not N...
PandasJSONParser
python
joke2k__faker
tests/providers/test_internet.py
{ "start": 28449, "end": 29440 }
class ____: """Test ar_AA internet provider methods""" @patch( "faker.providers.internet.Provider.user_name", lambda x: "اصيل", ) def test_ascii_safe_email(self, faker): email = faker.ascii_safe_email() validate_email(email) assert email.split("@")[0] == "asyl" ...
TestArAa
python
pypa__setuptools
setuptools/_distutils/tests/test_dist.py
{ "start": 456, "end": 711 }
class ____(Command): """Sample distutils extension command.""" user_options: ClassVar[list[tuple[str, str, str]]] = [ ("sample-option=", "S", "help text"), ] def initialize_options(self): self.sample_option = None
test_dist
python
pypa__pipenv
pipenv/patched/pip/_internal/utils/misc.py
{ "start": 19116, "end": 23570 }
class ____(BuildBackendHookCaller): def __init__( self, config_holder: Any, source_dir: str, build_backend: str, backend_path: Optional[str] = None, runner: Optional[Callable[..., None]] = None, python_executable: Optional[str] = None, ): super()._...
ConfiguredBuildBackendHookCaller
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_reflection.py
{ "start": 975, "end": 6319 }
class ____(DeclarativeReflectionBase): @classmethod def define_tables(cls, metadata): Table( "users", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("name", String(50)), te...
DeclarativeReflectionTest
python
python__mypy
mypyc/ir/class_ir.py
{ "start": 3158, "end": 3329 }
class ____(NamedTuple): cls: "ClassIR" # noqa: UP037 name: str method: FuncIR shadow_method: FuncIR | None VTableEntries = list[VTableMethod]
VTableMethod
python
pytest-dev__pytest-xdist
testing/test_dsession.py
{ "start": 10850, "end": 18113 }
class ____: def test_ideal_case(self, pytester: pytest.Pytester) -> None: config = pytester.parseconfig("--tx=2*popen") sched = WorkStealingScheduling(config) node1, node2 = MockNode(), MockNode() sched.add_node(node1) sched.add_node(node2) collection = [f"test_workst...
TestWorkStealingScheduling
python
huggingface__transformers
src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
{ "start": 25537, "end": 26691 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.layer = nn.ModuleList( [InstructBlipVideoQFormerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.gradient_checkpointing = False @c...
InstructBlipVideoQFormerEncoder
python
pydantic__pydantic
pydantic/_internal/_model_construction.py
{ "start": 35423, "end": 38277 }
class ____: """Wrapper for `weakref.ref` that enables `pickle` serialization. Cloudpickle fails to serialize `weakref.ref` objects due to an arcane error related to abstract base classes (`abc.ABC`). This class works around the issue by wrapping `weakref.ref` instead of subclassing it. See https:/...
_PydanticWeakRef
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/roles.py
{ "start": 4813, "end": 5024 }
class ____(AllowsLambdaRole, UsesInspection, StructuralRole): __slots__ = () _role_name = ( "Join target, typically a FROM expression, or ORM " "relationship attribute" )
JoinTargetRole
python
django__django
django/db/migrations/utils.py
{ "start": 245, "end": 4401 }
class ____: def __init__(self, obj): self.pattern = obj.pattern self.flags = obj.flags def __eq__(self, other): if not isinstance(other, RegexObject): return NotImplemented return self.pattern == other.pattern and self.flags == other.flags def get_migration_name_ti...
RegexObject