language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable_py30.py | {
"start": 1799,
"end": 1898
} | class ____(metaclass=ab.ABCMeta): # [undefined-variable]
""" Notice the `ab` module. """
| SecondBad |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/common.py | {
"start": 4006,
"end": 4703
} | class ____(BaseModel):
"""
Serializer for individual bulk action responses.
Represents the outcome of a single bulk operation (create, update, or delete).
The response includes a list of successful keys and any errors encountered during the operation.
This structure helps users understand which key... | BulkActionResponse |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-primes-to-sum-to-target.py | {
"start": 139,
"end": 761
} | class ____(object):
def minNumberOfPrimes(self, n, m):
"""
:type n: int
:type m: int
:rtype: int
"""
is_prime = [True]*(n+1)
cnt = 0
dp = [float("inf")]*(n+1)
dp[0] = 0
for i in xrange(2, n+1):
if not is_prime[i]:
... | Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/vector_stores/types.py | {
"start": 7579,
"end": 9485
} | class ____(Protocol):
"""Abstract vector store protocol."""
stores_text: bool
is_embedding_query: bool = True
@property
def client(self) -> Any:
"""Get client."""
...
def add(
self,
nodes: List[BaseNode],
**add_kwargs: Any,
) -> List[str]:
"... | VectorStore |
python | google__flatbuffers | tests/MyGame/Example/ArrayStruct.py | {
"start": 252,
"end": 3712
} | class ____(object):
__slots__ = ['_tab']
@classmethod
def SizeOf(cls) -> int:
return 160
# ArrayStruct
def Init(self, buf: bytes, pos: int):
self._tab = flatbuffers.table.Table(buf, pos)
# ArrayStruct
def A(self): return self._tab.Get(flatbuffers.number_types.Float32Flags,... | ArrayStruct |
python | kamyu104__LeetCode-Solutions | Python/strange-printer.py | {
"start": 33,
"end": 661
} | class ____(object):
def strangePrinter(self, s):
"""
:type s: str
:rtype: int
"""
def dp(s, i, j, lookup):
if i > j:
return 0
if (i, j) not in lookup:
lookup[(i, j)] = dp(s, i, j-1, lookup) + 1
for k in ... | Solution |
python | milvus-io__pymilvus | pymilvus/grpc_gen/milvus_pb2_grpc.py | {
"start": 195375,
"end": 196494
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
def RegisterLink(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
... | ProxyServiceServicer |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_qt.py | {
"start": 45982,
"end": 46161
} | class ____(_Backend):
backend_version = __version__
FigureCanvas = FigureCanvasQT
FigureManager = FigureManagerQT
mainloop = FigureManagerQT.start_main_loop
| _BackendQT |
python | Textualize__textual | tests/suggester/test_suggester.py | {
"start": 288,
"end": 3211
} | class ____(DOMNode):
def __init__(self, log_list: list[tuple[str, str]]) -> None:
self.log_list = log_list
def post_message(self, message: SuggestionReady):
# We hijack post_message so we can intercept messages without creating a full app.
self.log_list.append((message.suggestion, messa... | LogListNode |
python | jmcnamara__XlsxWriter | xlsxwriter/exceptions.py | {
"start": 713,
"end": 831
} | class ____(XlsxInputError):
"""Worksheet name is too long or contains restricted characters."""
| InvalidWorksheetName |
python | sympy__sympy | sympy/physics/wigner.py | {
"start": 29565,
"end": 37900
} | class ____(Function):
def doit(self, **hints):
if all(obj.is_number for obj in self.args):
return wigner_3j(*self.args)
else:
return self
def dot_rot_grad_Ynm(j, p, l, m, theta, phi):
r"""
Returns dot product of rotational gradients of spherical harmonics.
Expl... | Wigner3j |
python | django-guardian__django-guardian | guardian/testapp/tests/conf.py | {
"start": 897,
"end": 2611
} | class ____:
"""
Acts as either a decorator, or a context manager. If it's a decorator it
takes a function and returns a wrapped function. If it's a contextmanager
it's used with the `with` statement. In either event entering/exiting
are called before and after, respectively, the function/block is ex... | override_settings |
python | django-mptt__django-mptt | tests/myapp/models.py | {
"start": 6662,
"end": 6881
} | class ____(MPTTModel):
parent = TreeForeignKey(
"self", null=True, blank=True, related_name="children", on_delete=models.CASCADE
)
class Meta:
swappable = "MPTT_SWAPPABLE_MODEL"
| SwappableModel |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 116171,
"end": 116425
} | class ____(OpAlignPartitions):
_parameters = ["frame", "other", "op", "axis", "level", "fill_value"]
@staticmethod
def _op(frame, op, other, *args, **kwargs):
return MethodOperator(op, frame, other, *args, **kwargs)
| MethodOperatorAlign |
python | pallets__jinja | tests/test_ext.py | {
"start": 6047,
"end": 7132
} | class ____(Extension):
def filter_stream(self, stream):
for token in stream:
if token.type == "data":
yield from self.interpolate(token)
else:
yield token
def interpolate(self, token):
pos = 0
end = len(token.value)
lineno ... | StreamFilterExtension |
python | google__pytype | pytype/tests/test_match2.py | {
"start": 13789,
"end": 15488
} | class ____(test_base.BaseTest):
"""Tests for matching types."""
# Forked into py2 and py3 versions
def test_callable(self):
ty = self.Infer("""
import tokenize
def f():
pass
x = tokenize.generate_tokens(f)
""")
self.assertTypesMatchPytd(
ty,
"""
from t... | MatchTestPy3 |
python | django__django | tests/logging_tests/tests.py | {
"start": 3016,
"end": 4353
} | class ____:
def assertLogRecord(
self,
logger_cm,
msg,
levelno,
status_code,
request=None,
exc_class=None,
):
self.assertEqual(
records_len := len(logger_cm.records),
1,
f"Wrong number of calls for {logger_cm=} ... | LoggingAssertionMixin |
python | PrefectHQ__prefect | tests/server/orchestration/test_core_policy.py | {
"start": 21669,
"end": 26616
} | class ____:
async def test_can_manual_retry_with_arbitrary_state_name(
self,
session,
initialize_orchestration,
):
manual_retry_policy = [HandleFlowTerminalStateTransitions]
initial_state_type = states.StateType.FAILED
proposed_state_type = states.StateType.SCHEDU... | TestManualFlowRetries |
python | patrick-kidger__equinox | equinox/_module/_module.py | {
"start": 2629,
"end": 2995
} | class ____(Exception):
pass
def _is_array_like(x: object, /) -> None:
if is_array_like(x):
raise _JaxTransformException
_MSG_JAX_XFM_FUNC: Final = """
Possibly assigning a JAX-transformed callable as an attribute on
{0}.{1}. This will not have any of its parameters updated.
For example, the followi... | _JaxTransformException |
python | pypa__pipenv | pipenv/vendor/click/core.py | {
"start": 76398,
"end": 92552
} | class ____:
r"""A parameter to a command comes in two versions: they are either
:class:`Option`\s or :class:`Argument`\s. Other subclasses are currently
not supported by design as some of the internals for parsing are
intentionally not finalized.
Some settings are supported by both options and arg... | Parameter |
python | mlflow__mlflow | dev/clint/src/clint/rules/log_model_artifact_path.py | {
"start": 177,
"end": 1800
} | class ____(Rule):
def _message(self) -> str:
return "`artifact_path` parameter of `log_model` is deprecated. Use `name` instead."
@staticmethod
def check(node: ast.Call, index: "SymbolIndex") -> bool:
"""
Returns True if the call looks like `mlflow.<flavor>.log_model(...)` and
... | LogModelArtifactPath |
python | euske__pdfminer | pdfminer/utils.py | {
"start": 7362,
"end": 9666
} | class ____:
def __init__(self, bbox, gridsize=50):
self._seq = [] # preserve the object order.
self._objs = set()
self._grid = {}
self.gridsize = gridsize
(self.x0, self.y0, self.x1, self.y1) = bbox
return
def __repr__(self):
return ('<Plane obj... | Plane |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 714161,
"end": 714703
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("body", "key", "name", "resource_path", "url")
body = sgqlc.types.Field(String, graphql_name="body")
key = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="... | CodeOfConduct |
python | openai__openai-python | src/openai/types/beta/code_interpreter_tool.py | {
"start": 196,
"end": 333
} | class ____(BaseModel):
type: Literal["code_interpreter"]
"""The type of tool being defined: `code_interpreter`"""
| CodeInterpreterTool |
python | sqlalchemy__sqlalchemy | test/sql/test_type_expressions.py | {
"start": 13181,
"end": 15887
} | class ____:
@testing.requires.insertmanyvalues
def test_insertmanyvalues_returning(self, connection):
tt = self.tables.test_table
result = connection.execute(
tt.insert().returning(tt.c["x", "y"]),
[
{"x": "X1", "y": "Y1"},
{"x": "X2", "y":... | RoundTripTestBase |
python | ray-project__ray | doc/source/ray-core/doc_code/streaming_generator.py | {
"start": 1188,
"end": 4172
} | class ____:
def f(self):
for i in range(5):
yield i
actor = Actor.remote()
for ref in actor.f.remote():
print(ray.get(ref))
actor = AsyncActor.remote()
for ref in actor.f.remote():
print(ray.get(ref))
actor = ThreadedActor.remote()
for ref in actor.f.remote():
print(ray.get(ref))
... | ThreadedActor |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zoho-crm/source_zoho_crm/streams.py | {
"start": 707,
"end": 2656
} | class ____(HttpStream, ABC):
primary_key: str = "id"
module: ModuleMeta = None
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
if response.status_code in EMPTY_BODY_STATUSES:
return None
pagination = response.json()["info"]
if not p... | ZohoCrmStream |
python | kamyu104__LeetCode-Solutions | Python/counting-elements.py | {
"start": 272,
"end": 672
} | class ____(object):
def countElements(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
arr.sort()
result, l = 0, 1
for i in xrange(len(arr)-1):
if arr[i] == arr[i+1]:
l += 1
continue
if arr[i]+1 == ar... | Solution |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 7829,
"end": 8141
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
start: PyrePosition
end: PyrePosition
def to_lsp_range(self) -> "LspRange":
return LspRange(
start=self.start.to_lsp_position(),
end=self.end.to_lsp_position(),
)
@dataclasses.dataclass(frozen=True)
| PyreRange |
python | pytorch__pytorch | torch/fx/experimental/unification/multipledispatch/dispatcher.py | {
"start": 573,
"end": 3147
} | class ____(NotImplementedError):
"""A NotImplementedError for multiple dispatch"""
def ambiguity_warn(dispatcher, ambiguities):
"""Raise warning when ambiguity is detected
Parameters
----------
dispatcher : Dispatcher
The dispatcher on which the ambiguity was detected
ambiguities : set... | MDNotImplementedError |
python | pytorch__pytorch | torch/distributed/flight_recorder/components/types.py | {
"start": 1190,
"end": 2156
} | class ____(Enum):
"""
Enum representing the possible states of matching for collective operations.
- FULLY_MATCHED: Indicates that all aspects of the collective operations match.
- COLLECTIVE_TYPE_MISMATCH: The types of the collective operations differ.
- SIZE_OR_SYNTAX_MISMATCH: There is a mismatc... | MatchState |
python | huggingface__transformers | src/transformers/integrations/mxfp4.py | {
"start": 3730,
"end": 4824
} | class ____(ConversionOps):
def __init__(self, hf_quantizer):
self.hf_quantizer = hf_quantizer
def convert(
self,
input_dict: dict[str, torch.Tensor],
model: Optional[torch.nn.Module] = None,
full_layer_name: str | None = None,
missing_keys=None,
**kwargs,... | Mxfp4Dequantize |
python | numba__numba | numba/core/pythonapi.py | {
"start": 2692,
"end": 3084
} | class ____(object):
"""
Encapsulate the result of converting a Python object to a native value,
recording whether the conversion was successful and how to cleanup.
"""
def __init__(self, value, is_error=None, cleanup=None):
self.value = value
self.is_error = is_error if is_error is ... | NativeValue |
python | pytransitions__transitions | transitions/extensions/nesting.py | {
"start": 2423,
"end": 3668
} | class ____(object):
"""A wrapper to enable transitions' convenience function to_<state> for nested states.
This allows to call model.to_A.s1.C() in case a custom separator has been chosen."""
def __init__(self, func):
"""
Args:
func: Function to be called at the end of the pa... | FunctionWrapper |
python | Pylons__pyramid | docs/tutorials/wiki2/src/authentication/tutorial/models/user.py | {
"start": 137,
"end": 885
} | class ____(Base):
""" The SQLAlchemy declarative model class for a User object. """
__tablename__ = 'users'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(unique=True)
role: Mapped[str]
password_hash: Mapped[Optional[str]]
def set_password(self, pw):
... | User |
python | crytic__slither | slither/slithir/tmp_operations/argument.py | {
"start": 257,
"end": 1201
} | class ____(Operation):
def __init__(self, argument: Expression) -> None:
super().__init__()
self._argument = argument
self._type = ArgumentType.CALL
self._callid: Optional[str] = None
@property
def argument(self) -> Expression:
return self._argument
@property
... | Argument |
python | huggingface__transformers | src/transformers/data/datasets/glue.py | {
"start": 2164,
"end": 2239
} | class ____(Enum):
train = "train"
dev = "dev"
test = "test"
| Split |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_assorted_poly.py | {
"start": 65535,
"end": 67387
} | class ____(fixtures.DeclarativeMappedTest):
"""Test [ticket:2419]'s test case."""
@classmethod
def setup_classes(cls):
Base = cls.DeclarativeBasic
class A(Base):
__tablename__ = "a"
id = Column(
Integer, primary_key=True, test_needs_autoincrement=Tr... | Ticket2419Test |
python | google__jax | jax/_src/interpreters/partial_eval.py | {
"start": 32321,
"end": 54012
} | class ____(NamedTuple):
eqn_id: Any
in_tracers: Sequence[JaxprTracer]
out_tracer_refs: Sequence[ref[JaxprTracer]]
out_avals: Sequence[core.AbstractValue]
primitive: Primitive
params: dict[str, Any]
effects: core.Effects
source_info: source_info_util.SourceInfo
ctx: JaxprEqnContext
def new_eqn_recipe(... | JaxprEqnRecipe |
python | pandas-dev__pandas | pandas/core/_numba/extensions.py | {
"start": 1937,
"end": 2671
} | class ____(types.Type):
"""
The type class for Index objects.
"""
def __init__(self, dtype, layout, pyclass: any) -> None:
self.pyclass = pyclass
name = f"index({dtype}, {layout})"
self.dtype = dtype
self.layout = layout
super().__init__(name)
@property
... | IndexType |
python | walkccc__LeetCode | solutions/705. Design HashSet/705.py | {
"start": 0,
"end": 264
} | class ____:
def __init__(self):
self.set = [False] * 1000001
def add(self, key: int) -> None:
self.set[key] = True
def remove(self, key: int) -> None:
self.set[key] = False
def contains(self, key: int) -> bool:
return self.set[key]
| MyHashSet |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_index_returned.py | {
"start": 411,
"end": 517
} | class ____(type):
def __index__(cls):
return 1
@six.add_metaclass(IndexMetaclass)
| IndexMetaclass |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/ir.py | {
"start": 70738,
"end": 75507
} | class ____(IR):
"""A conditional inner join of two dataframes on a predicate."""
class Predicate:
"""Serializable wrapper for a predicate expression."""
predicate: expr.Expr
ast: plc.expressions.Expression
def __init__(self, predicate: expr.Expr):
self.predicate = ... | ConditionalJoin |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/_redaction.py | {
"start": 602,
"end": 9918
} | class ____(Exception):
"""Raised when configured to block on detected sensitive values."""
def __init__(self, pii_type: str, matches: Sequence[PIIMatch]) -> None:
"""Initialize the exception with match context.
Args:
pii_type: Name of the detected sensitive type.
matche... | PIIDetectionError |
python | davidhalter__jedi | test/completion/ordering.py | {
"start": 1037,
"end": 1646
} | class ____(object):
a = ""
a = 3
#? int()
a
a = list()
def __init__(self):
self.b = ""
def before(self):
self.b = 3
# TODO should this be so? include entries after cursor?
#? int() str() list
self.b
self.b = list
self.a = 1
#?... | A |
python | wntrblm__nox | tests/test_sessions.py | {
"start": 3344,
"end": 39618
} | class ____:
def make_session_and_runner(
self,
) -> tuple[nox.sessions.Session, nox.sessions.SessionRunner]:
func = mock.Mock(spec=["python"], python="3.7")
runner = nox.sessions.SessionRunner(
name="test",
signatures=["test"],
func=func,
g... | TestSession |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/function7.py | {
"start": 497,
"end": 588
} | class ____(Protocol):
def write(self, a: str, /, b: str) -> object:
pass
| _Writer2 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/source_shopify/utils.py | {
"start": 682,
"end": 2151
} | class ____:
"""Holds the errors classification and messaging scenarios."""
def __new__(self, stream: str) -> Mapping[str, Any]:
return {
401: ErrorResolution(
response_action=ResponseAction.IGNORE,
failure_type=FailureType.config_error,
error_... | ShopifyNonRetryableErrors |
python | has2k1__plotnine | plotnine/scales/scale_color.py | {
"start": 14820,
"end": 14893
} | class ____(scale_color_desaturate):
pass
@alias
| scale_colour_desaturate |
python | falconry__falcon | falcon/asgi/reader.py | {
"start": 1005,
"end": 12595
} | class ____:
"""File-like input object wrapping asynchronous iterator over bytes.
This class implements coroutine functions for asynchronous reading or
iteration, but otherwise provides an interface similar to that defined by
:class:`io.IOBase`.
"""
__slots__ = [
'_buffer',
'_bu... | BufferedReader |
python | pytorch__pytorch | test/profiler/test_profiler.py | {
"start": 2592,
"end": 5745
} | class ____(TestCase):
def test_mem_leak(self):
"""Checks that there's no memory leak when using profiler with CUDA"""
t = torch.rand(1, 1).cuda()
p = psutil.Process()
last_rss = collections.deque(maxlen=5)
for _ in range(10):
with _profile(use_cuda=True):
... | TestProfilerCUDA |
python | pandas-dev__pandas | pandas/tests/arithmetic/test_datetime64.py | {
"start": 59902,
"end": 64300
} | class ____:
# TODO: box + de-duplicate
def test_dt64_overflow_masking(self, box_with_array):
# GH#25317
left = Series([Timestamp("1969-12-31")], dtype="M8[ns]")
right = Series([NaT])
left = tm.box_expected(left, box_with_array)
right = tm.box_expected(right, box_with_ar... | TestDatetime64OverflowHandling |
python | doocs__leetcode | solution/1600-1699/1648.Sell Diminishing-Valued Colored Balls/Solution.py | {
"start": 0,
"end": 914
} | class ____:
def maxProfit(self, inventory: List[int], orders: int) -> int:
inventory.sort(reverse=True)
mod = 10**9 + 7
ans = i = 0
n = len(inventory)
while orders > 0:
while i < n and inventory[i] >= inventory[0]:
i += 1
nxt = 0
... | Solution |
python | google__jax | jax/_src/source_info_util.py | {
"start": 9920,
"end": 10455
} | class ____(contextlib.ContextDecorator):
__slots__ = ['name', 'prev']
def __init__(self, name: str):
self.name = name
def __enter__(self):
self.prev = prev = _source_info_context.context
name_stack = prev.name_stack.transform(self.name)
_source_info_context.context = prev.replace(name_stack=name... | TransformNameStackContextManager |
python | getsentry__sentry | tests/sentry/workflow_engine/processors/test_data_condition_group.py | {
"start": 7371,
"end": 9539
} | class ____(TestEvaluationConditionCase):
def setUp(self) -> None:
super().setUp()
self.data_condition_group.logic_type = DataConditionGroup.Type.ANY_SHORT_CIRCUIT
def test_evaluate_data_conditions__passes_all(self) -> None:
assert evaluate_data_conditions(
self.get_condition... | TestEvaluateConditionGroupTypeAnyShortCircuit |
python | apache__airflow | providers/papermill/src/airflow/providers/papermill/hooks/kernel.py | {
"start": 1368,
"end": 1582
} | class ____:
"""Class to represent kernel connection object."""
ip: str
shell_port: int
iopub_port: int
stdin_port: int
control_port: int
hb_port: int
session_key: str
| KernelConnection |
python | allegroai__clearml | clearml/backend_api/services/v2_9/queues.py | {
"start": 6757,
"end": 12711
} | class ____(NonStrictDataModel):
"""
:param id: Queue id
:type id: str
:param name: Queue name
:type name: str
:param user: Associated user id
:type user: str
:param company: Company id
:type company: str
:param created: Queue creation time
:type created: datetime.datetime
... | Queue |
python | fabric__fabric | fabric/exceptions.py | {
"start": 172,
"end": 562
} | class ____(Exception):
"""
Lightweight exception wrapper for `.GroupResult` when one contains errors.
.. versionadded:: 2.0
"""
def __init__(self, result):
#: The `.GroupResult` object which would have been returned, had there
#: been no errors. See its docstring (and that of `.Gro... | GroupException |
python | dagster-io__dagster | python_modules/dagster-webserver/dagster_webserver_tests/webserver/conftest.py | {
"start": 536,
"end": 1432
} | class ____(DagsterWebserver):
def test_req_ctx_endpoint(self, request: Request):
with self.request_context(request) as ctx:
# instantiate cached property with backref
_ = ctx.instance_queryer
return JSONResponse({"name": ctx.__class__.__name__})
def build_routes(self... | TestDagsterWebserver |
python | explosion__spaCy | spacy/errors.py | {
"start": 47,
"end": 1559
} | class ____(type):
def __getattribute__(self, code):
msg = super().__getattribute__(code)
if code.startswith("__"): # python system attributes like __class__
return msg
else:
return "[{code}] {msg}".format(code=code, msg=msg)
def setup_default_warnings():
# igno... | ErrorsWithCodes |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/assets/job/asset_job.py | {
"start": 8315,
"end": 30964
} | class ____(AssetGraph):
"""An AssetGraph that is scoped to a particular job."""
def __init__(
self,
asset_nodes_by_key: Mapping[AssetKey, AssetNode],
assets_defs_by_check_key: Mapping[AssetCheckKey, AssetsDefinition],
source_asset_graph: AssetGraph,
):
super().__init... | JobScopedAssetGraph |
python | PyCQA__pylint | pylint/extensions/eq_without_hash.py | {
"start": 606,
"end": 1470
} | class ____(checkers.BaseChecker):
name = "eq-without-hash"
msgs = {
"W1641": (
"Implementing __eq__ without also implementing __hash__",
"eq-without-hash",
"Used when a class implements __eq__ but not __hash__. Objects get "
"None as their default __hash_... | EqWithoutHash |
python | walkccc__LeetCode | solutions/2113. Elements in Array After Removing and Replacing Elements/2113.py | {
"start": 0,
"end": 459
} | class ____:
def elementInNums(
self,
nums: list[int],
queries: list[list[int]],
) -> list[int]:
n = len(nums)
def f(time: int, index: int) -> int:
if time < n: # [0, 1, 2] -> [1, 2] -> [2]
index += time
return -1 if index >= n else nums[index]
else: # [] -> [... | Solution |
python | sqlalchemy__sqlalchemy | examples/syntax_extensions/qualify.py | {
"start": 669,
"end": 2403
} | class ____(SyntaxExtension, ClauseElement):
"""Define the QUALIFY class."""
predicate: ColumnElement[bool]
"""A single column expression that is the predicate within the QUALIFY."""
_traverse_internals = [
("predicate", visitors.InternalTraversal.dp_clauseelement)
]
"""This structure d... | Qualify |
python | google__jax | jax/_src/pallas/core.py | {
"start": 9896,
"end": 10227
} | class ____:
"""Use to index an array using an elementwise start index."""
block_size: int
padding: tuple[int, int] = (0, 0)
def __str__(self):
if self.padding == (0, 0):
return f"Element({self.block_size})"
return f"Element({self.block_size}, padding={self.padding})"
@dataclasses.dataclass(froze... | Element |
python | pandas-dev__pandas | pandas/plotting/_matplotlib/converter.py | {
"start": 12075,
"end": 30846
} | class ____(mdates.DateLocator):
UNIT = 1.0 / (24 * 3600 * 1000)
def __init__(self, tz) -> None:
mdates.DateLocator.__init__(self, tz)
self._interval = 1.0
def _get_unit(self):
return self.get_unit_generic(-1)
@staticmethod
def get_unit_generic(freq):
unit = mdates.... | MilliSecondLocator |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/base.py | {
"start": 54870,
"end": 55332
} | class ____(NamedTuple):
columns: Optional[Sequence[Column[Any]]] = None
is_explicit: bool = False
is_autoinc: bool = False
default_characterization: _SentinelDefaultCharacterization = (
_SentinelDefaultCharacterization.NONE
)
_COLKEY = TypeVar("_COLKEY", Union[None, str], str)
_COL_co = T... | _SentinelColumnCharacterization |
python | huggingface__transformers | src/transformers/models/phi4_multimodal/modular_phi4_multimodal.py | {
"start": 50506,
"end": 58903
} | class ____(Phi4MultimodalAudioPreTrainedModel):
def __init__(self, config: Phi4MultimodalAudioConfig):
super().__init__(config)
self.config = config
self.encoder_embedding = Phi4MultimodalAudioMeanVarianceNormLayer(config)
self.embed = Phi4MultimodalAudioNemoConvSubsampling(config)
... | Phi4MultimodalAudioModel |
python | ansible__ansible | lib/ansible/_internal/_wrapt.py | {
"start": 13913,
"end": 14151
} | class ____(ObjectProxy):
def __call__(*args, **kwargs):
def _unpack_self(self, *args):
return self, args
self, args = _unpack_self(*args)
return self.__wrapped__(*args, **kwargs)
| CallableObjectProxy |
python | huggingface__transformers | src/transformers/models/switch_transformers/modular_switch_transformers.py | {
"start": 29896,
"end": 33250
} | class ____(SwitchTransformersPreTrainedModel):
_tied_weights_keys = {
"encoder.embed_tokens.weight": "shared.weight",
"decoder.embed_tokens.weight": "shared.weight",
}
def __init__(self, config: SwitchTransformersConfig):
super().__init__(config)
self.shared = nn.Embedding(c... | SwitchTransformersModel |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 953592,
"end": 957027
} | class ____(Predicate):
"""
FieldLTEPredicate schema wrapper.
Parameters
----------
field : str, :class:`FieldName`
Field to be tested.
lte : str, dict, float, :class:`ExprRef`, :class:`DateTime`
The value that the field should be less than or equals to.
timeUnit : dict, :cla... | FieldLTEPredicate |
python | ray-project__ray | python/ray/tune/search/variant_generator.py | {
"start": 17305,
"end": 17420
} | class ____(Exception):
def __init__(self, msg: str):
Exception.__init__(self, msg)
| RecursiveDependencyError |
python | scipy__scipy | scipy/sparse/linalg/_interface.py | {
"start": 24564,
"end": 25717
} | class ____(LinearOperator):
def __init__(self, A, alpha):
if not isinstance(A, LinearOperator):
raise ValueError('LinearOperator expected as A')
if not np.isscalar(alpha):
raise ValueError('scalar expected as alpha')
if isinstance(A, _ScaledLinearOperator):
... | _ScaledLinearOperator |
python | altair-viz__altair | tests/utils/test_schemapi.py | {
"start": 2634,
"end": 2759
} | class ____(_TestSchema):
_schema = {"$ref": "#/definitions/StringMapping"}
_rootschema = MySchema._schema
| StringMapping |
python | PrefectHQ__prefect | src/prefect/input/run_input.py | {
"start": 1008,
"end": 1590
} | class ____(RunInput):
number: int
@flow
async def sender_flow(receiver_flow_run_id: UUID):
logger = get_run_logger()
the_number = random.randint(1, 100)
await NumberData(number=the_number).send_to(receiver_flow_run_id)
receiver = NumberData.receive(flow_run_id=receiver_flow_run_id)
squared ... | NumberData |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/executors/ecs/test_utils.py | {
"start": 4681,
"end": 9232
} | class ____:
"""Test EcsExecutorTask class."""
def test_ecs_executor_task_creation(self):
"""Test EcsExecutorTask object creation."""
task_arn = "arn:aws:ecs:us-east-1:123456789012:task/test-task"
last_status = "RUNNING"
desired_status = "RUNNING"
containers = [{"name": "... | TestEcsExecutorTask |
python | Pylons__pyramid | src/pyramid/httpexceptions.py | {
"start": 19454,
"end": 19929
} | class ____(_HTTPMove):
"""
subclass of :class:`~_HTTPMove`
This indicates that the requested resource resides permanently
under a different URI and that the request method must not be
changed.
code: 308, title: Permanent Redirect
"""
code = 308
title = 'Permanent Redirect'
#####... | HTTPPermanentRedirect |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_project_forms.py | {
"start": 23392,
"end": 26128
} | class ____(TestCase):
def setUp(self):
self.user_owner = get(User)
self.social_owner = get(
SocialAccount, user=self.user_owner, provider=GitHubProvider.id
)
self.user_admin = get(User)
self.social_admin = get(
SocialAccount, user=self.user_admin, prov... | TestProjectPrevalidationFormsWithOrganizations |
python | ray-project__ray | rllib/algorithms/impala/impala.py | {
"start": 2434,
"end": 23052
} | class ____(AlgorithmConfig):
"""Defines a configuration class from which an Impala can be built.
.. testcode::
from ray.rllib.algorithms.impala import IMPALAConfig
config = (
IMPALAConfig()
.environment("CartPole-v1")
.env_runners(num_env_runners=1)
... | IMPALAConfig |
python | huggingface__transformers | src/transformers/models/conditional_detr/modeling_conditional_detr.py | {
"start": 3521,
"end": 4655
} | class ____(Seq2SeqModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the decoder of the model.
intermediate_hidden_states (`torch.FloatTensor` of shape `(config.decoder_layers,... | ConditionalDetrModelOutput |
python | getsentry__sentry | src/sentry/integrations/example/integration.py | {
"start": 8489,
"end": 8546
} | class ____(ExampleIntegration):
pass
| AliasedIntegration |
python | walkccc__LeetCode | solutions/1610. Maximum Number of Visible Points/1610.py | {
"start": 0,
"end": 619
} | class ____:
def visiblePoints(
self,
points: list[list[int]],
angle: int,
location: list[int],
) -> int:
posX, posY = location
maxVisible = 0
same = 0
A = []
for x, y in points:
if x == posX and y == posY:
same += 1
else:
A.append(math.atan2(y... | Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/test/steps/python_connectors.py | {
"start": 1230,
"end": 8129
} | class ____(Step, ABC):
"""An abstract class to run pytest tests and evaluate success or failure according to pytest logs."""
context: ConnectorTestContext
PYTEST_INI_FILE_NAME = "pytest.ini"
PYPROJECT_FILE_NAME = "pyproject.toml"
common_test_dependencies: List[str] = []
skipped_exit_code = 5
... | PytestStep |
python | kamyu104__LeetCode-Solutions | Python/count-k-reducible-numbers-less-than-n.py | {
"start": 828,
"end": 1931
} | class ____(object):
def countKReducibleNumbers(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
MOD = 10**9+7
fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]
def nCr(n, k):
while len(inv) <= n: # lazy initialization
... | Solution2 |
python | PrefectHQ__prefect | tests/cli/test_work_pool.py | {
"start": 17265,
"end": 17675
} | class ____:
async def test_pause(self, prefect_client, work_pool):
assert work_pool.is_paused is False
res = await run_sync_in_worker_thread(
invoke_and_assert,
f"work-pool pause {work_pool.name}",
)
assert res.exit_code == 0
client_res = await prefect... | TestPause |
python | spyder-ide__spyder | spyder/api/widgets/status.py | {
"start": 8297,
"end": 9982
} | class ____(StatusBarWidget):
"""
Base class for status bar widgets that update based on timers.
"""
def __init__(self, parent=None):
"""Base class for status bar widgets that update based on timers."""
self.timer = None # Needs to come before parent call
super().__init__(parent... | BaseTimerStatus |
python | joke2k__faker | tests/providers/test_phone_number.py | {
"start": 6660,
"end": 11876
} | class ____:
"""Test en_PH phone number provider methods"""
@classmethod
def setup_class(cls):
cls.mobile_number_pattern: Pattern = re.compile(r"^(?:0|\+63)(\d+)-\d{3}-\d{4}$")
cls.area2_landline_number_pattern: Pattern = re.compile(r"^(?:0|\+63)2-(\d{4})-\d{4}")
cls.non_area2_landli... | TestEnPh |
python | spyder-ide__spyder | spyder/api/widgets/menus.py | {
"start": 17530,
"end": 18387
} | class ____(SpyderMenu):
"""
Options menu for PluginMainWidget.
"""
def render(self):
"""Render the menu's bottom section as expected."""
if self._dirty:
self.clear()
self._add_missing_actions()
bottom = OptionsMenuSections.Bottom
actions ... | PluginMainWidgetOptionsMenu |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-upstage/llama_index/readers/upstage/document_parse.py | {
"start": 2557,
"end": 14643
} | class ____(BaseReader):
"""
Upstage Document Parse Reader.
To use, you should have the environment variable `UPSTAGE_API_KEY`
set with your API key or pass it as a named parameter to the constructor.
Example:
.. code-block:: python
from llama_index.readers.file import UpstageD... | UpstageDocumentParseReader |
python | google__jax | tests/mosaic/gpu_test.py | {
"start": 153338,
"end": 154403
} | class ____(TestCase, jtu.JaxTestCase):
def test_profiler(self):
def body(ctx, input, result, scratch):
del scratch
with ctx.named_region("load"):
reg = mgpu.FragmentedArray.load_strided(input)
with ctx.named_region("store"):
reg.store_untiled(result)
dtype = jnp.bfloat16
... | ProfilerTest |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-file/llama_index/readers/file/tabular/base.py | {
"start": 314,
"end": 1659
} | class ____(BaseReader):
"""
CSV parser.
Args:
concat_rows (bool): whether to concatenate all rows into one document.
If set to False, a Document will be created for each row.
True by default.
"""
def __init__(self, *args: Any, concat_rows: bool = True, **kwargs: An... | CSVReader |
python | numpy__numpy | numpy/testing/_private/utils.py | {
"start": 79206,
"end": 98732
} | class ____:
"""
Context manager and decorator doing much the same as
``warnings.catch_warnings``.
However, it also provides a filter mechanism to work around
https://bugs.python.org/issue4180.
This bug causes Python before 3.4 to not reliably show warnings again
after they have been ignore... | suppress_warnings |
python | numba__numba | numba/core/typing/arraydecl.py | {
"start": 26287,
"end": 31495
} | class ____(ArrayAttribute):
key = types.NestedArray
def _expand_integer(ty):
"""
If *ty* is an integer, expand it to a machine int (like Numpy).
"""
if isinstance(ty, types.Integer):
if ty.signed:
return max(types.intp, ty)
else:
return max(types.uintp, ty)
... | NestedArrayAttribute |
python | modin-project__modin | modin/core/computation/scope.py | {
"start": 3509,
"end": 11172
} | class ____:
"""
Object to hold scope, with a few bells to deal with some custom syntax
and contexts added by pandas.
Parameters
----------
level : int
global_dict : dict or None, optional, default None
local_dict : dict or Scope or None, optional, default None
resolvers : list-like ... | Scope |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1589465,
"end": 1589851
} | class ____(sgqlc.types.Union):
"""Types of memberships that can be restored for an Organization
member.
"""
__schema__ = github_schema
__types__ = (
OrgRestoreMemberMembershipOrganizationAuditEntryData,
OrgRestoreMemberMembershipRepositoryAuditEntryData,
OrgRestoreMemberMemb... | OrgRestoreMemberAuditEntryMembership |
python | eventlet__eventlet | eventlet/green/zmq.py | {
"start": 3863,
"end": 7058
} | class ____(__zmq__.Context):
"""Subclass of :class:`zmq.Context`
"""
def socket(self, socket_type):
"""Overridden method to ensure that the green version of socket is used
Behaves the same as :meth:`zmq.Context.socket`, but ensures
that a :class:`Socket` with all of its send and re... | Context |
python | anthropics__anthropic-sdk-python | src/anthropic/resources/beta/skills/skills.py | {
"start": 1501,
"end": 11897
} | class ____(SyncAPIResource):
@cached_property
def versions(self) -> Versions:
return Versions(self._client)
@cached_property
def with_raw_response(self) -> SkillsWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw respons... | Skills |
python | wandb__wandb | wandb/apis/public/runs.py | {
"start": 5627,
"end": 16474
} | class ____(SizedPaginator["Run"]):
"""A lazy iterator of `Run` objects associated with a project and optional filter.
Runs are retrieved in pages from the W&B server as needed.
This is generally used indirectly using the `Api.runs` namespace.
Args:
client: (`wandb.apis.public.RetryingClient`)... | Runs |
python | pytorch__pytorch | torch/optim/lbfgs.py | {
"start": 8177,
"end": 20094
} | class ____(Optimizer):
"""Implements L-BFGS algorithm.
Heavily inspired by `minFunc
<https://www.cs.ubc.ca/~schmidtm/Software/minFunc.html>`_.
.. warning::
This optimizer doesn't support per-parameter options and parameter
groups (there can be only one).
.. warning::
Right... | LBFGS |
python | econchick__interrogate | tests/functional/sample/partial.py | {
"start": 1533,
"end": 1613
} | class ____:
def method_bar(self):
class InnerBar:
pass
| Bar |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.