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/a/abstract/abstract_class_instantiated.py | {
"start": 808,
"end": 856
} | class ____(SecondBadClass):
pass
| ThirdBadClass |
python | getsentry__sentry | tests/sentry/integrations/slack/webhooks/commands/test_link_user.py | {
"start": 1337,
"end": 2171
} | class ____(SlackCommandsTest):
"""Slash commands results are generated on Region Silo"""
@patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
def test_link_command(self, mock_record: MagicMock) -> None:
data = self.send_slack_message("link")
assert "Link your Slack identi... | SlackCommandsLinkUserTest |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/extra/ghostwriter.py | {
"start": 36416,
"end": 73249
} | class ____(NamedTuple):
type_name: str
imports: set[str]
def _parameters_to_annotation_name(
parameters: Iterable[Any] | None, imports: ImportSet
) -> str | None:
if parameters is None:
return None
annotations = tuple(
annotation
for annotation in map(_parameter_to_annotati... | _AnnotationData |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 347999,
"end": 355470
} | class ____(Response):
"""
Response of tasks.reset endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
:param deleted_indices: List of deleted ES indices that were removed as part of
the reset... | ResetResponse |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1212577,
"end": 1212808
} | class ____(sgqlc.types.Type, Node):
"""A branch linked to an issue."""
__schema__ = github_schema
__field_names__ = ("ref",)
ref = sgqlc.types.Field("Ref", graphql_name="ref")
"""The branch's ref."""
| LinkedBranch |
python | scikit-image__scikit-image | src/skimage/_shared/utils.py | {
"start": 6663,
"end": 16007
} | class ____:
"""Deprecate a parameter of a function.
Parameters
----------
deprecated_name : str
The name of the deprecated parameter.
start_version : str
The package version in which the warning was introduced.
stop_version : str
The package version in which the warning ... | deprecate_parameter |
python | lepture__authlib | authlib/oauth2/rfc6749/errors.py | {
"start": 4551,
"end": 4987
} | class ____(OAuth2Error):
"""The authorization grant type is not supported by the
authorization server.
https://tools.ietf.org/html/rfc6749#section-5.2
"""
error = "unsupported_grant_type"
def __init__(self, grant_type):
super().__init__()
self.grant_type = grant_type
def ... | UnsupportedGrantTypeError |
python | kamyu104__LeetCode-Solutions | Python/reformat-phone-number.py | {
"start": 48,
"end": 1104
} | class ____(object):
def reformatNumber(self, number):
"""
:type number: str
:rtype: str
"""
number = list(number)
src_len = 0
for c in number: # remove non-digit characters
if c.isdigit():
number[src_len] = c
src_le... | Solution |
python | astropy__astropy | astropy/time/tests/test_quantity_interaction.py | {
"start": 11078,
"end": 13326
} | class ____:
def test_delta_ut1_utc(self):
t = Time("2010-01-01 00:00:00", format="iso", scale="utc", precision=6)
t.delta_ut1_utc = 0.3 * u.s
assert t.ut1.iso == "2010-01-01 00:00:00.300000"
t.delta_ut1_utc = 0.4 / 60.0 * u.minute
assert t.ut1.iso == "2010-01-01 00:00:00.4000... | TestDeltaAttributes |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/__init__.py | {
"start": 3833,
"end": 4521
} | class ____(torch.nn.Module):
r"""Dequantizes an incoming tensor
Examples::
>>> input = torch.tensor([[1., -1.], [1., -1.]])
>>> scale, zero_point, dtype = 1.0, 2, torch.qint8
>>> qm = Quantize(scale, zero_point, dtype)
>>> # xdoctest: +SKIP
>>> quantized_input = qm(input... | DeQuantize |
python | getsentry__sentry | tests/sentry/middleware/integrations/test_integration_control.py | {
"start": 890,
"end": 6418
} | class ____(TestCase):
get_response = MagicMock()
middleware = IntegrationControlMiddleware(get_response=get_response)
integration_cls = IntegrationClassification(response_handler=get_response)
plugin_cls = PluginClassification(response_handler=get_response)
def setUp(self) -> None:
self.fac... | IntegrationControlMiddlewareTest |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/installation_external_requests.py | {
"start": 540,
"end": 1409
} | class ____(SentryAppInstallationBaseEndpoint):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
def get(self, request: Request, installation) -> Response:
try:
project = Project.objects.get(
id=request.GET.get("projectId"), ... | SentryAppInstallationExternalRequestsEndpoint |
python | pypa__pipenv | pipenv/utils/requirementslib.py | {
"start": 11703,
"end": 28060
} | class ____(KeyError, IndexError, TypeError):
"""An amalgamation of KeyError, IndexError, and TypeError, representing
what can occur when looking up a path in a nested object."""
def __init__(self, exc, seg, path):
self.exc = exc
self.seg = seg
self.path = path
def __repr__(self... | PathAccessError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1400310,
"end": 1401588
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'removed_from_merge_queue' event on a given pull
request.
"""
__schema__ = github_schema
__field_names__ = ("actor", "before_commit", "created_at", "enqueuer", "merge_queue", "pull_request", "reason")
actor = sgqlc.types.Field(Actor, graphql_n... | RemovedFromMergeQueueEvent |
python | ray-project__ray | python/ray/tests/test_task_metrics.py | {
"start": 17010,
"end": 17806
} | class ____:
def f(self):
try:
ray.get(phaser.inc.remote())
except Exception:
print("RESTART")
os._exit(1)
f = F.remote()
ray.get(f.f.remote())
time.sleep(999)
"""
proc = run_string_as_driver_nonblocking(driver)
expected = {
("F.__init__", "FINISH... | F |
python | pyinstaller__pyinstaller | bootloader/waflib/Runner.py | {
"start": 1486,
"end": 2023
} | class ____(Utils.threading.Thread):
def __init__(self, spawner, task):
Utils.threading.Thread.__init__(self)
self.task = task
self.spawner = spawner
self.daemon = True
self.start()
def run(self):
try:
if not self.spawner.master.stop:
s... | Consumer |
python | graphql-python__graphene | graphene/relay/tests/test_connection_query.py | {
"start": 416,
"end": 7013
} | class ____(ObjectType):
letters = ConnectionField(LetterConnection)
connection_letters = ConnectionField(LetterConnection)
async_letters = ConnectionField(LetterConnection)
node = Node.Field()
def resolve_letters(self, info, **args):
return list(letters.values())
async def resolve_asy... | Query |
python | scipy__scipy | scipy/optimize/tests/test__shgo.py | {
"start": 34780,
"end": 39217
} | class ____:
def test_1_maxiter(self):
"""Test failure on insufficient iterations"""
options = {'maxiter': 2}
res = shgo(test4_1.f, test4_1.bounds, n=2, iters=None,
options=options, sampling_method='sobol')
np.testing.assert_equal(False, res.success)
# np.t... | TestShgoFailures |
python | redis__redis-py | redis/commands/cluster.py | {
"start": 29094,
"end": 30745
} | class ____(
ClusterDataAccessCommands, AsyncDataAccessCommands
):
"""
A class for Redis Cluster Data Access Commands
The class inherits from Redis's core DataAccessCommand class and do the
required adjustments to work with cluster mode
"""
async def scan_iter(
self,
match: ... | AsyncClusterDataAccessCommands |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 81981,
"end": 102093
} | class ____(Indexable, TypeEngine[Any]):
"""Represent a SQL JSON type.
.. note:: :class:`_types.JSON`
is provided as a facade for vendor-specific
JSON types. Since it supports JSON SQL operations, it only
works on backends that have an actual JSON type, currently:
* PostgreSQL - s... | JSON |
python | PrefectHQ__prefect | tests/test_flow_engine.py | {
"start": 64503,
"end": 75421
} | class ____:
async def get_flow_run_for_flow(self, flow_name: str):
async with get_client() as prefect_client:
flow_runs = await prefect_client.read_flow_runs(
flow_filter=FlowFilter(name=FlowFilterName(any_=[flow_name]))
)
assert len(flow_runs) == 1
re... | TestRunFlowInSubprocess |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/utils/mixins.py | {
"start": 2383,
"end": 7407
} | class ____:
"""
Mixin class to be used by both the DatabricksSqlStatementsOperator, and the DatabricksSqlStatementSensor.
- _handle_operator_execution (renamed to _handle_execution)
- _handle_deferrable_operator_execution (renamed to _handle_deferrable_execution)
- execute_complete
... | DatabricksSQLStatementsMixin |
python | mahmoud__glom | glom/core.py | {
"start": 67102,
"end": 67649
} | class ____:
"""Evaluate specs one after the other, passing the result of
the previous evaluation in as the target of the next spec:
>>> glom({'a': {'b': -5}}, Pipe('a', 'b', abs))
5
Same behavior as ``Auto(tuple(steps))``, but useful for explicit
usage in other modes.
"""
def __ini... | Pipe |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/test_system_message.py | {
"start": 2089,
"end": 10806
} | class ____:
"""Test ModelRequest with system_message field."""
@pytest.mark.parametrize(
"system_message,system_prompt,expected_msg,expected_prompt",
[
# Test with SystemMessage
(
SystemMessage(content="You are helpful"),
None,
... | TestModelRequestSystemMessage |
python | getsentry__sentry | src/sentry/preprod/pull_request/types.py | {
"start": 225,
"end": 359
} | class ____(StrEnum):
ADDED = "added"
MODIFIED = "modified"
REMOVED = "removed"
RENAMED = "renamed"
| PullRequestFileStatus |
python | apache__airflow | dev/breeze/src/airflow_breeze/commands/release_management_commands.py | {
"start": 106240,
"end": 171034
} | class ____(NamedTuple):
"""Stores details about commits"""
full_hash: str
short_hash: str
date: str
message: str
message_without_backticks: str
pr: int | None
def get_change_from_line(line: str):
split_line = line.split(" ", maxsplit=3)
message = split_line[3]
pr = None
pr... | Change |
python | conda__conda | conda/base/constants.py | {
"start": 8372,
"end": 11156
} | class ____(ValueEnum):
CRITICAL = "critical"
WARNING = "warning"
INFO = "info"
# Magic files for permissions determination
PACKAGE_CACHE_MAGIC_FILE: Final[PathType] = "urls.txt"
PREFIX_MAGIC_FILE: Final[PathType] = join("conda-meta", "history")
PREFIX_FROZEN_FILE: Final[PathType] = join("conda-meta", "fro... | NoticeLevel |
python | sympy__sympy | sympy/matrices/common.py | {
"start": 56426,
"end": 73319
} | class ____(MatrixRequired):
"""Provides basic matrix shape and elementwise
operations. Should not be instantiated directly."""
def _eval_adjoint(self):
return self.transpose().conjugate()
def _eval_applyfunc(self, f):
out = self._new(self.rows, self.cols, [f(x) for x in self])
... | MatrixOperations |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py | {
"start": 1178,
"end": 2627
} | class ____(ControlSiloOrganizationEndpoint):
owner = ApiOwner.ECOSYSTEM
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
@extend_schema(
operation_id="Retrieve the custom integrations created by an organization",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
... | OrganizationSentryAppsEndpoint |
python | bokeh__bokeh | src/bokeh/document/json.py | {
"start": 1921,
"end": 2002
} | class ____(TypedDict):
kind: Literal["TitleChanged"]
title: str
| TitleChanged |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_ip_asn_country_code_in_set.py | {
"start": 938,
"end": 2029
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.ip_asn_country_code_in_set"
condition_value_keys = ("country_codes",)
# This method implements the core logic for the PandasExecutionEngine
@column_conditi... | ColumnValuesToBePrivateIpV6 |
python | neetcode-gh__leetcode | python/0473-matchsticks-to-square.py | {
"start": 0,
"end": 651
} | class ____:
def makesquare(self, matchsticks: List[int]) -> bool:
length = sum(matchsticks) // 4
sides = [0] * 4
if sum(matchsticks) / 4 != length:
return False
matchsticks.sort(reverse=True)
def backtrack(i):
if i == len(matchsticks):
... | Solution |
python | gevent__gevent | src/greentest/3.14/test_urllib2.py | {
"start": 2752,
"end": 11396
} | class ____(unittest.TestCase):
def test_request_headers_dict(self):
"""
The Request.headers dictionary is not a documented interface. It
should stay that way, because the complete set of headers are only
accessible through the .get_header(), .has_header(), .header_items()
i... | RequestHdrsTests |
python | readthedocs__readthedocs.org | readthedocs/projects/tests/test_views.py | {
"start": 800,
"end": 6024
} | class ____(TestCase):
def setUp(self):
self.user = get(User)
self.project = get(Project, users=[self.user])
self.integration = get(
Integration,
integration_type=Integration.GITHUB_WEBHOOK,
project=self.project,
)
self.url = reverse("projec... | TestExternalBuildOption |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 41873,
"end": 42217
} | class ____(str, Enum):
"""
Fusion algorithm allows to combine results of multiple prefetches. Available fusion algorithms: * `rrf` - Reciprocal Rank Fusion (with default parameters) * `dbsf` - Distribution-Based Score Fusion
"""
def __str__(self) -> str:
return str(self.value)
RRF = "rrf... | Fusion |
python | huggingface__transformers | tests/models/llava_onevision/test_modeling_llava_onevision.py | {
"start": 10530,
"end": 25548
} | class ____(unittest.TestCase):
def setUp(self):
self.processor = AutoProcessor.from_pretrained(
"llava-hf/llava-onevision-qwen2-0.5b-ov-hf", padding_side="left"
)
image_file = hf_hub_download(
repo_id="raushan-testing-hf/images_test", filename="llava_v1_5_radar.jpg", ... | LlavaOnevisionForConditionalGenerationIntegrationTest |
python | scrapy__scrapy | tests/test_spidermiddleware_process_start.py | {
"start": 1955,
"end": 2277
} | class ____:
async def process_start(self, start):
yield ITEM_A
async for item_or_request in start:
yield item_or_request
yield ITEM_C
def process_start_requests(self, start, spider):
yield ITEM_A
yield from start
yield ITEM_C
| UniversalWrapSpiderMiddleware |
python | kamyu104__LeetCode-Solutions | Python/sum-of-good-numbers.py | {
"start": 37,
"end": 334
} | class ____(object):
def sumOfGoodNumbers(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
return sum(nums[i] for i in xrange(len(nums)) if (i-k < 0 or nums[i-k] < nums[i]) and (i+k >= len(nums) or nums[i+k] < nums[i]))
| Solution |
python | streamlit__streamlit | lib/streamlit/runtime/scriptrunner_utils/script_requests.py | {
"start": 1500,
"end": 2411
} | class ____:
"""Data attached to RERUN requests. Immutable."""
query_string: str = ""
widget_states: WidgetStates | None = None
page_script_hash: str = ""
page_name: str = ""
# A single fragment_id to append to fragment_id_queue.
fragment_id: str | None = None
# The queue of fragment_id... | RerunData |
python | nedbat__coveragepy | coverage/html.py | {
"start": 2707,
"end": 2922
} | class ____:
"""Data for each index page."""
noun: str
plural: str
filename: str
summaries: list[IndexItem]
totals: Numbers
skipped_covered_count: int
skipped_empty_count: int
| IndexPage |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-oci-data-science/tests/test_oci_data_science_client.py | {
"start": 10542,
"end": 17205
} | class ____:
"""Unit tests for Client class."""
def setup_method(self):
self.endpoint = "https://example.com/api"
self.auth_mock = {"signer": Mock()}
self.retries = 2
self.backoff_factor = 0.1
self.timeout = 10
self.client = Client(
endpoint=self.endp... | TestClient |
python | fluentpython__example-code-2e | 15-more-types/cafeteria/contravariant.py | {
"start": 58,
"end": 102
} | class ____: # <1>
"""Any refuse."""
| Refuse |
python | getsentry__sentry | tests/snuba/test_metrics_layer.py | {
"start": 33070,
"end": 35660
} | class ____(TestCase, BaseMetricsTestCase):
def ts(self, dt: datetime) -> int:
return int(dt.timestamp())
def setUp(self) -> None:
super().setUp()
self.generic_metrics: Mapping[str, Literal["counter", "set", "distribution", "gauge"]] = {
TransactionMRI.DURATION.value: "distr... | MQLMetaTest |
python | keras-team__keras | keras/src/optimizers/schedules/learning_rate_schedule.py | {
"start": 28057,
"end": 35828
} | class ____(LearningRateSchedule):
"""A `LearningRateSchedule` that uses a cosine decay schedule with restarts.
See [Loshchilov & Hutter, ICLR2016](https://arxiv.org/abs/1608.03983),
SGDR: Stochastic Gradient Descent with Warm Restarts.
When training a model, it is often useful to lower the learning ra... | CosineDecayRestarts |
python | openai__openai-python | src/openai/types/realtime/realtime_response_create_mcp_tool.py | {
"start": 1891,
"end": 2324
} | class ____(BaseModel):
always: Optional[RequireApprovalMcpToolApprovalFilterAlways] = None
"""A filter object to specify which tools are allowed."""
never: Optional[RequireApprovalMcpToolApprovalFilterNever] = None
"""A filter object to specify which tools are allowed."""
RequireApproval: TypeAlias =... | RequireApprovalMcpToolApprovalFilter |
python | FactoryBoy__factory_boy | factory/base.py | {
"start": 13979,
"end": 21782
} | class ____(Generic[T]):
"""Factory base support for sequences, attributes and stubs."""
# Backwards compatibility
UnknownStrategy = errors.UnknownStrategy
UnsupportedStrategy = errors.UnsupportedStrategy
def __new__(cls, *args, **kwargs):
"""Would be called if trying to instantiate the cla... | BaseFactory |
python | dateutil__dateutil | src/dateutil/rrule.py | {
"start": 1973,
"end": 2610
} | class ____(weekdaybase):
"""
This version of weekday does not allow n = 0.
"""
def __init__(self, wkday, n=None):
if n == 0:
raise ValueError("Can't create weekday with n==0")
super(weekday, self).__init__(wkday, n)
MO, TU, WE, TH, FR, SA, SU = weekdays = tuple(weekday(x) ... | weekday |
python | wandb__wandb | wandb/vendor/pygments/formatters/img.py | {
"start": 1243,
"end": 1336
} | class ____(ImportError):
"""When Python imaging library is not available"""
| PilNotAvailable |
python | ray-project__ray | python/ray/dag/tests/experimental/test_compiled_graphs.py | {
"start": 35030,
"end": 35333
} | class ____:
def sleep_and_echo(self, x):
time.sleep(x)
return x
def fail_if_x_is_even(self, x):
if x % 2 == 0:
raise ValueError("x is even")
return x
def sleep_and_fail(self, x):
time.sleep(x)
raise ValueError("fail")
| FastFailActor |
python | spack__spack | lib/spack/spack/externals.py | {
"start": 6078,
"end": 16987
} | class ____:
"""Transforms a list of external dicts into a list of specs."""
def __init__(
self,
external_dicts: List[ExternalDict],
*,
complete_node: Callable[[spack.spec.Spec], None] = complete_variants_and_architecture,
allow_nonexisting: bool = True,
):
""... | ExternalSpecsParser |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/window_test.py | {
"start": 1349,
"end": 10652
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(
combinations.times(
test_base.default_test_combinations(),
combinations.combine(
count=20,
size=[10, 14, 17],
shift=[7, 14],
stride=[1, 2, 6],
... | WindowTest |
python | pandas-dev__pandas | pandas/tests/arrays/sparse/test_indexing.py | {
"start": 342,
"end": 3892
} | class ____:
def test_getitem(self, arr):
dense = arr.to_dense()
for i, value in enumerate(arr):
tm.assert_almost_equal(value, dense[i])
tm.assert_almost_equal(arr[-i], dense[-i])
def test_getitem_arraylike_mask(self, arr):
arr = SparseArray([0, 1, 2])
res... | TestGetitem |
python | django__django | tests/fixtures/models.py | {
"start": 2995,
"end": 3324
} | class ____(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Person)
class Meta:
ordering = ("name",)
def __str__(self):
authors = " and ".join(a.name for a in self.authors.all())
return "%s by %s" % (self.name, authors) if authors else sel... | Book |
python | ansible__ansible | test/units/test_context.py | {
"start": 247,
"end": 747
} | class ____:
pass
def test_set_global_context():
options = FakeOptions()
options.tags = [u'production', u'webservers']
options.check_mode = True
options.start_at_task = u'Start with くらとみ'
expected = frozenset((('tags', (u'production', u'webservers')),
('check_mode', T... | FakeOptions |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_bytes.py | {
"start": 2495,
"end": 2534
} | class ____(bytes):
pass
| BytesSubclass |
python | pytorch__pytorch | torch/distributed/tensor/examples/convnext_example.py | {
"start": 568,
"end": 1297
} | class ____(nn.Module):
def __init__(self, normalized_shape, eps=1e-6, data_format=torch.contiguous_format):
super().__init__()
self.weight = nn.Parameter(torch.ones(normalized_shape))
self.bias = nn.Parameter(torch.zeros(normalized_shape))
self.eps = eps
self.data_format = da... | LayerNorm |
python | pypa__pip | tests/lib/options_helpers.py | {
"start": 594,
"end": 882
} | class ____:
def setup_method(self) -> None:
commands_dict["fake"] = CommandInfo(
"tests.lib.options_helpers",
"FakeCommand",
"fake summary",
)
def teardown_method(self) -> None:
commands_dict.pop("fake")
| AddFakeCommandMixin |
python | jazzband__django-waffle | waffle/tests/test_testutils.py | {
"start": 10193,
"end": 10392
} | class ____(OverrideFlagOnClassTestsMixin,
TestCase):
"""
Run tests with Django TestCase
"""
@override_flag('foo', active=False)
| OverrideFlagOnClassTestCase |
python | pyca__cryptography | src/cryptography/hazmat/primitives/serialization/pkcs7.py | {
"start": 1308,
"end": 1673
} | class ____(utils.Enum):
Text = "Add text/plain MIME type"
Binary = "Don't translate input data into canonical MIME format"
DetachedSignature = "Don't embed data in the PKCS7 structure"
NoCapabilities = "Don't embed SMIME capabilities"
NoAttributes = "Don't embed authenticatedAttributes"
NoCerts ... | PKCS7Options |
python | huggingface__transformers | src/transformers/models/zamba2/modeling_zamba2.py | {
"start": 16228,
"end": 25309
} | class ____(nn.Module):
"""
Multi-headed attention from 'Attention Is All You Need' paper.
Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
The extra fac... | Zamba2Attention |
python | falconry__falcon | tests/test_validators.py | {
"start": 2373,
"end": 2637
} | class ____:
def __init__(self, valid=True):
self._media = _VALID_MEDIA if valid else {}
async def get_media(self):
return self._media
def MockReq(asgi, valid=True):
return _MockReqAsync(valid) if asgi else _MockReq(valid)
| _MockReqAsync |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 2162,
"end": 2290
} | class ____(SimpleSitemap):
lastmod = datetime(2013, 3, 13, 10, 0, 0, tzinfo=timezone.get_fixed_timezone(-300))
| TimezoneSiteMap |
python | huggingface__transformers | src/transformers/models/ernie/modeling_ernie.py | {
"start": 21450,
"end": 22868
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([ErnieLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optio... | ErnieEncoder |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 879110,
"end": 879520
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("PullRequestReviewThread",... | PullRequestReviewThreadEdge |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_allocated_device_status.py | {
"start": 383,
"end": 10542
} | 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... | V1beta1AllocatedDeviceStatus |
python | doocs__leetcode | solution/0200-0299/0205.Isomorphic Strings/Solution.py | {
"start": 0,
"end": 293
} | class ____:
def isIsomorphic(self, s: str, t: str) -> bool:
d1 = {}
d2 = {}
for a, b in zip(s, t):
if (a in d1 and d1[a] != b) or (b in d2 and d2[b] != a):
return False
d1[a] = b
d2[b] = a
return True
| Solution |
python | TheAlgorithms__Python | data_structures/linked_list/doubly_linked_list_two.py | {
"start": 1165,
"end": 6906
} | class ____:
head: Node | None = None # First node in list
tail: Node | None = None # Last node in list
def __str__(self):
current = self.head
nodes = []
while current is not None:
nodes.append(current.data)
current = current.next
return " ".join(str... | LinkedList |
python | django__django | tests/servers/tests.py | {
"start": 6437,
"end": 6546
} | class ____(LiveServerTestCase):
server_thread_class = LiveServerSingleThread
| SingleThreadLiveServerTestCase |
python | sympy__sympy | sympy/sets/fancysets.py | {
"start": 6869,
"end": 14486
} | class ____(Set):
"""
Image of a set under a mathematical function. The transformation
must be given as a Lambda function which has as many arguments
as the elements of the set upon which it operates, e.g. 1 argument
when acting on the set of integers or 2 arguments when acting on
a complex regio... | ImageSet |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 45292,
"end": 45411
} | class ____(BaseModel):
responses: Dict[str, "OperationDurationStatistics"] = Field(..., description="")
| GrpcTelemetry |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_pdf.py | {
"start": 14449,
"end": 14641
} | class ____:
"""Store verbatim PDF command content for later inclusion in the stream."""
def __init__(self, x):
self._x = x
def pdfRepr(self):
return self._x
| Verbatim |
python | astropy__astropy | astropy/table/tests/conftest.py | {
"start": 1232,
"end": 1285
} | class ____(table.TableColumns):
pass
| MyTableColumns |
python | walkccc__LeetCode | solutions/1759. Count Number of Homogenous Substrings/1759.py | {
"start": 0,
"end": 274
} | class ____:
def countHomogenous(self, s: str) -> int:
MOD = 1_000_000_007
ans = 0
count = 0
currentChar = '@'
for c in s:
count = count + 1 if c == currentChar else 1
currentChar = c
ans += count
ans %= MOD
return ans
| Solution |
python | spyder-ide__spyder | spyder/plugins/run/confpage.py | {
"start": 1343,
"end": 6042
} | class ____(HoverRowsTableView):
def __init__(self, parent, model):
super().__init__(parent)
self._parent = parent
self.setModel(model)
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.setSortingEnab... | RunParametersTableView |
python | apache__airflow | providers/celery/tests/unit/celery/executors/test_celery_executor.py | {
"start": 2480,
"end": 4099
} | class ____:
@property
def state(self):
raise Exception(FAKE_EXCEPTION_MSG)
def task_id(self):
return "task_id"
@contextlib.contextmanager
def _prepare_app(broker_url=None, execute=None):
broker_url = broker_url or conf.get("celery", "BROKER_URL")
if AIRFLOW_V_3_0_PLUS:
ex... | FakeCeleryResult |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/matrix_mult_test.py | {
"start": 2067,
"end": 2980
} | class ____(op_bench.TorchBenchmarkBase):
def init(self, B, M, N, device, op_func):
self.inputs = {
"input_one": torch.rand(B, M, N, device=device),
"input_two": torch.rand(B, M, N, device=device),
}
self.op_func = op_func
def forward(self, input_one, input_two):
... | BatchElementWiseBenchmark |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/cpython/cpython3.py | {
"start": 1580,
"end": 6427
} | class ____(CPythonWindows, CPython3):
"""CPython 3 on Windows."""
@classmethod
def setup_meta(cls, interpreter):
if is_store_python(interpreter): # store python is not supported here
return None
return super().setup_meta(interpreter)
@classmethod
def sources(cls, inter... | CPython3Windows |
python | great-expectations__great_expectations | great_expectations/exceptions/exceptions.py | {
"start": 14386,
"end": 14522
} | class ____(GreatExpectationsError):
"""Error connecting to a database including during an integration test."""
| DatabaseConnectionError |
python | pyparsing__pyparsing | examples/lineno_example.py | {
"start": 966,
"end": 1530
} | class ____:
def __init__(self, st, locn, tok_string):
self.token_string = tok_string
self.locn = locn
self.source_line = pp.line(locn, st)
self.line_no = pp.lineno(locn, st)
self.col = pp.col(locn, st)
def __str__(self):
return f"{self.token_string!r} (line: {sel... | Token |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-mailchimp/unit_tests/test_config_datacenter_migration.py | {
"start": 463,
"end": 3793
} | class ____:
"""Test cases for ExtractAndSetDataCenterConfigValue."""
def setup_method(self):
"""Set up test fixtures."""
self.extractor = ExtractAndSetDataCenterConfigValue()
def test_transform_with_existing_data_center(self):
"""Test that transform exits early if data_center alrea... | TestExtractAndSetDataCenterConfigValue |
python | explosion__spaCy | spacy/lang/ti/__init__.py | {
"start": 735,
"end": 834
} | class ____(Language):
lang = "ti"
Defaults = TigrinyaDefaults
__all__ = ["Tigrinya"]
| Tigrinya |
python | pennersr__django-allauth | tests/apps/socialaccount/test_registry.py | {
"start": 297,
"end": 2012
} | class ____(TestCase):
@override_settings(
INSTALLED_APPS=[
"allauth.socialaccount.providers.facebook",
]
)
def test_load_provider_with_default_app_config(self):
registry = providers.ProviderRegistry()
provider_list = registry.get_class_list()
self.assertT... | ProviderRegistryTests |
python | davidhalter__jedi | jedi/inference/value/iterable.py | {
"start": 6508,
"end": 7682
} | class ____(LazyAttributeOverwrite, IterableMixin):
api_type = 'instance'
@property
def name(self):
return compiled.CompiledValueName(self, self.array_type)
def _get_generics(self):
return (self.merge_types_of_iterate().py__class__(),)
@inference_state_method_cache(default=())
... | Sequence |
python | getsentry__sentry | tests/sentry/utils/security/test_orgauthtoken_token.py | {
"start": 214,
"end": 2524
} | class ____(TestCase):
def test_generate_token(self) -> None:
token = generate_token("test-org", "https://test-region.sentry.io")
assert token
assert token.startswith(SENTRY_ORG_AUTH_TOKEN_PREFIX)
def test_parse_token(self) -> None:
token = generate_token("test-org", "https://te... | OrgAuthTokenTokenTest |
python | kamyu104__LeetCode-Solutions | Python/number-of-ways-to-build-house-of-cards.py | {
"start": 466,
"end": 944
} | class ____(object):
def houseOfCards(self, n):
"""
:type n: int
:rtype: int
"""
dp = [[0]*(n+1) for _ in xrange((n+1)//3+1)] # dp[t][i]: number of ways with i cards and t triangles in the first row
dp[0][0] = 1
for t in xrange(1, (n+1)//3+1):
for ... | Solution_TLE |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 142619,
"end": 145615
} | class ____(nn.Module):
"""
A modified Snake function which uses separate parameters for the magnitude of the periodic components
Shape:
- Input: (B, C, T)
- Output: (B, C, T), same shape as the input
Parameters:
- alpha - trainable parameter that controls frequency
- beta... | SnakeBeta |
python | fastai__fastai | fastai/torch_core.py | {
"start": 4745,
"end": 4954
} | class ____(ndarray):
"An `ndarray` that can modify casting behavior"
@classmethod
def _before_cast(cls, x): return x if isinstance(x,ndarray) else array(x)
# %% ../nbs/00_torch_core.ipynb 28
| ArrayBase |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/isinstance4.py | {
"start": 610,
"end": 715
} | class ____(Protocol):
pass
isinstance(4, MyProtocol2)
issubclass(str, (str, MyProtocol2))
| MyProtocol2 |
python | pytorch__pytorch | torch/onnx/_internal/fx/passes/type_promotion.py | {
"start": 47581,
"end": 50495
} | class ____(_python_dispatch.TorchDispatchMode):
"""Trace ops that were dispatched.
Utilize the dispatch mechanism in [`__torch_dispatch__`](https://dev-discuss.pytorch.org/t/what-and-why-is-torch-dispatch/557)
to trace op overloads that were dispatched to. This is used to find the compatible
op overloa... | _OpTraceDispatchMode |
python | getsentry__sentry-python | sentry_sdk/integrations/openai.py | {
"start": 1564,
"end": 25131
} | class ____(Integration):
identifier = "openai"
origin = f"auto.ai.{identifier}"
def __init__(self, include_prompts=True, tiktoken_encoding_name=None):
# type: (OpenAIIntegration, bool, Optional[str]) -> None
self.include_prompts = include_prompts
self.tiktoken_encoding = None
... | OpenAIIntegration |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 116435,
"end": 116613
} | class ____:
xlSparkScaleCustom = 3 # from enum XlSparkScale
xlSparkScaleGroup = 1 # from enum XlSparkScale
xlSparkScaleSingle = 2 # from enum XlSparkScale
| SparkScale |
python | google__pytype | pytype/tools/xref/indexer.py | {
"start": 28600,
"end": 39155
} | class ____:
"""Runs the indexer visitor and collects its results."""
def __init__(self,
*,
ast,
src,
loader,
pytd_module,
module_name):
self.ast = ast
self.source = src
self.loader = loader
self.pytd_module = ... | Indexer |
python | spack__spack | lib/spack/spack/util/ctest_log_parser.py | {
"start": 7855,
"end": 9498
} | class ____:
"""Class representing interesting events (e.g., errors) in a build log."""
def __init__(
self,
text,
line_no,
source_file=None,
source_line_no=None,
pre_context=None,
post_context=None,
):
self.text = text
self.line_no = li... | LogEvent |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/organization_workflow_stats.py | {
"start": 1075,
"end": 2163
} | class ____(OrganizationWorkflowEndpoint):
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ISSUES
@extend_schema(
operation_id="Retrieve Firing Stats for a Workflow for a Given Time Range.",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
... | OrganizationWorkflowStatsEndpoint |
python | getsentry__sentry | tests/sentry/web/frontend/test_oauth_authorize.py | {
"start": 10174,
"end": 14280
} | class ____(TestCase):
@cached_property
def path(self) -> str:
return "/oauth/authorize/"
def setUp(self) -> None:
super().setUp()
self.application = ApiApplication.objects.create(
owner=self.user, redirect_uris="https://example.com"
)
def test_missing_respon... | OAuthAuthorizeTokenTest |
python | giampaolo__psutil | tests/test_system.py | {
"start": 27129,
"end": 33693
} | class ____(PsutilTestCase):
@pytest.mark.skipif(not HAS_NET_IO_COUNTERS, reason="not supported")
def test_net_io_counters(self):
def check_ntuple(nt):
assert nt[0] == nt.bytes_sent
assert nt[1] == nt.bytes_recv
assert nt[2] == nt.packets_sent
assert nt[3] ... | TestNetAPIs |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/state.py | {
"start": 2904,
"end": 34275
} | class ____(interfaces.InspectionAttrInfo, Generic[_O]):
"""Tracks state information at the instance level.
The :class:`.InstanceState` is a key object used by the
SQLAlchemy ORM in order to track the state of an object;
it is created the moment an object is instantiated, typically
as a result of :t... | InstanceState |
python | apache__airflow | airflow-ctl/src/airflowctl/api/operations.py | {
"start": 20911,
"end": 21922
} | class ____(BaseOperations):
"""Dag run operations."""
def get(self, dag_id: str, dag_run_id: str) -> DAGRunResponse | ServerResponseError:
"""Get a dag run."""
try:
self.response = self.client.get(f"/dags/{dag_id}/dagRuns/{dag_run_id}")
return DAGRunResponse.model_valida... | DagRunOperations |
python | pytorch__pytorch | functorch/dim/__init__.py | {
"start": 12193,
"end": 12735
} | class ____(Exception):
pass
from . import op_properties
def _safe_print(*args: Any, **kwargs: Any) -> None:
"""Safe print that avoids recursive torch function dispatches."""
import sys
# Convert any torch objects to basic representations
safe_args = []
for arg in args:
if hasattr(ar... | DimensionBindError |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/plan.py | {
"start": 3047,
"end": 25131
} | class ____:
"""This is the state that is built up during the execution plan build process."""
def __init__(
self,
job_def: JobDefinition,
resolved_run_config: ResolvedRunConfig,
step_keys_to_execute: Optional[Sequence[str]],
known_state: KnownExecutionState,
inst... | _PlanBuilder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.