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 | ansible__ansible | lib/ansible/_internal/_collection_proxy.py | {
"start": 103,
"end": 1154
} | class ____[T](_c.Sequence[T]):
"""A read-only sequence proxy."""
# DTFIX5: needs unit test coverage
__slots__ = ('__value',)
def __init__(self, value: _c.Sequence[T]) -> None:
self.__value = value
@_t.overload
def __getitem__(self, index: int) -> T: ...
@_t.overload
def __ge... | SequenceProxy |
python | getsentry__sentry | src/sentry/models/options/option.py | {
"start": 2226,
"end": 2439
} | class ____(BaseOption):
__relocation_scope__ = RelocationScope.Config
class Meta:
app_label = "sentry"
db_table = "sentry_controloption"
__repr__ = sane_repr("key", "value")
| ControlOption |
python | apache__airflow | providers/google/tests/unit/google/cloud/utils/test_credentials_provider.py | {
"start": 23831,
"end": 24303
} | class ____:
def test_get_scopes_with_default(self):
assert _get_scopes() == _DEFAULT_SCOPES
@pytest.mark.parametrize(
("scopes_str", "scopes"),
[
pytest.param("scope1", ["scope1"], id="single-scope"),
pytest.param("scope1,scope2", ["scope1", "scope2"], id="multip... | TestGetScopes |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_simplify/SIM115.py | {
"start": 5750,
"end": 6057
} | class ____(TestCase):
@classmethod
def setUpClass(cls):
cls.enterClassContext(open("filename"))
# OK
async def foo():
class ExampleAsyncTests(IsolatedAsyncioTestCase):
async def test_something(self):
await self.enterAsyncContext(open("filename"))
# OK
| ExampleClassTests |
python | chroma-core__chroma | chromadb/server/fastapi/__init__.py | {
"start": 5879,
"end": 74567
} | class ____(Server):
def __init__(self, settings: Settings):
ProductTelemetryClient.SERVER_CONTEXT = ServerContext.FASTAPI
# https://fastapi.tiangolo.com/advanced/custom-response/#use-orjsonresponse
self._app = fastapi.FastAPI(debug=True, default_response_class=ORJSONResponse)
self._s... | FastAPI |
python | pytorch__pytorch | test/distributed/_composable/test_composability/test_pp_composability.py | {
"start": 2228,
"end": 2610
} | class ____(torch.nn.Module):
def __init__(self, d_hid: int):
super().__init__()
self.net1 = nn.Linear(d_hid, d_hid)
self.net2 = nn.Linear(d_hid, d_hid)
self.net3 = nn.Linear(d_hid, d_hid * 2)
def forward(self, x):
x = F.relu(self.net1(x))
x = F.relu(self.net2(x))... | MLPModuleEven |
python | openai__gym | gym/envs/mujoco/reacher.py | {
"start": 111,
"end": 2190
} | class ____(MuJocoPyEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
],
"render_fps": 50,
}
def __init__(self, **kwargs):
utils.EzPickle.__init__(self, **kwargs)
observation_space = Box(low=-... | ReacherEnv |
python | numba__numba | numba/tests/test_ssa.py | {
"start": 962,
"end": 5733
} | class ____(SSABaseTest):
"""
Contains tests to help isolate problems in SSA
"""
def test_argument_name_reused(self):
@njit
def foo(x):
x += 1
return x
self.check_func(foo, 123)
def test_if_else_redefine(self):
@njit
def foo(x, y):
... | TestSSA |
python | milvus-io__pymilvus | pymilvus/orm/mutation.py | {
"start": 619,
"end": 1961
} | class ____:
def __init__(self, mr: Any) -> None:
self._mr = mr
@property
def primary_keys(self):
return self._mr.primary_keys if self._mr else []
@property
def insert_count(self):
return self._mr.insert_count if self._mr else 0
@property
def delete_count(self):
... | MutationResult |
python | getsentry__sentry | src/sentry/api/serializers/models/project.py | {
"start": 10454,
"end": 11373
} | class ____(_ProjectSerializerOptionalBaseResponse):
id: str
slug: str
name: str # TODO: add deprecation about this field (not used in app)
platform: str | None
dateCreated: datetime
isBookmarked: bool
isMember: bool
features: list[str]
firstEvent: datetime | None
firstTransactio... | ProjectSerializerBaseResponse |
python | pytorch__pytorch | torch/distributed/fsdp/wrap.py | {
"start": 21606,
"end": 23154
} | class ____:
"""
Helper class to wrap modules based on default config args via a context manager.
See :func:`enable_wrap` for more information.
"""
in_autowrap_context: bool = False # Context flag
wrapper_cls: Optional[Callable] = None # The wrapper class
kwargs: dict[str, Any] = {} # Wra... | _ConfigAutoWrap |
python | openai__openai-python | src/openai/types/responses/input_token_count_params.py | {
"start": 4206,
"end": 5498
} | class ____(TypedDict, total=False):
format: ResponseFormatTextConfigParam
"""An object specifying the format that the model must output.
Configuring `{ "type": "json_schema" }` enables Structured Outputs, which
ensures the model will match your supplied JSON schema. Learn more in the
[Structured Ou... | Text |
python | doocs__leetcode | solution/0100-0199/0105.Construct Binary Tree from Preorder and Inorder Traversal/Solution2.py | {
"start": 0,
"end": 675
} | class ____:
def getBinaryTrees(self, preOrder: List[int], inOrder: List[int]) -> List[TreeNode]:
def dfs(i: int, j: int, n: int) -> List[TreeNode]:
if n <= 0:
return [None]
v = preOrder[i]
ans = []
for k in d[v]:
if j <= k < j +... | Solution |
python | catalyst-team__catalyst | examples/catalyst_rl/dqn.py | {
"start": 550,
"end": 2424
} | class ____(ISampler):
def get_action(
self, env, actor: nn.Module, state: np.array, epsilon: float = -1
) -> int:
if np.random.random() < epsilon:
action = env.action_space.sample()
else:
state = torch.tensor(state[None], dtype=torch.float32)
q_values ... | Sampler |
python | pypa__setuptools | setuptools/_vendor/autocommand/autoparse.py | {
"start": 1396,
"end": 1464
} | class ____(AutocommandError):
'''Docstring error'''
| DocstringError |
python | google__jax | jax/_src/pallas/core.py | {
"start": 27556,
"end": 36627
} | class ____:
"""An internal canonicalized version of GridSpec.
Encodes the calling conventions of the pallas_call primitive, the kernel,
and the index maps.
The pallas_call is invoked with: ``*dynamic_grid_sizes, *index, *inputs``.
The ``index`` operands are for the scalar prefetch.
The kernel function is... | GridMapping |
python | doocs__leetcode | solution/2200-2299/2240.Number of Ways to Buy Pens and Pencils/Solution.py | {
"start": 0,
"end": 246
} | class ____:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
ans = 0
for x in range(total // cost1 + 1):
y = (total - (x * cost1)) // cost2 + 1
ans += y
return ans
| Solution |
python | jina-ai__jina | tests/integration/stateful/test_stateful.py | {
"start": 521,
"end": 11841
} | class ____(TextDoc):
id: str
tags: Dict[str, Union[str, int]] = {}
l: List[Union[str, int]] = []
@pytest.fixture(scope='function')
def kill_all_children():
yield
from multiprocessing import active_children
children = active_children()
for p in children:
print(f' Child process {p.p... | TextDocWithId |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 604823,
"end": 605152
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("RequestedReviewer", graphql_name="node")
| RequestedReviewerEdge |
python | doocs__leetcode | solution/1500-1599/1588.Sum of All Odd Length Subarrays/Solution2.py | {
"start": 0,
"end": 305
} | class ____:
def sumOddLengthSubarrays(self, arr: List[int]) -> int:
ans, f, g = arr[0], arr[0], 0
for i in range(1, len(arr)):
ff = g + arr[i] * (i // 2 + 1)
gg = f + arr[i] * ((i + 1) // 2)
f, g = ff, gg
ans += f
return ans
| Solution |
python | ray-project__ray | python/ray/air/util/tensor_extensions/arrow.py | {
"start": 24562,
"end": 25459
} | class ____(_BaseFixedShapeArrowTensorType):
"""Arrow ExtensionType (v2) for tensors (supporting tensors > 4Gb)."""
OFFSET_DTYPE = pa.int64()
def __init__(self, shape: Tuple[int, ...], dtype: pa.DataType):
"""
Construct the Arrow extension type for array of fixed-shaped tensors.
Ar... | ArrowTensorTypeV2 |
python | ApeWorX__ape | src/ape/api/transactions.py | {
"start": 1434,
"end": 9034
} | class ____(BaseInterfaceModel):
"""
An API class representing a transaction.
Ecosystem plugins implement one or more of transaction APIs
depending on which schemas they permit,
such as typed-transactions from `EIP-1559 <https://eips.ethereum.org/EIPS/eip-1559>`__.
"""
chain_id: Optional[Hex... | TransactionAPI |
python | fastai__fastai | fastai/text/models/core.py | {
"start": 5918,
"end": 8414
} | class ____(Module):
"Create a linear classifier with pooling"
def __init__(self,
dims:list, # List of hidden sizes for MLP as `int`s
ps:list, # List of dropout probabilities as `float`s
bptt:int, # Backpropagation through time
y_range:tuple=None # Tuple of (low, high) output va... | PoolingLinearClassifier |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_cond_format16.py | {
"start": 315,
"end": 1601
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("cond_format16.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with conditional formatting."""
... | TestCompareXLSXFiles |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 962809,
"end": 963205
} | 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("SecurityAdvisory", graphq... | SecurityAdvisoryEdge |
python | prabhupant__python-ds | data_structures/binary_trees/diagonal_tree.py | {
"start": 127,
"end": 858
} | class ____:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def diagonal_print_util(root, d, diagonal_map):
if root is None:
return
try:
diagonal_map[d].append(root.val)
except:
diagonal_map[d] = [root.val]
# Increase ve... | Node |
python | kamyu104__LeetCode-Solutions | Python/jump-game-v.py | {
"start": 5707,
"end": 6765
} | class ____(object):
def maxJumps(self, arr, d):
"""
:type arr: List[int]
:type d: int
:rtype: int
"""
left, decreasing_stk = range(len(arr)), []
for i in xrange(len(arr)):
while decreasing_stk and arr[decreasing_stk[-1]] < arr[i]:
i... | Solution3 |
python | sqlalchemy__sqlalchemy | examples/performance/bulk_updates.py | {
"start": 479,
"end": 1714
} | class ____(Base):
__tablename__ = "customer"
id = Column(Integer, Identity(), primary_key=True)
name = Column(String(255))
description = Column(String(255))
Profiler.init("bulk_updates", num=100000)
@Profiler.setup
def setup_database(dburl, echo, num):
global engine
engine = create_engine(db... | Customer |
python | joblib__joblib | joblib/externals/loky/process_executor.py | {
"start": 40479,
"end": 52348
} | class ____(Executor):
_at_exit = None
def __init__(
self,
max_workers=None,
job_reducers=None,
result_reducers=None,
timeout=None,
context=None,
initializer=None,
initargs=(),
env=None,
):
"""Initializes a new ProcessPoolExecu... | ProcessPoolExecutor |
python | huggingface__transformers | src/transformers/models/dab_detr/modeling_dab_detr.py | {
"start": 30636,
"end": 33371
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: DabDetrConfig):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = DetrAttention(config)
self.self_attn_layer_norm = nn.LayerNorm(self.hidden_size)
self.dropout = config.dropout
... | DabDetrEncoderLayer |
python | pypa__pip | src/pip/_vendor/rich/highlighter.py | {
"start": 1230,
"end": 1454
} | class ____(Highlighter):
"""A highlighter object that doesn't highlight.
May be used to disable highlighting entirely.
"""
def highlight(self, text: Text) -> None:
"""Nothing to do"""
| NullHighlighter |
python | joke2k__faker | faker/providers/internet/__init__.py | {
"start": 2087,
"end": 27180
} | class ____(BaseProvider):
safe_domain_names: ElementsType[str] = ("example.org", "example.com", "example.net")
free_email_domains: ElementsType[str] = ("gmail.com", "yahoo.com", "hotmail.com")
tlds: ElementsType[str] = (
"com",
"com",
"com",
"com",
"com",
"com... | Provider |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-pebblo/tests/test_readers_pebblo.py | {
"start": 346,
"end": 2663
} | class ____:
def __init__(self, json_data: Dict, status_code: int):
self.json_data = json_data
self.status_code = status_code
def json(self) -> Dict:
return self.json_data
@pytest.fixture()
def create_empty_file():
with open(csv_empty_file_name, "w"):
pass
yield
if... | MockResponse |
python | python-markdown__markdown | tests/test_syntax/extensions/test_smarty.py | {
"start": 6380,
"end": 7615
} | class ____(TestCase):
default_kwargs = {
'extensions': ['smarty'],
'extension_configs': {
'smarty': {
'smart_angled_quotes': True,
'substitutions': {
'ndash': '\u2013',
'mdash': '\u2014',
'ellips... | TestSmartyCustomSubstitutions |
python | getsentry__sentry | tests/sentry/monitors/endpoints/test_project_monitor_details.py | {
"start": 465,
"end": 620
} | class ____(BaseUpdateMonitorTest, BaseProjectMonitorTest):
endpoint = "sentry-api-0-project-monitor-details"
__test__ = True
| ProjectUpdateMonitorTest |
python | pypa__warehouse | tests/unit/admin/views/test_users.py | {
"start": 45623,
"end": 48168
} | class ____:
def test_user_recover_account_cancel_cancels_active_account_recoveries(
self, db_request, monkeypatch
):
admin_user = UserFactory.create()
user = UserFactory.create(
totp_secret=b"aaaaabbbbbcccccddddd",
webauthn=[
WebAuthn(
... | TestUserRecoverAccountCancel |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/ext/asyncio/async_sessionmaker.py | {
"start": 735,
"end": 894
} | class ____(Base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[str]
bs: Mapped[List[B]] = relationship()
| A |
python | pypa__pipenv | pipenv/exceptions.py | {
"start": 2666,
"end": 3292
} | class ____(PipenvException):
def __init__(self, cmd, out="", err="", exit_code=1):
self.cmd = cmd
self.out = out
self.err = err
self.exit_code = exit_code
message = f"Error running command: {cmd}"
PipenvException.__init__(self, message)
def show(self, file=None):... | PipenvCmdError |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_process.py | {
"start": 100679,
"end": 105022
} | class ____(RelocationTaskTestCase):
def setUp(self) -> None:
RelocationTaskTestCase.setUp(self)
TransactionTestCase.setUp(self)
self.relocation.step = Relocation.Step.NOTIFYING.value
self.relocation.latest_task = OrderedTask.NOTIFYING_USERS.name
self.relocation.save()
... | NotifyingOwnerTest |
python | huggingface__transformers | src/transformers/models/mobilevit/modeling_mobilevit.py | {
"start": 10932,
"end": 11919
} | class ____(nn.Module):
def __init__(self, config: MobileViTConfig, hidden_size: int, intermediate_size: int) -> None:
super().__init__()
self.attention = MobileViTAttention(config, hidden_size)
self.intermediate = MobileViTIntermediate(config, hidden_size, intermediate_size)
self.out... | MobileViTTransformerLayer |
python | langchain-ai__langchain | libs/core/tests/unit_tests/test_tools.py | {
"start": 42306,
"end": 46822
} | class ____(BaseTool):
name: str = "structured_api"
args_schema: type[BaseModel] = _MockSchema
description: str = "A Structured Tool"
response_format: Literal["content_and_artifact"] = "content_and_artifact"
@override
def _run(
self,
arg1: int,
arg2: bool,
arg3: d... | _MockStructuredToolWithRawOutput |
python | boto__boto3 | boto3/resources/model.py | {
"start": 5149,
"end": 6355
} | class ____:
"""
A resource response to create after performing an action.
:type definition: dict
:param definition: The JSON definition
:type resource_defs: dict
:param resource_defs: All resources defined in the service
"""
def __init__(self, definition, resource_defs):
self._... | ResponseResource |
python | pytorch__pytorch | test/inductor/test_codecache.py | {
"start": 7431,
"end": 67448
} | class ____(TestCase):
device_type = GPU_TYPE
def setUp(self):
super().setUp()
counters.clear()
DynamoCache.clear()
PrecompileContext.clear()
AOTAutogradCache.clear()
PatchCaches.setUp()
CacheArtifactManager.clear()
torch._dynamo.reset()
def t... | TestFxGraphCache |
python | pytorch__pytorch | test/dynamo/test_aot_autograd_cache.py | {
"start": 84302,
"end": 84419
} | class ____(AOTAutogradCacheTests):
pass
@inductor_config.patch("fx_graph_cache", True)
| AOTAutogradCacheBundledTests |
python | huggingface__transformers | tests/models/pegasus_x/test_modeling_pegasus_x.py | {
"start": 35167,
"end": 36297
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (PegasusXDecoder,) if is_torch_available() else ()
is_encoder_decoder = False
def setUp(
self,
):
self.model_tester = PegasusXStandaloneDecoderModelTester(self, is_training=False)
self.config_tester = ConfigTe... | PegasusXStandaloneDecoderModelTest |
python | django-extensions__django-extensions | tests/management/commands/test_drop_test_database.py | {
"start": 2420,
"end": 13646
} | class ____(TestCase):
"""Test for drop_test_database command."""
@patch("sys.stdout", new_callable=StringIO)
@patch("django_extensions.management.commands.drop_test_database.input")
def test_should_raise_CommandError_if_database_is_unknown(self, m_input, m_stdout):
m_input.return_value = "no"
... | DropTestDatabaseTests |
python | great-expectations__great_expectations | tests/integration/data_sources_and_expectations/test_expectation_conditions.py | {
"start": 10591,
"end": 14279
} | class ____:
"""Simple tests to ensure that pandas properly utilizes row condition from each
type of expectation (ColumnMapExpectation, ColumnPairMapExpectation, etc)
"""
@parameterize_batch_for_data_sources(
data_source_configs=[PandasDataFrameDatasourceTestConfig()],
data=DATA,
)
... | TestPandasConditionClassAcrossExpectationTypes |
python | django-import-export__django-import-export | import_export/formats/base_formats.py | {
"start": 3692,
"end": 3860
} | class ____(TextFormat):
TABLIB_MODULE = "tablib.formats._yaml"
# See https://stackoverflow.com/questions/332129/yaml-mime-type
CONTENT_TYPE = "text/yaml"
| YAML |
python | apache__airflow | providers/databricks/tests/unit/databricks/hooks/test_databricks.py | {
"start": 9676,
"end": 50319
} | class ____:
"""
Tests for DatabricksHook.
"""
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id=DEFAULT_CONN_ID,
conn_type="databricks",
host=... | TestDatabricksHook |
python | python-openxml__python-docx | tests/oxml/unitdata/section.py | {
"start": 483,
"end": 590
} | class ____(BaseBuilder):
__tag__ = "w:sectPr"
__nspfxs__ = ("w",)
__attrs__ = ()
| CT_SectPrBuilder |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dlp.py | {
"start": 14798,
"end": 15663
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.dlp.CloudDLPHook")
def test_get_inspect_template(self, mock_hook):
mock_hook.return_value.get_inspect_template.return_value = InspectTemplate()
operator = CloudDLPGetInspectTemplateOperator(
template_id=TEMPLATE_ID, or... | TestCloudDLPGetInspectTemplateOperator |
python | langchain-ai__langchain | libs/partners/ollama/langchain_ollama/chat_models.py | {
"start": 8855,
"end": 62934
} | class ____(BaseChatModel):
r"""Ollama chat model integration.
???+ note "Setup"
Install `langchain-ollama` and download any models you want to use from ollama.
```bash
ollama pull gpt-oss:20b
pip install -U langchain-ollama
```
Key init args — completion params:
... | ChatOllama |
python | numpy__numpy | numpy/_utils/_pep440.py | {
"start": 4294,
"end": 7546
} | class ____(_BaseVersion):
def __init__(self, version):
self._version = str(version)
self._key = _legacy_cmpkey(self._version)
def __str__(self):
return self._version
def __repr__(self):
return f"<LegacyVersion({str(self)!r})>"
@property
def public(self):
r... | LegacyVersion |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py | {
"start": 40076,
"end": 55680
} | class ____(Qwen2_5OmniPreTrainedModelForConditionalGeneration):
def get_llm_pos_ids_for_vision(
self,
start_idx: int,
vision_idx: int,
spatial_merge_size: int,
t_index: list[torch.Tensor],
grid_hs: list[torch.Tensor],
grid_ws: list[torch.Tensor],
):
... | Qwen3OmniMoePreTrainedModelForConditionalGeneration |
python | kamyu104__LeetCode-Solutions | Python/number-of-days-in-a-month.py | {
"start": 29,
"end": 316
} | class ____(object):
def numberOfDays(self, Y, M):
"""
:type Y: int
:type M: int
:rtype: int
"""
leap = 1 if ((Y % 4 == 0) and (Y % 100 != 0)) or (Y % 400 == 0) else 0
return (28+leap if (M == 2) else 31-(M-1)%7%2)
| Solution |
python | pandas-dev__pandas | asv_bench/benchmarks/timeseries.py | {
"start": 5070,
"end": 5388
} | class ____:
# GH 7754
def setup(self):
rng3 = date_range(
start="2000-01-01 00:00:00", end="2000-01-01 10:00:00", freq="555000us"
)
self.dt_ts = Series(5, rng3, dtype="datetime64[ns]")
def time_resample(self):
self.dt_ts.resample("1s").last()
| ResampleDatetetime64 |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 115471,
"end": 116412
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"pull_request_id",
"commit_headline",
"commit_body",
"expected_head_oid",
"merge_method",
"author_email",
"client_mutation_id... | MergePullRequestInput |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 395,
"end": 5186
} | class ____(NonStrictDataModel):
"""
:param queue: ID of the queue
:type queue: str
:param dates: List of timestamps (in seconds from epoch) in the acceding order.
The timestamps are separated by the requested interval. Timestamps where no
queue status change was recorded are omitted.
... | QueueMetrics |
python | kamyu104__LeetCode-Solutions | Python/recover-the-original-array.py | {
"start": 52,
"end": 856
} | class ____(object):
def recoverArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def check(k, cnt, result):
for x in nums:
if cnt[x] == 0:
continue
if cnt[x+2*k] == 0:
return ... | Solution |
python | python-poetry__poetry | src/poetry/console/commands/check.py | {
"start": 303,
"end": 7765
} | class ____(Command):
name = "check"
description = (
"Validates the content of the <comment>pyproject.toml</> file and its"
" consistency with the poetry.lock file."
)
options: ClassVar[list[Option]] = [
option(
"lock",
None,
"Checks that <comm... | CheckCommand |
python | pytorch__pytorch | test/mobile/model_test/math_ops.py | {
"start": 14384,
"end": 16529
} | class ____(torch.nn.Module):
def forward(self):
return self.blas_lapack_ops()
def blas_lapack_ops(self):
m = torch.randn(3, 3)
a = torch.randn(10, 3, 4)
b = torch.randn(10, 4, 3)
v = torch.randn(3)
return len(
torch.addbmm(m, a, b),
torch.... | BlasLapackOpsModule |
python | getsentry__sentry | tests/sentry/grouping/__init__.py | {
"start": 2886,
"end": 12248
} | class ____:
def __init__(self, inputs_dir: str, filename: str):
self.filename = filename # Necessary for test naming
with open(path.join(inputs_dir, self.filename)) as f:
self.data = json.load(f)
def _manually_save_event(
self, grouping_config: GroupingConfig, fingerprintin... | GroupingInput |
python | getsentry__sentry | src/sentry/api/serializers/models/groupseen.py | {
"start": 185,
"end": 1141
} | class ____(Serializer):
def get_attrs(self, item_list, user, **kwargs):
serialized_users = user_service.serialize_many(
filter=dict(user_ids=[i.user_id for i in item_list]), as_user=user
)
user_map = {}
for serialized in serialized_users:
user_map[serialized["... | GroupSeenSerializer |
python | ansible__ansible | lib/ansible/module_utils/_internal/_patches/_sys_intern_patch.py | {
"start": 160,
"end": 252
} | class ____(str):
"""Wrapper around `str` to test if subclasses are accepted."""
| _CustomStr |
python | django__django | tests/auth_tests/test_basic.py | {
"start": 5615,
"end": 8610
} | class ____(TestCase):
def test_get_user_anonymous(self):
request = HttpRequest()
request.session = self.client.session
user = get_user(request)
self.assertIsInstance(user, AnonymousUser)
async def test_aget_user_anonymous(self):
request = HttpRequest()
request.se... | TestGetUser |
python | tensorflow__tensorflow | tensorflow/python/platform/benchmark_test.py | {
"start": 918,
"end": 2756
} | class ____(test.TestCase, benchmark.TensorFlowBenchmark):
def testReportBenchmark(self):
output_dir = self.get_temp_dir() + os.path.sep
os.environ['TEST_REPORT_FILE_PREFIX'] = output_dir
proto_file_path = os.path.join(output_dir,
'BenchmarkTest.testReportBenchmark')
... | BenchmarkTest |
python | Netflix__metaflow | metaflow/plugins/datastores/s3_storage.py | {
"start": 404,
"end": 5473
} | class ____(DataStoreStorage):
TYPE = "s3"
@check_s3_deps
def __init__(self, root=None):
super(S3Storage, self).__init__(root)
self.s3_client = S3Client()
@classmethod
def get_datastore_root_from_config(cls, echo, create_on_absent=True):
return DATASTORE_SYSROOT_S3
def ... | S3Storage |
python | scipy__scipy | scipy/optimize/tests/test_linprog.py | {
"start": 93693,
"end": 93907
} | class ____(LinprogRSTests):
options = {"pivot": "bland"}
############################################
# HiGHS-Simplex-Dual Option-Specific Tests #
############################################
| TestLinprogRSBland |
python | qdrant__qdrant-client | qdrant_client/grpc/qdrant_pb2_grpc.py | {
"start": 694,
"end": 1675
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
def HealthCheck(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | QdrantServicer |
python | apache__airflow | providers/sftp/tests/unit/sftp/hooks/test_sftp.py | {
"start": 30340,
"end": 40129
} | class ____:
@patch("asyncssh.connect", new_callable=AsyncMock)
@patch("airflow.providers.sftp.hooks.sftp.SFTPHookAsync.get_connection")
@pytest.mark.asyncio
async def test_extra_dejson_fields_for_connection_building_known_hosts_none(
self, mock_get_connection, mock_connect, caplog
):
... | TestSFTPHookAsync |
python | celery__celery | t/unit/tasks/test_canvas.py | {
"start": 3063,
"end": 3249
} | class ____(chain):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.subtask_type = "chain_subclass"
@Signature.register_type()
| chain_subclass |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 48758,
"end": 49269
} | class ____(VOTableSpecWarning):
"""
The ``timeorigin`` attribute on the ``TIMESYS`` element must be
either a floating point literal specifying a valid Julian Date,
or, for convenience, the string "MJD-origin" (standing for 2400000.5)
or the string "JD-origin" (standing for 0).
**References**: `... | E23 |
python | PyCQA__pylint | tests/functional/g/generic_alias/generic_alias_typing.py | {
"start": 2713,
"end": 2770
} | class ____(typing.OrderedDict):
pass
| DerivedOrderedDict2 |
python | mlflow__mlflow | tests/pyfunc/test_scoring_server.py | {
"start": 3092,
"end": 3745
} | class ____(PythonModel):
# Example model that takes "prompt" as model input
def predict(self, context, model_input, params=None):
if isinstance(model_input, pd.DataFrame):
model_input = model_input.to_dict(orient="records")[0]
ret = model_input["prompt"]
return {
... | MyCompletionsLLM |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/type/directives.py | {
"start": 273,
"end": 1165
} | class ____(object):
# Operations
QUERY = 'QUERY'
MUTATION = 'MUTATION'
SUBSCRIPTION = 'SUBSCRIPTION'
FIELD = 'FIELD'
FRAGMENT_DEFINITION = 'FRAGMENT_DEFINITION'
FRAGMENT_SPREAD = 'FRAGMENT_SPREAD'
INLINE_FRAGMENT = 'INLINE_FRAGMENT'
# Schema Definitions
SCHEMA = 'SCHEMA'
SCA... | DirectiveLocation |
python | tensorflow__tensorflow | tensorflow/python/ops/embedding_ops_test.py | {
"start": 1233,
"end": 3478
} | class ____(test_util.TensorFlowTestCase):
def testEmbeddingLookupOnUninitializedVariableDoesSparseRead(self):
x = resource_variable_ops.UninitializedVariable(
trainable=True, shape=[3, 3], dtype=dtypes.float32)
@def_function.function(input_signature=[])
def _init():
return x.assign(np.zero... | EmbeddingLookupTest |
python | django-haystack__django-haystack | test_haystack/test_fields.py | {
"start": 22691,
"end": 23312
} | class ____(TestCase):
def test_init(self):
try:
foo = FacetMultiValueField(model_attr="foo")
foo_exact = FacetMultiValueField(facet_for="bar")
except:
self.fail()
self.assertEqual(foo.facet_for, None)
self.assertEqual(foo_exact.null, True)
... | FacetMultiValueFieldTestCase |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/descriptors.py | {
"start": 20879,
"end": 21119
} | class ____(AOTInput):
"""The world token which is threaded through side-effectful operations"""
idx: int
def expr(self) -> str:
return f"__forward_token{self.idx}"
@dataclasses.dataclass(frozen=True)
| ForwardTokenAOTInput |
python | ansible__ansible | test/units/module_utils/facts/test_collectors.py | {
"start": 7114,
"end": 7310
} | class ____(BaseFactsTest):
__test__ = True
gather_subset = ['!all', 'dns']
valid_subsets = ['dns']
fact_namespace = 'ansible_dns'
collector_class = DnsFactCollector
| TestDnsFacts |
python | PyCQA__pylint | doc/data/messages/m/multiple-constructor-doc/bad.py | {
"start": 0,
"end": 354
} | class ____: # [multiple-constructor-doc]
"""Represents a point in the xy-coordinate plane.
:param x: coordinate
:param y: coordinate
"""
def __init__(self, x, y):
"""Represents a point in the xy-coordinate plane.
:param x: coordinate
:param y: coordinate
"""
... | Point |
python | kubernetes-client__python | kubernetes/base/config/kube_config_test.py | {
"start": 13942,
"end": 15803
} | class ____:
FILE_KEYS = ["ssl_ca_cert", "key_file", "cert_file"]
IGNORE_KEYS = ["refresh_api_key_hook"]
def __init__(self, token=None, **kwargs):
self.api_key = {}
# Provided by the OpenAPI-generated Configuration class
self.refresh_api_key_hook = None
if token:
... | FakeConfig |
python | pytorch__pytorch | torch/ao/quantization/fx/fuse_handler.py | {
"start": 723,
"end": 1302
} | class ____(ABC):
"""Base handler class for the fusion patterns"""
@abstractmethod
def __init__(self, node: Node):
pass
@abstractmethod
def fuse(
self,
load_arg: Callable,
named_modules: dict[str, torch.nn.Module],
fused_graph: Graph,
root_node: Node,... | FuseHandler |
python | langchain-ai__langchain | libs/langchain/langchain_classic/evaluation/schema.py | {
"start": 3503,
"end": 5345
} | class ____:
"""Mixin for checking evaluation arguments."""
@property
def requires_reference(self) -> bool:
"""Whether this evaluator requires a reference label."""
return False
@property
def requires_input(self) -> bool:
"""Whether this evaluator requires an input string.""... | _EvalArgsMixin |
python | apache__airflow | dev/breeze/src/airflow_breeze/commands/ui_commands.py | {
"start": 3821,
"end": 4224
} | class ____(NamedTuple):
"""
Summary of missing and extra translation keys for a file, per locale.
Attributes:
missing_keys: A dictionary mapping locale codes to lists of missing translation keys.
extra_keys: A dictionary mapping locale codes to lists of extra translation keys.
"""
... | LocaleSummary |
python | huggingface__transformers | src/transformers/models/minimax/modular_minimax.py | {
"start": 21665,
"end": 21720
} | class ____(MixtralTopKRouter):
pass
| MiniMaxTopKRouter |
python | ray-project__ray | release/llm_tests/benchmark/load_test.py | {
"start": 13600,
"end": 15188
} | class ____(BaseProvider):
DEFAULT_MODEL_NAME = "ensemble"
def get_url(self):
assert not self.parsed_options.chat, "Chat is not supported"
stream_suffix = "_stream" if self.parsed_options.stream else ""
return f"/v2/models/{self.model}/generate{stream_suffix}"
def format_payload(sel... | TritonGenerateProvider |
python | numpy__numpy | benchmarks/benchmarks/bench_ma.py | {
"start": 7430,
"end": 8474
} | class ____(Benchmark):
param_names = ['mtype', 'msize']
params = [['np', 'np.ma'],
['small', 'big']]
def setup(self, mtype, msize):
# Small arrays
xs = np.random.uniform(-1, 1, 6).reshape(2, 3)
ys = np.random.uniform(-1, 1, 6).reshape(2, 3)
m1 = [[True, False, ... | Where |
python | ApeWorX__ape | tests/functional/test_accounts.py | {
"start": 2078,
"end": 2153
} | class ____(EIP712Type):
addr: "address" # type: ignore # noqa: F821
| Baz |
python | jazzband__tablib | src/tablib/exceptions.py | {
"start": 0,
"end": 71
} | class ____(Exception):
"""Tablib common exception."""
| TablibException |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol1.py | {
"start": 2044,
"end": 2082
} | class ____(Protocol[_B]): ...
| ProtoBase2 |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_scalarmath.py | {
"start": 3270,
"end": 5390
} | class ____(TestCase):
def test_blocked(self):
# test alignments offsets for simd instructions
# alignments for vz + 2 * (vs - 1) + 1
for dt, sz in [(np.float32, 11), (np.float64, 7), (np.int32, 11)]:
for out, inp1, inp2, msg in _gen_alignment_data(
dtype=dt, type=... | TestBaseMath |
python | scipy__scipy | scipy/io/_harwell_boeing/hb.py | {
"start": 12957,
"end": 14964
} | class ____:
"""Class to hold the matrix type."""
# q2f* translates qualified names to Fortran character
_q2f_type = {
"real": "R",
"complex": "C",
"pattern": "P",
"integer": "I",
}
_q2f_structure = {
"symmetric": "S",
"unsymmetric": "U",
... | HBMatrixType |
python | docker__docker-py | docker/errors.py | {
"start": 4240,
"end": 4659
} | class ____(DockerException):
pass
def create_unexpected_kwargs_error(name, kwargs):
quoted_kwargs = [f"'{k}'" for k in sorted(kwargs)]
text = [f"{name}() "]
if len(quoted_kwargs) == 1:
text.append("got an unexpected keyword argument ")
else:
text.append("got unexpected keyword argu... | ImageLoadError |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/triggers/batch.py | {
"start": 1103,
"end": 2724
} | class ____(AwsBaseWaiterTrigger):
"""
Checks for the status of a submitted job_id to AWS Batch until it reaches a failure or a success state.
:param job_id: the job ID, to poll for job completion or not
:param region_name: AWS region name to use
Override the region_name in connection (if provid... | BatchJobTrigger |
python | google__pytype | pytype/pytd/pytd.py | {
"start": 8378,
"end": 9329
} | class ____(Node):
"""Represents an individual signature of a function.
For overloaded functions, this is one specific combination of parameters.
For non-overloaded functions, there is a 1:1 correspondence between function
and signature.
Attributes:
params: The list of parameters for this function defini... | Signature |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 116991,
"end": 117122
} | class ____:
xlSpeakByColumns = 1 # from enum XlSpeakDirection
xlSpeakByRows = 0 # from enum XlSpeakDirection
| SpeakDirection |
python | pydantic__pydantic | pydantic/types.py | {
"start": 84059,
"end": 85792
} | class ____(BaseModel):
base64_bytes: Base64Bytes
# Initialize the model with base64 data
m = Model(base64_bytes=b'VGhpcyBpcyB0aGUgd2F5')
# Access decoded value
print(m.base64_bytes)
#> b'This is the way'
# Serialize into the base64 form
print(m.model_dump())
#> {'base64_bytes': b'VGhpcyBpcyB0aGUgd2F5'}
# Valida... | Model |
python | getsentry__sentry | src/sentry/rules/conditions/event_attribute.py | {
"start": 7956,
"end": 8465
} | class ____(AttributeHandler):
minimum_path_length = 1
@classmethod
def _handle(cls, path: list[str], event: GroupEvent) -> list[str]:
path.pop(0)
value = event.data.get("extra", {})
while path:
bit = path.pop(0)
value = value.get(bit)
if not value... | ExtraAttributeHandler |
python | coleifer__peewee | playhouse/test_utils.py | {
"start": 1122,
"end": 1854
} | class ____(count_queries):
def __init__(self, expected, only_select=False):
super(assert_query_count, self).__init__(only_select=only_select)
self.expected = expected
def __call__(self, f):
@wraps(f)
def decorated(*args, **kwds):
with self:
ret = f(*a... | assert_query_count |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/models.py | {
"start": 2621,
"end": 2705
} | class ____(models.Model):
customish = CustomishField(default="b")
| CustomishDefault |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.