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
fluentpython__example-code-2e
14-inheritance/strkeydict_dictsub.py
{ "start": 1243, "end": 2162 }
class ____(dict): def __init__(self, iterable=None, **kwds): super().__init__() self.update(iterable, **kwds) def __missing__(self, key): if isinstance(key, str): raise KeyError(key) return self[str(key)] def __contains__(self, key): return key in self....
StrKeyDict
python
huggingface__transformers
src/transformers/models/ernie4_5_moe/configuration_ernie4_5_moe.py
{ "start": 870, "end": 10535 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Ernie4_5_MoeModel`]. It is used to instantiate a Ernie 4.5 MoE model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a si...
Ernie4_5_MoeConfig
python
PrefectHQ__prefect
tests/test_cache_policies.py
{ "start": 1191, "end": 4866 }
class ____: def test_initializes(self): policy = Inputs() assert isinstance(policy, CachePolicy) def test_key_varies_on_inputs(self): policy = Inputs() none_key = policy.compute_key(task_ctx=None, inputs=None, flow_parameters=None) x_key = policy.compute_key( ...
TestInputsPolicy
python
pytorch__pytorch
torch/onnx/_internal/exporter/_capture_strategies.py
{ "start": 6765, "end": 9040 }
class ____(CaptureStrategy): def _capture( self, model, args, kwargs, dynamic_shapes ) -> torch.export.ExportedProgram: with ( # Support the dynamism with 0/1 input dim torch.fx.experimental._config.patch(backed_size_oblivious=True), # type: ignore[attr-defined] ...
TorchExportNonStrictStrategy
python
astropy__astropy
astropy/modeling/fitting.py
{ "start": 67414, "end": 70571 }
class ____(Fitter): """ Sequential Least Squares Programming (SLSQP) optimization algorithm and least squares statistic. Raises ------ ModelLinearityError A linear model is passed to a nonlinear fitter Notes ----- See also the `~astropy.modeling.optimizers.SLSQP` optimizer....
SLSQPLSQFitter
python
jschneier__django-storages
tests/test_s3.py
{ "start": 39308, "end": 43685 }
class ____(TestCase): """ Using mock_aws as a class decorator automatically decorates methods, but NOT classmethods or staticmethods. """ def setUp(cls): super().setUp() cls.storage = s3.S3Storage() cls.bucket = cls.storage.connection.Bucket(settings.AWS_STORAGE_BUCKET_NAME...
S3StorageTestsWithMoto
python
streamlit__streamlit
lib/tests/streamlit/components/v2/test_bidi_component.py
{ "start": 12327, "end": 39320 }
class ____(DeltaGeneratorTestCase): """Test the bidi_component functionality.""" def setUp(self): super().setUp() # Create a mock component manager for testing self.mock_component_manager = BidiComponentManager() # Patch the Runtime to return our mock component manager ...
BidiComponentTest
python
tiangolo__fastapi
docs_src/response_model/tutorial001.py
{ "start": 115, "end": 562 }
class ____(BaseModel): name: str description: Union[str, None] = None price: float tax: Union[float, None] = None tags: List[str] = [] @app.post("/items/", response_model=Item) async def create_item(item: Item) -> Any: return item @app.get("/items/", response_model=List[Item]) async def read...
Item
python
streamlit__streamlit
lib/streamlit/elements/heading.py
{ "start": 1229, "end": 1417 }
class ____(Enum): TITLE_TAG = "h1" HEADER_TAG = "h2" SUBHEADER_TAG = "h3" Anchor: TypeAlias = str | Literal[False] | None Divider: TypeAlias = bool | str | None
HeadingProtoTag
python
huggingface__transformers
src/transformers/models/lfm2_moe/modeling_lfm2_moe.py
{ "start": 30091, "end": 33625 }
class ____(Lfm2MoePreTrainedModel): def __init__(self, config: Lfm2MoeConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.l...
Lfm2MoeModel
python
psf__black
src/blib2to3/pgen2/pgen.py
{ "start": 359, "end": 406 }
class ____(grammar.Grammar): pass
PgenGrammar
python
getsentry__sentry
tests/sentry/models/test_release.py
{ "start": 56460, "end": 62460 }
class ____(TestCase): @receivers_raise_on_send() def test_simple(self) -> None: org = self.create_organization(owner=Factories.create_user()) project = self.create_project(organization=org, name="foo") group = self.create_group(project=project) repo = Repository.objects.create(o...
ClearCommitsTestCase
python
jmcnamara__XlsxWriter
xlsxwriter/test/table/test_table05.py
{ "start": 481, "end": 1975 }
class ____(unittest.TestCase): """ Test assembling a complete Table file. """ def test_assemble_xml_file(self): """Test writing a table""" self.maxDiff = None worksheet = Worksheet() worksheet.worksheet_meta = WorksheetMeta() worksheet.str_table = SharedStringT...
TestAssembleTable
python
django__django
tests/i18n/tests.py
{ "start": 77535, "end": 77880 }
class ____(ResolutionOrderI18NTests): def test_locale_paths_translation(self): self.assertGettext("Time", "LOCALE_PATHS") def test_locale_paths_override_app_translation(self): with self.settings(INSTALLED_APPS=["i18n.resolution"]): self.assertGettext("Time", "LOCALE_PATHS")
LocalePathsResolutionOrderI18NTests
python
PrefectHQ__prefect
tests/utilities/test_collections.py
{ "start": 3020, "end": 4401 }
class ____: """ Checks that the Pydantic test objects defined in this file behave as expected. These tests do not cover Prefect functionality and may break if Pydantic introduces breaking changes. """ def test_private_pydantic_behaves_as_expected(self): input = PrivatePydantic(x=1) ...
TestPydanticObjects
python
TheAlgorithms__Python
dynamic_programming/edit_distance.py
{ "start": 346, "end": 3435 }
class ____: """ Use : solver = EditDistance() editDistanceResult = solver.solve(firstString, secondString) """ def __init__(self): self.word1 = "" self.word2 = "" self.dp = [] def __min_dist_top_down_dp(self, m: int, n: int) -> int: if m == -1:...
EditDistance
python
bokeh__bokeh
src/bokeh/models/widgets/pickers.py
{ "start": 4674, "end": 7681 }
class ____(HasProps): """ Common properties for date-like picker widgets. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) disabled_dates = Nullable(List(Either(Date, Tuple(Date, Date))), default=None, h...
DateCommon
python
allegroai__clearml
clearml/backend_api/services/v2_13/models.py
{ "start": 61400, "end": 78108 }
class ____(Request): """ Get all models :param name: Get only models whose name matches this pattern (python regular expression syntax) :type name: str :param user: List of user IDs used to filter results by the model's creating user :type user: Sequence[str] :param ready: I...
GetAllRequest
python
tornadoweb__tornado
tornado/test/locks_test.py
{ "start": 11116, "end": 13919 }
class ____(AsyncTestCase): @gen_test def test_context_manager(self): sem = locks.Semaphore() with (yield sem.acquire()) as yielded: self.assertIsNone(yielded) # Semaphore was released and can be acquired again. self.assertTrue(asyncio.ensure_future(sem.acquire()).don...
SemaphoreContextManagerTest
python
doocs__leetcode
solution/3600-3699/3668.Restore Finishing Order/Solution.py
{ "start": 0, "end": 194 }
class ____: def recoverOrder(self, order: List[int], friends: List[int]) -> List[int]: d = {x: i for i, x in enumerate(order)} return sorted(friends, key=lambda x: d[x])
Solution
python
django__django
tests/forms_tests/field_tests/test_genericipaddressfield.py
{ "start": 193, "end": 9451 }
class ____(SimpleTestCase): def test_generic_ipaddress_invalid_arguments(self): with self.assertRaises(ValueError): GenericIPAddressField(protocol="hamster") with self.assertRaises(ValueError): GenericIPAddressField(protocol="ipv4", unpack_ipv4=True) def test_generic_ipa...
GenericIPAddressFieldTest
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/model_service.py
{ "start": 19883, "end": 23041 }
class ____(GoogleCloudBaseOperator): """ Lists Model versions in a Location. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param model_id: Required. The ID of the ...
ListModelVersionsOperator
python
vyperlang__vyper
vyper/semantics/analysis/base.py
{ "start": 4127, "end": 5009 }
class ____(AnalysisResult): alias: str # the name in the namespace qualified_module_name: str # for error messages compiler_input: CompilerInput # to recover file info for ast export parsed: Any # (json) abi | AST _typ: Any = None # type to be filled in during analysis @property def ty...
ImportInfo
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dag_versions.py
{ "start": 1395, "end": 1572 }
class ____(BaseModel): """DAG Version Collection serializer for responses.""" dag_versions: Iterable[DagVersionResponse] total_entries: int
DAGVersionCollectionResponse
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE796.py
{ "start": 332, "end": 420 }
class ____(Enum): A = 1.0 B = True C = False D = False # PIE796
FakeEnum5
python
catalyst-team__catalyst
catalyst/contrib/data/reader_cv.py
{ "start": 1412, "end": 2823 }
class ____(IReader): """Mask reader abstraction. Reads masks from a `csv` dataset.""" def __init__( self, input_key: str, output_key: Optional[str] = None, rootpath: Optional[str] = None, clip_range: Tuple[Union[int, float], Union[int, float]] = (0, 1), ): ""...
MaskReader
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/serializers/action_handler_serializer.py
{ "start": 288, "end": 487 }
class ____(TypedDict): id: str name: str installationId: str installationUuid: str status: int settings: NotRequired[dict[str, Any]] title: NotRequired[str]
SentryAppContext
python
pytorch__pytorch
torchgen/api/types/types_base.py
{ "start": 4256, "end": 5000 }
class ____(CType): elem: CType def cpp_type(self, *, strip_ref: bool = False) -> str: if strip_ref: return self.elem.cpp_type(strip_ref=strip_ref) return f"{self.elem.cpp_type()} &" def remove_const_ref(self) -> CType: return self.elem.remove_const_ref() # A NamedCTyp...
MutRefCType
python
TheAlgorithms__Python
knapsack/tests/test_greedy_knapsack.py
{ "start": 77, "end": 2343 }
class ____(unittest.TestCase): """ Test cases for knapsack """ def test_sorted(self): """ kp.calc_profit takes the required argument (profit, weight, max_weight) and returns whether the answer matches to the expected ones """ profit = [10, 20, 30, 40, 50, 60] ...
TestClass
python
apache__airflow
task-sdk/src/airflow/sdk/execution_time/comms.py
{ "start": 21572, "end": 21660 }
class ____(BaseModel): type: Literal["SentFDs"] = "SentFDs" fds: list[int]
SentFDs
python
google__jax
tests/lax_test.py
{ "start": 156619, "end": 163874 }
class ____(jtu.JaxTestCase): def _Check(self, make_const, expected): # check casting to ndarray works asarray_result = np.asarray(make_const()) # check passing as an argument works (should hit constant handler) zero = np.array(0, expected.dtype) argument_result = lax.add(zero, make_const()) ...
LazyConstantTest
python
kamyu104__LeetCode-Solutions
Python/find-unique-binary-string.py
{ "start": 361, "end": 865 }
class ____(object): def findDifferentBinaryString(self, nums): """ :type nums: List[str] :rtype: str """ lookup = set(map(lambda x: int(x, 2), nums)) # Time: O(k * n) = O(n^2) return next(bin(i)[2:].zfill(len(nums[0])) for i in xrange(2**len(nums[0])) if i not in loo...
Solution2
python
scrapy__scrapy
tests/test_settings/__init__.py
{ "start": 21777, "end": 21837 }
class ____: pass Component1Alias = Component1
Component1
python
doocs__leetcode
solution/0000-0099/0026.Remove Duplicates from Sorted Array/Solution.py
{ "start": 0, "end": 220 }
class ____: def removeDuplicates(self, nums: List[int]) -> int: k = 0 for x in nums: if k == 0 or x != nums[k - 1]: nums[k] = x k += 1 return k
Solution
python
coleifer__peewee
tests/sqliteq.py
{ "start": 698, "end": 5858 }
class ____(object): database_config = {} n_rows = 20 n_threads = 20 def setUp(self): super(BaseTestQueueDatabase, self).setUp() User._meta.database = db with db: db.create_tables([User], safe=True) User._meta.database = \ self.database = get_...
BaseTestQueueDatabase
python
dask__distributed
distributed/http/scheduler/json.py
{ "start": 1646, "end": 1746 }
class ____(RequestHandler): def get(self): self.write(self.server.identity())
IdentityJSON
python
django__django
django/db/migrations/operations/models.py
{ "start": 14069, "end": 15306 }
class ____(ModelOperation): """Drop a model's table.""" category = OperationCategory.REMOVAL def deconstruct(self): kwargs = { "name": self.name, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.remove_mod...
DeleteModel
python
hyperopt__hyperopt
hyperopt/tests/unit/test_tpe.py
{ "start": 1315, "end": 5595 }
class ____(unittest.TestCase): def setUp(self): self.rng = np.random.default_rng(234) def test_mu_is_used_correctly(self): assert np.allclose(10, GMM1([1], [10.0], [0.0000001], rng=self.rng)) def test_sigma_is_used_correctly(self): samples = GMM1([1], [0.0], [10.0], size=[1000], rn...
TestGMM1
python
pytorch__pytorch
test/distributed/checkpoint/test_pg_transport.py
{ "start": 12707, "end": 14859 }
class ____(TestCase): def test_prepare_state_dict_basic(self): """Test basic state dict preparation.""" state_dict = {"weight": torch.randn(3, 4), "bias": torch.randn(4)} device = torch.device("cpu") meta, tensors = _prepare_state_dict(state_dict, device) # Check metadata ...
TestPrepareStateDict
python
Textualize__textual
src/textual/widgets/_selection_list.py
{ "start": 1108, "end": 1209 }
class ____(TypeError): """Type of an error raised if a selection is badly-formed."""
SelectionError
python
spyder-ide__spyder
spyder/plugins/ipythonconsole/utils/websocket_client.py
{ "start": 12852, "end": 13312 }
class ____: def __init__(self): AsyncDispatcher(loop="ipythonconsole", early_return=False)( self._create_queue )() async def _create_queue(self): self.shell = asyncio.Queue() self.iopub = asyncio.Queue() self.stdin = asyncio.Queue() self.control = asy...
_ChannelQueues
python
getsentry__sentry
tests/sentry/issues/auto_source_code_config/test_process_event.py
{ "start": 17899, "end": 19695 }
class ____(LanguageSpecificDeriveCodeMappings): platform = "python" def test_backslash_filename_simple(self) -> None: # The lack of a \ after the drive letter in the third frame signals that # this is a relative path. This may be unlikely to occur in practice, # but worth testing noneth...
TestBackSlashDeriveCodeMappings
python
wandb__wandb
wandb/vendor/pygments/lexers/perl.py
{ "start": 10459, "end": 32006 }
class ____(ExtendedRegexLexer): """ For `Perl 6 <http://www.perl6.org>`_ source code. .. versionadded:: 2.0 """ name = 'Perl6' aliases = ['perl6', 'pl6'] filenames = ['*.pl', '*.pm', '*.nqp', '*.p6', '*.6pl', '*.p6l', '*.pl6', '*.6pm', '*.p6m', '*.pm6', '*.t'] mimetype...
Perl6Lexer
python
getsentry__sentry
src/sentry/utils/email/message_builder.py
{ "start": 3393, "end": 10264 }
class ____: def __init__( self, subject: str, context: Mapping[str, Any] | None = None, template: str | None = None, html_template: str | None = None, body: str = "", html_body: str | None = None, headers: Mapping[str, str] | None = None, refer...
MessageBuilder
python
davidhalter__parso
parso/python/errors.py
{ "start": 18295, "end": 18695 }
class ____(Rule): code = 901 def _get_message(self, message, node): message = super()._get_message(message, node) if ( "f-string" not in message and _any_fstring_error(self._normalizer.version, node) ): message = "f-string: " + message return ...
SyntaxRule
python
has2k1__plotnine
plotnine/themes/themeable.py
{ "start": 57108, "end": 57537 }
class ____(themeable): """ Justification of legends placed at the top Parameters ---------- theme_element : Literal["left", "center", "right"] | float How to justify the entire group with 1 or more guides. i.e. How to slide the legend along the top row. If a float, it should...
legend_justification_top
python
openai__openai-python
src/openai/types/responses/response_apply_patch_tool_call.py
{ "start": 618, "end": 781 }
class ____(BaseModel): path: str """Path of the file to delete.""" type: Literal["delete_file"] """Delete the specified file."""
OperationDeleteFile
python
django__django
tests/generic_views/models.py
{ "start": 1397, "end": 1470 }
class ____(models.Model): event_date = models.DateTimeField()
BookSigning
python
great-expectations__great_expectations
contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/tests/conftest.py
{ "start": 738, "end": 11107 }
class ____: """ This class should ideally be named "MockBaseProfiler"; however, it has to be called "BaseProfiler", because its "load()" method returns "BaseProfiler" type, which is type of class itself (using "fluent" programming style). """ # noinspection PyMethodMayBeStatic,PyMethodParameters ...
BaseProfiler
python
jina-ai__jina
tests/unit/jaml/test_gateway_parse.py
{ "start": 122, "end": 1646 }
class ____(Gateway): async def setup_server(self): self.server = 'dummy server' async def run_server(self): self.logger.info(self.server) async def shutdown(self): pass def test_cls_from_tag(): assert JAML.cls_from_tag('MyDummyGateway') == MyDummyGateway assert JAML.cls_f...
MyDummyGateway
python
kamyu104__LeetCode-Solutions
Python/flip-game.py
{ "start": 52, "end": 732 }
class ____(object): def generatePossibleNextMoves(self, s): """ :type s: str :rtype: List[str] """ res = [] i, n = 0, len(s) - 1 while i < n: # O(n) time if s[i] == '+': while i < n and s[i+1] == '...
Solution
python
aio-libs__aiohttp
aiohttp/http_parser.py
{ "start": 19460, "end": 22902 }
class ____(HttpParser[RawRequestMessage]): """Read request status line. Exception .http_exceptions.BadStatusLine could be raised in case of any errors in status line. Returns RawRequestMessage. """ def parse_message(self, lines: list[bytes]) -> RawRequestMessage: # request line ...
HttpRequestParser
python
pypa__warehouse
tests/unit/organizations/test_models.py
{ "start": 11397, "end": 20373 }
class ____: def test_acl(self, db_session): organization = DBOrganizationFactory.create() team = DBTeamFactory.create(organization=organization) owner1 = DBOrganizationRoleFactory.create(organization=organization) owner2 = DBOrganizationRoleFactory.create(organization=organization) ...
TestTeam
python
openai__openai-python
src/openai/types/responses/response_content_part_added_event.py
{ "start": 771, "end": 1337 }
class ____(BaseModel): content_index: int """The index of the content part that was added.""" item_id: str """The ID of the output item that the content part was added to.""" output_index: int """The index of the output item that the content part was added to.""" part: Part """The con...
ResponseContentPartAddedEvent
python
python-excel__xlwt
xlwt/Cell.py
{ "start": 1305, "end": 3700 }
class ____(object): __slots__ = ["rowx", "colx", "xf_idx", "number"] def __init__(self, rowx, colx, xf_idx, number): self.rowx = rowx self.colx = colx self.xf_idx = xf_idx self.number = float(number) def get_encoded_data(self): rk_encoded = 0 num = self.numb...
NumberCell
python
doocs__leetcode
solution/1500-1599/1505.Minimum Possible Integer After at Most K Adjacent Swaps On Digits/Solution.py
{ "start": 0, "end": 445 }
class ____: def __init__(self, n): self.n = n self.c = [0] * (n + 1) @staticmethod def lowbit(x): return x & -x def update(self, x, delta): while x <= self.n: self.c[x] += delta x += BinaryIndexedTree.lowbit(x) def query(self, x): s ...
BinaryIndexedTree
python
facebookresearch__faiss
tests/test_extra_distances.py
{ "start": 9091, "end": 9608 }
class ____(unittest.TestCase): """ since it has a distance computer, HNSW should work """ def test_hnsw(self): d = 10 nb = 1000 nq = 100 nt = 0 xt, xb, xq = get_dataset_2(d, nt, nb, nq) mt = faiss.METRIC_L1 index = faiss.IndexHNSW(faiss.IndexFlat(d, mt...
TestHNSW
python
google__jax
jax/experimental/pallas/ops/gpu/ragged_dot_mgpu.py
{ "start": 1138, "end": 12351 }
class ____: """Information regarding the group being processed in a block.""" group_id: jax.Array block: jax.Array block_start: jax.Array actual_start: jax.Array actual_end: jax.Array start_within_block: jax.Array actual_size: jax.Array @classmethod def create(cls, group_lengths, tile, tid): "...
GroupInfo
python
pypa__pip
src/pip/_vendor/packaging/licenses/__init__.py
{ "start": 1950, "end": 5727 }
class ____(ValueError): """Raised when a license-expression string is invalid >>> canonicalize_license_expression("invalid") Traceback (most recent call last): ... packaging.licenses.InvalidLicenseExpression: Invalid license expression: 'invalid' """ def canonicalize_license_expression( ...
InvalidLicenseExpression
python
coleifer__peewee
tests/sql.py
{ "start": 84177, "end": 86634 }
class ____(BaseTestCase): database = MySQLDatabase(None) def setUp(self): super(TestOnConflictMySQL, self).setUp() self.database.server_version = None def test_replace(self): query = Person.insert(name='huey').on_conflict('replace') self.assertSQL(query, ( 'REPL...
TestOnConflictMySQL
python
getsentry__sentry
src/sentry/integrations/github/integration.py
{ "start": 34863, "end": 40175 }
class ____(IntegrationProvider): key = IntegrationProviderSlug.GITHUB.value name = "GitHub" metadata = metadata integration_cls: type[IntegrationInstallation] = GitHubIntegration features = frozenset( [ IntegrationFeatures.COMMITS, IntegrationFeatures.ISSUE_BASIC, ...
GitHubIntegrationProvider
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 13928, "end": 14110 }
class ____(models.Model): name = models.CharField(max_length=100) history = HistoricalRecords() class Meta: verbose_name_plural = "\u570b"
UnicodeVerboseNamePlural
python
facelessuser__soupsieve
tests/test_level1/test_visited.py
{ "start": 52, "end": 568 }
class ____(util.TestCase): """Test visited selectors.""" def test_visited(self): """Test visited.""" markup = """ <div> <p>Some text <span id="1" class="foo:bar:foobar"> in a paragraph</span>. <a id="2" class="bar" href="http://google.com">Link</a> <a id="3">Pla...
TestVisited
python
fastapi__sqlmodel
tests/test_deprecations.py
{ "start": 84, "end": 690 }
class ____(Item): password: str def test_deprecated_from_orm_inheritance(): new_item = SubItem(name="Hello", password="secret") with pytest.warns(DeprecationWarning): item = Item.from_orm(new_item) assert item.name == "Hello" assert not hasattr(item, "password") def test_deprecated_parse...
SubItem
python
great-expectations__great_expectations
great_expectations/checkpoint/actions.py
{ "start": 27582, "end": 34952 }
class ____(ValidationAction): """Sends an email to a given list of email addresses. ```yaml - name: send_email_on_validation_result action: class_name: EmailAction notify_on: all # possible values: "all", "failure", "success" notify_with: renderer: # the class that imple...
EmailAction
python
walkccc__LeetCode
solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431-2.py
{ "start": 0, "end": 684 }
class ____: def maxTastiness( self, price: list[int], tastiness: list[int], maxAmount: int, maxCoupons: int, ) -> int: # dp[j][k] := the maximum tastiness of price so far with j amount of money and k coupons dp = [[0] * (maxCoupons + 1) for _ in range(maxAmount + 1)] for p...
Solution
python
ray-project__ray
python/ray/data/_internal/execution/streaming_executor.py
{ "start": 30586, "end": 32400 }
class ____(OutputIterator): """Iterator automatically shutting down executor upon exhausting the iterable sequence. NOTE: If this iterator isn't fully exhausted, executor still have to be closed manually by the caller! """ def __init__(self, executor: StreamingExecutor): self._ex...
_ClosingIterator
python
run-llama__llama_index
llama-index-core/llama_index/core/prompts/rich.py
{ "start": 672, "end": 4820 }
class ____(BasePromptTemplate): # type: ignore[no-redef] template_str: str = Field(description="The template string for the prompt.") def __init__( self, template_str: str, metadata: Optional[Dict[str, Any]] = None, output_parser: Optional[BaseOutputParser] = None, temp...
RichPromptTemplate
python
spyder-ide__spyder
spyder/plugins/remoteclient/api/modules/file_services.py
{ "start": 10228, "end": 15743 }
class ____(SpyderBaseJupyterAPI): """ API for remote file services. This API allows for interacting with files on a remote server. Raises ------ RemoteFileServicesError If an error occurs when interacting with the file services. RemoteOSError If an OSError occured on the re...
SpyderRemoteFileServicesAPI
python
ray-project__ray
python/ray/autoscaler/v2/tests/util.py
{ "start": 4516, "end": 5725 }
class ____(Check): def __init__( self, resources: Dict[str, float], op: operator = operator.eq, enforce_all=False ): self.resources = resources self.op = op self.enforce_all = enforce_all def check(self, status: ClusterStatus): actual = status.total_resources() ...
TotalResourceCheck
python
kamyu104__LeetCode-Solutions
Python/adding-two-negabinary-numbers.py
{ "start": 29, "end": 587 }
class ____(object): def addNegabinary(self, arr1, arr2): """ :type arr1: List[int] :type arr2: List[int] :rtype: List[int] """ result = [] carry = 0 while arr1 or arr2 or carry: if arr1: carry += arr1.pop() if ar...
Solution
python
huggingface__transformers
src/transformers/models/idefics2/modeling_idefics2.py
{ "start": 13499, "end": 14593 }
class ____(nn.Module): """Multihead Attention Pooling.""" def __init__(self, config: Idefics2VisionConfig): super().__init__() self.probe = nn.Parameter(torch.randn(1, 1, config.hidden_size)) self.attention = torch.nn.MultiheadAttention(config.hidden_size, config.num_attention_heads, b...
Idefics2MultiheadAttentionPoolingHead
python
wandb__wandb
wandb/vendor/pygments/lexers/data.py
{ "start": 852, "end": 15672 }
class ____(ExtendedRegexLexer): """ Lexer for `YAML <http://yaml.org/>`_, a human-friendly data serialization language. .. versionadded:: 0.11 """ name = 'YAML' aliases = ['yaml'] filenames = ['*.yaml', '*.yml'] mimetypes = ['text/x-yaml'] def something(token_class): "...
YamlLexer
python
skorch-dev__skorch
skorch/tests/test_classifier.py
{ "start": 316, "end": 7657 }
class ____: @pytest.fixture(scope='module') def data(self, classifier_data): return classifier_data @pytest.fixture(scope='module') def dummy_callback(self): from skorch.callbacks import Callback cb = Mock(spec=Callback) # make dummy behave like an estimator cb.g...
TestNeuralNet
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/exc.py
{ "start": 3843, "end": 4209 }
class ____(UnmappedError): """An mapping operation was requested for an unknown class.""" def __init__(self, cls: Type[_T], msg: Optional[str] = None): if not msg: msg = _default_unmapped(cls) UnmappedError.__init__(self, msg) def __reduce__(self) -> Any: return self.__...
UnmappedClassError
python
realpython__materials
python-textual/horizontal_layout.py
{ "start": 122, "end": 500 }
class ____(App): def compose(self): with Horizontal(): for i in range(NUM_BOXES): static = Static(f"Static {i + 1}") static.styles.border = ("solid", "green") static.styles.width = "10%" yield static if __name__ == "__main__": ...
HorizontalLayoutApp
python
google__pytype
pytype/tests/test_typeguard.py
{ "start": 4820, "end": 6475 }
class ____(test_base.BaseTest): """Tests for TypeGuard as a Callable return type.""" def test_callable(self): self.Check(""" from typing import Callable, TypeGuard def f(x: Callable[[object], TypeGuard[int]], y: object): if x(y): assert_type(y, int) """) def test_generic(se...
CallableTest
python
kubernetes-client__python
kubernetes/client/models/v1_overhead.py
{ "start": 383, "end": 3586 }
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...
V1Overhead
python
huggingface__transformers
src/transformers/models/idefics/processing_idefics.py
{ "start": 1090, "end": 1223 }
class ____(TextKwargs, total=False): add_eos_token: Optional[bool] add_end_of_utterance_token: Optional[bool]
IdeficsTextKwargs
python
pikepdf__pikepdf
src/pikepdf/models/metadata.py
{ "start": 8153, "end": 8890 }
class ____(Converter): """Convert XMP document authors to DocumentInfo.""" @staticmethod def xmp_from_docinfo(docinfo_val: str | None) -> Any: # type: ignore """Derive XMP authors info from DocumentInfo.""" return [docinfo_val] @staticmethod def docinfo_from_xmp(xmp_val): ...
AuthorConverter
python
pypa__warehouse
tests/unit/helpdesk/test_services.py
{ "start": 576, "end": 1485 }
class ____: """Common tests for the service interface.""" def test_verify_service_class(self, service_class): assert verifyClass(IHelpDeskService, service_class) @responses.activate def test_create_service(self, service_class): responses.add( responses.POST, "ht...
TestHelpDeskService
python
pallets__jinja
tests/test_lexnparse.py
{ "start": 1139, "end": 5989 }
class ____: def test_raw1(self, env): tmpl = env.from_string( "{% raw %}foo{% endraw %}|{%raw%}{{ bar }}|{% baz %}{% endraw %}" ) assert tmpl.render() == "foo|{{ bar }}|{% baz %}" def test_raw2(self, env): tmpl = env.from_string("1 {%- raw -%} 2 {%- end...
TestLexer
python
django__django
tests/delete_regress/models.py
{ "start": 1360, "end": 1438 }
class ____(Contact): email_address = models.EmailField(max_length=100)
Email
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 198295, "end": 201503 }
class ____(sgqlc.types.Input): """Autogenerated input type of CreateSponsorsListing""" __schema__ = github_schema __field_names__ = ( "sponsorable_login", "fiscal_host_login", "fiscally_hosted_project_profile_url", "billing_country_or_region_code", "residence_country...
CreateSponsorsListingInput
python
Pylons__pyramid
tests/test_config/pkgs/scannable/__init__.py
{ "start": 1662, "end": 1778 }
class ____: @view_config(name='basemethod', renderer=null_renderer) def basemethod(self): """ """
Base
python
tensorflow__tensorflow
tensorflow/python/autograph/tests/loop_control_flow_test.py
{ "start": 3700, "end": 7416 }
class ____(reference_test_base.TestCase, parameterized.TestCase): @parameterized.parameters(*itertools.product( ( [], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4], ), ( list, _int_tensor, _int_dataset, ), ( ...
LoopControlFlowTest
python
ipython__ipython
tests/test_dir2.py
{ "start": 53, "end": 1446 }
class ____(object): x = 1 z = 23 def test_base(): res = dir2(Base()) assert "x" in res assert "z" in res assert "y" not in res assert "__class__" in res assert res.count("x") == 1 assert res.count("__class__") == 1 def test_SubClass(): class SubClass(Base): y = 2 ...
Base
python
dask__dask
dask/dataframe/dask_expr/_groupby.py
{ "start": 17833, "end": 17929 }
class ____(SingleAggregation): groupby_chunk = M.idxmin groupby_aggregate = M.first
IdxMin
python
boto__boto3
boto3/docs/resource.py
{ "start": 1261, "end": 14259 }
class ____(BaseDocumenter): def __init__(self, resource, botocore_session, root_docs_path): super().__init__(resource) self._botocore_session = botocore_session self._root_docs_path = root_docs_path self._resource_sub_path = self._resource_name.lower() if self._resource_name ...
ResourceDocumenter
python
pydata__xarray
xarray/coding/variables.py
{ "start": 2082, "end": 8417 }
class ____(indexing.ExplicitlyIndexedNDArrayMixin): """Decode arrays on the fly from integer to boolean datatype This is useful for decoding boolean arrays from integer typed netCDF variables. >>> x = np.array([1, 0, 1, 1, 0], dtype="i1") >>> x.dtype dtype('int8') >>> BoolTypeArray(x).dt...
BoolTypeArray
python
getsentry__sentry
tests/sentry/explore/translation/test_discover_translation.py
{ "start": 371, "end": 15512 }
class ____(TestCase): def create_discover_query(self, name: str, query: dict, explore_query=None): discover_saved_query = DiscoverSavedQuery.objects.create( organization=self.org, created_by_id=self.user.id, name=name, version=2, query=query, ...
DiscoverToExploreTranslationTest
python
pydantic__pydantic
tests/mypy/modules/plugin_success.py
{ "start": 1630, "end": 1696 }
class ____(BaseModel, frozen=True): x: int
KwargsNoMutationModel
python
numpy__numpy
numpy/_core/tests/test_numeric.py
{ "start": 83869, "end": 87568 }
class ____: @pytest.mark.parametrize( "bx,by,equal_nan,expected", _test_array_equal_parametrizations() ) def test_array_equal_equal_nan(self, bx, by, equal_nan, expected): """ This test array_equal for a few combinations: - are the two inputs the same object or not (same obj...
TestArrayComparisons
python
huggingface__transformers
src/transformers/models/dpr/modeling_dpr.py
{ "start": 1236, "end": 1992 }
class ____(ModelOutput): r""" pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`): The DPR encoder outputs the *pooler_output* that corresponds to the context representation. Last layer hidden-state of the first token of the sequence (classification token) further proces...
DPRContextEncoderOutput
python
gevent__gevent
src/gevent/tests/test__select.py
{ "start": 3067, "end": 3738 }
class ____(greentest.TestCase): def test_int(self): sock = socket.socket() try: select.select([int(sock.fileno())], [], [], 0.001) finally: sock.close() def test_iterable(self): sock = socket.socket() def fileno_iter(): yield int(soc...
TestSelectTypes
python
viewflow__viewflow
viewflow/views/base.py
{ "start": 732, "end": 1265 }
class ____(object): """ Mixin for FormView to infer View.fields definition from form Layout. """ form_class: Any = None @viewprop def layout(self): if self.form_class is not None and hasattr(self.form_class, "layout"): return self.form_class.layout @viewprop def fi...
FormLayoutMixin
python
langchain-ai__langchain
libs/langchain/langchain_classic/agents/structured_chat/output_parser.py
{ "start": 589, "end": 2201 }
class ____(AgentOutputParser): """Output parser for the structured chat agent.""" format_instructions: str = FORMAT_INSTRUCTIONS """Default formatting instructions""" pattern: Pattern = re.compile(r"```(?:json\s+)?(\W.*?)```", re.DOTALL) """Regex pattern to parse the output.""" @override ...
StructuredChatOutputParser
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 41309, "end": 41482 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("NUMBER",)
TeamDiscussionCommentOrderField
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_path_converters.py
{ "start": 213, "end": 2393 }
class ____: def test_core_dagster_module(self): root = Path("/dagster") file_path = root / "python_modules" / "dagster" / "dagster" / "core" / "executor.py" result = dagster_path_converter(file_path, root) assert result == "dagster.core.executor" def test_core_dagster_init_modu...
TestDagsterPathConverter
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-scrapegraph/tests/test_integration.py
{ "start": 364, "end": 638 }
class ____(BaseModel): """Test schema for integration testing.""" title: str = Field(description="Page title") content: str = Field(description="Main content") links: List[str] = Field(description="Important links", default_factory=list)
IntegrationTestSchema