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 | run-llama__llama_index | llama-index-core/tests/agent/workflow/test_events.py | {
"start": 1202,
"end": 1273
} | class ____(BaseModel):
operation: str
result: str
| WrongMathResult |
python | kamyu104__LeetCode-Solutions | Python/steps-to-make-array-non-decreasing.py | {
"start": 46,
"end": 539
} | class ____(object):
def totalSteps(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = [0]*len(nums) # dp[i]: number of rounds for nums[i] to remove all the covered elements
stk = []
for i in reversed(xrange(len(nums))):
while stk and nums... | Solution |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 7308,
"end": 7403
} | class ____(PydanticTypeError):
msg_template = 'value is not a valid frozenset'
| FrozenSetError |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/shortcuts/choice_input.py | {
"start": 1224,
"end": 10523
} | class ____(Generic[_T]):
"""
Input selection prompt. Ask the user to choose among a set of options.
Example usage::
input_selection = ChoiceInput(
message="Please select a dish:",
options=[
("pizza", "Pizza with mushrooms"),
("salad", "Salad ... | ChoiceInput |
python | viewflow__viewflow | tests/workflow/test_nodes__view.py | {
"start": 3153,
"end": 3681
} | class ____(flow.Flow): # noqa: D101
start = flow.StartHandle().Next(this.approve)
approve = (
flow.View(views.UpdateProcessView.as_view(fields=[]))
.Permission(auto_create=True)
.onCreate(this.toggle_on_create)
.Next(this.end)
)
end = flow.End()
def toggle_on_crea... | TestWorkflow |
python | getsentry__sentry | src/sentry/integrations/vsts/integration.py | {
"start": 26962,
"end": 29857
} | class ____:
def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase:
with IntegrationPipelineViewEvent(
IntegrationPipelineViewType.ACCOUNT_CONFIG,
IntegrationDomain.SOURCE_CODE_MANAGEMENT,
VstsIntegrationProvider.key,
).capture... | AccountConfigView |
python | pytorch__pytorch | test/distributed/_shard/sharded_tensor/ops/test_init.py | {
"start": 635,
"end": 4036
} | class ____(ShardedTensorTestBase):
"""Testing torch.nn.init functions for ShardedTensor"""
@with_comms
@skip_if_lt_x_gpu(4)
@requires_nccl()
def test_init_sharded_tensor_with_uniform(self):
"""Test torch.nn.init.uniform_(ShardedTensor, a, b)"""
spec = ChunkShardingSpec(
... | TestShardedTensorNNInit |
python | psf__black | src/black/mode.py | {
"start": 7858,
"end": 7982
} | class ____(UserWarning):
"""Visible deprecation warning."""
_MAX_CACHE_KEY_PART_LENGTH: Final = 32
@dataclass
| Deprecated |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 229315,
"end": 229636
} | 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("CommitComment", graphql_name="node")
| CommitCommentEdge |
python | Pylons__pyramid | docs/tutorials/wiki2/src/authentication/tutorial/models/page.py | {
"start": 137,
"end": 524
} | class ____(Base):
""" The SQLAlchemy declarative model class for a Page object. """
__tablename__ = 'pages'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(unique=True)
data: Mapped[str]
creator_id: Mapped[int] = mapped_column(ForeignKey('users.id'))
crea... | Page |
python | bottlepy__bottle | test/test_auth.py | {
"start": 73,
"end": 345
} | class ____(ServerTestBase):
def test__header(self):
@bottle.route('/')
@bottle.auth_basic(lambda x, y: False)
def test(): return {}
self.assertStatus(401)
self.assertHeader('Www-Authenticate', 'Basic realm="private"')
| TestBasicAuth |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 856659,
"end": 857069
} | 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("ProjectV2ItemFieldValue",... | ProjectV2ItemFieldValueEdge |
python | keon__algorithms | tests/test_array.py | {
"start": 4244,
"end": 4584
} | class ____(unittest.TestCase):
def test_garage(self):
initial = [1, 2, 3, 0, 4]
final = [0, 3, 2, 1, 4]
steps, seq = garage(initial, final)
self.assertEqual(steps, 4)
self.assertListEqual(
seq, [[0, 2, 3, 1, 4], [2, 0, 3, 1, 4], [2, 3, 0, 1, 4], [0, 3, 2, 1, 4]... | TestGarage |
python | sqlalchemy__sqlalchemy | test/orm/dml/test_bulk_statements.py | {
"start": 81566,
"end": 87442
} | class ____(
fixtures.DeclarativeMappedTest, testing.AssertsExecutionResults
):
run_inserts = "each"
__requires__ = ("insert_returning",)
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(Base):
__tablename__ = "a"
id: Mapped[int] = map... | EagerLoadTest |
python | doocs__leetcode | solution/0900-0999/0979.Distribute Coins in Binary Tree/Solution.py | {
"start": 192,
"end": 575
} | class ____:
def distributeCoins(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if root is None:
return 0
left, right = dfs(root.left), dfs(root.right)
nonlocal ans
ans += abs(left) + abs(right)
return left + right + root.val... | Solution |
python | kamyu104__LeetCode-Solutions | Python/smallest-subarrays-with-maximum-bitwise-or.py | {
"start": 52,
"end": 512
} | class ____(object):
def smallestSubarrays(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = [0]*len(nums)
lookup = [-1]*max(max(nums).bit_length(), 1)
for i in reversed(xrange(len(nums))):
for bit in xrange(len(lookup)):
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-equalize-binary-string.py | {
"start": 36,
"end": 862
} | class ____(object):
def minOperations(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
def ceil_divide(a, b):
return (a+b-1)//b
zero = s.count('0')
if len(s) == k:
return 0 if zero == 0 else 1 if zero == len(s) else -... | Solution |
python | pytorch__pytorch | torch/_inductor/codegen/cpp.py | {
"start": 183985,
"end": 184179
} | class ____(Enum):
SAME_VARS_REDUCE = "same_vars_reduce"
COMPATIBLE_REDUCTION = "compatible_reduction"
COMPATIBLE_RANGES_NO_REDUCTION = "compatible_ranges_no_reduction"
| ReasonFusedNodes |
python | keon__algorithms | tests/test_linkedlist.py | {
"start": 350,
"end": 676
} | class ____(object):
def __init__(self, x):
self.val = x
self.next = None
# Convert from linked list Node to list for testing
def convert(head):
ret = []
if head:
current = head
while current:
ret.append(current.val)
current = current.next
return ... | Node |
python | walkccc__LeetCode | solutions/156. Binary Tree Upside Down/156-2.py | {
"start": 0,
"end": 415
} | class ____:
def upsideDownBinaryTree(self, root: TreeNode | None) -> TreeNode | None:
prevRoot = None
prevRightChild = None
while root:
nextRoot = root.left # Cache the next root.
root.left = prevRightChild
prevRightChild = root.right
root.right = prevRoot
prevRoot = root ... | Solution |
python | django__django | django/contrib/gis/gdal/prototypes/generation.py | {
"start": 445,
"end": 4888
} | class ____(c_char_p):
pass
def bool_output(func, argtypes, errcheck=None):
"""Generate a ctypes function that returns a boolean value."""
func.argtypes = argtypes
func.restype = c_bool
if errcheck:
func.errcheck = errcheck
return func
def double_output(func, argtypes, errcheck=False,... | gdal_char_p |
python | sqlalchemy__sqlalchemy | test/ext/test_associationproxy.py | {
"start": 93288,
"end": 93489
} | class ____(
ScalarRemoveTest, fixtures.DeclarativeMappedTest
):
run_create_tables = None
useobject = True
cascade_scalar_deletes = True
uselist = False
| ScalarRemoveScalarObjectCascade |
python | dask__dask | dask/dataframe/dask_expr/_concat.py | {
"start": 12484,
"end": 12764
} | class ____(ConcatUnindexed):
@staticmethod
def operation(*args, ignore_order, _kwargs, axis, join):
return methods.concat(args, ignore_order=ignore_order, axis=axis, join=join)
def _broadcast_dep(self, dep: Expr):
return dep.npartitions == 1
| ConcatIndexed |
python | PyCQA__pylint | tests/functional/a/assigning/assigning_non_slot.py | {
"start": 4919,
"end": 4980
} | class ____:
__slots__ = ()
attr2 = MyDescriptor()
| Base |
python | pandas-dev__pandas | asv_bench/benchmarks/hash_functions.py | {
"start": 42,
"end": 251
} | class ____:
def setup(self):
lst = [x << 32 for x in range(5000)]
self.arr = np.array(lst, dtype=np.object_)
def time_unique(self):
pd.unique(self.arr)
| UniqueForLargePyObjectInts |
python | openai__openai-python | src/openai/types/realtime/realtime_session_create_response.py | {
"start": 8191,
"end": 8384
} | class ____(BaseModel):
input: Optional[AudioInput] = None
output: Optional[AudioOutput] = None
ToolChoice: TypeAlias = Union[ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMcp]
| Audio |
python | PyCQA__pylint | tests/functional/p/postponed/postponed_evaluation_pep585.py | {
"start": 1510,
"end": 1594
} | class ____:
my_var: list[int]
@my_decorator
@dataclasses.dataclass
| CustomDataClass3 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/inspection.py | {
"start": 1902,
"end": 2279
} | class ____(Generic[_T]):
"""define a class as inspectable.
This allows typing to set up a linkage between an object that
can be inspected and the type of inspection it returns.
Unfortunately we cannot at the moment get all classes that are
returned by inspection to suit this interface as we get in... | Inspectable |
python | getsentry__sentry | tests/sentry/api/serializers/test_base.py | {
"start": 390,
"end": 511
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
raise Exception
| FailingChildSerializer |
python | pypa__pipenv | pipenv/vendor/click/types.py | {
"start": 14251,
"end": 16933
} | class ____(_NumberParamTypeBase):
def __init__(
self,
min: t.Optional[float] = None,
max: t.Optional[float] = None,
min_open: bool = False,
max_open: bool = False,
clamp: bool = False,
) -> None:
self.min = min
self.max = max
self.min_open ... | _NumberRangeBase |
python | pytest-dev__pytest-django | tests/test_unittest.py | {
"start": 474,
"end": 1197
} | class ____(TestCase):
def setUp(self) -> None:
"""setUp should be called after starting a transaction"""
assert Item.objects.count() == 0
Item.objects.create(name="Some item")
Item.objects.create(name="Some item again")
def test_count(self) -> None:
self.assertEqual(Item... | TestSetup |
python | numba__numba | numba/tests/test_parfors.py | {
"start": 82140,
"end": 90140
} | class ____(TestParforsBase):
def test_parfor_slice1(self):
def test_impl(a):
(n,) = a.shape
b = a[0:n-2] + a[1:n-1]
return b
self.check(test_impl, np.ones(10))
def test_parfor_slice2(self):
def test_impl(a, m):
(n,) = a.shape
... | TestParforsSlice |
python | pyinstaller__pyinstaller | PyInstaller/fake-modules/_pyi_rth_utils/_win32.py | {
"start": 1488,
"end": 11564
} | class ____(ctypes.Structure):
_fields_ = [
("nLength", ctypes.wintypes.DWORD),
("lpSecurityDescriptor", PSECURITY_DESCRIPTOR),
("bInheritHandle", ctypes.wintypes.BOOL),
]
# win32 API functions, bound via ctypes.
# NOTE: we do not use ctypes.windll.<dll_name> to avoid modifying its (glo... | SECURITY_ATTRIBUTES |
python | sympy__sympy | sympy/sets/sets.py | {
"start": 80353,
"end": 81750
} | class ____(Kind):
"""
SetKind is kind for all Sets
Every instance of Set will have kind ``SetKind`` parametrised by the kind
of the elements of the ``Set``. The kind of the elements might be
``NumberKind``, or ``TupleKind`` or something else. When not all elements
have the same kind then the ki... | SetKind |
python | anthropics__anthropic-sdk-python | src/anthropic/types/messages/batch_list_params.py | {
"start": 196,
"end": 691
} | class ____(TypedDict, total=False):
after_id: str
"""ID of the object to use as a cursor for pagination.
When provided, returns the page of results immediately after this object.
"""
before_id: str
"""ID of the object to use as a cursor for pagination.
When provided, returns the page of r... | BatchListParams |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/agent.py | {
"start": 2738,
"end": 3062
} | class ____(BaseEvent):
"""
AgentToolCallEvent.
Args:
arguments (str): Arguments.
tool (ToolMetadata): Tool metadata.
"""
arguments: str
tool: ToolMetadata
@classmethod
def class_name(cls) -> str:
"""Class name."""
return "AgentToolCallEvent"
| AgentToolCallEvent |
python | spyder-ide__spyder | spyder/plugins/variableexplorer/widgets/objectexplorer/toggle_column_mixin.py | {
"start": 5687,
"end": 6084
} | class ____(QTreeWidget, ToggleColumnMixIn):
"""
A QTreeWidget where right clicking on the header allows the user to
show/hide columns.
"""
def _horizontal_header(self):
"""
Returns the horizontal header (of type QHeaderView).
Override this if the horizontalHeader() function ... | ToggleColumnTreeWidget |
python | kamyu104__LeetCode-Solutions | Python/tree-of-coprimes.py | {
"start": 1907,
"end": 3034
} | class ____(object):
def getCoprimes(self, nums, edges):
"""
:type nums: List[int]
:type edges: List[List[int]]
:rtype: List[int]
"""
def dfs(nums, adj, prev, node, depth, path, result):
max_d = -1
for x in path.iterkeys():
... | Solution2 |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/openai_api_models.py | {
"start": 1828,
"end": 1957
} | class ____(vLLMErrorResponse):
model_config = ConfigDict(arbitrary_types_allowed=True)
# TODO (Kourosh): Upstream
| ErrorResponse |
python | doocs__leetcode | solution/1200-1299/1235.Maximum Profit in Job Scheduling/Solution.py | {
"start": 0,
"end": 456
} | class ____:
def jobScheduling(
self, startTime: List[int], endTime: List[int], profit: List[int]
) -> int:
@cache
def dfs(i):
if i >= n:
return 0
_, e, p = jobs[i]
j = bisect_left(jobs, e, lo=i + 1, key=lambda x: x[0])
retur... | Solution |
python | cython__cython | Cython/Compiler/Scanning.py | {
"start": 1419,
"end": 3247
} | class ____:
def __init__(self, outer=None):
self.entries = {}
self.outer = outer
def declare(self, name, value):
self.entries[name] = value
def update(self, other):
self.entries.update(other)
def lookup_here(self, name):
return self.entries[name]
def __co... | CompileTimeScope |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_size.py | {
"start": 699,
"end": 1612
} | class ____:
def __rmul__(self, other):
return self * other
def __mul__(self, other):
if not isinstance(other, Real):
return NotImplemented
return Fraction(other, self)
def __div__(self, other):
return (1 / other) * self
def __add__(self, other):
if ... | _Base |
python | scipy__scipy | scipy/stats/tests/test_qmc.py | {
"start": 27223,
"end": 30482
} | class ____(QMCEngineTests):
qmce = qmc.LatinHypercube
can_scramble = True
def test_continuing(self, *args):
pytest.skip("Not applicable: not a sequence.")
def test_fast_forward(self, *args):
pytest.skip("Not applicable: not a sequence.")
def test_sample(self, *args):
pytes... | TestLHS |
python | ApeWorX__ape | src/ape_ethereum/transactions.py | {
"start": 4753,
"end": 5466
} | class ____(BaseTransaction):
"""
Transactions that are pre-EIP-1559 and use the ``gasPrice`` field.
"""
gas_price: Optional[HexInt] = Field(default=None, alias="gasPrice")
max_priority_fee: Optional[HexInt] = Field(default=None, exclude=True) # type: ignore
type: HexInt = Field(default=Transac... | StaticFeeTransaction |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py | {
"start": 1851,
"end": 2399
} | class ____:
quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)
# Regression tests for:
# https://github.com/astral-sh/ruff/issues/6447
from typing import NewType
ListOfStrings = NewType("ListOfStrs", list[str])
StringsToInts = NewType("IntsToStrings", dict[str, int])
SpecialString ... | InventoryItem |
python | doocs__leetcode | solution/0300-0399/0379.Design Phone Directory/Solution.py | {
"start": 0,
"end": 572
} | class ____:
def __init__(self, maxNumbers: int):
self.available = set(range(maxNumbers))
def get(self) -> int:
if not self.available:
return -1
return self.available.pop()
def check(self, number: int) -> bool:
return number in self.available
def release(se... | PhoneDirectory |
python | lepture__authlib | tests/django/test_oauth2/models.py | {
"start": 653,
"end": 2214
} | class ____(Model, ClientMixin):
user = ForeignKey(User, on_delete=CASCADE)
client_id = CharField(max_length=48, unique=True, db_index=True)
client_secret = CharField(max_length=48, blank=True)
redirect_uris = TextField(default="")
default_redirect_uri = TextField(blank=False, default="")
scope =... | Client |
python | dagster-io__dagster | python_modules/libraries/dagster-airflow/dagster_airflow_tests/test_dagster_pipeline_factory/test_load_connections.py | {
"start": 3689,
"end": 5209
} | class ____(unittest.TestCase):
@mock.patch("dagster_airflow.hooks.dagster_hook.DagsterHook.launch_run", return_value="run_id")
@mock.patch("dagster_airflow.hooks.dagster_hook.DagsterHook.wait_for_run")
def test_ingest_airflow_dags_with_connections(self, launch_run, wait_for_run):
connections = [
... | TestConnectionsAirflow1 |
python | allegroai__clearml | clearml/backend_api/services/v2_20/workers.py | {
"start": 51783,
"end": 58089
} | class ____(Response):
"""
Response of workers.get_all endpoint.
:param workers:
:type workers: Sequence[Worker]
"""
_service = "workers"
_action = "get_all"
_version = "2.20"
_schema = {
"definitions": {
"current_task_entry": {
"properties": {
... | GetAllResponse |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_content_block_source_param.py | {
"start": 351,
"end": 530
} | class ____(TypedDict, total=False):
content: Required[Union[str, Iterable[BetaContentBlockSourceContentParam]]]
type: Required[Literal["content"]]
| BetaContentBlockSourceParam |
python | python__mypy | mypy/nodes.py | {
"start": 83196,
"end": 83633
} | class ____(Expression):
"""Tuple literal expression (..., ...)
Also lvalue sequences (..., ...) and [..., ...]"""
__slots__ = ("items",)
__match_args__ = ("items",)
items: list[Expression]
def __init__(self, items: list[Expression]) -> None:
super().__init__()
self.items = i... | TupleExpr |
python | huggingface__transformers | src/transformers/models/helium/modeling_helium.py | {
"start": 2708,
"end": 5708
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: HeliumConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.... | HeliumRotaryEmbedding |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_layout02.py | {
"start": 315,
"end": 1670
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_layout02.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with user defined layout."""
workbook... | TestCompareXLSXFiles |
python | networkx__networkx | networkx/exception.py | {
"start": 1993,
"end": 2136
} | class ____(NetworkXException):
"""Raised if a graph has a cycle when an algorithm expects that it
will have no cycles.
"""
| HasACycle |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 12118,
"end": 12218
} | class ____(VyperInternalException):
"""Invalid code generated during codegen phase"""
| CodegenPanic |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol1.py | {
"start": 1343,
"end": 1565
} | class ____:
def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]:
return []
# This should generate an error because NotProto is not a protocol class.
not_proto: NotProto = good_cb
| NotProto |
python | tensorflow__tensorflow | tensorflow/python/ops/resource_variable_ops.py | {
"start": 105454,
"end": 105665
} | class ____(StructurePattern):
"""Represents a singleton leaf StructurePattern."""
def __new__(cls):
if not hasattr(cls, "instance"):
cls.instance = super().__new__(cls)
return cls.instance
| PLeaf |
python | davidhalter__parso | parso/python/tree.py | {
"start": 29817,
"end": 29874
} | class ____(KeywordStatement):
__slots__ = ()
| ReturnStmt |
python | pyqtgraph__pyqtgraph | pyqtgraph/parametertree/parameterTypes/actiongroup.py | {
"start": 1276,
"end": 1924
} | class ____(GroupParameter):
itemClass = ActionGroupParameterItem
sigActivated = QtCore.Signal(object)
def __init__(self, **opts):
opts.setdefault("button", {})
super().__init__(**opts)
@QtCore.Slot()
def activate(self):
self.sigActivated.emit(self)
self.emitStateCh... | ActionGroupParameter |
python | kubernetes-client__python | kubernetes/base/stream/ws_client_test.py | {
"start": 2575,
"end": 7177
} | class ____(unittest.TestCase):
def test_websocket_client(self):
for url, ws_url in [
('http://localhost/api', 'ws://localhost/api'),
('https://localhost/api', 'wss://localhost/api'),
('https://domain.com/api', 'wss://domain.com/api'),
('https:... | WSClientTest |
python | huggingface__transformers | src/transformers/models/mistral/modular_mistral.py | {
"start": 4081,
"end": 4352
} | class ____(LlamaDecoderLayer):
def __init__(self, config: MistralConfig, layer_idx: int):
super().__init__(config, layer_idx)
self.self_attn = MistralAttention(config=config, layer_idx=layer_idx)
self.mlp = MistralMLP(config)
| MistralDecoderLayer |
python | astropy__astropy | astropy/coordinates/tests/test_representation.py | {
"start": 47988,
"end": 54694
} | class ____:
def test_name(self):
assert CylindricalRepresentation.name == "cylindrical"
assert CylindricalRepresentation.name in REPRESENTATION_CLASSES
def test_empty_init(self):
with pytest.raises(TypeError) as exc:
s = CylindricalRepresentation()
def test_init_quantit... | TestCylindricalRepresentation |
python | streamlit__streamlit | lib/tests/streamlit/web/server/upload_file_request_handler_test.py | {
"start": 1203,
"end": 1357
} | class ____(NamedTuple):
name: str
data: bytes
def _get_filename(file):
"""Sort key for lists of UploadedFiles"""
return file.name
| MockFile |
python | modin-project__modin | modin/core/dataframe/algebra/default2pandas/default.py | {
"start": 1879,
"end": 10405
} | class ____(Operator):
"""
Builder for default-to-pandas methods.
Attributes
----------
OBJECT_TYPE : str
Object type name that will be shown in default-to-pandas warning message.
DEFAULT_OBJECT_TYPE : object
Default place to search for a function.
"""
OBJECT_TYPE = "Dat... | DefaultMethod |
python | pypa__pipenv | pipenv/patched/pip/_internal/models/link.py | {
"start": 6368,
"end": 18789
} | class ____:
"""Represents a parsed link from a Package Index's simple URL"""
__slots__ = [
"_parsed_url",
"_url",
"_path",
"_hashes",
"comes_from",
"requires_python",
"yanked_reason",
"metadata_file_data",
"cache_link_parsing",
"eg... | Link |
python | plotly__plotly.py | plotly/graph_objs/layout/scene/zaxis/_tickfont.py | {
"start": 235,
"end": 9914
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.scene.zaxis"
_path_str = "layout.scene.zaxis.tickfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
... | Tickfont |
python | spack__spack | lib/spack/spack/vendor/jinja2/exceptions.py | {
"start": 364,
"end": 1291
} | class ____(IOError, LookupError, TemplateError):
"""Raised if a template does not exist.
.. versionchanged:: 2.11
If the given name is :class:`Undefined` and no message was
provided, an :exc:`UndefinedError` is raised.
"""
# Silence the Python warning about message being deprecated sin... | TemplateNotFound |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/plugins/_rope_task_handle.py | {
"start": 1838,
"end": 2883
} | class ____(BaseTaskHandle):
name: str
observers: list
job_sets: list[PylspJobSet]
stopped: bool
workspace: Workspace
_report: Callable[[str, str], None]
def __init__(self, workspace: Workspace) -> None:
self.workspace = workspace
self.job_sets = []
self.observers = [... | PylspTaskHandle |
python | getsentry__sentry | tests/sentry/api/endpoints/test_sudo.py | {
"start": 176,
"end": 1620
} | class ____(APITestCase):
def test_sudo_required_del_org(self) -> None:
org = self.create_organization()
url = reverse(
"sentry-api-0-organization-details", kwargs={"organization_id_or_slug": org.slug}
)
user = self.create_user(email="foo@example.com")
self.create... | SudoTest |
python | pyodide__pyodide | src/py/_pyodide/_base.py | {
"start": 5485,
"end": 21133
} | class ____:
"""This class allows fine control over the execution of a code block.
It is primarily intended for REPLs and other sophisticated consumers that
may wish to add their own AST transformations, separately signal to the user
when parsing is complete, etc. The simpler :py:func:`eval_code` and
... | CodeRunner |
python | sqlalchemy__sqlalchemy | test/orm/test_query.py | {
"start": 5554,
"end": 7704
} | class ____(QueryTest):
def test_single_entity_false(self):
User = self.classes.User
query = fixture_session().query(User).only_return_tuples(False)
is_true(query.is_single_entity)
row = query.first()
assert isinstance(row, User)
def test_single_entity_true(self):
... | OnlyReturnTuplesTest |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 143123,
"end": 144915
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
account_id: str,
client_secret: str,
start_date: str,
lookback_window_days: Optional[int] = None,
slice_range: Optional[int] = None,
):
r"""Airbyte Source for Stripe.
... | StripeSource |
python | weaviate__weaviate-python-client | weaviate/collections/classes/internal.py | {
"start": 12650,
"end": 14300
} | class ____:
prop: str
number_of_groups: int
objects_per_group: int
def __init__(self, prop: str, number_of_groups: int, objects_per_group: int) -> None:
self.prop = prop
self.number_of_groups = number_of_groups
self.objects_per_group = objects_per_group
def to_grpc(self) ->... | _GroupBy |
python | google__jax | jax/_src/export/_export.py | {
"start": 13694,
"end": 13954
} | class ____(Protocol):
def __call__(self, aux_data: PyTreeAuxData) -> bytes:
"""Serializes the PyTree node AuxData.
The AuxData is returned by the ``flatten_func`` registered by
:func:`jax.tree_util.register_pytree_node`).
"""
| _SerializeAuxData |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/ir.py | {
"start": 95230,
"end": 97820
} | class ____(IR):
"""Sort a dataframe."""
__slots__ = ("by", "null_order", "order", "stable", "zlice")
_non_child = ("schema", "by", "order", "null_order", "stable", "zlice")
by: tuple[expr.NamedExpr, ...]
"""Sort keys."""
order: tuple[plc.types.Order, ...]
"""Sort order for each sort key."""... | Sort |
python | pytorch__pytorch | torch/distributed/checkpoint/_experimental/config.py | {
"start": 433,
"end": 1528
} | class ____:
"""
Configuration class for checkpointer construction.
This class consolidates the core component configuration options needed to construct
a checkpointer, providing a clean separation of concerns where each component
manages its own configuration.
Attributes:
writer_config... | CheckpointerConfig |
python | pytorch__pytorch | test/distributed/checkpoint/test_state_dict_stager.py | {
"start": 32314,
"end": 33529
} | class ____(DTensorTestBase):
@with_comms
@requires_accelerator_dist_backend()
@skip_if_lt_x_gpu(2)
def test_dtensor(self):
"""
Test that StateDictStager works correctly with DTensors.
"""
# Create a DTensor
device_mesh = dist.DeviceMesh(
self.device_ty... | TestDTensorStateDictStager |
python | astral-sh__uv | scripts/benchmark/src/benchmark/resolver.py | {
"start": 1972,
"end": 2489
} | class ____(enum.Enum):
"""Enumeration of the benchmarks to run."""
RESOLVE_COLD = "resolve-cold"
RESOLVE_WARM = "resolve-warm"
RESOLVE_INCREMENTAL = "resolve-incremental"
RESOLVE_NOOP = "resolve-noop"
INSTALL_COLD = "install-cold"
INSTALL_WARM = "install-warm"
# The requirement to use whe... | Benchmark |
python | openai__openai-python | src/openai/resources/chat/completions/messages.py | {
"start": 3936,
"end": 7116
} | class ____(AsyncAPIResource):
@cached_property
def with_raw_response(self) -> AsyncMessagesWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.g... | AsyncMessages |
python | django__django | tests/csrf_tests/tests.py | {
"start": 6790,
"end": 7325
} | class ____(SessionStore):
"""
A version of SessionStore that stores what cookie values are passed to
set_cookie() when CSRF_USE_SESSIONS=True.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# This is a list of the cookie values passed to set_cookie() over... | TestingSessionStore |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 81620,
"end": 81747
} | class ____(BaseModel, extra="forbid"):
overwrite_payload: "SetPayload" = Field(..., description="")
| OverwritePayloadOperation |
python | sympy__sympy | sympy/codegen/cfunctions.py | {
"start": 5074,
"end": 6450
} | class ____(Function):
"""
Represents the logarithm function with base two.
Explanation
===========
The benefit of using ``log2(x)`` over ``log(x)/log(2)``
is that the latter is not as efficient under finite precision
arithmetic.
Examples
========
>>> from sympy.abc import x
... | log2 |
python | scrapy__scrapy | tests/test_contracts.py | {
"start": 6426,
"end": 6500
} | class ____(DemoSpider):
name = "inherits_demo_spider"
| InheritsDemoSpider |
python | matplotlib__matplotlib | lib/matplotlib/dates.py | {
"start": 62303,
"end": 64095
} | class ____(units.ConversionInterface):
"""
Converter for `datetime.date` and `datetime.datetime` data, or for
date/time data represented as it would be converted by `date2num`.
The 'unit' tag for such data is None or a `~datetime.tzinfo` instance.
"""
def __init__(self, *, interval_multiples=T... | DateConverter |
python | sympy__sympy | sympy/core/numbers.py | {
"start": 94341,
"end": 95258
} | class ____(IntegerConstant, metaclass=Singleton):
"""The number one.
One is a singleton, and can be accessed by ``S.One``.
Examples
========
>>> from sympy import S, Integer
>>> Integer(1) is S.One
True
References
==========
.. [1] https://en.wikipedia.org/wiki/1_%28number%2... | One |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_cond_format01.py | {
"start": 345,
"end": 2778
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with conditional formatting."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle... | TestAssembleWorksheet |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/observability.py | {
"start": 8045,
"end": 11839
} | class ____(BaseObservation):
__test__ = False # no! bad pytest!
type: Literal["test_case"]
status: TestCaseStatus
status_reason: str
representation: str
arguments: dict
how_generated: str
features: dict
coverage: dict[str, list[int]] | None
timing: dict[str, float]
metadata... | TestCaseObservation |
python | dask__dask | dask/dataframe/dask_expr/_reductions.py | {
"start": 20197,
"end": 22518
} | class ____(ApplyConcatApply):
_parameters = ["frame", "columns", "index", "values", "aggfunc"]
_defaults = {"columns": None, "index": None, "values": None, "aggfunc": "mean"}
@functools.cached_property
def _meta(self):
df = self.frame._meta
columns = self.operand("columns")
valu... | PivotTable |
python | doocs__leetcode | solution/0600-0699/0640.Solve the Equation/Solution.py | {
"start": 0,
"end": 838
} | class ____:
def solveEquation(self, equation: str) -> str:
def f(s):
x = y = 0
if s[0] != '-':
s = '+' + s
i, n = 0, len(s)
while i < n:
sign = 1 if s[i] == '+' else -1
i += 1
j = i
... | Solution |
python | sphinx-doc__sphinx | tests/test_ext_autodoc/test_ext_autodoc.py | {
"start": 40942,
"end": 99995
} | class ____:
def __init__(self, name: str, *, module: str = 'target.enums') -> None:
self.name = name
self.module = module
@property
def target(self) -> str:
"""The autodoc target class."""
return f'{self.module}.{self.name}'
def subtarget(self, name: str) -> str:
... | _EnumFormatter |
python | sphinx-doc__sphinx | sphinx/builders/text.py | {
"start": 527,
"end": 2959
} | class ____(Builder):
name = 'text'
format = 'text'
epilog = __('The text files are in %(outdir)s.')
out_suffix = '.txt'
allow_parallel = True
default_translator_class = TextTranslator
current_docname: str | None = None
def init(self) -> None:
# section numbers for headings in ... | TextBuilder |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/with1.py | {
"start": 2077,
"end": 2203
} | class ____(Class5[int]): ...
async def do():
async with Class6() as f:
reveal_type(f, expected_text="Class6")
| Class6 |
python | Textualize__rich | rich/prompt.py | {
"start": 10414,
"end": 12435
} | class ____(PromptBase[bool]):
"""A yes / no confirmation prompt.
Example:
>>> if Confirm.ask("Continue"):
run_job()
"""
response_type = bool
validate_error_message = "[prompt.invalid]Please enter Y or N"
choices: List[str] = ["y", "n"]
def render_default(self, def... | Confirm |
python | apache__airflow | airflow-core/src/airflow/providers_manager.py | {
"start": 6106,
"end": 6303
} | class ____:
"""
Provider information.
:param version: version string
:param data: dictionary with information about the provider
"""
version: str
data: dict
| ProviderInfo |
python | pytorch__pytorch | torch/_export/db/examples/class_method.py | {
"start": 41,
"end": 499
} | class ____(torch.nn.Module):
"""
Class methods are inlined during tracing.
"""
@classmethod
def method(cls, x):
return x + 1
def __init__(self) -> None:
super().__init__()
self.linear = torch.nn.Linear(4, 2)
def forward(self, x):
x = self.linear(x)
... | ClassMethod |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ROI.py | {
"start": 71165,
"end": 72495
} | class ____(ROI):
r"""
Rectangular ROI subclass with scale-rotate handles on either side. This
allows the ROI to be positioned as if moving the ends of a line segment.
A third handle controls the width of the ROI orthogonal to its "line" axis.
============== =====================================... | LineROI |
python | lxml__lxml | src/lxml/tests/test_xmlschema.py | {
"start": 14086,
"end": 18885
} | class ____(HelperTestCase):
resolver_schema_int = BytesIO(b"""\
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:etype="http://codespeak.net/lxml/test/external"
targetNamespace="http://codespeak.net/lxml/test/internal">
<xsd:import namespace="http://codespeak.net/lxml/test/external" sc... | ETreeXMLSchemaResolversTestCase |
python | huggingface__transformers | src/transformers/models/timesformer/modeling_timesformer.py | {
"start": 2593,
"end": 7097
} | class ____(nn.Module):
"""
Construct the patch and position embeddings.
"""
def __init__(self, config):
super().__init__()
embed_dim = config.hidden_size
num_frames = config.num_frames
drop_rate = config.hidden_dropout_prob
attention_type = config.attention_type... | TimesformerEmbeddings |
python | getsentry__sentry | src/sentry/models/projectkey.py | {
"start": 1132,
"end": 1916
} | class ____(BaseManager["ProjectKey"]):
def post_save(self, *, instance: ProjectKey, created: bool, **kwargs: object) -> None:
schedule_invalidate_project_config(
public_key=instance.public_key, trigger="projectkey.post_save"
)
def post_delete(self, instance, **kwargs):
sched... | ProjectKeyManager |
python | ray-project__ray | doc/source/serve/doc_code/intel_gaudi_inference_serve_deepspeed.py | {
"start": 351,
"end": 4909
} | class ____:
def __init__(self, model_id_or_path: str, world_size: int, local_rank: int):
"""An actor that runs a DeepSpeed inference engine.
Arguments:
model_id_or_path: Either a Hugging Face model ID
or a path to a cached model.
world_size: Total number of w... | DeepSpeedInferenceWorker |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.