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
facelessuser__pymdown-extensions
tests/test_extensions/test_highlight.py
{ "start": 14100, "end": 14857 }
class ____(util.MdCase): """Test with line numbers globally disabled with no Pygments.""" extension = ['pymdownx.highlight', 'pymdownx.superfences'] extension_configs = { 'pymdownx.highlight': { 'linenums': False, 'use_pygments': False } } def test_global_di...
TestDisabledLinenumsNoPygments
python
pytorch__pytorch
torch/_inductor/codegen/cpp_utils.py
{ "start": 10930, "end": 28276 }
class ____: """ This class creates a context that helps to generate code involving Inductor IR with function local buffers. These buffers are constructed during the codegen process and are used to store intermediate results such as local accumulators. We do not want to add them to `V.graph` since th...
LocalBufferContext
python
pytorch__pytorch
torch/distributions/transforms.py
{ "start": 6657, "end": 8515 }
class ____(Transform): """ Inverts a single :class:`Transform`. This class is private; please instead use the ``Transform.inv`` property. """ def __init__(self, transform: Transform) -> None: super().__init__(cache_size=transform._cache_size) self._inv: Transform = transform # type...
_InverseTransform
python
walkccc__LeetCode
solutions/3551. Minimum Swaps to Sort by Digit Sum/3551.py
{ "start": 0, "end": 598 }
class ____: def minSwaps(self, nums: list[int]) -> int: ans = 0 seen = set() sortedNums = sorted(nums, key=lambda x: (self._getDigitSum(x), x)) numToIndex = {num: i for i, num in enumerate(sortedNums)} for i, num in enumerate(nums): if i in seen or numToIndex[num] == i: continue ...
Solution
python
huggingface__transformers
src/transformers/models/sam2_video/modeling_sam2_video.py
{ "start": 43859, "end": 44536 }
class ____(nn.Module): def __init__(self, config: Sam2VideoConfig, in_channels: int, out_channels: int): super().__init__() self.conv = nn.Conv2d( in_channels, out_channels, kernel_size=config.mask_downsampler_kernel_size, stride=config.mask_downsample...
Sam2VideoMaskDownSamplerLayer
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 28007, "end": 28159 }
class ____(_TargetArgsExpr): """ Matches a call_module node in the FX graphs: `module(*args, **kwargs)` """ op = "call_module"
CallModule
python
huggingface__transformers
examples/modular-transformers/configuration_new_model.py
{ "start": 678, "end": 7923 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`NewModelModel`]. It is used to instantiate an NewModel model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar co...
NewModelConfig
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefault3.py
{ "start": 398, "end": 491 }
class ____(Generic[T2, T1]): ... # This should generate an error because T1 is after T2.
ClassA
python
huggingface__transformers
src/transformers/models/data2vec/modeling_data2vec_text.py
{ "start": 47580, "end": 50586 }
class ____(Data2VecTextPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) # Ini...
Data2VecTextForQuestionAnswering
python
tensorflow__tensorflow
tensorflow/python/debug/lib/debug_grappler_test.py
{ "start": 1974, "end": 5080 }
class ____(test_util.TensorFlowTestCase): def setUp(self): super(SessionDebugGrapplerInteractionTest, self).setUp() self._dump_root = tempfile.mkdtemp() self._debug_url = "file://%s" % self._dump_root def tearDown(self): ops.reset_default_graph() if os.path.isdir(self._dump_root): file_i...
SessionDebugGrapplerInteractionTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 920096, "end": 920688 }
class ____(sgqlc.types.Type): """Autogenerated return type of RegenerateEnterpriseIdentityProviderRecoveryCodes """ __schema__ = github_schema __field_names__ = ("client_mutation_id", "identity_provider") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A u...
RegenerateEnterpriseIdentityProviderRecoveryCodesPayload
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 10333, "end": 10395 }
class ____(_ClusterPermission): pass
ClusterPermissionOutput
python
django__django
django/core/management/commands/testserver.py
{ "start": 135, "end": 2221 }
class ____(BaseCommand): help = "Runs a development server with data from the given fixture(s)." requires_system_checks = [] def add_arguments(self, parser): parser.add_argument( "args", metavar="fixture", nargs="*", help="Path(s) to fixtures to load...
Command
python
django__django
tests/composite_pk/models/tenant.py
{ "start": 418, "end": 705 }
class ____(models.Model): pk = models.CompositePrimaryKey("tenant_id", "id") tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE) email = models.EmailField(unique=True) id = models.SmallIntegerField(unique=True) class Meta: abstract = True
AbstractUser
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/file_manager.py
{ "start": 1965, "end": 8453 }
class ____(ABC): """Base class for all file managers in dagster. The file manager is an interface that can be implemented by resources to provide abstract access to a file system such as local disk, S3, or other cloud storage. For examples of usage, see the documentation of the concrete file manager i...
FileManager
python
Lightning-AI__lightning
tests/tests_pytorch/strategies/test_ddp_integration.py
{ "start": 9412, "end": 10037 }
class ____(BoringModel): def on_train_start(self) -> None: # make sure that the model is on CPU when training assert self.device == torch.device("cpu") @RunIf(skip_windows=True) def test_ddp_cpu(): """Tests if device is set correctly when training for DDPStrategy.""" trainer = Trainer(devi...
BoringModelDDPCPU
python
apache__airflow
airflow-core/src/airflow/models/taskinstance.py
{ "start": 13799, "end": 95649 }
class ____(Base, LoggingMixin): """ Task instances store the state of a task instance. This table is the authority and single source of truth around what tasks have run and the state they are in. The SqlAlchemy model doesn't have a SqlAlchemy foreign key to the task or dag model deliberately t...
TaskInstance
python
PrefectHQ__prefect
src/prefect/task_engine.py
{ "start": 10518, "end": 33811 }
class ____(BaseTaskRunEngine[P, R]): task_run: Optional[TaskRun] = None _client: Optional[SyncPrefectClient] = None @property def client(self) -> SyncPrefectClient: if not self._is_started or self._client is None: raise RuntimeError("Engine has not started.") return self._cl...
SyncTaskRunEngine
python
dagster-io__dagster
python_modules/dagster/dagster/_core/workspace/permissions.py
{ "start": 116, "end": 3343 }
class ____(str, Enum): LAUNCH_PIPELINE_EXECUTION = "launch_pipeline_execution" LAUNCH_PIPELINE_REEXECUTION = "launch_pipeline_reexecution" START_SCHEDULE = "start_schedule" STOP_RUNNING_SCHEDULE = "stop_running_schedule" EDIT_SENSOR = "edit_sensor" UPDATE_SENSOR_CURSOR = "update_sensor_cursor" ...
Permissions
python
ansible__ansible
test/units/cli/test_galaxy.py
{ "start": 14600, "end": 15123 }
class ____(unittest.TestCase, ValidRoleTests): @classmethod def setUpClass(cls): cls.setUpRole(role_name='delete_me') @classmethod def tearDownClass(cls): cls.tearDownRole() def test_metadata_contents(self): with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') a...
TestGalaxyInitDefault
python
django__django
tests/m2o_recursive/models.py
{ "start": 609, "end": 969 }
class ____(models.Model): full_name = models.CharField(max_length=20) mother = models.ForeignKey( "self", models.SET_NULL, null=True, related_name="mothers_child_set" ) father = models.ForeignKey( "self", models.SET_NULL, null=True, related_name="fathers_child_set" ) def __str__...
Person
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-dashscope/tests/test_dashscope.py
{ "start": 1685, "end": 9984 }
class ____: metadata = DummyMetadata() @patch("llama_index.llms.dashscope.base.call_with_messages") def test_dashscope_complete( mock_call_with_messages, dashscope_llm, dashscope_api_response, prompt ): mock_call_with_messages.return_value = dashscope_api_response response = dashscope_llm.complete(pro...
DummyTool
python
walkccc__LeetCode
solutions/3207. Maximum Points After Enemy Battles/3207.py
{ "start": 0, "end": 254 }
class ____: def maximumPoints(self, enemyEnergies: list[int], currentEnergy: int) -> int: minEnergy = min(enemyEnergies) return (0 if currentEnergy < minEnergy else (currentEnergy + sum(enemyEnergies) - minEnergy) // minEnergy)
Solution
python
Pylons__pyramid
tests/test_csrf.py
{ "start": 10366, "end": 15672 }
class ____(unittest.TestCase): def _callFUT(self, *args, **kwargs): from pyramid.csrf import check_csrf_origin return check_csrf_origin(*args, **kwargs) def test_success_with_http(self): request = testing.DummyRequest() request.scheme = "http" self.assertTrue(self._call...
Test_check_csrf_origin
python
pennersr__django-allauth
tests/projects/common/idp/rest_framework/views.py
{ "start": 256, "end": 532 }
class ____(APIView): authentication_classes = [TokenAuthentication] permission_classes = [TokenPermission.has_scope(["view-resource"])] def get(self, request, *args, **kwargs): return Response({"resource": "ok", "user_email": request.user.email})
ResourceView
python
anthropics__anthropic-sdk-python
src/anthropic/types/raw_message_delta_event.py
{ "start": 432, "end": 1275 }
class ____(BaseModel): delta: Delta type: Literal["message_delta"] usage: MessageDeltaUsage """Billing and rate-limit usage. Anthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems. Under the hood, the API transforms requests into a f...
RawMessageDeltaEvent
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/streams.py
{ "start": 16271, "end": 16366 }
class ____(IterableExportStreamAdjustableRange): data_field = "emailSubscribe"
EmailSubscribe
python
mwaskom__seaborn
seaborn/_core/scales.py
{ "start": 16928, "end": 25210 }
class ____(ContinuousBase): """ A numeric scale supporting norms and functional transforms. """ values: tuple | str | None = None trans: str | TransFuncs | None = None # TODO Add this to deal with outliers? # outside: Literal["keep", "drop", "clip"] = "keep" _priority: ClassVar[int] = ...
Continuous
python
run-llama__llama_index
llama-index-packs/llama-index-packs-evaluator-benchmarker/llama_index/packs/evaluator_benchmarker/base.py
{ "start": 404, "end": 6374 }
class ____(BaseLlamaPack): """ A pack for benchmarking/evaluating your own evaluator. Args: evaluator (BaseEvaluator): The evaluator to evaluate/benchmark. eval_dataset (LabelledEvaluatorDataset | LabelledPairwiseEvaluatorDataset): The labelled evaluation dataset to run benchmar...
EvaluatorBenchmarkerPack
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/class_definition.py
{ "start": 1721, "end": 1858 }
class ____( 1 # comment ): pass @dataclass # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->AltCLIP
C
python
walkccc__LeetCode
solutions/346. Moving Average from Data Stream/346.py
{ "start": 0, "end": 308 }
class ____: def __init__(self, size: int): self.size = size self.sum = 0 self.q = collections.deque() def next(self, val: int) -> float: if len(self.q) == self.size: self.sum -= self.q.popleft() self.sum += val self.q.append(val) return self.sum / len(self.q)
MovingAverage
python
sphinx-doc__sphinx
sphinx/pygments_styles.py
{ "start": 317, "end": 380 }
class ____(Style): """Style without any styling."""
NoneStyle
python
airbytehq__airbyte
airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/test_owners_archived.py
{ "start": 452, "end": 2614 }
class ____(HubspotTestCase): """ The test case contains a single test - this is just a sanity check, as the tested stream is identical to the `Owners` stream (which is covered by acceptance tests), except for a single url param. """ SCOPES = ["crm.objects.owners.read"] CURSOR_FIELD = "updatedAt...
TestOwnersArchivedStream
python
pyqtgraph__pyqtgraph
pyqtgraph/ThreadsafeTimer.py
{ "start": 55, "end": 1611 }
class ____(QtCore.QObject): """ Thread-safe replacement for QTimer. """ timeout = QtCore.Signal() sigTimerStopRequested = QtCore.Signal() sigTimerStartRequested = QtCore.Signal(object) def __init__(self): QtCore.QObject.__init__(self) self.timer = QtCore.QTimer() ...
ThreadsafeTimer
python
airbytehq__airbyte
airbyte-integrations/connectors/source-mixpanel/source_mixpanel/components.py
{ "start": 4565, "end": 5040 }
class ____(SubstreamPartitionRouter): def get_request_body_json( self, stream_state: Optional[StreamState] = None, stream_slice: Optional[StreamSlice] = None, next_page_token: Optional[Mapping[str, Any]] = None, ) -> Mapping[str, Any]: # https://developer.mixpanel.com/ref...
CohortMembersSubstreamPartitionRouter
python
scipy__scipy
scipy/stats/_distn_infrastructure.py
{ "start": 116136, "end": 147046 }
class ____(rv_generic): """A generic discrete random variable class meant for subclassing. `rv_discrete` is a base class to construct specific distribution classes and instances for discrete random variables. It can also be used to construct an arbitrary distribution defined by a list of support po...
rv_discrete
python
chroma-core__chroma
chromadb/test/api/test_schema.py
{ "start": 1192, "end": 2123 }
class ____(EmbeddingFunction[List[str]]): """Mock embedding function for testing.""" def __init__(self, model_name: str = "mock_model"): self._model_name = model_name def __call__(self, input: List[str]) -> Embeddings: import numpy as np # Return mock embeddings (3-dimensional) ...
MockEmbeddingFunction
python
astropy__astropy
astropy/io/fits/util.py
{ "start": 641, "end": 29352 }
class ____: """ Mixin class that provides services by which objects can register listeners to changes on that object. All methods provided by this class are underscored, since this is intended for internal use to communicate between classes in a generic way, and is not machinery that should be ...
NotifierMixin
python
django__django
tests/delete/models.py
{ "start": 6732, "end": 6863 }
class ____(models.Model): b1 = models.ForeignKey(B1, models.RESTRICT) b2 = models.ForeignKey(B2, models.CASCADE)
DeleteBottom
python
walkccc__LeetCode
solutions/1259. Handshakes That Don't Cross/1259.py
{ "start": 0, "end": 387 }
class ____: def numberOfWays(self, numPeople: int) -> int: MOD = 1_000_000_007 # dp[i] := the number of ways i handshakes could occure s.t. none of the # handshakes cross dp = [1] + [0] * (numPeople // 2) for i in range(1, numPeople // 2 + 1): for j in range(i): dp[i] += dp[j] * dp[...
Solution
python
pandas-dev__pandas
pandas/tests/arrays/sparse/test_constructors.py
{ "start": 227, "end": 10573 }
class ____: def test_constructor_dtype(self): arr = SparseArray([np.nan, 1, 2, np.nan]) assert arr.dtype == SparseDtype(np.float64, np.nan) assert arr.dtype.subtype == np.float64 assert np.isnan(arr.fill_value) arr = SparseArray([np.nan, 1, 2, np.nan], fill_value=0) ...
TestConstructors
python
pdm-project__pdm
src/pdm/installers/uv.py
{ "start": 3721, "end": 3965 }
class ____(UvSynchronizer): def _get_sync_command(self) -> list[str | HiddenText]: cmd = super()._get_sync_command() if "--verbose" in cmd: cmd.remove("--verbose") return [*cmd, "--quiet"]
QuietUvSynchronizer
python
doocs__leetcode
solution/1900-1999/1914.Cyclically Rotating a Grid/Solution.py
{ "start": 0, "end": 1189 }
class ____: def rotateGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: def rotate(p: int, k: int): nums = [] for j in range(p, n - p - 1): nums.append(grid[p][j]) for i in range(p, m - p - 1): nums.append(grid[i][n - p - 1]) ...
Solution
python
ray-project__ray
python/ray/autoscaler/_private/event_system.py
{ "start": 151, "end": 1623 }
class ____(Enum): """Events to track in ray.autoscaler.sdk.create_or_update_cluster. Attributes: up_started : Invoked at the beginning of create_or_update_cluster. ssh_keypair_downloaded : Invoked when the ssh keypair is downloaded. cluster_booting_started : Invoked when when the cluste...
CreateClusterEvent
python
coleifer__peewee
tests/regressions.py
{ "start": 32261, "end": 32641 }
class ____(ModelTestCase): requires = [TC] def test_type_coercion(self): t = TC.create(ifield='10', ffield='20.5', cfield=30, tfield=40) t_db = TC.get(TC.id == t.id) self.assertEqual(t_db.ifield, 10) self.assertEqual(t_db.ffield, 20.5) self.assertEqual(t_db.cfield, '30'...
TestTypeCoercion
python
huggingface__transformers
src/transformers/models/wav2vec2_with_lm/processing_wav2vec2_with_lm.py
{ "start": 2368, "end": 28786 }
class ____(ProcessorMixin): r""" Constructs a Wav2Vec2 processor which wraps a Wav2Vec2 feature extractor, a Wav2Vec2 CTC tokenizer and a decoder with language model support into a single processor for language model boosted speech recognition decoding. Args: feature_extractor ([`Wav2Vec2Featur...
Wav2Vec2ProcessorWithLM
python
huggingface__transformers
src/transformers/models/glm4/modular_glm4.py
{ "start": 4872, "end": 4950 }
class ____(GlmForSequenceClassification): pass
Glm4ForSequenceClassification
python
huggingface__transformers
src/transformers/models/chameleon/modeling_chameleon.py
{ "start": 24180, "end": 24666 }
class ____(nn.Module): def __init__(self, in_channels): super().__init__() self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0) def forward(self, hidden_states): # no asymmetric padding in torch conv, must do it ourselves hidden_states = F.pad(hidd...
ChameleonVQVAEEncoderConvDownsample
python
pytorch__pytorch
torch/_export/db/case.py
{ "start": 682, "end": 1769 }
class ____(Enum): """ Indicates at what stage the feature used in the example is handled in export. """ SUPPORTED = 1 NOT_SUPPORTED_YET = 0 ArgsType = tuple[Any, ...] def check_inputs_type(args, kwargs): if not isinstance(args, tuple): raise ValueError( f"Expecting a...
SupportLevel
python
networkx__networkx
networkx/algorithms/tree/tests/test_mst.py
{ "start": 8826, "end": 9876 }
class ____(MinimumSpanningTreeTestBase): """Unit tests for computing a minimum (or maximum) spanning tree using Borůvka's algorithm. """ algorithm = "boruvka" def test_unicode_name(self): """Tests that using a Unicode string can correctly indicate Borůvka's algorithm. """ ...
TestBoruvka
python
tornadoweb__tornado
tornado/simple_httpclient.py
{ "start": 1934, "end": 8700 }
class ____(AsyncHTTPClient): """Non-blocking HTTP client with no external dependencies. This class implements an HTTP 1.1 client on top of Tornado's IOStreams. Some features found in the curl-based AsyncHTTPClient are not yet supported. In particular, proxies are not supported, connections are not...
SimpleAsyncHTTPClient
python
Textualize__textual
src/textual/pilot.py
{ "start": 1284, "end": 1397 }
class ____(Exception): """Raised when the pilot mouse target is outside of the (visible) screen."""
OutOfBounds
python
getsentry__sentry
src/sentry/issues/endpoints/organization_group_suspect_tags.py
{ "start": 560, "end": 2191 }
class ____(GroupEndpoint): publish_status = {"GET": ApiPublishStatus.PRIVATE} def get(self, request: Request, group: Group) -> Response: """Stats bucketed by time.""" if not features.has( "organizations:issues-suspect-tags", group.organization, actor=request....
OrganizationGroupSuspectTagsEndpoint
python
astropy__astropy
astropy/coordinates/tests/test_representation_arithmetic.py
{ "start": 45850, "end": 54325 }
class ____: def setup_method(self): self.s = SphericalRepresentation( lon=[0.0, 6.0, 21.0] * u.hourangle, lat=[0.0, -30.0, 85.0] * u.deg, distance=[1, 2, 3] * u.kpc, ) @pytest.mark.parametrize( "sd_cls", [SphericalDifferential, SphericalCosLatDifferen...
TestDifferentialConversion
python
lepture__authlib
authlib/integrations/django_oauth2/resource_protector.py
{ "start": 1958, "end": 2597 }
class ____(_BearerTokenValidator): def __init__(self, token_model, realm=None, **extra_attributes): self.token_model = token_model super().__init__(realm, **extra_attributes) def authenticate_token(self, token_string): try: return self.token_model.objects.get(access_token=to...
BearerTokenValidator
python
pytorch__pytorch
torch/fx/interpreter.py
{ "start": 19436, "end": 25278 }
class ____(Interpreter): """ ``Transformer`` is a special type of interpreter that produces a new ``Module``. It exposes a ``transform()`` method that returns the transformed ``Module``. ``Transformer`` does not require arguments to run, as ``Interpreter`` does. ``Transformer`` works entirely sy...
Transformer
python
HypothesisWorks__hypothesis
hypothesis-python/tests/attrs/test_pretty.py
{ "start": 853, "end": 1177 }
class ____: def _repr_pretty_(self, p, cycle): """Exercise the IPython callback interface.""" p.text("I am a banana") def test_custom_pretty_print_method_overrides_field_printing(): assert pretty.pretty(SomeAttrsClassWithCustomPretty()) == "I am a banana" @attrs.define
SomeAttrsClassWithCustomPretty
python
ansible__ansible
test/lib/ansible_test/_internal/config.py
{ "start": 11854, "end": 12366 }
class ____(TestConfig): """Configuration for the units command.""" def __init__(self, args: t.Any) -> None: super().__init__(args, 'units') self.collect_only: bool = args.collect_only self.num_workers: int = args.num_workers self.requirements_mode: str = getattr(args, 'require...
UnitsConfig
python
kamyu104__LeetCode-Solutions
Python/truncate-sentence.py
{ "start": 29, "end": 337 }
class ____(object): def truncateSentence(self, s, k): """ :type s: str :type k: int :rtype: str """ for i in xrange(len(s)): if s[i] == ' ': k -= 1 if not k: return s[:i] return s
Solution
python
run-llama__llama_index
llama-index-core/llama_index/core/instrumentation/events/agent.py
{ "start": 1342, "end": 2738 }
class ____(BaseEvent): """ AgentChatWithStepEndEvent. Args: response (Optional[AGENT_CHAT_RESPONSE_TYPE]): Agent chat response. """ response: Optional[AGENT_CHAT_RESPONSE_TYPE] @model_validator(mode="before") @classmethod def validate_response(cls: Any, values: Any) -> Any: ...
AgentChatWithStepEndEvent
python
ansible__ansible
lib/ansible/modules/group.py
{ "start": 9009, "end": 9661 }
class ____(Group): """ This is a Linux Group manipulation class. This is to apply the '-f' parameter to the groupdel command This overrides the following methods from the generic class:- - group_del() """ platform = 'Linux' distribution = None def group_del(self): if self....
Linux
python
Pylons__pyramid
src/pyramid/interfaces.py
{ "start": 31637, "end": 32610 }
class ____(Interface): def __call__(request, elements, kw): """A pregenerator is a function associated by a developer with a :term:`route`. The pregenerator for a route is called by :meth:`pyramid.request.Request.route_url` in order to adjust the set of arguments passed to it by the ...
IRoutePregenerator
python
jazzband__django-formtools
tests/wizard/wizardtests/tests.py
{ "start": 18409, "end": 19183 }
class ____(TestCase): def setUp(self): self.rf = RequestFactory() self.poet = Poet.objects.create(name='test') self.poem = self.poet.poem_set.create(name='test poem') def test_set_instance(self): # Regression test for #21259 poet = self.poet class InlineFormSetW...
WizardInlineFormSetTests
python
tensorflow__tensorflow
tensorflow/python/util/deprecation_test.py
{ "start": 40975, "end": 41516 }
class ____(test.TestCase): @test.mock.patch.object(logging, "warning", autospec=True) def testCallDeprecatedModule(self, mock_warning): from tensorflow.python.util import deprecated_module # pylint: disable=g-import-not-at-top self.assertEqual(0, mock_warning.call_count) result = deprecated_module.a()...
DeprecateMovedModuleTest
python
Textualize__textual
src/textual/widgets/_select.py
{ "start": 5607, "end": 8236 }
class ____(Horizontal): """Displays the currently selected option.""" DEFAULT_CSS = """ SelectCurrent { border: tall $border-blurred; color: $foreground; background: $surface; width: 1fr; height: auto; padding: 0 2; &.-textual-compact { b...
SelectCurrent
python
wandb__wandb
wandb/sdk/data_types/helper_types/bounding_boxes_2d.py
{ "start": 709, "end": 13794 }
class ____(JSONMetadata): """Format images with 2D bounding box overlays for logging to W&B. Args: val: (dictionary) A dictionary of the following form: box_data: (list of dictionaries) One dictionary for each bounding box, containing: position: (dictionary) the position and...
BoundingBoxes2D
python
pytorch__pytorch
torch/_dynamo/device_interface.py
{ "start": 19464, "end": 22332 }
class ____(DeviceInterface): @staticmethod def is_bf16_supported(including_emulation: bool = False) -> bool: return torch.backends.mps.is_macos_or_newer(14, 0) @classmethod def is_dtype_supported( cls, dtype: torch.dtype, including_emulation: bool = False ) -> bool: if dtype...
MpsInterface
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 83412, "end": 83802 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = FunctionalConv2d() self.conv2 = FunctionalConv2d() def forward(self, x): x = self.conv1(x) x = self.conv2(x) return x def get_example_inputs(self) -> tuple[Any, ...]: ...
TwoLayerFunctionalConvModel
python
scrapy__scrapy
tests/test_feedexport.py
{ "start": 4940, "end": 7880 }
class ____: def get_test_spider(self, settings=None): class TestSpider(scrapy.Spider): name = "test_spider" crawler = get_crawler(settings_dict=settings) return TestSpider.from_crawler(crawler) async def _store(self, uri, content, feed_options=None, settings=None): ...
TestFTPFeedStorage
python
dagster-io__dagster
python_modules/dagster/dagster/components/resolved/scopes.py
{ "start": 2711, "end": 3462 }
class ____(WrappedObjectScope): """Provides access to Dagster definitions and utilities within templates. Available via `{{ dg.* }}` in component YAML files. Examples: {{ dg.AutomationCondition.eager() }} {{ dg.DailyPartitionsDefinition(start_date="2024-01-01") }} """ def __init__...
DgScope
python
getsentry__sentry
tests/sentry/seer/fetch_issues/test_by_function_name.py
{ "start": 16124, "end": 21188 }
class ____(IntegrationTestCase, CreateEventTestCase): provider = GitHubIntegrationProvider def setUp(self): super().setUp() self.gh_repo: Repository = self.create_repo( name="getsentry/sentry", provider="integrations:github", integration_id=self.integration.i...
TestFetchIssuesFromRepoProjects
python
walkccc__LeetCode
solutions/500. Keyboard Row/500.py
{ "start": 0, "end": 297 }
class ____: def findWords(self, words: list[str]) -> list[str]: ans = [] rows = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')] for word in words: lowerWord = set(word.lower()) if any(lowerWord <= row for row in rows): ans.append(word) return ans
Solution
python
sympy__sympy
sympy/integrals/manualintegrate.py
{ "start": 4310, "end": 4587 }
class ____(AtomicRule): """integrate(x**a, x)""" base: Expr exp: Expr def eval(self) -> Expr: return Piecewise( ((self.base**(self.exp + 1))/(self.exp + 1), Ne(self.exp, -1)), (log(self.base), True), ) @dataclass
PowerRule
python
jazzband__django-model-utils
tests/models.py
{ "start": 9370, "end": 9555 }
class ____(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() mutable = MutableField(default=None) tracker = ModelTracker()
ModelTracked
python
PyCQA__pylint
tests/functional/i/invalid/invalid_exceptions/invalid_exceptions_caught.py
{ "start": 2270, "end": 2358 }
class ____(HasErrorInMRO): pass try: raise Second except Second: pass
Second
python
google__pytype
pytype/pyc/opcodes.py
{ "start": 8786, "end": 8886 }
class ____(Opcode): _FLAGS = HAS_JUNKNOWN # might call __exit__ __slots__ = ()
WITH_CLEANUP_START
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/ddl.py
{ "start": 14941, "end": 15093 }
class ____(_CreateBase["Table"]): def to_metadata(self, metadata: MetaData, table: Table) -> Self: raise NotImplementedError()
TableCreateDDL
python
numba__numba
numba/core/utils.py
{ "start": 11305, "end": 11832 }
class ____(MutableMapping[Tk, Tv], _tp.Generic[Tk, Tv]): def __init__(self, dct=None): if dct is None: dct = {} self._dct: dict[Tk, Tv] = dct def __getitem__(self, k: Tk) -> Tv: return self._dct[k] def __setitem__(self, k: Tk, v: Tv): self._dct[k] = v def _...
MutableSortedMap
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE796.py
{ "start": 653, "end": 719 }
class ____(enum.Enum): A = "A" B = "B" C = "C"
FakeEnum9
python
catalyst-team__catalyst
catalyst/contrib/losses/regression.py
{ "start": 228, "end": 1258 }
class ____(nn.Module): """@TODO: Docs. Contribution is welcome.""" def __init__(self, clip_delta=1.0, reduction="mean"): """@TODO: Docs. Contribution is welcome.""" super().__init__() self.clip_delta = clip_delta self.reduction = reduction or "none" def forward( sel...
HuberLossV0
python
pypa__warehouse
warehouse/packaging/search.py
{ "start": 402, "end": 1879 }
class ____(Document): name = Text() normalized_name = Text(analyzer=NameAnalyzer) summary = Text(analyzer="snowball") description = Text(analyzer="snowball") author = Text() author_email = Text(analyzer=EmailAnalyzer) maintainer = Text() maintainer_email = Text(analyzer=EmailAnalyzer) ...
Project
python
geekcomputers__Python
flappyBird_pygame/flappy_bird.py
{ "start": 361, "end": 1937 }
class ____(pygame.sprite.Sprite): WIDTH = 32 # bird image width HEIGHT = 32 # bird image height DOWN_SPEED = 0.18 # pix per ms -y UP_SPEED = 0.3 # pix per ms +y UP_DURATION = 150 # time for which bird go up def __init__(self, x, y, ms_to_up, images): super(Bird, self)._...
Bird
python
pennersr__django-allauth
tests/apps/socialaccount/providers/xing/tests.py
{ "start": 235, "end": 2127 }
class ____(OAuthTestsMixin, TestCase): provider_id = XingProvider.id def get_mocked_response(self): return [ MockedResponse( HTTPStatus.OK, """ {"users":[{"id":"20493333_1cd028","active_email":"raymond.penners@example.com", "badges":[],"birth_date":{"year":nu...
XingTests
python
plotly__plotly.py
plotly/graph_objs/layout/map/layer/_circle.py
{ "start": 235, "end": 2380 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout.map.layer" _path_str = "layout.map.layer.circle" _valid_props = {"radius"} @property def radius(self): """ Sets the circle radius (map.layer.paint.circle-radius). Has an effect only when `type` is set to "circl...
Circle
python
astropy__astropy
astropy/utils/metadata/tests/test_metadata.py
{ "start": 318, "end": 369 }
class ____(OrderedDict): pass
OrderedDictSubclass
python
coleifer__peewee
peewee.py
{ "start": 13673, "end": 13731 }
class ____(object): pass # SQL Generation.
ModelDescriptor
python
numba__numba
numba/core/typing/templates.py
{ "start": 8018, "end": 11182 }
class ____(ABC): # Set to true to disable unsafe cast. # subclass overide-able unsafe_casting = True # Set to true to require exact match without casting. # subclass overide-able exact_match_required = False # Set to true to prefer literal arguments. # Useful for definitions that special...
FunctionTemplate
python
scipy__scipy
scipy/special/tests/test_legendre.py
{ "start": 21309, "end": 28518 }
class ____: @pytest.mark.parametrize("shape", [(10,), (4, 9), (3, 5, 7)]) def test_specific(self, shape): rng = np.random.default_rng(1234) theta = rng.uniform(-np.pi, np.pi, shape) p, p_jac = sph_legendre_p_all(4, 4, theta, diff_n=1) np.testing.assert_allclose(p[0, 0], ...
TestSphLegendreP
python
matplotlib__matplotlib
lib/matplotlib/backend_bases.py
{ "start": 52580, "end": 60907 }
class ____(LocationEvent): """ A key event (key press, key release). A KeyEvent has a number of special attributes in addition to those defined by the parent `Event` and `LocationEvent` classes. Attributes ---------- key : None or str The key(s) pressed. Could be *None*, a single c...
KeyEvent
python
davidhalter__jedi
jedi/inference/arguments.py
{ "start": 10289, "end": 12218 }
class ____(_AbstractArgumentsMixin): def __init__(self, arguments): self._wrapped_arguments = arguments @property def context(self): return self._wrapped_arguments.context @property def argument_node(self): return self._wrapped_arguments.argument_node @property def...
TreeArgumentsWrapper
python
sympy__sympy
sympy/geometry/polygon.py
{ "start": 968, "end": 45281 }
class ____(GeometrySet): """A two-dimensional polygon. A simple polygon in space. Can be constructed from a sequence of points or from a center, radius, number of sides and rotation angle. Parameters ========== vertices A sequence of points. n : int, optional If $> 0$, an...
Polygon
python
pypa__pip
src/pip/_vendor/distro/distro.py
{ "start": 21227, "end": 49430 }
class ____: """ Provides information about a OS distribution. This package creates a private module-global instance of this class with default initialization arguments, that is used by the `consolidated accessor functions`_ and `single source accessor functions`_. By using default initializatio...
LinuxDistribution
python
kamyu104__LeetCode-Solutions
Python/binary-tree-inorder-traversal.py
{ "start": 956, "end": 1510 }
class ____(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ result, stack = [], [(root, False)] while stack: root, is_visited = stack.pop() if root is None: continue if is_vis...
Solution2
python
airbytehq__airbyte
airbyte-integrations/bases/base-normalization/normalization/transform_catalog/table_name_registry.py
{ "start": 3632, "end": 18360 }
class ____: """ A registry object that records table names being used during the run This registry helps detecting naming conflicts/collisions and how to resolve them. First, we collect all schema/stream_name/json_path listed in the catalog to detect any collisions, whether it is from: - table na...
TableNameRegistry
python
huggingface__transformers
src/transformers/models/electra/modeling_electra.py
{ "start": 21407, "end": 22067 }
class ____(nn.Module): """Prediction module for the generator, made up of two dense layers.""" def __init__(self, config): super().__init__() self.activation = get_activation("gelu") self.LayerNorm = nn.LayerNorm(config.embedding_size, eps=config.layer_norm_eps) self.dense = nn...
ElectraGeneratorPredictions
python
getsentry__sentry
tests/sentry/integrations/jira_server/test_search.py
{ "start": 336, "end": 4572 }
class ____(APITestCase): @cached_property def integration(self): return get_integration(self.organization, self.user) @responses.activate def test_get_success_text_search(self) -> None: org = self.organization integration = self.integration responses.add( res...
JiraServerSearchEndpointTest
python
getsentry__sentry
src/sentry/integrations/cursor/webhooks/handler.py
{ "start": 1167, "end": 9385 }
class ____(Endpoint): owner = ApiOwner.ML_AI publish_status = { "POST": ApiPublishStatus.PRIVATE, } authentication_classes = () permission_classes = () @method_decorator(csrf_exempt) def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: if request.method...
CursorWebhookEndpoint
python
zarr-developers__zarr-python
src/zarr/storage/_wrapper.py
{ "start": 458, "end": 4505 }
class ____(Store, Generic[T_Store]): """ Store that wraps an existing Store. By default all of the store methods are delegated to the wrapped store instance, which is accessible via the ``._store`` attribute of this class. Use this class to modify or extend the behavior of the other store classes....
WrapperStore
python
redis__redis-py
redis/http/http_client.py
{ "start": 1693, "end": 15177 }
class ____: """ A lightweight HTTP client for REST API calls. """ def __init__( self, base_url: str = "", headers: Optional[Mapping[str, str]] = None, timeout: float = DEFAULT_TIMEOUT, retry: Retry = Retry( backoff=ExponentialWithJitterBackoff(base=1,...
HttpClient
python
readthedocs__readthedocs.org
readthedocs/redirects/exceptions.py
{ "start": 38, "end": 140 }
class ____(Exception): """Exception raised when a redirect loops forever."""
InfiniteRedirectException