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
dagster-io__dagster
python_modules/libraries/dagster-deltalake/dagster_deltalake/config.py
{ "start": 2052, "end": 3863 }
class ____(Config): """Storage configuration for Amazon Web Services (AWS) S3 object store.""" provider: Literal["s3"] = "s3" access_key_id: Optional[str] = None """AWS access key ID""" secret_access_key: Optional[str] = None """AWS access key secret""" region: Optional[str] = None "...
S3Config
python
dask__distributed
distributed/dashboard/components/scheduler.py
{ "start": 20833, "end": 22364 }
class ____(DashboardComponent): """Histogram of memory usage, showing how many workers there are in each bucket of usage. Replaces the per-worker graph when there are >= 50 workers. """ @log_errors def __init__(self, scheduler, **kwargs): self.last = 0 self.scheduler = scheduler ...
WorkersMemoryHistogram
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1012943, "end": 1013411 }
class ____(sgqlc.types.Type): """Autogenerated return type of UnmarkProjectV2AsTemplate""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "project_v2") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performi...
UnmarkProjectV2AsTemplatePayload
python
walkccc__LeetCode
solutions/1895. Largest Magic Square/1895.py
{ "start": 0, "end": 1617 }
class ____: def largestMagicSquare(self, grid: list[list[int]]) -> int: m = len(grid) n = len(grid[0]) # prefixRow[i][j] := the sum of the first j numbers in the i-th row prefixRow = [[0] * (n + 1) for _ in range(m)] # prefixCol[i][j] := the sum of the first j numbers in the i-th column prefix...
Solution
python
PyCQA__pycodestyle
tests/test_blank_lines.py
{ "start": 9601, "end": 10114 }
class ____(object): pass """) self.assertEqual([ 'E302:9:1', # another_function 'E302:17:1', # SomeCloseClass ], result) def test_top_level_more_blank_lines(self): """ It will trigger an error when more 2 blank lines are found before top level d...
AFarEnoughClass
python
sqlalchemy__sqlalchemy
test/orm/test_options.py
{ "start": 27301, "end": 37167 }
class ____(_fixtures.FixtureTest): """test the error messages emitted when using property options in conjunction with column-only entities, or for not existing options """ run_create_tables = False run_inserts = None run_deletes = None def test_option_with_mapper_PropCompatator(self):...
OptionsNoPropTest
python
tensorflow__tensorflow
tensorflow/python/training/saving/saveable_object_util.py
{ "start": 27593, "end": 33071 }
class ____(trackable.Trackable): """Converts object's `SaveableObjects` to functions used in TF2 checkpointing. A class that converts a Trackable object's `SaveableObjects` to save and restore functions with the same signatures as `Trackable._serialize_to_tensors` and `Trackable._restore_from_tensors`. This ...
SaveableCompatibilityConverter
python
falconry__falcon
falcon/asgi/response.py
{ "start": 1158, "end": 15928 }
class ____(response.Response): """Represents an HTTP response to a client request. Note: ``Response`` is not meant to be instantiated directly by responders. Keyword Arguments: options (dict): Set of global options passed from the App handler. """ # PERF(kgriffs): These will be sh...
Response
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-milvus/destination_milvus/destination.py
{ "start": 808, "end": 2681 }
class ____(Destination): indexer: Indexer embedder: Embedder def _init_indexer(self, config: ConfigModel): self.embedder = create_from_config(config.embedding, config.processing) self.indexer = MilvusIndexer(config.indexing, self.embedder.embedding_dimensions) def write( self, ...
DestinationMilvus
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_hyperlink24.py
{ "start": 315, "end": 1461 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("hyperlink24.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with hyperlinks.""" workbook = Wor...
TestCompareXLSXFiles
python
numpy__numpy
numpy/_core/tests/test_unicode.py
{ "start": 2874, "end": 2987 }
class ____(CreateZeros): """Check the creation of zero-valued arrays (size 2)""" ulen = 2
TestCreateZeros_2
python
joke2k__faker
faker/providers/ssn/zh_TW/__init__.py
{ "start": 1013, "end": 1310 }
class ____(SsnProvider): def ssn(self) -> str: ssn_without_last_char = self.numerify(self.random_uppercase_letter() + str(self.random_int(1, 2)) + "#######") last_char = str((10 - checksum(ssn_without_last_char) % 10) % 10) return ssn_without_last_char + last_char
Provider
python
google__pytype
pytype/metrics_test.py
{ "start": 4976, "end": 8216 }
class ____(unittest.TestCase): """Tests for Distribution.""" def setUp(self): super().setUp() metrics._prepare_for_test() def test_accumulation(self): d = metrics.Distribution("foo") # Check contents of an empty distribution. self.assertEqual(0, d._count) self.assertEqual(0, d._total) ...
DistributionTest
python
networkx__networkx
networkx/algorithms/planarity.py
{ "start": 6978, "end": 25509 }
class ____: """A class to maintain the state during planarity check.""" __slots__ = [ "G", "roots", "height", "lowpt", "lowpt2", "nesting_depth", "parent_edge", "DG", "adjs", "ordered_adjs", "ref", "side", "...
LRPlanarity
python
HypothesisWorks__hypothesis
hypothesis-python/tests/django/toystore/test_basic_configuration.py
{ "start": 908, "end": 1314 }
class ____: @settings( suppress_health_check=[HealthCheck.too_slow, HealthCheck.differing_executors] ) @given(integers()) def test_is_blank_slate(self, unused): Company.objects.create(name="MickeyCo") def test_normal_test_1(self): Company.objects.create(name="MickeyCo") ...
SomeStuff
python
matplotlib__matplotlib
lib/mpl_toolkits/axisartist/angle_helper.py
{ "start": 5349, "end": 8798 }
class ____: deg_mark = r"^{\circ}" min_mark = r"^{\prime}" sec_mark = r"^{\prime\prime}" fmt_d = "$%d" + deg_mark + "$" fmt_ds = r"$%d.%s" + deg_mark + "$" # %s for sign fmt_d_m = r"$%s%d" + deg_mark + r"\,%02d" + min_mark + "$" fmt_d_ms = r"$%s%d" + deg_mark + r"\,%02d.%s" + min_mark ...
FormatterDMS
python
PyCQA__pylint
tests/functional/c/class_members.py
{ "start": 62, "end": 283 }
class ____: attr: int # `bar` definitely does not exist here, but in a complex scenario, # it might. We simply exclude PEP 526 class and instance variables # from `no-member`. print(Class().attr) print(Class.attr)
Class
python
ray-project__ray
python/ray/data/aggregate.py
{ "start": 45474, "end": 49247 }
class ____(AggregateFnV2[List[int], float]): """Calculates the percentage of zero values in a numeric column. This aggregation computes the percentage of zero values in a numeric dataset column. It can optionally ignore null values when calculating the percentage. The result is a percentage value betwe...
ZeroPercentage
python
keras-team__keras
keras/src/ops/numpy_test.py
{ "start": 128400, "end": 194307 }
class ____(testing.TestCase): def test_mean(self): x = np.array([[1, 2, 3], [3, 2, 1]]) self.assertAllClose(knp.mean(x), np.mean(x)) self.assertAllClose(knp.mean(x, axis=()), np.mean(x, axis=())) self.assertAllClose(knp.mean(x, axis=1), np.mean(x, axis=1)) self.assertAllClose...
NumpyOneInputOpsCorrectnessTest
python
readthedocs__readthedocs.org
readthedocs/builds/migrations/0015_uploading_build_state.py
{ "start": 149, "end": 923 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("builds", "0014_migrate-doctype-from-project-to-version"), ] operations = [ migrations.AlterField( model_name="build", name="state", field=models.CharField( ...
Migration
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/functions.py
{ "start": 60393, "end": 60532 }
class ____(AnsiFunction[str]): """The SESSION_USER() SQL function.""" type = sqltypes.String() inherit_cache = True
session_user
python
getsentry__sentry
tests/sentry/deletions/test_monitor_checkin.py
{ "start": 437, "end": 14318 }
class ____(APITestCase, TransactionTestCase, HybridCloudTestMixin): def test_delete_checkin_directly(self) -> None: """ Test that deleting a MonitorCheckIn directly (not via Monitor deletion) properly handles MonitorIncident children via MonitorCheckInDeletionTask. """ proje...
DeleteMonitorCheckInTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/type_api.py
{ "start": 54693, "end": 55830 }
class ____(TypeEngineMixin): """Indicates DB-native types supported by an :class:`.Emulated` type.""" @classmethod def adapt_native_to_emulated( cls, impl: Union[TypeEngine[Any], TypeEngineMixin], **kw: Any, ) -> TypeEngine[Any]: """Given an impl, adapt this type's class...
NativeForEmulated
python
huggingface__transformers
src/transformers/models/phimoe/modeling_phimoe.py
{ "start": 24200, "end": 25854 }
class ____(GradientCheckpointingLayer): def __init__(self, config: PhimoeConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = PhimoeAttention(config, layer_idx) self.mlp = PhimoeSparseMoeBlock(config) self.input_layernorm = Phim...
PhimoeDecoderLayer
python
huggingface__transformers
src/transformers/models/colpali/modular_colpali.py
{ "start": 1467, "end": 15474 }
class ____(PaliGemmaProcessor): r""" Constructs a ColPali processor which wraps a PaliGemmaProcessor and special methods to process images and queries, as well as to compute the late-interaction retrieval score. [`ColPaliProcessor`] offers all the functionalities of [`PaliGemmaProcessor`]. See the [`~P...
ColPaliProcessor
python
walkccc__LeetCode
solutions/1636. Sort Array by Increasing Frequency/1636.py
{ "start": 222, "end": 555 }
class ____: def frequencySort(self, nums: list[int]) -> list[int]: ans = [] heap = [] for num, freq in collections.Counter(nums).items(): heapq.heappush(heap, T(num, freq)) while len(heap) > 0: num = heap[0].num freq = heapq.heappop(heap).freq ans.extend([num] * freq) re...
Solution
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/addmm_test.py
{ "start": 2300, "end": 4614 }
class ____(op_bench.TorchBenchmarkBase): def init(self, B, M, N, K, device, dtype): self.inputs = { "input_one": torch.rand( (M, N), device=device, requires_grad=self.auto_set(), dtype=dtype ), "batch1": torch.rand( (B, M, K), device=device...
AddbmmBenchmark
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/context/invocation.py
{ "start": 2924, "end": 5087 }
class ____: """Base class for any direct invocation execution contexts. Each type of execution context (ex. OpExecutionContext, AssetExecutionContext) needs to have a variant for direct invocation. Those direct invocation contexts have some methods that are not available until the context is bound to a ...
BaseDirectExecutionContext
python
google__pytype
pytype/pyc/opcodes.py
{ "start": 8226, "end": 8424 }
class ____(Opcode): _FLAGS = HAS_JUNKNOWN __slots__ = () # NOTE: GET_AWAITABLE gains an argument in Python 3.11, but adding the argument # here causes tests in earlier versions to fail.
YIELD_FROM
python
ray-project__ray
python/ray/dag/compiled_dag_node.py
{ "start": 15138, "end": 16138 }
class ____: """Represents an input to an ExecutableTask. Args: input_variant: either an unresolved input (when type is ChannelInterface) , or a resolved input value (when type is Any) channel_idx: if input_variant is an unresolved input, this is the index into the input ...
_ExecutableTaskInput
python
psf__requests
tests/test_utils.py
{ "start": 9555, "end": 10512 }
class ____: @pytest.mark.parametrize( "path", ( "/", __file__, pytest.__file__, "/etc/invalid/location", ), ) def test_unzipped_paths_unchanged(self, path): assert path == extract_zipped_paths(path) def test_zipped_paths_ex...
TestExtractZippedPaths
python
dask__dask
dask/dataframe/tseries/resample.py
{ "start": 6326, "end": 6382 }
class ____(ResampleReduction): how = "std"
ResampleStd
python
doocs__leetcode
lcof/面试题58 - I. 翻转单词顺序/Solution.py
{ "start": 0, "end": 400 }
class ____: def reverseWords(self, s: str) -> str: words = [] i, n = 0, len(s) while i < n: while i < n and s[i] == " ": i += 1 if i < n: j = i while j < n and s[j] != " ": j += 1 word...
Solution
python
doocs__leetcode
solution/1700-1799/1702.Maximum Binary String After Change/Solution.py
{ "start": 0, "end": 245 }
class ____: def maximumBinaryString(self, binary: str) -> str: k = binary.find('0') if k == -1: return binary k += binary[k + 1 :].count('0') return '1' * k + '0' + '1' * (len(binary) - k - 1)
Solution
python
davidhalter__jedi
jedi/inference/gradual/typing.py
{ "start": 8912, "end": 10166 }
class ____(LazyValueWrapper): def __init__(self, parent_context, origin_tree_name, actual): self.inference_state = parent_context.inference_state self.parent_context = parent_context self._origin_tree_name = origin_tree_name self._actual = actual # e.g. builtins.list @property ...
TypeAlias
python
apache__airflow
airflow-core/src/airflow/jobs/dag_processor_job_runner.py
{ "start": 1184, "end": 2366 }
class ____(BaseJobRunner, LoggingMixin): """ DagProcessorJobRunner is a job runner that runs a DagFileProcessorManager processor. :param job: Job instance to use :param processor: DagFileProcessorManager instance to use """ job_type = "DagProcessorJob" def __init__( self, ...
DagProcessorJobRunner
python
pytorch__pytorch
torch/profiler/_memory_profiler.py
{ "start": 1259, "end": 1517 }
class ____(enum.Enum): PREEXISTING = enum.auto() CREATE = enum.auto() INCREMENT_VERSION = enum.auto() DESTROY = enum.auto() _ACTION_TO_INDEX = {i: i.value for i in Action} @dataclasses.dataclass(eq=True, unsafe_hash=False, frozen=True)
Action
python
pytorch__pytorch
test/dynamo/test_functions.py
{ "start": 85475, "end": 86699 }
class ____(torch.nn.Module): def forward(self, s9: "Sym(s9)", L_lambda0_keywords_y_: "f32[s9, s9]"): l_lambda0_keywords_y_ = L_lambda0_keywords_y_ mul: "f32[s9, s9]" = l_lambda0_keywords_y_ * l_lambda0_keywords_y_ add: "f32[s9, s9]" = l_lambda0_keywords_y_ + l_lambda0_keywords_y_; l_lambd...
GraphModule
python
Textualize__textual
tests/test_app_focus_blur.py
{ "start": 186, "end": 2840 }
class ____(App[None]): AUTO_FOCUS = "#input-4" def compose(self) -> ComposeResult: for n in range(10): yield Input(id=f"input-{n}") async def test_app_blur() -> None: """Test that AppBlur removes focus.""" async with FocusBlurApp().run_test() as pilot: assert pilot.app.fo...
FocusBlurApp
python
getsentry__sentry
src/sentry/issues/endpoints/related_issues.py
{ "start": 913, "end": 2556 }
class ____(GroupEndpoint): owner = ApiOwner.ISSUES publish_status = {"GET": ApiPublishStatus.EXPERIMENTAL} enforce_rate_limit = True rate_limits = RateLimitConfig( limit_overrides={ "GET": { RateLimitCategory.IP: RateLimit(limit=15, window=5), RateLimi...
RelatedIssuesEndpoint
python
kamyu104__LeetCode-Solutions
Python/number-of-excellent-pairs.py
{ "start": 128, "end": 591 }
class ____(object): def countExcellentPairs(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def popcount(x): return bin(x)[2:].count('1') cnt = collections.Counter(popcount(x) for x in set(nums)) return sum(cnt[i]*cn...
Solution
python
kamyu104__LeetCode-Solutions
Python/find-array-given-subset-sums.py
{ "start": 5679, "end": 7009 }
class ____(object): def recoverArray(self, n, sums): """ :type n: int :type sums: List[int] :rtype: List[int] """ dp = {k: v for k, v in collections.Counter(sums).iteritems()} sorted_sums = sorted(dp.iterkeys()) # Time: O(2^n * log(2^n)) = O(n * 2^n) ...
Solution4
python
weaviate__weaviate-python-client
weaviate/backup/backup.py
{ "start": 1998, "end": 2215 }
class ____(BaseModel): """Return type of the backup status methods.""" error: Optional[str] = Field(default=None) status: BackupStatus path: str backup_id: str = Field(alias="id")
BackupStatusReturn
python
bokeh__bokeh
src/bokeh/client/states.py
{ "start": 1815, "end": 1928 }
class ____(Enum): NO_ERROR = auto() HTTP_ERROR = auto() NETWORK_ERROR = auto()
ErrorReason
python
huggingface__transformers
src/transformers/models/timesformer/modeling_timesformer.py
{ "start": 9069, "end": 9711 }
class ____(nn.Module): """ The residual connection is defined in TimesformerLayer instead of here (as is the case with other models), due to the layernorm applied before each block. """ def __init__(self, config: TimesformerConfig) -> None: super().__init__() self.dense = nn.Linear(...
TimesformerSelfOutput
python
doocs__leetcode
solution/2700-2799/2787.Ways to Express an Integer as Sum of Powers/Solution.py
{ "start": 0, "end": 408 }
class ____: def numberOfWays(self, n: int, x: int) -> int: mod = 10**9 + 7 f = [[0] * (n + 1) for _ in range(n + 1)] f[0][0] = 1 for i in range(1, n + 1): k = pow(i, x) for j in range(n + 1): f[i][j] = f[i - 1][j] if k <= j: ...
Solution
python
mlflow__mlflow
mlflow/types/responses_helpers.py
{ "start": 6101, "end": 6535 }
class ____(BaseModel): tool_choice: str | ToolChoiceFunction | None = None @model_validator(mode="after") def check_tool_choice(self) -> "ToolChoice": if ( self.tool_choice and isinstance(self.tool_choice, str) and self.tool_choice not in {"none", "auto", "requir...
ToolChoice
python
ansible__ansible
lib/ansible/plugins/action/set_fact.py
{ "start": 945, "end": 2186 }
class ____(ActionBase): TRANSFERS_FILES = False _requires_connection = False def run(self, tmp=None, task_vars=None): if task_vars is None: task_vars = dict() result = super(ActionModule, self).run(tmp, task_vars) del tmp # tmp no longer has any effect facts ...
ActionModule
python
python-poetry__poetry
src/poetry/console/commands/env/info.py
{ "start": 288, "end": 2688 }
class ____(Command): name = "env info" description = "Displays information about the current environment." options: ClassVar[list[Option]] = [ option("path", "p", "Only display the environment's path."), option( "executable", "e", "Only display the environment's python executabl...
EnvInfoCommand
python
pypa__pip
src/pip/_vendor/rich/layout.py
{ "start": 883, "end": 947 }
class ____(Exception): """Layout related error."""
LayoutError
python
astropy__astropy
astropy/time/formats.py
{ "start": 3359, "end": 17488 }
class ____: """ Base class for time representations. Parameters ---------- val1 : numpy ndarray, list, number, str, or bytes Values to initialize the time or times. Bytes are decoded as ascii. Quantities with time units are allowed for formats where the interpretation is un...
TimeFormat
python
getsentry__sentry
src/sentry/dynamic_sampling/rules/biases/custom_rule_bias.py
{ "start": 458, "end": 2100 }
class ____(Bias): """ Boosts to 100% sample rate all the traces matching an active custom rule. """ def generate_rules(self, project: Project, base_sample_rate: float) -> list[PolymorphicRule]: rules = CustomDynamicSamplingRule.get_project_rules(project) ret_val: list[PolymorphicRule] ...
CustomRuleBias
python
mlflow__mlflow
mlflow/utils/lazy_load.py
{ "start": 80, "end": 1726 }
class ____(types.ModuleType): """Class for module lazy loading. This class helps lazily load modules at package level, which avoids pulling in large dependencies like `tensorflow` or `torch`. This class is mirrored from wandb's LazyLoader: https://github.com/wandb/wandb/blob/79b2d4b73e3a9e4488e503c3131...
LazyLoader
python
huggingface__transformers
tests/models/gpt_neox_japanese/test_modeling_gpt_neox_japanese.py
{ "start": 7966, "end": 11046 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else () pipeline_model_mapping = ( {"feature-extraction": GPTNeoXJapaneseModel, "text-generation": GPTNeoXJapaneseFo...
GPTNeoXModelJapaneseTest
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 12223, "end": 14177 }
class ____(Node): """ Sets compiler directives for the children nodes """ # directives {string:value} A dictionary holding the right value for # *all* possible directives. # body Node child_attrs = ["body"] @classmethod def for_direct...
CompilerDirectivesNode
python
huggingface__transformers
src/transformers/models/mixtral/modular_mixtral.py
{ "start": 8316, "end": 9274 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.top_k = config.num_experts_per_tok self.jitter_noise = config.router_jitter_noise self.gate = MixtralTopKRouter(config) self.experts = MixtralExperts(config) def forward(self, hidden_states: torch...
MixtralSparseMoeBlock
python
pennersr__django-allauth
tests/apps/socialaccount/providers/wahoo/tests.py
{ "start": 238, "end": 981 }
class ____(OAuth2TestsMixin, TestCase): provider_id = WahooProvider.id def get_mocked_response(self): # https://cloud-api.wahooligan.com/#users return MockedResponse( HTTPStatus.OK, """ { "id": 60462, "height": "2.0", ...
WahooTests
python
readthedocs__readthedocs.org
readthedocs/config/tests/test_validation.py
{ "start": 3067, "end": 3757 }
class ____: def test_it_accepts_unicode(self): result = validate_string("Unicöde") assert isinstance(result, str) def test_it_accepts_nonunicode(self): result = validate_string("Unicode") assert isinstance(result, str) def test_it_rejects_float(self): with raises(Co...
TestValidateString
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/array_ops_test.py
{ "start": 46265, "end": 47662 }
class ____(object): def __init__(self, test, x, tensor_type=dtypes.float32, use_resource=False): self.tensor_type = tensor_type self.test = test self._use_resource = use_resource self.x_np = np.array(x).astype(tensor_type.as_numpy_dtype) # Give the value a non-zero imaginary component for comple...
StridedSliceAssignChecker
python
geekcomputers__Python
insta_monitering/insta_datafetcher.py
{ "start": 8503, "end": 9217 }
class ____(multiprocessing.Process): def __init__(self, user, tags, type, productId): try: multiprocessing.Process.__init__(self) self.user = user self.tags = tags self.type = type self.productId = productId except Exception as err: ...
theradPorcess
python
kamyu104__LeetCode-Solutions
Python/solve-the-equation.py
{ "start": 41, "end": 566 }
class ____(object): def solveEquation(self, equation): """ :type equation: str :rtype: str """ a, b, side = 0, 0, 1 for eq, sign, num, isx in re.findall('(=)|([-+]?)(\d*)(x?)', equation): if eq: side = -1 elif isx: ...
Solution
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_managed_kafka.py
{ "start": 6488, "end": 7798 }
class ____: @mock.patch(MANAGED_KAFKA_PATH.format("types.Cluster.to_dict")) @mock.patch(MANAGED_KAFKA_PATH.format("ManagedKafkaHook")) def test_execute(self, mock_hook, to_dict_mock): op = ManagedKafkaUpdateClusterOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, ...
TestManagedKafkaUpdateClusterOperator
python
huggingface__transformers
src/transformers/models/swin2sr/modeling_swin2sr.py
{ "start": 33714, "end": 35092 }
class ____(nn.Module): """Upsample module. Args: scale (`int`): Scale factor. Supported scales: 2^n and 3. num_features (`int`): Channel number of intermediate features. """ def __init__(self, scale, num_features): super().__init__() self.scale ...
Upsample
python
google__pytype
pytype/abstract/_singletons.py
{ "start": 6457, "end": 7948 }
class ____(_base.BaseValue): """A Singleton class must only be instantiated once. This is essentially an ABC for Unsolvable, Empty, and others. """ # TODO: b/350643999 - Should rather be a ClassVar but it breaks build # investigate and fix. _instance: Optional["Singleton"] = None def __new__(cls, *args,...
Singleton
python
huggingface__transformers
src/transformers/models/zamba2/modeling_zamba2.py
{ "start": 78452, "end": 83455 }
class ____(Zamba2PreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.model = Zamba2Model(config) self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) # Initialize weights and apply final processin...
Zamba2ForSequenceClassification
python
cython__cython
Cython/Debugger/Tests/test_libcython_in_gdb.py
{ "start": 13922, "end": 15247 }
class ____(DebugTestCase): def setUp(self): super().setUp() self.fd, self.tmpfilename = tempfile.mkstemp() self.tmpfile = os.fdopen(self.fd, 'r+') def tearDown(self): super().tearDown() try: self.tmpfile.close() finally: os.remove(self.t...
TestExec
python
anthropics__anthropic-sdk-python
src/anthropic/types/beta_authentication_error.py
{ "start": 199, "end": 301 }
class ____(BaseModel): message: str type: Literal["authentication_error"]
BetaAuthenticationError
python
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_unittest.py
{ "start": 1230, "end": 1588 }
class ____(unittest.TestCase): @fails_with(FailedHealthCheck) @given(st.integers()) def setUp(self, i): pass def test(self): """Provide something to set up for, so the setUp method is called.""" SUBTEST_SUITE = """ import unittest from hypothesis import given, settings, strategies as ...
test_given_on_setUp_fails_health_check
python
huggingface__transformers
src/transformers/models/nanochat/modeling_nanochat.py
{ "start": 12700, "end": 14461 }
class ____(GradientCheckpointingLayer): def __init__(self, config: NanoChatConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = NanoChatAttention(config=config, layer_idx=layer_idx) self.mlp = NanoChatMLP(config) self.input_lay...
NanoChatDecoderLayer
python
apache__airflow
airflow-core/tests/unit/core/test_stats.py
{ "start": 15627, "end": 16230 }
class ____: def setup_method(self): pytest.importorskip("datadog") from datadog import DogStatsd self.dogstatsd_client = Mock(spec=DogStatsd) self.dogstatsd = SafeDogStatsdLogger(self.dogstatsd_client, metrics_tags=True) def test_does_send_stats_using_dogstatsd_with_tags(self):...
TestDogStatsWithMetricsTags
python
tensorflow__tensorflow
tensorflow/python/distribute/numpy_dataset.py
{ "start": 3647, "end": 3800 }
class ____(object): """Used with `colocate_with` to create a non-mirrored variable.""" def __init__(self, device): self.device = device
SingleDevice
python
apache__airflow
providers/dingding/tests/unit/dingding/operators/test_dingding.py
{ "start": 1043, "end": 2374 }
class ____: _config = { "dingding_conn_id": "dingding_default", "message_type": "text", "message": "Airflow dingding webhook test", "at_mobiles": ["123", "456"], "at_all": False, } def setup_method(self): args = {"owner": "airflow", "start_date": DEFAULT_DATE...
TestDingdingOperator
python
pypa__setuptools
setuptools/tests/config/test_apply_pyprojecttoml.py
{ "start": 19420, "end": 19933 }
class ____: def test_namespace_packages(self, tmp_path): pyproject = tmp_path / "pyproject.toml" config = """ [project] name = "myproj" version = "42" [tool.setuptools] namespace-packages = ["myproj.pkg"] """ pyproject.write_text(cleandoc(confi...
TestDeprecatedFields
python
pydantic__pydantic
pydantic/_internal/_core_metadata.py
{ "start": 295, "end": 5162 }
class ____(TypedDict, total=False): """A `TypedDict` for holding the metadata dict of the schema. Attributes: pydantic_js_functions: List of JSON schema functions that resolve refs during application. pydantic_js_annotation_functions: List of JSON schema functions that don't resolve refs during...
CoreMetadata
python
matplotlib__matplotlib
lib/matplotlib/cbook.py
{ "start": 5565, "end": 13295 }
class ____: """ Handle registering, processing, blocking, and disconnecting for a set of signals and callbacks: >>> def oneat(x): ... print('eat', x) >>> def ondrink(x): ... print('drink', x) >>> from matplotlib.cbook import CallbackRegistry >>> call...
CallbackRegistry
python
falconry__falcon
tests/test_middleware.py
{ "start": 529, "end": 628 }
class ____: def process_request(self, req, resp): self.req = req
CaptureRequestMiddleware
python
huggingface__transformers
src/transformers/models/ernie/modular_ernie.py
{ "start": 4932, "end": 4972 }
class ____(BertLayer): pass
ErnieLayer
python
keras-team__keras
keras/src/metrics/reduction_metrics.py
{ "start": 3171, "end": 5119 }
class ____(Metric): """Compute the (weighted) mean of the given values. For example, if values is `[1, 3, 5, 7]` then the mean is 4. If `sample_weight` was specified as `[1, 1, 0, 0]` then the mean would be 2. This metric creates two variables, `total` and `count`. The mean value returned is simpl...
Mean
python
apache__airflow
airflow-core/src/airflow/models/xcom_arg.py
{ "start": 4929, "end": 8971 }
class ____(SchedulerXComArg): args: Sequence[SchedulerXComArg] fillvalue: Any @classmethod def _deserialize(cls, data: dict[str, Any], dag: SerializedDAG) -> Self: return cls( [deserialize_xcom_arg(arg, dag) for arg in data["args"]], fillvalue=data.get("fillvalue", NOTSE...
SchedulerZipXComArg
python
getsentry__sentry
tests/sentry/models/test_apitoken.py
{ "start": 7449, "end": 9161 }
class ____(TestCase): def setUp(self) -> None: self.user = self.create_user() self.proxy = self.create_user() self.org = self.create_organization() self.internal_app = self.create_internal_integration( name="Internal App", organization=self.org, ) ...
ApiTokenInternalIntegrationTest
python
numba__numba
numba/cuda/cudadrv/devicearray.py
{ "start": 18521, "end": 24888 }
class ____(DeviceNDArrayBase): ''' An on-GPU array type ''' def is_f_contiguous(self): ''' Return true if the array is Fortran-contiguous. ''' return self._dummy.is_f_contig @property def flags(self): """ For `numpy.ndarray` compatibility. Ideally...
DeviceNDArray
python
scrapy__scrapy
tests/test_responsetypes.py
{ "start": 175, "end": 4983 }
class ____: def test_from_filename(self): mappings = [ ("data.bin", Response), ("file.txt", TextResponse), ("file.xml.gz", Response), ("file.xml", XmlResponse), ("file.html", HtmlResponse), ("file.unknownext", Response), ] ...
TestResponseTypes
python
walkccc__LeetCode
solutions/1248. Count Number of Nice Subarrays/1248.py
{ "start": 0, "end": 510 }
class ____: def numberOfSubarrays(self, nums: list[int], k: int) -> int: def numberOfSubarraysAtMost(k: int) -> int: ans = 0 l = 0 r = 0 while r <= len(nums): if k >= 0: ans += r - l if r == len(nums): break if nums[r] & 1: k -...
Solution
python
pytorch__pytorch
torch/nn/modules/padding.py
{ "start": 13813, "end": 14075 }
class ____(Module): __constants__ = ["padding"] padding: Sequence[int] def forward(self, input: Tensor) -> Tensor: return F.pad(input, self.padding, "reflect") def extra_repr(self) -> str: return f"{self.padding}"
_ReflectionPadNd
python
django__django
django/views/generic/detail.py
{ "start": 6748, "end": 7040 }
class ____(SingleObjectTemplateResponseMixin, BaseDetailView): """ Render a "detail" view of an object. By default this is a model instance looked up from `self.queryset`, but the view will support display of *any* object by overriding `self.get_object()`. """
DetailView
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 272130, "end": 272486 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "owner") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") owner = sgqlc.types.Field("VerifiableDomainOwner", graphql_name=...
DeleteVerifiableDomainPayload
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/exc.py
{ "start": 10302, "end": 10462 }
class ____(InvalidRequestError): """An operation was requested from a connection, cursor, or other object that's in a closed state."""
ResourceClosedError
python
pandas-dev__pandas
asv_bench/benchmarks/gil.py
{ "start": 2055, "end": 2851 }
class ____: params = ([2, 4, 8], ["count", "last", "max", "mean", "min", "prod", "sum", "var"]) param_names = ["threads", "method"] def setup(self, threads, method): N = 10**6 ngroups = 10**3 df = DataFrame( {"key": np.random.randint(0, ngroups, size=N), "data": np.rando...
ParallelGroupbyMethods
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_format24.py
{ "start": 315, "end": 994 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("format24.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with automatic color.""" workbook = W...
TestCompareXLSXFiles
python
airbytehq__airbyte
airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_credit_adjustments.py
{ "start": 1848, "end": 3834 }
class ____(StreamTestCase): _STREAM_NAME = "credit_adjustments" @HttpMocker() def test_state_message_produced_while_read_and_state_match_latest_record(self, http_mocker: HttpMocker) -> None: min_cursor_value = "2025-04-13T00:00:00+00:00" max_cursor_value = "2025-05-13T00:00:00+00:00" ...
TestIncremental
python
agronholm__apscheduler
src/apscheduler/abc.py
{ "start": 602, "end": 1621 }
class ____(Iterator[datetime], metaclass=ABCMeta): """ Abstract base class that defines the interface that every trigger must implement. """ __slots__ = () @abstractmethod def next(self) -> datetime | None: """ Return the next datetime to fire on. If no such datetime c...
Trigger
python
huggingface__transformers
src/transformers/models/deepseek_vl/image_processing_deepseek_vl_fast.py
{ "start": 1674, "end": 7538 }
class ____(BaseImageProcessorFast): resample = PILImageResampling.BICUBIC image_mean = OPENAI_CLIP_MEAN image_std = OPENAI_CLIP_STD size = {"height": 384, "width": 384} min_size = 14 do_resize = True do_rescale = True do_normalize = True do_pad = True valid_kwargs = DeepseekVLIma...
DeepseekVLImageProcessorFast
python
numba__numba
numba/cuda/cudadrv/nvvm.py
{ "start": 1742, "end": 6589 }
class ____(object): '''Process-wide singleton. ''' _PROTOTYPES = { # nvvmResult nvvmVersion(int *major, int *minor) 'nvvmVersion': (nvvm_result, POINTER(c_int), POINTER(c_int)), # nvvmResult nvvmCreateProgram(nvvmProgram *cu) 'nvvmCreateProgram': (nvvm_result, POINTER(nvvm_...
NVVM
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/black/cases/annotations.py
{ "start": 28, "end": 224 }
class ____: def foo(self): if True: content_ids: Mapping[ str, Optional[ContentId] ] = self.publisher_content_store.store_config_contents(files)
Foo
python
doocs__leetcode
solution/0100-0199/0146.LRU Cache/Solution.py
{ "start": 0, "end": 162 }
class ____: def __init__(self, key: int = 0, val: int = 0): self.key = key self.val = val self.prev = None self.next = None
Node
python
Lightning-AI__lightning
tests/tests_pytorch/strategies/test_single_device.py
{ "start": 2415, "end": 3073 }
class ____: ... def test_strategy_pickle(): strategy = SingleDeviceStrategy("cpu") optimizer = MockOptimizer() strategy.optimizers = [optimizer] assert isinstance(strategy.optimizers[0], MockOptimizer) assert isinstance(strategy._lightning_optimizers[0], LightningOptimizer) state = pickle.du...
MockOptimizer
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/docstring_signature.py
{ "start": 0, "end": 33 }
class ____: """A(foo, bar)"""
A
python
mlflow__mlflow
mlflow/gateway/app.py
{ "start": 1795, "end": 7308 }
class ____(FastAPI): def __init__(self, config: GatewayConfig, limiter: Limiter, *args: Any, **kwargs: Any): super().__init__(*args, **kwargs) self.state.limiter = limiter self.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler) self.dynamic_endpoints: dict[str, En...
GatewayAPI
python
cython__cython
tests/run/test_grammar.py
{ "start": 10420, "end": 10624 }
class ____: def __init__(self): self._dct = {} def __setitem__(self, item, value): self._dct[item.lower()] = value def __getitem__(self, item): return self._dct[item]
CNS
python
huggingface__transformers
tests/repo_utils/test_check_copies.py
{ "start": 4681, "end": 5460 }
class ____: attr_1 = 1 attr_2 = 3 def __init__(self, a=1, b=2): self.a = a self.b = b # Ignore copy def only_in_roberta_to_be_ignored(self, c): return 3 # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward def forward(self, c): ...
RobertaBertDummyModel