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
numpy__numpy
numpy/lib/tests/test_function_base.py
{ "start": 1505, "end": 3789 }
class ____: def test_basic(self): assert_raises(ValueError, rot90, np.ones(4)) assert_raises(ValueError, rot90, np.ones((2, 2, 2)), axes=(0, 1, 2)) assert_raises(ValueError, rot90, np.ones((2, 2)), axes=(0, 2)) assert_raises(ValueError, rot90, np.ones((2, 2)), axes=(1, 1)) as...
TestRot90
python
getsentry__sentry
tests/sentry/api/endpoints/test_project_tagkey_details.py
{ "start": 1261, "end": 3349 }
class ____(APITestCase): @mock.patch("sentry.eventstream.backend") def test_simple(self, mock_eventstream: mock.MagicMock) -> None: key = "foo" val = "bar" project = self.create_project() self.store_event( data={"tags": {key: val}, "timestamp": before_now(seconds=1)....
ProjectTagKeyDeleteTest
python
doocs__leetcode
solution/0400-0499/0465.Optimal Account Balancing/Solution.py
{ "start": 0, "end": 692 }
class ____: def minTransfers(self, transactions: List[List[int]]) -> int: g = defaultdict(int) for f, t, x in transactions: g[f] -= x g[t] += x nums = [x for x in g.values() if x] m = len(nums) f = [inf] * (1 << m) f[0] = 0 for i in ran...
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_origin.py
{ "start": 5572, "end": 7479 }
class ____(IHaveNew, LegacyNamedTupleMixin, CodeLocationOrigin): loadable_target_origin: LoadableTargetOrigin # pyright: ignore[reportIncompatibleMethodOverride] location_name: str # pyright: ignore[reportIncompatibleMethodOverride] container_image: Optional[str] entry_point: Sequence[str] contain...
InProcessCodeLocationOrigin
python
pytorch__pytorch
torch/_inductor/codegen/mps.py
{ "start": 1886, "end": 5881 }
class ____(ExprPrinter_): """Converts sympy expression to Metal code snippet""" def _print_FloorDiv(self, expr: sympy.Expr) -> str: x, div = expr.args x = self.doprint(x) div = self.doprint(div) if expr.is_integer: return f"c10::metal::floor_divide({x}, {div})" ...
MetalExprPrinter
python
numba__llvmlite
llvmlite/binding/module.py
{ "start": 7521, "end": 11174 }
class ____(_Iterator): kind = 'type' def _dispose(self): self._capi.LLVMPY_DisposeTypesIter(self) def __next__(self): vp = self._next() if vp: return TypeRef(vp) else: raise StopIteration def _next(self): return ffi.lib.LLVMPY_TypesIter...
_TypesIterator
python
Lightning-AI__lightning
tests/parity_pytorch/test_sync_batchnorm_parity.py
{ "start": 785, "end": 4395 }
class ____(LightningModule): def __init__(self, batch_size): super().__init__() self.batch_size = batch_size self.bn_layer = nn.BatchNorm1d(1) self.linear = nn.Linear(1, 10) self.bn_outputs = [] def on_train_start(self) -> None: assert isinstance(self.bn_layer, t...
SyncBNModule
python
kamyu104__LeetCode-Solutions
Python/convert-binary-number-in-a-linked-list-to-integer.py
{ "start": 165, "end": 433 }
class ____(object): def getDecimalValue(self, head): """ :type head: ListNode :rtype: int """ result = 0 while head: result = result*2 + head.val head = head.next return result
Solution
python
numpy__numpy
numpy/_core/tests/test_multiarray.py
{ "start": 271917, "end": 273944 }
class ____: def test_basic(self): dt_numeric = np.typecodes['AllFloat'] + np.typecodes['AllInteger'] dt_complex = np.typecodes['Complex'] # test real a = np.eye(3) for dt in dt_numeric + 'O': b = a.astype(dt) res = np.vdot(b, b) assert_(np...
TestVdot
python
pytorch__pytorch
test/inductor/test_mix_order_reduction.py
{ "start": 16516, "end": 16644 }
class ____(MixOrderReductionTest): pass if __name__ == "__main__": if HAS_GPU: run_tests()
NoMixOrderReductionTest
python
getsentry__sentry
src/sentry/models/groupmeta.py
{ "start": 2801, "end": 3383 }
class ____(Model): """ Arbitrary key/value store for Groups. Generally useful for things like storing metadata provided by plugins. """ __relocation_scope__ = RelocationScope.Excluded group = FlexibleForeignKey("sentry.Group") key = models.CharField(max_length=64) value = models.T...
GroupMeta
python
huggingface__transformers
src/transformers/models/qwen3/modeling_qwen3.py
{ "start": 23493, "end": 23592 }
class ____(GenericForTokenClassification, Qwen3PreTrainedModel): pass
Qwen3ForTokenClassification
python
pytorch__pytorch
torch/distributed/distributed_c10d.py
{ "start": 19863, "end": 23843 }
class ____: """ Container class for c10d process group state. This is used during registration and lookup of PG state. .. warning:: This is an experimental API intended to expose the inner workings of c10d and is subject to change.. """ def __init__(self) -> None: self._default...
_World
python
great-expectations__great_expectations
great_expectations/metrics/metric_results.py
{ "start": 1216, "end": 2074 }
class ____(MetricResult[Union[pd.Series, "pyspark.sql.Column", "BinaryExpression"]]): @classmethod def validate_value_type(cls, value): if isinstance(value, pd.Series): return value try: from great_expectations.compatibility.pyspark import pyspark if isinsta...
ConditionValues
python
pytorch__pytorch
benchmarks/functional_autograd_benchmark/torchvision_models.py
{ "start": 30767, "end": 35025 }
class ____(nn.Module): """This class computes an assignment between the targets and the predictions of the network For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more predictions than targets. In this case, we do a 1-to-1 matching of the best predicti...
HungarianMatcher
python
bokeh__bokeh
src/bokeh/command/subcommand.py
{ "start": 2391, "end": 5727 }
class ____(metaclass=ABCMeta): ''' Abstract base class for subcommands Subclasses should implement an ``invoke(self, args)`` method that accepts a set of argparse processed arguments as input. Subclasses should also define the following class attributes: * ``name`` a name for this subcommand ...
Subcommand
python
coleifer__peewee
playhouse/shortcuts.py
{ "start": 7246, "end": 11059 }
class ____(object): """ Mixin class that attempts to automatically reconnect to the database under certain error conditions. For example, MySQL servers will typically close connections that are idle for 28800 seconds ("wait_timeout" setting). If your application makes use of long-lived connecti...
ReconnectMixin
python
pandas-dev__pandas
asv_bench/benchmarks/frame_methods.py
{ "start": 19086, "end": 19951 }
class ____: params = [True, False] param_names = ["monotonic"] def setup(self, monotonic): N = 10000 K = 10 df = DataFrame( { "key1": Index([f"i-{i}" for i in range(N)], dtype=object).values.repeat( K ), ...
SortMultiKey
python
pydantic__pydantic
tests/benchmarks/test_discriminated_unions.py
{ "start": 324, "end": 1300 }
class ____(BaseModel): state_type: Literal['leaf'] AnyState = Annotated[Union[NestedState, LoopState, LeafState], Field(discriminator='state_type')] @pytest.mark.benchmark def test_schema_build(benchmark) -> None: @benchmark def run(): adapter = TypeAdapter(AnyState) assert adapter.core_...
LeafState
python
getsentry__sentry
src/sentry/issues/grouptype.py
{ "start": 12566, "end": 12964 }
class ____(GroupType): type_id = 1007 slug = "performance_consecutive_db_queries" description = "Consecutive DB Queries" category = GroupCategory.PERFORMANCE.value category_v2 = GroupCategory.DB_QUERY.value noise_config = NoiseConfig(ignore_limit=15) default_priority = PriorityLevel.LOW ...
PerformanceConsecutiveDBQueriesGroupType
python
walkccc__LeetCode
solutions/801. Minimum Swaps To Make Sequences Increasing/801.py
{ "start": 0, "end": 566 }
class ____: def minSwap(self, nums1: list[int], nums2: list[int]) -> int: keepAt = [math.inf] * len(nums1) swapAt = [math.inf] * len(nums1) keepAt[0] = 0 swapAt[0] = 1 for i in range(1, len(nums1)): if nums1[i] > nums1[i - 1] and nums2[i] > nums2[i - 1]: keepAt[i] = keepAt[i - 1] ...
Solution
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/guides/components/asset_factory/asset_factory_component.py
{ "start": 105, "end": 304 }
class ____(dg.Model): bucket: str = dg.Field source_object: str = dg.Field target_object: str = dg.Field sql: str = dg.Field # end_etl_job_model # start_asset_factory_component
EtlJob
python
mlflow__mlflow
mlflow/types/chat.py
{ "start": 4615, "end": 5430 }
class ____(BaseModel): """Common parameters used for chat completions and completion endpoints.""" temperature: float = Field(0.0, ge=0, le=2) n: int = Field(1, ge=1) stop: list[str] | None = Field(None, min_length=1) max_tokens: int | None = Field(None, ge=1) stream: bool | None = None str...
BaseRequestPayload
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefault2.py
{ "start": 1725, "end": 1839 }
class ____[*Ts = Unpack[tuple[int, ...]]]: ... # This should generate an error because T1 isn't legal here.
ClassTs8
python
tensorflow__tensorflow
tensorflow/python/distribute/checkpoint_utils_test.py
{ "start": 2062, "end": 5249 }
class ____( test.TestCase, parameterized.TestCase): def _get_test_object(self): checkpoint_dir = self.get_temp_dir() with self.cached_session() as session: v1, v2 = _create_checkpoints(session, checkpoint_dir) return checkpoint_dir, v1, v2 @combinations.generate( combinations.combine( ...
CheckpointUtilsWithDistributionStrategyTest
python
dagster-io__dagster
python_modules/libraries/dagster-fivetran/dagster_fivetran_tests/deprecated/test_asset_defs.py
{ "start": 7094, "end": 9472 }
class ____(DagsterFivetranTranslator): def get_asset_spec(self, props: FivetranConnectorTableProps) -> AssetSpec: default_spec = super().get_asset_spec(props) return default_spec.replace_attributes( key=["wacky", *["".join(reversed(item)) for item in default_spec.key.path], "wow"], ...
MyCustomTranslatorWackyKeys
python
ray-project__ray
python/ray/air/util/tensor_extensions/arrow.py
{ "start": 6572, "end": 20005 }
class ____(Exception): """Error raised when there is an issue converting data to Arrow.""" MAX_DATA_STR_LEN = 200 def __init__(self, data_str: str): if len(data_str) > self.MAX_DATA_STR_LEN: data_str = data_str[: self.MAX_DATA_STR_LEN] + "..." message = f"Error converting data ...
ArrowConversionError
python
instagram__MonkeyType
tests/test_stubs.py
{ "start": 41798, "end": 42422 }
class ____: cases = [ (Dummy.a_static_method, FunctionKind.STATIC), (Dummy.a_class_method.__func__, FunctionKind.CLASS), (Dummy.an_instance_method, FunctionKind.INSTANCE), (Dummy.a_property.fget, FunctionKind.PROPERTY), (a_module_func, FunctionKind.MODULE), ] if cache...
TestFunctionKind
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/firehose.py
{ "start": 978, "end": 2023 }
class ____(AwsBaseHook): """ Interact with Amazon Kinesis Firehose. Provide thick wrapper around :external+boto3:py:class:`boto3.client("firehose") <Firehose.Client>`. :param delivery_stream: Name of the delivery stream Additional arguments (such as ``aws_conn_id``) may be specified and are p...
FirehoseHook
python
getsentry__sentry
src/sentry/apidocs/examples/team_examples.py
{ "start": 1603, "end": 16326 }
class ____: ADD_TO_TEAM = [ OpenApiExample( "Join, request access to or add a member to a team", value=BASE_TEAM_1, status_codes=["201"], response_only=True, ) ] CREATE_TEAM = [ OpenApiExample( "Create a new team", ...
TeamExamples
python
sqlalchemy__sqlalchemy
test/sql/test_compare.py
{ "start": 5383, "end": 5508 }
class ____(TypeDecorator): impl = Integer cache_ok = True def __init__(self, arg): self.arg = arg
MyType3
python
sqlalchemy__sqlalchemy
test/orm/test_relationships.py
{ "start": 191750, "end": 193874 }
class ____(fixtures.MappedTest): """test usage of the old 'relation' function.""" run_inserts = "once" run_deletes = None @classmethod def define_tables(cls, metadata): Table( "users_table", metadata, Column("id", Integer, primary_key=True), ...
RelationDeprecationTest
python
getsentry__sentry
src/sentry/utils/pubsub.py
{ "start": 163, "end": 1054 }
class ____: # XXX(markus): Deprecated. Please use `sentry.utils.arroyo_producer.get_arroyo_producer`. def __init__(self, connection: dict[str, Any], asynchronous: bool = True) -> None: connection = connection or {} if "client.id" not in connection: connection["client.id"] = "sentry.u...
KafkaPublisher
python
getsentry__sentry
src/sentry/models/statistical_detectors.py
{ "start": 822, "end": 3135 }
class ____(Model): __relocation_scope__ = RelocationScope.Excluded # Meta data about the regression group date_added = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) # When the regression started, this is the breakpoint. date_regressed = models.DateT...
RegressionGroup
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/recompose_on_mount.py
{ "start": 214, "end": 539 }
class ____(Static): choices: reactive[list[str]] = reactive(list, recompose=True) def compose(self) -> ComposeResult: yield RadioSet(*self.choices) async def on_mount(self) -> None: self.choices.append("Foo") self.choices.append("Bar") self.mutate_reactive(Profile.choices) ...
Profile
python
chroma-core__chroma
chromadb/execution/expression/operator.py
{ "start": 10910, "end": 11121 }
class ____(Where): """Not in comparison - value is not in a list""" key: str values: List[Any] def to_dict(self) -> Dict[str, Any]: return {self.key: {"$nin": self.values}} @dataclass
Nin
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 131060, "end": 134171 }
class ____(Response): """ Response of tasks.archive_many endpoint. :param succeeded: :type succeeded: Sequence[dict] :param failed: :type failed: Sequence[dict] """ _service = "tasks" _action = "archive_many" _version = "2.23" _schema = { "definitions": {}, ...
ArchiveManyResponse
python
great-expectations__great_expectations
great_expectations/render/renderer/site_index_page_renderer.py
{ "start": 764, "end": 18020 }
class ____(Renderer): @classmethod def _generate_expectation_suites_link_table(cls, index_links_dict): table_options = { "search": "true", "trimOnSearch": "false", "visibleSearch": "true", "rowStyle": "rowStyleLinks", "rowAttributes": "rowAttri...
SiteIndexPageRenderer
python
modin-project__modin
modin/core/execution/dispatching/factories/factories.py
{ "start": 3466, "end": 22168 }
class ____(object): io_cls: typing.Type[BaseIO] = None # The module where the I/O functionality exists. @classmethod def get_info(cls) -> FactoryInfo: """ Get information about current factory. Notes ----- It parses factory name, so it must be conformant with how `...
BaseFactory
python
huggingface__transformers
tests/models/audio_spectrogram_transformer/test_modeling_audio_spectrogram_transformer.py
{ "start": 5167, "end": 8259 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as AST does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = ( ( ASTModel, ASTForAud...
ASTModelTest
python
lepture__authlib
authlib/integrations/requests_client/assertion_session.py
{ "start": 446, "end": 2073 }
class ____(AssertionClient, Session): """Constructs a new Assertion Framework for OAuth 2.0 Authorization Grants per RFC7521_. .. _RFC7521: https://tools.ietf.org/html/rfc7521 """ token_auth_class = AssertionAuth JWT_BEARER_GRANT_TYPE = JWTBearerGrant.GRANT_TYPE ASSERTION_METHODS = { ...
AssertionSession
python
readthedocs__readthedocs.org
readthedocs/api/v3/serializers.py
{ "start": 2745, "end": 4193 }
class ____(BaseLinksSerializer): _self = serializers.SerializerMethodField() version = serializers.SerializerMethodField() project = serializers.SerializerMethodField() notifications = serializers.SerializerMethodField() def get__self(self, obj): path = reverse( "projects-builds...
BuildLinksSerializer
python
ray-project__ray
python/ray/tests/spark/test_basic.py
{ "start": 10054, "end": 16963 }
class ____: @classmethod def setup_class(cls): cls.spark = ( SparkSession.builder.master("local[2]") .config("spark.task.cpus", "1") .config("spark.task.maxFailures", "1") .getOrCreate() ) @classmethod def teardown_class(cls): time...
TestSparkLocalCluster
python
realpython__materials
arcade-a-primer/arcade_game.py
{ "start": 614, "end": 7859 }
class ____(arcade.Window): """Space Shooter side scroller game Player starts on the left, enemies appear on the right Player can move anywhere, but not off screen Enemies fly to the left at variable speed Collisions end the game """ def __init__(self, width: int, height: int, title: str): ...
SpaceShooter
python
getsentry__sentry
src/sentry/roles/manager.py
{ "start": 3882, "end": 7107 }
class ____: def __init__( self, org_config: Iterable[Mapping[str, Any]], team_config: Iterable[Mapping[str, Any]], default_org_role: str | None = None, ) -> None: self.organization_roles: RoleLevel[OrganizationRole] = RoleLevel( ( OrganizationR...
RoleManager
python
huggingface__transformers
src/transformers/models/moonshine/modeling_moonshine.py
{ "start": 16381, "end": 18371 }
class ____(GradientCheckpointingLayer): def __init__(self, config: MoonshineConfig, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = MoonshineAttention( config=config, layer_idx=layer_idx, is_causal=False, ...
MoonshineEncoderLayer
python
ray-project__ray
python/ray/_private/external_storage.py
{ "start": 15238, "end": 20582 }
class ____(ExternalStorage): """The external storage class implemented by smart_open. (https://github.com/RaRe-Technologies/smart_open) Smart open supports multiple backend with the same APIs. To use this implementation, you should pre-create the given uri. For example, if your uri is a local file...
ExternalStorageSmartOpenImpl
python
run-llama__llama_index
llama-index-core/llama_index/core/selectors/pydantic_selectors.py
{ "start": 1366, "end": 3325 }
class ____(BaseSelector): def __init__(self, selector_program: BasePydanticProgram) -> None: self._selector_program = selector_program @classmethod def from_defaults( cls, program: Optional[BasePydanticProgram] = None, llm: Optional["OpenAI"] = None, prompt_template_...
PydanticSingleSelector
python
spack__spack
lib/spack/spack/hooks/__init__.py
{ "start": 794, "end": 2329 }
class ____: #: Order in which hooks are executed HOOK_ORDER = [ "spack.hooks.module_file_generation", "spack.hooks.licensing", "spack.hooks.sbang", "spack.hooks.windows_runtime_linkage", "spack.hooks.drop_redundant_rpaths", "spack.hooks.absolutify_elf_sonames", ...
_HookRunner
python
apache__thrift
lib/py/src/transport/TTwisted.py
{ "start": 9668, "end": 10904 }
class ____(resource.Resource): allowedMethods = ('POST',) def __init__(self, processor, inputProtocolFactory, outputProtocolFactory=None): resource.Resource.__init__(self) self.inputProtocolFactory = inputProtocolFactory if outputProtocolFactory is None: se...
ThriftResource
python
pytorch__pytorch
torch/distributed/pipelining/schedules.py
{ "start": 73793, "end": 74237 }
class ____: def __init__( self, schedule_ref: _PipelineSchedule, arg_mbs: list[tuple] | None = None, kwarg_mbs: list[dict] | None = None, target_mbs: list | None = None, losses: list | None = None, ): self.schedule_ref = schedule_ref self.arg_mbs =...
_PipelineContext
python
django__django
tests/migrations/test_migrations_squashed_complex_multi_apps/app2/1_squashed_2.py
{ "start": 35, "end": 262 }
class ____(migrations.Migration): replaces = [ ("app2", "1_auto"), ("app2", "2_auto"), ] dependencies = [("app1", "1_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
Migration
python
pytorch__pytorch
torch/_inductor/mkldnn_ir.py
{ "start": 42088, "end": 43615 }
class ____(ExternKernelAlloc): def __init__( self, layout, inputs, constant_args=(), ) -> None: """ inputs = [x, w, qGroupSize, qScalesAndZeros] constant_args = () """ assert len(inputs) == 4 assert len(constant_args) == 0 s...
WeightInt4PackMatmul
python
tqdm__tqdm
tqdm/std.py
{ "start": 1985, "end": 3938 }
class ____(object): """ Provide a default write lock for thread and multiprocessing safety. Works only on platforms supporting `fork` (so Windows is excluded). You must initialise a `tqdm` or `TqdmDefaultWriteLock` instance before forking in order for the write lock to work. On Windows, you need...
TqdmDefaultWriteLock
python
vyperlang__vyper
vyper/ast/nodes.py
{ "start": 37769, "end": 38156 }
class ____(ExprNode): __slots__ = ("value",) def validate(self): if not isinstance(self.value, Call): # TODO: investigate wrong col_offset for `self.value` raise StructureException( "`extcall` must be followed by a function call", self.value, ...
ExtCall
python
pytorch__pytorch
test/dynamo/cpython/3_13/seq_tests.py
{ "start": 1813, "end": 1976 }
class ____: 'Sequence using __getitem__' def __init__(self, seqn): self.seqn = seqn def __getitem__(self, i): return self.seqn[i]
Sequence
python
getsentry__responses
responses/tests/test_responses.py
{ "start": 70111, "end": 73005 }
class ____: def test_strict_wrapper(self): """Test that assert_all_requests_are_fired could be applied to the decorator.""" @responses.activate(assert_all_requests_are_fired=True) def run_strict(): responses.add(responses.GET, "https://someapi1.com/", "success") resp...
TestStrictWrapper
python
django__django
tests/mail/tests.py
{ "start": 103849, "end": 105296 }
class ____(BaseEmailBackendTests, SimpleTestCase): email_backend = "django.core.mail.backends.locmem.EmailBackend" def get_mailbox_content(self): return [m.message() for m in mail.outbox] def flush_mailbox(self): mail.outbox = [] def tearDown(self): super().tearDown() ...
LocmemBackendTests
python
huggingface__transformers
src/transformers/models/biogpt/modeling_biogpt.py
{ "start": 4682, "end": 10280 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__( self, embed_dim: int, num_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, config: Opti...
BioGptAttention
python
rq__rq
tests/test_scheduler.py
{ "start": 967, "end": 6451 }
class ____(RQTestCase): def test_get_jobs_to_enqueue(self): """Getting job ids to enqueue from ScheduledJobRegistry.""" queue = Queue(connection=self.connection) registry = ScheduledJobRegistry(queue=queue) timestamp = current_timestamp() self.connection.zadd(registry.key, {...
TestScheduledJobRegistry
python
gevent__gevent
src/greentest/3.14/test_threading_local.py
{ "start": 6520, "end": 6606 }
class ____(unittest.TestCase, BaseLocalTest): _local = _thread._local
ThreadLocalTest
python
gevent__gevent
src/greentest/3.9/test_ssl.py
{ "start": 44571, "end": 74745 }
class ____(unittest.TestCase): def test_constructor(self): for protocol in PROTOCOLS: if has_tls_protocol(protocol): with warnings_helper.check_warnings(): ctx = ssl.SSLContext(protocol) self.assertEqual(ctx.protocol, protocol) with wa...
ContextTests
python
ray-project__ray
release/ray_release/tests/test_buildkite.py
{ "start": 1649, "end": 1781 }
class ____(MockReturn): def builds(self): return self def artifacts(self): return self
MockBuildkitePythonAPI
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_sagemaker_base.py
{ "start": 7928, "end": 10200 }
class ____: @patch( "airflow.providers.amazon.aws.hooks.sagemaker.SageMakerHook.conn", new_callable=mock.PropertyMock, ) def test_create_experiment( self, conn_mock, session, clean_dags_dagruns_and_dagbundles, testing_dag_bundle ): conn_mock().create_experiment.return_val...
TestSageMakerExperimentOperator
python
ray-project__ray
python/ray/dashboard/modules/usage_stats/usage_stats_head.py
{ "start": 429, "end": 7996 }
class ____(dashboard_utils.DashboardHeadModule): def __init__(self, config: dashboard_utils.DashboardHeadModuleConfig): super().__init__(config) self.usage_stats_enabled = ray_usage_lib.usage_stats_enabled() self.usage_stats_prompt_enabled = ray_usage_lib.usage_stats_prompt_enabled() ...
UsageStatsHead
python
ansible__ansible
lib/ansible/_internal/_errors/_alarm_timeout.py
{ "start": 145, "end": 2519 }
class ____(BaseException): """A general purpose timeout.""" _MAX_TIMEOUT = 100_000_000 """ The maximum supported timeout value. This value comes from BSD's alarm limit, which is due to that function using setitimer. """ def __init__(self, timeout: int) -> None: self.timeout = timeo...
AnsibleTimeoutError
python
sphinx-doc__sphinx
sphinx/domains/python/_object.py
{ "start": 4903, "end": 4963 }
class ____(PyXrefMixin, GroupedField): pass
PyGroupedField
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 163700, "end": 167410 }
class ____(Operation): def __init__(self, pad_width, mode="constant", *, name=None): super().__init__(name=name) self.pad_width = self._process_pad_width(pad_width) self.mode = mode def _process_pad_width(self, pad_width): if isinstance(pad_width, int): return ((pad_...
Pad
python
getsentry__sentry
src/sentry/incidents/models/incident.py
{ "start": 1298, "end": 5095 }
class ____(BaseManager["Incident"]): CACHE_KEY = "incidents:active:%s:%s:%s" def fetch_for_organization(self, organization, projects): return self.filter(organization=organization, projects__in=projects).distinct() @classmethod def _build_active_incident_cache_key(cls, alert_rule_id, project_i...
IncidentManager
python
langchain-ai__langchain
libs/langchain_v1/langchain/agents/middleware/context_editing.py
{ "start": 1239, "end": 5368 }
class ____(ContextEdit): """Configuration for clearing tool outputs when token limits are exceeded.""" trigger: int = 100_000 """Token count that triggers the edit.""" clear_at_least: int = 0 """Minimum number of tokens to reclaim when the edit runs.""" keep: int = 3 """Number of most rec...
ClearToolUsesEdit
python
modin-project__modin
modin/config/envvars.py
{ "start": 45208, "end": 47032 }
class ____(EnvironmentVariable, type=bool): """ Set to true to use Modin's dynamic-partitioning implementation where possible. Please refer to documentation for cases where enabling this options would be beneficial: https://modin.readthedocs.io/en/stable/usage_guide/optimization_notes/index.html#dynami...
DynamicPartitioning
python
pandas-dev__pandas
pandas/tseries/frequencies.py
{ "start": 13031, "end": 18529 }
class ____(_FrequencyInferer): def _infer_daily_rule(self): if self.is_unique: return self._get_daily_rule() def _is_multiple(us, mult: int) -> bool: return us % mult == 0 def _maybe_add_count(base: str, count: float) -> str: if count != 1: assert count == int(count) ...
_TimedeltaFrequencyInferer
python
dagster-io__dagster
python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/commands/config.py
{ "start": 3868, "end": 4552 }
class ____(HTTPServer): organization: Optional[str] = None token: Optional[str] = None def __init__(self, host: tuple[str, int], nonce: str): super().__init__(host, create_token_callback_handler(nonce)) def shutdown(self): # Stop serving the token server # https://stackoverflow...
TokenServer
python
wandb__wandb
wandb/sdk/wandb_setup.py
{ "start": 1661, "end": 3213 }
class ____: """Early logger which captures logs in memory until logging can be configured.""" def __init__(self) -> None: self._log: list[tuple] = [] self._exception: list[tuple] = [] # support old warn() as alias of warning() self.warn = self.warning def debug(self, msg: s...
_EarlyLogger
python
django__django
tests/messages_tests/base.py
{ "start": 920, "end": 13980 }
class ____: storage_class = default_storage levels = { "debug": constants.DEBUG, "info": constants.INFO, "success": constants.SUCCESS, "warning": constants.WARNING, "error": constants.ERROR, } @classmethod def setUpClass(cls): cls.enterClassContext( ...
BaseTests
python
walkccc__LeetCode
solutions/1823. Find the Winner of the Circular Game/1823.py
{ "start": 0, "end": 474 }
class ____: def findTheWinner(self, n: int, k: int) -> int: # True if i-th friend is left friends = [False] * n friendCount = n fp = 0 # friends' index while friendCount > 1: for _ in range(k): while friends[fp % n]: # The friend is not there. fp += 1 # Point to the ne...
Solution
python
pypa__pip
src/pip/_vendor/pyproject_hooks/_in_process/_in_process.py
{ "start": 10180, "end": 12216 }
class ____(Exception): """For internal use when backend raises UnsupportedOperation""" def __init__(self, traceback): self.traceback = traceback def build_sdist(sdist_directory, config_settings): """Invoke the mandatory build_sdist hook.""" backend = _build_backend() try: return b...
GotUnsupportedOperation
python
getsentry__sentry
tests/sentry/rules/processing/test_buffer_processing.py
{ "start": 3576, "end": 8210 }
class ____(CreateEventTestCase, PerformanceIssueTestCase): buffer_timestamp = (FROZEN_TIME + timedelta(seconds=1)).timestamp() def assert_buffer_cleared(self, project_id): rule_group_data = buffer.backend.get_hash(Project, {"project_id": project_id}) assert rule_group_data == {} def setUp(...
ProcessDelayedAlertConditionsTestBase
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 103963, "end": 104197 }
class ____(SendrecvmsgBase): # Defines flags to be checked in msg_flags for SCTP sockets. @property def msg_flags_eor_indicator(self): return super().msg_flags_eor_indicator | socket.MSG_EOR
SendrecvmsgSCTPFlagsBase
python
pytorch__pytorch
torch/onnx/_internal/exporter/_capture_strategies.py
{ "start": 9040, "end": 10566 }
class ____(CaptureStrategy): def _capture( self, model, args, kwargs, dynamic_shapes ) -> torch.export.ExportedProgram: ep = torch.export.draft_export( model, args, kwargs=kwargs, dynamic_shapes=dynamic_shapes ) report = ep._report # type: ignore[attr-defined] ...
TorchExportDraftExportStrategy
python
huggingface__transformers
src/transformers/models/mistral3/modular_mistral3.py
{ "start": 9743, "end": 14388 }
class ____(LlavaForConditionalGeneration): def get_image_features( self, pixel_values: torch.FloatTensor, image_sizes: torch.Tensor, vision_feature_layer: Optional[Union[int, list[int]]] = None, **kwargs, ): return self.model.get_image_features( pixel_...
Mistral3ForConditionalGeneration
python
tensorflow__tensorflow
tensorflow/dtensor/python/tests/input_util_test.py
{ "start": 21052, "end": 22941 }
class ____(test_util.DTensorBaseTest): def setUp(self): super().setUp() mesh = mesh_util.create_mesh( devices=['CPU:%d' % i for i in range(8)], mesh_dims=[(MESH_DIM_BATCH, 8)]) self.mesh = self.configTestMesh({'CPU': mesh}) self.images = stateless_random_ops.stateless_random_uniform(...
DTensorIteratorSpecTest
python
scipy__scipy
scipy/interpolate/tests/test_bary_rational.py
{ "start": 11682, "end": 12231 }
class ____: # FloaterHormann class with reference batch behaviour def __init__(self, x, y, axis): y = np.moveaxis(y, axis, -1) self._batch_shape = y.shape[:-1] self._interps = [FloaterHormannInterpolator(x, yi,) for yi in y.reshape(-1, y.shape[-1])] self....
BatchFloaterHormann
python
pytorch__pytorch
torch/ao/pruning/_experimental/data_sparsifier/data_norm_sparsifier.py
{ "start": 237, "end": 7778 }
class ____(BaseDataSparsifier): r"""L1-Norm Sparsifier This sparsifier computes the *L1-norm* of every sparse block and "zeroes-out" the ones with the lowest norm. The level of sparsity defines how many of the blocks is removed. This sparsifier is controlled by three variables: 1. `sparsity_leve...
DataNormSparsifier
python
apache__airflow
providers/standard/src/airflow/providers/standard/sensors/time.py
{ "start": 1773, "end": 4513 }
class ____(BaseSensorOperator): """ Waits until the specified time of the day. :param target_time: time after which the job succeeds :param deferrable: whether to defer execution .. seealso:: For more information on how to use this sensor, take a look at the guide: :ref:`howto/oper...
TimeSensor
python
pypa__warehouse
tests/unit/manage/views/test_teams.py
{ "start": 995, "end": 5820 }
class ____: @pytest.mark.usefixtures("_enable_organizations") def test_manage_team(self, db_request, organization_service, user_service): team = TeamFactory.create() view = team_views.ManageTeamSettingsViews(team, db_request) result = view.manage_team() form = result["save_team_...
TestManageTeamSettings
python
getsentry__sentry
src/sentry/backup/crypto.py
{ "start": 1440, "end": 1678 }
class ____(ABC): """ A `IO[bytes]`-wrapper that contains relevant information and methods to encrypt some an in-memory JSON-ifiable dict. """ @abstractmethod def get_public_key_pem(self) -> bytes: pass
Encryptor
python
pymupdf__PyMuPDF
src/__init__.py
{ "start": 93946, "end": 94948 }
class ____: def __init__(self, type_): """Supported are GRAY, RGB and CMYK.""" if isinstance( type_, mupdf.FzColorspace): self.this = type_ elif type_ == CS_GRAY: self.this = mupdf.FzColorspace(mupdf.FzColorspace.Fixed_GRAY) elif type_ == CS_CMYK: ...
Colorspace
python
HIPS__autograd
autograd/core.py
{ "start": 8318, "end": 8361 }
class ____(Box): __slots__ = []
SparseBox
python
allegroai__clearml
clearml/utilities/deferred.py
{ "start": 1177, "end": 1520 }
class ____(dict): def __init__(self, factory: Callable[[Any], Any], *args: Any, **kwargs: Any) -> None: super(ParameterizedDefaultDict, self).__init__(*args, **kwargs) self._factory = factory def __missing__(self, key: Any) -> Any: self[key] = self._factory(key) return self[key]...
ParameterizedDefaultDict
python
tensorflow__tensorflow
tensorflow/python/tpu/tpu_test.py
{ "start": 3136, "end": 4248 }
class ____(test.TestCase): def testUsingInfeedQueueWithRegularizer(self): """Test that Layer regularizers can reference data created in loops.""" with ops.Graph().as_default(): def make_regularizer(scale): def regularizer(inputs): return scale * math_ops.reduce_sum(math_ops.square(i...
TPULayerRewriteTest
python
pytorch__pytorch
test/torch_np/test_ufuncs_basic.py
{ "start": 4259, "end": 6334 }
class ____(TestCase): def get_xy(self, ufunc): return np.arange(5, dtype="float64"), np.arange(8, 13, dtype="float64") @parametrize_binary_ufuncs def test_scalar(self, ufunc): # check that ufunc accepts a scalar and the result is convertible to scalar xy = self.get_xy(ufunc) ...
TestBinaryUfuncs
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 73534, "end": 74859 }
class ____(Operation): def __init__(self, axis=None, dtype=None, *, name=None): super().__init__(name=name) self.axis = axis self.dtype = None if dtype is None else backend.standardize_dtype(dtype) def call(self, x): return backend.numpy.cumsum(x, axis=self.axis, dtype=self.dtyp...
Cumsum
python
PyCQA__pylint
tests/functional/s/super/super_init_not_called.py
{ "start": 1410, "end": 1581 }
class ____(ctypes.Union): def __init__(self): pass # Should not be called on abstract __init__ methods # https://github.com/pylint-dev/pylint/issues/3975
MyUnion
python
encode__django-rest-framework
rest_framework/fields.py
{ "start": 62139, "end": 64294 }
class ____(Field): child = _UnvalidatedField() initial = {} default_error_messages = { 'not_a_dict': _('Expected a dictionary of items but got type "{input_type}".'), 'empty': _('This dictionary may not be empty.'), } def __init__(self, **kwargs): self.child = kwargs.pop('ch...
DictField
python
mlflow__mlflow
mlflow/types/chat.py
{ "start": 5538, "end": 5682 }
class ____(BaseModel): prompt_tokens: int | None = None completion_tokens: int | None = None total_tokens: int | None = None
ChatUsage
python
astropy__astropy
astropy/io/votable/converters.py
{ "start": 24852, "end": 24994 }
class ____(FloatingPoint): """ Handles the double datatype. Double-precision IEEE floating-point. """ format = "f8"
Double
python
ethereum__web3.py
web3/types.py
{ "start": 10102, "end": 10202 }
class ____(TypedDict): difficulty: int head: HexStr network: int version: int
Protocol
python
astropy__astropy
astropy/table/mixins/dask.py
{ "start": 109, "end": 225 }
class ____(ParentDtypeInfo): @staticmethod def default_format(val): return f"{val.compute()}"
DaskInfo
python
tqdm__tqdm
examples/tqdm_wget.py
{ "start": 1767, "end": 3511 }
class ____(tqdm): """Alternative Class-based version of the above. Provides `update_to(n)` which uses `tqdm.update(delta_n)`. Inspired by [twine#242](https://github.com/pypa/twine/pull/242), [here](https://github.com/pypa/twine/commit/42e55e06). """ def update_to(self, b=1, bsize=1, tsize=Non...
TqdmUpTo