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
getsentry__sentry
tests/sentry/integrations/slack/test_integration.py
{ "start": 19197, "end": 21468 }
class ____(TestCase): def setUp(self) -> None: self.integration = self.create_provider_integration( provider="slack", name="Slack", external_id="TXXXXXXX1", metadata={ "access_token": "xoxb-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx", "i...
SlackIntegrationSendNotificationTest
python
getsentry__sentry
src/sentry/sentry_metrics/querying/units.py
{ "start": 2645, "end": 2853 }
class ____: """ Represents the specification of multiple units which has a common reference unit. """ reference_unit: MeasurementUnit units: Sequence[Unit] @dataclass(frozen=True)
UnitsSpec
python
apache__airflow
providers/apache/hdfs/tests/unit/apache/hdfs/log/test_hdfs_task_handler.py
{ "start": 1391, "end": 8922 }
class ____: @pytest.fixture(autouse=True) def ti(self, create_task_instance, create_log_template): create_log_template("{try_number}.log") ti = create_task_instance( dag_id="dag_for_testing_hdfs_task_handler", task_id="task_for_testing_hdfs_log_handler", logic...
TestHdfsTaskHandler
python
tensorflow__tensorflow
tensorflow/compiler/tests/unary_ops_test.py
{ "start": 1622, "end": 34873 }
class ____(xla_test.XLATestCase): """Test cases for unary operators.""" def _assertOpOutputMatchesExpected( self, op, inp, expected, equality_test=None, rtol=1e-3, atol=1e-5 ): """Verifies that 'op' produces 'expected' when fed input 'inp' . Args: op: operator to test inp: numpy input ...
UnaryOpsTest
python
gevent__gevent
src/gevent/tests/test__monkey_queue.py
{ "start": 8519, "end": 8588 }
class ____(BaseQueueTest): type2test = Queue.LifoQueue
LifoQueueTest
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 112027, "end": 113148 }
class ____(ASTBase): def __init__( self, value: ASTExpression | ASTBracedInitList, hasAssign: bool = True ) -> None: self.value = value self.hasAssign = hasAssign def __eq__(self, other: object) -> bool: if not isinstance(other, ASTInitializer): return NotImpleme...
ASTInitializer
python
tensorflow__tensorflow
tensorflow/python/distribute/vars_test.py
{ "start": 3463, "end": 19315 }
class ____(test.TestCase, parameterized.TestCase): @combinations.generate(strategy_and_run_tf_function_combinations()) def testAssign(self, distribution, experimental_run_tf_function): def assign(fn, v, update_value, cross_replica): update_fn = lambda: getattr(v, fn)(update_value) if cross_replica...
OnWriteVariableSync
python
tensorflow__tensorflow
tensorflow/python/framework/error_interpolation_test.py
{ "start": 2767, "end": 3806 }
class ____(test.TestCase): def testCorrectFormatWithActiveDeviceAssignments(self): assignments = [] assignments.append( traceable_stack.TraceableObject("/cpu:0", filename="hope.py", lineno=24) ) assignments.append( traceable_stack.TraceableObject( "/gpu:2", filename="pleas...
ComputeDeviceSummaryFromOpTest
python
django-guardian__django-guardian
guardian/managers.py
{ "start": 369, "end": 6297 }
class ____(models.Manager): @property def user_or_group_field(self) -> str: try: self.model._meta.get_field("user") return "user" except FieldDoesNotExist: return "group" def is_generic(self) -> bool: try: self.model._meta.get_field("o...
BaseObjectPermissionManager
python
encode__django-rest-framework
tests/test_generics.py
{ "start": 13474, "end": 14198 }
class ____(TestCase): def setUp(self): self.objects = Comment.objects self.view = CommentView.as_view() def test_create_model_with_auto_now_add_field(self): """ Regression test for #285 https://github.com/encode/django-rest-framework/issues/285 """ data ...
TestCreateModelWithAutoNowAddField
python
lepture__authlib
authlib/jose/errors.py
{ "start": 2235, "end": 2355 }
class ____(JoseError): error = "invalid_use" description = "Key 'use' is not valid for your usage"
InvalidUseError
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/base.py
{ "start": 42301, "end": 42373 }
class ____(_UnicodeLiteral, sqltypes.UnicodeText): pass
_MSUnicodeText
python
pytest-dev__pluggy
docs/examples/eggsample/eggsample/host.py
{ "start": 532, "end": 1579 }
class ____: FAVORITE_INGREDIENTS = ("egg", "egg", "egg") def __init__(self, hook): self.hook = hook self.ingredients = None def add_ingredients(self): results = self.hook.eggsample_add_ingredients( ingredients=self.FAVORITE_INGREDIENTS ) my_ingredients =...
EggsellentCook
python
pypa__pip
tests/unit/test_network_session.py
{ "start": 2167, "end": 10535 }
class ____: def test_cache_defaults_off(self) -> None: session = PipSession() assert not hasattr(session.adapters["http://"], "cache") assert not hasattr(session.adapters["https://"], "cache") def test_cache_is_enabled(self, tmpdir: Path) -> None: cache_directory = os.fspath(tm...
TestPipSession
python
ray-project__ray
rllib/examples/rl_modules/classes/vpg_using_shared_encoder_rlm.py
{ "start": 8551, "end": 9562 }
class ____(TorchRLModule): """ A VPG (vanilla pol. gradient)-style RLModule that doesn't use a shared encoder. Facilitates experiments comparing shared and individual encoder architectures. """ def setup(self): super().setup() # Incoming feature dim from the encoder. embedd...
VPGPolicyNoSharedEncoder
python
django__django
tests/admin_views/models.py
{ "start": 18026, "end": 18527 }
class ____(models.Model): question = models.ForeignKey(Question, models.PROTECT) question_with_to_field = models.ForeignKey( Question, models.SET_NULL, blank=True, null=True, to_field="uuid", related_name="uuid_answers", limit_choices_to=~models.Q(question...
Answer
python
doocs__leetcode
solution/1900-1999/1905.Count Sub Islands/Solution.py
{ "start": 0, "end": 560 }
class ____: def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int: def dfs(i: int, j: int) -> int: ok = grid1[i][j] grid2[i][j] = 0 for a, b in pairwise(dirs): x, y = i + a, j + b if 0 <= x < m and 0 <= y < n and ...
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/scheduler/instigation.py
{ "start": 11404, "end": 11637 }
class ____(Enum): STARTED = "STARTED" SKIPPED = "SKIPPED" SUCCESS = "SUCCESS" FAILURE = "FAILURE" @whitelist_for_serdes( old_storage_names={"JobTick"}, storage_field_names={"tick_data": "job_tick_data"} )
TickStatus
python
coleifer__peewee
tests/results.py
{ "start": 263, "end": 4278 }
class ____(ModelTestCase): database = get_in_memory_db() requires = [User] def test_iteration(self): for i in range(10): User.create(username=str(i)) query = User.select() cursor = query.execute() first_five = [] for i, u in enumerate(cursor): ...
TestCursorWrapper
python
apache__airflow
providers/google/tests/unit/google/cloud/sensors/test_dataproc.py
{ "start": 1477, "end": 6282 }
class ____: def create_job(self, state: int): job = mock.Mock() job.status = mock.Mock() job.status.state = state return job @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_done(self, mock_hook): job = self.create_job(JobStatus.State.DONE) job_id =...
TestDataprocJobSensor
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events_timeseries_logs.py
{ "start": 390, "end": 7073 }
class ____(OrganizationEventsEndpointTestBase): endpoint = "sentry-api-0-organization-events-timeseries" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.start = self.day_ago = before_now(days=1).replace( hour=10, minute=0, second=0, microsecond=0 ...
OrganizationEventsStatsOurlogsMetricsEndpointTest
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_heapq.py
{ "start": 17449, "end": 17573 }
class ____(_TestErrorHandling, __TestCase): module = c_heapq if __name__ == "__main__": run_tests()
TestErrorHandlingC
python
getsentry__sentry
src/sentry/preprod/analytics.py
{ "start": 883, "end": 1103 }
class ____(analytics.Event): organization_id: int project_id: int user_id: int | None = None artifact_id: str @analytics.eventclass("preprod_artifact.api.list_builds")
PreprodArtifactApiGetBuildDetailsEvent
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_validation__property.py
{ "start": 2149, "end": 2929 }
class ____: def test_validate(self) -> None: assert validation_on() with bcpv.validate(False): assert not validation_on() assert validation_on() with bcpv.validate(False): assert not validation_on() with bcpv.validate(True): assert...
TestValidationControl
python
django-extensions__django-extensions
tests/management/commands/test_generate_secret_key.py
{ "start": 141, "end": 643 }
class ____(TestCase): """Tests for generate_secret_key command.""" @patch( "django_extensions.management.commands.generate_secret_key.get_random_secret_key" ) @patch("sys.stdout", new_callable=StringIO) def test_should_return_random_secret_key(self, m_stdout, m_get_random_secret): m...
GenerateSecretKeyTests
python
getsentry__sentry
src/sentry/organizations/services/organization/service.py
{ "start": 20842, "end": 22104 }
class ____(abc.ABC): @abc.abstractmethod def schedule_signal( self, signal: Signal, organization_id: int, args: Mapping[str, int | str | None], ) -> None: pass def _signal_from_outbox() -> OrganizationSignalService: from sentry.organizations.services.organizatio...
OrganizationSignalService
python
getsentry__sentry
tests/sentry/seer/explorer/test_explorer_client.py
{ "start": 336, "end": 12993 }
class ____(TestCase): def setUp(self): super().setUp() self.user = self.create_user() self.organization = self.create_organization(owner=self.user) @patch("sentry.seer.explorer.client.has_seer_explorer_access_with_detail") def test_client_init_checks_access(self, mock_access): ...
TestSeerExplorerClient
python
pytorch__pytorch
test/test_dataloader.py
{ "start": 37018, "end": 41817 }
class ____(TestCase): def setUp(self): super().setUp() self.data = torch.randn(100, 2, 3, 5) self.labels = torch.randperm(50).repeat(2) self.dataset = TensorDataset(self.data, self.labels) self.persistent_workers = False def _get_data_loader(self, dataset, **kwargs): ...
TestDataLoader
python
kamyu104__LeetCode-Solutions
Python/number-of-good-binary-strings.py
{ "start": 81, "end": 883 }
class ____(object): def goodBinaryStrings(self, minLength, maxLength, oneGroup, zeroGroup): """ :type minLength: int :type maxLength: int :type oneGroup: int :type zeroGroup: int :rtype: int """ MOD = 10**9+7 result = 0 w = max(oneGroup...
Solution
python
fastai__fastai
fastai/layers.py
{ "start": 18689, "end": 19326 }
class ____(Module): "Merge a shortcut with the result of the module by multiplying them." def forward(self, x): return x * x.orig # %% ../nbs/01_layers.ipynb 129 inplace_relu = partial(nn.ReLU, inplace=True) # %% ../nbs/01_layers.ipynb 130 def SEModule(ch, reduction, act_cls=defaults.activation): nf = mat...
ProdLayer
python
scipy__scipy
scipy/stats/tests/test_resampling.py
{ "start": 34262, "end": 50723 }
class ____: atol = 2.5e-2 # for comparing p-value def get_rvs(self, rvs_in, rs, dtype=None, xp=np): return lambda *args, **kwds: xp.asarray(rvs_in(*args, random_state=rs, **kwds), dtype=dtype) def get_statistic(self, xp): def statistic(x, ax...
TestMonteCarloHypothesisTest
python
apache__airflow
airflow-core/tests/unit/timetables/test_assets_timetable.py
{ "start": 1504, "end": 8950 }
class ____(Timetable): """ A mock Timetable class for testing purposes in Apache Airflow. """ __test__ = False def __init__(self) -> None: """ Initializes the MockTimetable with the current DateTime. """ self._now = DateTime.now() def next_dagrun_info( ...
MockTimetable
python
sympy__sympy
sympy/stats/crv_types.py
{ "start": 43526, "end": 45680 }
class ____(SingleContinuousDistribution): _argnames = ('d1', 'd2') set = Interval(-oo, oo) @staticmethod def check(d1, d2): _value_check(d1 > 0, "Degree of freedom d1 must be positive.") _value_check(d2 > 0, "Degree of freedom d2 must be positive.") def pdf(self, x): d1, d...
FisherZDistribution
python
doocs__leetcode
solution/3300-3399/3340.Check Balanced String/Solution.py
{ "start": 0, "end": 179 }
class ____: def isBalanced(self, num: str) -> bool: f = [0, 0] for i, x in enumerate(map(int, num)): f[i & 1] += x return f[0] == f[1]
Solution
python
Lightning-AI__lightning
examples/pytorch/domain_templates/computer_vision_fine_tuning.py
{ "start": 9565, "end": 10298 }
class ____(LightningCLI): def add_arguments_to_parser(self, parser): parser.add_lightning_class_args(MilestonesFinetuning, "finetuning") parser.link_arguments("data.batch_size", "model.batch_size") parser.link_arguments("finetuning.milestones", "model.milestones") parser.link_argumen...
MyLightningCLI
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/base.py
{ "start": 18566, "end": 19265 }
class ____(SQLCoreOperations[_T_co], TypingOnly): __slots__ = () if typing.TYPE_CHECKING: def of_type( self, class_: _EntityType[Any] ) -> PropComparator[_T_co]: ... def and_( self, *criteria: _ColumnExpressionArgument[bool] ) -> PropComparator[bool]: ....
SQLORMOperations
python
ray-project__ray
python/ray/serve/tests/test_cli_3.py
{ "start": 3026, "end": 18023 }
class ____: @pytest.mark.skipif( sys.platform == "win32", reason="File path incorrect on Windows." ) @pytest.mark.parametrize( "proxy_location,expected", [ ( None, "EveryNode", ), # default ProxyLocation `EveryNode` is used as ...
TestRun
python
numpy__numpy
numpy/lib/_index_tricks_impl.py
{ "start": 18871, "end": 19834 }
class ____(AxisConcatenator): """ Translates slice objects to concatenation along the second axis. This is short-hand for ``np.r_['-1,2,0', index expression]``, which is useful because of its common occurrence. In particular, arrays will be stacked along their last axis after being upgraded to at l...
CClass
python
numba__numba
numba/tests/test_caching.py
{ "start": 31448, "end": 32428 }
class ____(BaseCacheTest): # Nested multiprocessing.Pool raises AssertionError: # "daemonic processes are not allowed to have children" _numba_parallel_test_ = False here = os.path.dirname(__file__) usecases_file = os.path.join(here, "cache_usecases.py") modname = "dispatcher_caching_test_fodd...
TestMultiprocessCache
python
huggingface__transformers
tests/quantization/quanto_integration/test_quanto.py
{ "start": 16770, "end": 17313 }
class ____(unittest.TestCase): def test_quantize_activation(self): quantization_config = QuantoConfig( weights="int8", activations="int8", ) with self.assertRaises(ValueError) as e: AutoModelForCausalLM.from_pretrained("bigscience/bloom-560m", quantization...
QuantoQuantizationActivationTest
python
pytorch__pytorch
test/test_reductions.py
{ "start": 3562, "end": 179273 }
class ____(TestCase): ########################################################################### # ReductionOpInfo unit tests ########################################################################### def _test_dim_keepdim(self, op: ReductionOpInfo, device, *, ndim, **dim_keepdim): """Tests ...
TestReductions
python
google__jax
jax/_src/checkify.py
{ "start": 4448, "end": 4905 }
class ____(JaxException): def __init__(self, traceback_info, primitive_name): super().__init__(traceback_info) self.prim = primitive_name def tree_flatten(self): return ([], (self.traceback_info, self.prim)) @classmethod def tree_unflatten(cls, metadata, _): return cls(*metadata) def get_e...
NaNError
python
ray-project__ray
release/train_tests/benchmark/config.py
{ "start": 196, "end": 428 }
class ____(BaseModel): train_batch_size: int = 32 limit_training_rows: int = 1000000 # Use -1 for unlimited validation_batch_size: int = 256 limit_validation_rows: int = 50000 # Use -1 for unlimited
DataLoaderConfig
python
doocs__leetcode
solution/2800-2899/2844.Minimum Operations to Make a Special Number/Solution.py
{ "start": 0, "end": 360 }
class ____: def minimumOperations(self, num: str) -> int: @cache def dfs(i: int, k: int) -> int: if i == n: return 0 if k == 0 else n ans = dfs(i + 1, k) + 1 ans = min(ans, dfs(i + 1, (k * 10 + int(num[i])) % 25)) return ans n ...
Solution
python
keon__algorithms
tests/test_backtrack.py
{ "start": 11653, "end": 12190 }
class ____(unittest.TestCase): def test_subsets_unique(self): nums1 = [1, 2, 2] answer1 = [(1, 2), (1,), (1, 2, 2), (2,), (), (2, 2)] self.assertEqual(sorted(subsets_unique(nums1)), sorted(answer1)) nums2 = [1, 2, 3, 4] answer2 = [(1, 2), (1, 3), (1, 2, 3, 4), (1,), (2,), (...
TestSubsetsUnique
python
huggingface__transformers
src/transformers/models/lfm2/modeling_lfm2.py
{ "start": 5978, "end": 6935 }
class ____(nn.Module): def __init__(self, config: Lfm2Config): super().__init__() intermediate_size = config.intermediate_size if config.block_auto_adjust_ff_dim: intermediate_size = int(2 * intermediate_size / 3) # custom dim factor multiplier if config.b...
Lfm2MLP
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 72219, "end": 72451 }
class ____(Elemwise): _parameters = ["frame", "divisions"] operation = staticmethod(_return_input) _preserves_partitioning_information = True def _divisions(self): return self.operand("divisions")
SetDivisions
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 246027, "end": 251145 }
class ____(Request): """ Enqueue tasks :param ids: IDs of the tasks to enqueue :type ids: Sequence[str] :param status_reason: Reason for status change :type status_reason: str :param status_message: Extra information regarding status change :type status_message: str :param queue: Qu...
EnqueueManyRequest
python
dask__distributed
distributed/diskutils.py
{ "start": 3182, "end": 9407 }
class ____: """ An on-disk workspace that tracks disposable work directories inside it. If a process crashes or another event left stale directories behind, this will be detected and the directories purged. """ base_dir: str _global_lock_path: str _purge_lock_path: str # Keep track...
WorkSpace
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_slots/SLOT001.py
{ "start": 159, "end": 216 }
class ____(Tuple[str, int, float]): # SLOT001 pass
Bad
python
Pylons__pyramid
tests/test_config/test_i18n.py
{ "start": 358, "end": 6146 }
class ____(unittest.TestCase): def _makeOne(self, *arg, **kw): from pyramid.config import Configurator config = Configurator(*arg, **kw) return config def test_set_locale_negotiator(self): from pyramid.interfaces import ILocaleNegotiator config = self._makeOne(autocomm...
TestI18NConfiguratorMixin
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 47493, "end": 47640 }
class ____: def __init__(self, name): self.name = name def __call__(self, obj): return getattr(obj, self.name)
PickleKeyFunc
python
kamyu104__LeetCode-Solutions
Python/maximum-product-of-two-integers-with-no-common-bits.py
{ "start": 67, "end": 733 }
class ____(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ l = max(nums).bit_length() dp = [0]*(1<<l) for x in nums: dp[x] = x for i in xrange(l): for j in xrange(0, 1<<l, 1<<(i+1)): ...
Solution
python
getsentry__sentry
src/sentry/grouping/enhancer/matchers.py
{ "start": 5731, "end": 10041 }
class ____(EnhancementMatch): # Global registry of matchers instances: dict[InstanceKey, EnhancementMatch] = {} field: MatchFrameKey | None = None @classmethod def from_key(cls, key: str, pattern: str, negated: bool) -> EnhancementMatch: instance_key = (key, pattern, negated) if ins...
FrameMatch
python
ray-project__ray
python/ray/experimental/util/types.py
{ "start": 418, "end": 526 }
class ____(_CollectiveOp): reduceOp: ReduceOp = ReduceOp.SUM @PublicAPI(stability="alpha")
ReduceScatterOp
python
django__django
tests/auth_tests/models/no_password.py
{ "start": 437, "end": 640 }
class ____(AbstractBaseUser): password = None last_login = None username = models.CharField(max_length=50, unique=True) USERNAME_FIELD = "username" objects = UserManager()
NoPasswordUser
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol10.py
{ "start": 423, "end": 550 }
class ____(ImplementsBase): def c(self) -> None: pass a: ProtocolExtended a = ImplementsExtended()
ImplementsExtended
python
encode__django-rest-framework
tests/test_one_to_one_with_inheritance.py
{ "start": 242, "end": 433 }
class ____(RESTFrameworkModel): child_model = models.OneToOneField(ChildModel, on_delete=models.CASCADE) child_name = models.CharField(max_length=100) # Serializers
ChildAssociatedModel
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_select.py
{ "start": 1409, "end": 2520 }
class ____(fixtures.TablesTest): __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( "some_table", metadata, Column("id", Integer, primary_key=True), Column("data", String(100)), ) @classmethod def i...
CollateTest
python
pytorch__pytorch
torch/distributed/checkpoint/hf_storage.py
{ "start": 7760, "end": 15411 }
class ____(FileSystemReader): """ A reader that reads a checkpoint in the huggingface safetensors format. """ def __init__(self, path: str, thread_count: int = 1) -> None: """ Initialize the huggingface reader pointing to path. Args: path: directory where the checkp...
HuggingFaceStorageReader
python
apache__airflow
dev/breeze/src/airflow_breeze/commands/ui_commands.py
{ "start": 4503, "end": 28289 }
class ____(NamedTuple): """ Represents a locale and its set of translation keys for a file (or None if file missing). Attributes: locale: The locale code (e.g., 'en', 'pl'). keys: A set of translation keys for the file, or None if the file is missing for this locale. """ locale: st...
LocaleKeySet
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/elasticache_replication_group.py
{ "start": 954, "end": 12089 }
class ____(AwsBaseHook): """ Interact with Amazon ElastiCache. Provide thick wrapper around :external+boto3:py:class:`boto3.client("elasticache") <ElastiCache.Client>`. :param max_retries: Max retries for checking availability of and deleting replication group If this is not supplied then ...
ElastiCacheReplicationGroupHook
python
viewflow__viewflow
tests/fsm/test_fsm__inheritance.py
{ "start": 1491, "end": 3607 }
class ____(TestCase): def setUp(self): self.publication = GuestPublication(text="test publication") self.assertEqual(self.publication.state, ReviewState.NEW) def test_method_transitions_list(self): transitions = { (transition.source, transition.target) for transi...
Test
python
Netflix__metaflow
metaflow/runner/deployer.py
{ "start": 2080, "end": 3307 }
class ____(type): def __new__(mcs, name, bases, dct): cls = super().__new__(mcs, name, bases, dct) from metaflow.plugins import DEPLOYER_IMPL_PROVIDERS def _injected_method(method_name, deployer_class): def f(self, **deployer_kwargs): return deployer_class( ...
DeployerMeta
python
doocs__leetcode
solution/2400-2499/2414.Length of the Longest Alphabetical Continuous Substring/Solution.py
{ "start": 0, "end": 287 }
class ____: def longestContinuousSubstring(self, s: str) -> int: ans = cnt = 1 for x, y in pairwise(map(ord, s)): if y - x == 1: cnt += 1 ans = max(ans, cnt) else: cnt = 1 return ans
Solution
python
keras-team__keras
keras/src/callbacks/model_checkpoint_test.py
{ "start": 504, "end": 19216 }
class ____(testing.TestCase): @pytest.mark.skipif( h5py is None, reason="`h5py` is a required dependency for `ModelCheckpoint` tests.", ) @pytest.mark.skipif( testing.jax_uses_gpu(), reason="Mysterious core dump on CI after upgrading JAX", ) @pytest.mark.requires_trai...
ModelCheckpointTest
python
realpython__materials
contact-book-python-textual/source_code_step_2/rpcontacts/tui.py
{ "start": 199, "end": 1598 }
class ____(App): CSS_PATH = "rpcontacts.tcss" BINDINGS = [ ("m", "toggle_dark", "Toggle dark mode"), ("a", "add", "Add"), ("d", "delete", "Delete"), ("c", "clear_all", "Clear All"), ("q", "request_quit", "Quit"), ] def compose(self): yield Header() ...
ContactsApp
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/freshness.py
{ "start": 10636, "end": 11009 }
class ____: """Store serialized metadata about the freshness state for an entity. Left blank for now, a few examples of what we might want to store here: - Source timestamp for external assets / freshness checks - Snapshot of the freshness policy at the time of record creation """ metadata: Op...
FreshnessStateRecordBody
python
getsentry__sentry
src/sentry/discover/models.py
{ "start": 5047, "end": 7240 }
class ____(BaseManager["TeamKeyTransaction"]): @staticmethod def __schedule_invalidate_project_config_transaction_commit(instance, trigger): try: project = getattr(instance.project_team, "project", None) except ProjectTeam.DoesNotExist: # During org deletions TeamKeyTrans...
TeamKeyTransactionModelManager
python
modin-project__modin
modin/pandas/series_utils.py
{ "start": 2197, "end": 3135 }
class ____(ClassLogger): _series: Series _query_compiler: BaseQueryCompiler def __init__(self, data: Series = None): self._series = data self._query_compiler = data._query_compiler @cached_property def _Series(self) -> Series: # noqa: GL08 # to avoid cyclic import ...
StructAccessor
python
spack__spack
lib/spack/spack/vendor/jinja2/loaders.py
{ "start": 1052, "end": 5545 }
class ____: """Baseclass for all loaders. Subclass this and override `get_source` to implement a custom loading mechanism. The environment provides a `get_template` method that calls the loader's `load` method to get the :class:`Template` object. A very basic example for a loader that looks up te...
BaseLoader
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 224890, "end": 225216 }
class ____(ConditionalMarkPropFieldOrDatumDef): """ConditionalPredicateMarkPropFieldOrDatumDef schema wrapper.""" _schema = {"$ref": "#/definitions/ConditionalPredicate<MarkPropFieldOrDatumDef>"} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
ConditionalPredicateMarkPropFieldOrDatumDef
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE807.py
{ "start": 448, "end": 564 }
class ____: foo: List[str] = field(default_factory=list) bar: Dict[str, int] = field(default_factory=dict)
Foo
python
conda__conda
conda/plugins/reporter_backends/console.py
{ "start": 1165, "end": 2667 }
class ____(ProgressBarBase): """ Progress bar class used for tqdm progress bars """ def __init__( self, description: str, position=None, leave=True, **kwargs, ) -> None: super().__init__(description) self.enabled = True bar_format = ...
TQDMProgressBar
python
django__django
django/forms/models.py
{ "start": 58197, "end": 62010 }
class ____(ModelChoiceField): """A MultipleChoiceField whose choices are a model QuerySet.""" widget = SelectMultiple hidden_widget = MultipleHiddenInput default_error_messages = { "invalid_list": _("Enter a list of values."), "invalid_choice": _( "Select a valid choice. %(v...
ModelMultipleChoiceField
python
mlflow__mlflow
tests/langchain/sample_code/workflow.py
{ "start": 681, "end": 3403 }
class ____(ChatOpenAI, extra="allow"): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._responses = iter( [ AIMessage( content="", tool_calls=[ToolCall(name="uc_tool_format", args={}, id="123")], ...
FakeOpenAI
python
python-openxml__python-docx
tests/opc/test_oxml.py
{ "start": 809, "end": 1250 }
class ____: def it_provides_read_access_to_xml_values(self): override = an_Override().element assert override.partname == "/part/name.xml" assert override.content_type == "app/vnd.type" def it_can_construct_a_new_override_element(self): override = CT_Override.new("/part/name.xml...
DescribeCT_Override
python
pennersr__django-allauth
allauth/socialaccount/providers/weixin/client.py
{ "start": 246, "end": 1931 }
class ____(OAuth2Client): def get_redirect_url(self, authorization_url, scope, extra_params): scope = self.scope_delimiter.join(set(scope)) params = { "appid": self.consumer_key, "redirect_uri": self.callback_url, "scope": scope, "response_type": "code...
WeixinOAuth2Client
python
django__django
django/core/validators.py
{ "start": 13747, "end": 13959 }
class ____(BaseValidator): message = _("Ensure this value is less than or equal to %(limit_value)s.") code = "max_value" def compare(self, a, b): return a > b @deconstructible
MaxValueValidator
python
openai__openai-python
src/openai/types/responses/response_error.py
{ "start": 190, "end": 915 }
class ____(BaseModel): code: Literal[ "server_error", "rate_limit_exceeded", "invalid_prompt", "vector_store_timeout", "invalid_image", "invalid_image_format", "invalid_base64_image", "invalid_image_url", "image_too_large", "image_too_s...
ResponseError
python
django__django
django/templatetags/i18n.py
{ "start": 1868, "end": 2092 }
class ____(Node): def __init__(self, variable): self.variable = variable def render(self, context): context[self.variable] = translation.get_language_bidi() return ""
GetCurrentLanguageBidiNode
python
keras-team__keras
keras/src/backend/common/stateless_scope_test.py
{ "start": 176, "end": 1985 }
class ____(testing.TestCase): def test_basic_flow(self): var1 = backend.Variable(np.zeros((2,))) var2 = backend.Variable(np.zeros((2,))) var_out = backend.Variable(np.zeros((2,))) value1 = ops.ones(shape=(2,)) value2 = ops.ones(shape=(2,)) with StatelessScope( ...
TestStatelessScope
python
tiangolo__fastapi
docs_src/schema_extra_example/tutorial002_py310.py
{ "start": 85, "end": 479 }
class ____(BaseModel): name: str = Field(examples=["Foo"]) description: str | None = Field(default=None, examples=["A very nice Item"]) price: float = Field(examples=[35.4]) tax: float | None = Field(default=None, examples=[3.2]) @app.put("/items/{item_id}") async def update_item(item_id: int, item: I...
Item
python
openai__openai-python
src/openai/types/chat/chat_completion_allowed_tool_choice_param.py
{ "start": 318, "end": 636 }
class ____(TypedDict, total=False): allowed_tools: Required[ChatCompletionAllowedToolsParam] """Constrains the tools available to the model to a pre-defined set.""" type: Required[Literal["allowed_tools"]] """Allowed tool configuration type. Always `allowed_tools`."""
ChatCompletionAllowedToolChoiceParam
python
kamyu104__LeetCode-Solutions
Python/keyboard-row.py
{ "start": 29, "end": 745 }
class ____(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ rows = [set(['q', 'w', 'e', 'r', 't', 'y','u', 'i', 'o', 'p']), set(['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']), set(['z', 'x', 'c', 'v', 'b' ,'...
Solution
python
dateutil__dateutil
tests/test_tz.py
{ "start": 6785, "end": 6969 }
class ____(object): def __init__(*args, **kwargs): pass def __enter__(*args, **kwargs): pass def __exit__(*args, **kwargs): pass
context_passthrough
python
doocs__leetcode
solution/1000-1099/1049.Last Stone Weight II/Solution.py
{ "start": 0, "end": 504 }
class ____: def lastStoneWeightII(self, stones: List[int]) -> int: s = sum(stones) m, n = len(stones), s >> 1 dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(n + 1): dp[i][j] = dp[i - 1][j] if stones[i - ...
Solution
python
huggingface__transformers
tests/models/ibert/test_modeling_ibert.py
{ "start": 1520, "end": 8753 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_head...
IBertModelTester
python
celery__celery
t/unit/utils/test_serialization.py
{ "start": 2629, "end": 3256 }
class ____: @pytest.mark.parametrize('s,b', STRTOBOOL_DEFAULT_TABLE.items()) def test_default_table(self, s, b): assert strtobool(s) == b def test_unknown_value(self): with pytest.raises(TypeError, match="Cannot coerce 'foo' to type bool"): strtoboo...
test_strtobool
python
huggingface__transformers
src/transformers/models/yoso/modeling_yoso.py
{ "start": 11114, "end": 16919 }
class ____(nn.Module): def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention...
YosoSelfAttention
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1408307, "end": 1408583 }
class ____(sgqlc.types.Type, Node, AuditEntry, OrganizationAuditEntryData, RepositoryAuditEntryData): """Audit log entry for a repo.config.lock_anonymous_git_access event.""" __schema__ = github_schema __field_names__ = ()
RepoConfigLockAnonymousGitAccessAuditEntry
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_bigquery.py
{ "start": 63895, "end": 77868 }
class ____: def setup_method(self) -> None: class MockedBigQueryAsyncHook(BigQueryAsyncHook): def get_credentials_and_project_id(self): return CREDENTIALS, PROJECT_ID self.hook = MockedBigQueryAsyncHook() @pytest.mark.db_test @pytest.mark.asyncio @mock.patch...
TestBigQueryAsyncHookMethods
python
celery__celery
t/unit/tasks/test_trace.py
{ "start": 21585, "end": 23214 }
class ____: def test_stackprotection(self): setup_worker_optimizations(self.app) try: @self.app.task(shared=False, bind=True) def foo(self, i): if i: return foo(0) return self.request assert foo(1).called_direc...
test_stackprotection
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_table_via_select.py
{ "start": 808, "end": 21706 }
class ____(fixtures.TablesTest): __sparse_driver_backend__ = True @classmethod def temp_table_name(cls): return get_temp_table_name( config, config.db, f"user_tmp_{config.ident}" ) @classmethod def temp_view_name(cls): return get_temp_table_name( con...
TableViaSelectTest
python
hynek__structlog
tests/test_stdlib.py
{ "start": 1788, "end": 4860 }
class ____: def setup_method(self, method): """ The stdlib logger factory modifies global state to fix caller identification. """ self.original_logger = logging.getLoggerClass() def teardown_method(self, method): logging.setLoggerClass(self.original_logger) ...
TestLoggerFactory
python
getsentry__sentry
src/sentry/grouping/enhancer/matchers.py
{ "start": 10920, "end": 10973 }
class ____(PathLikeMatch): field = "path"
PathMatch
python
sphinx-doc__sphinx
tests/roots/test-ext-imgmockconverter/mocksvgconverter.py
{ "start": 343, "end": 939 }
class ____(ImageConverter): conversion_rules = [ ('image/svg+xml', 'application/pdf'), ] def is_available(self) -> bool: return True def convert( self, _from: str | os.PathLike[str], _to: str | os.PathLike[str] ) -> bool: """Mock converts the image from SVG to PDF."...
MyConverter
python
PyCQA__pylint
tests/functional/a/arguments.py
{ "start": 354, "end": 2500 }
class ____: """Test class for method invocations.""" @staticmethod def static_method(arg): """static method.""" return arg + arg @classmethod def class_method(cls, arg): """class method""" return arg + arg def method(self, arg): """method.""" re...
DemoClass
python
celery__celery
celery/utils/graph.py
{ "start": 650, "end": 6391 }
class ____: """A directed acyclic graph of objects and their dependencies. Supports a robust topological sort to detect the order in which they must be handled. Takes an optional iterator of ``(obj, dependencies)`` tuples to build the graph from. Warning: Does not support cycle detect...
DependencyGraph
python
pyca__cryptography
src/cryptography/hazmat/primitives/hashes.py
{ "start": 2975, "end": 3087 }
class ____(HashAlgorithm): # noqa: N801 name = "sha3-256" digest_size = 32 block_size = None
SHA3_256