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/array-partition-i.py
{ "start": 849, "end": 1073 }
class ____(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ nums = sorted(nums) return sum([nums[i] for i in range(0, len(nums), 2)])
Solution3
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/logging_ops_test.py
{ "start": 1457, "end": 2464 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testAssertDivideByZero(self): with self.cached_session() as sess: epsilon = ops.convert_to_tensor(1e-20) x = ops.convert_to_tensor(0.0) y = ops.convert_to_tensor(1.0) z = ops.convert_to_tensor(2.0) # assert(epsilon < y) ...
LoggingOpsTest
python
pytorch__pytorch
test/onnx/test_custom_ops.py
{ "start": 2631, "end": 3876 }
class ____(pytorch_test_common.ExportTestCase): opset_version = 14 keep_initializers_as_inputs = False onnx_shape_inference = True def test_contrib_op_with_loop(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() self.gelu ...
TestExportAsContribOps
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/asset/__init__.py
{ "start": 17174, "end": 17311 }
class ____(Asset): """A representation of dataset dependencies between workflows.""" asset_type: ClassVar[str] = "dataset"
Dataset
python
kamyu104__LeetCode-Solutions
Python/maximum-69-number.py
{ "start": 387, "end": 566 }
class ____(object): def maximum69Number (self, num): """ :type num: int :rtype: int """ return int(str(num).replace('6', '9', 1))
Solution2
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/sensors/kinesis_analytics.py
{ "start": 1416, "end": 3355 }
class ____(AwsBaseSensor[KinesisAnalyticsV2Hook]): """ General sensor behaviour for AWS Managed Service for Apache Flink. Subclasses must set the following fields: - ``INTERMEDIATE_STATES`` - ``FAILURE_STATES`` - ``SUCCESS_STATES`` - ``FAILURE_MESSAGE`` - ``SUCCESS_...
KinesisAnalyticsV2BaseSensor
python
huggingface__transformers
src/transformers/models/flex_olmo/modular_flex_olmo.py
{ "start": 10584, "end": 10636 }
class ____(Olmo2Attention): pass
FlexOlmoAttention
python
tensorflow__tensorflow
tensorflow/python/framework/test_combinations.py
{ "start": 2385, "end": 4360 }
class ____: """Customize the behavior of `generate()` and the tests that it executes. Here is sequence of steps for executing a test combination: 1. The test combination is evaluated for whether it should be executed in the given environment by calling `should_execute_combination`. 2. If the test co...
TestCombination
python
FactoryBoy__factory_boy
tests/alchemyapp/models.py
{ "start": 987, "end": 1098 }
class ____(Base): __tablename__ = 'NonIntegerPk' id = Column(Unicode(20), primary_key=True)
NonIntegerPk
python
huggingface__transformers
src/transformers/models/dinov2_with_registers/modeling_dinov2_with_registers.py
{ "start": 3552, "end": 9067 }
class ____(nn.Module): """ Construct the CLS token, mask token, register tokens, position and patch embeddings. """ def __init__(self, config: Dinov2WithRegistersConfig) -> None: super().__init__() self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size)) self.mask_t...
Dinov2WithRegistersEmbeddings
python
sqlalchemy__sqlalchemy
test/orm/test_lockmode.py
{ "start": 401, "end": 1860 }
class ____(_fixtures.FixtureTest): @classmethod def setup_mappers(cls): User, users = cls.classes.User, cls.tables.users cls.mapper_registry.map_imperatively(User, users) def _assert( self, read=False, nowait=False, of=None, key_share=None, as...
ForUpdateTest
python
google__jax
jax/_src/pallas/mosaic_gpu/core.py
{ "start": 29443, "end": 30041 }
class ____(state_types.Transform): device_id: Any device_id_type: pallas_primitives.DeviceIdType def transform_shape(self, shape): return shape def transform_dtype(self, dtype): return dtype def untransform_index( self, idxs: tuple[Index, ...] ) -> tuple[tuple[Index, ...], state_types.Trans...
PeerMemRef
python
pappasam__jedi-language-server
jedi_language_server/notebook_utils.py
{ "start": 1626, "end": 1765 }
class ____(NamedTuple): """A text edit in a document.""" uri: str text_edit: Union[TextEdit, AnnotatedTextEdit]
DocumentTextEdit
python
chroma-core__chroma
chromadb/rate_limit/simple_rate_limit/__init__.py
{ "start": 283, "end": 723 }
class ____(RateLimitEnforcer): """ A naive implementation of a rate limit enforcer that allows all requests. """ def __init__(self, system: System) -> None: super().__init__(system) @override def rate_limit(self, func: T) -> T: @wraps(func) def wrapper(*args: Any, **kwa...
SimpleRateLimitEnforcer
python
huggingface__transformers
src/transformers/models/phi3/modeling_phi3.py
{ "start": 2836, "end": 9509 }
class ____(nn.Module): inv_freq: torch.Tensor # fix linting for `register_buffer` def __init__(self, config: Phi3Config, device=None): super().__init__() self.max_seq_len_cached = config.max_position_embeddings self.original_max_seq_len = config.max_position_embeddings self.co...
Phi3RotaryEmbedding
python
walkccc__LeetCode
solutions/384. Shuffle an Array/384.py
{ "start": 0, "end": 317 }
class ____: def __init__(self, nums: list[int]): self.nums = nums def reset(self) -> list[int]: return self.nums def shuffle(self) -> list[int]: arr = self.nums.copy() for i in range(len(arr) - 1, 0, -1): j = random.randint(0, i) arr[i], arr[j] = arr[j], arr[i] return arr
Solution
python
falconry__falcon
falcon/routing/converters.py
{ "start": 6752, "end": 7816 }
class ____(BaseConverter): """Field converted used to match the rest of the path. This field converter matches the remainder of the URL path, returning it as a string. This converter is currently supported only when used at the end of the URL template. The classic routing rules of falcon appl...
PathConverter
python
pyca__cryptography
src/cryptography/hazmat/primitives/_serialization.py
{ "start": 4648, "end": 5123 }
class ____(KeySerializationEncryption): def __init__( self, format: PrivateFormat, password: bytes, *, kdf_rounds: int | None, hmac_hash: HashAlgorithm | None, key_cert_algorithm: PBES | None, ): self._format = format self.password = passwo...
_KeySerializationEncryption
python
getsentry__sentry
src/sentry/migrations/0916_delete_open_period_rows.py
{ "start": 776, "end": 2102 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # o...
Migration
python
tornadoweb__tornado
tornado/options.py
{ "start": 17982, "end": 19163 }
class ____: """`mock.patch` compatible wrapper for `OptionParser`. As of ``mock`` version 1.0.1, when an object uses ``__getattr__`` hooks instead of ``__dict__``, ``patch.__exit__`` tries to delete the attribute it set instead of setting a new one (assuming that the object does not capture ``__set...
_Mockable
python
pytorch__pytorch
torch/testing/_internal/common_dist_composable.py
{ "start": 518, "end": 886 }
class ____(nn.Module): def __init__(self, device: torch.device): super().__init__() self.l1 = nn.Linear(100, 100, device=device) self.u1 = UnitModule(device) self.u2 = UnitModule(device) self.l2 = nn.Linear(100, 100, device=device) def forward(self, x): return se...
CompositeModel
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_ordered_dict.py
{ "start": 30497, "end": 31399 }
class ____(OrderedDictTests, __TestCase): module = py_coll OrderedDict = py_coll.OrderedDict def test_issue119004_attribute_error(self): with torch._dynamo.error_on_graph_break(False): class Key(_TriggerSideEffectOnEqual): def side_effect(self): del ...
PurePythonOrderedDictTests
python
celery__celery
t/unit/backends/test_base.py
{ "start": 1744, "end": 1958 }
class ____: def test_create_exception_cls(self): assert serialization.create_exception_cls('FooError', 'm') assert serialization.create_exception_cls('FooError', 'm', KeyError)
test_serialization
python
django-crispy-forms__django-crispy-forms
crispy_forms/bootstrap.py
{ "start": 325, "end": 3789 }
class ____(Field): """ Layout object for rendering a field with prepended and appended text. Attributes ---------- template : str The default template which this Layout Object will be rendered with. attrs : dict Attributes to be applied to the field. These are converted ...
PrependedAppendedText
python
huggingface__transformers
src/transformers/models/instructblipvideo/modeling_instructblipvideo.py
{ "start": 11177, "end": 12281 }
class ____(GradientCheckpointingLayer): def __init__(self, config: InstructBlipVideoConfig): super().__init__() self.embed_dim = config.hidden_size self.self_attn = InstructBlipVideoAttention(config) self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps) s...
InstructBlipVideoEncoderLayer
python
kamyu104__LeetCode-Solutions
Python/best-time-to-buy-and-sell-stock-v.py
{ "start": 38, "end": 694 }
class ____(object): def maximumProfit(self, prices, k): """ :type prices: List[int] :type k: int :rtype: int """ dp = [0]*(len(prices)+1) result = 0 for i in xrange(k): x, y = float("-inf"), float("-inf") new_dp = [float("-inf")...
Solution
python
langchain-ai__langchain
libs/core/langchain_core/callbacks/base.py
{ "start": 12631, "end": 13871 }
class ____( LLMManagerMixin, ChainManagerMixin, ToolManagerMixin, RetrieverManagerMixin, CallbackManagerMixin, RunManagerMixin, ): """Base callback handler for LangChain.""" raise_error: bool = False """Whether to raise an error if an exception occurs.""" run_inline: bool = Fal...
BaseCallbackHandler
python
pypa__pip
src/pip/_vendor/resolvelib/resolvers/exceptions.py
{ "start": 1336, "end": 1599 }
class ____(ResolutionError, Generic[RT, CT]): def __init__(self, causes: Collection[RequirementInformation[RT, CT]]): super().__init__(causes) # causes is a list of RequirementInformation objects self.causes = causes
ResolutionImpossible
python
huggingface__transformers
src/transformers/models/donut/modeling_donut_swin.py
{ "start": 28789, "end": 30938 }
class ____(GradientCheckpointingLayer): def __init__(self, config, dim, input_resolution, depth, num_heads, drop_path, downsample): super().__init__() self.config = config self.dim = dim self.blocks = nn.ModuleList( [ DonutSwinLayer( co...
DonutSwinStage
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/dist_autograd_test.py
{ "start": 39643, "end": 48237 }
class ____(CommonDistAutogradTest): # Sparse tests only work with TensorPipeAgent. @dist_init def test_graph_for_builtin_call_sparse(self): self._test_graph(torch.add, ExecMode.RPC_SYNC, True) @dist_init def test_graph_for_python_call_sparse(self): self._test_graph(my_py_add, ExecMo...
TensorPipeAgentDistAutogradTest
python
streamlit__streamlit
lib/streamlit/errors.py
{ "start": 4316, "end": 4786 }
class ____(StreamlitAPIException, Warning): """Used to display a warning. Note that this should not be "raised", but passed to st.exception instead. """ def __init__(self, *args: Any) -> None: super().__init__(*args) import inspect import traceback f = inspect.curr...
StreamlitAPIWarning
python
pytorch__pytorch
torch/utils/tensorboard/_pytorch_graph.py
{ "start": 3676, "end": 13908 }
class ____: """Helper class to convert torch.nn.Module to GraphDef proto and visualization with TensorBoard. GraphDef generation operates in two passes: In the first pass, all nodes are read and saved to two lists. One list is for input/output nodes (nodes_io), which only have inbound or outbound ...
GraphPy
python
gevent__gevent
src/gevent/tests/test__pywsgi.py
{ "start": 22927, "end": 22997 }
class ____(TestChunkedApp): chunks = [b'a' * 8192] * 3
TestBigChunks
python
pytorch__pytorch
torch/testing/_internal/common_distributed.py
{ "start": 24075, "end": 40117 }
class ____(TestCase): MAIN_PROCESS_RANK = -1 # This exit code is used to indicate that the test code had an error and # exited abnormally. There are certain tests that might use sys.exit() to # simulate failures and in those cases, we can't have an exit code of 0, # but we still want to ensure we di...
MultiProcessTestCase
python
sqlalchemy__sqlalchemy
test/orm/test_selectin_relations.py
{ "start": 94303, "end": 97325 }
class ____(fixtures.DeclarativeMappedTest): @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class A(Base): __tablename__ = "a" id = Column(Integer, primary_key=True) b_id = Column(ForeignKey("b.id")) a2_id = Column(ForeignKey("a2...
TestExistingRowPopulation
python
tensorflow__tensorflow
tensorflow/python/distribute/strategy_common_test.py
{ "start": 17105, "end": 22930 }
class ____(test.TestCase, parameterized.TestCase): def testDense(self, strategy, tf_function): if (strategy_test_lib.is_tpu_strategy(strategy) and tf_function is combinations.no_tf_function): self.skipTest('Skip TPUStrategy + eager combination.') @tf_function def fn(): def replica_f...
AllReduceTest
python
django__django
tests/generic_relations/test_forms.py
{ "start": 590, "end": 14931 }
class ____(TestCase): def test_output(self): GenericFormSet = generic_inlineformset_factory(TaggedItem, extra=1) formset = GenericFormSet() self.assertHTMLEqual( "".join(form.as_p() for form in formset.forms), """ <p><label for="id_generic_...
GenericInlineFormsetTests
python
huggingface__transformers
src/transformers/models/sam3/configuration_sam3.py
{ "start": 4686, "end": 7796 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Sam3VisionModel`]. It is used to instantiate a SAM vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration defaults will yield a similar config...
Sam3VisionConfig
python
getsentry__sentry
tests/sentry/rules/actions/test_notify_event.py
{ "start": 294, "end": 769 }
class ____(RuleTestCase): rule_cls = NotifyEventAction def test_applies_correctly(self) -> None: event = self.get_event() plugin = MagicMock() rule = self.get_rule() rule.get_plugins = lambda: (LegacyPluginService(plugin),) results = list(rule.after(event=event)) ...
NotifyEventActionTest
python
pennersr__django-allauth
allauth/socialaccount/providers/odnoklassniki/provider.py
{ "start": 242, "end": 857 }
class ____(ProviderAccount): def get_profile_url(self): return "https://ok.ru/profile/" + self.account.extra_data["uid"] def get_avatar_url(self): ret = None pic_big_url = self.account.extra_data.get("pic1024x768") pic_medium_url = self.account.extra_data.get("pic640x480") ...
OdnoklassnikiAccount
python
django__django
tests/user_commands/management/commands/subparser_dest.py
{ "start": 54, "end": 373 }
class ____(BaseCommand): def add_arguments(self, parser): subparsers = parser.add_subparsers(dest="subcommand", required=True) parser_foo = subparsers.add_parser("foo") parser_foo.add_argument("--bar") def handle(self, *args, **options): self.stdout.write(",".join(options))
Command
python
aimacode__aima-python
probability.py
{ "start": 593, "end": 2352 }
class ____: """A discrete probability distribution. You name the random variable in the constructor, then assign and query probability of values. >>> P = ProbDist('Flip'); P['H'], P['T'] = 0.25, 0.75; P['H'] 0.25 >>> P = ProbDist('X', {'lo': 125, 'med': 375, 'hi': 500}) >>> P['lo'], P['med'], P[...
ProbDist
python
pytorch__pytorch
torch/testing/_internal/autograd_function_db.py
{ "start": 13346, "end": 14528 }
class ____(torch.autograd.Function): generate_vmap_rule = True @staticmethod def forward(x, y): return x.clone(), y.clone() @staticmethod def setup_context(ctx, inputs, outputs): pass @staticmethod def backward(ctx, gx, gy): # Intentionally returning torch.zeros in...
ZeroGradientsGenVmap
python
aimacode__aima-python
planning.py
{ "start": 31156, "end": 36267 }
class ____: """ Contains the state of the planning problem and exhaustive list of actions which use the states as pre-condition. """ def __init__(self, kb): """Initializes variables to hold state and action details of a level""" self.kb = kb # current state self...
Level
python
jazzband__django-polymorphic
src/polymorphic/admin/parentadmin.py
{ "start": 845, "end": 952 }
class ____(RuntimeError): "The admin model can't be registered anymore at this point."
RegistrationClosed
python
tensorflow__tensorflow
tensorflow/python/trackable/data_structures.py
{ "start": 24567, "end": 26693 }
class ____(TrackableDataStructure, collections_abc.Mapping): """An append-only trackable mapping data structure with string keys. Maintains checkpoint dependencies on its contents (which must also be trackable), named based on its keys. Note that once a key has been added, it may not be deleted or replaced. ...
Mapping
python
huggingface__transformers
src/transformers/trainer.py
{ "start": 8465, "end": 258416 }
class ____: """ Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers. Args: model ([`PreTrainedModel`] or `torch.nn.Module`, *optional*): The model to train, evaluate or use for predictions. If not provided, a `model_init` must be pa...
Trainer
python
django__django
tests/model_inheritance/models.py
{ "start": 1113, "end": 1406 }
class ____(models.Model): post = models.ForeignKey( Post, models.CASCADE, related_name="attached_%(class)s_set", related_query_name="attached_%(app_label)s_%(class)ss", ) content = models.TextField() class Meta: abstract = True
Attachment
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 52077, "end": 52854 }
class ____(ObjectBaseModel): """An ORM representation of a worker""" name: str = Field(description="The name of the worker.") work_pool_id: UUID = Field( description="The work pool with which the queue is associated." ) last_heartbeat_time: Optional[datetime.datetime] = Field( defau...
Worker
python
PyCQA__pylint
doc/data/messages/t/too-many-ancestors/bad.py
{ "start": 242, "end": 359 }
class ____(Animal): ... # max of 7 by default, can be configured # each edge of a diamond inheritance counts
Vertebrate
python
astropy__astropy
astropy/table/tests/test_init_table.py
{ "start": 13186, "end": 13677 }
class ____(BaseInitFromDictLike): def _setup(self, table_type): self.data = OrderedDict( [ ("a", Column(name="x", data=[1, 3])), ("b", [2, 4]), ("c", np.array([3, 5], dtype="i8")), ] ) def test_col_order(self, table_type): ...
TestInitFromOrderedDict
python
walkccc__LeetCode
solutions/6. ZigZag Conversion/6.py
{ "start": 0, "end": 281 }
class ____: def convert(self, s: str, numRows: int) -> str: rows = [''] * numRows k = 0 direction = (numRows == 1) - 1 for c in s: rows[k] += c if k == 0 or k == numRows - 1: direction *= -1 k += direction return ''.join(rows)
Solution
python
django__django
tests/invalid_models_tests/test_ordinary_fields.py
{ "start": 40273, "end": 44890 }
class ____(TestCase): def test_db_default(self): class Model(models.Model): field = models.FloatField(db_default=Pi()) field = Model._meta.get_field("field") errors = field.check(databases=self.databases) if connection.features.supports_expression_defaults: ...
InvalidDBDefaultTests
python
pytest-dev__pytest
src/_pytest/outcomes.py
{ "start": 1990, "end": 2284 }
class ____(Exception): """Raised for immediate program exits (no tracebacks/summaries).""" def __init__( self, msg: str = "unknown reason", returncode: int | None = None ) -> None: self.msg = msg self.returncode = returncode super().__init__(msg)
Exit
python
pandas-dev__pandas
pandas/errors/__init__.py
{ "start": 5024, "end": 5821 }
class ____(PandasDeprecationWarning): """ Warning raised for an upcoming change that will be enforced in pandas 4.0. See Also -------- errors.PandasChangeWarning: Class for deprecations that will raise any warning. errors.PandasPendingDeprecationWarning : Class for deprecations that will raise ...
Pandas4Warning
python
urllib3__urllib3
src/urllib3/http2/probe.py
{ "start": 55, "end": 3014 }
class ____: __slots__ = ( "_lock", "_cache_locks", "_cache_values", ) def __init__(self) -> None: self._lock = threading.Lock() self._cache_locks: dict[tuple[str, int], threading.RLock] = {} self._cache_values: dict[tuple[str, int], bool | None] = {} def...
_HTTP2ProbeCache
python
zarr-developers__zarr-python
src/zarr/core/dtype/npy/structured.py
{ "start": 1645, "end": 2224 }
class ____( NamedConfig[Literal["structured"], dict[str, Sequence[Sequence[str | DTypeJSON]]]] ): """ A JSON representation of a structured data type in Zarr V3. References ---------- This representation is not currently defined in an external specification. Examples -------- ```py...
StructuredJSON_V3
python
walkccc__LeetCode
solutions/2934. Minimum Operations to Maximize Last Elements in Arrays/2934.py
{ "start": 0, "end": 663 }
class ____: def minOperations(self, nums1: list[int], nums2: list[int]) -> int: n = len(nums1) mn = min(nums1[-1], nums2[-1]) mx = max(nums1[-1], nums2[-1]) # the number of the minimum operations, where nums1[n - 1] is not swapped # with nums2[n - 1] dp1 = 0 # the number of the minimum ope...
Solution
python
ansible__ansible
lib/ansible/cli/scripts/ansible_connection_cli_stub.py
{ "start": 1694, "end": 13121 }
class ____(object): """ The connection process wraps around a Connection object that manages the connection to a remote device that persists over the playbook """ def __init__(self, fd, play_context, socket_path, original_path, task_uuid=None, ansible_playbook_pid=None): self.play_context = ...
ConnectionProcess
python
huggingface__transformers
src/transformers/models/sam_hq/modeling_sam_hq.py
{ "start": 49238, "end": 54227 }
class ____(nn.Module): def __init__(self, config: SamHQConfig): super().__init__() self.shared_embedding = SamHQPositionalEmbedding(config.vision_config) config = config.prompt_encoder_config self.mask_embed = SamHQMaskEmbedding(config) self.no_mask_embed = nn.Embedding(1, co...
SamHQPromptEncoder
python
huggingface__transformers
src/transformers/models/janus/modeling_janus.py
{ "start": 24613, "end": 27416 }
class ____(nn.Module): """ A module for vector quantization using learned embedding vectors. This module implements the quantization process similar to te one described in the VQ-VAE (Vector Quantized Variational AutoEncoder) paper. It quantizes continuous input vectors into discrete codebook vecto...
JanusVQVAEVectorQuantizer
python
getsentry__sentry
src/sentry/integrations/slack/requests/action.py
{ "start": 338, "end": 5258 }
class ____(SlackRequest): """ An Action request sent from Slack. Action requests nest their data inside of a ``payload`` key in the request body, for some reason. Therefore they require an extra bit of data validation. """ @property def type(self) -> str: return str(self.data.g...
SlackActionRequest
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_graph.py
{ "start": 57558, "end": 57830 }
class ____(graphene.ObjectType): class Meta: name = "DefinitionGroup" groupName = graphene.NonNull(graphene.String) repositoryName = graphene.NonNull(graphene.String) repositoryLocationName = graphene.NonNull(graphene.String)
GrapheneDefinitionGroup
python
django-haystack__django-haystack
haystack/backends/elasticsearch_backend.py
{ "start": 39158, "end": 39281 }
class ____(BaseEngine): backend = ElasticsearchSearchBackend query = ElasticsearchSearchQuery
ElasticsearchSearchEngine
python
openai__openai-python
src/openai/types/fine_tuning/reinforcement_hyperparameters_param.py
{ "start": 248, "end": 1357 }
class ____(TypedDict, total=False): batch_size: Union[Literal["auto"], int] """Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance. """ compute_multiplier: Union[Literal["auto"], float] """ Multiplier on...
ReinforcementHyperparametersParam
python
PyCQA__pylint
tests/functional/u/unexpected_special_method_signature.py
{ "start": 1563, "end": 2008 }
class ____: def __aiter__(self, extra): # [unexpected-special-method-signature] pass def __anext__(self, extra, argument): # [unexpected-special-method-signature] pass def __await__(self, param): # [unexpected-special-method-signature] pass def __aenter__(self, first): # [unexpe...
Async
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/asset_health.py
{ "start": 1590, "end": 1828 }
class ____(graphene.ObjectType): numNotExecutedChecks = graphene.NonNull(graphene.Int) totalNumChecks = graphene.NonNull(graphene.Int) class Meta: name = "AssetHealthCheckUnknownMeta"
GrapheneAssetHealthCheckUnknownMeta
python
encode__django-rest-framework
tests/test_parsers.py
{ "start": 5290, "end": 6727 }
class ____(TestCase): def setUp(self): self.factory = APIRequestFactory() def test_post_accessed_in_post_method(self): django_request = self.factory.post('/', {'foo': 'bar'}) request = Request(django_request, parsers=[FormParser(), MultiPartParser()]) django_request.POST ...
TestPOSTAccessed
python
pytorch__pytorch
test/inductor/test_compiled_autograd.py
{ "start": 3265, "end": 3482 }
class ____(torch.autograd.Function): @staticmethod def forward(ctx, x): return x * 2 @staticmethod def backward(ctx, grad_output): raise NotImplementedError("must override")
BaseCustomOp
python
ray-project__ray
python/ray/llm/tests/serve/cpu/deployments/prefill_decode_disagg/test_prefill_decode_disagg.py
{ "start": 7385, "end": 8942 }
class ____: @pytest.mark.parametrize("kv_connector", ["NixlConnector", "LMCacheConnectorV1"]) def test_parse_dict(self, kv_connector: str): prefill_config = LLMConfig( model_loading_config=dict( model_id="qwen-0.5b", model_source="Qwen/Qwen2.5-0.5B-Instruct", ...
TestServingArgsParsing
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 163055, "end": 163884 }
class ____(ASTBase): def __init__( self, nestedName: ASTNestedName, templatePrefix: ASTTemplateDeclarationPrefix ) -> None: self.nestedName = nestedName self.templatePrefix = templatePrefix def __eq__(self, other: object) -> bool: if not isinstance(other, ASTNamespace): ...
ASTNamespace
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/deadcode.py
{ "start": 1371, "end": 1595 }
class ____(): def __init__(self, y): return self.x = _test_source() _test_sink(y) def early_return_no_issue_class(): object = EarlyReturns(_test_source()) _test_sink(object.x)
EarlyReturns
python
crytic__slither
slither/printers/summary/martin.py
{ "start": 645, "end": 1226 }
class ____(AbstractPrinter): ARGUMENT = "martin" HELP = "Martin agile software metrics (Ca, Ce, I, A, D)" WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#martin" def output(self, _filename: str) -> Output: if len(self.contracts) == 0: return self.generate_...
Martin
python
wandb__wandb
wandb/vendor/pygments/lexers/modeling.py
{ "start": 585, "end": 3719 }
class ____(RegexLexer): """ For `Modelica <http://www.modelica.org/>`_ source code. .. versionadded:: 1.1 """ name = 'Modelica' aliases = ['modelica'] filenames = ['*.mo'] mimetypes = ['text/x-modelica'] flags = re.DOTALL | re.MULTILINE _name = r"(?:'(?:[^\\']|\\.)+'|[a-zA-Z_]...
ModelicaLexer
python
pyca__cryptography
tests/x509/test_x509_ext.py
{ "start": 77863, "end": 78959 }
class ____: def test_not_oid(self): with pytest.raises(TypeError): x509.RegisteredID(b"notanoid") # type:ignore[arg-type] with pytest.raises(TypeError): x509.RegisteredID(1.3) # type:ignore[arg-type] def test_repr(self): gn = x509.RegisteredID(NameOID.COMMON_N...
TestRegisteredID
python
tensorflow__tensorflow
tensorflow/python/debug/cli/debugger_cli_common_test.py
{ "start": 31691, "end": 36608 }
class ____(test_util.TensorFlowTestCase): def setUp(self): self._tc_reg = debugger_cli_common.TabCompletionRegistry() # Register the items in an unsorted order deliberately, to test the sorted # output from get_completions(). self._tc_reg.register_tab_comp_context( ["print_tensor", "pt"], ...
TabCompletionRegistryTest
python
huggingface__transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
{ "start": 4096, "end": 9065 }
class ____(ModelOutput): r""" waveform (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): The final audio waveform predicted by the model. waveform_lengths (`torch.IntTensor` of shape `(batch_size,)`, *optional*): The length in samples of each element in the `waveform` batch. ...
SeamlessM4TGenerationOutput
python
ApeWorX__ape
src/ape_compile/config.py
{ "start": 269, "end": 568 }
class ____(ConfigEnum): """ Extra stuff you can output. It will appear in ``.build/{key.lower()/`` """ ABI = "ABI" """ Include this value to output the ABIs of your contracts to minified JSONs. This is useful for hosting purposes for web-apps. """
OutputExtras
python
pytorch__pytorch
test/distributed/test_c10d_gloo.py
{ "start": 96444, "end": 100823 }
class ____(test_c10d_common.AbstractCommTest, MultiProcessTestCase): @property def device(self): return "cpu" def setUp(self): super().setUp() self._spawn_processes() def tearDown(self): super().tearDown() try: os.remove(self.file_name) excep...
CommTest
python
pennersr__django-allauth
allauth/socialaccount/providers/edmodo/provider.py
{ "start": 436, "end": 1267 }
class ____(OAuth2Provider): id = "edmodo" name = "Edmodo" account_class = EdmodoAccount oauth2_adapter_class = EdmodoOAuth2Adapter def get_default_scope(self): return ["basic"] def extract_uid(self, data): return str(data["id"]) def extract_common_fields(self, data): ...
EdmodoProvider
python
pandas-dev__pandas
pandas/tests/arithmetic/test_timedelta64.py
{ "start": 24310, "end": 26940 }
class ____: # TODO: parametrize over boxes @pytest.mark.parametrize("str_ts", ["1950-01-01", "1980-01-01"]) def test_tdarr_add_timestamp_nat_masking(self, box_with_array, str_ts): # GH#17991 checking for overflow-masking with NaT tdinat = pd.to_timedelta(["24658 days 11:15:00", "NaT"]) ...
TestAddSubNaTMasking
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_optimize10.py
{ "start": 315, "end": 1608 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("optimize10.xlsx") self.set_text_file("unicode_polish_utf8.txt") def test_create_file(self): """Test example file converting Unicode...
TestCompareXLSXFiles
python
getsentry__sentry
tests/sentry/api/test_utils.py
{ "start": 4048, "end": 6328 }
class ____(APITestCase): def setUp(self) -> None: self.handler_error = Exception("nope") @patch("sys.stderr.write") def test_logs_error_locally(self, mock_stderr_write: MagicMock) -> None: try: raise self.handler_error except Exception as e: print_and_capture...
PrintAndCaptureHandlerExceptionTest
python
pydantic__pydantic
tests/mypy/modules/generics.py
{ "start": 295, "end": 354 }
class ____(BaseModel): raw: str doctype: str
HtmlBody
python
pytorch__pytorch
test/dynamo/test_higher_order_ops.py
{ "start": 213170, "end": 215328 }
class ____(torch.nn.Module): def forward(self, L_x_: "f32[3, 3]", L_v_: "f32[3, 3]"): l_x_ = L_x_ l_v_ = L_v_ _jvp_increment_nesting = torch._C._functorch._jvp_increment_nesting(); _jvp_increment_nesting = None _set_fwd_grad_enabled = torch._C._set_fwd_grad_enabled(True); _set_fwd...
GraphModule
python
python__mypy
mypyc/ir/ops.py
{ "start": 60605, "end": 60699 }
class ____(NamedTuple): classes: dict[str, ClassIR] functions: dict[str, FuncIR]
DeserMaps
python
jazzband__django-waffle
waffle/tests/test_testutils.py
{ "start": 9753, "end": 10193 }
class ____: @classmethod def setUpClass(cls): super().setUpClass() assert not waffle.get_waffle_flag_model().objects.filter(name='foo').exists() waffle.get_waffle_flag_model().objects.create(name='foo', everyone=True) def test_undecorated_method_is_set_properly_for_flag(self): ...
OverrideFlagOnClassTestsMixin
python
walkccc__LeetCode
solutions/3333. Find the Original Typed String II/3333.py
{ "start": 0, "end": 1224 }
class ____: def possibleStringCount(self, word: str, k: int) -> int: MOD = 1_000_000_007 groups = self._getConsecutiveLetters(word) totalCombinations = functools.reduce(lambda subtotal, group: subtotal * group % MOD, groups) if k <= len(groups): return to...
Solution
python
numba__numba
numba/cuda/deviceufunc.py
{ "start": 20201, "end": 20852 }
class ____(object): def __init__(self, parent, ishapes, oshapes, loopdims, pinned): self.parent = parent # core shapes self.ishapes = ishapes self.oshapes = oshapes # looping dimension self.loopdims = loopdims self.loopn = reduce(operator.mul, loopdims, 1) ...
GUFuncSchedule
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 147603, "end": 148813 }
class ____(nn.Module): def __init__( self, in_channels, out_channels, kernel_size, dilation=1, stride=1, groups=1, ): super().__init__() self.conv = nn.Conv1d( in_channels, out_channels, kernel_size, ...
Qwen3OmniMoeCausalConvNet
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 7788, "end": 7921 }
class ____(VOWarning, RuntimeWarning): """ A network or IO error occurred, but was recovered using the cache. """
IOWarning
python
mlflow__mlflow
tests/sagemaker/mock/__init__.py
{ "start": 32625, "end": 34709 }
class ____: """ Object representing a SageMaker transform job operation ("create" or "stop"). Every transform job is associated with the operation that was most recently invoked on it. """ def __init__(self, latency_seconds, pending_status, completed_status): """ Args: l...
TransformJobOperation
python
huggingface__transformers
src/transformers/models/albert/modeling_albert.py
{ "start": 10561, "end": 11646 }
class ____(nn.Module): def __init__(self, config: AlbertConfig): super().__init__() self.config = config self.embedding_hidden_mapping_in = nn.Linear(config.embedding_size, config.hidden_size) self.albert_layer_groups = nn.ModuleList([AlbertLayerGroup(config) for _ in range(config.n...
AlbertTransformer
python
uqfoundation__dill
dill/tests/test_moduledict.py
{ "start": 627, "end": 1182 }
class ____(object): def __reduce__(self): raise Exception unpicklable = SomeUnreferencedUnpicklableClass() # This works fine outside of Doctest: def test_normal(): serialized = dill.dumps(lambda x: x) # should not try to pickle unpicklable object in __globals__ def tests(): """ >>> serialized...
SomeUnreferencedUnpicklableClass
python
spack__spack
lib/spack/spack/installer.py
{ "start": 2881, "end": 3988 }
class ____(enum.Enum): """Different build (task) states.""" #: Build status indicating task has been added/queued. QUEUED = enum.auto() #: Build status indicating the spec failed to install FAILED = enum.auto() #: Build status indicating the spec is being installed (possibly by another #:...
BuildStatus
python
huggingface__transformers
tests/trainer/test_trainer.py
{ "start": 6677, "end": 7649 }
class ____: def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): np.random.seed(seed) self.label_names = ["labels"] if label_names is None else label_names self.length = length self.x = np.random.normal(size=(length,)).astype(np.float32) self.ys = [a * self.x +...
RegressionDataset
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py
{ "start": 39561, "end": 40076 }
class ____(Qwen2_5OmniPreTrainedModel, PreTrainedModel): @torch.no_grad() def _init_weights(self, module): PreTrainedModel._init_weights(self, module) std = self.config.initializer_range if isinstance(module, Qwen3OmniMoeThinkerTextSparseMoeBlock): init.normal_(module.experts...
Qwen3OmniMoePreTrainedModel
python
dagster-io__dagster
python_modules/libraries/dagster-airflow/dagster_airflow/resources/airflow_db.py
{ "start": 595, "end": 3849 }
class ____: """Airflow database Dagster resource.""" def __init__(self, dagster_run: DagsterRun, dag_run_config: Optional[dict] = None): self.dagster_run = dagster_run self.dag_run_config = dag_run_config def _parse_execution_date_for_job( self, dag: DAG, run_tags: Mapping[str, str...
AirflowDatabase
python
scrapy__scrapy
tests/test_request_attribute_binding.py
{ "start": 1160, "end": 1378 }
class ____(SingleRequestSpider): name = "alternative_callbacks_spider" def alt_callback(self, response, foo=None): self.logger.info("alt_callback was invoked with foo=%s", foo)
AlternativeCallbacksSpider
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_contextlib.py
{ "start": 16193, "end": 17521 }
class ____(__TestCase): def boilerPlate(self, lock, locked): self.assertFalse(locked()) with lock: self.assertTrue(locked()) self.assertFalse(locked()) with self.assertRaises(ZeroDivisionError): with lock: self.assertTrue(locked()) ...
LockContextTestCase