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 | astropy__astropy | astropy/utils/shapes.py | {
"start": 14452,
"end": 19305
} | class ____(ValueError):
def __init__(
self,
shape_a: tuple[int, ...],
shape_a_idx: int,
shape_b: tuple[int, ...],
shape_b_idx: int,
) -> None:
super().__init__(shape_a, shape_a_idx, shape_b, shape_b_idx)
@deprecated("7.0", alternative="np.broadcast_shapes")
def ... | IncompatibleShapeError |
python | pytorch__pytorch | torch/_inductor/remote_cache.py | {
"start": 11279,
"end": 11994
} | class ____(RedisRemoteCache):
pass
def create_cache(
key: str,
is_fbcode: bool,
fb_cache_cls: str,
oss_cache_cls: str,
) -> Optional[RemoteCache[JsonDataTy]]:
try:
if is_fbcode:
import torch._inductor.fb.remote_cache
cache_cls = getattr(torch._inductor.fb.remot... | RemoteDynamoPGOCache |
python | airbytehq__airbyte | airbyte-ci/connectors/live-tests/src/live_tests/commons/errors.py | {
"start": 94,
"end": 196
} | class ____(Exception):
def __init__(self, message: str):
super().__init__(message)
| ExportError |
python | walkccc__LeetCode | solutions/3360. Stone Removal Game/3360.py | {
"start": 0,
"end": 164
} | class ____:
def canAliceWin(self, n: int) -> bool:
for stones in range(10, -1, -1):
if stones > n:
return stones % 2 == 1
n -= stones
| Solution |
python | kamyu104__LeetCode-Solutions | Python/reverse-words-in-a-string-iii.py | {
"start": 29,
"end": 504
} | class ____(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
def reverse(s, begin, end):
for i in xrange((end - begin) // 2):
s[begin + i], s[end - 1 - i] = s[end - 1 - i], s[begin + i]
s, i = list(s), 0
for j in... | Solution |
python | getsentry__sentry | src/sentry/migrations/0954_user_option_json_field.py | {
"start": 244,
"end": 1745
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | django__django | tests/db_typecasts/tests.py | {
"start": 2499,
"end": 2994
} | class ____(unittest.TestCase):
def test_typeCasts(self):
for k, v in TEST_CASES.items():
for inpt, expected in v:
with self.subTest(k=k, inpt=inpt):
got = getattr(typecasts, k)(inpt)
self.assertEqual(
got,
... | DBTypeCasts |
python | apache__airflow | airflow-core/src/airflow/example_dags/plugins/workday.py | {
"start": 1566,
"end": 4177
} | class ____(Timetable):
def get_next_workday(self, d: DateTime, incr=1) -> DateTime:
next_start = d
while True:
if next_start.weekday() not in (5, 6): # not on weekend
if holiday_calendar is None:
holidays = set()
else:
... | AfterWorkdayTimetable |
python | walkccc__LeetCode | solutions/1235. Maximum Profit in Job Scheduling/1235.py | {
"start": 0,
"end": 641
} | class ____:
def jobScheduling(
self,
startTime: list[int],
endTime: list[int],
profit: list[int],
) -> int:
jobs = sorted([(s, e, p) for s, e, p in zip(startTime, endTime, profit)])
# Will use binary search to find the first available startTime
for i in range(len(startTime)):
... | Solution |
python | django-import-export__django-import-export | tests/core/tests/test_widgets.py | {
"start": 13249,
"end": 14492
} | class ____(TestCase, RowDeprecationTestMixin):
def setUp(self):
self.value = 11.111
self.widget = widgets.NumberWidget()
self.widget_coerce_to_string = widgets.NumberWidget(coerce_to_string=True)
def test_is_empty_value_is_none(self):
self.assertTrue(self.widget.is_empty(None))
... | NumberWidgetTest |
python | langchain-ai__langchain | libs/langchain/tests/integration_tests/cache/fake_embeddings.py | {
"start": 1270,
"end": 2462
} | class ____(FakeEmbeddings):
"""Consistent fake embeddings.
Fake embeddings which remember all the texts seen so far to return consistent
vectors for the same texts.
"""
def __init__(self, dimensionality: int = 10) -> None:
self.known_texts: list[str] = []
self.dimensionality = dime... | ConsistentFakeEmbeddings |
python | openai__openai-python | src/openai/types/responses/web_search_tool_param.py | {
"start": 1262,
"end": 1862
} | class ____(TypedDict, total=False):
type: Required[Literal["web_search", "web_search_2025_08_26"]]
"""The type of the web search tool.
One of `web_search` or `web_search_2025_08_26`.
"""
filters: Optional[Filters]
"""Filters for the search."""
search_context_size: Literal["low", "medium",... | WebSearchToolParam |
python | sympy__sympy | sympy/categories/baseclasses.py | {
"start": 1101,
"end": 3856
} | class ____(Basic):
"""
The base class for any morphism in an abstract category.
Explanation
===========
In abstract categories, a morphism is an arrow between two
category objects. The object where the arrow starts is called the
domain, while the object where the arrow ends is called the
... | Morphism |
python | facebookresearch__faiss | tests/test_binary_io.py | {
"start": 2333,
"end": 3029
} | class ____(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
d = 32
nt = 200
nb = 1500
nq = 500
(self.xt, self.xb, self.xq) = make_binary_dataset(d, nb, nt, nq)
def test_read_index_ownership(self):
... | TestObjectOwnership |
python | keras-team__keras | keras/src/regularizers/regularizers.py | {
"start": 212,
"end": 5707
} | class ____:
"""Regularizer base class.
Regularizers allow you to apply penalties on layer parameters or layer
activity during optimization. These penalties are summed into the loss
function that the network optimizes.
Regularization penalties are applied on a per-layer basis. The exact API
wil... | Regularizer |
python | ray-project__ray | rllib/connectors/env_to_module/env_to_module_pipeline.py | {
"start": 538,
"end": 1844
} | class ____(ConnectorPipelineV2):
@override(ConnectorPipelineV2)
def __call__(
self,
*,
rl_module: RLModule,
batch: Optional[Dict[str, Any]] = None,
episodes: List[EpisodeType],
explore: bool,
shared_data: Optional[dict] = None,
metrics: Optional[Me... | EnvToModulePipeline |
python | pytorch__pytorch | test/distributed/tensor/parallel/test_parallelize_api.py | {
"start": 694,
"end": 835
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(self, x):
return x
| DummyModule |
python | great-expectations__great_expectations | tests/datasource/fluent/test_config_str.py | {
"start": 11531,
"end": 12652
} | class ____:
@pytest.mark.parametrize("uri", ["invalid_uri", "http:/example.com"])
def test_invalid_uri(self, uri: str):
with pytest.raises(pydantic.ValidationError):
_ = pydantic.parse_obj_as(ConfigUri, uri)
@pytest.mark.parametrize(
"uri",
[
"${MY_SCHEME}://... | TestConfigUriInvalid |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 294105,
"end": 299786
} | class ____(rv_continuous):
r"""An Irwin-Hall (Uniform Sum) continuous random variable.
An `Irwin-Hall <https://en.wikipedia.org/wiki/Irwin-Hall_distribution/>`_
continuous random variable is the sum of :math:`n` independent
standard uniform random variables [1]_ [2]_.
%(before_notes)s
Notes
... | irwinhall_gen |
python | ray-project__ray | rllib/examples/envs/classes/multi_agent/footsies/game/constants.py | {
"start": 81,
"end": 235
} | class ____:
NONE = 0
BACK = 1
FORWARD = 2
ATTACK = 3
BACK_ATTACK = 4
FORWARD_ATTACK = 5
SPECIAL_CHARGE = 6
@dataclass
| EnvActions |
python | pytorch__pytorch | test/inductor/test_remote_cache.py | {
"start": 428,
"end": 577
} | class ____(RemoteCacheBackend):
def _get(self, key):
return None
def _put(self, key, data):
return None
@dataclass
| NoopBackend |
python | scipy__scipy | scipy/special/tests/test_spherical_bessel.py | {
"start": 4700,
"end": 5434
} | class ____:
def test_spherical_jn_yn_cross_product_1(self):
# https://dlmf.nist.gov/10.50.E3
n = np.array([1, 5, 8])
x = np.array([0.1, 1, 10])
left = (spherical_jn(n + 1, x) * spherical_yn(n, x) -
spherical_jn(n, x) * spherical_yn(n + 1, x))
right = 1/x**2
... | TestSphericalJnYnCrossProduct |
python | google__jax | jax/_src/api_util.py | {
"start": 3989,
"end": 26920
} | class ____:
"""Box object used when comparing static arguments as a jit key.
Requires exact type equality using `is` and value equality."""
__slots__ = ["val"]
def __init__(self, val):
self.val = val
def __hash__(self):
return hash(self.val)
def __eq__(self, other):
return type(self.val) is ... | _HashableWithStrictTypeEquality |
python | weaviate__weaviate-python-client | weaviate/cluster/types.py | {
"start": 544,
"end": 753
} | class ____(TypedDict):
batchStats: BatchStats
gitHash: str
name: str
shards: Optional[List[Shard]]
stats: Stats
status: str
version: str
Verbosity = Literal["minimal", "verbose"]
| Node |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 10980,
"end": 11130
} | class ____(_NumberBoundError):
code = 'number.not_le'
msg_template = 'ensure this value is less than or equal to {limit_value}'
| NumberNotLeError |
python | openai__openai-python | examples/realtime/audio_util.py | {
"start": 926,
"end": 4266
} | class ____:
def __init__(self):
self.queue = []
self.lock = threading.Lock()
self.stream = sd.OutputStream(
callback=self.callback,
samplerate=SAMPLE_RATE,
channels=CHANNELS,
dtype=np.int16,
blocksize=int(CHUNK_LENGTH_S * SAMPLE_RAT... | AudioPlayerAsync |
python | numpy__numpy | numpy/random/tests/test_random.py | {
"start": 11866,
"end": 45716
} | class ____:
# Make sure the random distribution returns the correct value for a
# given seed
seed = 1234567890
def test_rand(self):
rng = random.RandomState(self.seed)
actual = rng.rand(3, 2)
desired = np.array([[0.61879477158567997, 0.59162362775974664],
... | TestRandomDist |
python | numpy__numpy | numpy/_core/tests/test_umath.py | {
"start": 43918,
"end": 51927
} | class ____:
def test_power_float(self):
x = np.array([1., 2., 3.])
assert_equal(x**0, [1., 1., 1.])
assert_equal(x**1, x)
assert_equal(x**2, [1., 4., 9.])
y = x.copy()
y **= 2
assert_equal(y, [1., 4., 9.])
assert_almost_equal(x**(-1), [1., 0.5, 1. / 3]... | TestPower |
python | pypa__hatch | tests/cli/test/test_test.py | {
"start": 30560,
"end": 36380
} | class ____:
@pytest.mark.usefixtures("env_run")
@pytest.mark.parametrize("option", ["--include", "--exclude"])
def test_usage_with_all(self, hatch, temp_dir, config_file, helpers, option):
config_file.model.template.plugins["default"]["tests"] = False
config_file.save()
project_name... | TestFilters |
python | python-markdown__markdown | markdown/inlinepatterns.py | {
"start": 33933,
"end": 35744
} | class ____(LinkInlineProcessor):
""" Match to a stored reference and return link element. """
NEWLINE_CLEANUP_RE = re.compile(r'\s+', re.MULTILINE)
RE_LINK = re.compile(r'\s?\[([^\]]*)\]', re.DOTALL | re.UNICODE)
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | None, int | N... | ReferenceInlineProcessor |
python | numpy__numpy | numpy/_core/tests/test_overrides.py | {
"start": 850,
"end": 4435
} | class ____:
def test_ndarray(self):
array = np.array(1)
args = _get_implementing_args([array])
assert_equal(list(args), [array])
args = _get_implementing_args([array, array])
assert_equal(list(args), [array])
args = _get_implementing_args([array, 1])
asser... | TestGetImplementingArgs |
python | openai__gym | gym/envs/classic_control/cartpole.py | {
"start": 368,
"end": 11570
} | class ____(gym.Env[np.ndarray, Union[int, np.ndarray]]):
"""
### Description
This environment corresponds to the version of the cart-pole problem described by Barto, Sutton, and Anderson in
["Neuronlike Adaptive Elements That Can Solve Difficult Learning Control Problem"](https://ieeexplore.ieee.org/do... | CartPoleEnv |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-seller-partner/unit_tests/integration/test_vendor_direct_fulfillment_shipping.py | {
"start": 2136,
"end": 6564
} | class ____:
@staticmethod
def _read(config_: ConfigBuilder, expecting_exception: bool = False) -> EntrypointOutput:
return read_output(
config_builder=config_,
stream_name=_STREAM_NAME,
sync_mode=SyncMode.full_refresh,
expecting_exception=expecting_excepti... | TestFullRefresh |
python | redis__redis-py | redis/auth/err.py | {
"start": 196,
"end": 522
} | class ____(Exception):
"""
Represents an exception related to invalid token schema.
"""
def __init__(self, missing_fields: Iterable[str] = []):
super().__init__(
"Unexpected token schema. Following fields are missing: "
+ ", ".join(missing_fields)
)
| InvalidTokenSchemaErr |
python | numba__numba | numba/cuda/tests/cudapy/test_multithreads.py | {
"start": 1214,
"end": 2861
} | class ____(CUDATestCase):
@unittest.skipIf(not has_concurrent_futures, "no concurrent.futures")
def test_concurrent_compiling(self):
check_concurrent_compiling()
@unittest.skipIf(not has_mp_get_context, "no multiprocessing.get_context")
def test_spawn_concurrent_compilation(self):
# fo... | TestMultiThreadCompiling |
python | sphinx-doc__sphinx | sphinx/util/_files.py | {
"start": 223,
"end": 1912
} | class ____(dict[str, tuple[set[str], str]]): # NoQA: FURB189
"""A dictionary that automatically generates unique names for its keys,
interpreted as filenames, and keeps track of a set of docnames they
appear in. Used for images and downloadable files in the environment.
"""
def __init__(self) -> ... | FilenameUniqDict |
python | xlwings__xlwings | xlwings/conversion/standard.py | {
"start": 5716,
"end": 5920
} | class ____(Accessor):
@classmethod
def reader(cls, options):
return Pipeline().append_stage(
ExpandRangeStage(options), only_if=options.get("expand", None)
)
| BaseAccessor |
python | TheAlgorithms__Python | data_structures/hashing/hash_table_with_linked_list.py | {
"start": 67,
"end": 846
} | class ____(HashTable):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _set_value(self, key, data):
self.values[key] = deque([]) if self.values[key] is None else self.values[key]
self.values[key].appendleft(data)
self._keys[key] = self.values[key]
... | HashTableWithLinkedList |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pie/PIE796.py | {
"start": 261,
"end": 332
} | class ____(Enum):
A = 1.0
B = 2.5
C = 2.5 # PIE796
| FakeEnum4 |
python | sanic-org__sanic | sanic/cli/base.py | {
"start": 145,
"end": 371
} | class ____(ArgumentParser):
def _check_value(self, action: Action, value: Any) -> None:
if isinstance(action, SanicSubParsersAction):
return
super()._check_value(action, value)
| SanicArgumentParser |
python | pytorch__pytorch | test/inductor/test_op_completeness.py | {
"start": 419,
"end": 1590
} | class ____(TestCase):
def verify_ops_handler_completeness(self, handler):
for op in OP_NAMES:
self.assertIsNot(
getattr(handler, op),
getattr(OpsHandler, op),
msg=f"{handler} must implement {op}",
)
extra_ops = list_ops(handler)... | TestOpCompleteness |
python | celery__celery | celery/exceptions.py | {
"start": 6466,
"end": 6540
} | class ____(CeleryError):
"""Security related exception."""
| SecurityError |
python | getsentry__sentry | src/sentry/integrations/utils/metrics.py | {
"start": 1576,
"end": 3458
} | class ____(EventLifecycleMetric, ABC):
"""A metric relating to integrations that uses a standard naming structure."""
def get_metrics_domain(self) -> str:
"""Return a constant describing the top-level metrics category.
This defaults to a catch-all value but can optionally be overridden.
... | IntegrationEventLifecycleMetric |
python | pytorch__pytorch | torch/ao/nn/intrinsic/quantized/modules/conv_relu.py | {
"start": 5781,
"end": 8513
} | class ____(nnq.Conv3d):
r"""
A ConvReLU3d module is a fused module of Conv3d and ReLU
We adopt the same interface as :class:`torch.ao.nn.quantized.Conv3d`.
Attributes: Same as torch.ao.nn.quantized.Conv3d
"""
_FLOAT_MODULE = torch.ao.nn.intrinsic.ConvReLU3d # type: ignore[assignment]
d... | ConvReLU3d |
python | langchain-ai__langchain | libs/core/langchain_core/agents.py | {
"start": 1302,
"end": 3294
} | class ____(Serializable):
"""Represents a request to execute an action by an agent.
The action consists of the name of the tool to execute and the input to pass
to the tool. The log is used to pass along extra information about the action.
"""
tool: str
"""The name of the Tool to execute."""
... | AgentAction |
python | jazzband__django-polymorphic | src/polymorphic/templatetags/polymorphic_admin_tags.py | {
"start": 87,
"end": 1704
} | class ____(Node):
def __init__(self, base_opts, nodelist):
self.base_opts = base_opts
self.nodelist = nodelist # Note, takes advantage of Node.child_nodelists
@classmethod
def parse(cls, parser, token):
bits = token.split_contents()
if len(bits) == 2:
(tagname, ... | BreadcrumbScope |
python | joblib__joblib | joblib/compressor.py | {
"start": 7007,
"end": 18241
} | class ____(io.BufferedIOBase):
"""A file object providing transparent zlib (de)compression.
TODO python2_drop: is it still needed since we dropped Python 2 support A
BinaryZlibFile can act as a wrapper for an existing file object, or refer
directly to a named file on disk.
Note that BinaryZlibFile... | BinaryZlibFile |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 26694,
"end": 26810
} | class ____(Interface):
def __call__(request):
"""Return a root object based on the request"""
| IRootFactory |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 1609,
"end": 1644
} | class ____(BasicEntity):
pass
| Foo |
python | sphinx-doc__sphinx | tests/roots/test-ext-autosummary/autosummary_dummy_inherited_module.py | {
"start": 43,
"end": 231
} | class ____(Foo):
def __init__(self):
#: other docstring
self.subclassattr = 'subclassattr'
super().__init__()
__all__ = ['InheritedAttrClass']
| InheritedAttrClass |
python | django__django | django/core/cache/backends/redis.py | {
"start": 837,
"end": 5101
} | class ____:
def __init__(
self,
servers,
serializer=None,
pool_class=None,
parser_class=None,
**options,
):
import redis
self._lib = redis
self._servers = servers
self._pools = {}
self._client = self._lib.Redis
if... | RedisCacheClient |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/torch_entities/layers.py | {
"start": 5819,
"end": 7640
} | class ____(MemoryModule):
"""
Memory module that implements LSTM.
"""
def __init__(
self,
input_size: int,
memory_size: int,
num_layers: int = 1,
forget_bias: float = 1.0,
kernel_init: Initialization = Initialization.XavierGlorotUniform,
bias_init... | LSTM |
python | sqlalchemy__sqlalchemy | test/orm/declarative/test_dc_transforms.py | {
"start": 82275,
"end": 93950
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
"""tests related to #12168"""
__dialect__ = "default"
@testing.fixture(params=[True, False])
def dc_decl_base(self, request, metadata):
_md = metadata
udd = request.param
class Base(MappedAsDataclass, DeclarativeBase)... | UseDescriptorDefaultsTest |
python | qdrant__qdrant-client | qdrant_client/local/distances.py | {
"start": 393,
"end": 513
} | class ____(str, Enum):
BIGGER_IS_BETTER = "bigger_is_better"
SMALLER_IS_BETTER = "smaller_is_better"
| DistanceOrder |
python | google__jax | tests/array_extensibility_test.py | {
"start": 2663,
"end": 18332
} | class ____:
"""Shortcut for specifying ShapeDtypeStruct."""
def __init__(self, dtype):
self.dtype = jax.dtypes.canonicalize_dtype(dtype)
def __getitem__(self, shape) -> jax.ShapeDtypeStruct:
if isinstance(shape, int):
shape = (shape,)
return jax.ShapeDtypeStruct(shape, self.dtype)
Bool = ShapeD... | ShapeDtype |
python | mlflow__mlflow | mlflow/types/chat.py | {
"start": 6645,
"end": 7008
} | class ____(BaseModel):
"""
A response from the chat completion API.
Must be compatible with OpenAI's Chat Completion API.
https://platform.openai.com/docs/api-reference/chat
"""
id: str | None = None
object: str = "chat.completion"
created: int
model: str
choices: list[ChatChoi... | ChatCompletionResponse |
python | apache__airflow | airflow-core/src/airflow/models/backfill.py | {
"start": 2526,
"end": 2706
} | class ____(AirflowException):
"""
Raised when a backfill cannot be completed because the reprocess behavior is not valid.
:meta private:
"""
| InvalidReprocessBehavior |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_vectors.py | {
"start": 2554,
"end": 9348
} | class ____(ColumnMapExpectation):
"""Expect column values to be vectors."""
# These examples will be shown in the public gallery, and also executed as unit tests for your Expectation
examples = [
{
"data": {
"mostly_vectors_and_numbers_strings_scalars": [
... | ExpectColumnValuesToBeVectors |
python | pandas-dev__pandas | pandas/core/arrays/numeric.py | {
"start": 8304,
"end": 10228
} | class ____(BaseMaskedArray):
"""
Base class for IntegerArray and FloatingArray.
"""
_dtype_cls: type[NumericDtype]
def __init__(
self, values: np.ndarray, mask: npt.NDArray[np.bool_], copy: bool = False
) -> None:
checker = self._dtype_cls._checker
if not (isinstance(va... | NumericArray |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0052_migrate_null_external_builds_field.py | {
"start": 371,
"end": 593
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0051_project_urlconf_feature"),
]
operations = [
migrations.RunPython(forwards_func),
]
| Migration |
python | huggingface__transformers | src/transformers/models/glm4v/modular_glm4v.py | {
"start": 38055,
"end": 42618
} | class ____(Qwen2_5_VLTextModel):
def __init__(self, config: Glm4vTextConfig):
super().__init__(config)
self.layers = nn.ModuleList(
[Glm4vTextDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.norm = Glm4vRMSNorm(config.hidden_size, e... | Glm4vTextModel |
python | pytorch__pytorch | torch/distributed/pipelining/_schedule_visualizer.py | {
"start": 583,
"end": 3823
} | class ____(NamedTuple):
stage_index: int
computation_type: _ComputationType
microbatch_index: int
def get_schedule_ops(
schedule: str | type[_PipelineSchedule],
pp_degree: int,
num_microbatches: int,
num_stages_per_rank: int | None = None,
add_spacing: bool = False,
with_comms: boo... | OpKey |
python | PyCQA__pylint | tests/functional/g/generic_class_syntax.py | {
"start": 262,
"end": 508
} | class ____(Entity[int]):
def __init__(self, data: int) -> None:
super().__init__(data)
def async_update(self) -> None:
self.data = 2
if self.last_update is None:
pass
self.last_update = 2
| Sensor |
python | PrefectHQ__prefect | tests/_internal/test_installation.py | {
"start": 5902,
"end": 11805
} | class ____:
@patch("prefect._internal.installation.importlib.import_module")
@patch("prefect.utilities.processutils.run_process", new_callable=AsyncMock)
async def test_ainstall_packages_with_uv_available(
self, mock_run_process: AsyncMock, mock_import_module: MagicMock
):
packages = ["p... | TestAinstallPackages |
python | davidhalter__parso | parso/pgen2/grammar_parser.py | {
"start": 1216,
"end": 5515
} | class ____:
"""
The parser for Python grammar files.
"""
def __init__(self, bnf_grammar: str):
self._bnf_grammar = bnf_grammar
self.generator = tokenize(
bnf_grammar,
version_info=parse_version_string('3.9')
)
self._gettoken() # Initialize lookahe... | GrammarParser |
python | astropy__astropy | astropy/modeling/tests/test_models.py | {
"start": 40300,
"end": 41294
} | class ____(_ModelMeta):
@classmethod
def __prepare__(cls, name, bases, **kwds):
# this shows the parent class machinery still applies
namespace = super().__prepare__(name, bases, **kwds)
# the custom bit
namespace.update(kwds)
return namespace
model = models.Gaussian... | _ExtendedModelMeta |
python | great-expectations__great_expectations | great_expectations/render/components.py | {
"start": 787,
"end": 907
} | class ____(str, Enum):
"""Available renderer prefixes"""
LEGACY = "renderer"
ATOMIC = "atomic"
| RendererPrefix |
python | kamyu104__LeetCode-Solutions | Python/minimize-connected-groups-by-inserting-interval.py | {
"start": 82,
"end": 739
} | class ____(object):
def minConnectedGroups(self, intervals, k):
"""
:type intervals: List[List[int]]
:type k: int
:rtype: int
"""
intervals.sort()
result = 0
prefix = [0]*(len(intervals)+1)
mx = float("-inf")
left = 0
for right ... | Solution |
python | huggingface__transformers | src/transformers/models/longcat_flash/modeling_longcat_flash.py | {
"start": 10540,
"end": 15179
} | class ____(nn.Module):
"""
A mixed expert module containing zero compute (identity) experts.
"""
def __init__(self, config):
super().__init__()
self.intermediate_size = config.expert_ffn_hidden_size
self.config = config
self.experts = LongcatFlashExperts(config)
... | LongcatFlashMoE |
python | apache__airflow | providers/jenkins/src/airflow/providers/jenkins/operators/jenkins_job_trigger.py | {
"start": 2899,
"end": 10397
} | class ____(BaseOperator):
"""
Trigger a Jenkins Job and monitor its execution.
This operator depend on the python-jenkins library version >= 0.4.15 to
communicate with the Jenkins server. You'll also need to configure a Jenkins
connection in the connections screen.
:param jenkins_connection_id... | JenkinsJobTriggerOperator |
python | celery__celery | celery/local.py | {
"start": 8056,
"end": 12008
} | class ____(Proxy):
"""Proxy that evaluates object once.
:class:`Proxy` will evaluate the object each time, while the
promise will only evaluate it once.
"""
__slots__ = ('__pending__', '__weakref__')
def _get_current_object(self):
try:
return object.__getattribute__(self, ... | PromiseProxy |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 30372,
"end": 31465
} | class ____(Sky2PixProjection, Conic):
r"""
Alber's conic equal area projection - sky to pixel.
Corresponds to the ``COE`` projection in FITS WCS.
See `Conic` for a description of the entire equation.
The projection formulae are:
.. math::
C &= \gamma / 2 \\
R_\theta &= \frac{... | Sky2Pix_ConicEqualArea |
python | celery__celery | t/unit/backends/test_arangodb.py | {
"start": 405,
"end": 8246
} | class ____:
def setup_method(self):
self.backend = ArangoDbBackend(app=self.app)
def test_init_no_arangodb(self):
prev, module.py_arango_connection = module.py_arango_connection, None
try:
with pytest.raises(ImproperlyConfigured):
ArangoDbBackend(app=self.ap... | test_ArangoDbBackend |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_str.py | {
"start": 205,
"end": 339
} | class ____:
def __str__(self):
return False
# TODO: Once Ruff has better type checking
def return_int():
return 3
| Bool |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/dags.py | {
"start": 4176,
"end": 4283
} | class ____(StrictBaseModel):
"""Dag Serializer for updatable bodies."""
is_paused: bool
| DAGPatchBody |
python | psf__requests | src/requests/exceptions.py | {
"start": 2090,
"end": 2158
} | class ____(ConnectionError):
"""An SSL error occurred."""
| SSLError |
python | kamyu104__LeetCode-Solutions | Python/profitable-schemes.py | {
"start": 60,
"end": 608
} | class ____(object):
def profitableSchemes(self, G, P, group, profit):
"""
:type G: int
:type P: int
:type group: List[int]
:type profit: List[int]
:rtype: int
"""
dp = [[0 for _ in xrange(G+1)] for _ in xrange(P+1)]
dp[0][0] = 1
for p, ... | Solution |
python | matplotlib__matplotlib | lib/matplotlib/_mathtext.py | {
"start": 37638,
"end": 38252
} | class ____(Node):
"""A node with a physical location."""
def __init__(self, width: float, height: float, depth: float) -> None:
super().__init__()
self.width = width
self.height = height
self.depth = depth
def shrink(self) -> None:
super().shrink()
if self... | Box |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 1530,
"end": 1633
} | class ____(Sitemap):
changefreq = "never"
priority = 0.5
location = "/location/"
| EmptySitemap |
python | numba__numba | numba/core/config.py | {
"start": 3495,
"end": 23057
} | class ____(object):
def __init__(self):
self.reset()
def reset(self):
self.old_environ = {}
self.update(force=True)
def update(self, force=False):
new_environ = {}
# first check if there's a .numba_config.yaml and use values from that
if os.path.exists(_co... | _EnvReloader |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 163917,
"end": 164304
} | class ____(sgqlc.types.Input):
"""A message to include with a new commit"""
__schema__ = github_schema
__field_names__ = ("headline", "body")
headline = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="headline")
"""The headline of the message."""
body = sgqlc.types.Field(String, ... | CommitMessage |
python | sqlalchemy__sqlalchemy | test/orm/test_deprecations.py | {
"start": 12754,
"end": 16072
} | class ____(fixtures.TestBase):
def test_unloaded_expirable(self, decl_base):
class A(decl_base):
__tablename__ = "a"
id = mapped_column(Integer, Identity(), primary_key=True)
x = mapped_column(
Integer,
)
y = mapped_column(Integer, ... | MiscDeprecationsTest |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1561149,
"end": 1562807
} | class ____(
ColorDef, MarkPropDefGradientstringnull
):
"""
ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull schema wrapper.
Parameters
----------
condition : dict, :class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalParameterMarkPropFieldOrDatumDef`, :class:`Conditiona... | ValueDefWithConditionMarkPropFieldOrDatumDefGradientstringnull |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 920631,
"end": 923195
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"associated_pull_requests",
"branch_protection_rule",
"name",
"prefix",
"ref_update_rule",
"repository",
"target",
)... | Ref |
python | doocs__leetcode | lcof2/剑指 Offer II 097. 子序列的数目/Solution2.py | {
"start": 0,
"end": 260
} | class ____:
def numDistinct(self, s: str, t: str) -> int:
n = len(t)
f = [1] + [0] * n
for a in s:
for j in range(n, 0, -1):
if a == t[j - 1]:
f[j] += f[j - 1]
return f[n]
| Solution |
python | google__pytype | pytype/pattern_matching.py | {
"start": 2577,
"end": 4767
} | class ____:
"""Holds a set of options."""
def __init__(self):
# Collection of options, stored as a dict rather than a set so we can find a
# given option efficiently.
self._options: dict[abstract.Class, _Option] = {}
def __iter__(self):
yield from self._options.values()
def __bool__(self):
... | _OptionSet |
python | walkccc__LeetCode | solutions/99. Recover Binary Search Tree/99.py | {
"start": 0,
"end": 636
} | class ____:
def recoverTree(self, root: TreeNode | None) -> None:
def swap(x: TreeNode | None, y: TreeNode | None) -> None:
temp = x.val
x.val = y.val
y.val = temp
def inorder(root: TreeNode | None) -> None:
if not root:
return
inorder(root.left)
if self.pred and... | Solution |
python | sanic-org__sanic | sanic/cli/console.py | {
"start": 1596,
"end": 3022
} | class ____(NamedTuple):
request: Request
response: HTTPResponse
def make_request(
url: str = "/",
headers: Optional[Union[dict[str, Any], Sequence[tuple[str, str]]]] = None,
method: str = "GET",
body: Optional[str] = None,
):
assert repl_app, "No Sanic app has been registered."
headers... | Result |
python | django__django | tests/postgres_tests/test_app_installed_check.py | {
"start": 783,
"end": 4945
} | class ____(PostgreSQLTestCase):
def _make_error(self, obj, klass_name):
"""Helper to create postgres.E005 error for specific objects."""
return checks.Error(
"'django.contrib.postgres' must be in INSTALLED_APPS in order to "
f"use {klass_name}.",
obj=obj,
... | TestPostgresAppInstalledCheck |
python | getsentry__sentry | src/sentry/snuba/sessions_v2.py | {
"start": 2882,
"end": 4147
} | class ____:
def get_snuba_columns(self, raw_groupby):
if "session.status" in raw_groupby:
return [
"sessions",
"sessions_abnormal",
"sessions_crashed",
"sessions_errored",
"sessions_unhandled",
]
... | SessionsField |
python | getsentry__sentry | src/sentry/runner/commands/tsdb.py | {
"start": 233,
"end": 3224
} | class ____(click.ParamType):
name = "datetime"
def convert(
self,
value: str | datetime | None,
param: click.Parameter | None,
context: click.Context | None,
) -> datetime | None:
if value is None:
return value
elif isinstance(value, datetime):
... | DateTimeParamType |
python | astropy__astropy | astropy/units/tests/test_quantity.py | {
"start": 12172,
"end": 29424
} | class ____:
q1 = u.Quantity(11.42, u.meter)
q2 = u.Quantity(8.0, u.centimeter)
def test_addition(self):
# Take units from left object, q1
new_quantity = self.q1 + self.q2
assert new_quantity.value == 11.5
assert new_quantity.unit == u.meter
# Take units from left ob... | TestQuantityOperations |
python | aimacode__aima-python | search.py | {
"start": 2595,
"end": 5239
} | class ____:
"""A node in a search tree. Contains a pointer to the parent (the node
that this is a successor of) and to the actual state for this node. Note
that if a state is arrived at by two paths, then there are two nodes with
the same state. Also includes the action that got us to this state, and
... | Node |
python | PyCQA__pylint | tests/lint/unittest_lint.py | {
"start": 32140,
"end": 42839
} | class ____(PyLinter):
@staticmethod
def should_analyze_file(modname: str, path: str, is_argument: bool = False) -> bool:
if os.path.basename(path) == "wrong.py":
return False
return super(_CustomPyLinter, _CustomPyLinter).should_analyze_file(
modname, path, is_argument=i... | _CustomPyLinter |
python | joblib__joblib | joblib/pool.py | {
"start": 3551,
"end": 6056
} | class ____(object):
"""Locked Pipe implementation that uses a customizable pickler.
This class is an alternative to the multiprocessing implementation
of SimpleQueue in order to make it possible to pass custom
pickling reducers, for instance to avoid memory copy when passing
memory mapped datastruc... | CustomizablePicklingQueue |
python | django__django | django/utils/connection.py | {
"start": 139,
"end": 836
} | class ____:
"""Proxy for accessing a connection object's attributes."""
def __init__(self, connections, alias):
self.__dict__["_connections"] = connections
self.__dict__["_alias"] = alias
def __getattr__(self, item):
return getattr(self._connections[self._alias], item)
def __s... | ConnectionProxy |
python | sympy__sympy | sympy/utilities/_compilation/runners.py | {
"start": 9630,
"end": 10237
} | class ____(CompilerRunner):
environ_key_compiler = 'FC'
environ_key_flags = 'FFLAGS'
standards = (None, 'f77', 'f95', 'f2003', 'f2008')
std_formater = {
'gfortran': lambda x: '-std=gnu' if x is None else '-std=legacy' if x == 'f77' else '-std={}'.format(x),
'ifort': lambda x: '-stand ... | FortranCompilerRunner |
python | pydantic__pydantic | pydantic/mypy.py | {
"start": 5666,
"end": 8722
} | class ____:
"""A Pydantic mypy plugin config holder.
Attributes:
init_forbid_extra: Whether to add a `**kwargs` at the end of the generated `__init__` signature.
init_typed: Whether to annotate fields in the generated `__init__`.
warn_required_dynamic_aliases: Whether to raise required ... | PydanticPluginConfig |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_open_library_id.py | {
"start": 1626,
"end": 3910
} | class ____(ColumnMapExpectation):
"""Expect column values to conform to the valid Open Library ID format."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_o... | ExpectColumnValuesToBeValidOpenLibraryId |
python | google__jax | tests/python_callback_test.py | {
"start": 33393,
"end": 44086
} | class ____(jtu.JaxTestCase):
def setUp(self):
super().setUp()
if not jtu.test_device_matches(["cpu", "gpu", "tpu"]):
self.skipTest(f"Host callback not supported on {jtu.device_under_test()}")
def tearDown(self):
super().tearDown()
dispatch.runtime_tokens.clear()
def test_io_callback_can_m... | IOCallbackTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.