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 | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/selectable.py | {
"start": 150436,
"end": 150901
} | class ____(CompileState):
@util.memoized_property
def _label_resolve_dict(
self,
) -> Tuple[
Dict[str, ColumnElement[Any]],
Dict[str, ColumnElement[Any]],
Dict[str, ColumnElement[Any]],
]:
# TODO: this is hacky and slow
hacky_subquery = self.statement.subq... | CompoundSelectState |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 18813,
"end": 19219
} | class ____(StringIORewind):
def setup(self):
count_elem = 100_000
data = "a\n" + "2019-12-31\n" * count_elem
self.StringIO_input = StringIO(data)
def time_read_csv_index_col(self):
read_csv(
self.data(self.StringIO_input),
parse_dates=["a"],
e... | ReadCSVDatePyarrowEngine |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1585370,
"end": 1585542
} | class ____(sgqlc.types.Union):
"""Types that can initiate an audit log event."""
__schema__ = github_schema
__types__ = (Bot, Organization, User)
| AuditEntryActor |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 84003,
"end": 85212
} | class ____(Response):
"""
Response of tasks.add_or_update_model endpoint.
:param updated: Number of tasks updated (0 or 1)
:type updated: int
"""
_service = "tasks"
_action = "add_or_update_model"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
... | AddOrUpdateModelResponse |
python | numba__numba | numba/cpython/setobj.py | {
"start": 3481,
"end": 12301
} | class ____(object):
def __init__(self, context, builder, set_type, ptr):
payload = get_payload_struct(context, builder, set_type, ptr)
self._context = context
self._builder = builder
self._ty = set_type
self._payload = payload
self._entries = payload._get_ptr_by_name... | _SetPayload |
python | geekcomputers__Python | Industrial_developed_hangman/src/hangman/main.py | {
"start": 303,
"end": 2488
} | class ____(Enum):
"""Enum that represents switch between local and web word parsing."""
FROM_FILE = 0 # noqa: WPS115
FROM_INTERNET = 1 # noqa: WPS115
def print_wrong(text: str, print_function: Callable[[str], None]) -> None:
"""
Print styled text(red).
:parameter text: text to print.
:... | Source |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/deadcode.py | {
"start": 1673,
"end": 1890
} | class ____:
a: MyCallable
def dead_code_by_type_refinement(d: Optional[Foo]) -> None:
if d is not None:
if isinstance(d.a, MyCallable):
print("..")
else:
_test_sink(d)
| Foo |
python | doocs__leetcode | solution/3200-3299/3285.Find Indices of Stable Mountains/Solution.py | {
"start": 0,
"end": 174
} | class ____:
def stableMountains(self, height: List[int], threshold: int) -> List[int]:
return [i for i in range(1, len(height)) if height[i - 1] > threshold]
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-recharge/unit_tests/integration/streams/test_collections.py | {
"start": 409,
"end": 1584
} | class ____(StreamTestCase):
_STREAM_NAME = "collections"
@HttpMocker()
def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
self.stream_request().with_limit(250).build(),
get_stream_response(_STREAM_NAME).with_record(... | TestFullRefresh |
python | readthedocs__readthedocs.org | readthedocs/storage/rclone.py | {
"start": 4127,
"end": 6129
} | class ____(BaseRClone):
"""
RClone remote implementation for S3.
All secrets will be passed as environ variables to the rclone command.
See https://rclone.org/s3/ and https://rclone.org/s3/#configuration.
:params bucket_name: Name of the S3 bucket.
:params access_key_id: AWS access key id.
... | RCloneS3Remote |
python | ansible__ansible | lib/ansible/errors/__init__.py | {
"start": 12703,
"end": 13207
} | class ____(AnsibleAction):
"""
An action runtime skip.
This exception provides a result dictionary via the ContributesToTaskResult mixin.
"""
@property
def result_contribution(self) -> _c.Mapping[str, object]:
return self._result | dict(
skipped=True,
msg=self.m... | AnsibleActionSkip |
python | google__pytype | pytype/rewrite/flow/conditions.py | {
"start": 360,
"end": 482
} | class ____(Condition):
def __repr__(self):
return 'FALSE'
TRUE = _True()
FALSE = _False()
@_frozen_dataclass
| _False |
python | fluentpython__example-code | 20-descriptor/bulkfood/model_v5.py | {
"start": 30,
"end": 540
} | class ____: # <1>
__counter = 0
def __init__(self):
cls = self.__class__
prefix = cls.__name__
index = cls.__counter
self.storage_name = '_{}#{}'.format(prefix, index)
cls.__counter += 1
def __get__(self, instance, owner):
if instance is None:
r... | AutoStorage |
python | pytorch__pytorch | torch/nn/modules/loss.py | {
"start": 87856,
"end": 96445
} | class ____(_Loss):
r"""The Connectionist Temporal Classification loss.
Calculates loss between a continuous (unsegmented) time series and a target sequence. CTCLoss sums over the
probability of possible alignments of input to target, producing a loss value which is differentiable
with respect to each i... | CTCLoss |
python | doocs__leetcode | solution/2200-2299/2291.Maximum Profit From Trading Stocks/Solution.py | {
"start": 0,
"end": 445
} | class ____:
def maximumProfit(self, present: List[int], future: List[int], budget: int) -> int:
f = [[0] * (budget + 1) for _ in range(len(present) + 1)]
for i, w in enumerate(present, 1):
for j in range(budget + 1):
f[i][j] = f[i - 1][j]
if j >= w and fut... | Solution |
python | getsentry__sentry | tests/sentry/releases/endpoints/test_organization_release_details.py | {
"start": 28109,
"end": 45139
} | class ____(APITestCase):
@patch("sentry.tasks.commits.fetch_commits")
def test_simple(self, mock_fetch_commits: MagicMock) -> None:
user = self.create_user(is_staff=False, is_superuser=False)
org = self.organization
org.flags.allow_joinleave = False
org.save()
repo = Rep... | UpdateReleaseDetailsTest |
python | huggingface__transformers | src/transformers/models/ernie4_5/modeling_ernie4_5.py | {
"start": 15508,
"end": 18653
} | class ____(Ernie4_5PreTrainedModel):
def __init__(self, config: Ernie4_5Config):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
self... | Ernie4_5Model |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 22015,
"end": 22426
} | class ____(ProjectAdminMixin, PrivateViewMixin):
form_class = EmailHookForm
def get_success_url(self):
return reverse(
"projects_notifications",
args=[self.get_project().slug],
)
def get_form(self, data=None, files=None, **kwargs):
kwargs["project"] = self.g... | ProjectNotificationsMixin |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 16567,
"end": 17022
} | class ____(Token):
""" Represents a goto statement in Fortran
Examples
========
>>> from sympy.codegen.fnodes import GoTo
>>> go = GoTo([10, 20, 30], 'i')
>>> from sympy import fcode
>>> fcode(go, source_format='free')
'go to (10, 20, 30), i'
"""
__slots__ = _fields = ('labels... | GoTo |
python | pypa__pip | src/pip/_vendor/rich/console.py | {
"start": 7617,
"end": 7847
} | class ____(Protocol):
"""An object that may be 'cast' to a console renderable."""
def __rich__(
self,
) -> Union["ConsoleRenderable", "RichCast", str]: # pragma: no cover
...
@runtime_checkable
| RichCast |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/class_interval.py | {
"start": 10570,
"end": 10872
} | class ____(A23):
def m1(self, a):
return add_feature_e(a)
def issue_precise_tito_intervals(b: B23):
# False positive: Should see feature_c and feature_d but not feature_e, due to distinguishing
# the breadcrumbs from different tito intervals
_test_sink(b.m0(_test_source()))
| E23 |
python | google__pytype | pytype/tests/test_utils.py | {
"start": 8274,
"end": 8623
} | class ____:
"""Match a sequence of substrings in order."""
def __init__(self, seq):
self.seq = seq
def match(self, message):
start = 0
for s in self.seq:
i = message.find(s, start)
if i == -1:
return False
start = i + len(s)
return True
def __repr__(self):
return... | SequenceMatcher |
python | davidhalter__jedi | jedi/inference/compiled/subprocess/__main__.py | {
"start": 372,
"end": 1076
} | class ____(MetaPathFinder):
def __init__(self, path_dct):
self._path_dct = path_dct
def find_spec(self, fullname, path=None, target=None):
if path is None and fullname in self._path_dct:
p = self._path_dct[fullname]
spec = PathFinder.find_spec(fullname, path=[p], target=... | _ExactImporter |
python | openai__openai-python | src/openai/resources/evals/runs/runs.py | {
"start": 23611,
"end": 24359
} | class ____:
def __init__(self, runs: AsyncRuns) -> None:
self._runs = runs
self.create = async_to_streamed_response_wrapper(
runs.create,
)
self.retrieve = async_to_streamed_response_wrapper(
runs.retrieve,
)
self.list = async_to_streamed_resp... | AsyncRunsWithStreamingResponse |
python | pydata__xarray | xarray/namedarray/parallelcompat.py | {
"start": 921,
"end": 6172
} | class ____(Protocol):
def rechunk(self, chunks: Any, **kwargs: Any) -> Any: ...
@property
def dtype(self) -> np.dtype[Any]: ...
@property
def chunks(self) -> _NormalizedChunks: ...
def compute(
self, *data: Any, **kwargs: Any
) -> tuple[np.ndarray[Any, _DType_co], ...]: ...
T_Ch... | ChunkedArrayMixinProtocol |
python | falconry__falcon | tests/test_headers.py | {
"start": 8373,
"end": 8652
} | class ____:
def on_get(self, req, resp):
resp.media = {
'raw': req.headers,
'lower': req.headers_lower,
}
def on_get_header(self, req, resp, header):
resp.media = {header.lower(): req.get_header(header)}
| HeadersDebugResource |
python | walkccc__LeetCode | solutions/2005. Subtree Removal Game with Fibonacci Tree/2005.py | {
"start": 0,
"end": 82
} | class ____:
def findGameWinner(self, n: int) -> bool:
return n % 6 != 1
| Solution |
python | pandas-dev__pandas | web/tests/test_pandas_web.py | {
"start": 147,
"end": 2154
} | class ____:
def __init__(self, status_code: int, response: dict) -> None:
self.status_code = status_code
self._resp = response
def json(self):
return self._resp
@staticmethod
def raise_for_status() -> None:
return
@pytest.fixture
def context() -> dict:
return {
... | MockResponse |
python | huggingface__transformers | src/transformers/models/jetmoe/modeling_jetmoe.py | {
"start": 12024,
"end": 18917
} | class ____(nn.Module):
"""
A Sparsely gated mixture of attention layer with pairs of query- and output-projections as experts.
Args:
config:
Configuration object with model hyperparameters.
"""
def __init__(self, config: JetMoeConfig):
super().__init__()
self.n... | JetMoeMoA |
python | pytorch__pytorch | test/distributed/test_dynamo_distributed.py | {
"start": 4262,
"end": 4790
} | class ____(torch.nn.Module):
def __init__(self, device):
super().__init__()
self.linear = torch.nn.Linear(1, 1)
self.__dict__["forced_linear"] = torch.nn.Linear(1, 1).to(device=device)
self.counter = 0
def forward(self, x):
self.counter += 1
return x * self.linea... | ForcedGetAttrMod |
python | PyCQA__pylint | tests/functional/m/method_hidden.py | {
"start": 1883,
"end": 1964
} | class ____(Parent):
def _protected(self): # [method-hidden]
pass
| Child |
python | scrapy__scrapy | tests/test_scheduler.py | {
"start": 9662,
"end": 9789
} | class ____(
DownloaderAwareSchedulerTestMixin, TestSchedulerInMemoryBase
):
pass
| TestSchedulerWithDownloaderAwareInMemory |
python | dask__distributed | distributed/dashboard/components/shared.py | {
"start": 15563,
"end": 20315
} | class ____(DashboardComponent):
def __init__(self, worker, height=150, last_count=None, **kwargs):
self.worker = worker
names = worker.monitor.quantities
self.last_count = 0
if last_count is not None:
names = worker.monitor.range_query(start=last_count)
self.... | SystemMonitor |
python | openai__openai-python | src/openai/_exceptions.py | {
"start": 3490,
"end": 3620
} | class ____(APIStatusError):
status_code: Literal[404] = 404 # pyright: ignore[reportIncompatibleVariableOverride]
| NotFoundError |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/dataplex.py | {
"start": 86025,
"end": 88637
} | class ____(GoogleBaseAsyncHook):
"""
Asynchronous Hook for Google Cloud Dataplex APIs.
All the methods in the hook where project_id is used must be called with
keyword arguments rather than positional.
"""
sync_hook_class = DataplexHook
def __init__(
self,
gcp_conn_id: str... | DataplexAsyncHook |
python | getsentry__sentry | src/sentry/new_migrations/monkey/models.py | {
"start": 373,
"end": 3905
} | class ____(DeleteModel):
def __init__(self, *args, deletion_action: DeletionAction, **kwargs):
super().__init__(*args, **kwargs)
self.deletion_action = deletion_action
def state_forwards(self, app_label: str, state: SentryProjectState) -> None: # type: ignore[override]
if self.deletion... | SafeDeleteModel |
python | ansible__ansible | test/units/parsing/yaml/test_dumper.py | {
"start": 1512,
"end": 4437
} | class ____(unittest.TestCase, YamlTestUtils):
def setUp(self):
self.vault_password = "hunter42"
vault_secret = TextVaultSecret(self.vault_password)
self.vault_secrets = [('vault_secret', vault_secret)]
self.good_vault = vault.VaultLib(self.vault_secrets)
self.vault = self.goo... | TestAnsibleDumper |
python | walkccc__LeetCode | solutions/2311. Longest Binary Subsequence Less Than or Equal to K/2311.py | {
"start": 0,
"end": 353
} | class ____:
def longestSubsequence(self, s: str, k: int) -> int:
oneCount = 0
num = 0
pow = 1
# Take as many 1s as possible from the right.
for i in reversed(range(len(s))):
if num + pow > k:
break
if s[i] == '1':
oneCount += 1
num += pow
pow *= 2
re... | Solution |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_quote_name10.py | {
"start": 314,
"end": 1510
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("quote_name10.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got... | TestCompareXLSXFiles |
python | wandb__wandb | tests/system_tests/test_launch/test_launch_kubernetes.py | {
"start": 7904,
"end": 8060
} | class ____(dict):
# use a dict to mock an object
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
| MockDict |
python | huggingface__transformers | src/transformers/models/patchtst/modeling_patchtst.py | {
"start": 35777,
"end": 37319
} | class ____(ModelOutput):
r"""
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
MSE loss.
prediction_outputs (`torch.FloatTensor` of shape `(batch_size, prediction_length, -1)`):
Prediction outputs of the time series modeling heads.
attentions (`... | PatchTSTForPredictionOutput |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/agent.py | {
"start": 11176,
"end": 11453
} | class ____(BaseOutputParser[AgentAction | AgentFinish]):
"""Base class for parsing agent output into agent action/finish."""
@abstractmethod
def parse(self, text: str) -> AgentAction | AgentFinish:
"""Parse text into agent action/finish."""
| AgentOutputParser |
python | huggingface__transformers | src/transformers/models/bark/configuration_bark.py | {
"start": 5893,
"end": 6924
} | class ____(BarkSubModelConfig):
model_type = "coarse_acoustics"
base_config_key = "coarse_acoustics_config"
@add_start_docstrings(
BARK_SUBMODELCONFIG_START_DOCSTRING.format(config="BarkFineConfig", model="BarkFineModel"),
"""
n_codes_total (`int`, *optional*, defaults to 8):
The t... | BarkCoarseConfig |
python | allegroai__clearml | clearml/config/__init__.py | {
"start": 1505,
"end": 8626
} | class ____(object):
_config_sdk = None
@classmethod
def _init(cls) -> None:
if cls._config_sdk is None:
cls._config_sdk = ConfigWrapper.get("sdk")
@classmethod
def get(cls, *args: Any, **kwargs: Any) -> Any:
cls._init()
return cls._config_sdk.get(*args, **kwargs... | ConfigSDKWrapper |
python | pytorch__pytorch | test/jit/test_dataclasses.py | {
"start": 959,
"end": 1018
} | class ____(Enum):
A = 1
B = 2
@dataclass
| MixupScheme2 |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_to_tensor_op_test.py | {
"start": 3268,
"end": 30237
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
def testDocStringExamples(self):
"""Example from ragged_to_tensor.__doc__."""
rt = ragged_factory_ops.constant([[9, 8, 7], [], [6, 5], [4]])
dt = rt.to_tensor()
self.assertAllEqual(dt, [[9, 8, 7], [0, 0... | RaggedTensorToTensorOpTest |
python | cython__cython | Cython/Plex/Regexps.py | {
"start": 6310,
"end": 6789
} | class ____(RE):
"""
RawNewline is a low-level RE which matches a newline character.
For internal use only.
"""
nullable = 0
match_nl = 1
def build_machine(self, m, initial_state, final_state, match_bol, nocase):
if match_bol:
initial_state = self.build_opt(m, initial_sta... | _RawNewline |
python | numba__numba | numba/core/bytecode.py | {
"start": 1752,
"end": 8571
} | class ____(object):
'''
Attributes
----------
- offset:
byte offset of opcode
- opcode:
opcode integer value
- arg:
instruction arg
- lineno:
-1 means unknown
'''
__slots__ = 'offset', 'next', 'opcode', 'opname', 'arg', 'lineno'
def __init__(self,... | ByteCodeInst |
python | Textualize__textual | docs/examples/guide/screens/questions01.py | {
"start": 703,
"end": 1142
} | class ____(App):
"""Demonstrates wait_for_dismiss"""
CSS_PATH = "questions01.tcss"
@work # (3)!
async def on_mount(self) -> None:
if await self.push_screen_wait( # (4)!
QuestionScreen("Do you like Textual?"),
):
self.notify("Good answer!")
else:
... | QuestionsApp |
python | pytorch__pytorch | torch/_dynamo/variables/streams.py | {
"start": 12304,
"end": 16799
} | class ____(VariableTracker):
def __init__(
self,
proxy: Proxy,
value: torch.Event,
user_object_index: Optional[int],
**kwargs: Any,
) -> None:
if proxy is not None and "example_value" in proxy.node.meta:
assert proxy.node.meta["example_value"] == value... | EventVariable |
python | plotly__plotly.py | _plotly_utils/basevalidators.py | {
"start": 34573,
"end": 44440
} | class ____(BaseValidator):
"""
"color": {
"description": "A string describing color. Supported formats:
- hex (e.g. '#d3d3d3')
- rgb (e.g. 'rgb(255, 0, 0)')
- rgba (e.g. 'rgb(255, 0, 0, 0.5)')
- hsl (e.g. 'hs... | ColorValidator |
python | pyca__cryptography | tests/x509/test_x509.py | {
"start": 20964,
"end": 27702
} | class ____:
def test_revoked_basics(self, backend):
crl = _load_cert(
os.path.join("x509", "custom", "crl_all_reasons.pem"),
x509.load_pem_x509_crl,
)
for i, rev in enumerate(crl):
assert isinstance(rev, x509.RevokedCertificate)
assert isinsta... | TestRevokedCertificate |
python | fastapi__sqlmodel | docs_src/tutorial/relationship_attributes/create_and_update_relationships/tutorial001.py | {
"start": 330,
"end": 3364
} | class ____(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
team_id: Optional[int] = Field(default=None, foreign_key="team.id")
team: Optional[Team] = Relationship... | Hero |
python | huggingface__transformers | src/transformers/models/blenderbot_small/modeling_blenderbot_small.py | {
"start": 42571,
"end": 50095
} | class ____(BlenderbotSmallPreTrainedModel, GenerationMixin):
base_model_prefix = "model"
_keys_to_ignore_on_load_missing = ["final_logits_bias"]
_tied_weights_keys = {
"lm_head.weight": "model.shared.weight",
}
def __init__(self, config: BlenderbotSmallConfig):
super().__init__(conf... | BlenderbotSmallForConditionalGeneration |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 6403,
"end": 6934
} | class ____(Rule):
"""Apply PartsRule multiple times to integrate exp(x)*sin(x)"""
parts_rules: list[PartsRule]
coefficient: Expr
def eval(self) -> Expr:
result = []
sign = 1
for rule in self.parts_rules:
result.append(sign * rule.u * rule.v_step.eval())
s... | CyclicPartsRule |
python | pytorch__pytorch | torch/testing/_internal/distributed/common_state_dict.py | {
"start": 6293,
"end": 6725
} | class ____(FusionEmbeddingWithHook):
# _fqn_modifiers is a private function as a contract between DSD. When users change the state_dict
# keys, they need to provide a mapping from the new key to the original key. This is used to ensure
# consistency between the state_dict keys and fqn.
def _fqn_modifier... | FusionEmbeddingWithModifier |
python | pikepdf__pikepdf | src/pikepdf/_methods.py | {
"start": 27707,
"end": 28165
} | class ____:
def keys(self):
return KeysView(self._as_map())
def values(self):
return ValuesView(self._as_map())
def items(self):
return ItemsView(self._as_map())
get = MutableMapping.get
pop = MutableMapping.pop
popitem = MutableMapping.popitem
clear = MutableMappi... | Extend_NumberTree |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataproc.py | {
"start": 158807,
"end": 161397
} | class ____:
@mock.patch(DATAPROC_PATH.format("DataprocHook"))
def test_execute(self, mock_hook):
op = DataprocDiagnoseClusterOperator(
task_id=TASK_ID,
region=GCP_REGION,
project_id=GCP_PROJECT,
cluster_name=CLUSTER_NAME,
gcp_conn_id=GCP_CONN_I... | TestDataprocDiagnoseClusterOperator |
python | doocs__leetcode | solution/1000-1099/1053.Previous Permutation With One Swap/Solution.py | {
"start": 0,
"end": 405
} | class ____:
def prevPermOpt1(self, arr: List[int]) -> List[int]:
n = len(arr)
for i in range(n - 1, 0, -1):
if arr[i - 1] > arr[i]:
for j in range(n - 1, i - 1, -1):
if arr[j] < arr[i - 1] and arr[j] != arr[j - 1]:
arr[i - 1], a... | Solution |
python | matplotlib__matplotlib | lib/matplotlib/backend_bases.py | {
"start": 136172,
"end": 136409
} | class ____(_Backend):
"""
Simple base class to generate a ``show()`` function in backends.
Subclass must override ``mainloop()`` method.
"""
def __call__(self, block=None):
return self.show(block=block)
| ShowBase |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_button01.py | {
"start": 315,
"end": 805
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("button01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_file... | TestCompareXLSXFiles |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_format14.py | {
"start": 315,
"end": 1590
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_format14.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = ... | TestCompareXLSXFiles |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataproc_metastore.py | {
"start": 9463,
"end": 11124
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
@mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.MetadataExport")
@mock.patch(
"airflow.providers.google.cloud.operators.dataproc_metastore"
".DataprocMetastor... | TestDataprocMetastoreExportMetadataOperator |
python | google__pytype | pytype/abstract/_pytd_function.py | {
"start": 1307,
"end": 1699
} | class ____(Exception):
"""Raise an error for invalid signature mutation in a pyi file."""
def __init__(self, pytd_sig: "PyTDSignature"):
self.pytd_sig = pytd_sig
def _is_literal(annot: _base.BaseValue | None) -> bool:
if isinstance(annot, _typing.Union):
return all(_is_literal(o) for o in annot.options... | SignatureMutationError |
python | walkccc__LeetCode | solutions/1615. Maximal Network Rank/1615.py | {
"start": 0,
"end": 2244
} | class ____:
def maximalNetworkRank(self, n: int, roads: list[list[int]]) -> int:
degrees = [0] * n
for u, v in roads:
degrees[u] += 1
degrees[v] += 1
# Find the first maximum and the second maximum degrees.
maxDegree1 = 0
maxDegree2 = 0
for degree in degrees:
if degree > ma... | Solution |
python | great-expectations__great_expectations | great_expectations/checkpoint/actions.py | {
"start": 10452,
"end": 17954
} | class ____(DataDocsAction):
"""Sends a Slack notification to a given webhook.
```yaml
- name: send_slack_notification_on_validation_result
action:
class_name: SlackNotificationAction
# put the actual webhook URL in the uncommitted/config_variables.yml file
# or pass in as environment ... | SlackNotificationAction |
python | run-llama__llama_index | llama-index-core/llama_index/core/llama_dataset/rag.py | {
"start": 2685,
"end": 3697
} | class ____(BaseLlamaPredictionDataset):
"""RagDataset class."""
_prediction_type = RagExamplePrediction
def to_pandas(self) -> Any:
"""Create pandas dataframe."""
try:
import pandas as pd
except ImportError:
raise ImportError(
"pandas is requ... | RagPredictionDataset |
python | allegroai__clearml | clearml/utilities/dicts.py | {
"start": 3421,
"end": 5878
} | class ____(dict):
@property
def pip(self) -> Optional[Any]:
return self.get("pip")
@property
def conda(self) -> Optional[Any]:
return self.get("conda")
@property
def orig_pip(self) -> Optional[Any]:
return self.get("orig_pip")
def merge_dicts(dict1: dict, dict2: dict)... | RequirementsDict |
python | wandb__wandb | wandb/vendor/pygments/lexer.py | {
"start": 8824,
"end": 9031
} | class ____(object):
"""
Indicates the a state should inherit from its superclass.
"""
def __repr__(self):
return 'inherit'
inherit = _inherit() # pylint: disable=invalid-name
| _inherit |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/expressions/base.py | {
"start": 4327,
"end": 6419
} | class ____:
# NamedExpr does not inherit from Expr since it does not appear
# when evaluating expressions themselves, only when constructing
# named return values in dataframe (IR) nodes.
__slots__ = ("name", "value")
value: Expr
name: str
def __init__(self, name: str, value: Expr) -> None:... | NamedExpr |
python | justquick__django-activity-stream | actstream/feeds.py | {
"start": 8265,
"end": 8485
} | class ____:
def items(self, request, *args, **kwargs):
return self.get_stream()(
self.get_object(request, *args, **kwargs),
**self.get_stream_kwargs(request)
)
| StreamKwargsMixin |
python | huggingface__transformers | src/transformers/models/qwen3_next/modeling_qwen3_next.py | {
"start": 43005,
"end": 44435
} | class ____(PreTrainedModel):
config: Qwen3NextConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["Qwen3NextDecoderLayer"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn_2 = True
_supports_sdpa = True
_keys_to_ignore_on_loa... | Qwen3NextPreTrainedModel |
python | urllib3__urllib3 | test/with_dummyserver/test_socketlevel.py | {
"start": 76730,
"end": 78281
} | class ____(SocketDummyServerTestCase):
def _test_broken_header_parsing(
self, headers: list[bytes], unparsed_data_check: str | None = None
) -> None:
self.start_response_handler(
(
b"HTTP/1.1 200 OK\r\n"
b"Content-Length: 0\r\n"
b"Conte... | TestBrokenHeaders |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/entities/snippets.py | {
"start": 4923,
"end": 5334
} | class ____(ndb.Expando):
pass
def create_entity_using_expando_model():
e = Mine()
e.foo = 1
e.bar = "blah"
e.tags = ["exp", "and", "oh"]
e.put()
return e
def get_properties_defined_on_expando(e):
return e._properties
# {
# 'foo': GenericProperty('foo'),
# 'bar': ... | Mine |
python | weaviate__weaviate-python-client | weaviate/collections/queries/near_media/query/sync.py | {
"start": 308,
"end": 449
} | class ____(
Generic[Properties, References],
_NearMediaQueryExecutor[ConnectionSync, Properties, References],
):
pass
| _NearMediaQuery |
python | django__django | django/db/models/fields/reverse_related.py | {
"start": 9862,
"end": 10656
} | class ____(ManyToOneRel):
"""
Used by OneToOneField to store information about the relation.
``_meta.get_fields()`` returns this class to provide access to the field
flags for the reverse relation.
"""
def __init__(
self,
field,
to,
field_name,
related_n... | OneToOneRel |
python | django__django | django/forms/fields.py | {
"start": 13959,
"end": 15976
} | class ____(IntegerField):
default_error_messages = {
"invalid": _("Enter a number."),
}
def __init__(
self,
*,
max_value=None,
min_value=None,
max_digits=None,
decimal_places=None,
**kwargs,
):
self.max_digits, self.decimal_places ... | DecimalField |
python | python__mypy | mypyc/test-data/fixtures/ir.py | {
"start": 12300,
"end": 12519
} | class ____(Iterable[int]):
def __init__(self, x: int, y: int = ..., z: int = ...) -> None: pass
def __iter__(self) -> Iterator[int]: pass
def __len__(self) -> int: pass
def __next__(self) -> int: pass
| range |
python | pytorch__pytorch | test/jit/test_list_dict.py | {
"start": 66591,
"end": 73253
} | class ____(JitTestCase):
def test_namedtuple(self):
class FeatureVector(NamedTuple):
float_features: float
sequence_features: List[float]
time_since_first: float
@torch.jit.script
def foo(x) -> float:
fv = FeatureVector(3.0, [3.0], 3.0)
... | TestNamedTuple |
python | keras-team__keras | keras/src/layers/rnn/conv_lstm1d_test.py | {
"start": 160,
"end": 2838
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_basics(self):
channels_last = backend.config.image_data_format() == "channels_last"
self.run_layer_test(
layers.ConvLSTM1D,
init_kwargs={"filters": 5, "kernel_size": 3, "padding": "same"},
... | ConvLSTM1DTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/response_synthesizers/no_text.py | {
"start": 220,
"end": 796
} | class ____(BaseSynthesizer):
def _get_prompts(self) -> PromptDictType:
"""Get prompts."""
return {}
def _update_prompts(self, prompts: PromptDictType) -> None:
"""Update prompts."""
def get_response(
self,
query_str: str,
text_chunks: Sequence[str],
... | NoText |
python | celery__celery | t/unit/events/test_snapshot.py | {
"start": 2262,
"end": 3359
} | class ____:
class MockReceiver:
raise_keyboard_interrupt = False
def capture(self, **kwargs):
if self.__class__.raise_keyboard_interrupt:
raise KeyboardInterrupt()
class MockEvents(Events):
def Receiver(self, *args, **kwargs):
return test_evcam... | test_evcam |
python | django__django | tests/delete_regress/models.py | {
"start": 3432,
"end": 3793
} | class ____(models.Model):
name = models.CharField(max_length=32)
lives_in = models.ForeignKey(House, models.CASCADE)
class Meta:
ordering = ["name"]
def get_best_toy():
toy, _ = Toy.objects.get_or_create(name="best")
return toy
def get_worst_toy():
toy, _ = Toy.objects.get_or_create... | OrderedPerson |
python | apache__airflow | providers/teradata/tests/unit/teradata/transfers/test_teradata_to_teradata.py | {
"start": 1439,
"end": 4285
} | class ____:
dest_teradata_conn_id = "dest_teradata_conn_id"
destination_table = "destination_table"
source_teradata_conn_id = "source_teradata_conn_id"
sql = (r"""select DATE where DATE > {{ sql_params.ref_date }} ;""",)
sql_params = {"ref_date": "2018-01-01"}
def test_source_hook(self):
... | TestTeradataToTeradataTransfer |
python | pennersr__django-allauth | allauth/socialaccount/providers/basecamp/provider.py | {
"start": 404,
"end": 1263
} | class ____(OAuth2Provider):
id = "basecamp"
name = "Basecamp"
account_class = BasecampAccount
oauth2_adapter_class = BasecampOAuth2Adapter
def get_auth_params_from_request(self, request, action):
data = super().get_auth_params_from_request(request, action)
data["type"] = "web_server... | BasecampProvider |
python | pypa__pip | src/pip/_vendor/rich/console.py | {
"start": 16535,
"end": 16743
} | class ____(threading.local):
"""Thread local values for Console context."""
theme_stack: ThemeStack
buffer: List[Segment] = field(default_factory=list)
buffer_index: int = 0
| ConsoleThreadLocals |
python | pandas-dev__pandas | asv_bench/benchmarks/join_merge.py | {
"start": 8841,
"end": 9785
} | class ____:
params = [
[
"Int64",
"Int32",
"Int16",
"UInt64",
"UInt32",
"UInt16",
"Float64",
"Float32",
],
[True, False],
]
param_names = ["dtype", "monotonic"]
def setup(self, dtype,... | MergeEA |
python | ray-project__ray | python/ray/dashboard/modules/aggregator/publisher/ray_event_publisher.py | {
"start": 993,
"end": 1441
} | class ____(ABC):
"""Abstract interface for publishing Ray event batches to external destinations."""
@abstractmethod
async def run_forever(self) -> None:
"""Run the publisher forever until cancellation or process death."""
pass
@abstractmethod
async def wait_until_running(self, tim... | RayEventPublisherInterface |
python | pyinstaller__pyinstaller | tests/unit/test_pyimodulegraph.py | {
"start": 2639,
"end": 8309
} | class ____(analysis.PyiModuleGraph):
def _analyze_base_modules(self):
# suppress this to speed up set-up
self._base_modules = ()
@pytest.fixture
def fresh_pyi_modgraph(monkeypatch):
"""
Get a fresh PyiModuleGraph
"""
def fake_base_modules(self):
# speed up set up
se... | FakePyiModuleGraph |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-cloudflare-ai-gateway/llama_index/llms/cloudflare_ai_gateway/base.py | {
"start": 1307,
"end": 2157
} | class ____(BaseModel):
"""Options for Cloudflare AI Gateway requests."""
cache_key: Optional[str] = Field(default=None, description="Custom cache key")
cache_ttl: Optional[int] = Field(
default=None, ge=0, description="Cache time-to-live in seconds"
)
skip_cache: bool = Field(default=False,... | CloudflareAIGatewayOptions |
python | pytorch__pytorch | torch/_inductor/codegen/cuda/cutlass_lib_extensions/cutlass_mock_imports/cuda/cuda.py | {
"start": 204,
"end": 314
} | class ____:
pass
def cuDeviceGetCount():
return (CUresult.CUDA_SUCCESS, torch.cuda.device_count())
| nvrtc |
python | tox-dev__tox | src/tox/session/state.py | {
"start": 441,
"end": 1712
} | class ____:
"""Runtime state holder."""
def __init__(self, options: Options, args: Sequence[str]) -> None:
(extended_envs,) = tee(chain.from_iterable(MANAGER.tox_extend_envs()), 1)
self.conf = Config.make(options.parsed, options.pos_args, options.source, extended_envs)
self.conf.core.ad... | State |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/GradientEditorItem.py | {
"start": 767,
"end": 14399
} | class ____(GraphicsWidget):
## public class
"""**Bases:** :class:`GraphicsWidget <pyqtgraph.GraphicsWidget>`
A rectangular item with tick marks along its length that can (optionally) be moved by the user."""
sigTicksChanged = QtCore.Signal(object)
sigTicksChangeFinished = QtCore.Signal(obj... | TickSliderItem |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_nbagg.py | {
"start": 1558,
"end": 2026
} | class ____(NavigationToolbar2WebAgg):
# Use the standard toolbar items + download button
toolitems = [(text, tooltip_text,
_FONT_AWESOME_CLASSES[image_file], name_of_method)
for text, tooltip_text, image_file, name_of_method
in (NavigationToolbar2.toolitems +... | NavigationIPy |
python | spack__spack | lib/spack/spack/oci/opener.py | {
"start": 1989,
"end": 5913
} | class ____:
__slots__ = ["scheme", "params"]
def __init__(
self, scheme: Optional[str] = None, params: Optional[List[Tuple[str, str]]] = None
) -> None:
self.scheme = scheme or ""
self.params = params or []
def __repr__(self) -> str:
return f"Challenge({self.scheme}, {s... | Challenge |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/name_conflict/__init__.py | {
"start": 23,
"end": 94
} | class ____:
"""docstring of target.name_conflict::foo."""
pass
| foo |
python | getsentry__sentry | src/sentry/sentry_apps/api/endpoints/sentry_internal_app_tokens.py | {
"start": 1155,
"end": 3974
} | class ____(SentryAppBaseEndpoint):
owner = ApiOwner.INTEGRATIONS
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
authentication_classes = (SessionNoAuthTokenAuthentication,)
permission_classes = (SentryInternalAppTokenPermission,)
def get(... | SentryInternalAppTokensEndpoint |
python | openai__openai-python | src/openai/types/beta/threads/runs/run_step.py | {
"start": 486,
"end": 838
} | class ____(BaseModel):
code: Literal["server_error", "rate_limit_exceeded"]
"""One of `server_error` or `rate_limit_exceeded`."""
message: str
"""A human-readable description of the error."""
StepDetails: TypeAlias = Annotated[
Union[MessageCreationStepDetails, ToolCallsStepDetails], PropertyInfo... | LastError |
python | kamyu104__LeetCode-Solutions | Python/check-if-digits-are-equal-in-string-after-operations-i.py | {
"start": 55,
"end": 1000
} | class ____(object):
def hasSameDigits(self, s):
"""
:type s: str
:rtype: bool
"""
def check(mod):
def decompose(x, mod): # x = a * mod^cnt
cnt = 0
while x > 1 and x%mod == 0:
x //= mod
cnt +=... | Solution |
python | tensorflow__tensorflow | tensorflow/tools/docs/fenced_doctest_lib.py | {
"start": 2580,
"end": 7995
} | class ____(doctest.DocTestParser):
"""Implements test parsing for ``` fenced cells.
https://docs.python.org/3/library/doctest.html#doctestparser-objects
The `get_examples` method receives a string and returns an
iterable of `doctest.Example` objects.
"""
patched = False
def __init__(self, fence_label='... | FencedCellParser |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.