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 | PyCQA__pylint | tests/functional/r/regression/regression_3535_double_enum_inherit.py | {
"start": 114,
"end": 144
} | class ____(enum.Enum):
pass
| A |
python | mlflow__mlflow | mlflow/store/artifact/mlflow_artifacts_repo.py | {
"start": 1906,
"end": 3678
} | class ____(HttpArtifactRepository):
"""Scheme wrapper around HttpArtifactRepository for mlflow-artifacts server functionality"""
def __init__(
self, artifact_uri: str, tracking_uri: str | None = None, registry_uri: str | None = None
) -> None:
effective_tracking_uri = tracking_uri or get_tr... | MlflowArtifactsRepository |
python | huggingface__transformers | src/transformers/models/internvl/modeling_internvl.py | {
"start": 9113,
"end": 13064
} | class ____(nn.Module):
"""
Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
"""
def __init__(self, config: InternVLVisionConfig) -> None:
super().__init__()
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
if config.u... | InternVLVisionEmbeddings |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 987629,
"end": 988494
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"action",
"previous_sponsors_tier",
"sponsor",
"sponsorable",
"sponsors_tier",
"timestamp",
)
action = sgqlc.types.Field... | SponsorsActivity |
python | apache__airflow | providers/google/tests/unit/google/suite/transfers/test_local_to_drive.py | {
"start": 1121,
"end": 2361
} | class ____:
@mock.patch("airflow.providers.google.suite.transfers.local_to_drive.GoogleDriveHook")
def test_execute(self, mock_hook):
context = {}
mock_hook.return_value.upload_file.return_value = REMOTE_FILE_IDS
op = LocalFilesystemToGoogleDriveOperator(
task_id="test_task",... | TestLocalFilesystemToGoogleDriveOperator |
python | numba__numba | numba/cuda/cudadrv/driver.py | {
"start": 80556,
"end": 81144
} | class ____(Module):
def get_function(self, name):
handle = drvapi.cu_function()
driver.cuModuleGetFunction(byref(handle), self.handle,
name.encode('utf8'))
return CtypesFunction(weakref.proxy(self), handle, name)
def get_global_symbol(self, name):
... | CtypesModule |
python | mlflow__mlflow | mlflow/types/chat.py | {
"start": 4196,
"end": 4364
} | class ____(BaseModel):
name: str
description: str | None = None
parameters: FunctionParams | None = None
strict: bool | None = None
| FunctionToolDefinition |
python | sphinx-doc__sphinx | sphinx/builders/linkcheck.py | {
"start": 11952,
"end": 12082
} | class ____(NamedTuple):
uri: str
docname: str
lineno: int
status: _Status
message: str
code: int
| CheckResult |
python | milvus-io__pymilvus | pymilvus/client/types.py | {
"start": 7627,
"end": 9187
} | class ____:
def __init__(self, compaction_id: int, state: int) -> None:
self.compaction_id = compaction_id
self.state = State.new(state)
self.plans = []
def __repr__(self) -> str:
return f"""
Compaction Plans:
- compaction id: {self.compaction_id}
- state: {self.state}
- plan... | CompactionPlans |
python | keras-team__keras | keras/src/backend/tensorflow/core.py | {
"start": 21802,
"end": 22852
} | class ____(base_name_scope):
def __init__(self, name, **kwargs):
super().__init__(name, **kwargs)
self._tf_name_scope = tf.name_scope(name)
def __enter__(self):
name_scope_stack = global_state.get_global_attribute(
"name_scope_stack", default=[], set_to_default=True
... | name_scope |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_dialect.py | {
"start": 29277,
"end": 30103
} | class ____(fixtures.TestBase):
__only_on__ = "postgresql"
def test_error_code(self, metadata, connection):
t = Table("t", metadata, Column("id", Integer, primary_key=True))
t.create(connection)
errmsg = assert_raises(
exc.IntegrityError,
connection.execute,
... | PGCodeTest |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_any.py | {
"start": 16152,
"end": 28919
} | class ____(Enum):
a = 1
b = 'b'
def test_enum(any_serializer):
assert any_serializer.to_python(MyEnum.a) == MyEnum.a
assert any_serializer.to_python(MyEnum.b) == MyEnum.b
assert any_serializer.to_python({MyEnum.a: 42}) == {MyEnum.a: 42}
assert any_serializer.to_python({MyEnum.b: 42}) == {MyEnu... | MyEnum |
python | huggingface__transformers | src/transformers/models/clipseg/modeling_clipseg.py | {
"start": 15419,
"end": 16096
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
... | CLIPSegMLP |
python | graphql-python__graphene | graphene/types/tests/test_definition.py | {
"start": 1147,
"end": 1214
} | class ____(Union):
class Meta:
types = (Article,)
| MyUnion |
python | ray-project__ray | python/ray/tests/ludwig/ludwig_test_utils.py | {
"start": 1878,
"end": 18651
} | class ____(LocalBackend):
@property
def supports_multiprocessing(self):
return False
def parse_flag_from_env(key, default=False):
try:
value = os.environ[key]
except KeyError:
# KEY isn't set, default to `default`.
_value = default
else:
# KEY is set, conver... | LocalTestBackend |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/ecr.py | {
"start": 1450,
"end": 2115
} | class ____:
"""Helper (frozen dataclass) for storing temporary ECR credentials."""
username: str
password: str
proxy_endpoint: str
expires_at: datetime
def __post_init__(self):
"""Initialize the `Ecr` credentials object."""
mask_secret(self.password)
logger.debug("Crede... | EcrCredentials |
python | dagster-io__dagster | python_modules/libraries/dagster-powerbi/dagster_powerbi/components/power_bi_workspace/component.py | {
"start": 5567,
"end": 6089
} | class ____(Resolvable):
credentials: Annotated[
Union[PowerBIToken, PowerBIServicePrincipal],
Resolver(
resolve_powerbi_credentials,
model_field_type=PowerBICredentialsModel,
),
]
workspace_id: str
def _resolve_powerbi_workspace(context: ResolutionContext, m... | PowerBIWorkspaceModel |
python | astropy__astropy | astropy/table/tests/test_item_access.py | {
"start": 275,
"end": 346
} | class ____:
pass
@pytest.mark.usefixtures("table_data")
| BaseTestItems |
python | openai__openai-python | src/openai/types/beta/threads/image_file_content_block.py | {
"start": 233,
"end": 363
} | class ____(BaseModel):
image_file: ImageFile
type: Literal["image_file"]
"""Always `image_file`."""
| ImageFileContentBlock |
python | facebookresearch__faiss | tests/test_index_composite.py | {
"start": 10469,
"end": 11908
} | class ____(unittest.TestCase):
def test_chain(self):
# generate data
d = 4
nt = 1000
nb = 200
nq = 200
# normal distribition
x = faiss.randn((nt + nb + nq) * d, 1234).reshape(nt + nb + nq, d)
# make distribution very skewed
x *= [10, 4, 1, ... | TestTransformChain |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 266637,
"end": 267907
} | class ____(StatNode):
"""Definition of a C property, backed by a CFuncDefNode getter.
"""
# name string
# doc EncodedString or None Doc string of the property
# entry Symtab.Entry The Entry of the property attribute
# body StatListNode[CFuncDefNode] (for comp... | CPropertyNode |
python | huggingface__transformers | tests/models/seamless_m4t/test_tokenization_seamless_m4t.py | {
"start": 1470,
"end": 12141
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "facebook/hf-seamless-m4t-medium"
tokenizer_class = SeamlessM4TTokenizer
test_rust_tokenizer = True
integration_expected_tokens = ['▁This', '▁is', '▁a', '▁test', '▁', '😊', '▁I', '▁was', '▁born', '▁in', '▁9', '2000', ',', '▁and',... | SeamlessM4TTokenizationTest |
python | py-pdf__pypdf | pypdf/constants.py | {
"start": 110,
"end": 244
} | class ____(str, Enum): # Once we are on Python 3.11+: enum.StrEnum
def __str__(self) -> str:
return str(self.value)
| StrEnum |
python | aio-libs__aiohttp | aiohttp/web_runner.py | {
"start": 4250,
"end": 5113
} | class ____(BaseSite):
__slots__ = ("_path",)
def __init__(self, runner: "BaseRunner[Any]", path: str) -> None:
loop = asyncio.get_event_loop()
if not isinstance(
loop, asyncio.ProactorEventLoop # type: ignore[attr-defined]
):
raise RuntimeError(
... | NamedPipeSite |
python | pytorch__pytorch | torch/_dynamo/convert_frame.py | {
"start": 19023,
"end": 29113
} | class ____:
def __init__(
self,
compiler_fn: CompilerFn,
one_graph: bool = True,
export: bool = False,
export_constraints: Optional[typing.Never] = None,
package: Optional[CompilePackage] = None,
) -> None:
# assert export_constraints is None
reset... | ConvertFrameAssert |
python | numba__numba | numba/core/typeinfer.py | {
"start": 1060,
"end": 4259
} | class ____(object):
def __init__(self, context, var):
self.context = context
self.var = var
self.type = None
self.locked = False
# Stores source location of first definition
self.define_loc = None
# Qualifiers
self.literal_value = NOTSET
def add_t... | TypeVar |
python | tensorflow__tensorflow | tensorflow/tools/compatibility/tf_upgrade_v2.py | {
"start": 1866,
"end": 2185
} | class ____(ast_edits.APIAnalysisSpec):
def __init__(self):
self.symbols_to_detect = {}
self.imports_to_detect = {
("tensorflow", None): UnaliasedTFImport(),
("tensorflow.compat.v1", "tf"): compat_v1_import,
("tensorflow.compat.v2", "tf"): compat_v2_import,
}
| TFAPIImportAnalysisSpec |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/vision.py | {
"start": 30691,
"end": 34260
} | class ____(GoogleCloudBaseOperator):
"""
Permanently delete a product and its reference images.
Metadata of the product and all its images will be deleted right away, but
search queries against ProductSets containing the product may still work
until all related caches are refreshed.
Possible e... | CloudVisionDeleteProductOperator |
python | walkccc__LeetCode | solutions/3086. Minimum Moves to Pick K Ones/3086.py | {
"start": 0,
"end": 1876
} | class ____:
def minimumMoves(self, nums: list[int], k: int, maxChanges: int) -> int:
# Dylan has two actions for collecting '1's in a sequence:
# Action 1: Put a '1' next to him and pick it up.
# The cost is 2.
# Action 2: Swap a '1' towards him and collect it.
# The cost equal... | Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/serialization/serialized_data.py | {
"start": 3229,
"end": 3963
} | class ____(NamedTuple):
id: int
uri: str
extra: Mapping[str, Any]
created_at: str
updated_at: str
consuming_dags: Sequence[DatasetConsumingDag]
producing_tasks: Sequence[DatasetProducingTask]
def is_produced_by_task(self, *, task_id: str, dag_id: str) -> bool:
return any(
... | Dataset |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 2412,
"end": 2495
} | class ____(Evaluation):
assignee = models.CharField(max_length=50)
| QualityControl |
python | matplotlib__matplotlib | lib/matplotlib/tri/_trirefine.py | {
"start": 191,
"end": 1527
} | class ____:
"""
Abstract base class for classes implementing mesh refinement.
A TriRefiner encapsulates a Triangulation object and provides tools for
mesh refinement and interpolation.
Derived classes must implement:
- ``refine_triangulation(return_tri_index=False, **kwargs)`` , where
t... | TriRefiner |
python | pallets__jinja | tests/test_api.py | {
"start": 699,
"end": 5570
} | class ____:
def test_item_and_attribute(self, env):
from jinja2.sandbox import SandboxedEnvironment
for env in Environment(), SandboxedEnvironment():
tmpl = env.from_string("{{ foo.items()|list }}")
assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"
tmpl ... | TestExtendedAPI |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 99832,
"end": 100989
} | class ____:
def test_format_timeframe(self):
assert self.locale._format_timeframe("now", 0) == "dál"
assert self.locale._format_timeframe("second", 1) == "sekunda"
assert self.locale._format_timeframe("seconds", 3) == "3 sekundda"
assert self.locale._format_timeframe("minute", 1) == ... | TestSamiLocale |
python | sphinx-doc__sphinx | sphinx/util/_files.py | {
"start": 1912,
"end": 3152
} | class ____(dict[Path, tuple[set[str], _StrPath]]): # NoQA: FURB189
"""A special dictionary for download files.
.. important:: This class would be refactored in nearly future.
Hence don't hack this directly.
"""
def add_file(self, docname: str, filename: str | os.PathLike[str]) -> _... | DownloadFiles |
python | getsentry__sentry | tests/sentry/seer/fetch_issues/test_utils.py | {
"start": 401,
"end": 3007
} | class ____(TestCase):
def test_get_repo_and_projects_success(self):
repo = self.create_repo(
project=self.project,
name="getsentry/sentry",
provider="integrations:github",
external_id="123",
)
self.create_code_mapping(project=self.project, repo... | TestGetRepoAndProjects |
python | pydata__xarray | xarray/core/indexing.py | {
"start": 19604,
"end": 20176
} | class ____:
"""Mixin to mark support for Indexer subclasses in indexing."""
__slots__ = ()
def __array__(
self, dtype: DTypeLike | None = None, /, *, copy: bool | None = None
) -> np.ndarray:
# Leave casting to an array up to the underlying array type.
if Version(np.__version__... | ExplicitlyIndexed |
python | huggingface__transformers | src/transformers/models/big_bird/modeling_big_bird.py | {
"start": 70036,
"end": 70754
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
pooler_output (`torch.FloatTensor` of shape `(batch_size, 1)`):
pooler output fr... | BigBirdForQuestionAnsweringModelOutput |
python | readthedocs__readthedocs.org | readthedocs/proxito/views/serve.py | {
"start": 2270,
"end": 3709
} | class ____(CDNCacheControlMixin, ServeRedirectMixin, ServeDocsMixin, View):
"""
Page redirect view.
This allows users to redirec to the default version of a project.
For example:
- /page/api/index.html -> /en/latest/api/index.html
- /projects/subproject/page/index.html -> /projects/subproject/... | ServePageRedirect |
python | facebook__pyre-check | tools/generate_taint_models/get_dynamic_graphql_sources.py | {
"start": 679,
"end": 1211
} | class ____():
def __init__(self, template_str: str) -> None:
if not template_str or '{gql_type_name}' not in template_str or '{gql_field}' not in template_str:
raise ModelGenerationException("Template string must be provided and contain '{gql_type_name}' and '{gql_field}'")
self.template... | DynamicGraphQLFormattableSpecification |
python | sanic-org__sanic | sanic/server/protocols/websocket_protocol.py | {
"start": 802,
"end": 8335
} | class ____(HttpProtocol):
__slots__ = (
"websocket",
"websocket_timeout",
"websocket_max_size",
"websocket_ping_interval",
"websocket_ping_timeout",
"websocket_url",
"websocket_peer",
)
def __init__(
self,
*args,
websocket_time... | WebSocketProtocol |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs.py | {
"start": 1135,
"end": 1542
} | class ____:
hidden_mutable_default: list[int] = default_function()
another_dataclass: A = A()
not_optimal: ImmutableType = ImmutableType(20)
good_variant: ImmutableType = DEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES
okay_variant: A = DEFAULT_A_FOR_ALL_DATACLASSES
fine_dataclass_function: list[int]... | B |
python | pypa__warehouse | tests/unit/manage/test_views.py | {
"start": 228963,
"end": 235832
} | class ____:
def test_get(self, db_request, user_service):
project = ProjectFactory.create()
release = ReleaseFactory.create(project=project)
file_ = FileFactory.create(release=release)
# NOTE: intentionally out of order, to test sorting.
events = [
FileEventFactor... | TestManageProjectHistory |
python | apache__airflow | providers/http/tests/unit/http/sensors/test_http.py | {
"start": 10004,
"end": 12286
} | class ____:
@mock.patch("airflow.providers.http.hooks.http.Session", FakeSession)
def test_get(self):
op = HttpOperator(
task_id="get_op",
method="GET",
endpoint="/search",
data={"client": "ubuntu", "q": "airflow"},
headers={},
)
... | TestHttpOpSensor |
python | django__django | tests/migrations2/test_migrations_2_first/0001_initial.py | {
"start": 43,
"end": 572
} | class ____(migrations.Migration):
dependencies = [
("migrations", "__first__"),
]
operations = [
migrations.CreateModel(
"OtherAuthor",
[
("id", models.AutoField(primary_key=True)),
("name", models.CharField(max_length=255)),
... | Migration |
python | django-extensions__django-extensions | django_extensions/db/fields/json.py | {
"start": 985,
"end": 3144
} | class ____(models.TextField):
"""
JSONField is a generic textfield that neatly serializes/unserializes
JSON objects seamlessly. Main thingy must be a dict object.
"""
def __init__(self, *args, **kwargs):
kwargs["default"] = kwargs.get("default", dict)
models.TextField.__init__(self... | JSONField |
python | falconry__falcon | examples/recipes/raw_url_path_wsgi.py | {
"start": 34,
"end": 317
} | class ____:
def process_request(self, req, resp):
raw_uri = req.env.get('RAW_URI') or req.env.get('REQUEST_URI')
# NOTE: Reconstruct the percent-encoded path from the raw URI.
if raw_uri:
req.path, _, _ = raw_uri.partition('?')
| RawPathComponent |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 20117,
"end": 20538
} | class ____(sgqlc.types.Enum):
"""The possible values for the members can make purchases setting.
Enumeration Choices:
* `DISABLED`: The setting is disabled for organizations in the
enterprise.
* `ENABLED`: The setting is enabled for organizations in the
enterprise.
"""
__schema__ ... | EnterpriseMembersCanMakePurchasesSettingValue |
python | PrefectHQ__prefect | tests/events/server/storage/test_database.py | {
"start": 2190,
"end": 5970
} | class ____:
async def test_write_event(self, session: AsyncSession, event: ReceivedEvent):
# Write the event
async with session as session:
await write_events(session=session, events=[event])
await session.commit()
# Read it back
async with session as session... | TestWriteEvents |
python | psf__requests | src/requests/auth.py | {
"start": 2045,
"end": 2220
} | class ____:
"""Base class that all auth implementations derive from"""
def __call__(self, r):
raise NotImplementedError("Auth hooks must be callable.")
| AuthBase |
python | nedbat__coveragepy | tests/test_bytecode.py | {
"start": 408,
"end": 1493
} | class ____(CoverageTest):
"""Tests for bytecode.py"""
def test_code_objects(self) -> None:
code = compile(
dedent("""\
def f(x):
def g(y):
return {z for z in range(10)}
def j():
return [z... | BytecodeTest |
python | huggingface__transformers | src/transformers/models/led/configuration_led.py | {
"start": 853,
"end": 7437
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`LEDModel`]. It is used to instantiate an LED
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuratio... | LEDConfig |
python | kamyu104__LeetCode-Solutions | Python/convert-sorted-array-to-binary-search-tree.py | {
"start": 1467,
"end": 2001
} | class ____(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
self.iterator = iter(nums)
return self.helper(0, len(nums))
def helper(self, start, end):
if start == end:
return None
mi... | Solution2 |
python | dask__dask | dask/tests/test_tokenize.py | {
"start": 26377,
"end": 26431
} | class ____:
a: int
@dataclasses.dataclass
| ADataClass |
python | joke2k__faker | faker/providers/phone_number/tw_GH/__init__.py | {
"start": 49,
"end": 578
} | class ____(PhoneNumberProvider):
formats = (
"+23327#######",
"+23357#######",
"+23355#######",
"+23324#######",
"+23354#######",
"+23320#######",
"+23350#######",
"+23326#######",
"+23356#######",
"+23328#######",
"024#######",... | Provider |
python | scrapy__scrapy | tests/test_squeues_request.py | {
"start": 3848,
"end": 4115
} | class ____(TestRequestQueueBase):
is_fifo = True
@pytest.fixture
def q(self, crawler, tmp_path):
return MarshalFifoDiskQueue.from_crawler(
crawler=crawler, key=str(tmp_path / "marshal" / "fifo")
)
| TestMarshalFifoDiskQueueRequest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassConverter2.py | {
"start": 406,
"end": 1383
} | class ____(ModelBase):
asymmetric: int = model_field(converter=converter_simple)
symmetric: str | int = model_field(converter=converter_passThru)
dc1 = DC1("1", 1)
reveal_type(dc1.asymmetric, expected_text="int")
dc1.asymmetric = "2"
reveal_type(
dc1.asymmetric, expected_text="int"
) # Asymmetric -- typ... | DC1 |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_eks.py | {
"start": 8119,
"end": 52690
} | class ____:
def test_hook(self, cluster_builder) -> None:
eks_hook, _ = cluster_builder()
assert eks_hook.get_conn() is not None
assert eks_hook.aws_conn_id == DEFAULT_CONN_ID
assert eks_hook.region_name == REGION
###
# This specific test does not use the fixture since
#... | TestEksHooks |
python | huggingface__transformers | src/transformers/models/mobilenet_v2/image_processing_mobilenet_v2.py | {
"start": 1524,
"end": 2026
} | class ____(ImagesKwargs, total=False):
"""
do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):
Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0
is used for background, and background itself is not included in all class... | MobileNetV2ImageProcessorKwargs |
python | wandb__wandb | wandb/vendor/pygments/lexers/parsers.py | {
"start": 10765,
"end": 11216
} | class ____(DelegatingLexer):
"""
A lexer for `Ragel`_ in a Java host file.
.. versionadded:: 1.1
"""
name = 'Ragel in Java Host'
aliases = ['ragel-java']
filenames = ['*.rl']
def __init__(self, **options):
super(RagelJavaLexer, self).__init__(JavaLexer, RagelEmbeddedLexer,
... | RagelJavaLexer |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/ops/snapshot.py | {
"start": 1192,
"end": 12308
} | class ____(dataset_ops.UnaryUnchangedStructureDataset):
"""A Dataset that captures a snapshot or reads from a snapshot."""
def __init__(self,
input_dataset,
path,
compression=None,
reader_path_prefix=None,
writer_path_prefix=None,
... | _LegacySnapshotDataset |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py | {
"start": 3885,
"end": 4098
} | class ____:
def m[S](self: S, other: S) -> S:
x: S = other
return x
@classmethod
def n[S](cls: type[S], other: S) -> S:
x: type[S] = type(other)
return x()
| MethodsWithBody |
python | fastai__fastai | fastai/vision/core.py | {
"start": 5678,
"end": 6034
} | class ____(Transform):
"Add the code metadata to a `TensorMask`"
def __init__(self, codes=None):
self.codes = codes
if codes is not None: self.vocab,self.c = codes,len(codes)
def decodes(self, o:TensorMask):
if self.codes is not None: o.codes=self.codes
return o
# %% ../../... | AddMaskCodes |
python | pallets__flask | src/flask/config.py | {
"start": 257,
"end": 1094
} | class ____(t.Generic[T]):
"""Makes an attribute forward to the config"""
def __init__(
self, name: str, get_converter: t.Callable[[t.Any], T] | None = None
) -> None:
self.__name__ = name
self.get_converter = get_converter
@t.overload
def __get__(self, obj: None, owner: Non... | ConfigAttribute |
python | streamlit__streamlit | lib/streamlit/errors.py | {
"start": 17491,
"end": 17968
} | class ____(LocalizableStreamlitException):
"""Exception raised when data provided to a bidirectional component cannot be serialized."""
def __init__(self) -> None:
super().__init__(
"The `data` provided to the bidirectional component could not be serialized. "
"Please ensure the... | BidiComponentUnserializableDataError |
python | plotly__plotly.py | plotly/graph_objs/pie/marker/_pattern.py | {
"start": 233,
"end": 15270
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "pie.marker"
_path_str = "pie.marker.pattern"
_valid_props = {
"bgcolor",
"bgcolorsrc",
"fgcolor",
"fgcolorsrc",
"fgopacity",
"fillmode",
"path",
"pathsrc",
"shape",
"shape... | Pattern |
python | vyperlang__vyper | vyper/venom/basicblock.py | {
"start": 2420,
"end": 2874
} | class ____:
"""
IRDebugInfo represents debug information in IR, used to annotate IR
instructions with source code information when printing IR.
"""
line_no: int
src: str
def __init__(self, line_no: int, src: str) -> None:
self.line_no = line_no
self.src = src
def __rep... | IRDebugInfo |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1501788,
"end": 1503787
} | class ____(sgqlc.types.Type, Node):
"""Represents a commit status."""
__schema__ = github_schema
__field_names__ = ("combined_contexts", "commit", "context", "contexts", "state")
combined_contexts = sgqlc.types.Field(
sgqlc.types.non_null(StatusCheckRollupContextConnection),
graphql_nam... | Status |
python | django__django | tests/decorators/test_csrf.py | {
"start": 2330,
"end": 4040
} | class ____(CsrfTestMixin, SimpleTestCase):
def test_wrapped_sync_function_is_not_coroutine_function(self):
def sync_view(request):
return HttpResponse()
wrapped_view = requires_csrf_token(sync_view)
self.assertIs(iscoroutinefunction(wrapped_view), False)
def test_wrapped_as... | RequiresCsrfTokenTests |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/prefect_dbt/cli/configs/base.py | {
"start": 13502,
"end": 13796
} | class ____(ImportError):
def __init__(self, service, *args, **kwargs):
msg = (
f"To use {service.title()}TargetConfigs, "
f'execute `pip install "prefect-dbt[{service.lower()}]"`'
)
super().__init__(msg, *args, **kwargs)
| MissingExtrasRequireError |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 42396,
"end": 42851
} | class ____:
def __init__(self, value=None):
self.value = value
def __hash__(self):
return hash(self.value)
def __eq__(self, other):
if isinstance(other, EqOverride):
return self.value == other.value
else:
return False
def __ne__(self, other):
... | HashEqOverride |
python | huggingface__transformers | examples/metrics-monitoring/metrics_example.py | {
"start": 139,
"end": 1551
} | class ____:
def __init__(self, name):
# The attach_tracer decorator has already created self.tracer for us
self.name = name
@traced # This method will use the tracer from the class instance
def process_data(self, data):
# This method is traced and can use self.tracer
return... | ExampleClass |
python | pytorch__pytorch | torch/distributed/_symmetric_memory/__init__.py | {
"start": 18782,
"end": 57158
} | class ____(Enum):
UNSCALED = "unscaled"
TENSOR_WISE = "tensor-wise"
ROW_WISE_SHARDED = "row-wise-sharded"
ROW_WISE_REPLICATED = "row-wise-replicated"
def _check_and_verify_fp8_all_gather_scale_mode(
shard: torch.Tensor, scale: torch.Tensor | None, gather_dim: int, group_size: int
) -> _ScaleMode:
... | _ScaleMode |
python | dask__dask | dask/dataframe/tseries/resample.py | {
"start": 6040,
"end": 6096
} | class ____(ResampleReduction):
how = "min"
| ResampleMin |
python | google__jax | tests/pallas/tpu_pallas_random_test.py | {
"start": 8891,
"end": 10341
} | class ____(parameterized.TestCase):
def setUp(self):
if not jtu.test_device_matches(["tpu"]):
self.skipTest("Need TPU devices")
super().setUp()
def test_block_invariance(self):
def make_kernel_body(index_map):
def body(key_ref, o_ref):
key = key_ref[...]
samples = pltpu.sa... | BlockInvarianceTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/weixin/provider.py | {
"start": 483,
"end": 930
} | class ____(OAuth2Provider):
id = "weixin"
name = "Weixin"
account_class = WeixinAccount
oauth2_adapter_class = WeixinOAuth2Adapter
def extract_uid(self, data):
return data["openid"]
def get_default_scope(self):
return ["snsapi_login"]
def extract_common_fields(self, data):... | WeixinProvider |
python | doocs__leetcode | solution/1700-1799/1792.Maximum Average Pass Ratio/Solution.py | {
"start": 0,
"end": 410
} | class ____:
def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float:
h = [(a / b - (a + 1) / (b + 1), a, b) for a, b in classes]
heapify(h)
for _ in range(extraStudents):
_, a, b = heappop(h)
a, b = a + 1, b + 1
heappush(h, (a / b ... | Solution |
python | milvus-io__pymilvus | pymilvus/client/types.py | {
"start": 4468,
"end": 4817
} | class ____(IntEnum):
INVALID = 0
L2 = 1
IP = 2
# Only supported for byte vectors
HAMMING = 3
JACCARD = 4
TANIMOTO = 5
SUBSTRUCTURE = 6
SUPERSTRUCTURE = 7
def __repr__(self) -> str:
return f"<{self.__class__.__name__}: {self._name_}>"
def __str__(self) -> str:
... | MetricType |
python | django__django | django/db/models/fields/json.py | {
"start": 23345,
"end": 23465
} | class ____(
CaseInsensitiveMixin, KeyTransformTextLookupMixin, lookups.IStartsWith
):
pass
| KeyTransformIStartsWith |
python | paramiko__paramiko | paramiko/pkey.py | {
"start": 2741,
"end": 3106
} | class ____(Exception):
"""
An unknown public/private key algorithm was attempted to be read.
"""
def __init__(self, key_type=None, key_bytes=None):
self.key_type = key_type
self.key_bytes = key_bytes
def __str__(self):
return f"UnknownKeyType(type={self.key_type!r}, bytes=<... | UnknownKeyType |
python | ray-project__ray | doc/source/ray-core/doc_code/actors.py | {
"start": 529,
"end": 768
} | class ____:
# Disable task events reporting for this method.
@ray.method(enable_task_events=False)
def foo(self):
pass
foo_actor = FooActor.remote()
ray.get(foo_actor.foo.remote())
# __enable_task_events_end__
| FooActor |
python | kubernetes-client__python | kubernetes/client/models/v1_deployment_status.py | {
"start": 383,
"end": 13231
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1DeploymentStatus |
python | huggingface__transformers | src/transformers/models/longt5/modeling_longt5.py | {
"start": 81429,
"end": 89911
} | class ____(LongT5PreTrainedModel, GenerationMixin):
_keys_to_ignore_on_load_unexpected = [
r"decoder.block.0.layer.1.EncDecAttention.relative_attention_bias.weight",
]
_tied_weights_keys = {
"encoder.embed_tokens.weight": "shared.weight",
"decoder.embed_tokens.weight": "shared.weight... | LongT5ForConditionalGeneration |
python | huggingface__transformers | src/transformers/models/esm/configuration_esm.py | {
"start": 2574,
"end": 5469
} | class ____:
num_blocks: int = 48
sequence_state_dim: int = 1024
pairwise_state_dim: int = 128
sequence_head_width: int = 32
pairwise_head_width: int = 32
position_bins: int = 32
dropout: float = 0
layer_drop: float = 0
cpu_grad_checkpoint: bool = False
max_recycles: int = 4
c... | TrunkConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-iterable/source_iterable/streams.py | {
"start": 9874,
"end": 12687
} | class ____(IterableExportStream, ABC):
"""
For streams that could produce large amount of data in single request so we
cant just use IterableExportStreamRanged to split it in even ranges. If
request processing takes a lot of time API server could just close
connection and connector code would fail w... | IterableExportStreamAdjustableRange |
python | getsentry__sentry | src/sentry/monitors/types.py | {
"start": 1086,
"end": 2793
} | class ____:
"""
Represents a check-in to be processed
"""
ts: datetime
"""
The timestamp the check-in was produced into the kafka topic. This differs
from the start_time that is part of the CheckIn
"""
partition: int
"""
The kafka partition id the check-in was produced into... | CheckinItem |
python | huggingface__transformers | src/transformers/models/dia/modeling_dia.py | {
"start": 19542,
"end": 21918
} | class ____(DiaPreTrainedModel):
def __init__(self, config: DiaEncoderConfig):
super().__init__(config)
self.config = config
self.embedding = nn.Embedding(config.vocab_size, config.hidden_size)
self.layers = nn.ModuleList(
[DiaEncoderLayer(config, layer_idx) for layer_idx... | DiaEncoder |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_pubsub.py | {
"start": 24127,
"end": 25714
} | class ____:
@pytest.fixture
def hook(self):
return PubSubAsyncHook()
@pytest.mark.asyncio
@mock.patch("airflow.providers.google.cloud.hooks.pubsub.PubSubAsyncHook._get_subscriber_client")
async def test_pull(self, mock_subscriber_client, hook):
client = mock_subscriber_client.return... | TestPubSubAsyncHook |
python | django__django | tests/gis_tests/layermap/tests.py | {
"start": 17460,
"end": 18055
} | class ____:
def db_for_read(self, model, **hints):
return "other"
def db_for_write(self, model, **hints):
return self.db_for_read(model, **hints)
def allow_relation(self, obj1, obj2, **hints):
# ContentType objects are created during a post-migrate signal while
# performing... | OtherRouter |
python | readthedocs__readthedocs.org | readthedocs/api/v3/views.py | {
"start": 12910,
"end": 14356
} | class ____(
APIv3Settings,
NestedViewSetMixin,
ProjectQuerySetMixin,
FlexFieldsMixin,
UpdateMixin,
UpdateModelMixin,
ReadOnlyModelViewSet,
):
model = Version
lookup_field = "slug"
lookup_url_kwarg = "version_slug"
# Allow ``.`` (dots) on version slug
lookup_value_regex =... | VersionsViewSet |
python | spack__spack | lib/spack/spack/test/installer_tui.py | {
"start": 31498,
"end": 35582
} | class ____:
"""Test search mode with display filtering"""
def test_search_mode_filters_displayed_builds(self):
"""Test that search mode actually filters what's displayed"""
status, _, fake_stdout = create_build_status(total=4)
specs = [
MockSpec("package-foo", "1.0"),
... | TestSearchFilteringIntegration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 686572,
"end": 687054
} | class ____(sgqlc.types.Type):
"""Represents the language of a repository."""
__schema__ = github_schema
__field_names__ = ("cursor", "node", "size")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field(sgqlc.types.non_null("Language"), graphql_na... | LanguageEdge |
python | langchain-ai__langchain | libs/core/tests/unit_tests/runnables/test_runnable.py | {
"start": 6205,
"end": 6420
} | class ____(Runnable[str, int]):
@override
def invoke(
self,
input: str,
config: RunnableConfig | None = None,
**kwargs: Any,
) -> int:
return len(input)
| FakeRunnable |
python | pandas-dev__pandas | pandas/tests/io/test_common.py | {
"start": 941,
"end": 14404
} | class ____:
data1 = """index,A,B,C,D
foo,2,3,4,5
bar,7,8,9,10
baz,12,13,14,15
qux,12,13,14,15
foo2,12,13,14,15
bar2,12,13,14,15
"""
def test_expand_user(self):
filename = "~/sometest"
expanded_name = icom._expand_user(filename)
assert expanded_name != filename
assert os.path.is... | TestCommonIOCapabilities |
python | getsentry__sentry | src/sentry/interfaces/security.py | {
"start": 3849,
"end": 5640
} | class ____(SecurityReport):
"""
A CSP violation report.
See also: https://www.w3.org/TR/CSP/#violation-events
>>> {
>>> "document_uri": "http://example.com/",
>>> "violated_directive": "style-src cdn.example.com",
>>> "blocked_uri": "http://example.com/style.css",
>>> "... | Csp |
python | Textualize__textual | tests/test_widget_mount_point.py | {
"start": 97,
"end": 1295
} | class ____(Widget):
pass
async def test_find_dom_spot():
# Build up a "fake" DOM for an application.
screen = Widget(name="Screen")
header = Widget(name="Header", id="header")
body = Body(id="body")
content = [Content(id=f"item{n}") for n in range(1000)]
body._add_children(*content)
fo... | Body |
python | huggingface__transformers | src/transformers/models/flava/modeling_flava.py | {
"start": 18668,
"end": 20081
} | class ____(nn.Module):
"""
Image to Patch Embedding.
"""
def __init__(
self,
image_size: int = 224,
patch_size: Union[int, tuple[int, int]] = 16,
num_channels: int = 3,
embed_dim: int = 768,
):
super().__init__()
if not isinstance(image_size, ... | PatchEmbeddings |
python | redis__redis-py | tests/test_asyncio/test_pubsub.py | {
"start": 12170,
"end": 17354
} | class ____:
def setup_method(self, method):
self.message = None
def message_handler(self, message):
self.message = message
async def async_message_handler(self, message):
self.async_message = message
async def test_published_message_to_channel(self, r: redis.Redis, pubsub):
... | TestPubSubMessages |
python | encode__django-rest-framework | tests/test_fields.py | {
"start": 58415,
"end": 61021
} | class ____(FieldValues):
"""
Valid and invalid values for `DurationField`.
"""
valid_inputs = {
'13': datetime.timedelta(seconds=13),
'3 08:32:01.000123': datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123),
'08:01': datetime.timedelta(minutes=8, seconds=... | TestDurationField |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin_ini/plugin_fail.py | {
"start": 5427,
"end": 5702
} | class ____(BaseModel, validate_by_name=True):
x: str = Field(..., alias=x_alias)
z: int
KwargsDynamicAliasModel(y='y', z=1)
# MYPY: error: Missing named argument "x" for "KwargsDynamicAliasModel" [call-arg]
KwargsDynamicAliasModel(x='y', z=1)
| KwargsDynamicAliasModel |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.