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 | benchmarks/benchmarks/bench_reduce.py | {
"start": 1725,
"end": 2019
} | class ____(Benchmark):
params = [np.float32, np.float64]
param_names = ['dtype']
def setup(self, dtype):
self.d = np.ones(20000, dtype=dtype)
def time_min(self, dtype):
np.fmin.reduce(self.d)
def time_max(self, dtype):
np.fmax.reduce(self.d)
| FMinMax |
python | readthedocs__readthedocs.org | readthedocs/projects/querysets.py | {
"start": 6690,
"end": 8198
} | class ____(NoReprQuerySet, models.QuerySet):
"""
Useful for objects that relate to Project and its permissions.
Objects get the permissions from the project itself.
..note:: This shouldn't be used as a subclass.
"""
use_for_related_fields = True
project_field = "project"
def _add_fro... | RelatedProjectQuerySet |
python | spack__spack | lib/spack/spack/util/environment.py | {
"start": 12137,
"end": 12589
} | class ____(NamePathModifier):
def execute(self, env: MutableMapping[str, str]):
tty.debug(f"PrependPath: {self.name}+{self.value}", level=3)
environment_value = env.get(self.name, "")
directories = environment_value.split(self.separator) if environment_value else []
directories = [pa... | PrependPath |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_kronecker_test.py | {
"start": 3133,
"end": 11741
} | class ____(
linear_operator_test_util.SquareLinearOperatorDerivedClassTest):
"""Most tests done in the base class LinearOperatorDerivedClassTest."""
def tearDown(self):
config.enable_tensor_float_32_execution(self.tf32_keep_)
def setUp(self):
self.tf32_keep_ = config.tensor_float_32_execution_enable... | SquareLinearOperatorKroneckerTest |
python | pytorch__pytorch | test/quantization/eager/test_model_numerics.py | {
"start": 304,
"end": 7618
} | class ____(QuantizationTestCase):
def test_float_quant_compare_per_tensor(self):
for qengine in supported_qengines:
with override_quantized_engine(qengine):
torch.manual_seed(42)
my_model = ModelMultipleOps().to(torch.float32)
my_model.eval()
... | TestModelNumericsEager |
python | ray-project__ray | python/ray/tests/spark/test_basic.py | {
"start": 1437,
"end": 9430
} | class ____(ABC):
spark = None
num_total_cpus = None
num_total_gpus = None
num_cpus_per_spark_task = None
num_gpus_per_spark_task = None
max_spark_tasks = None
@classmethod
def teardown_class(cls):
time.sleep(10) # Wait all background spark job canceled.
os.environ.pop("... | RayOnSparkCPUClusterTestBase |
python | getsentry__sentry | tests/sentry/incidents/utils/test_metric_issue_base.py | {
"start": 947,
"end": 4356
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.detector_group_key = None
self.detector = self.create_detector(
project=self.project,
workflow_condition_group=self.create_data_condition_group(),
type=MetricIssue.slug,
create... | BaseMetricIssueTest |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-shopify/llama_index/tools/shopify/base.py | {
"start": 91,
"end": 1142
} | class ____(BaseToolSpec):
"""Shopify tool spec."""
spec_functions = ["run_graphql_query"]
def __init__(self, shop_url: str, api_version: str, admin_api_key: str):
# Currently only supports Admin API auth
# https://shopify.dev/docs/apps/auth/admin-app-access-tokens
from shopify impo... | ShopifyToolSpec |
python | fastai__fastai | nbs/examples/migrating_catalyst.py | {
"start": 698,
"end": 1319
} | class ____(dl.Runner):
def predict_batch(self, batch): return self.model(batch[0].to(self.device).view(batch[0].size(0), -1))
def _handle_batch(self, batch):
x, y = batch
y_hat = self.model(x.view(x.size(0), -1))
loss = F.cross_entropy(y_hat, y)
accuracy01, accuracy03 = metrics... | CustomRunner |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pygments/cmdline.py | {
"start": 16607,
"end": 23655
} | class ____(argparse.HelpFormatter):
def __init__(self, prog, indent_increment=2, max_help_position=16, width=None):
if width is None:
try:
width = shutil.get_terminal_size().columns - 2
except Exception:
pass
argparse.HelpFormatter.__init__(sel... | HelpFormatter |
python | PyCQA__pyflakes | pyflakes/checker.py | {
"start": 9187,
"end": 10506
} | class ____(Importation):
"""
A binding created by a submodule import statement.
A submodule import is a special case where the root module is implicitly
imported, without an 'as' clause, and the submodule is also imported.
Python does not restrict which attributes of the root module may be used.
... | SubmoduleImportation |
python | python__mypy | mypyc/codegen/emit.py | {
"start": 1608,
"end": 2719
} | class ____:
"""A representation of a declaration in C.
This is used to generate declarations in header files and
(optionally) definitions in source files.
Attributes:
decl: C source code for the declaration.
defn: Optionally, C source code for a definition.
dependencies: The names of... | HeaderDeclaration |
python | apache__airflow | providers/teradata/src/airflow/providers/teradata/transfers/s3_to_teradata.py | {
"start": 1359,
"end": 5546
} | class ____(BaseOperator):
"""
Loads CSV, JSON and Parquet format data from Amazon S3 to Teradata.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:S3ToTeradataOperator`
:param s3_source_key: The URI format specifying the loca... | S3ToTeradataOperator |
python | numba__numba | numba/tests/test_inlining.py | {
"start": 4000,
"end": 4251
} | class ____(compiler.CompilerBase):
"""compiler pipeline for testing inlining after optimization
"""
def define_pipelines(self):
pm = gen_pipeline(self.state, InlineTestPass)
pm.finalize()
return [pm]
| InlineTestPipeline |
python | RaRe-Technologies__gensim | gensim/models/ensemblelda.py | {
"start": 5163,
"end": 22779
} | class ____:
max_num_neighboring_labels: int # the max number of parent labels among each topic of a given cluster
neighboring_labels: List[Set[int]] # a concatenated list of the neighboring_labels sets of each topic
label: int # the unique identifier of the cluster
num_cores: int # how many topics i... | Cluster |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance18.py | {
"start": 267,
"end": 507
} | class ____(NamedTuple, Generic[T]):
pass
def func1(val: NT1[str] | tuple[int, int]):
if isinstance(val, NT1):
reveal_type(val, expected_text="NT1[str]")
else:
reveal_type(val, expected_text="tuple[int, int]")
| NT1 |
python | catalyst-team__catalyst | examples/catalyst_rl/ddpg.py | {
"start": 3407,
"end": 10878
} | class ____(dl.Runner):
def __init__(
self,
*,
gamma: float,
tau: float,
tau_period: int = 1,
actor_key: str = "actor",
critic_key: str = "critic",
target_actor_key: str = "target_actor",
target_critic_key: str = "target_critic",
actor_o... | CustomRunner |
python | pytorch__pytorch | test/dynamo/test_fx_graph_runnable.py | {
"start": 3133,
"end": 13132
} | class ____(TestCase):
def setUp(self):
super().setUp()
torch._dynamo.reset()
torch._logging.structured.INTERN_TABLE.clear()
self.old_level = trace_log.level
trace_log.setLevel(logging.DEBUG)
# Create a custom filter specifically for fx_graph_runnable entries
... | FxGraphRunnableTest |
python | huggingface__transformers | tests/models/chinese_clip/test_processing_chinese_clip.py | {
"start": 968,
"end": 2485
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = ChineseCLIPProcessor
@classmethod
def _setup_tokenizer(cls):
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
vocab_tokens = [
"[UNK]",
"[CLS]",
"[SEP]",
... | ChineseCLIPProcessorTest |
python | apache__airflow | airflow-core/tests/unit/dag_processing/test_collection.py | {
"start": 13275,
"end": 41068
} | class ____:
"""Tests centred around the ``update_dag_parsing_results_in_db`` function."""
@pytest.fixture
def clean_db(self, session):
yield
clear_db_serialized_dags()
clear_db_dags()
clear_db_import_errors()
@pytest.fixture(name="dag_import_error_listener")
def _da... | TestUpdateDagParsingResults |
python | pypa__pip | src/pip/_internal/req/req_file.py | {
"start": 9974,
"end": 14756
} | class ____:
def __init__(
self,
session: PipSession,
line_parser: LineParser,
) -> None:
self._session = session
self._line_parser = line_parser
def parse(
self, filename: str, constraint: bool
) -> Generator[ParsedLine, None, None]:
"""Parse a gi... | RequirementsFileParser |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 576,
"end": 636
} | class ____(str, Enum):
OIDC = "oidc"
@dataclass
| GroupTypes |
python | ray-project__ray | python/ray/tests/test_runtime_env_packaging.py | {
"start": 10860,
"end": 11436
} | class ____:
def test_get_top_level_valid(self, random_zip_file_with_top_level_dir):
top_level_dir_name = get_top_level_dir_from_compressed_package(
str(random_zip_file_with_top_level_dir)
)
assert top_level_dir_name == TOP_LEVEL_DIR_NAME
def test_get_top_level_invalid(self, ... | TestGetTopLevelDirFromCompressedPackage |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/log.py | {
"start": 7469,
"end": 8498
} | class ____:
__doc__ = """\
When ``True``, enable log output for this element.
This has the effect of setting the Python logging level for the namespace
of this element's class and object reference. A value of boolean ``True``
indicates that the loglevel ``logging.INFO`` will be set for the logger,... | echo_property |
python | getsentry__sentry | tests/sentry/core/endpoints/scim/test_scim_schema.py | {
"start": 50,
"end": 254
} | class ____(SCIMTestCase):
endpoint = "sentry-api-0-organization-scim-schema-index"
def test_schema_200s(self) -> None:
self.get_success_response(self.organization.slug)
| SCIMSchemaEndpointTest |
python | sqlalchemy__sqlalchemy | test/orm/_fixtures.py | {
"start": 11074,
"end": 17584
} | class ____:
"""Built on demand, instances use mappers in effect at time of call."""
def __init__(self, test):
self.test = test
@property
def user_result(self):
User = self.test.classes.User
return [User(id=7), User(id=8), User(id=9), User(id=10)]
@property
def user_ad... | CannedResults |
python | jina-ai__jina | tests/unit/orchestrate/pods/test_pod.py | {
"start": 2284,
"end": 4502
} | class ____(BaseExecutor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
raise RuntimeError('intentional error')
def test_failing_executor():
args = _generate_pod_args(
[
'--uses',
'RaisingExecutor',
]
)
with pytest.raise... | RaisingExecutor |
python | pytorch__pytorch | torch/distributed/elastic/utils/api.py | {
"start": 1202,
"end": 1705
} | class ____:
"""
Defines simple macros for caffe2.distributed.launch cmd args substitution
"""
local_rank = "${local_rank}"
@staticmethod
def substitute(args: list[Any], local_rank: str) -> list[str]:
args_sub = []
for arg in args:
if isinstance(arg, str):
... | macros |
python | pytorch__pytorch | test/jit/test_custom_operators.py | {
"start": 456,
"end": 4865
} | class ____(JitTestCase):
def test_dynamic_op_registry(self):
from torch._ops import _OpNamespace
self.assertTrue(hasattr(torch, "ops"))
if "_test" in torch.ops.__dict__:
torch.ops.__dict__.pop("_test")
# Don't use `hasattr()` because it will call `__getattr__`.
... | TestCustomOperators |
python | doocs__leetcode | solution/3100-3199/3114.Latest Time You Can Obtain After Replacing Characters/Solution.py | {
"start": 0,
"end": 271
} | class ____:
def findLatestTime(self, s: str) -> str:
for h in range(11, -1, -1):
for m in range(59, -1, -1):
t = f"{h:02d}:{m:02d}"
if all(a == b for a, b in zip(s, t) if a != "?"):
return t
| Solution |
python | getsentry__sentry | src/sentry/onboarding_tasks/backends/organization_onboarding_task.py | {
"start": 775,
"end": 5864
} | class ____(OnboardingTaskBackend[OrganizationOnboardingTask]):
Model = OrganizationOnboardingTask
def fetch_onboarding_tasks(self, organization, user):
return self.Model.objects.filter(
organization=organization,
task__in=OnboardingTask.values(), # we exclude any tasks that mig... | OrganizationOnboardingTaskBackend |
python | lepture__authlib | authlib/oauth2/rfc7591/errors.py | {
"start": 638,
"end": 847
} | class ____(OAuth2Error):
"""The software statement presented is invalid.
https://tools.ietf.org/html/rfc7591#section-3.2.2.
"""
error = "invalid_software_statement"
| InvalidSoftwareStatementError |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pyproject_hooks/_impl.py | {
"start": 926,
"end": 1137
} | class ____(Exception):
"""Will be raised on missing hooks (if a fallback can't be used)."""
def __init__(self, hook_name):
super().__init__(hook_name)
self.hook_name = hook_name
| HookMissing |
python | cython__cython | Cython/Shadow.py | {
"start": 16473,
"end": 16982
} | class ____:
"""
The cython.parallel module.
"""
__all__ = ['parallel', 'prange', 'threadid']
def parallel(self, num_threads=None):
return nogil
def prange(self, start=0, stop=None, step=1, nogil=False, schedule=None, chunksize=None, num_threads=None):
if stop is None:
... | CythonDotParallel |
python | sanic-org__sanic | sanic/touchup/schemes/ode.py | {
"start": 141,
"end": 1564
} | class ____(BaseScheme):
ident = "ODE"
SYNC_SIGNAL_NAMESPACES = "http."
def __init__(self, app) -> None:
super().__init__(app)
self._sync_events()
self._registered_events = [
signal.name for signal in app.signal_router.routes
]
def visitors(self) -> list[Nod... | OptionalDispatchEvent |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 35342,
"end": 35546
} | class ____(BoringModel):
def on_validation_start(self):
if not self.trainer.sanity_checking and self.current_epoch == 1:
raise RuntimeError("Trouble!")
| TroubledModelOnValidationStart |
python | huggingface__transformers | src/transformers/models/oneformer/modeling_oneformer.py | {
"start": 83210,
"end": 84575
} | class ____(nn.Module):
def __init__(
self,
d_model,
dim_feedforward=2048,
dropout=0.0,
activation="relu",
normalize_before=False,
layer_norm_eps=1e-05,
):
super().__init__()
# Implementation of Feedforward model
self.linear1 = nn.Li... | OneFormerTransformerDecoderFFNLayer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 575946,
"end": 576583
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of DisablePullRequestAutoMerge"""
__schema__ = github_schema
__field_names__ = ("actor", "client_mutation_id", "pull_request")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who performed the event."""
c... | DisablePullRequestAutoMergePayload |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/back_populates/tutorial002_py310.py | {
"start": 300,
"end": 4532
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
team_id: int | None = Field(default=None, foreign_key="team.id")
team: Team | None = Relationship(back_popula... | Hero |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 307478,
"end": 307658
} | class ____(VegaLiteSchema):
"""Element schema wrapper."""
_schema = {"$ref": "#/definitions/Element"}
def __init__(self, *args):
super().__init__(*args)
| Element |
python | django__django | tests/serializers/models/base.py | {
"start": 2928,
"end": 3573
} | class ____(models.CharField):
def __init__(self):
super().__init__(max_length=100)
def get_db_prep_save(self, value, connection):
return str(value.title)
def to_python(self, value):
if isinstance(value, Team):
return value
return Team(value)
def from_db_val... | TeamField |
python | milvus-io__pymilvus | pymilvus/orm/future.py | {
"start": 1777,
"end": 1929
} | class ____(BaseFuture):
"""SearchFuture of async already returns SearchResult, add BaseFuture
functions into async.SearchFuture
"""
| SearchFuture |
python | skorch-dev__skorch | examples/word_language_model/net.py | {
"start": 121,
"end": 3546
} | class ____(skorch.NeuralNet):
def __init__(
self,
criterion=torch.nn.CrossEntropyLoss,
clip=0.25,
lr=20,
ntokens=10000,
*args,
**kwargs
):
self.clip = clip
self.ntokens = ntokens
super(Net, self).__init_... | Net |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 63514,
"end": 63755
} | class ____(BaseModel, extra="forbid"):
"""
Select points with empty payload for a specified field
"""
is_empty: "PayloadField" = Field(..., description="Select points with empty payload for a specified field")
| IsEmptyCondition |
python | django-guardian__django-guardian | example_project_custom_group/articles/models.py | {
"start": 1404,
"end": 1774
} | class ____(GroupObjectPermissionAbstract):
group = models.ForeignKey(CustomGroup, on_delete=models.CASCADE)
class Meta(GroupObjectPermissionAbstract.Meta):
abstract = False
indexes = [
*GroupObjectPermissionAbstract.Meta.indexes,
models.Index(fields=["content_type", "obj... | BigGroupObjectPermission |
python | doocs__leetcode | solution/1400-1499/1424.Diagonal Traverse II/Solution.py | {
"start": 0,
"end": 277
} | class ____:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
arr = []
for i, row in enumerate(nums):
for j, v in enumerate(row):
arr.append((i + j, j, v))
arr.sort()
return [v[2] for v in arr]
| Solution |
python | apache__airflow | providers/oracle/tests/unit/oracle/transfers/test_oracle_to_oracle.py | {
"start": 975,
"end": 2911
} | class ____:
def test_execute(self):
oracle_destination_conn_id = "oracle_destination_conn_id"
destination_table = "destination_table"
oracle_source_conn_id = "oracle_source_conn_id"
source_sql = "select sysdate from dual where trunc(sysdate) = :p_data"
source_sql_params = {":... | TestOracleToOracleTransfer |
python | boto__boto3 | tests/unit/docs/test_subresource.py | {
"start": 662,
"end": 1978
} | class ____(BaseDocsTest):
def test_document_sub_resources(self):
sub_resource_documentor = SubResourceDocumenter(
self.resource, self.root_services_path
)
sub_resource_documentor.document_sub_resources(self.doc_structure)
self.assert_contains_lines_in_order(
[... | TestSubResourceDocumenter |
python | gevent__gevent | src/gevent/tests/test__greenness.py | {
"start": 1948,
"end": 2295
} | class ____(HTTPServer, object):
messages = ()
requests_handled = 0
def __init__(self):
HTTPServer.__init__(self,
params.DEFAULT_BIND_ADDR_TUPLE,
QuietHandler)
def handle_request(self):
HTTPServer.handle_request(self)
self... | Server |
python | pytorch__pytorch | .github/scripts/test_trymerge.py | {
"start": 36148,
"end": 38686
} | class ____(TestCase):
def test_get_classifications(self, *args: Any) -> None:
pr = GitHubPR("pytorch", "pytorch", 111467)
checks = pr.get_checkrun_conclusions()
checks = get_classifications(
pr.pr_num,
pr.project,
checks,
[],
)
... | TestBypassFailuresOnSandCastle |
python | pydata__xarray | xarray/core/variable.py | {
"start": 12116,
"end": 101430
} | class ____(NamedArray, AbstractArray, VariableArithmetic):
"""A netcdf-like variable consisting of dimensions, data and attributes
which describe a single Array. A single Variable object is not fully
described outside the context of its parent Dataset (if you want such a
fully described object, use a Da... | Variable |
python | pypa__pip | src/pip/_vendor/pkg_resources/__init__.py | {
"start": 8335,
"end": 8510
} | class ____(Exception):
"""Abstract base for dependency resolution errors"""
def __repr__(self):
return self.__class__.__name__ + repr(self.args)
| ResolutionError |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_spec.py | {
"start": 383,
"end": 8144
} | 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... | V1IngressSpec |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/cluster_coordinator_test.py | {
"start": 38885,
"end": 41819
} | class ____(TestCaseWithErrorReportingThread):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.coordinator = make_coordinator(
num_workers=5, num_ps=2,
partitioner=sharded_variable.FixedShardsPartitioner(3))
cls.strategy = cls.coordinator.strategy
def testEmbeddingLookup(se... | ShardedVariableTest |
python | getsentry__sentry | src/sentry/notifications/notifications/activity/resolved.py | {
"start": 142,
"end": 415
} | class ____(GroupActivityNotification):
metrics_key = "resolved_activity"
title = "Resolved Issue"
def get_description(self) -> tuple[str, str | None, Mapping[str, Any]]:
return "{author} marked {an issue} as resolved", None, {}
| ResolvedActivityNotification |
python | pyinstaller__pyinstaller | bootloader/waflib/Errors.py | {
"start": 1123,
"end": 1170
} | class ____(WafError):
pass
| ConfigurationError |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 110484,
"end": 112486
} | class ____(Request):
"""
Get histogram data of all the scalar metrics and variants in the task
:param task: Task ID
:type task: str
:param metric:
:type metric: str
:param variant:
:type variant: str
"""
_service = "events"
_action = "vector_metrics_iter_histogram"
_ver... | VectorMetricsIterHistogramRequest |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/testing/codegen.py | {
"start": 1118,
"end": 1296
} | class ____(NodeSampler):
sample_map = dict((
(gast.Assign, 10),
(gast.Print, 1),
(gast.If, 2),
(gast.While, 2),
(gast.For, 0),
))
| StatementSampler |
python | huggingface__transformers | src/transformers/models/patchtsmixer/modeling_patchtsmixer.py | {
"start": 1371,
"end": 2031
} | class ____(nn.Module):
"""
Module that applies gated attention to input data.
Args:
in_size (`int`): The input size.
out_size (`int`): The output size.
"""
def __init__(self, in_size: int, out_size: int):
super().__init__()
self.attn_layer = nn.Linear(in_size, out_s... | PatchTSMixerGatedAttention |
python | sympy__sympy | sympy/logic/boolalg.py | {
"start": 26836,
"end": 30149
} | class ____(BooleanFunction):
"""
Logical Not function (negation)
Returns ``true`` if the statement is ``false`` or ``False``.
Returns ``false`` if the statement is ``true`` or ``True``.
Examples
========
>>> from sympy import Not, And, Or
>>> from sympy.abc import x, A, B
>>> Not... | Not |
python | huggingface__transformers | src/transformers/models/dab_detr/modeling_dab_detr.py | {
"start": 53248,
"end": 64462
} | class ____(DabDetrPreTrainedModel):
def __init__(self, config: DabDetrConfig):
super().__init__(config)
self.auxiliary_loss = config.auxiliary_loss
# Create backbone + positional encoding
self.backbone = DabDetrConvEncoder(config)
object_queries = DabDetrSinePositionEmbeddi... | DabDetrModel |
python | walkccc__LeetCode | solutions/1220. Count Vowels Permutation/1220.py | {
"start": 0,
"end": 415
} | class ____:
def countVowelPermutation(self, n: int) -> int:
MOD = 1_000_000_007
dp = {'a': 1, 'e': 1, 'i': 1, 'o': 1, 'u': 1}
for _ in range(n - 1):
newDp = {'a': dp['e'] + dp['i'] + dp['u'],
'e': dp['a'] + dp['i'],
'i': dp['e'] + dp['o'],
'o': dp['i'],
... | Solution |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-vectorx/tests/test_vector_stores_vectorx.py | {
"start": 8838,
"end": 10059
} | class ____(unittest.TestCase):
def setUp(self):
self.mock_index = MagicMock()
self.mock_index.dimension = 2
self.mock_index.query.return_value = [
{
"id": "1",
"similarity": 0.9,
"meta": {"text": "mock text"},
"vecto... | TestVectorXMock |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 77135,
"end": 90959
} | class ____(
roles.DDLConstraintColumnRole,
roles.DDLExpressionRole,
roles.StatementOptionRole,
roles.WhereHavingRole,
roles.OrderByRole,
roles.FromClauseRole,
roles.SelectStatementRole,
roles.InElementRole,
Generative,
ExecutableStatement,
DQLDMLClauseElement,
roles.Binar... | TextClause |
python | coleifer__peewee | tests/psycopg3_ext.py | {
"start": 17704,
"end": 19683
} | class ____(ModelTestCase):
database = db
requires = [KX]
def setUp(self):
super(TestPsycopg3AutocommitIntegration, self).setUp()
with self.database.atomic():
kx1 = KX.create(key='k1', value=1)
def force_integrity_error(self):
# Force an integrity error, then verify ... | TestPsycopg3AutocommitIntegration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-azure-blob-storage/source_azure_blob_storage/config_migrations.py | {
"start": 3742,
"end": 4331
} | class ____(MigrateConfig):
"""
This class stands for migrating the config azure_blob_storage_account_key inside object `credentials`
"""
@classmethod
def should_migrate(cls, config: Mapping[str, Any]) -> bool:
return "credentials" not in config
@classmethod
def migrate_config(cls, ... | MigrateCredentials |
python | weaviate__weaviate-python-client | weaviate/collections/classes/internal.py | {
"start": 2366,
"end": 2573
} | class ____(Generic[P, R, M]):
uuid: uuid_package.UUID
metadata: M
properties: P
references: R
vector: Dict[str, Union[List[float], List[List[float]]]]
collection: str
@dataclass
| _Object |
python | keras-team__keras | keras/src/layers/convolutional/base_conv_transpose.py | {
"start": 599,
"end": 10719
} | class ____(Layer):
"""Abstract N-D transposed convolution layer.
The need for transposed convolutions generally arises from the desire to use
a transformation going in the opposite direction of a normal convolution,
i.e., from something that has the shape of the output of some convolution to
someth... | BaseConvTranspose |
python | falconry__falcon | falcon/testing/srmock.py | {
"start": 919,
"end": 2264
} | class ____:
"""Mock object representing a WSGI `start_response` callable."""
status: str | None
"""HTTP status line, e.g. '785 TPS Cover Sheet not attached'."""
headers: HeaderIter | None
"""Raw headers list passed to `start_response`, per PEP-3333."""
headers_dict: Headers
"""Headers as a ... | StartResponseMock |
python | vyperlang__vyper | vyper/ast/pre_parser.py | {
"start": 4619,
"end": 6389
} | class ____:
def __init__(self, code):
self._code = code
self.annotations = {}
self._current_annotation = None
self._state = ParserState.NOT_RUNNING
self._current_for_loop = None
def consume(self, token):
# state machine: we can start slurping tokens soon
... | ForParser |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip.py | {
"start": 31758,
"end": 38337
} | class ____(BlipPreTrainedModel, GenerationMixin):
config: BlipConfig
main_input_name = "pixel_values"
_tied_weights_keys = {
"text_decoder.cls.predictions.decoder.bias": "text_decoder.cls.predictions.bias",
"text_decoder.cls.predictions.decoder.weight": "text_decoder.bert.embeddings.word_emb... | BlipForConditionalGeneration |
python | pennersr__django-allauth | allauth/account/internal/flows/email_verification_by_code.py | {
"start": 560,
"end": 5004
} | class ____(AbstractCodeVerificationProcess):
def __init__(self, request, state: dict, user=None) -> None:
self.request = request
super().__init__(
state=state,
user=user,
max_attempts=app_settings.EMAIL_VERIFICATION_BY_CODE_MAX_ATTEMPTS,
timeout=app_se... | EmailVerificationProcess |
python | faif__python-patterns | patterns/behavioral/command.py | {
"start": 1442,
"end": 1911
} | class ____:
"""
A command to delete a file given its name
"""
def __init__(self) -> None:
# an array of deleted files, to undo them as needed
self._deleted_files: List[str] = []
def execute(self, filename: str) -> None:
print(f"deleting {filename}")
self._deleted_fi... | DeleteFileCommand |
python | gevent__gevent | src/greentest/3.13/test_weakref.py | {
"start": 2142,
"end": 34197
} | class ____(TestBase):
def test_basic_ref(self):
self.check_basic_ref(C)
self.check_basic_ref(create_function)
self.check_basic_ref(create_bound_method)
# Just make sure the tp_repr handler doesn't raise an exception.
# Live reference:
o = C()
wr = weakref.re... | ReferencesTestCase |
python | PrefectHQ__prefect | src/prefect/tasks.py | {
"start": 9991,
"end": 79590
} | class ____(Generic[P, R]):
"""
A Prefect task definition.
Wraps a function with an entrypoint to the Prefect engine. Calling this class within a flow function
creates a new task run.
To preserve the input and output types, we use the generic type variables P and R for "Parameters" and
"Returns... | Task |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 91296,
"end": 91372
} | class ____(BinOpFrame):
operation = M.ge
_operator_repr = ">="
| GEFrame |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dlp.py | {
"start": 5731,
"end": 10397
} | class ____(GoogleCloudBaseOperator):
"""
Create a deidentify template to reuse frequently-used configurations for content, images, and storage.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDLPCreateDeidentifyTemplateOpera... | CloudDLPCreateDeidentifyTemplateOperator |
python | scipy__scipy | scipy/stats/_qmc.py | {
"start": 58212,
"end": 70966
} | class ____(QMCEngine):
"""Engine for generating (scrambled) Sobol' sequences.
Sobol' sequences are low-discrepancy, quasi-random numbers. Points
can be drawn using two methods:
* `random_base2`: safely draw :math:`n=2^m` points. This method
guarantees the balance properties of the sequence.
... | Sobol |
python | huggingface__transformers | src/transformers/models/deepseek_v3/modular_deepseek_v3.py | {
"start": 1083,
"end": 3279
} | class ____(Qwen2MoeMLP):
pass
def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
r"""
TODO let's just use the original freqcis computation to not have the view
transpose + reshape! This is not optimized!
Applies Rotary Position Embedding to the query and key t... | DeepseekV3MLP |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/default_types.py | {
"start": 12282,
"end": 17570
} | class ____(trace.TraceType, serialization.Serializable):
"""Represents a NamedTuple of TraceType objects."""
def __init__(self,
type_name: str,
attribute_names: PythonTuple[str],
attributes: PythonTuple[trace.TraceType],
placeholder_type: Optional[Type[An... | NamedTuple |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol32.py | {
"start": 392,
"end": 492
} | class ____(Base2[Value], Protocol[Arg, Value]):
def another(self, arg: Arg) -> None: ...
| Interface |
python | pydata__xarray | xarray/core/_aggregations.py | {
"start": 235067,
"end": 285932
} | class ____:
_obj: DataArray
def reduce(
self,
func: Callable[..., Any],
dim: Dims = None,
*,
axis: int | Sequence[int] | None = None,
keep_attrs: bool | None = None,
keepdims: bool = False,
**kwargs: Any,
) -> DataArray:
raise NotImple... | DataArrayGroupByAggregations |
python | joke2k__faker | tests/providers/test_date_time.py | {
"start": 34095,
"end": 34451
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("it_IT")
Faker.seed(0)
def test_day(self):
day = self.fake.day_of_week()
assert day in ItItProvider.DAY_NAMES.values()
def test_month(self):
month = self.fake.month_name()
assert month in ItIt... | TestItIt |
python | django__django | tests/i18n/test_extraction.py | {
"start": 38435,
"end": 41427
} | class ____(ExtractorTests):
def test_no_location_enabled(self):
"""
Behavior is correct if --no-location switch is specified. See #16903.
"""
management.call_command(
"makemessages", locale=[LOCALE], verbosity=0, no_location=True
)
self.assertTrue(os.path.... | LocationCommentsTests |
python | simplejson__simplejson | simplejson/tests/test_raw_json.py | {
"start": 262,
"end": 1062
} | class ____(unittest.TestCase):
def test_normal_str(self):
self.assertNotEqual(json.dumps(dct2), json.dumps(dct3))
def test_raw_json_str(self):
self.assertEqual(json.dumps(dct2), json.dumps(dct4))
self.assertEqual(dct2, json.loads(json.dumps(dct4)))
def test_list(self):
sel... | TestRawJson |
python | huggingface__transformers | src/transformers/models/data2vec/configuration_data2vec_vision.py | {
"start": 805,
"end": 8671
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Data2VecVisionModel`]. It is used to instantiate
an Data2VecVision model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield ... | Data2VecVisionConfig |
python | Textualize__textual | docs/examples/widgets/list_view.py | {
"start": 107,
"end": 446
} | class ____(App):
CSS_PATH = "list_view.tcss"
def compose(self) -> ComposeResult:
yield ListView(
ListItem(Label("One")),
ListItem(Label("Two")),
ListItem(Label("Three")),
)
yield Footer()
if __name__ == "__main__":
app = ListViewExample()
ap... | ListViewExample |
python | tensorflow__tensorflow | tensorflow/python/ops/weak_tensor_math_ops_test.py | {
"start": 27693,
"end": 28979
} | class ____(
parameterized.TestCase, test_util.TensorFlowTestCase):
@parameterized.parameters(
itertools.product(
allowed_var_op_input_combinations,
("assign", "assign_add", "assign_sub")))
def testAllowedDtypes(self, v_dtype_and_delta, op):
v_dtype, delta = v_dtype_and_delta
i... | VariableInplaceOpsTest |
python | walkccc__LeetCode | solutions/866. Prime Palindrome/866.py | {
"start": 0,
"end": 687
} | class ____:
def primePalindrome(self, n: int) -> int:
def getPalindromes(n: int) -> int:
length = n // 2
for i in range(10**(length - 1), 10**length):
s = str(i)
for j in range(10):
yield int(s + str(j) + s[::-1])
def isPrime(num: int) -> bool:
return not any(num %... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 53002,
"end": 53647
} | class ____(sgqlc.types.Enum):
"""The possible values for the members can create repositories
setting on an organization.
Enumeration Choices:
* `ALL`: Members will be able to create public and private
repositories.
* `DISABLED`: Members will not be able to create public or private
repo... | OrganizationMembersCanCreateRepositoriesSettingValue |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-confluence/llama_index/readers/confluence/event.py | {
"start": 2239,
"end": 2584
} | class ____(BaseEvent):
"""Event emitted when an attachment is skipped."""
page_id: str
attachment_id: str
attachment_name: str
attachment_type: str
attachment_size: int
attachment_link: str
reason: str
@classmethod
def class_name(cls) -> str:
return "AttachmentSkippedEv... | AttachmentSkippedEvent |
python | jazzband__prettytable | tests/test_prettytable.py | {
"start": 14947,
"end": 22637
} | class ____:
"""Some very basic tests."""
def test_table_rows(self, city_data: PrettyTable) -> None:
rows = city_data.rows
assert len(rows) == 7
assert rows[0] == CITY_DATA[0]
def test_add_rows(self, city_data: PrettyTable) -> None:
"""A table created with multiple add_row c... | TestBasic |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 143547,
"end": 144653
} | class ____(multi_rv_frozen):
__class_getitem__ = None
def __init__(self, dim=None, seed=None):
"""Create a frozen SO(N) distribution.
Parameters
----------
dim : scalar
Dimension of matrices
seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomSt... | special_ortho_group_frozen |
python | great-expectations__great_expectations | great_expectations/metrics/column/sample_values.py | {
"start": 152,
"end": 215
} | class ____(MetricResult[list[Any]]): ...
| ColumnSampleValuesResult |
python | django__django | django/contrib/sites/middleware.py | {
"start": 96,
"end": 309
} | class ____(MiddlewareMixin):
"""
Middleware that sets `site` attribute to request object.
"""
def process_request(self, request):
request.site = get_current_site(request)
| CurrentSiteMiddleware |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/config/models.py | {
"start": 2400,
"end": 2660
} | class ____(BaseModel, extra="forbid"):
locations: list[Location] = Field(description="List of code locations")
def load_dagster_cloud_yaml(text) -> DagsterCloudYaml:
return DagsterCloudYaml.model_validate(yaml.safe_load(text))
| ProcessedDagsterCloudConfig |
python | has2k1__plotnine | plotnine/scales/scale_color.py | {
"start": 14962,
"end": 15033
} | class ____(scale_color_gradient2):
pass
@alias
| scale_colour_gradient2 |
python | openai__openai-python | src/openai/lib/streaming/chat/_events.py | {
"start": 937,
"end": 1026
} | class ____(BaseModel):
type: Literal["refusal.done"]
refusal: str
| RefusalDoneEvent |
python | numba__numba | numba/cuda/tests/nocuda/test_dummyarray.py | {
"start": 6201,
"end": 10761
} | class ____(unittest.TestCase):
def test_reshape_2d2d(self):
nparr = np.empty((4, 5))
arr = Array.from_desc(0, nparr.shape, nparr.strides,
nparr.dtype.itemsize)
expect = nparr.reshape(5, 4)
got = arr.reshape(5, 4)[0]
self.assertEqual(got.shape, ex... | TestReshape |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 683969,
"end": 713534
} | class ____(
FieldChannelMixin, core.FieldOrDatumDefWithConditionMarkPropFieldDefnumber
):
r"""
StrokeOpacity schema wrapper.
Parameters
----------
shorthand : str, dict, Sequence[str], :class:`RepeatRef`
shorthand for field, aggregate, and type
aggregate : dict, :class:`Aggregate`, ... | StrokeOpacity |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.