language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
numpy__numpy
numpy/_core/tests/test_simd.py
{ "start": 12383, "end": 22559 }
class ____(_Test_Utility): """ To test all float vector types at once """ def test_arithmetic_fused(self): vdata_a, vdata_b, vdata_c = [self.load(self._data())] * 3 vdata_cx2 = self.add(vdata_c, vdata_c) # multiply and add, a*b + c data_fma = self.load([a * b + c for a, b...
_SIMD_FP
python
pytorch__pytorch
torch/testing/_internal/distributed/distributed_test.py
{ "start": 9824, "end": 10104 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.a = nn.Linear(10, 10, bias=False) self.b = nn.Linear(10, 1, bias=False) def forward(self, x): a = self.a(x) b = self.b(x) return (a, b)
TwoLinLayerNet
python
kamyu104__LeetCode-Solutions
Python/maximize-greatness-of-an-array.py
{ "start": 66, "end": 337 }
class ____(object): def maximizeGreatness(self, nums): """ :type nums: List[int] :rtype: int """ return len(nums)-max(collections.Counter(nums).itervalues()) # Time: O(nlogn) # Space: O(1) # sort, greedy, two pointers
Solution
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/configuration_sam3_tracker_video.py
{ "start": 1288, "end": 3411 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Sam3TrackerVideoPromptEncoder`]. The [`Sam3TrackerVideoPromptEncoder`] module is used to encode the input 2D points and bounding boxes. Configuration objects inherit from [`PreTrainedConfig`] and can be...
Sam3TrackerVideoPromptEncoderConfig
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/pool/base.py
{ "start": 21632, "end": 36554 }
class ____(ConnectionPoolEntry): """Maintains a position in a connection pool which references a pooled connection. This is an internal object used by the :class:`_pool.Pool` implementation to provide context management to a DBAPI connection maintained by that :class:`_pool.Pool`. The public faci...
_ConnectionRecord
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 20230, "end": 20359 }
class ____(torch.nn.Module): @classmethod def custom_add(cls, x): x = x + x return x
ComplicatedSuperParent
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/events.py
{ "start": 13479, "end": 16300 }
class ____( NamedTuple( "_AssetObservation", [ ("asset_key", PublicAttr[AssetKey]), ("description", PublicAttr[Optional[str]]), ("metadata", PublicAttr[Mapping[str, MetadataValue]]), ("partition", PublicAttr[Optional[str]]), ("tags", Public...
AssetObservation
python
PrefectHQ__prefect
src/prefect/server/schemas/schedules.py
{ "start": 1848, "end": 11182 }
class ____(PrefectBaseModel): """ A schedule formed by adding `interval` increments to an `anchor_date`. If no `anchor_date` is supplied, the current UTC time is used. If a timezone-naive datetime is provided for `anchor_date`, it is assumed to be in the schedule's timezone (or UTC). Even if suppli...
IntervalSchedule
python
getsentry__sentry
src/sentry/sentry_metrics/querying/visitors/base.py
{ "start": 1932, "end": 3226 }
class ____(ABC, Generic[TVisited]): """ Abstract visitor that defines a visiting behavior of a `QueryCondition`. """ def visit_group(self, condition_group: ConditionGroup) -> ConditionGroup: if not condition_group: return condition_group visited_conditions = [] for ...
QueryConditionVisitor
python
facebook__pyre-check
tools/incremental_test/specification.py
{ "start": 10456, "end": 11508 }
class ____(SingleUpdate): changes: Dict[str, str] removals: List[str] def update(self, environment: Environment, working_directory: Path) -> None: for handle, content in self.changes.items(): # Need to create parent directory if it doesn't exist parent_path = Path(handle).pa...
FileRepositoryUpdate
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 28507, "end": 28928 }
class ____(HTTPClientError): """ subclass of :class:`~HTTPClientError` This indicates that the server is refusing to service the request because the Request-URI is longer than the server is willing to interpret. code: 414, title: Request-URI Too Long """ code = 414 title = 'Reques...
HTTPRequestURITooLong
python
weaviate__weaviate-python-client
weaviate/gql/filter.py
{ "start": 1747, "end": 2426 }
class ____(ABC): """A base abstract class for all filters.""" def __init__(self, content: dict): """Initialize a Filter class instance. Args: content: The content of the `Filter` clause. """ if not isinstance(content, dict): raise TypeError( ...
Filter
python
tensorflow__tensorflow
third_party/xla/xla/python/xla_client.py
{ "start": 3728, "end": 5555 }
class ____: """Python representation of a xla.OpMetadata protobuf.""" __slots__ = ('op_type', 'op_name', 'source_file', 'source_line', 'source_end_line', 'source_column', 'source_end_column') def __init__(self, op_type='', op_name='', source_file='', source_line=0, source_end_line=...
OpMetadata
python
PrefectHQ__prefect
src/prefect/blocks/notifications.py
{ "start": 631, "end": 2482 }
class ____(NotificationBlock, ABC): """ An abstract class for sending notifications using Apprise. """ notify_type: Literal["info", "success", "warning", "failure"] = Field( default=PREFECT_NOTIFY_TYPE_DEFAULT, description="The type of notification being performed.", ) def __in...
AbstractAppriseNotificationBlock
python
keras-team__keras
keras/src/ops/image.py
{ "start": 2714, "end": 5272 }
class ____(Operation): def __init__(self, data_format=None, *, name=None): super().__init__(name=name) self.data_format = backend.standardize_data_format(data_format) def call(self, images): return backend.image.rgb_to_hsv(images, data_format=self.data_format) def compute_output_sp...
RGBToHSV
python
airbytehq__airbyte
airbyte-integrations/connectors/source-marketo/source_marketo/source.py
{ "start": 17074, "end": 18266 }
class ____(Oauth2Authenticator): def __init__(self, config): super().__init__( token_refresh_endpoint=f"{config['domain_url']}/identity/oauth/token", client_id=config["client_id"], client_secret=config["client_secret"], refresh_token=None, ) def g...
MarketoAuthenticator
python
PyCQA__pylint
tests/functional/e/e1101_9588_base_attr_aug_assign.py
{ "start": 355, "end": 682 }
class ____(BaseClass): "The first derived class which triggers the false positive" def __init__(self): "Augmented assignment triggers E1101." BaseClass.__init__(self) self.e1101 += 1 def countup(self): "Consequently this also triggers E1101." self.e1101 += 1
FalsePositiveClass
python
wandb__wandb
gpu_stats/hatch.py
{ "start": 124, "end": 2481 }
class ____(Exception): """Raised when building GPU stats service fails.""" def build_gpu_stats( cargo_binary: pathlib.Path, output_path: pathlib.Path, ) -> None: """Builds the `gpu_stats` Rust binary for monitoring NVIDIA and Apple ARM GPUs. NOTE: Cargo creates a cache under `./target/release` wh...
GpuStatsBuildError
python
pennersr__django-allauth
tests/apps/socialaccount/providers/feedly/tests.py
{ "start": 240, "end": 902 }
class ____(OAuth2TestsMixin, TestCase): provider_id = FeedlyProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """ { "id": "c805fcbf-3acf-4302-a97e-d82f9d7c897f", "email": "jim.smith@example.com", "givenName": "Jim", "familyName": "Smith", ...
FeedlyTests
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_inline_schemas/pipeline.py
{ "start": 978, "end": 3092 }
class ____(Step): """Check if the connector is a candidate to get inline schemas. Candidate conditions: - The connector is a Python connector. - The connector is a source connector. - The connector has a manifest file. - The connector has schemas directory. """ context: ConnectorContext...
CheckIsInlineCandidate
python
sqlalchemy__sqlalchemy
test/ext/test_associationproxy.py
{ "start": 112175, "end": 115727 }
class ____(fixtures.DeclarativeMappedTest): # test some GC scenarios, including issue #4268 @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class A(Base): __tablename__ = "a" id = Column(Integer, primary_key=True) data = Column(String(5...
ScopeBehaviorTest
python
python-excel__xlwt
xlwt/antlr.py
{ "start": 17477, "end": 19564 }
class ____(object): SKIP = -1 INVALID_TYPE = 0 EOF_TYPE = 1 EOF = 1 NULL_TREE_LOOKAHEAD = 3 MIN_USER_TYPE = 4 def __init__(self,**argv): try: self.type = argv['type'] except: self.type = INVALID_T...
Token
python
networkx__networkx
benchmarks/benchmarks/benchmark_harmonic_centrality.py
{ "start": 74, "end": 1180 }
class ____: timeout = 120 nodes = [10, 100, 1000] params = [f"wheel_graph({i})" for i in nodes] + [ f"directed_wheel({i})" for i in nodes ] param_names = ["graph"] def setup(self, graph): def directed_wheel(n): # bidirectional edges on the rim with directed edges to ...
HarmonicCentralityBenchmarks
python
scrapy__scrapy
scrapy/downloadermiddlewares/robotstxt.py
{ "start": 877, "end": 5147 }
class ____: DOWNLOAD_PRIORITY: int = 1000 def __init__(self, crawler: Crawler): if not crawler.settings.getbool("ROBOTSTXT_OBEY"): raise NotConfigured self._default_useragent: str = crawler.settings["USER_AGENT"] self._robotstxt_useragent: str | None = crawler.settings["ROBO...
RobotsTxtMiddleware
python
pandas-dev__pandas
pandas/tests/frame/test_alter_axes.py
{ "start": 114, "end": 887 }
class ____: # Tests for setting index/columns attributes directly (i.e. __setattr__) def test_set_axis_setattr_index(self): # GH 6785 # set the index manually df = DataFrame([{"ts": datetime(2014, 4, 1, tzinfo=timezone.utc), "foo": 1}]) expected = df.set_index("ts") df....
TestDataFrameAlterAxes
python
eventlet__eventlet
tests/wsgi_test.py
{ "start": 3980, "end": 4327 }
class ____(Site): def __call__(self, env, start_response): it = self.application(env, start_response) yield from it CONTENT_LENGTH = 'content-length' def recvall(sock): result = b'' while True: chunk = sock.recv(16 << 10) if chunk == b'': return result ...
IterableSite
python
spack__spack
lib/spack/spack/binary_distribution.py
{ "start": 96171, "end": 98993 }
class ____(IndexFetcher): """Fetcher for index.json, using separate index.json.hash as cache invalidation strategy""" def __init__(self, url, local_hash, urlopen=web_util.urlopen): self.url = url self.local_hash = local_hash self.urlopen = urlopen self.headers = {"User-Agent": w...
DefaultIndexFetcherV2
python
pandas-dev__pandas
pandas/tests/indexes/test_base.py
{ "start": 47749, "end": 54284 }
class ____: # Mostly the tests from common.py for which the results differ # in py2 and py3 because ints and strings are uncomparable in py3 # (GH 13514) @pytest.fixture def simple_index(self) -> Index: return Index([0, "a", 1, "b", 2, "c"]) def test_argsort(self, simple_index): ...
TestMixedIntIndex
python
ethereum__web3.py
tests/integration/go_ethereum/test_goethereum_http.py
{ "start": 5096, "end": 5177 }
class ____(GoEthereumAsyncNetModuleTest): pass
TestGoEthereumAsyncNetModuleTest
python
huggingface__transformers
src/transformers/models/dia/modeling_dia.py
{ "start": 11684, "end": 14783 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: Union[DiaEncoderConfig, DiaDecoderConfig], layer_idx: int, is_causal: bool = False): super().__init__() self.config = config self.layer_idx = layer_idx self.hidd...
DiaSelfAttention
python
Lightning-AI__lightning
tests/tests_pytorch/models/test_hooks.py
{ "start": 1145, "end": 7462 }
class ____(BoringDataModule): def __init__(self, called): super().__init__() def call(hook, fn, *args, **kwargs): out = fn(*args, **kwargs) d = {"name": hook} if args: d["args"] = args if kwargs: d["kwargs"] = kwargs ...
HookedDataModule
python
getsentry__sentry
src/sentry/buffer/inprocess.py
{ "start": 93, "end": 630 }
class ____(Buffer): """ In-process buffer which computes changes in real-time. **Note**: This does not actually buffer anything, and should only be used in development and testing environments. """ def incr( self, model: type[models.Model], columns: dict[str, ...
InProcessBuffer
python
dask__distributed
distributed/core.py
{ "start": 35366, "end": 40969 }
class ____: """Conveniently interact with a remote server >>> remote = rpc(address) # doctest: +SKIP >>> response = await remote.add(x=10, y=20) # doctest: +SKIP One rpc object can be reused for several interactions. Additionally, this object creates and destroys many comms as necessary and ...
rpc
python
huggingface__transformers
tests/models/textnet/test_modeling_textnet.py
{ "start": 11854, "end": 12132 }
class ____(BackboneTesterMixin, unittest.TestCase): all_model_classes = (TextNetBackbone,) if is_torch_available() else () config_class = TextNetConfig has_attentions = False def setUp(self): self.model_tester = TextNetModelTester(self)
TextNetBackboneTest
python
sqlalchemy__sqlalchemy
test/orm/test_deprecations.py
{ "start": 80270, "end": 81407 }
class ____(_fixtures.FixtureTest): run_inserts = None def test_bidirectional_no_load(self): users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_...
ManyToOneTest
python
tensorflow__tensorflow
tensorflow/python/distribute/tpu_strategy_compilation_test.py
{ "start": 1876, "end": 2839 }
class ____(test.TestCase): def test_functions_compile_same_signature(self): """Tests compiling different functions with the same signature.""" strategy = get_tpu_strategy() @def_function.function def return_one(): def computation(): return constant_op.constant(1) return strateg...
TPUStrategyCompilationTest
python
sphinx-doc__sphinx
doc/development/tutorials/examples/recipe.py
{ "start": 2635, "end": 3696 }
class ____(Index): """A custom index that creates an recipe matrix.""" name = 'recipe' localname = 'Recipe Index' shortname = 'Recipe' def generate(self, docnames=None): content = defaultdict(list) # sort the list of recipes in alphabetical order recipes = self.domain.get_...
RecipeIndex
python
ansible__ansible
test/lib/ansible_test/_internal/target.py
{ "start": 15524, "end": 16743 }
class ____(CompletionTarget): """Generic test target.""" def __init__( self, path: str, module_path: t.Optional[str], module_prefix: t.Optional[str], base_path: str, symlink: t.Optional[bool] = None, ) -> None: super().__init__() if symlink i...
TestTarget
python
getsentry__sentry
tests/sentry/issues/endpoints/test_group_details.py
{ "start": 29988, "end": 33114 }
class ____(APITestCase): def test_delete_deferred(self) -> None: self.login_as(user=self.user) group = self.create_group() hash = "x" * 32 GroupHash.objects.create(project=group.project, hash=hash, group=group) url = f"/api/0/issues/{group.id}/" response = self.cli...
GroupDeleteTest
python
python-poetry__poetry
src/poetry/console/commands/add.py
{ "start": 747, "end": 17061 }
class ____(InstallerCommand, InitCommand): name = "add" description = "Adds a new dependency to <comment>pyproject.toml</> and installs it." arguments: ClassVar[list[Argument]] = [ argument("name", "The packages to add.", multiple=True) ] options: ClassVar[list[Option]] = [ option( ...
AddCommand
python
getsentry__sentry
src/sentry/taskworker/app.py
{ "start": 213, "end": 315 }
class ____(Protocol): def add(self, key: str, value: str, timeout: int) -> bool: ...
AtMostOnceStore
python
Textualize__textual
tests/test_lazy.py
{ "start": 785, "end": 1606 }
class ____(App): def compose(self) -> ComposeResult: with Reveal(Vertical()): yield Label(id="foo") yield Label(id="bar") yield Label(id="baz") async def test_lazy_reveal(): app = RevealApp() async with app.run_test() as pilot: # No #foo on initial mount...
RevealApp
python
oauthlib__oauthlib
oauthlib/openid/connect/core/exceptions.py
{ "start": 359, "end": 408 }
class ____(OAuth2Error): pass
OpenIDClientError
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_trace_item_attributes.py
{ "start": 1636, "end": 12818 }
class ____( OrganizationTraceItemAttributesEndpointTestBase, OurLogTestCase ): feature_flags = {"organizations:ourlogs-enabled": True} item_type = SupportedTraceItemType.LOGS def test_no_feature(self) -> None: response = self.do_request(features={}) assert response.status_code == 404, r...
OrganizationTraceItemAttributesEndpointLogsTest
python
wandb__wandb
wandb/sdk/artifacts/_generated/fragments.py
{ "start": 4501, "end": 4653 }
class ____(GQLResult): typename__: Typename[Literal["File"]] = "File" name: str direct_url: str = Field(alias="directUrl")
FileWithUrlFragment
python
conda__conda
conda/plugins/types.py
{ "start": 8832, "end": 9023 }
class ____(CondaPlugin): """ Return type to use when defining conda health checks plugin hook. """ name: str action: Callable[[str, bool], None] @dataclass
CondaHealthCheck
python
huggingface__transformers
src/transformers/models/deit/modeling_deit.py
{ "start": 23721, "end": 26920 }
class ____(DeiTPreTrainedModel): def __init__(self, config: DeiTConfig) -> None: super().__init__(config) self.num_labels = config.num_labels self.deit = DeiTModel(config, add_pooling_layer=False) # Classifier head self.classifier = nn.Linear(config.hidden_size, config.num_...
DeiTForImageClassification
python
scipy__scipy
scipy/optimize/tests/test_optimize.py
{ "start": 3407, "end": 5357 }
class ____: """ Base test case for a simple constrained entropy maximization problem (the machine translation example of Berger et al in Computational Linguistics, vol 22, num 1, pp 39--72, 1996.) """ def setup_method(self): self.F = np.array([[1, 1, 1], [1, 1, 0]...
CheckOptimize
python
doocs__leetcode
solution/2500-2599/2563.Count the Number of Fair Pairs/Solution.py
{ "start": 0, "end": 325 }
class ____: def countFairPairs(self, nums: List[int], lower: int, upper: int) -> int: nums.sort() ans = 0 for i, x in enumerate(nums): j = bisect_left(nums, lower - x, lo=i + 1) k = bisect_left(nums, upper - x + 1, lo=i + 1) ans += k - j return ans...
Solution
python
kamyu104__LeetCode-Solutions
Python/bomb-enemy.py
{ "start": 38, "end": 1359 }
class ____(object): def maxKilledEnemies(self, grid): """ :type grid: List[List[str]] :rtype: int """ result = 0 if not grid or not grid[0]: return result down = [[0 for _ in xrange(len(grid[0]))] for _ in xrange(len(grid))] right = [[0 fo...
Solution
python
django__django
tests/auth_tests/models/invalid_models.py
{ "start": 100, "end": 619 }
class ____(AbstractBaseUser): """ A user with a non-unique username. This model is not invalid if it is used with a custom authentication backend which supports non-unique usernames. """ username = models.CharField(max_length=30) email = models.EmailField(blank=True) is_staff = models....
CustomUserNonUniqueUsername
python
python__mypy
mypyc/analysis/selfleaks.py
{ "start": 905, "end": 5836 }
class ____(OpVisitor[GenAndKill]): """Analyze whether 'self' may be seen by arbitrary code in '__init__'. More formally, the set is not empty if along some path from IR entry point arbitrary code could have been executed that has access to 'self'. (We don't consider access via 'gc.get_objects()'.) ...
SelfLeakedVisitor
python
django__django
tests/admin_changelist/models.py
{ "start": 1178, "end": 1355 }
class ____(models.Model): name = models.CharField(max_length=30) age = models.IntegerField(null=True, blank=True) def __str__(self): return self.name
Musician
python
geekcomputers__Python
JustDialScrapperGUI/Justdial Scrapper GUI.py
{ "start": 176, "end": 6531 }
class ____: def __init__(self, query, location, file_name, progressbar, label_progress): self.query = query self.location = location self.file_name = file_name self.progressbar = progressbar self.label_progress = label_progress @staticmethod def inner_html(element): ...
ScrapperLogic
python
kamyu104__LeetCode-Solutions
Python/summary-ranges.py
{ "start": 709, "end": 984 }
class ____(object): # @param {integer[]} nums # @return {string[]} def summaryRanges(self, nums): return [re.sub('->.*>', '->', '->'.join(repr(n) for _, n in g)) for _, g in itertools.groupby(enumerate(nums), lambda i_n: i_n[1]-i_n[0])]
Solution2
python
numba__numba
numba/tests/npyufunc/test_caching.py
{ "start": 224, "end": 2238 }
class ____(BaseCacheTest): """ Since the cache stats is not exposed by ufunc, we test by looking at the cache debug log. """ _numba_parallel_test_ = False here = os.path.dirname(__file__) usecases_file = os.path.join(here, "cache_usecases.py") modname = "ufunc_caching_test_fodder" ...
UfuncCacheTest
python
apache__airflow
task-sdk/src/airflow/sdk/api/datamodels/_generated.py
{ "start": 11955, "end": 12637 }
class ____(BaseModel): """ Schema for TaskInstance model with minimal required fields needed for Runtime. """ id: Annotated[UUID, Field(title="Id")] task_id: Annotated[str, Field(title="Task Id")] dag_id: Annotated[str, Field(title="Dag Id")] run_id: Annotated[str, Field(title="Run Id")] ...
TaskInstance
python
django-haystack__django-haystack
test_haystack/test_query.py
{ "start": 988, "end": 3464 }
class ____(TestCase): def test_split_expression(self): sq = SQ(foo="bar") self.assertEqual(sq.split_expression("foo"), ("foo", "content")) self.assertEqual(sq.split_expression("foo__exact"), ("foo", "exact")) self.assertEqual(sq.split_expression("foo__content"), ("foo", "content")) ...
SQTestCase
python
encode__starlette
starlette/middleware/authentication.py
{ "start": 379, "end": 1800 }
class ____: def __init__( self, app: ASGIApp, backend: AuthenticationBackend, on_error: Callable[[HTTPConnection, AuthenticationError], Response] | None = None, ) -> None: self.app = app self.backend = backend self.on_error: Callable[[HTTPConnection, Authe...
AuthenticationMiddleware
python
great-expectations__great_expectations
great_expectations/datasource/fluent/sql_datasource.py
{ "start": 35710, "end": 37000 }
class ____(_SQLAsset): """An asset made from a SQL query Args: query: The query to be used to construct the underlying Data Asset """ # Instance fields type: Literal["query"] = "query" query: str @pydantic.validator("query") def query_must_start_with_select(cls, v: str): ...
QueryAsset
python
google__pytype
pytype/rewrite/tests/test_basic.py
{ "start": 2709, "end": 3786 }
class ____(RewriteTest): """Import tests.""" def test_import(self): self.Check(""" import os assert_type(os.__name__, str) # attribute of the 'module' class assert_type(os.name, str) # attribute of the 'os' module """) def test_builtins(self): self.Check(""" assert_type(__b...
ImportsTest
python
apache__airflow
airflow-core/tests/unit/always/test_project_structure.py
{ "start": 1039, "end": 17111 }
class ____: def test_reference_to_providers_from_core(self): for filename in AIRFLOW_CORE_SOURCES_PATH.glob("example_dags/**/*.py"): self.assert_file_not_contains(filename, "providers") def test_deprecated_packages(self): for filename in AIRFLOW_CORE_SOURCES_PATH.glob("airflow/contr...
TestProjectStructure
python
getsentry__sentry
src/sentry/backup/mixins.py
{ "start": 226, "end": 2627 }
class ____: """ Handles the `ImportFlags.overwrite_configs` setting when it's piped through to a `RelocationScope.Config` model with at least one `unique=True` field, thereby handling the collision in the manner the importer requested. """ # TODO(getsentry/team-ospo#190): Clean up the type chec...
OverwritableConfigMixin
python
marshmallow-code__marshmallow
src/marshmallow/types.py
{ "start": 897, "end": 1161 }
class ____(typing.Protocol): def dumps( self, obj: typing.Any, *args: typing.Any, **kwargs: typing.Any ) -> str: ... def loads( self, s: str | bytes | bytearray, *args: typing.Any, **kwargs: typing.Any ) -> typing.Any: ...
RenderModule
python
sympy__sympy
sympy/polys/polyoptions.py
{ "start": 19473, "end": 19681 }
class ____(BooleanOption, Flag, metaclass=OptionType): """``series`` flag to polynomial manipulation functions. """ option = 'series' @classmethod def default(cls): return False
Series
python
getsentry__sentry
src/sentry/audit_log/events.py
{ "start": 6477, "end": 7979 }
class ____(AuditLogEvent): def __init__(self) -> None: super().__init__( event_id=178, name="PROJECT_PERFORMANCE_ISSUE_DETECTION_CHANGE", api_name="project.change-performance-issue-detection", ) def render(self, audit_log_entry: AuditLogEntry) -> str: ...
ProjectPerformanceDetectionSettingsAuditLogEvent
python
pytorch__pytorch
torch/_inductor/codegen/cpp.py
{ "start": 150918, "end": 182582 }
class ____(CppKernel): # Subclass CppKernel, CppVecKernel, etc., to customize code generation. # Override CppOverrides or CppVecOverrides to emit custom ops. # Earlier, this meant copying codegen_functions() to use your subclasses. # Now, use kernel_cls and vec_kernel_cls class attributes instead. #...
CppKernelProxy
python
ray-project__ray
rllib/utils/exploration/slate_soft_q.py
{ "start": 411, "end": 1509 }
class ____(SoftQ): @override(SoftQ) def get_exploration_action( self, action_distribution: ActionDistribution, timestep: Union[int, TensorType], explore: bool = True, ): assert ( self.framework == "torch" ), "ERROR: SlateSoftQ only supports torch s...
SlateSoftQ
python
pypa__warehouse
tests/unit/admin/views/test_flags.py
{ "start": 548, "end": 2761 }
class ____: @pytest.mark.parametrize( ("description", "enabled", "post", "expected_description", "expected_enabled"), [ ( # Nothing changed when enabled "old", True, {"id": "foo-bar", "description": "old", "enabled": "on"}, ...
TestEditFlag
python
numpy__numpy
numpy/polynomial/tests/test_polynomial.py
{ "start": 17363, "end": 22880 }
class ____: def test_polyfromroots(self): res = poly.polyfromroots([]) assert_almost_equal(trim(res), [1]) for i in range(1, 5): roots = np.cos(np.linspace(-np.pi, 0, 2 * i + 1)[1::2]) tgt = Tlist[i] res = poly.polyfromroots(roots) * 2**(i - 1) ...
TestMisc
python
mlflow__mlflow
mlflow/tracing/destination.py
{ "start": 3411, "end": 5060 }
class ____(TraceDestination): """ A destination representing a Databricks tracing server. By setting this destination in the :py:func:`mlflow.tracing.set_destination` function, MLflow will log traces to the specified experiment. If neither experiment_id nor experiment_name is specified, an active ...
Databricks
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/context/system.py
{ "start": 8002, "end": 9728 }
class ____(IPlanContext): """Context for the orchestration of a run. This context assumes inability to run user code directly. """ def __init__( self, plan_data: PlanData, log_manager: DagsterLogManager, executor: Executor, output_capture: Optional[dict[StepOutp...
PlanOrchestrationContext
python
huggingface__transformers
tests/models/deepseek_v2/test_modeling_deepseek_v2.py
{ "start": 7391, "end": 11288 }
class ____(unittest.TestCase): def test_deepseek_v2_lite(self): EXPECTED_TEXT = ['An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors.\n\nAttention functions are used in a variety of applications, incl...
DeepseekV2IntegrationTest
python
vyperlang__vyper
tests/functional/builtins/codegen/test_abi_decode_fuzz.py
{ "start": 8458, "end": 15485 }
class ____: nesting: int = 0 num_dynamic_types: int = 0 # number of dynamic types in the type breadth: int = 0 # e.g. int16[50] has higher breadth than int16[1] width: int = 0 # size of type def _type_stats(typ: VyperType) -> _TypeStats: def _finalize(): # little trick to save re-typing the ar...
_TypeStats
python
getsentry__sentry
src/sentry/feedback/endpoints/organization_feedback_categories.py
{ "start": 2511, "end": 14570 }
class ____(OrganizationEndpoint): owner = ApiOwner.FEEDBACK publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } permission_classes = (OrganizationUserReportsPermission,) def get(self, request: Request, organization: Organization) -> Response: """ Gets categories of fe...
OrganizationFeedbackCategoriesEndpoint
python
doocs__leetcode
solution/1400-1499/1411.Number of Ways to Paint N × 3 Grid/Solution2.py
{ "start": 0, "end": 985 }
class ____: def numOfWays(self, n: int) -> int: def f1(x: int) -> bool: last = -1 for _ in range(3): if x % 3 == last: return False last = x % 3 x //= 3 return True def f2(x: int, y: int) -> bool...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 937627, "end": 938387 }
class ____(sgqlc.types.relay.Connection): """A list of repository invitations.""" __schema__ = github_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("RepositoryInvitationEdge"), graphql_name="edges") """A list of edges.""" ...
RepositoryInvitationConnection
python
sympy__sympy
sympy/codegen/fnodes.py
{ "start": 18205, "end": 18265 }
class ____(FFunction): _required_standard = 95
F95Function
python
realpython__materials
python-with-statement/timer.py
{ "start": 39, "end": 343 }
class ____: def __enter__(self): self.start = perf_counter() def __exit__(self, *_): end = perf_counter() print(f"Elapsed time: {end - self.start:.4f} seconds") if __name__ == "__main__": with Timer(): # The code to measure goes here... sleep(0.5)
Timer
python
scrapy__scrapy
tests/test_spidermiddleware_referer.py
{ "start": 21884, "end": 22064 }
class ____(MixinStrictOrigin, TestRefererMiddleware): settings = { "REFERRER_POLICY": "scrapy.spidermiddlewares.referer.StrictOriginPolicy" }
TestSettingsStrictOrigin
python
pypa__pipenv
pipenv/exceptions.py
{ "start": 6106, "end": 6529 }
class ____(PipenvFileError): def __init__(self, filename="Pipfile.lock", extra=None, **kwargs): extra = kwargs.pop("extra", []) message = "{} {} {}".format( "[bold]You need to run[/bold]", "[bold red]$ pipenv lock[/bold red]", "[bold]before you can continue.[/bold...
LockfileNotFound
python
mlflow__mlflow
tests/dspy/test_dspy_autolog.py
{ "start": 10479, "end": 10739 }
class ____(dspy.Signature): """Answer questions with short factoid answers.""" context = dspy.InputField(desc="may contain relevant facts") question = dspy.InputField() answer = dspy.OutputField(desc="often between 1 and 5 words")
GenerateAnswer
python
sympy__sympy
sympy/liealgebras/type_c.py
{ "start": 77, "end": 4426 }
class ____(Standard_Cartan): def __new__(cls, n): if n < 3: raise ValueError("n cannot be less than 3") return Standard_Cartan.__new__(cls, "C", n) def dimension(self): """Dimension of the vector space V underlying the Lie algebra Examples ======== ...
TypeC
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/circular2.py
{ "start": 154, "end": 214 }
class ____: a_attr: object _T = TypeVar("_T", bound=A)
A
python
sympy__sympy
sympy/polys/monomials.py
{ "start": 11043, "end": 14876 }
class ____: """Code generator of fast monomial arithmetic functions. """ @cacheit def __new__(cls, ngens): obj = super().__new__(cls) obj.ngens = ngens return obj def __getnewargs__(self): return (self.ngens,) def _build(self, code, name): ns = {} e...
MonomialOps
python
kamyu104__LeetCode-Solutions
Python/number-of-increasing-paths-in-a-grid.py
{ "start": 1467, "end": 2281 }
class ____(object): def countPaths(self, grid): """ :type grid: List[List[int]] :rtype: int """ MOD = 10**9+7 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] def memoization(grid, i, j, lookup): if not lookup[i][j]: lookup[i][j] = 1...
Solution2
python
skorch-dev__skorch
skorch/probabilistic.py
{ "start": 27337, "end": 35005 }
class ____(ClassifierMixin, GPBase): __doc__ = get_gp_binary_clf_doc(NeuralNet.__doc__) def __init__( self, module, *args, likelihood=gpytorch.likelihoods.BernoulliLikelihood, criterion=gpytorch.mlls.VariationalELBO, train_split=ValidSplit...
GPBinaryClassifier
python
astropy__astropy
astropy/utils/masked/tests/test_functions.py
{ "start": 16650, "end": 16747 }
class ____(TestMaskedArrayConcatenation, LongitudeSetup): pass
TestMaskedLongitudeConcatenation
python
numba__numba
numba/core/datamodel/models.py
{ "start": 9449, "end": 9752 }
class ____(PrimitiveModel): """ Passed as opaque pointers """ _ptr_type = ir.IntType(8).as_pointer() def __init__(self, dmm, fe_type): be_type = self._ptr_type super(OpaqueModel, self).__init__(dmm, fe_type, be_type) @register_default(types.MemInfoPointer)
OpaqueModel
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/coercions.py
{ "start": 22903, "end": 26023 }
class ____(RoleImpl): __slots__ = () def _implicit_coercions( self, element: Any, resolved: Any, argname: Optional[str] = None, **kw: Any, ) -> Any: if resolved._is_from_clause: if ( isinstance(resolved, selectable.Alias) ...
InElementImpl
python
numpy__numpy
benchmarks/benchmarks/bench_ufunc.py
{ "start": 14899, "end": 15242 }
class ____(Benchmark): def setup(self): self.x = np.asarray(1.0) self.y = np.asarray(1.0 + 1j) self.z = complex(1.0, 1.0) def time_add_scalar(self): (self.x + self.x) def time_add_scalar_conv(self): (self.x + 1.0) def time_add_scalar_conv_complex(self): ...
Scalar
python
kamyu104__LeetCode-Solutions
Python/number-of-pairs-of-strings-with-concatenation-equal-to-target.py
{ "start": 130, "end": 832 }
class ____(object): def numOfPairs(self, nums, target): """ :type nums: List[str] :type target: str :rtype: int """ lookup = collections.Counter() result = 0 for num in nums: cnt1, cnt2 = lookup[-(len(target)-len(num))], lookup[len(target)-...
Solution
python
django__django
tests/backends/models.py
{ "start": 372, "end": 582 }
class ____(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __str__(self): return "%s %s" % (self.first_name, self.last_name)
Person
python
nedbat__coveragepy
tests/test_plugins.py
{ "start": 1853, "end": 5501 }
class ____(CoverageTest): """Test Plugins construction.""" def test_implicit_boolean(self) -> None: self.make_file( "plugin1.py", """\ from coverage import CoveragePlugin class Plugin(CoveragePlugin): pass def coverage_init(r...
LoadPluginsTest
python
huggingface__transformers
tests/models/parakeet/test_modeling_parakeet.py
{ "start": 5977, "end": 6759 }
class ____(ModelTesterMixin, unittest.TestCase): all_model_classes = (ParakeetEncoder,) if is_torch_available() else () test_resize_embeddings = False test_torch_exportable = True def setUp(self): self.model_tester = ParakeetEncoderModelTester(self) self.config_tester = ConfigTester(se...
ParakeetEncoderModelTest
python
jmcnamara__XlsxWriter
xlsxwriter/packager.py
{ "start": 1191, "end": 30490 }
class ____: """ A class for writing the Excel XLSX Packager file. This module is used in conjunction with XlsxWriter to create an Excel XLSX container file. From Wikipedia: The Open Packaging Conventions (OPC) is a container-file technology initially created by Microsoft to store a combina...
Packager
python
google__jax
jax/_src/pallas/mosaic/pipeline.py
{ "start": 44219, "end": 81973 }
class ____: """Sequences input and output copies and waits for a pipeline.""" def __init__( self, step: jax.Array, indices: tuple[int | jax.Array, ...], grid: tuple[int | jax.Array, ...], grid_offsets: tuple[int | jax.Array, ...], num_stages: int, first_cycle=None, l...
Scheduler
python
getsentry__sentry
src/sentry/notifications/api/endpoints/user_notification_email.py
{ "start": 623, "end": 2799 }
class ____(UserEndpoint): publish_status = { "GET": ApiPublishStatus.PRIVATE, "PUT": ApiPublishStatus.PRIVATE, } owner = ApiOwner.ALERTS_NOTIFICATIONS def get(self, request: Request, user) -> Response: """ Fetches the user's email notification settings. Returns a...
UserNotificationEmailEndpoint
python
huggingface__transformers
src/transformers/models/glm4/modeling_glm4.py
{ "start": 15847, "end": 16383 }
class ____(PreTrainedModel): config: Glm4Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Glm4DecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True ...
Glm4PreTrainedModel
python
doocs__leetcode
solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution.py
{ "start": 0, "end": 203 }
class ____: def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]: nums.sort() s = list(accumulate(nums)) return [bisect_right(s, q) for q in queries]
Solution