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 | kamyu104__LeetCode-Solutions | Python/minimum-cost-to-separate-sentence-into-rows.py | {
"start": 1202,
"end": 2247
} | class ____(object):
def minimumCost(self, sentence, k):
"""
:type sentence: str
:type k: int
:rtype: int
"""
word_lens = []
j = 0
for i in xrange(len(sentence)+1):
if i != len(sentence) and sentence[i] != ' ':
continue
... | Solution2 |
python | doocs__leetcode | solution/0600-0699/0687.Longest Univalue Path/Solution.py | {
"start": 192,
"end": 719
} | class ____:
def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
l, r = dfs(root.left), dfs(root.right)
l = l + 1 if root.left and root.left.val == root.val else 0
r... | Solution |
python | numba__numba | numba/cuda/tests/cudapy/test_lineinfo.py | {
"start": 313,
"end": 6855
} | class ____(CUDATestCase):
def _loc_directive_regex(self):
# This is used in several tests
pat = (
r'\.loc' # .loc directive beginning
r'\s+[0-9]+' # whitespace then file index
r'\s+[0-9]+' # whitespace then line number
r'\s+[0-9]+' # whitespac... | TestCudaLineInfo |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 387109,
"end": 387963
} | class ____(sgqlc.types.Interface):
"""An object that can be closed"""
__schema__ = github_schema
__field_names__ = ("closed", "closed_at", "viewer_can_close", "viewer_can_reopen")
closed = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="closed")
"""Indicates if the object is closed (... | Closable |
python | fluentpython__example-code | 17-futures/countries/flags2_asyncio_executor.py | {
"start": 424,
"end": 3051
} | class ____(Exception):
def __init__(self, country_code):
self.country_code = country_code
@asyncio.coroutine
def get_flag(base_url, cc):
url = '{}/{cc}/{cc}.gif'.format(base_url, cc=cc.lower())
resp = yield from aiohttp.request('GET', url)
with contextlib.closing(resp):
if resp.status ... | FetchError |
python | patrick-kidger__equinox | equinox/nn/_normalisation.py | {
"start": 10692,
"end": 15145
} | class ____(Module):
r"""
A simplified version of LayerNorm which rescales the inputs, but does not center
them. Optionally applies a learned reweighting of the transformed array afterward.
Given an input array $x$, this layer computes
$$\frac{x}{\sqrt{\varepsilon + \frac{1}{n}\Vert x \Vert^2_2}} \... | RMSNorm |
python | neetcode-gh__leetcode | python/0152-maximum-product-subarray.py | {
"start": 0,
"end": 357
} | class ____:
def maxProduct(self, nums: List[int]) -> int:
# O(n)/O(1) : Time/Memory
res = nums[0]
curMin, curMax = 1, 1
for n in nums:
tmp = curMax * n
curMax = max(n * curMax, n * curMin, n)
curMin = min(tmp, n * curMin, n)
res = max... | Solution |
python | apache__airflow | airflow-core/tests/unit/cli/commands/test_kerberos_command.py | {
"start": 1137,
"end": 5524
} | class ____:
@classmethod
def setup_class(cls):
cls.parser = cli_parser.get_parser()
@mock.patch("airflow.cli.commands.kerberos_command.krb")
@conf_vars({("core", "executor"): "CeleryExecutor"})
def test_run_command(self, mock_krb):
args = self.parser.parse_args(["kerberos", "PRINCIP... | TestKerberosCommand |
python | coleifer__peewee | peewee.py | {
"start": 193794,
"end": 195980
} | class ____(MetaField):
sequence = None
def __init__(self, *field_names):
self.field_names = field_names
self._safe_field_names = None
@property
def safe_field_names(self):
if self._safe_field_names is None:
if self.model is None:
return self.field_na... | CompositeKey |
python | patrick-kidger__equinox | equinox/nn/_pool.py | {
"start": 8967,
"end": 10516
} | class ____(Pool):
"""Two-dimensional downsample using an average over a sliding window."""
def __init__(
self,
kernel_size: int | Sequence[int],
stride: int | Sequence[int] = 1,
padding: int | Sequence[int] | Sequence[tuple[int, int]] = 0,
use_ceil: bool = False,
):
... | AvgPool2d |
python | walkccc__LeetCode | solutions/457. Circular Array Loop/457.py | {
"start": 0,
"end": 694
} | class ____:
def circularArrayLoop(self, nums: list[int]) -> bool:
def advance(i: int) -> int:
return (i + nums[i]) % len(nums)
if len(nums) < 2:
return False
for i, num in enumerate(nums):
if num == 0:
continue
slow = i
fast = advance(slow)
while num * nums[f... | Solution |
python | pandas-dev__pandas | pandas/core/computation/pytables.py | {
"start": 12571,
"end": 12849
} | class ____(ConditionBinOp):
# error: Signature of "evaluate" incompatible with supertype "BinOp"
def evaluate(self) -> Self: # type: ignore[override]
self.condition = f"({self.lhs.condition} {self.op} {self.rhs.condition})"
return self
| JointConditionBinOp |
python | Lightning-AI__lightning | src/lightning/fabric/strategies/launchers/multiprocessing.py | {
"start": 6322,
"end": 10213
} | class ____:
"""Captures a hand-selected set of (global) variables in modules and provides a way to restore them.
It facilitates and encapsulates the transfer of globals like PyTorch's deterministic flags or random generator state
across process boundaries when launching processes with :func:`torch.multipro... | _GlobalStateSnapshot |
python | openai__openai-python | src/openai/types/realtime/realtime_audio_config_output.py | {
"start": 294,
"end": 1389
} | class ____(BaseModel):
format: Optional[RealtimeAudioFormats] = None
"""The format of the output audio."""
speed: Optional[float] = None
"""
The speed of the model's spoken response as a multiple of the original speed.
1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum spee... | RealtimeAudioConfigOutput |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/context.py | {
"start": 7917,
"end": 10869
} | class ____(CompileState):
is_dml_returning = False
def _init_global_attributes(
self, statement, compiler, *, toplevel, process_criteria_for_toplevel
):
self.attributes = {}
if compiler is None:
# this is the legacy / testing only ORM _compile_state() use case.
... | _AbstractORMCompileState |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 28495,
"end": 29076
} | class ____(Dataset):
def __init__(self, size, error_event):
self.size = size
self.error_event = error_event
def __len__(self):
return self.size
def __getitem__(self, idx):
worker_info = torch.utils.data.get_worker_info()
if (
self.error_event is not None... | TestProperExitDataset |
python | scipy__scipy | scipy/stats/tests/test_continued_fraction.py | {
"start": 622,
"end": 6709
} | class ____:
rng = np.random.default_rng(5895448232066142650)
p = rng.uniform(1, 10, size=10)
def a1(self, n, x=1.5):
if n == 0:
y = 0*x
elif n == 1:
y = x
else:
y = -x**2
if np.isscalar(y) and np.__version__ < "2.0":
y = np.ful... | TestContinuedFraction |
python | kamyu104__LeetCode-Solutions | Python/palindrome-partitioning-iv.py | {
"start": 31,
"end": 1158
} | class ____(object):
def checkPartitioning(self, s):
"""
:type s: str
:rtype: bool
"""
def manacher(s):
s = '^#' + '#'.join(s) + '#$'
P = [0]*len(s)
C, R = 0, 0
for i in xrange(1, len(s)-1):
i_mirror = 2*C-i
... | Solution |
python | instagram__MonkeyType | tests/testmodule/__init__.py | {
"start": 202,
"end": 317
} | class ____:
def __init__(self, arg1: str, arg2: int) -> None:
self.arg1 = arg1
self.arg2 = arg2
| Foo |
python | astropy__astropy | astropy/coordinates/spectral_coordinate.py | {
"start": 4694,
"end": 31191
} | class ____(SpectralQuantity):
"""
A spectral coordinate with its corresponding unit.
.. note:: The |SpectralCoord| class is new in Astropy v4.1 and should be
considered experimental at this time. Note that we do not fully
support cases where the observer and target are moving
... | SpectralCoord |
python | astropy__astropy | astropy/io/fits/file.py | {
"start": 3878,
"end": 28373
} | class ____:
"""
Represents a FITS file on disk (or in some other file-like object).
"""
def __init__(
self,
fileobj=None,
mode=None,
memmap=None,
overwrite=False,
cache=True,
*,
use_fsspec=None,
fsspec_kwargs=None,
decompre... | _File |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/dms.py | {
"start": 24145,
"end": 30976
} | class ____(AwsBaseOperator[DmsHook]):
"""
Starts an AWS DMS Serverless replication.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DmsStartReplicationOperator`
:param replication_config_arn: ARN of the replication config
... | DmsStartReplicationOperator |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/schemas/user_schema.py | {
"start": 1193,
"end": 1877
} | class ____(SQLAlchemySchema):
"""user collection item schema."""
class Meta:
"""Meta."""
model = User
dateformat = "iso"
first_name = auto_field()
last_name = auto_field()
username = auto_field()
active = auto_field(dump_only=True)
email = auto_field()
last_log... | UserCollectionItemSchema |
python | jupyterlab__jupyterlab | jupyterlab/semver.py | {
"start": 9495,
"end": 19578
} | class ____:
def __init__(self, version, loose):
logger.debug("SemVer %s, %s", version, loose)
self.loose = loose
self.raw = version
m = regexp[LOOSE if loose else FULL].search(version.strip())
if not m:
if not loose:
raise ValueError(f"Invalid Ver... | SemVer |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 35165,
"end": 36373
} | class ____:
def setup_method(self):
self.rng = np.random.default_rng(5861367021)
def test_rvs(self):
vals = stats.nbinom.rvs(10, 0.75, size=(2, 50), random_state=self.rng)
assert_(np.all(vals >= 0))
assert_(np.shape(vals) == (2, 50))
assert_(vals.dtype.char in typecodes[... | TestNBinom |
python | has2k1__plotnine | plotnine/scales/scale_xy.py | {
"start": 6955,
"end": 7143
} | class ____(scale_position_discrete):
"""
Discrete y position
"""
_aesthetics = ["y", "ymin", "ymax", "yend", "yintercept"]
# Not part of the user API
@alias
| scale_y_discrete |
python | tensorflow__tensorflow | tensorflow/core/function/trace_type/default_types.py | {
"start": 9484,
"end": 12282
} | class ____(trace.TraceType, serialization.Serializable):
"""Represents a list of TraceType objects."""
def __init__(self, *components: trace.TraceType):
self.components_tuple = Tuple(*components)
def is_subtype_of(self, other: trace.TraceType) -> bool:
if not isinstance(other, List):
return False
... | List |
python | Textualize__textual | src/textual/scrollbar.py | {
"start": 1740,
"end": 7234
} | class ____:
VERTICAL_BARS: ClassVar[list[str]] = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", " "]
"""Glyphs used for vertical scrollbar ends, for smoother display."""
HORIZONTAL_BARS: ClassVar[list[str]] = ["▉", "▊", "▋", "▌", "▍", "▎", "▏", " "]
"""Glyphs used for horizontal scrollbar ends, for smoother displa... | ScrollBarRender |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF023.py | {
"start": 6131,
"end": 6882
} | class ____:
__slots__ = ()
__slots__ = []
__slots__ = ("single_item",)
__slots__ = (
"single_item_multiline",
)
__slots__ = {"single_item",}
__slots__ = {"single_item_no_trailing_comma": "docs for that"}
__slots__ = [
"single_item_multiline_no_trailing_comma"
]
__... | Klass6 |
python | tensorflow__tensorflow | tensorflow/python/distribute/tpu_strategy.py | {
"start": 79888,
"end": 86880
} | class ____(distribute_lib.ReplicaContext):
"""Replication Context class for TPU Strategy."""
# TODO(sourabhbajaj): Call for each replica should be updating this.
# TODO(b/118385803): Always properly initialize replica_id.
def __init__(self, strategy, replica_id_in_sync_group=0):
distribute_lib.ReplicaConte... | _TPUReplicaContext |
python | django__django | tests/force_insert_update/models.py | {
"start": 424,
"end": 468
} | class ____(SubCounter):
pass
| SubSubCounter |
python | run-llama__llama_index | llama-index-integrations/indices/llama-index-indices-managed-colbert/llama_index/indices/managed/colbert/retriever.py | {
"start": 442,
"end": 2133
} | class ____(BaseRetriever):
"""
Vector index retriever.
Args:
index (ColbertIndex): Colbert index.
similarity_top_k (int): number of top k results to return.
filters (Optional[MetadataFilters]): metadata filters, defaults to None
doc_ids (Optional[List[str]]): list of documen... | ColbertRetriever |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 7310,
"end": 7467
} | class ____(PrefectException):
"""
Raised when a task relies on the result of another task but that task is not
'COMPLETE'
"""
| UpstreamTaskError |
python | facebook__pyre-check | tools/generate_taint_models/get_exit_nodes.py | {
"start": 435,
"end": 1603
} | class ____(ModelGenerator[CallableModel]):
def __init__(
self,
django_urls: DjangoUrls,
whitelisted_views: Optional[List[str]] = None,
taint_annotation: str = "TaintSink[ReturnedToUser]",
) -> None:
self.django_urls = django_urls
self.whitelisted_views: List[str] ... | ExitNodeGenerator |
python | tensorflow__tensorflow | tensorflow/python/ops/weak_tensor_np_array_ops_test.py | {
"start": 19008,
"end": 42039
} | class ____(test.TestCase, parameterized.TestCase):
def setUp(self):
super(ArrayMethodsTest, self).setUp()
set_up_virtual_devices()
self.array_transforms = [
lambda x: x,
_get_weak_tensor,
np_array_ops.array,
]
def testCopy(self):
def run_test(arr, *args, **kwargs):
... | ArrayMethodsTest |
python | weaviate__weaviate-python-client | weaviate/collections/classes/internal.py | {
"start": 7593,
"end": 7824
} | class ____(Generic[P, R]):
"""The return type of a query within the `.query` namespace of a collection."""
objects: List[Object[P, R]]
_GQLEntryReturnType: TypeAlias = Dict[str, List[Dict[str, Any]]]
@dataclass
| QueryReturn |
python | explosion__spaCy | spacy/lang/ru/__init__.py | {
"start": 401,
"end": 657
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
lex_attr_getters = LEX_ATTRS
stop_words = STOP_WORDS
suffixes = COMBINING_DIACRITICS_TOKENIZER_SUFFIXES
infixes = COMBINING_DIACRITICS_TOKENIZER_INFIXES
| RussianDefaults |
python | pytorch__pytorch | torch/autograd/function.py | {
"start": 923,
"end": 11523
} | class ____:
def save_for_backward(self, *tensors: torch.Tensor):
r"""Save given tensors for a future call to :func:`~Function.backward`.
``save_for_backward`` should be called at most once, in either the
:func:`setup_context` or :func:`forward` methods, and only with tensors.
All t... | FunctionCtx |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_single.py | {
"start": 82498,
"end": 83527
} | class ____(AssertsCompiledSQL, fixtures.TestBase):
def test_discrim_on_column_prop(self, registry):
Base = registry.generate_base()
class Employee(Base):
__tablename__ = "employee"
id = Column(Integer, primary_key=True)
type = Column(String(20))
__ma... | ColExprTest |
python | encode__django-rest-framework | tests/test_write_only_fields.py | {
"start": 75,
"end": 909
} | class ____(TestCase):
def setUp(self):
class ExampleSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField(write_only=True)
self.Serializer = ExampleSerializer
def test_write_only_fields_are_present_on_input(self):
... | WriteOnlyFieldTests |
python | numpy__numpy | numpy/ma/tests/test_extras.py | {
"start": 58815,
"end": 68788
} | class ____:
def test_unique_onlist(self):
# Test unique on list
data = [1, 1, 1, 2, 2, 3]
test = unique(data, return_index=True, return_inverse=True)
assert_(isinstance(test[0], MaskedArray))
assert_equal(test[0], masked_array([1, 2, 3], mask=[0, 0, 0]))
assert_equal... | TestArraySetOps |
python | coleifer__peewee | tests/regressions.py | {
"start": 54792,
"end": 54856
} | class ____(TestModel):
a = TextField()
b = TextField()
| CQA |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/synthesis.py | {
"start": 497,
"end": 856
} | class ____(BaseEvent):
"""
SynthesizeEndEvent.
Args:
query (QueryType): Query as a string or query bundle.
response (RESPONSE_TYPE): Response.
"""
query: QueryType
response: RESPONSE_TYPE
@classmethod
def class_name(cls) -> str:
"""Class name."""
retur... | SynthesizeEndEvent |
python | walkccc__LeetCode | solutions/2431. Maximize Total Tastiness of Purchased Fruits/2431.py | {
"start": 0,
"end": 1315
} | class ____:
def maxTastiness(
self,
price: list[int],
tastiness: list[int],
maxAmount: int,
maxCoupons: int,
) -> int:
n = len(price)
# dp[i][j][k] := the maximum tastiness of the first i price with j amount of
# money and k coupons
dp = [[[0] * (maxCoupons + 1)
... | Solution |
python | spack__spack | lib/spack/spack/hash_types.py | {
"start": 321,
"end": 2425
} | class ____:
"""This class defines how hashes are generated on Spec objects.
Spec hashes in Spack are generated from a serialized (e.g., with
YAML) representation of the Spec graph. The representation may only
include certain dependency types, and it may optionally include a
canonicalized hash of t... | SpecHashDescriptor |
python | pola-rs__polars | py-polars/src/polars/interchange/protocol.py | {
"start": 557,
"end": 769
} | class ____(IntEnum):
"""Integer enum for device type codes matching DLPack."""
CPU = 1
CUDA = 2
CPU_PINNED = 3
OPENCL = 4
VULKAN = 7
METAL = 8
VPI = 9
ROCM = 10
| DlpackDeviceType |
python | donnemartin__interactive-coding-challenges | sorting_searching/merge_sort/test_merge_sort.py | {
"start": 18,
"end": 671
} | class ____(unittest.TestCase):
def test_merge_sort(self):
merge_sort = MergeSort()
print('None input')
self.assertRaises(TypeError, merge_sort.sort, None)
print('Empty input')
self.assertEqual(merge_sort.sort([]), [])
print('One element')
self.assertEqual(... | TestMergeSort |
python | simonw__datasette | datasette/permissions.py | {
"start": 5101,
"end": 6352
} | class ____:
"""
A plugin contributes SQL that yields:
parent TEXT NULL,
child TEXT NULL,
allow INTEGER, -- 1 allow, 0 deny
reason TEXT
For restriction-only plugins, sql can be None and only restriction_sql is provided.
"""
sql: str | None = (
None # SQL that S... | PermissionSQL |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-cart/source_cart/streams.py | {
"start": 3471,
"end": 5049
} | class ____(CartStream, ABC):
state_checkpoint_interval = 1000
cursor_field = "updated_at"
def request_params(self, stream_state: Mapping[str, Any], **kwargs) -> MutableMapping[str, Any]:
"""
Generates a query for incremental logic
Docs: https://developers.cart.com/docs/rest-api/doc... | IncrementalCartStream |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/executors/utils/test_exponential_backoff_retry.py | {
"start": 1057,
"end": 10644
} | class ____:
def test_exponential_backoff_retry_base_case(self, time_machine):
time_machine.move_to(datetime(2023, 1, 1, 12, 0, 5))
mock_callable_function = mock.Mock()
exponential_backoff_retry(
last_attempt_time=datetime(2023, 1, 1, 12, 0, 0, tzinfo=timezone.utc),
at... | TestExponentialBackoffRetry |
python | huggingface__transformers | src/transformers/models/sam2_video/modeling_sam2_video.py | {
"start": 29659,
"end": 34145
} | class ____(nn.Module):
"""
Vision Rotary Position Embedding for SAM2, following transformers library standards.
Supports 2D (axial) rotary embeddings for spatial dimensions.
"""
def __init__(self, config: Sam2VideoConfig):
super().__init__()
dim = config.memory_attention_hidden_size... | Sam2VideoVisionRotaryEmbedding |
python | spyder-ide__spyder | spyder/plugins/completion/api.py | {
"start": 20791,
"end": 20970
} | class ____:
"""LSP completion text interpretations."""
PLAIN_TEXT = 1
SNIPPET = 2
# ----------------- SAVING REQUEST RELATED VALUES -------------------
| InsertTextFormat |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_datasync.py | {
"start": 27032,
"end": 35121
} | class ____(DataSyncTestCaseBase):
def set_up_operator(
self, task_id="test_datasync_task_operator", task_arn="self", wait_for_completion=True
):
if task_arn == "self":
task_arn = self.task_arn
# Create operator
self.datasync = DataSyncOperator(
task_id=tas... | TestDataSyncOperator |
python | kamyu104__LeetCode-Solutions | Python/convert-binary-search-tree-to-sorted-doubly-linked-list.py | {
"start": 29,
"end": 168
} | class ____(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
| Node |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0036_change_mkdocs_name.py | {
"start": 149,
"end": 998
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0035_backport_indexes"),
]
operations = [
migrations.AlterField(
model_name="version",
name="documentation_type",
field=models.CharField(
choices... | Migration |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/profiling_test.py | {
"start": 972,
"end": 3777
} | class ____(test_util.TensorFlowTestCase):
def setUp(self):
node_1 = step_stats_pb2.NodeExecStats(
node_name="Add/123",
op_start_rel_micros=3,
op_end_rel_micros=5,
all_end_rel_micros=4)
self.profile_datum_1 = profiling.ProfileDatum(
"cpu:0", node_1, "/foo/bar.py", 10, "... | AggregateProfile |
python | ansible__ansible | test/integration/targets/assert/lookup_plugins/yield_terms.py | {
"start": 84,
"end": 221
} | class ____(LookupBase):
accept_args_markers = True
def run(self, terms, variables=None, **kwargs):
return terms
| LookupModule |
python | jd__tenacity | tenacity/asyncio/retry.py | {
"start": 1828,
"end": 2611
} | class ____(async_retry_base):
"""Retry strategy that retries if an exception verifies a predicate."""
def __init__(
self, predicate: typing.Callable[[BaseException], typing.Awaitable[bool]]
) -> None:
self.predicate = predicate
async def __call__(self, retry_state: "RetryCallState") ->... | retry_if_exception |
python | pydata__xarray | xarray/tests/test_plot.py | {
"start": 32665,
"end": 34381
} | class ____(PlotTestCase):
@pytest.fixture(autouse=True)
def setUp(self) -> None:
self.darray = DataArray(easy_array((2, 3, 4)))
def test_3d_array(self) -> None:
self.darray.plot.hist() # type: ignore[call-arg]
def test_xlabel_uses_name(self) -> None:
self.darray.name = "testpo... | TestPlotHistogram |
python | mlflow__mlflow | mlflow/types/chat.py | {
"start": 6068,
"end": 6300
} | class ____(BaseModel):
"""A chunk of a chat completion stream response."""
id: str | None = None
object: str = "chat.completion.chunk"
created: int
model: str
choices: list[ChatChunkChoice]
| ChatCompletionChunk |
python | getsentry__sentry | src/sentry/utils/concurrent.py | {
"start": 928,
"end": 1200
} | class ____[T](NamedTuple):
priority: int
item: tuple[sentry_sdk.Scope, sentry_sdk.Scope, Callable[[], T], Future[T]]
def __eq__(self, b):
return self.priority == b.priority
def __lt__(self, b):
return self.priority < b.priority
| PriorityTask |
python | rapidsai__cudf | python/cudf/cudf/tests/general_functions/test_register_accessor.py | {
"start": 308,
"end": 1597
} | class ____:
def __init__(self, obj):
self._validate(obj)
self._obj = obj
@staticmethod
def _validate(obj):
cols = obj.columns
if not all(vertex in cols for vertex in ["x", "y"]):
raise AttributeError("Must have vertices 'x', 'y'.")
@property
def bounding... | PointsAccessor |
python | django__django | tests/queries/models.py | {
"start": 10634,
"end": 10749
} | class ____(models.Model):
CaTeGoRy = models.ForeignKey(SimpleCategory, models.CASCADE)
| MixedCaseFieldCategoryItem |
python | huggingface__transformers | src/transformers/models/hubert/modeling_hubert.py | {
"start": 19871,
"end": 21600
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.attention = HubertAttention(
embed_dim=config.hidden_size,
num_heads=config.num_attention_heads,
dropout=config.attention_dropout,
is_decoder=False,
... | HubertEncoderLayerStableLayerNorm |
python | pandas-dev__pandas | pandas/core/arrays/base.py | {
"start": 90118,
"end": 93140
} | class ____:
"""
A base class for linking the operators to their dunder names.
.. note::
You may want to set ``__array_priority__`` if you want your
implementation to be called when involved in binary operations
with NumPy arrays.
"""
@classmethod
def _create_arithmetic_me... | ExtensionOpsMixin |
python | tensorflow__tensorflow | tensorflow/python/ops/clustering_ops_test.py | {
"start": 3375,
"end": 3871
} | class ____(test.TestCase):
def setUp(self):
self._distances = np.zeros(10)
def runTestWithSeed(self, seed):
with self.cached_session():
sampled_point = clustering_ops.kmc2_chain_initialization(
self._distances, seed)
self.assertAllEqual(sampled_point, 0)
def testBasic(self):
f... | KMC2InitializationCornercaseTest |
python | pallets__flask | src/flask/sansio/blueprints.py | {
"start": 4397,
"end": 27017
} | class ____(Scaffold):
"""Represents a blueprint, a collection of routes and other
app-related functions that can be registered on a real application
later.
A blueprint is an object that allows defining application functions
without requiring an application object ahead of time. It uses the
same... | Blueprint |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/units.py | {
"start": 755,
"end": 969
} | class ____(Enum):
"""
Represents family of units contains all units that are coercible between each other.
"""
DURATION = "duration"
INFORMATION = "information"
@dataclass(frozen=True)
| UnitFamily |
python | astropy__astropy | astropy/utils/masked/tests/test_function_helpers.py | {
"start": 9749,
"end": 10394
} | class ____(InvariantMaskTestSetup):
def test_copy(self):
self.check(np.copy)
# Also as kwarg
copy = np.copy(a=self.ma)
assert_array_equal(copy, self.ma)
@pytest.mark.skipif(not NUMPY_LT_2_0, reason="np.asfarray is removed in NumPy 2.0")
def test_asfarray(self):
self.... | TestCopyAndCreation |
python | getsentry__sentry | tests/sentry/monitors/test_utils.py | {
"start": 4172,
"end": 8111
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.monitor = self.create_monitor()
def test_deletes_data_source_and_detector(self) -> None:
ensure_cron_detector(self.monitor)
data_source = DataSource.objects.get(
type=DATA_SOURCE_CRON_MONITOR,
... | EnsureCronDetectorDeletionTest |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/validators/alertrule_detector.py | {
"start": 41,
"end": 652
} | class ____(serializers.Serializer):
rule_id = serializers.CharField(required=False)
alert_rule_id = serializers.CharField(required=False)
detector_id = serializers.CharField(required=False)
def validate(self, attrs):
super().validate(attrs)
if (
not attrs.get("rule_id")
... | AlertRuleDetectorValidator |
python | keras-team__keras | keras/src/metrics/probabilistic_metrics_test.py | {
"start": 5335,
"end": 7372
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(
metrics.CategoricalCrossentropy(
name="cce", dtype="int32", label_smoothing=0.2
)
)
def test_unweighted(self):
cce_obj = metrics.CategoricalCrossentropy()
... | CategoricalCrossentropyTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/isinstance5.py | {
"start": 492,
"end": 1094
} | class ____(Protocol):
def method1(self) -> int: ...
def func2(a: Any):
if isinstance(a, DataProtocol):
return
if isinstance(a, NonDataProtocol):
return
# This should generate an error because data protocols
# are not allowed with issubclass checks.
if issubclass(a, (DataProto... | NonDataProtocol |
python | PyCQA__pylint | pylint/lint/pylinter.py | {
"start": 2285,
"end": 8408
} | class ____(Protocol):
def __call__(
self, filepath: str, modname: str, data: str | None = None
) -> nodes.Module: ...
def _read_stdin() -> str:
# See https://github.com/python/typeshed/pull/5623 for rationale behind assertion
assert isinstance(sys.stdin, TextIOWrapper)
sys.stdin = TextIOWr... | GetAstProtocol |
python | spack__spack | lib/spack/spack/test/repo.py | {
"start": 19136,
"end": 36784
} | class ____(PackageBase):
pass
"""
)
with spack.repo.use_repositories(str(repo_dir)) as repo:
assert repo.exists("1example-2-test")
pkg_cls = repo.get_pkg_class("1example-2-test")
assert pkg_cls.name == "1example-2-test"
assert pkg_cls.module.__name__ == "spack_repo.repo_2.pa... | _1example2Test |
python | scipy__scipy | tools/authors.py | {
"start": 5596,
"end": 7381
} | class ____:
executable = None
def __init__(self, executable):
self.executable = executable
def _call(self, command, args, kw, repository=None, call=False):
cmd = [self.executable, command] + list(args)
cwd = None
if repository is not None:
cwd = os.getcwd()
... | Cmd |
python | allegroai__clearml | clearml/backend_api/session/jsonmodels/fields.py | {
"start": 400,
"end": 4355
} | class ____(object):
"""Base class for all fields."""
types = None
def __init__(
self,
required: bool = False,
nullable: bool = False,
help_text: str = None,
validators: Any = None,
default: Any = NotSet,
name: str = None,
) -> None:
self.... | BaseField |
python | realpython__materials | python-enum/days.py | {
"start": 177,
"end": 332
} | class ____(Enum):
MONDAY = auto()
TUESDAY = auto()
WEDNESDAY = 3
THURSDAY = auto()
FRIDAY = auto()
SATURDAY = auto()
SUNDAY = 7
| Day |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_gtk3agg.py | {
"start": 216,
"end": 2387
} | class ____(backend_agg.FigureCanvasAgg,
backend_gtk3.FigureCanvasGTK3):
def __init__(self, figure):
super().__init__(figure=figure)
self._bbox_queue = []
def on_draw_event(self, widget, ctx):
if self._idle_draw_id:
GLib.source_remove(self._idle_draw... | FigureCanvasGTK3Agg |
python | python-jsonschema__jsonschema | jsonschema/tests/test_validators.py | {
"start": 27519,
"end": 53570
} | class ____(TestCase):
# TODO: These really need unit tests for each individual keyword, rather
# than just these higher level tests.
def test_anyOf(self):
instance = 5
schema = {
"anyOf": [
{"minimum": 20},
{"type": "string"},
],
... | TestValidationErrorDetails |
python | walkccc__LeetCode | solutions/1263. Minimum Moves to Move a Box to Their Target Location/1263.py | {
"start": 0,
"end": 2213
} | class ____:
def minPushBox(self, grid: list[list[str]]) -> int:
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
m = len(grid)
n = len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j] == 'B':
box = (i, j)
elif grid[i][j] == 'S':
player = (i, j)
e... | Solution |
python | weaviate__weaviate-python-client | weaviate/collections/classes/grpc.py | {
"start": 816,
"end": 2363
} | class ____:
"""Define how the query's move operation should be performed."""
def __init__(
self,
force: float,
objects: Optional[Union[List[UUID], UUID]] = None,
concepts: Optional[Union[List[str], str]] = None,
):
if (objects is None or (isinstance(objects, list) an... | Move |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1148902,
"end": 1149550
} | class ____(ScaleInvalidDataShowAsx):
"""
ScaleInvalidDataShowAsValuex schema wrapper.
Parameters
----------
value : float, Literal['width']
X coordinates of the marks, or width of horizontal ``"bar"`` and ``"area"`` without
specified ``x2`` or ``width``.
The ``value`` of th... | ScaleInvalidDataShowAsValuex |
python | ray-project__ray | python/ray/dashboard/memory_utils.py | {
"start": 2622,
"end": 7235
} | class ____:
def __init__(
self, *, object_ref: dict, node_address: str, is_driver: bool, pid: int
):
# worker info
self.is_driver = is_driver
self.pid = pid
self.node_address = node_address
# object info
self.task_status = object_ref.get("taskStatus", "?"... | MemoryTableEntry |
python | kubernetes-client__python | kubernetes/client/models/v1_node_condition.py | {
"start": 383,
"end": 8205
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1NodeCondition |
python | Textualize__textual | src/textual/document/_wrapped_document.py | {
"start": 440,
"end": 17779
} | class ____:
"""A view into a Document which wraps the document at a certain
width and can be queried to retrieve lines from the *wrapped* version
of the document.
Allows for incremental updates, ensuring that we only re-wrap ranges of the document
that were influenced by edits.
"""
def __i... | WrappedDocument |
python | huggingface__transformers | tests/utils/test_feature_extraction_utils.py | {
"start": 1087,
"end": 2139
} | class ____(unittest.TestCase):
def test_cached_files_are_used_when_internet_is_down(self):
# A mock response for an HTTP head request to emulate server down
response_mock = mock.Mock()
response_mock.status_code = 500
response_mock.headers = {}
response_mock.raise_for_status.s... | FeatureExtractorUtilTester |
python | huggingface__transformers | src/transformers/models/hubert/modeling_hubert.py | {
"start": 45746,
"end": 50723
} | class ____(HubertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
if hasattr(config, "add_adapter") and config.add_adapter:
raise ValueError(
"Sequence classification does not support the use of Hubert adapters (config.add_adapter=True)"
... | HubertForSequenceClassification |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/sensors/rds.py | {
"start": 1709,
"end": 4019
} | class ____(RdsBaseSensor):
"""
Waits for RDS snapshot with a specific status.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:RdsSnapshotExistenceSensor`
:param db_type: Type of the DB - either "instance" or "cluster"
:param... | RdsSnapshotExistenceSensor |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/pipes/utils.py | {
"start": 21442,
"end": 23662
} | class ____(PipesThreadedMessageReader):
"""Message reader that reads a sequence of message chunks written by an external process into a
blob store such as S3, Azure blob storage, or GCS.
The reader maintains a counter, starting at 1, that is synchronized with a message writer in
some pipes process. The... | PipesBlobStoreMessageReader |
python | giampaolo__psutil | tests/test_linux.py | {
"start": 37210,
"end": 39439
} | class ____(PsutilTestCase):
@pytest.mark.skipif(
not shutil.which("ifconfig"), reason="ifconfig utility not available"
)
def test_against_ifconfig(self):
for name, stats in psutil.net_if_stats().items():
try:
out = sh(f"ifconfig {name}")
except Runtime... | TestSystemNetIfStats |
python | MongoEngine__mongoengine | mongoengine/fields.py | {
"start": 81043,
"end": 87123
} | class ____(BaseField):
"""A really lazy reference to a document.
Unlike the :class:`~mongoengine.fields.ReferenceField` it will
**not** be automatically (lazily) dereferenced on access.
Instead, access will return a :class:`~mongoengine.base.LazyReference` class
instance, allowing access to `pk` or ... | LazyReferenceField |
python | docker__docker-py | docker/errors.py | {
"start": 3334,
"end": 3394
} | class ____(DockerException, ValueError):
pass
| NullResource |
python | huggingface__transformers | examples/modular-transformers/modeling_test_detr.py | {
"start": 45341,
"end": 54271
} | class ____(TestDetrPreTrainedModel):
"""
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TestDetrDecoderLayer`].
The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
Some tweaks for Deformable DETR:
- `position_em... | TestDetrDecoder |
python | cython__cython | Cython/Compiler/FlowControl.py | {
"start": 11940,
"end": 12097
} | class ____(NameAssignment):
def __init__(self, lhs, rhs, entry):
NameAssignment.__init__(self, lhs, rhs, entry)
self.is_arg = True
| Argument |
python | gevent__gevent | src/greentest/3.14/test_urllib2.py | {
"start": 11396,
"end": 11656
} | class ____:
addheaders = []
def open(self, req, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
self.req, self.data, self.timeout = req, data, timeout
def error(self, proto, *args):
self.proto, self.args = proto, args
| MockOpener |
python | astropy__astropy | astropy/io/registry/core.py | {
"start": 13670,
"end": 14631
} | class ____(UnifiedInputRegistry, UnifiedOutputRegistry):
"""Unified I/O Registry.
.. versionadded:: 5.0
"""
def __init__(self):
super().__init__()
self._registries_order = ("read", "write", "identify")
def get_formats(self, data_class=None, readwrite=None):
"""
Get... | UnifiedIORegistry |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_data_forwarding_details.py | {
"start": 982,
"end": 20997
} | class ____(DataForwardingDetailsEndpointTest):
method = "PUT"
def test_without_revamp_feature_flag_access(self) -> None:
data_forwarder = self.create_data_forwarder(
provider=DataForwarderProviderSlug.SEGMENT,
config={"write_key": "old_key"},
is_enabled=True,
... | DataForwardingDetailsPutTest |
python | numba__numba | numba/experimental/function_type.py | {
"start": 1069,
"end": 1803
} | class ____(models.PrimitiveModel):
"""FunctionProtoModel describes the signatures of first-class functions
"""
def __init__(self, dmm, fe_type):
if isinstance(fe_type, FunctionType):
ftype = fe_type.ftype
elif isinstance(fe_type, FunctionPrototype):
ftype = fe_type
... | FunctionProtoModel |
python | jina-ai__jina | jina/proto/serializer.py | {
"start": 3529,
"end": 4210
} | class ____:
"""Since the serializer is replacing the `jina_pb2` to know how to exactly serialize messages, this is just a placeholder that
delegates the serializing and deserializing to the internal protobuf structure with no extra optimization.
"""
@staticmethod
def SerializeToString(x):
"... | JinaInfoProto |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.