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 | django__django | tests/queries/models.py | {
"start": 13598,
"end": 13742
} | class ____(models.Model):
programs = models.ManyToManyField(Program)
identifier = models.OneToOneField(Identifier, models.CASCADE)
| Channel |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1216702,
"end": 1216936
} | class ____(VegaLiteSchema):
"""
Spec schema wrapper.
Any specification in Vega-Lite.
"""
_schema = {"$ref": "#/definitions/Spec"}
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
| Spec |
python | pandas-dev__pandas | pandas/tests/arrays/interval/test_interval.py | {
"start": 893,
"end": 1682
} | class ____:
@pytest.mark.parametrize(
"left, right",
[
(0, 1),
(Timedelta("0 days"), Timedelta("1 day")),
(Timestamp("2018-01-01"), Timestamp("2018-01-02")),
(
Timestamp("2018-01-01", tz="US/Eastern"),
Timestamp("2018-01... | TestAttributes |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 15463,
"end": 15696
} | class ____(BaseModel):
"""
Extra Links Response.
"""
extra_links: Annotated[dict[str, str | None], Field(title="Extra Links")]
total_entries: Annotated[int, Field(title="Total Entries")]
| ExtraLinkCollectionResponse |
python | pytorch__pytorch | torch/testing/_internal/autograd_function_db.py | {
"start": 12903,
"end": 13346
} | class ____(torch.autograd.Function):
generate_vmap_rule = True
scale = 3.14
@staticmethod
def forward(x):
return x.clone()
@staticmethod
def setup_context(ctx, inputs, outputs):
pass
@staticmethod
def backward(ctx, grad_output):
return grad_output * ScaleGradGe... | ScaleGradGenVmap |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 11232,
"end": 11592
} | class ____(Stmt):
"""A macro definition. `name` is the name of the macro, `args` a list of
arguments and `defaults` a list of defaults if there are any. `body` is
a list of nodes for the macro body.
"""
fields = ("name", "args", "defaults", "body")
name: str
args: list["Name"]
default... | Macro |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1381845,
"end": 1385515
} | class ____(sgqlc.types.Type, Node):
"""A threaded list of comments for a given pull request."""
__schema__ = github_schema
__field_names__ = (
"comments",
"diff_side",
"is_collapsed",
"is_outdated",
"is_resolved",
"line",
"pull_request",
"repo... | PullRequestThread |
python | apache__airflow | providers/google/tests/unit/google/cloud/links/test_dataplex.py | {
"start": 7474,
"end": 8647
} | class ____:
@pytest.mark.db_test
def test_get_link(self, create_task_instance_of_operator, session, mock_supervisor_comms):
expected_url = EXPECTED_DATAPLEX_CATALOG_ENTRY_GROUP_LINK
link = DataplexCatalogEntryGroupLink()
ti = create_task_instance_of_operator(
DataplexCatalogG... | TestDataplexCatalogEntryGroupLink |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_vision.py | {
"start": 3377,
"end": 7515
} | class ____(nn.Module):
"""
Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
"""
def __init__(self, config: Data2VecVisionConfig) -> None:
super().__init__()
self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
if config.u... | Data2VecVisionEmbeddings |
python | scrapy__scrapy | tests/test_spidermiddleware_process_start.py | {
"start": 784,
"end": 1011
} | class ____:
async def process_start(self, start):
await maybe_deferred_to_future(twisted_sleep(SLEEP_SECONDS))
async for item_or_request in start:
yield item_or_request
| TwistedSleepSpiderMiddleware |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/twitter_oauth2/tests.py | {
"start": 264,
"end": 990
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = TwitterOAuth2Provider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""{
"data": {
"created_at": "2020-09-02T13:39:14.000Z",
"id": "13011526523... | TwitterOAuth2Tests |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 71133,
"end": 71303
} | class ____:
xlPivotTableReport = 1 # from enum XlImportDataAs
xlQueryTable = 0 # from enum XlImportDataAs
xlTable = 2 # from enum XlImportDataAs
| ImportDataAs |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_results.py | {
"start": 676,
"end": 3601
} | class ____(fixtures.TablesTest):
__backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"plain_pk",
metadata,
Column("id", Integer, primary_key=True),
Column("data", String(50)),
)
Table(
"has_dates",
... | RowFetchTest |
python | mlflow__mlflow | examples/pytorch/MNIST/mnist_autolog_example.py | {
"start": 2670,
"end": 7375
} | class ____(L.LightningModule):
def __init__(self, learning_rate=0.01):
"""
Initializes the network
"""
super().__init__()
# mnist images are (1, 28, 28) (channels, width, height)
self.optimizer = None
self.scheduler = None
self.layer_1 = torch.nn.Line... | LightningMNISTClassifier |
python | numpy__numpy | numpy/distutils/armccompiler.py | {
"start": 81,
"end": 962
} | class ____(UnixCCompiler):
"""
Arm compiler.
"""
compiler_type = 'arm'
cc_exe = 'armclang'
cxx_exe = 'armclang++'
def __init__(self, verbose=0, dry_run=0, force=0):
UnixCCompiler.__init__(self, verbose, dry_run, force)
cc_compiler = self.cc_exe
cxx_compiler = self.... | ArmCCompiler |
python | dagster-io__dagster | python_modules/libraries/dagster-wandb/dagster_wandb/utils/errors.py | {
"start": 0,
"end": 2744
} | class ____(Exception):
"""Represents an execution error of the W&B Artifacts IO Manager."""
def __init__(self, message="A W&B Artifacts IO Manager error occurred."):
self.message = message
super().__init__(self.message)
SUPPORTED_READ_CONFIG_KEYS = [
"alias",
"get_path",
"get",
... | WandbArtifactsIOManagerError |
python | huggingface__transformers | src/transformers/models/auto/tokenization_auto.py | {
"start": 48634,
"end": 63261
} | class ____:
r"""
This is a generic tokenizer class that will be instantiated as one of the tokenizer classes of the library when
created with the [`AutoTokenizer.from_pretrained`] class method.
This class cannot be instantiated directly using `__init__()` (throws an error).
"""
def __init__(se... | AutoTokenizer |
python | scipy__scipy | benchmarks/benchmarks/sparse_linalg_onenormest.py | {
"start": 286,
"end": 1998
} | class ____(Benchmark):
params = [
[2, 3, 5, 10, 30, 100, 300, 500, 1000, 1e4, 1e5, 1e6],
['exact', 'onenormest']
]
param_names = ['n', 'solver']
def setup(self, n, solver):
rng = np.random.default_rng(1234)
nrepeats = 100
shape = (int(n), int(n))
if solv... | BenchmarkOneNormEst |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overload5.py | {
"start": 804,
"end": 871
} | class ____(Protocol):
def method2(self, x: Any) -> Any: ...
| BBase |
python | getsentry__sentry | src/sentry/integrations/vsts/repository.py | {
"start": 591,
"end": 5322
} | class ____(IntegrationRepositoryProvider):
name = "Azure DevOps"
repo_provider = IntegrationProviderSlug.AZURE_DEVOPS.value
def get_repository_data(
self, organization: Organization, config: MutableMapping[str, Any]
) -> Mapping[str, str]:
from sentry.integrations.vsts.integration impor... | VstsRepositoryProvider |
python | PyCQA__pylint | doc/data/messages/r/redefined-slots-in-subclass/bad.py | {
"start": 41,
"end": 123
} | class ____(Base):
__slots__ = ("a", "d") # [redefined-slots-in-subclass]
| Subclass |
python | coleifer__peewee | tests/keys.py | {
"start": 1923,
"end": 2781
} | class ____(ModelTestCase):
requires = [Package, PackageItem]
def setUp(self):
super(TestForeignKeyToNonPrimaryKey, self).setUp()
for barcode in ['101', '102']:
Package.create(barcode=barcode)
for i in range(2):
PackageItem.create(
pac... | TestForeignKeyToNonPrimaryKey |
python | facebook__pyre-check | client/commands/infer.py | {
"start": 15769,
"end": 21976
} | class ____:
qualifier: str
path: str
options: StubGenerationOptions
globals_: List[GlobalAnnotation] = dataclasses.field(default_factory=list)
attributes: List[AttributeAnnotation] = dataclasses.field(default_factory=list)
functions: List[FunctionAnnotation] = dataclasses.field(default_factory=l... | ModuleAnnotations |
python | huggingface__transformers | src/transformers/models/deepseek_vl_hybrid/configuration_deepseek_vl_hybrid.py | {
"start": 1386,
"end": 5217
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DeepseekVLHybridModel`]. It is used to instantiate a
DeepseekVLHybrid model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yie... | DeepseekVLHybridConfig |
python | huggingface__transformers | src/transformers/models/mra/modeling_mra.py | {
"start": 31916,
"end": 32306
} | class ____(PreTrainedModel):
config: MraConfig
base_model_prefix = "mra"
supports_gradient_checkpointing = True
@torch.no_grad()
def _init_weights(self, module: nn.Module):
"""Initialize the weights"""
super()._init_weights(module)
if isinstance(module, MraLMPredictionHead):... | MraPreTrainedModel |
python | walkccc__LeetCode | solutions/2212. Maximum Points in an Archery Competition/2212.py | {
"start": 0,
"end": 951
} | class ____:
def maximumBobPoints(
self,
numArrows: int,
aliceArrows: list[int],
) -> list[int]:
FULL_MASK = (1 << 12) - 1
maxPoint = 0
maxMask = 0
def getShotableAndPoint(mask: int, leftArrows: int) -> tuple[bool, int]:
point = 0
for i in range(12):
if mask >> ... | Solution |
python | pandas-dev__pandas | asv_bench/benchmarks/rolling.py | {
"start": 11149,
"end": 11628
} | class ____:
params = ["single", "table"]
param_names = ["method"]
def setup(self, method):
self.df = pd.DataFrame(np.random.randn(10, 1000))
def time_apply(self, method):
self.df.rolling(2, method=method).apply(
table_method_func, raw=True, engine="numba"
)
def... | TableMethod |
python | numba__numba | numba/np/ufunc/decorators.py | {
"start": 252,
"end": 838
} | class ____(object):
@classmethod
def get_identity(cls, kwargs):
return kwargs.pop('identity', None)
@classmethod
def get_cache(cls, kwargs):
return kwargs.pop('cache', False)
@classmethod
def get_writable_args(cls, kwargs):
return kwargs.pop('writable_args', ())
@... | _BaseVectorize |
python | conda__conda | conda/plugins/types.py | {
"start": 17383,
"end": 18766
} | class ____(CondaPlugin):
"""
**EXPERIMENTAL**
Return type to use when defining a conda environment exporter plugin hook supporting a single platform.
:param name: name of the exporter (e.g., ``environment-yaml``)
:param aliases: user-friendly format aliases (e.g., ("yaml",))
:param default_fil... | CondaEnvironmentExporter |
python | sqlalchemy__sqlalchemy | test/orm/test_recursive_loaders.py | {
"start": 1356,
"end": 2080
} | class ____:
@classmethod
def define_tables(cls, metadata):
Table(
"nodes",
metadata,
Column("id", Integer, primary_key=True),
Column("parent_id", Integer, ForeignKey("nodes.id")),
Column("data", String(30)),
)
@classmethod
def ... | _NodeTest |
python | great-expectations__great_expectations | tests/datasource/fluent/test_spark_google_cloud_storage_datasource.py | {
"start": 848,
"end": 9000
} | class ____:
# noinspection PyMethodMayBeStatic,PyUnusedLocal
def list_blobs(
self,
bucket_or_name,
max_results=None,
prefix=None,
delimiter=None,
**kwargs,
) -> Iterator:
return iter([])
def _build_spark_gcs_datasource(
gcs_options: Dict[str, Any... | MockGCSClient |
python | huggingface__transformers | src/transformers/models/layoutlmv2/image_processing_layoutlmv2_fast.py | {
"start": 1299,
"end": 4579
} | class ____(BaseImageProcessorFast):
resample = PILImageResampling.BILINEAR
size = {"height": 224, "width": 224}
rescale_factor = None
do_resize = True
apply_ocr = True
ocr_lang = None
tesseract_config = ""
valid_kwargs = LayoutLMv2ImageProcessorKwargs
def __init__(self, **kwargs: Un... | LayoutLMv2ImageProcessorFast |
python | walkccc__LeetCode | solutions/746. Min Cost Climbing Stairs/746.py | {
"start": 0,
"end": 197
} | class ____:
def minCostClimbingStairs(self, cost: list[int]) -> int:
cost.append(0)
for i in range(2, len(cost)):
cost[i] += min(cost[i - 1], cost[i - 2])
return cost[-1]
| Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/chat_ui/events.py | {
"start": 247,
"end": 311
} | class ____(Event):
nodes: List[NodeWithScore]
| SourceNodesEvent |
python | walkccc__LeetCode | solutions/812. Largest Triangle Area/812.py | {
"start": 0,
"end": 314
} | class ____:
def largestTriangleArea(self, points: list[list[int]]) -> float:
ans = 0
for Ax, Ay in points:
for Bx, By in points:
for Cx, Cy in points:
ans = max(ans, 0.5 * abs((Bx - Ax) * (Cy - Ay) -
(Cx - Ax) * (By - Ay)))
return ans
| Solution |
python | apache__airflow | providers/fab/tests/unit/fab/auth_manager/api_endpoints/test_role_and_permission_endpoint.py | {
"start": 15300,
"end": 22518
} | class ____(TestRoleEndpoint):
@pytest.mark.parametrize(
("payload", "expected_name", "expected_actions"),
[
({"name": "mytest"}, "mytest", []),
(
{
"name": "mytest2",
"actions": [{"resource": {"name": "Connections"}, "ac... | TestPatchRole |
python | giampaolo__psutil | psutil/test/memleak.py | {
"start": 4890,
"end": 11141
} | class ____(unittest.TestCase):
# Number of times to call the tested function in each iteration.
times = 200
# Maximum number of retries if memory growth is detected.
retries = 5
# Number of warm-up calls before measurements begin.
warmup_times = 10
# Allowed memory difference (in bytes) befo... | MemoryLeakTestCase |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_bash_code_execution_output_block_param.py | {
"start": 237,
"end": 392
} | class ____(TypedDict, total=False):
file_id: Required[str]
type: Required[Literal["bash_code_execution_output"]]
| BetaBashCodeExecutionOutputBlockParam |
python | matplotlib__matplotlib | lib/matplotlib/_type1font.py | {
"start": 3714,
"end": 7832
} | class ____(_Token):
kind = 'number'
def is_number(self):
return True
def value(self):
if '.' not in self.raw:
return int(self.raw)
else:
return float(self.raw)
def _tokenize(data: bytes, skip_ws: bool) -> T.Generator[_Token, int, None]:
"""
A gener... | _NumberToken |
python | huggingface__transformers | src/transformers/models/timesformer/modeling_timesformer.py | {
"start": 20405,
"end": 25586
} | class ____(TimesformerPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.embeddings = TimesformerEmbeddings(config)
self.encoder = TimesformerEncoder(config)
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_nor... | TimesformerModel |
python | langchain-ai__langchain | libs/langchain/langchain_classic/chains/router/base.py | {
"start": 414,
"end": 544
} | class ____(NamedTuple):
"""A route to a destination chain."""
destination: str | None
next_inputs: dict[str, Any]
| Route |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_web_search_tool_20250305_param.py | {
"start": 861,
"end": 2117
} | class ____(TypedDict, total=False):
name: Required[Literal["web_search"]]
"""Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
"""
type: Required[Literal["web_search_20250305"]]
allowed_callers: List[Literal["direct", "code_execution_20250825"]]
... | BetaWebSearchTool20250305Param |
python | altair-viz__altair | altair/vegalite/v6/api.py | {
"start": 148040,
"end": 160344
} | class ____(
TopLevelMixin, _EncodingMixin, mixins.MarkMethodMixin, core.TopLevelUnitSpec
):
"""
Create a basic Altair/Vega-Lite chart.
Although it is possible to set all Chart properties as constructor attributes,
it is more idiomatic to use methods such as ``mark_point()``, ``encode()``,
``tra... | Chart |
python | django__django | tests/decorators/test_clickjacking.py | {
"start": 2654,
"end": 4567
} | class ____(SimpleTestCase):
def test_wrapped_sync_function_is_not_coroutine_function(self):
def sync_view(request):
return HttpResponse()
wrapped_view = xframe_options_exempt(sync_view)
self.assertIs(iscoroutinefunction(wrapped_view), False)
def test_wrapped_async_function_... | XFrameOptionsExemptTests |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 370565,
"end": 377148
} | class ____(DatumChannelMixin, core.DatumDef):
"""
Longitude2Datum schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to `... | Longitude2Datum |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/sagemaker.py | {
"start": 18288,
"end": 20567
} | class ____(SageMakerBaseOperator):
"""
Creates an endpoint configuration that Amazon SageMaker hosting services uses to deploy models.
In the configuration, you identify one or more models, created using the CreateModel API, to deploy and
the resources that you want Amazon SageMaker to provision.
... | SageMakerEndpointConfigOperator |
python | python-markdown__markdown | markdown/extensions/legacy_em.py | {
"start": 1294,
"end": 1693
} | class ____(Extension):
""" Add legacy_em extension to Markdown class."""
def extendMarkdown(self, md):
""" Modify inline patterns. """
md.inlinePatterns.register(LegacyUnderscoreProcessor(r'_'), 'em_strong2', 50)
def makeExtension(**kwargs): # pragma: no cover
""" Return an instance of t... | LegacyEmExtension |
python | numpy__numpy | numpy/_core/tests/test_multiarray.py | {
"start": 388795,
"end": 389422
} | class ____:
@pytest.mark.parametrize("cls", [np.datetime64, np.timedelta64])
def test_dt_tuple(self, cls):
# two valid uses - (unit, num) and (unit, num, den, None)
cls(1, ('ms', 2))
cls(1, ('ms', 2, 1, None))
# trying to use the event argument, removed in 1.7.0
# it use... | TestDateTimeCreationTuple |
python | lazyprogrammer__machine_learning_examples | ann_class2/theano_ann.py | {
"start": 630,
"end": 1087
} | class ____(object):
def __init__(self, M1, M2, f):
self.M1 = M1
self.M2 = M2
self.f = f
W = init_weight(M1, M2)
b = np.zeros(M2)
self.W = theano.shared(W)
self.b = theano.shared(b)
self.params = [self.W, self.b]
def forward(self, X):
if se... | HiddenLayer |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/pretty_grid_gutter_interaction.py | {
"start": 247,
"end": 320
} | class ____(Grid):
"""A simple grid with 2 columns and 2 rows."""
| MyGrid |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 10099,
"end": 10157
} | class ____(_RolesPermission):
pass
| RolesPermissionOutput |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/inventory.py | {
"start": 2856,
"end": 5901
} | class ____(dict):
"""Inventory of collected and rendered objects."""
def __init__(self, items: list[InventoryItem] | None = None, project: str = "project", version: str = "0.0.0"):
"""Initialize the object.
Arguments:
items: A list of items.
project: The project name.
... | Inventory |
python | ansible__ansible | test/lib/ansible_test/_internal/containers.py | {
"start": 1674,
"end": 10541
} | class ____:
"""Enum representing the types of hosts involved in running tests."""
origin = 'origin'
control = 'control'
managed = 'managed'
def run_support_container(
args: EnvironmentConfig,
context: str,
image: str,
name: str,
ports: list[int],
aliases: t.Optional[list[str]]... | HostType |
python | realpython__materials | python-maze-solver/source_code_step_3/src/maze_solver/view/primitives.py | {
"start": 1129,
"end": 1287
} | class ____(tuple[Line, ...]):
def draw(self, **attributes) -> str:
return "".join(line.draw(**attributes) for line in self)
@dataclass
| DisjointLines |
python | boto__boto3 | boto3/s3/transfer.py | {
"start": 18581,
"end": 18998
} | class ____(BaseSubscriber):
"""A back-compat wrapper to invoke a provided callback via a subscriber
:param callback: A callable that takes a single positional argument for
how many bytes were transferred.
"""
def __init__(self, callback):
self._callback = callback
def on_progress(... | ProgressCallbackInvoker |
python | astropy__astropy | astropy/io/ascii/core.py | {
"start": 7193,
"end": 7383
} | class ____:
"""
Superclass for ``StrType`` and ``NumType`` classes.
This class is the default type of ``Column`` and provides a base
class for other data types.
"""
| NoType |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-instructor/llama_index/embeddings/instructor/base.py | {
"start": 468,
"end": 3383
} | class ____(BaseEmbedding):
query_instruction: Optional[str] = Field(
description="Instruction to prepend to query text."
)
text_instruction: Optional[str] = Field(
description="Instruction to prepend to text."
)
cache_folder: Optional[str] = Field(
description="Cache folder f... | InstructorEmbedding |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 260990,
"end": 261662
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(
sgqlc.types.list_of("CreatedIssueContributionEdge"), graphql_name="edges"
)
no... | CreatedIssueContributionConnection |
python | kubernetes-client__python | kubernetes/client/api/networking_v1_api.py | {
"start": 543,
"end": 564884
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | NetworkingV1Api |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc.py | {
"start": 122875,
"end": 125862
} | class ____(GoogleCloudBaseOperator):
"""
Delete the batch workload resource.
:param batch_id: Required. The ID to use for the batch, which will become the final component
of the batch's resource name.
This value must be 4-63 characters. Valid characters are /[a-z][0-9]-/.
:param region:... | DataprocDeleteBatchOperator |
python | huggingface__transformers | src/transformers/models/mlcd/modular_mlcd.py | {
"start": 18725,
"end": 20174
} | class ____(CLIPVisionModel):
@check_model_inputs(tie_last_hidden_states=False)
@auto_docstring
def forward(
self,
pixel_values: Optional[torch.FloatTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, BaseModelOutputWithPooling]:
r"""
Example:
... | MLCDVisionModel |
python | gevent__gevent | src/greentest/3.9/test_subprocess.py | {
"start": 147182,
"end": 152003
} | class ____(unittest.TestCase):
class RecordingPopen(subprocess.Popen):
"""A Popen that saves a reference to each instance for testing."""
instances_created = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.instances_created.append(self... | MiscTests |
python | google__pytype | pytype/errors/errors_test.py | {
"start": 11741,
"end": 13401
} | class ____(unittest.TestCase):
dirname = path_utils.dirname
ERROR_FILE_PATH = path_utils.join(
dirname(dirname(errors.__file__)), "../docs/errors.md"
)
def _check_and_get_documented_errors(self):
with open(self.ERROR_FILE_PATH) as f:
lines = f.readlines()
entries = [line[3:].strip() for lin... | ErrorDocTest |
python | numpy__numpy | numpy/_core/tests/test_numerictypes.py | {
"start": 12503,
"end": 12701
} | class ____(ReadValuesNested):
"""Check the values of heterogeneous arrays (nested, multiple rows)"""
_descr = Ndescr
multiple_rows = True
_buffer = NbufferT
| TestReadValuesNestedMultiple |
python | huggingface__transformers | src/transformers/models/x_clip/configuration_x_clip.py | {
"start": 783,
"end": 5078
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`XCLIPModel`]. It is used to instantiate an X-CLIP
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configu... | XCLIPTextConfig |
python | scipy__scipy | scipy/linalg/tests/test_fblas.py | {
"start": 8603,
"end": 8833
} | class ____(BaseSwap):
blas_func = fblas.dswap
dtype = float64
try:
class TestCswap(BaseSwap):
blas_func = fblas.cswap
dtype = complex64
except AttributeError:
class TestCswap:
pass
| TestDswap |
python | django__django | tests/select_related_onetoone/models.py | {
"start": 737,
"end": 807
} | class ____(UserStat):
karma = models.IntegerField()
| AdvancedUserStat |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/device.py | {
"start": 817,
"end": 1480
} | class ____(OAuthLibMixin, View):
server_class = DeviceApplicationServer
def post(self, request, *args, **kwargs):
headers, response, status = self.create_device_authorization_response(request)
if status != 200:
return http.JsonResponse(data=json.loads(response), status=status, head... | DeviceAuthorizationView |
python | getsentry__sentry | src/sentry/preprod/models.py | {
"start": 12617,
"end": 13076
} | class ____(DefaultFieldsModel):
"""The build configuration used to build the artifact, e.g. "Debug" or "Release"."""
__relocation_scope__ = RelocationScope.Excluded
project = FlexibleForeignKey("sentry.Project")
name = models.CharField(max_length=255)
class Meta:
app_label = "preprod"
... | PreprodBuildConfiguration |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 10395,
"end": 10457
} | class ____(_BackupsPermission):
pass
| BackupsPermissionOutput |
python | Pylons__pyramid | tests/test_authentication.py | {
"start": 60314,
"end": 64543
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.authentication import BasicAuthAuthenticationPolicy as cls
return cls
def _makeOne(self, check):
return self._getTargetClass()(check, realm='SomeRealm')
def test_class_implements_IAuthenticationPolicy(self):
... | TestBasicAuthAuthenticationPolicy |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_chisquare_test_p_value_to_be_greater_than.py | {
"start": 269,
"end": 894
} | class ____(BatchExpectation):
def __init__(self, *args, **kwargs):
raise NotImplementedError
library_metadata = {
"maturity": "production",
"tags": [
"core expectation",
"column aggregate expectation",
"needs migration to modular expectations api",
... | ExpectColumnChiSquareTestPValueToBeGreaterThan |
python | kamyu104__LeetCode-Solutions | Python/find-the-distance-value-between-two-arrays.py | {
"start": 606,
"end": 1097
} | class ____(object):
def findTheDistanceValue(self, arr1, arr2, d):
"""
:type arr1: List[int]
:type arr2: List[int]
:type d: int
:rtype: int
"""
arr1.sort(), arr2.sort()
result, i, j = 0, 0, 0
while i < len(arr1) and j < len(arr2):
i... | Solution2 |
python | spack__spack | lib/spack/spack/vendor/jsonschema/_format.py | {
"start": 169,
"end": 6752
} | class ____(object):
"""
A ``format`` property checker.
JSON Schema does not mandate that the ``format`` property actually do any
validation. If validation is desired however, instances of this class can
be hooked into validators to enable format validation.
`FormatChecker` objects always retur... | FormatChecker |
python | optuna__optuna | optuna/samplers/_gp/sampler.py | {
"start": 1916,
"end": 21549
} | class ____(BaseSampler):
"""Sampler using Gaussian process-based Bayesian optimization.
This sampler fits a Gaussian process (GP) to the objective function and optimizes
the acquisition function to suggest the next parameters.
The current implementation uses Matern kernel with nu=2.5 (twice differenti... | GPSampler |
python | plotly__plotly.py | plotly/graph_objs/_sunburst.py | {
"start": 215,
"end": 67181
} | class ____(_BaseTraceType):
_parent_path_str = ""
_path_str = "sunburst"
_valid_props = {
"branchvalues",
"count",
"customdata",
"customdatasrc",
"domain",
"hoverinfo",
"hoverinfosrc",
"hoverlabel",
"hovertemplate",
"hovertempla... | Sunburst |
python | great-expectations__great_expectations | tests/integration/conftest.py | {
"start": 985,
"end": 9044
} | class ____:
data_source_config: DataSourceTestConfig
data: pd.DataFrame
extra_data: Mapping[str, pd.DataFrame]
secondary_source_config: Union[DataSourceTestConfig, None] = None
secondary_data: Union[pd.DataFrame, None] = None
@override
def __hash__(self) -> int:
if self.secondary_da... | TestConfig |
python | google__jax | tests/lru_cache_test.py | {
"start": 846,
"end": 1463
} | class ____(jtu.JaxTestCase):
name: str | None
path: pathlib.Path | None
def setUp(self):
if importlib.util.find_spec("filelock") is None:
self.skipTest("filelock is not installed")
super().setUp()
tmpdir = tempfile.TemporaryDirectory()
self.enter_context(tmpdir)
self.name = tmpdir.name... | LRUCacheTestCase |
python | great-expectations__great_expectations | tests/integration/metrics/column/test_values_not_match_regex_count.py | {
"start": 735,
"end": 1756
} | class ____:
@parameterize_batch_for_data_sources(
data_source_configs=ALL_DATA_SOURCES_EXCEPT_SNOWFLAKE,
data=DATA_FRAME,
)
def test_partial_match_characters(self, batch_for_datasource: Batch) -> None:
metric = ColumnValuesNotMatchRegexCount(column=COLUMN_NAME, regex="ab")
me... | TestColumnValuesNotMatchRegexCount |
python | PrefectHQ__prefect | src/prefect/client/schemas/filters.py | {
"start": 30657,
"end": 30869
} | class ____(PrefectBaseModel):
"""Filter by `Artifact.flow_run_id`."""
any_: Optional[List[UUID]] = Field(
default=None, description="A list of flow run IDs to include"
)
| ArtifactFilterFlowRunId |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/handle.py | {
"start": 336,
"end": 1704
} | class ____(NamedTuple("_StepHandle", [("node_handle", NodeHandle), ("key", str)])):
"""A reference to an ExecutionStep that was determined statically."""
def __new__(cls, node_handle: NodeHandle, key: Optional[str] = None):
return super().__new__(
cls,
node_handle=check.inst_par... | StepHandle |
python | PrefectHQ__prefect | src/integrations/prefect-docker/prefect_docker/worker.py | {
"start": 14775,
"end": 37125
} | class ____(BaseWorker[DockerWorkerJobConfiguration, Any, DockerWorkerResult]):
"""Prefect worker that executes flow runs within Docker containers."""
type = "docker"
job_configuration = DockerWorkerJobConfiguration
_description = (
"Execute flow runs within Docker containers. Works well for man... | DockerWorker |
python | graphql-python__graphene | graphene/tests/issues/test_490.py | {
"start": 75,
"end": 516
} | class ____(graphene.ObjectType):
some_field = graphene.String(from_=graphene.String(name="from"))
def resolve_some_field(self, info, from_=None):
return from_
def test_issue():
query_string = """
query myQuery {
someField(from: "Oh")
}
"""
schema = graphene.Schema(query=Que... | Query |
python | huggingface__transformers | src/transformers/models/blenderbot/modeling_blenderbot.py | {
"start": 36601,
"end": 43547
} | class ____(BlenderbotPreTrainedModel):
_tied_weights_keys = {
"encoder.embed_tokens.weight": "shared.weight",
"decoder.embed_tokens.weight": "shared.weight",
}
def __init__(self, config: BlenderbotConfig):
super().__init__(config)
padding_idx, vocab_size = config.pad_token_... | BlenderbotModel |
python | matplotlib__matplotlib | lib/matplotlib/figure.py | {
"start": 84737,
"end": 91566
} | class ____(FigureBase):
"""
Logical figure that can be placed inside a figure.
See :ref:`figure-api-subfigure` for an index of methods on this class.
Typically instantiated using `.Figure.add_subfigure` or
`.SubFigure.add_subfigure`, or `.SubFigure.subfigures`. A subfigure has
the same methods... | SubFigure |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-mcp/llama_index/tools/mcp/tool_spec_mixins.py | {
"start": 3028,
"end": 4533
} | class ____:
def _create_list_type(self: "McpToolSpec", schema: dict, defs: dict) -> type:
"""Create a List type from schema."""
item_type = self._resolve_field_type(schema["items"], defs)
return List[item_type]
def _create_dict_type(self: "McpToolSpec", schema: dict, defs: dict) -> type... | TypeCreationMixin |
python | tensorflow__tensorflow | tensorflow/lite/tools/flatbuffer_utils_test.py | {
"start": 9587,
"end": 10650
} | class ____(test_util.TensorFlowTestCase):
def testXxdOutputToBytes(self):
# 1. SETUP
# Define the initial model
initial_model = test_utils.build_mock_model()
initial_bytes = flatbuffer_utils.convert_object_to_bytearray(initial_model)
# Define temporary files
tmp_dir = self.get_temp_dir()
... | XxdOutputToBytesTest |
python | pytorch__pytorch | torch/_dynamo/variables/lists.py | {
"start": 36232,
"end": 42160
} | class ____(CommonListMethodsVariable):
def __init__(
self,
items: list[VariableTracker],
maxlen: Optional[VariableTracker] = None,
**kwargs: Any,
) -> None:
if maxlen is None:
maxlen = ConstantVariable.create(None)
assert maxlen.is_python_constant(), (... | DequeVariable |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/logs/events.py | {
"start": 1349,
"end": 1809
} | class ____(graphene.Interface):
runId = graphene.NonNull(graphene.String)
message = graphene.NonNull(graphene.String)
timestamp = graphene.NonNull(graphene.String)
level = graphene.NonNull(GrapheneLogLevel)
stepKey = graphene.Field(graphene.String)
solidHandleID = graphene.Field(graphene.String)... | GrapheneMessageEvent |
python | kamyu104__LeetCode-Solutions | Python/employee-importance.py | {
"start": 900,
"end": 1344
} | class ____(object):
def getImportance(self, employees, id):
"""
:type employees: Employee
:type id: int
:rtype: int
"""
result, q = 0, collections.deque([id])
while q:
curr = q.popleft()
employee = employees[curr-1]
result +... | Solution2 |
python | milvus-io__pymilvus | pymilvus/exceptions.py | {
"start": 2591,
"end": 2691
} | class ____(MilvusException):
"""Raise when datatype isn't supported"""
| DataTypeNotSupportException |
python | PyCQA__pylint | tests/regrtest_data/importing_plugin/importing_plugin.py | {
"start": 121,
"end": 749
} | class ____(BaseChecker):
options = (
(
"settings-module",
{
"default": "settings",
"type": "string",
"metavar": "<settings module>"
},
),
)
msgs = {
"E9999": (
"Importing checker error me... | ImportingChecker |
python | great-expectations__great_expectations | great_expectations/render/renderer/column_section_renderer.py | {
"start": 15619,
"end": 17936
} | class ____(ColumnSectionRenderer):
def __init__(self, table_renderer=None) -> None:
super().__init__()
if table_renderer is None:
table_renderer = {"class_name": "ValidationResultsTableContentBlockRenderer"}
module_name = table_renderer.get(
"module_name", "great_expe... | ValidationResultsColumnSectionRenderer |
python | pytorch__pytorch | torch/_dynamo/variables/higher_order_ops.py | {
"start": 117240,
"end": 120444
} | class ____(TorchHigherOrderOperatorVariable):
"""
This hop is not exposed to users but is inserted into the graph
after export as a post-processing step.
"""
def call_function(
self,
tx: "InstructionTranslator",
args: "list[VariableTracker]",
kwargs: "dict[str, Varia... | WrapWithAutocastHigherOrderVariable |
python | astropy__astropy | astropy/io/fits/tests/test_checksum.py | {
"start": 267,
"end": 1021
} | class ____(FitsTestCase):
def setup_method(self):
super().setup_method()
self._oldfilters = warnings.filters[:]
warnings.filterwarnings("error", message="Checksum verification failed")
warnings.filterwarnings("error", message="Datasum verification failed")
# Monkey-patch the... | BaseChecksumTests |
python | jazzband__django-formtools | tests/wizard/test_forms.py | {
"start": 11631,
"end": 11852
} | class ____(TestCase):
def test_init(self):
request = get_request()
testform = CookieWizardView.as_view([('start', Step1)])
self.assertIsInstance(testform(request), TemplateResponse)
| CookieFormTests |
python | fastai__fastai | fastai/data/transforms.py | {
"start": 15176,
"end": 15309
} | class ____(Transform):
"Convert item to appropriate tensor class"
order = 5
# %% ../../nbs/05_data.transforms.ipynb 111
| ToTensor |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/utils/__init__.py | {
"start": 859,
"end": 2657
} | class ____(ConfigurableResource):
region_name: Optional[str] = Field(
default=None, description="Specifies a custom region for the Boto3 session"
)
max_attempts: int = Field(
default=5,
description=(
"This provides Boto3's retry handler with a value of maximum retry attem... | ResourceWithBoto3Configuration |
python | pallets__werkzeug | src/werkzeug/routing/exceptions.py | {
"start": 430,
"end": 598
} | class ____(Exception):
"""Special exceptions that require the application to redirect, notifying
about missing urls, etc.
:internal:
"""
| RoutingException |
python | doocs__leetcode | solution/0300-0399/0311.Sparse Matrix Multiplication/Solution2.py | {
"start": 0,
"end": 659
} | class ____:
def multiply(self, mat1: List[List[int]], mat2: List[List[int]]) -> List[List[int]]:
def f(mat: List[List[int]]) -> List[List[int]]:
g = [[] for _ in range(len(mat))]
for i, row in enumerate(mat):
for j, x in enumerate(row):
if x:
... | Solution |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.