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 | pylint/utils/linterstats.py | {
"start": 730,
"end": 905
} | class ____(TypedDict):
"""TypedDict to store counts of lines of code types."""
code: int
comment: int
docstring: int
empty: int
total: int
| CodeTypeCount |
python | nedbat__coveragepy | tests/test_config.py | {
"start": 36466,
"end": 37740
} | class ____(CoverageTest):
"""Tests of serializing the configuration for subprocesses."""
def test_them(self) -> None:
tmpsrc = str(Path(tempfile.gettempdir()) / "more_source")
self.make_file(
".coveragerc",
f"""\
[run]
timid = True
dat... | SerializeConfigTest |
python | celery__celery | t/smoke/tests/quorum_queues/conftest.py | {
"start": 1949,
"end": 3441
} | class ____(SmokeWorkerContainer):
@classmethod
def log_level(cls) -> str:
return "INFO"
@classmethod
def worker_queue(cls) -> str:
return "celery"
@pytest.fixture
def default_worker_container_cls() -> type[SmokeWorkerContainer]:
return QuorumWorkerContainer
@pytest.fixture(scope... | QuorumWorkerContainer |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 361536,
"end": 361803
} | class ____(stats.rv_continuous):
def _pdf(self, x, a, b):
return a + b
def _cdf(self, x, a):
# Different # of shape params from _pdf, to be able to check that
# inspection catches the inconsistency.
return 42 * a + x
| _distr3_gen |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/enums.py | {
"start": 1892,
"end": 2108
} | class ____(ToUpperCase, enum.Enum):
"""this is enum class"""
x = 'x'
def say_hello(self):
"""docstring"""
@classmethod
def say_goodbye(cls):
"""docstring"""
| EnumClassWithMixinType |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 21942,
"end": 22843
} | class ____(TestCase):
def test_basic(self):
it = iter(['item'])
self.assertEqual(mi.one(it), 'item')
def test_too_short_new(self):
it = iter([])
self.assertRaises(ValueError, lambda: mi.one(it))
self.assertRaises(
OverflowError, lambda: mi.one(it, too_short=O... | OneTests |
python | ray-project__ray | rllib/algorithms/dqn/tests/test_dqn.py | {
"start": 142,
"end": 1363
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_dqn_compilation(self):
"""Test whether DQN can be built and trained."""
num_iterations = 2
config = (
... | TestDQN |
python | gevent__gevent | src/gevent/_greenlet_primitives.py | {
"start": 955,
"end": 1700
} | class ____(greenlet):
def __init__(self, function, parent):
greenlet.__init__(self, function, parent)
# See greenlet.py's Greenlet class. We capture the cheap
# parts to maintain the tree structure, but we do not capture
# the stack because that's too expensive for 'spawn_raw'.
... | TrackedRawGreenlet |
python | pytorch__pytorch | torch/_inductor/ops_handler.py | {
"start": 22882,
"end": 25421
} | class ____(OpsHandler[Any]):
def _default(self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> Any:
"""
Default implementation for all ops. Override in a subclass to
provide generic op behavior.
Args:
name: name of the op, see OpHandler.{name}
... | DefaultHandler |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/vertex_ai/test_feature_store.py | {
"start": 7105,
"end": 9740
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("feature_store.FeatureStoreHook"))
def test_execute(self, mock_hook_class):
feature_view_conf_params = {
"big_query_source": FeatureView.BigQuerySource(
uri="bq://{BQ_TABLE}",
entity_id_columns=["entity_id"],
... | TestCreateFeatureViewOperator |
python | pytest-dev__pytest | src/_pytest/outcomes.py | {
"start": 296,
"end": 1180
} | class ____(BaseException):
"""OutcomeException and its subclass instances indicate and contain info
about test and collection outcomes."""
def __init__(self, msg: str | None = None, pytrace: bool = True) -> None:
if msg is not None and not isinstance(msg, str):
error_msg = ( # type: ig... | OutcomeException |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable_py30.py | {
"start": 663,
"end": 1048
} | class ____:
""" Other annotation problems. """
Undef = 42
ABC = 42
class InnerScope:
""" Test inner scope definition. """
def test_undefined(self)->Undef: # [undefined-variable]
""" Looking at a higher scope is impossible. """
def test1(self)->ABC: # [undefined-va... | Undefined1 |
python | huggingface__transformers | src/transformers/models/switch_transformers/modeling_switch_transformers.py | {
"start": 2390,
"end": 5657
} | class ____(nn.Module):
"""
Router using tokens choose top-1 experts assignment.
This router uses the same mechanism as in Switch Transformer (https://huggingface.co/papers/2101.03961) and V-MoE
(https://huggingface.co/papers/2106.05974): tokens choose their top experts. Items are sorted by router_probs... | SwitchTransformersTop1Router |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1574552,
"end": 1577434
} | class ____(sgqlc.types.Type, Node):
"""A domain that can be verified or approved for an organization or
an enterprise.
"""
__schema__ = github_schema
__field_names__ = (
"created_at",
"database_id",
"dns_host_name",
"domain",
"has_found_host_name",
"h... | VerifiableDomain |
python | Pylons__pyramid | tests/test_scripts/dummy.py | {
"start": 2234,
"end": 3389
} | class ____:
def __init__(
self,
app=None,
registry=None,
request=None,
root=None,
root_factory=None,
closer=None,
):
self.app = app or DummyApp()
if registry is None:
registry = DummyRegistry()
self.registry = registry
... | DummyBootstrap |
python | huggingface__transformers | src/transformers/models/edgetam_video/modular_edgetam_video.py | {
"start": 20827,
"end": 25240
} | class ____(Sam2VideoAttention):
pass
def apply_rotary_pos_emb_2d_self_attn(
q: torch.Tensor,
k: torch.Tensor,
cos: torch.Tensor,
sin: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Apply rotary position embedding to query and key tensors for self-attention.
Args:
q:... | EdgeTamVideoAttention |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 10340,
"end": 10519
} | class ____(Where):
"""Less than comparison"""
key: str
value: Any
def to_dict(self) -> Dict[str, Any]:
return {self.key: {"$lt": self.value}}
@dataclass
| Lt |
python | PyCQA__isort | isort/exceptions.py | {
"start": 2869,
"end": 3337
} | class ____(ISortError):
"""Raised when the specified sorting function isn't available"""
def __init__(self, sort_order: str, available_sort_orders: list[str]):
super().__init__(
f"Specified sort_order of {sort_order} does not exist. "
f"Available sort_orders: {','.join(available... | SortingFunctionDoesNotExist |
python | joblib__joblib | joblib/pool.py | {
"start": 7673,
"end": 14134
} | class ____(PicklingPool):
"""Process pool that shares large arrays to avoid memory copy.
This drop-in replacement for `multiprocessing.pool.Pool` makes
it possible to work efficiently with shared memory in a numpy
context.
Existing instances of numpy.memmap are preserved: the child
suprocesses... | MemmappingPool |
python | tensorflow__tensorflow | tensorflow/python/ops/resource_variable_ops.py | {
"start": 105925,
"end": 115474
} | class ____(tensor_module.DenseSpec):
"""Describes a tf.Variable.
A `VariableSpec` provides metadata describing the `tf.Variable` objects
accepted or returned by TensorFlow 2.x APIs.
"""
__slots__ = ["trainable", "alias_id"]
value_type = property(lambda self: ResourceVariable)
def __init__(self, shape,... | VariableSpec |
python | walkccc__LeetCode | solutions/1277. Count Square Submatrices with All Ones/1277.py | {
"start": 0,
"end": 346
} | class ____:
def countSquares(self, matrix: list[list[int]]) -> int:
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 1 and i > 0 and j > 0:
matrix[i][j] += min(matrix[i - 1][j - 1],
matrix[i - 1][j], matrix[i][j - 1])
return ... | Solution |
python | cython__cython | Cython/Compiler/Main.py | {
"start": 1639,
"end": 25350
} | class ____:
# This class encapsulates the context needed for compiling
# one or more Cython implementation files along with their
# associated and imported declaration files. It includes
# the root of the module import namespace and the list
# of directories to search for include files.
#
... | Context |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP037_0.py | {
"start": 460,
"end": 502
} | class ____(NamedTuple):
x: "MyClass"
| Foo |
python | pytorch__pytorch | torch/xpu/__init__.py | {
"start": 5935,
"end": 6546
} | class ____:
r"""Context-manager that changes the selected device.
Args:
device (torch.device or int or str): device index to select. It's a no-op if
this argument is a negative integer or ``None``.
"""
def __init__(self, device: Any) -> None:
self.idx = _get_device_index(de... | device |
python | ethereum__web3.py | web3/_utils/datatypes.py | {
"start": 556,
"end": 1653
} | class ____(type):
def __init__(
cls,
name: str,
bases: tuple[type[Any], ...],
namespace: dict[str, Any],
**kwargs: dict[str, Any],
) -> None:
# see PEP487. To accept kwargs in __new__, they need to be
# filtered out here.
super().__init__(name, ba... | PropertyCheckingFactory |
python | redis__redis-py | redis/ocsp.py | {
"start": 6121,
"end": 11452
} | class ____:
"""A class to verify ssl sockets for RFC6960/RFC6961. This can be used
when using direct validation of OCSP responses and certificate revocations.
@see https://datatracker.ietf.org/doc/html/rfc6960
@see https://datatracker.ietf.org/doc/html/rfc6961
"""
def __init__(self, sock, host... | OCSPVerifier |
python | huggingface__transformers | utils/modular_integrations.py | {
"start": 6697,
"end": 7139
} | class ____(cst.CSTTransformer):
def __init__(self, relative_path: str, source_library: str):
super().__init__()
self.relative_path = relative_path
self.source_library = source_library
def leave_ImportFrom(self, original_node: cst.ImportFrom, updated_node: cst.ImportFrom) -> cst.ImportFr... | RelativeImportTransformer |
python | wandb__wandb | wandb/automations/_filters/run_metrics.py | {
"start": 1065,
"end": 1284
} | class ____(LenientStrEnum): # from: Aggregation
"""Supported run metric aggregation operations."""
MAX = "MAX"
MIN = "MIN"
AVERAGE = "AVERAGE"
# Shorter aliases for convenience
AVG = AVERAGE
| Agg |
python | pyparsing__pyparsing | pyparsing/results.py | {
"start": 344,
"end": 723
} | class ____:
tup: tuple[ParseResults, int]
__slots__ = ["tup"]
def __init__(self, p1: ParseResults, p2: int) -> None:
self.tup: tuple[ParseResults, int] = (p1, p2)
def __getitem__(self, i):
return self.tup[i]
def __getstate__(self):
return self.tup
def __setstate__(sel... | _ParseResultsWithOffset |
python | lxml__lxml | src/lxml/tests/test_xslt.py | {
"start": 326,
"end": 35003
} | class ____(HelperTestCase):
"""XSLT tests etree"""
def test_xslt(self):
tree = self.parse('<a><b>B</b><c>C</c></a>')
style = self.parse('''\
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*" />
<xsl:template match="/">
<foo><xsl:... | ETreeXSLTTestCase |
python | fsspec__filesystem_spec | fsspec/implementations/reference.py | {
"start": 713,
"end": 1566
} | class ____(RuntimeError):
def __init__(self, reference, target, *args):
super().__init__(*args)
self.reference = reference
self.target = target
def __str__(self):
return f'Reference "{self.reference}" failed to fetch target {self.target}'
def _first(d):
return next(iter(d.... | ReferenceNotReachable |
python | pytorch__pytorch | torch/_dynamo/variables/lists.py | {
"start": 501,
"end": 1672
} | class ____ handles its unique behaviors while integrating with Dynamo's
variable tracking system.
"""
import collections
import inspect
import operator
import sys
from collections.abc import Sequence
from typing import Any, Optional, TYPE_CHECKING
import torch
import torch.fx
from .. import graph_break_hints, polyfi... | that |
python | davidhalter__jedi | jedi/api/exceptions.py | {
"start": 503,
"end": 990
} | class ____(_JediError):
"""
Refactorings can fail for various reasons. So if you work with refactorings
like :meth:`.Script.rename`, :meth:`.Script.inline`,
:meth:`.Script.extract_variable` and :meth:`.Script.extract_function`, make
sure to catch these. The descriptions in the errors are usually val... | RefactoringError |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/column_map_expectation_template.py | {
"start": 996,
"end": 2468
} | class ____(ColumnMapMetricProvider):
# </snippet>
# This is the id string that will be used to reference your metric.
# <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/column_map_expectation_template.py metric_name">
condition_metric_name = "METRIC NAME GOES HER... | ColumnValuesMatchSomeCriteria |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 21975,
"end": 23380
} | class ____(Expr):
fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")
node: Expr
name: str
args: list[Expr]
kwargs: list[Pair]
dyn_args: Expr | None
dyn_kwargs: Expr | None
abstract = True
_is_filter = True
def as_const(self, eval_ctx: EvalContext | None = None... | _FilterTestCommon |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 26622,
"end": 27133
} | class ____(models.Model):
"""
Non-historic table with one to one relationship to historic table.
In this case it should simply behave like ForeignKey because
the origin model (this one) cannot be historic, so foreign key
lookups are always "current".
"""
name = models.CharField(max_length=... | TestParticipantToHistoricOrganizationOneToOne |
python | jazzband__django-oauth-toolkit | oauth2_provider/views/generic.py | {
"start": 580,
"end": 879
} | class ____(ReadWriteScopedResourceMixin, ProtectedResourceView):
"""
Generic view protecting resources with OAuth2 authentication and read/write scopes.
GET, HEAD, OPTIONS http methods require "read" scope. Otherwise "write" scope is required.
"""
pass
| ReadWriteScopedResourceView |
python | getsentry__sentry | src/sentry/sentry_metrics/configuration.py | {
"start": 1221,
"end": 1319
} | class ____(Enum):
POSTGRES = "postgres"
MOCK = "mock"
@dataclass(frozen=True)
| IndexerStorage |
python | pandas-dev__pandas | pandas/core/computation/pytables.py | {
"start": 1395,
"end": 2456
} | class ____(ops.Term):
env: PyTablesScope
def __new__(cls, name, env, side=None, encoding=None):
if isinstance(name, str):
klass = cls
else:
klass = Constant
return object.__new__(klass)
def __init__(self, name, env: PyTablesScope, side=None, encoding=None) -... | Term |
python | dask__dask | dask/tests/test_expr.py | {
"start": 2441,
"end": 2511
} | class ____(MySingletonWithCustomInit): ...
| MySingletonInheritsCustomInit |
python | walkccc__LeetCode | solutions/1456. Maximum Number of Vowels in a Substring of Given Length/1456.py | {
"start": 0,
"end": 272
} | class ____:
def maxVowels(self, s: str, k: int) -> int:
ans = 0
mx = 0
VOWELS = 'aeiou'
for i, c in enumerate(s):
if c in VOWELS:
mx += 1
if i >= k and s[i - k] in VOWELS:
mx -= 1
ans = max(ans, mx)
return ans
| Solution |
python | jmcnamara__XlsxWriter | examples/django_simple.py | {
"start": 517,
"end": 1820
} | class ____(View):
def get(self, request):
# Create an in-memory output file for the new workbook.
output = io.BytesIO()
# Even though the final file will be in memory the module uses temp
# files during assembly for efficiency. To avoid this on servers that
# don't allow tem... | MyView |
python | pytorch__pytorch | torch/fx/experimental/unification/match.py | {
"start": 1219,
"end": 3414
} | class ____(Dispatcher):
"""A dispatcher that calls functions with variable names
>>> # xdoctest: +SKIP
>>> d = VarDispatcher("d")
>>> x = var("x")
>>> @d.register("inc", x)
... def f(x):
... return x + 1
>>> @d.register("double", x)
... def f(x):
... return x * 2
>>> ... | VarDispatcher |
python | huggingface__transformers | src/transformers/models/idefics/perceiver.py | {
"start": 8626,
"end": 9426
} | class ____(nn.Module):
def __init__(self, intermediate_size, config: IdeficsConfig):
"""Simple MLP block with intermediate_size and embedding size"""
super().__init__()
self.embed_dim = config.vision_config.embed_dim
self.ln = nn.LayerNorm(self.embed_dim)
self.fc = nn.Linear(... | IdeficsMLP |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 41870,
"end": 41970
} | class ____:
def __init__(self, value=None):
self.value = value
__hash__ = None
| NoHash |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 90837,
"end": 90912
} | class ____(BinOpFrame):
operation = M.lt
_operator_repr = "<"
| LTFrame |
python | getsentry__sentry | src/sentry/api/endpoints/organization_stats_v2.py | {
"start": 6474,
"end": 6635
} | class ____(TypedDict): # this response is pretty dynamic, leaving generic
by: dict[str, Any]
totals: dict[str, Any]
series: dict[str, Any]
| _StatsGroup |
python | django__django | django/contrib/gis/db/models/aggregates.py | {
"start": 2920,
"end": 3015
} | class ____(GeoAggregate):
name = "MakeLine"
output_field_class = LineStringField
| MakeLine |
python | huggingface__transformers | src/transformers/models/detr/modeling_detr.py | {
"start": 9337,
"end": 11646
} | class ____(nn.Module):
"""
BatchNorm2d where the batch statistics and the affine parameters are fixed.
Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
torchvision.models.resnet[18,34,50,101] produce nans.
"""
def __init__(self, n):
... | DetrFrozenBatchNorm2d |
python | realpython__materials | tic-tac-toe-ai-python/source_code_bonus/tic-tac-toe/library/src/tic_tac_toe/logic/models.py | {
"start": 1149,
"end": 3679
} | class ____:
grid: Grid
starting_mark: Mark = Mark("X")
def __post_init__(self) -> None:
validate_game_state(self)
@cached_property
def current_mark(self) -> Mark:
if self.grid.x_count == self.grid.o_count:
return self.starting_mark
else:
return self.... | GameState |
python | pappasam__jedi-language-server | jedi_language_server/server.py | {
"start": 7545,
"end": 37830
} | class ____(LanguageServer):
"""Jedi language server.
:attr initialization_options: initialized in lsp_initialize from the
protocol_cls.
:attr project: a Jedi project. This value is created in
`JediLanguageServerProtocol.lsp_initialize`.
"""
initialization_options: InitializationOpt... | JediLanguageServer |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_W.py | {
"start": 8742,
"end": 9739
} | class ____(Benchmark):
r"""
Wolfe objective function.
This class defines the Wolfe [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Wolfe}}(x) = \frac{4}{3}(x_1^2 + x_2^2 - x_1x_2)^{0.75} + x_3
with :math:`x_i \in [0,... | Wolfe |
python | tornadoweb__tornado | tornado/websocket.py | {
"start": 3105,
"end": 3580
} | class ____:
def __init__(
self,
ping_interval: Optional[float] = None,
ping_timeout: Optional[float] = None,
max_message_size: int = _default_max_message_size,
compression_options: Optional[Dict[str, Any]] = None,
) -> None:
self.ping_interval = ping_interval
... | _WebSocketParams |
python | numba__numba | numba/tests/test_locals.py | {
"start": 88,
"end": 335
} | class ____(unittest.TestCase):
def test_seed_types(self):
cfunc = njit((), locals={'x': float32})(foo)
self.assertEqual(cfunc.nopython_signatures[0].return_type, float32)
if __name__ == '__main__':
unittest.main()
| TestLocals |
python | pytest-dev__pytest | src/_pytest/subtests.py | {
"start": 10312,
"end": 13235
} | class ____:
handler: LogCaptureHandler
def pytest_report_to_serializable(report: TestReport) -> dict[str, Any] | None:
if isinstance(report, SubtestReport):
return report._to_json()
return None
def pytest_report_from_serializable(data: dict[str, Any]) -> SubtestReport | None:
if data.get("_r... | CapturedLogs |
python | PrefectHQ__prefect | src/prefect/server/exceptions.py | {
"start": 50,
"end": 296
} | class ____(PrefectException):
"""
Error raised by the Prefect REST API when a requested object is not found.
If thrown during a request, this exception will be caught and
a 404 response will be returned.
"""
| ObjectNotFoundError |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/core/components/airflow_instance/component.py | {
"start": 4042,
"end": 4221
} | class ____(Resolvable):
dag_id: str
assets: Optional[Sequence[ResolvedMappedAsset]] = None
task_mappings: Optional[Sequence[AirflowTaskMapping]] = None
| AirflowDagMapping |
python | astropy__astropy | astropy/modeling/tests/test_input.py | {
"start": 23298,
"end": 33781
} | class ____:
"""
A suite of tests to check various cases of parameter and input combinations
on models with n_input = 1 but n_output = 2 on a toy model with n_models=1.
As of writing there are not enough controls to adjust how outputs from such
a model should be formatted (currently the shapes of ou... | TestSingleInputDoubleOutputSingleModel |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 115706,
"end": 116792
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("model_service.Model.to_dict"))
@mock.patch(VERTEX_AI_PATH.format("model_service.ModelServiceHook"))
def test_execute(self, mock_hook, to_dict_mock):
op = SetDefaultVersionOnModelOperator(
task_id=TASK_ID,
model_id=TEST_MODEL_NAME... | TestVertexAISetDefaultVersionOnModelOperator |
python | django__django | tests/admin_views/models.py | {
"start": 26739,
"end": 26845
} | class ____(models.Model):
# Don't point any FK at this model.
pass
# Models for #23934
| NotReferenced |
python | pypa__warehouse | tests/conftest.py | {
"start": 23598,
"end": 25781
} | class ____:
"""
Just enough Redis for our tests.
In-memory only, no persistence.
Does NOT implement the full Redis API.
"""
def __init__(self, cache=None):
self.cache = cache
if not self.cache: # pragma: no cover
self.cache = dict()
def __enter__(self):
... | _MockRedis |
python | scipy__scipy | scipy/special/tests/test_precompute_utils.py | {
"start": 439,
"end": 1165
} | class ____:
@pytest.mark.xfail_on_32bit("rtol only 2e-9, see gh-6938")
def test_log(self):
with mp.workdps(30):
logcoeffs = mp.taylor(lambda x: mp.log(1 + x), 0, 10)
expcoeffs = mp.taylor(lambda x: mp.exp(x) - 1, 0, 10)
invlogcoeffs = lagrange_inversion(logcoeffs)
... | TestInversion |
python | numpy__numpy | numpy/matrixlib/tests/test_masked_matrix.py | {
"start": 8116,
"end": 8822
} | class ____:
# Tests for mr_, the equivalent of r_ for masked arrays.
def test_matrix_builder(self):
assert_raises(np.ma.MAError, lambda: mr_['1, 2; 3, 4'])
def test_matrix(self):
# Test consistency with unmasked version. If we ever deprecate
# matrix, this test should either still... | TestConcatenator |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_worksheet07.py | {
"start": 400,
"end": 2720
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with formulas in cells."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle(fh)
... | TestAssembleWorksheet |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 200005,
"end": 200446
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "column_edge", "project")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
column_edge = sgqlc.types.Field("ProjectColumnE... | AddProjectColumnPayload |
python | readthedocs__readthedocs.org | readthedocs/api/v3/serializers.py | {
"start": 10440,
"end": 12290
} | class ____(serializers.ModelSerializer):
aliases = serializers.SerializerMethodField()
ref = serializers.CharField()
downloads = serializers.SerializerMethodField()
urls = VersionURLsSerializer(source="*")
_links = VersionLinksSerializer(source="*")
class Meta:
model = Version
f... | VersionSerializer |
python | pytorch__pytorch | test/distributed/tensor/test_random_ops.py | {
"start": 26999,
"end": 30368
} | class ____(DTensorTestBase):
@property
def world_size(self):
return 8
@skip_if_lt_x_gpu(8)
@with_comms
def test_hsdp_tp_model_meta_init(self):
# initialize the 3-d device mesh
global_mesh = init_device_mesh(
self.device_type,
mesh_shape=(self.world_si... | DistTensorRandomOpsTest3D |
python | scrapy__scrapy | tests/test_mail.py | {
"start": 188,
"end": 5073
} | class ____:
def test_send(self):
mailsender = MailSender(debug=True)
mailsender.send(
to=["test@scrapy.org"],
subject="subject",
body="body",
_callback=self._catch_mail_sent,
)
assert self.catched_msg
assert self.catched_msg["... | TestMailSender |
python | kamyu104__LeetCode-Solutions | Python/maximum-coins-from-k-consecutive-bags.py | {
"start": 70,
"end": 923
} | class ____(object):
def maximumCoins(self, coins, k):
"""
:type coins: List[List[int]]
:type k: int
:rtype: int
"""
def max_amount():
coins.sort()
result = curr = left = 0
for right in xrange(len(coins)):
curr += (co... | Solution |
python | realpython__materials | python-property/circle_v4.py | {
"start": 25,
"end": 335
} | class ____:
def __init__(self, radius):
self.radius = radius
self._diameter = None
@property
def diameter(self):
if self._diameter is None:
sleep(0.5) # Simulate a costly computation
self._diameter = self.radius * 2
return self._diameter
| Circle |
python | huggingface__transformers | src/transformers/models/flaubert/modeling_flaubert.py | {
"start": 70993,
"end": 77975
} | class ____(FlaubertPreTrainedModel):
def __init__(self, config, *inputs, **kwargs):
super().__init__(config, *inputs, **kwargs)
self.transformer = FlaubertModel(config)
self.sequence_summary = FlaubertSequenceSummary(config)
self.logits_proj = nn.Linear(config.num_labels, 1)
... | FlaubertForMultipleChoice |
python | huggingface__transformers | src/transformers/models/xlm/modeling_xlm.py | {
"start": 31372,
"end": 40450
} | class ____(XLMPreTrainedModel):
def __init__(self, config):
super().__init__(config)
# encoder / decoder, output layer
self.is_encoder = config.is_encoder
self.is_decoder = not config.is_encoder
if self.is_decoder:
raise NotImplementedError("Currently XLM can onl... | XLMModel |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_framework.py | {
"start": 30164,
"end": 36872
} | class ____:
"""Test before_agent and after_agent hooks working together."""
@pytest.mark.parametrize("is_async", [False, True])
async def test_execution_order(self, is_async: bool) -> None:
"""Test that before_agent executes before after_agent in both sync and async modes."""
from langchain... | TestAgentHooksCombined |
python | google__jax | jax/experimental/mosaic/gpu/utils.py | {
"start": 6360,
"end": 11121
} | class ____:
ref: ir.Value
@property
def type(self) -> ir.Type:
return ir.MemRefType(self.ref.type)
def store(self, value: ir.Value, indices: Sequence[ir.Value]):
ptr = memref_ptr(memref_slice(self.ref, tuple(indices)))
multimem_store(ptr, value)
def multimem_store(ptr: ir.Value, value: ir.Value)... | MultimemRef |
python | doocs__leetcode | solution/1900-1999/1987.Number of Unique Good Subsequences/Solution.py | {
"start": 0,
"end": 357
} | class ____:
def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
f = g = 0
ans = 0
mod = 10**9 + 7
for c in binary:
if c == "0":
g = (g + f) % mod
ans = 1
else:
f = (f + g + 1) % mod
ans = (ans +... | Solution |
python | PrefectHQ__prefect | tests/test_artifacts.py | {
"start": 26776,
"end": 34735
} | class ____:
async def test_update_progress_artifact_updates_progress_async(
self, client: httpx.AsyncClient
):
progress = 0.0
@flow
async def my_flow():
artifact_id = await acreate_progress_artifact(progress)
assert isinstance(artifact_id, UUID)
... | TestUpdateArtifacts |
python | python-openxml__python-docx | tests/image/test_png.py | {
"start": 4914,
"end": 7530
} | class ____:
def it_can_construct_from_a_stream(self, stream_, _ChunkParser_, chunk_parser_, _Chunks__init_):
chunk_lst = [1, 2]
chunk_parser_.iter_chunks.return_value = iter(chunk_lst)
chunks = _Chunks.from_stream(stream_)
_ChunkParser_.from_stream.assert_called_once_with(stream_)
... | Describe_Chunks |
python | tornadoweb__tornado | tornado/iostream.py | {
"start": 3426,
"end": 3542
} | class ____(Exception):
"""Exception raised by `IOStream` methods when the buffer is full."""
| StreamBufferFullError |
python | openai__openai-python | src/openai/types/responses/response_web_search_call_in_progress_event.py | {
"start": 213,
"end": 704
} | class ____(BaseModel):
item_id: str
"""Unique ID for the output item associated with the web search call."""
output_index: int
"""The index of the output item that the web search call is associated with."""
sequence_number: int
"""The sequence number of the web search call being processed."""
... | ResponseWebSearchCallInProgressEvent |
python | doocs__leetcode | lcof2/剑指 Offer II 006. 排序数组中两个数字之和/Solution.py | {
"start": 0,
"end": 298
} | class ____:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
n = len(numbers)
for i in range(n - 1):
x = target - numbers[i]
j = bisect_left(numbers, x, lo=i + 1)
if j < n and numbers[j] == x:
return [i, j]
| Solution |
python | modin-project__modin | modin/core/storage_formats/pandas/groupby.py | {
"start": 9114,
"end": 18208
} | class ____:
"""Provide MapReduce, Range-Partitioning and Full-Column implementations for 'pivot_table()'."""
@classmethod
def map_reduce_impl(
cls, qc, unique_keys, drop_column_level, pivot_kwargs
): # noqa: PR01
"""Compute 'pivot_table()' using MapReduce implementation."""
if ... | PivotTableImpl |
python | getsentry__sentry | src/sentry/apidocs/examples/dashboard_examples.py | {
"start": 5613,
"end": 6478
} | class ____:
DASHBOARD_GET_RESPONSE = [
OpenApiExample(
"Dashboard GET response",
value=DASHBOARD_OBJECT,
status_codes=["200"],
response_only=True,
)
]
DASHBOARD_PUT_RESPONSE = [
OpenApiExample(
"Dashboard PUT response",
... | DashboardExamples |
python | numba__numba | numba/core/debuginfo.py | {
"start": 2037,
"end": 17525
} | class ____(AbstractDIBuilder):
DWARF_VERSION = 4
DEBUG_INFO_VERSION = 3
DBG_CU_NAME = 'llvm.dbg.cu'
_DEBUG = False
def __init__(self, module, filepath, cgctx, directives_only):
self.module = module
self.filepath = os.path.abspath(filepath)
self.difile = self._di_file()
... | DIBuilder |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 107383,
"end": 114722
} | class ____(GenericView):
@staticmethod
def handle_negative_index(idx: Expr, size: Expr) -> Expr:
idx = sympy.expand(idx)
size = sympy.expand(size)
evaluate_expr = V.graph.sizevars.shape_env.evaluate_expr
if evaluate_expr(sympy.Lt(idx, 0)):
idx = idx + size
ret... | View |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 24120,
"end": 24543
} | class ____(RequestHandler):
def get(self):
if self.get_argument("permanent", None) is not None:
self.redirect("/", permanent=bool(int(self.get_argument("permanent"))))
elif self.get_argument("status", None) is not None:
self.redirect("/", status=int(self.get_argument("status"... | RedirectHandler |
python | donnemartin__system-design-primer | solutions/system_design/web_crawler/web_crawler_snippets.py | {
"start": 1183,
"end": 2202
} | class ____(object):
def __init__(self, pages, data_store, reverse_index_queue, doc_index_queue):
self.pages = pages
self.data_store = data_store
self.reverse_index_queue = reverse_index_queue
self.doc_index_queue = doc_index_queue
def crawl_page(self, page):
for url in ... | Crawler |
python | dask__dask | dask/tests/test_delayed.py | {
"start": 3029,
"end": 3093
} | class ____:
a: int
@dataclass(frozen=True)
| ANonFrozenDataClass |
python | nedbat__coveragepy | coverage/parser.py | {
"start": 20721,
"end": 21410
} | class ____(Block):
"""A block on the block stack representing a `for` or `while` loop."""
def __init__(self, start: TLineNo) -> None:
# The line number where the loop starts.
self.start = start
# A set of ArcStarts, the arcs from break statements exiting this loop.
self.break_ex... | LoopBlock |
python | PrefectHQ__prefect | src/prefect/server/events/ordering/__init__.py | {
"start": 1148,
"end": 1231
} | class ____(Protocol):
CausalOrdering: type["CausalOrdering"]
| CausalOrderingModule |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pep8_naming/N815.py | {
"start": 97,
"end": 427
} | class ____:
lower = 0
CONSTANT = 0
mixedCase = 0
_mixedCase = 0
mixed_Case = 0
myObj1 = collections.namedtuple("MyObj1", ["a", "b"])
myObj2 = namedtuple("MyObj2", ["a", "b"])
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
Point2D = TypedDict('Point2D', {'in': int, 'x... | C |
python | astropy__astropy | astropy/modeling/tests/test_models.py | {
"start": 41294,
"end": 41493
} | class ____(Model):
slope = Parameter()
intercept = Parameter()
_separable = False
@staticmethod
def evaluate(x, slope, intercept):
return slope * x + intercept
| ModelDefault |
python | openai__openai-python | src/openai/types/realtime/realtime_response_create_params_param.py | {
"start": 1116,
"end": 4316
} | class ____(TypedDict, total=False):
audio: RealtimeResponseCreateAudioOutputParam
"""Configuration for audio input and output."""
conversation: Union[str, Literal["auto", "none"]]
"""Controls which conversation the response is added to.
Currently supports `auto` and `none`, with `auto` as the defa... | RealtimeResponseCreateParamsParam |
python | kubernetes-client__python | kubernetes/client/api/storagemigration_api.py | {
"start": 543,
"end": 5205
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | StoragemigrationApi |
python | django__django | tests/admin_inlines/admin.py | {
"start": 7219,
"end": 7643
} | class ____(admin.TabularInline):
model = BinaryTree
def get_extra(self, request, obj=None, **kwargs):
extra = 2
if obj:
return extra - obj.binarytree_set.count()
return extra
def get_max_num(self, request, obj=None, **kwargs):
max_num = 3
if obj:
... | BinaryTreeAdmin |
python | django-haystack__django-haystack | test_haystack/test_models.py | {
"start": 384,
"end": 525
} | class ____(std_logging.Handler):
logs_seen = []
def emit(self, record):
CaptureHandler.logs_seen.append(record)
| CaptureHandler |
python | getsentry__sentry | src/sentry/analytics/events/sentryapp_issue_webhooks.py | {
"start": 359,
"end": 470
} | class ____(SentryAppIssueEvent):
pass
@analytics.eventclass("sentry_app.issue.ignored")
| SentryAppIssueCreated |
python | tensorflow__tensorflow | tensorflow/python/distribute/test_util_test.py | {
"start": 1605,
"end": 2606
} | class ____(test.TestCase, parameterized.TestCase):
def testOne(self, strategy):
@def_function.function
def f():
return array_ops.ones((), dtypes.float32)
results = test_util.gather(strategy, strategy.run(f))
self.assertAllEqual(
self.evaluate(results), [1.] * strategy.num_replicas_in_... | GatherTest |
python | facebook__pyre-check | tools/typeshed_patcher/tests/transforms_test.py | {
"start": 271,
"end": 21121
} | class ____(testslide.TestCase):
def assert_transform(
self,
original_code: str,
patch: patch_specs.Patch,
expected_code: str,
) -> None:
actual_output = transforms.apply_patches_in_sequence(
code=textwrap.dedent(original_code),
patches=[patch],
... | PatchTransformsTest |
python | streamlit__streamlit | scripts/cli_regression_tests.py | {
"start": 931,
"end": 8476
} | class ____:
"""Suite of CLI regression tests to be run against a release build of the Streamlit library.
Before running, ensure that you have:
- An isolated environment with Streamlit installed in production mode (not development) as
well as pytest. This can include the current version, night... | TestCLIRegressions |
python | django__django | tests/modeladmin/test_checks.py | {
"start": 31258,
"end": 31792
} | class ____(CheckTestCase):
def test_not_integer(self):
class TestModelAdmin(ModelAdmin):
list_max_show_all = "hello"
self.assertIsInvalid(
TestModelAdmin,
ValidationTestModel,
"The value of 'list_max_show_all' must be an integer.",
"admin.... | ListMaxShowAllCheckTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.