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
kamyu104__LeetCode-Solutions
Python/minimum-cost-good-caption.py
{ "start": 57, "end": 1293 }
class ____(object): def minCostGoodCaption(self, caption): """ :type caption: str :rtype: str """ L = 3 n = len(caption) if n < L: return "" dp = [[[0]*2 for _ in xrange(26)] for _ in xrange(n-L+1)] mn = [[0]*2 for _ in xrange(n-L+1...
Solution
python
google__pytype
pytype/tests/test_stdlib1.py
{ "start": 116, "end": 7780 }
class ____(test_base.BaseTest): """Tests for files in typeshed/stdlib.""" def test_ast(self): ty = self.Infer(""" import ast def f(): return ast.parse("True") """) self.assertTypesMatchPytd( ty, """ import ast def f() -> _ast.Module: ... """, ) ...
StdlibTests
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_aggregate_metrics/column_distinct_values.py
{ "start": 1133, "end": 4209 }
class ____(ColumnAggregateMetricProvider): metric_name = "column.distinct_values" @column_aggregate_value(engine=PandasExecutionEngine) # type: ignore[misc] # untyped-decorator def _pandas(cls, column: pd.Series, **kwargs) -> Set[Any]: return set(column.unique()) @metric_value(engine=SqlAlche...
ColumnDistinctValues
python
astropy__astropy
astropy/coordinates/representation/spherical.py
{ "start": 57094, "end": 60141 }
class ____(BaseDifferential): """Differential(s) of 3D spherical coordinates using physics convention. Parameters ---------- d_phi, d_theta : `~astropy.units.Quantity` The differential azimuth and inclination. d_r : `~astropy.units.Quantity` The differential radial distance. cop...
PhysicsSphericalDifferential
python
kamyu104__LeetCode-Solutions
Python/total-waviness-of-numbers-in-range-ii.py
{ "start": 5082, "end": 7369 }
class ____(object): def totalWaviness(self, num1, num2): """ :type num1: int :type num2: int :rtype: int """ def count(x): def encode(prev, prev2, zero, tight): key = 0 key = key*(10+1)+(prev+1) key = key*(10...
Solution4
python
fsspec__filesystem_spec
fsspec/implementations/tests/test_archive.py
{ "start": 5985, "end": 13138 }
class ____: """ Validate that all filesystem adapter implementations for archive files will adhere to the same specification. """ scenarios = [ scenario_zip, scenario_tar, scenario_targz, scenario_tarbz2, scenario_tarxz, scenario_libarchive, ] ...
TestAnyArchive
python
Lightning-AI__lightning
tests/tests_pytorch/models/test_hparams.py
{ "start": 10107, "end": 10186 }
class ____(MixinForBoringModel, CustomBoringModel): pass
BoringModelWithMixin
python
readthedocs__readthedocs.org
readthedocs/gold/views.py
{ "start": 3591, "end": 5366 }
class ____(GenericView): http_method_names = ["post"] def post(self, request, *args, **kwargs): try: user = request.user schema = "https" if settings.PUBLIC_DOMAIN_USES_HTTPS else "http" url = reverse_lazy("gold_detail") url = f"{schema}://{settings.PRODU...
GoldCreateCheckoutSession
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/sensor.py
{ "start": 508, "end": 868 }
class ____(BaseModel): """Single sensor metadata model.""" id: str name: str status: DgApiSensorStatus sensor_type: DgApiSensorType description: Optional[str] = None repository_origin: Optional[str] = None next_tick_timestamp: Optional[float] = None # Unix timestamp class Config: ...
DgApiSensor
python
realpython__materials
python-built-in-functions/processors.py
{ "start": 522, "end": 870 }
class ____: def __init__(self, filename): self.filename = filename def read(self): with open(self.filename, encoding="utf-8") as file: return json.load(file) def write(self, data): with open(self.filename, mode="w", encoding="utf-8") as file: json.dump(data,...
JSONProcessor
python
numpy__numpy
numpy/random/tests/test_generator_mt19937.py
{ "start": 83886, "end": 108348 }
class ____: # tests that functions that broadcast behave # correctly when presented with non-scalar arguments seed = 123456789 def test_uniform(self): random = Generator(MT19937(self.seed)) low = [0] high = [1] uniform = random.uniform desired = np.array([0.16693...
TestBroadcast
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 23763, "end": 23969 }
class ____(Dataset): def __init__(self, size): self.size = size def __getitem__(self, idx): return ctypes.string_at(0) def __len__(self): return self.size
SegfaultDataset
python
huggingface__transformers
tests/models/vitpose_backbone/test_modeling_vitpose_backbone.py
{ "start": 1166, "end": 4116 }
class ____: def __init__( self, parent, batch_size=13, image_size=[16 * 8, 12 * 8], patch_size=[8, 8], num_channels=3, is_training=True, use_labels=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, interm...
VitPoseBackboneModelTester
python
google__jax
tests/pallas/gpu_ops_test.py
{ "start": 10837, "end": 12433 }
class ____(PallasBaseTest): def setUp(self): super().setUp() if jtu.test_device_matches(["cpu", "tpu"]): self.skipTest("Works only on GPU") @parameterized.parameters(*[ (1, 384, 192), (2, 384, 192), ]) def test_fused_layernorm_fwd(self, batch_size, seq_len, embed_dim): k1, k2, k3 = r...
FusedLayerNormTest
python
django__django
django/contrib/syndication/views.py
{ "start": 1011, "end": 9371 }
class ____: feed_type = feedgenerator.DefaultFeed title_template = None description_template = None language = None def __call__(self, request, *args, **kwargs): try: obj = self.get_object(request, *args, **kwargs) except ObjectDoesNotExist: raise Http404("Fe...
Feed
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/declarative_automation/serialized_objects.py
{ "start": 1734, "end": 4392 }
class ____: """Serializable indicator that this value was an AllPartitionsSubset at serialization time, but the partitions may have changed since that time. """ def _get_maybe_compressed_dynamic_partitions_subset( subset: EntitySubset, ) -> SerializableEntitySubset: # for DefaultPartitionsSubset o...
HistoricalAllPartitionsSubsetSentinel
python
pyca__cryptography
tests/hazmat/primitives/test_x963kdf.py
{ "start": 405, "end": 4708 }
class ____: def test_length_limit(self, backend): big_length = hashes.SHA256().digest_size * (2**32 - 1) + 1 error = OverflowError if sys.maxsize <= 2**31 else ValueError with pytest.raises(error): X963KDF(hashes.SHA256(), big_length, None, backend) def test_already_finaliz...
TestX963KDF
python
Netflix__metaflow
metaflow/includefile.py
{ "start": 1317, "end": 2701 }
class ____(object): # Thin wrapper to indicate to the MF client that this object is special # and should be handled as an IncludedFile when returning it (ie: fetching # the actual content) # @tracefunc def __init__(self, descriptor: Dict[str, Any]): self._descriptor = descriptor sel...
IncludedFile
python
oauthlib__oauthlib
oauthlib/oauth2/rfc6749/errors.py
{ "start": 4001, "end": 4127 }
class ____(OAuth2Error): error = 'insecure_transport' description = 'OAuth 2 MUST utilize https.'
InsecureTransportError
python
django__django
tests/backends/sqlite/tests.py
{ "start": 10343, "end": 11136 }
class ____(TransactionTestCase): available_apps = ["backends"] def test_database_sharing_in_threads(self): thread_connections = [] def create_object(): Object.objects.create() thread_connections.append(connections[DEFAULT_DB_ALIAS].connection) main_connection =...
ThreadSharing
python
astropy__astropy
astropy/nddata/nddata_base.py
{ "start": 186, "end": 1994 }
class ____(metaclass=ABCMeta): """Base metaclass that defines the interface for N-dimensional datasets with associated meta information used in ``astropy``. All properties and ``__init__`` have to be overridden in subclasses. See `NDData` for a subclass that defines this interface on `numpy.ndarray`-li...
NDDataBase
python
pytest-dev__pytest
src/_pytest/tmpdir.py
{ "start": 1146, "end": 11387 }
class ____: """Factory for temporary directories under the common base temp directory, as discussed at :ref:`temporary directory location and retention`. """ _given_basetemp: Path | None # pluggy TagTracerSub, not currently exposed, so Any. _trace: Any _basetemp: Path | None _retention_...
TempPathFactory
python
huggingface__transformers
src/transformers/models/granite/modular_granite.py
{ "start": 1497, "end": 4988 }
class ____(LlamaDecoderLayer): def __init__(self, config: GraniteConfig, layer_idx: int): super().__init__(config, layer_idx) self.residual_multiplier = config.residual_multiplier self.self_attn = GraniteAttention(config=config, layer_idx=layer_idx) def forward( self, hi...
GraniteDecoderLayer
python
run-llama__llama_index
llama-index-core/tests/agent/workflow/test_multi_agent_workflow.py
{ "start": 790, "end": 18432 }
class ____(MockLLM): def __init__(self, responses: List[ChatMessage]): super().__init__() self._responses = responses self._response_index = 0 @property def metadata(self) -> LLMMetadata: return LLMMetadata(is_function_calling_model=True) async def astream_chat( ...
MockLLM
python
huggingface__transformers
src/transformers/models/dots1/modular_dots1.py
{ "start": 3049, "end": 4506 }
class ____(Qwen3ForCausalLM): def forward( self, **super_kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Ind...
Dots1ForCausalLM
python
bokeh__bokeh
src/bokeh/application/handlers/function.py
{ "start": 2250, "end": 5005 }
class ____(Handler): ''' A Handler that accepts a plain python function to use for modifying Bokeh Documents. For example, the following code configures a handler with a function that adds an empty plot to a Document: .. code-block:: python def add_empty_plot(doc: Document): p...
FunctionHandler
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 14113, "end": 14470 }
class ____(HTTPSuccessful): """ subclass of :class:`~HTTPSuccessful` This indicates that the server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. code: 204, title: No Content """ code = 204 title = 'No Conte...
HTTPNoContent
python
Pylons__pyramid
tests/test_util.py
{ "start": 29920, "end": 36093 }
class ____(unittest.TestCase): def _callFUT(self, view, attr=None, argname=None): from pyramid.util import takes_one_arg return takes_one_arg(view, attr=attr, argname=argname) def test_requestonly_newstyle_class_no_init(self): class foo: """ """ self.assertFalse(se...
Test_takes_one_arg
python
ray-project__ray
python/ray/serve/tests/test_config_files/grpc_deployment.py
{ "start": 3107, "end": 3430 }
class ____: def __init__(self): self.price = 3.0 def __call__(self, num_oranges: int): return num_oranges * self.price orange_stand = OrangeStand.bind() apple_stand = AppleStand.bind() g2 = FruitMarket.options(name="grpc-deployment-model-composition").bind( orange_stand, apple_stand )
AppleStand
python
mitmproxy__pdoc
test/testdata/misc.py
{ "start": 7094, "end": 7764 }
class ____: """https://github.com/mitmproxy/pdoc/issues/519""" def dynamically_modify_docstring1(): """this should **not** be the docstring.""" def dynamically_modify_docstring2(): pass dynamically_modify_docstring1.__doc__ = "https://github.com/mitmproxy/pdoc/issues/536" dynamically_modify_docstring2...
__init__
python
pandas-dev__pandas
pandas/io/sql.py
{ "start": 52006, "end": 53957 }
class ____(PandasObject, ABC): """ Subclasses Should define read_query and to_sql. """ def __enter__(self) -> Self: return self def __exit__(self, *args) -> None: pass def read_table( self, table_name: str, index_col: str | list[str] | None = None, ...
PandasSQL
python
doocs__leetcode
lcof/面试题31. 栈的压入、弹出序列/Solution.py
{ "start": 0, "end": 303 }
class ____: def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool: j, stk = 0, [] for v in pushed: stk.append(v) while stk and stk[-1] == popped[j]: stk.pop() j += 1 return j == len(pushed)
Solution
python
keras-team__keras
keras/src/export/onnx_test.py
{ "start": 511, "end": 2485 }
class ____(models.Model): def __init__(self, layer_list): super().__init__() self.layer_list = layer_list def call(self, input): output = input for layer in self.layer_list: output = layer(output) return output def get_model(type="sequential", input_shape=(...
CustomModel
python
fluentpython__example-code
18-asyncio/charfinder/charfinder.py
{ "start": 2527, "end": 6354 }
class ____: def __init__(self, chars=None): self.load(chars) def load(self, chars=None): self.index = None if chars is None: try: with open(INDEX_NAME, 'rb') as fp: self.index = pickle.load(fp) except OSError: ...
UnicodeNameIndex
python
pydantic__pydantic
pydantic/experimental/pipeline.py
{ "start": 1270, "end": 1349 }
class ____: func: Callable[[Any], Any] @dataclass(**_slots_frozen)
_Transform
python
google__pytype
pytype/overlays/attr_overlay.py
{ "start": 14122, "end": 21393 }
class ____(classgen.FieldConstructor): """Implements attr.ib/attrs.field.""" @classmethod def make(cls, ctx, module): return super().make("ib" if module == "attr" else "field", ctx, module) def _match_and_discard_args(self, node, funcb, args): """Discard invalid args so that we can still construct an ...
Attrib
python
getsentry__sentry
src/sentry/notifications/platform/types.py
{ "start": 5467, "end": 5795 }
class ____(StrEnum): """ The type of formatting to be applied to the encapsulated blocks. """ PARAGRAPH = "paragraph" """ A block of text with a line break before. """ CODE_BLOCK = "code_block" """ A new section of code with a line break before. """
NotificationBodyFormattingBlockType
python
Textualize__textual
src/textual/_sleep.py
{ "start": 156, "end": 1620 }
class ____(Thread): def __init__( self, ) -> None: self._exit = False self._sleep_time = 0.0 self._event = Event() self.future: Future | None = None self._loop = get_running_loop() super().__init__(daemon=True) def run(self): while True: ...
Sleeper
python
django__django
django/forms/models.py
{ "start": 8521, "end": 9219 }
class ____: def __init__(self, options=None): self.model = getattr(options, "model", None) self.fields = getattr(options, "fields", None) self.exclude = getattr(options, "exclude", None) self.widgets = getattr(options, "widgets", None) self.localized_fields = getattr(options,...
ModelFormOptions
python
ray-project__ray
python/ray/data/_internal/logical/operators/all_to_all_operator.py
{ "start": 1701, "end": 2819 }
class ____(AbstractAllToAll, LogicalOperatorSupportsPredicatePassThrough): """Logical operator for randomize_block_order.""" def __init__( self, input_op: LogicalOperator, seed: Optional[int] = None, ): super().__init__( "RandomizeBlockOrder", input_o...
RandomizeBlocks
python
facelessuser__pymdown-extensions
tests/test_extensions/test_blocks/test_legacy_tab.py
{ "start": 1225, "end": 2402 }
class ____(util.MdCase): """Test legacy tab slug separator cases.""" extension = ['pymdownx.blocks.tab', 'toc'] extension_configs = { 'pymdownx.blocks.tab': {'slugify': slugify(case='lower'), 'separator': '_'} } MD = r""" ### Here is some text /// tab | Here is some text conte...
TestLegacyTabSlugsSep
python
huggingface__transformers
tests/models/prophetnet/test_modeling_prophetnet.py
{ "start": 41873, "end": 42382 }
class ____(ModelTesterMixin, unittest.TestCase): all_model_classes = (ProphetNetEncoder,) if is_torch_available() else () test_resize_embeddings = False is_encoder_decoder = False def setUp(self): self.model_tester = ProphetNetStandaloneEncoderModelTester(self, is_training=False) self....
ProphetNetStandaloneEncoderModelTest
python
huggingface__transformers
src/transformers/models/gemma/modeling_gemma.py
{ "start": 12999, "end": 14781 }
class ____(GradientCheckpointingLayer): def __init__(self, config: GemmaConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = GemmaAttention(config=config, layer_idx=layer_idx) self.mlp = GemmaMLP(config) self.input_layernorm = G...
GemmaDecoderLayer
python
allegroai__clearml
clearml/backend_api/services/v2_23/datasets.py
{ "start": 99676, "end": 100522 }
class ____(Response): """ Response of datasets.delete_version endpoint. :param deleted: :type deleted: bool """ _service = "datasets" _action = "delete_version" _version = "2.23" _schema = { "definitions": {}, "properties": {"deleted": {"type": ["boolean", "null"]}...
DeleteVersionResponse
python
getsentry__sentry
tests/sentry/utils/test_committers.py
{ "start": 5818, "end": 8820 }
class ____(CommitTestCase): def test_simple(self) -> None: commit = self.create_commit() file_change = self.create_commitfilechange(filename="hello/app.py", type="A", commit=commit) file_changes = [ file_change, self.create_commitfilechange(filename="goodbye/app.js", ...
MatchCommitsPathTestCase
python
pytorch__pytorch
test/distributed/test_c10d_nccl.py
{ "start": 242190, "end": 244290 }
class ____(NCCLTraceTestDumpOnTimeoutBase): @requires_nccl() @skip_if_lt_x_gpu(2) @parametrize("timing_enabled", [True, False]) def test_timeout_dumps(self, timing_enabled): # dump on heartbeatmonitor thread os.environ["TORCH_NCCL_COORD_CHECK_MILSEC"] = "1000" # need rank0 to cra...
NCCLTraceTestDumpOnTimeout
python
doocs__leetcode
solution/2400-2499/2461.Maximum Sum of Distinct Subarrays With Length K/Solution.py
{ "start": 0, "end": 479 }
class ____: def maximumSubarraySum(self, nums: List[int], k: int) -> int: cnt = Counter(nums[:k]) s = sum(nums[:k]) ans = s if len(cnt) == k else 0 for i in range(k, len(nums)): cnt[nums[i]] += 1 cnt[nums[i - k]] -= 1 if cnt[nums[i - k]] == 0: ...
Solution
python
getsentry__sentry
tests/sentry/management/commands/test_generate_controlsilo_urls.py
{ "start": 192, "end": 2516 }
class ____(TestCase): def call_command(self, *args, **kwargs): out = StringIO() call_command("generate_controlsilo_urls", *args, stdout=out, stderr=StringIO(), **kwargs) return out.getvalue() def test_skip_includes(self) -> None: result = self.call_command(format="js") #...
TestGenerateControlsiloUrls
python
django-compressor__django-compressor
compressor/tests/test_utils.py
{ "start": 604, "end": 1734 }
class ____(TestCase): def test_has_finders_from_staticfiles(self): self.assertTrue( compressor.utils.staticfiles.finders is django.contrib.staticfiles.finders ) def test_has_finders_from_staticfiles_if_configured_per_appconfig(self): apps = get_apps_with_staticfiles_using_ap...
StaticFilesTestCase
python
tensorflow__tensorflow
tensorflow/python/keras/engine/keras_tensor.py
{ "start": 20845, "end": 21675 }
class ____(type_spec_module.TypeSpec): """TypeSpec to represent user-registered symbolic objects.""" def __init__(self, shape, dtype): self.shape = shape self._dtype = dtype self.dtype = dtype def _component_specs(self): raise NotImplementedError def _from_components(self, components): ra...
UserRegisteredSpec
python
apache__airflow
airflow-core/tests/unit/models/test_xcom_arg.py
{ "start": 5280, "end": 7995 }
class ____: def test_xcom_pass_to_op(self, dag_maker): with dag_maker(dag_id="test_xcom_pass_to_op") as dag: operator = PythonOperator( python_callable=lambda: VALUE, task_id="return_value_1", do_xcom_push=True, ) xarg = XCo...
TestXComArgRuntime
python
jazzband__django-formtools
tests/wizard/namedwizardtests/tests.py
{ "start": 14056, "end": 15006 }
class ____(NamedWizardTests, TestCase): wizard_urlname = 'nwiz_cookie' wizard_step_1_data = { 'cookie_contact_wizard-current_step': 'form1', } wizard_step_data = ( { 'form1-name': 'Pony', 'form1-thirsty': '2', 'cookie_contact_wizard-current_step': 'for...
NamedCookieWizardTests
python
airbytehq__airbyte
airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/test_post_comment_votes.py
{ "start": 1132, "end": 8084 }
class ____(TestCase): @property def _config(self): return ( ConfigBuilder() .with_basic_auth_credentials("user@example.com", "password") .with_subdomain("d3v-airbyte") .with_start_date(ab_datetime_now().subtract(timedelta(weeks=104))) .build() ...
TestPostsCommentVotesStreamFullRefresh
python
pytorch__pytorch
torch/onnx/_internal/exporter/_capture_strategies.py
{ "start": 4447, "end": 6765 }
class ____(CaptureStrategy): def _capture( self, model, args, kwargs, dynamic_shapes ) -> torch.export.ExportedProgram: with ( _patch_dynamo_unsupported_functions(), # Support the dynamism with 0/1 input dim torch.fx.experimental._config.patch(backed_size_obli...
TorchExportStrictStrategy
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_column02.py
{ "start": 315, "end": 1369 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_column02.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.go...
TestCompareXLSXFiles
python
mlflow__mlflow
mlflow/gateway/config.py
{ "start": 10410, "end": 10503 }
class ____(LimitModel): calls: int key: str | None = None renewal_period: str
Limit
python
spack__spack
lib/spack/spack/test/concretization/core.py
{ "start": 10208, "end": 117774 }
class ____: def test_concretize(self, spec): check_concretize(spec) def test_concretize_mention_build_dep(self): spec = check_concretize("cmake-client ^cmake@=3.21.3") # Check parent's perspective of child to_dependencies = spec.edges_to_dependencies(name="cmake") asser...
TestConcretize
python
tensorflow__tensorflow
tensorflow/python/ops/numpy_ops/tests/config.py
{ "start": 1457, "end": 4017 }
class ____(object): def __init__(self): self.values = {} self.meta = {} self.FLAGS = NameSpace(self.read) self.use_absl = False def update(self, name, val): if self.use_absl: setattr(self.absl_flags.FLAGS, name, val) else: self.check_exists(name) if name not in self.value...
Config
python
pypa__packaging
src/packaging/pylock.py
{ "start": 8402, "end": 9812 }
class ____: type: str url: str | None = None path: str | None = None requested_revision: str | None = None commit_id: str # type: ignore[misc] subdirectory: str | None = None def __init__( self, *, type: str, url: str | None = None, path: str | None ...
PackageVcs
python
getsentry__sentry
tests/sentry/charts/test_chartcuterie.py
{ "start": 460, "end": 4398 }
class ____(TestCase): def test_enabled(self) -> None: assert not charts.is_enabled() with self.options({"chart-rendering.enabled": True}): assert charts.is_enabled() @responses.activate @patch("sentry.charts.chartcuterie.uuid4") def test_simple(self, mock_uuid: MagicMock) -...
ChartcuterieTest
python
wandb__wandb
wandb/sdk/artifacts/_generated/run_input_artifacts.py
{ "start": 325, "end": 417 }
class ____(GQLResult): run: Optional[RunInputArtifactsProjectRun]
RunInputArtifactsProject
python
wandb__wandb
wandb/sdk/artifacts/_generated/artifact_collection_aliases.py
{ "start": 501, "end": 740 }
class ____(GQLResult): typename__: Typename[ Literal["ArtifactCollection", "ArtifactPortfolio", "ArtifactSequence"] ] aliases: ArtifactCollectionAliasesArtifactCollectionAliases
ArtifactCollectionAliasesArtifactCollection
python
django__django
tests/model_indexes/models.py
{ "start": 31, "end": 652 }
class ____(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=50) pages = models.IntegerField(db_column="page_count") shortcut = models.CharField(max_length=50, db_tablespace="idx_tbls") isbn = models.CharField(max_length=50, db_tablespace="idx_tbls") bar...
Book
python
tensorflow__tensorflow
tensorflow/python/compiler/tensorrt/test/tf_function_test.py
{ "start": 1835, "end": 14775 }
class ____(trt_test.TfTrtIntegrationTestBase): def __init__(self, methodName): # pylint: disable=invalid-name super(TfFunctionTest, self).__init__(methodName) self._profile_strategy = "Range" self._trt_engine_op_count_offset = 0 self._test_conversion_params = { "_tftrt_convert_function": Tru...
TfFunctionTest
python
catalyst-team__catalyst
catalyst/metrics/_accumulative.py
{ "start": 161, "end": 3291 }
class ____(ICallbackLoaderMetric): """This metric accumulates all the input data along loader Args: keys: list of keys to accumulate data from batch compute_on_call: if True, allows compute metric's value on call prefix: metric prefix suffix: metric suffix """ def __ini...
AccumulativeMetric
python
kubernetes-client__python
kubernetes/client/models/v1alpha1_param_ref.py
{ "start": 383, "end": 8400 }
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...
V1alpha1ParamRef
python
numpy__numpy
benchmarks/benchmarks/bench_ma.py
{ "start": 4206, "end": 4902 }
class ____(Benchmark): param_names = ['method', 'msize'] params = [['ravel', 'transpose', 'compressed', 'conjugate'], ['small', 'big']] def setup(self, method, msize): xs = np.random.uniform(-1, 1, 6).reshape(2, 3) m1 = [[True, False, False], [False, False, True]] xl =...
MAMethod0v
python
zarr-developers__zarr-python
src/zarr/codecs/gzip.py
{ "start": 781, "end": 2069 }
class ____(BytesBytesCodec): """gzip codec""" is_fixed_size = False level: int = 5 def __init__(self, *, level: int = 5) -> None: level_parsed = parse_gzip_level(level) object.__setattr__(self, "level", level_parsed) @classmethod def from_dict(cls, data: dict[str, JSON]) -> ...
GzipCodec
python
huggingface__transformers
tests/models/maskformer/test_modeling_maskformer.py
{ "start": 20687, "end": 29983 }
class ____(unittest.TestCase): @cached_property def default_image_processor(self): return ( MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco") if is_vision_available() else None ) def test_inference_no_head(self): mode...
MaskFormerModelIntegrationTest
python
pypa__setuptools
setuptools/command/install_lib.py
{ "start": 205, "end": 4319 }
class ____(orig.install_lib): """Don't add compiled flags to filenames of non-Python files""" distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution def run(self) -> None: self.build() outfiles = self.install() if outfiles is not None: ...
install_lib
python
kamyu104__LeetCode-Solutions
Python/largest-number-at-least-twice-of-others.py
{ "start": 29, "end": 286 }
class ____(object): def dominantIndex(self, nums): """ :type nums: List[int] :rtype: int """ m = max(nums) if all(m >= 2*x for x in nums if x != m): return nums.index(m) return -1
Solution
python
tensorflow__tensorflow
tensorflow/python/summary/writer/event_file_writer.py
{ "start": 8225, "end": 10289 }
class ____: """Stripped-down fork of the standard library Queue that is closeable.""" def __init__(self, maxsize=0): """Create a queue object with a given maximum size. Args: maxsize: int size of queue. If <= 0, the queue size is infinite. """ self._maxsize = maxsize self._queue = collec...
CloseableQueue
python
huggingface__transformers
tests/models/csm/test_modeling_csm.py
{ "start": 11773, "end": 38812 }
class ____(unittest.TestCase): def setUp(self): # TODO: @eustlb, update with correct sesame's repo self.model_checkpoint = "sesame/csm-1b" def tearDown(self): cleanup(torch_device, gc_collect=True) def _load_conversation(self): ds = load_dataset("hf-internal-testing/dailyta...
CsmForConditionalGenerationIntegrationTest
python
jschneier__django-storages
tests/test_gcloud.py
{ "start": 963, "end": 22752 }
class ____(GCloudTestCase): def test_open_read(self): """ Test opening a file and reading from it """ data = b"This is some test read data." with self.storage.open(self.filename) as f: self.storage._client.bucket.assert_called_with(self.bucket_name) s...
GCloudStorageTests
python
doocs__leetcode
solution/3500-3599/3549.Multiply Two Polynomials/Solution.py
{ "start": 0, "end": 1494 }
class ____: def multiply(self, poly1: List[int], poly2: List[int]) -> List[int]: if not poly1 or not poly2: return [] m = len(poly1) + len(poly2) - 1 n = 1 while n < m: n <<= 1 fa = list(map(complex, poly1)) + [0j] * (n - len(poly1)) fb = lis...
Solution
python
scikit-image__scikit-image
tests/skimage/io/test_imageio.py
{ "start": 1342, "end": 2724 }
class ____: @pytest.mark.parametrize( "shape,dtype", [ # float32, float64 can't be saved as PNG and raise # uint32 is not roundtripping properly ((10, 10), np.uint8), ((10, 10), np.uint16), ((10, 10, 2), np.uint8), ((10, 10, 3),...
TestSave
python
marshmallow-code__marshmallow
src/marshmallow/validate.py
{ "start": 21997, "end": 23138 }
class ____(OneOf): """Validator which succeeds if ``value`` is a sequence and each element in the sequence is also in the sequence passed as ``choices``. Empty input is considered valid. :param choices: Same as :class:`OneOf`. :param labels: Same as :class:`OneOf`. :param error: Same as :class:...
ContainsOnly
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_condition_evaluations.py
{ "start": 3159, "end": 4476 }
class ____(graphene.ObjectType): uniqueId = graphene.NonNull(graphene.String) description = graphene.NonNull(graphene.String) entityKey = graphene.NonNull(GrapheneEntityKey) startTimestamp = graphene.Field(graphene.Float) endTimestamp = graphene.Field(graphene.Float) numTrue = graphene.NonNull...
GraphenePartitionedAssetConditionEvaluationNode
python
huggingface__transformers
tests/models/sam2_video/test_modeling_sam2_video.py
{ "start": 2032, "end": 23858 }
class ____(unittest.TestCase): def setUp(self): super().setUp() self.video_model = Sam2VideoModel.from_pretrained("facebook/sam2.1-hiera-tiny").to(torch.float32) self.processor = Sam2VideoProcessor.from_pretrained("facebook/sam2.1-hiera-tiny") self.video_model.to(torch_device) ...
Sam2VideoModelIntegrationTest
python
pytorch__pytorch
torch/testing/_internal/distributed/ddp_under_dist_autograd_test.py
{ "start": 1758, "end": 2418 }
class ____(NamedTuple): """A feature set has 2 types of features""" dense_features: torch.Tensor sparse_features: torch.LongTensor values: torch.Tensor def _call_method(method, rref, *args, **kwargs): return method(rref.local_value(), *args, **kwargs) def _remote_method(method, rref, *args, **k...
FeatureSet
python
doocs__leetcode
solution/2300-2399/2343.Query Kth Smallest Trimmed Number/Solution.py
{ "start": 0, "end": 295 }
class ____: def smallestTrimmedNumbers( self, nums: List[str], queries: List[List[int]] ) -> List[int]: ans = [] for k, trim in queries: t = sorted((v[-trim:], i) for i, v in enumerate(nums)) ans.append(t[k - 1][1]) return ans
Solution
python
sympy__sympy
sympy/solvers/ode/single.py
{ "start": 67416, "end": 70400 }
class ____(SingleODESolver): r""" Solves ODEs that only involve derivatives of the dependent variable using a substitution of the form `f^n(x) = g(x)`. For example any second order ODE of the form `f''(x) = h(f'(x), x)` can be transformed into a pair of 1st order ODEs `g'(x) = h(g(x), x)` and `...
NthOrderReducible
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/assets.py
{ "start": 1830, "end": 1983 }
class ____(BaseModel): """Asset watcher serializer for responses.""" name: str trigger_id: int created_date: datetime
AssetWatcherResponse
python
doocs__leetcode
solution/3600-3699/3674.Minimum Operations to Equalize Array/Solution.py
{ "start": 0, "end": 121 }
class ____: def minOperations(self, nums: List[int]) -> int: return int(any(x != nums[0] for x in nums))
Solution
python
huggingface__transformers
tests/models/bert_generation/test_tokenization_bert_generation.py
{ "start": 987, "end": 9473 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "google/bert_for_seq_generation_L-24_bbc_encoder" tokenizer_class = BertGenerationTokenizer test_rust_tokenizer = False test_sentencepiece = True @classmethod def setUpClass(cls): super().setUpClass() tok...
BertGenerationTokenizationTest
python
networkx__networkx
networkx/classes/reportviews.py
{ "start": 44809, "end": 46132 }
class ____(OutMultiEdgeView): """A EdgeView class for inward edges of a MultiDiGraph""" __slots__ = () def __setstate__(self, state): self._graph = state["_graph"] self._adjdict = state["_adjdict"] self._nodes_nbrs = self._adjdict.items dataview = InMultiEdgeDataView def ...
InMultiEdgeView
python
pypa__warehouse
tests/common/db/organizations.py
{ "start": 3407, "end": 3653 }
class ____(WarehouseFactory): class Meta: model = OrganizationRole role_name = OrganizationRoleType.Owner user = factory.SubFactory(UserFactory) organization = factory.SubFactory(OrganizationFactory)
OrganizationRoleFactory
python
pydantic__pydantic
pydantic-core/tests/validators/test_union.py
{ "start": 31457, "end": 51449 }
class ____: class ModelA: a: int = 0 class ModelB: b: int = 0 model_a_schema = core_schema.model_schema( ModelA, core_schema.model_fields_schema( fields={'a': core_schema.model_field(core_schema.with_default_schema(core_schema.int_schema(), default=0))} ...
TestSmartUnionWithDefaults
python
sqlalchemy__sqlalchemy
test/typing/plain_files/ext/association_proxy/association_proxy_one.py
{ "start": 556, "end": 864 }
class ____(Base): __tablename__ = "user" id = mapped_column(Integer, primary_key=True) name = mapped_column(String, nullable=False) addresses: Mapped[Set["Address"]] = relationship() email_addresses: AssociationProxy[Set[str]] = association_proxy( "addresses", "email" )
User
python
doocs__leetcode
solution/2300-2399/2366.Minimum Replacements to Sort the Array/Solution.py
{ "start": 0, "end": 372 }
class ____: def minimumReplacement(self, nums: List[int]) -> int: ans = 0 n = len(nums) mx = nums[-1] for i in range(n - 2, -1, -1): if nums[i] <= mx: mx = nums[i] continue k = (nums[i] + mx - 1) // mx ans += k - 1 ...
Solution
python
fastapi__sqlmodel
docs_src/tutorial/create_db_and_table/tutorial003.py
{ "start": 99, "end": 615 }
class ____(SQLModel, table=True): # (3)! id: Optional[int] = Field(default=None, primary_key=True) # (4)! name: str # (5)! secret_name: str # (6)! age: Optional[int] = None # (7)! sqlite_file_name = "database.db" # (8)! sqlite_url = f"sqlite:///{sqlite_file_name}" # (9)! engine = create_engine...
Hero
python
catalyst-team__catalyst
examples/reinforcement_learning/ddpg.py
{ "start": 2413, "end": 5409 }
class ____(gym.ActionWrapper): def action(self, action: float) -> float: low_bound = self.action_space.low upper_bound = self.action_space.high action = low_bound + (action + 1.0) * 0.5 * (upper_bound - low_bound) action = np.clip(action, low_bound, upper_bound) return acti...
NormalizedActions
python
walkccc__LeetCode
solutions/604. Design Compressed String Iterator/604.py
{ "start": 0, "end": 607 }
class ____: def __init__(self, compressedString: str): self.s = compressedString self.i = 0 # s' index self.num = 0 # currentChar's count self.currentChar = ' ' def next(self) -> str: if not self.hasNext(): return ' ' if self.num == 0: self.currentChar = self.s[self.i] ...
StringIterator
python
pytorch__pytorch
torch/_inductor/template_heuristics/triton.py
{ "start": 95280, "end": 95486 }
class ____(AddMMConfigMixin, MTIAMMTemplateConfigHeuristic): """Addmm specific mixin for MTIA""" @register_template_heuristic(mm_template.uid, "mtia", op_name="scaled_mm")
MTIAAddMMTemplateConfigHeuristic
python
sqlalchemy__sqlalchemy
test/orm/test_query.py
{ "start": 124777, "end": 125613 }
class ____(QueryTest): def test_entity(self): User = self.classes.User s = fixture_session() q = s.query(User) assert q._compile_state()._has_mapper_entities def test_cols(self): User = self.classes.User s = fixture_session() q = s.query(User.id) ...
HasMapperEntitiesTest
python
spack__spack
lib/spack/spack/vendor/pyrsistent/_plist.py
{ "start": 6189, "end": 7268 }
class ____(_PListBase): """ Classical Lisp style singly linked list. Adding elements to the head using cons is O(1). Element access is O(k) where k is the position of the element in the list. Taking the length of the list is O(n). Fully supports the Sequence and Hashable protocols including indexin...
PList
python
airbytehq__airbyte
airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py
{ "start": 1369, "end": 1727 }
class ____(RkiCovidStream): """Docs: https://api.corona-zahlen.org/germany""" primary_key = None def path( self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None ) -> str: return "germany/" # class that contains...
Germany
python
huggingface__transformers
src/transformers/models/data2vec/modeling_data2vec_vision.py
{ "start": 9412, "end": 13326 }
class ____(nn.Module): def __init__(self, config: Data2VecVisionConfig, window_size: Optional[tuple] = None) -> None: super().__init__() self.config = config if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( ...
Data2VecVisionSelfAttention
python
huggingface__transformers
src/transformers/models/diffllama/modular_diffllama.py
{ "start": 18552, "end": 18830 }
class ____(LlamaDecoderLayer): def __init__(self, config: DiffLlamaConfig, layer_idx: int): super().__init__(config, layer_idx) self.self_attn = DIFFLLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
DiffLlamaDecoderLayer
python
PrefectHQ__prefect
tests/test_artifacts.py
{ "start": 808, "end": 26776 }
class ____: @pytest.fixture def artifact(self): yield ArtifactCreate( key="voltaic", data=1, description="# This is a markdown description title", ) async def test_create_and_read_link_artifact_with_linktext_succeeds( self, artifact: ArtifactCreat...
TestCreateArtifacts