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 | numba__numba | numba/core/ir.py | {
"start": 27540,
"end": 27925
} | class ____(Stmt):
"""
Assign to a variable.
"""
def __init__(self, value, target, loc):
assert isinstance(value, AbstractRHS)
assert isinstance(target, Var)
assert isinstance(loc, Loc)
self.value = value
self.target = target
self.loc = loc
def __str__... | Assign |
python | PyCQA__pylint | doc/data/messages/s/subclassed-final-class/bad.py | {
"start": 148,
"end": 260
} | class ____(PlatypusData): # [subclassed-final-class]
"""Playtipus with fluorescent fur."""
| FluorescentPlaytipus |
python | apache__airflow | providers/mysql/src/airflow/providers/mysql/hooks/mysql.py | {
"start": 2010,
"end": 16335
} | class ____(DbApiHook):
"""
Interact with MySQL.
You can specify charset in the extra field of your connection
as ``{"charset": "utf8"}``. Also you can choose cursor as
``{"cursor": "SSCursor"}``. Refer to the MySQLdb.cursors for more details.
Note: For AWS IAM authentication, use iam in the ex... | MySqlHook |
python | mwaskom__seaborn | tests/_core/test_moves.py | {
"start": 8432,
"end": 9723
} | class ____(MoveFixtures):
def test_basic(self, toy_df):
groupby = GroupBy(["color", "group"])
res = Stack()(toy_df, groupby, "x", {})
assert_array_equal(res["x"], [0, 0, 1])
assert_array_equal(res["y"], [1, 3, 3])
assert_array_equal(res["baseline"], [0, 1, 0])
def tes... | TestStack |
python | sympy__sympy | sympy/integrals/manualintegrate.py | {
"start": 20015,
"end": 20183
} | class ____(AtomicRule):
a: Expr
d: Expr
def eval(self) -> Expr:
return elliptic_f(self.variable, self.d/self.a)/sqrt(self.a)
@dataclass
| EllipticFRule |
python | pandas-dev__pandas | pandas/tests/reshape/merge/test_join.py | {
"start": 624,
"end": 40938
} | class ____:
# aggregate multiple columns
@pytest.fixture
def df(self):
df = DataFrame(
{
"key1": get_test_data(),
"key2": get_test_data(),
"data1": np.random.default_rng(2).standard_normal(50),
"data2": np.random.default_rng... | TestJoin |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 80707,
"end": 83333
} | class ____(NonStrictDataModel):
"""
:param name: Name of the parameter. Should be unique
:type name: str
:param value: Value of the parameter
:type value: str
:param type: Type of the parameter. Optional
:type type: str
:param description: The parameter description. Optional
:type de... | ConfigurationItem |
python | pikepdf__pikepdf | src/pikepdf/canvas.py | {
"start": 30834,
"end": 33253
} | class ____:
"""Canvas for rendering PDFs with pikepdf.
All drawing is done on a pikepdf canvas using the ``.do`` property.
This interface manages the graphics state of the canvas.
A Canvas can be exported as a single page Pdf using ``.to_pdf``. This Pdf can
then be merged into other PDFs or writte... | Canvas |
python | Netflix__metaflow | metaflow/plugins/cards/card_datastore.py | {
"start": 585,
"end": 650
} | class ____:
DATA = "data.json"
CARD = "html"
| CardNameSuffix |
python | tensorflow__tensorflow | tensorflow/python/eager/polymorphic_function/concrete_function.py | {
"start": 39059,
"end": 43541
} | class ____(_TapeGradientFunctions):
"""Caches tape-friendly functions for higher-order gradients."""
# TODO(b/136189779): Cond/while under a tape may need similar logic. Consider
# generalizing if so.
def _forward_and_backward_functions(self, inference_args, input_tangents):
"""Forward and backward functio... | _HigherOrderTapeGradientFunctions |
python | PrefectHQ__prefect | tests/server/orchestration/test_core_policy.py | {
"start": 11552,
"end": 17471
} | class ____:
@pytest.mark.parametrize(
["expiration", "expected_status", "expected_name"],
[
(now("UTC") - timedelta(days=1), SetStateStatus.ACCEPT, "Running"),
(now("UTC") + timedelta(days=1), SetStateStatus.REJECT, "Cached"),
(None, SetStateStatus.REJECT, "Cached... | TestCachingBackendLogic |
python | pytorch__pytorch | test/distributed/test_c10d_gloo.py | {
"start": 85730,
"end": 86214
} | class ____(nn.Module):
def __init__(self) -> None:
super().__init__()
self.fc1 = nn.Linear(2, 10, bias=False)
self.fc2 = nn.Linear(10, 4, bias=False)
self.fc3 = nn.Linear(4, 4, bias=False)
self.relu = nn.ReLU()
def forward(self, x, use_fc3=True):
x = self.relu(se... | ReducerModule |
python | doocs__leetcode | solution/0900-0999/0940.Distinct Subsequences II/Solution3.py | {
"start": 0,
"end": 293
} | class ____:
def distinctSubseqII(self, s: str) -> int:
mod = 10**9 + 7
dp = [0] * 26
ans = 0
for c in s:
i = ord(c) - ord('a')
add = ans - dp[i] + 1
ans = (ans + add) % mod
dp[i] += add
return ans
| Solution |
python | numba__numba | numba/tests/test_dyn_func.py | {
"start": 574,
"end": 811
} | class ____(TestCase):
def test_issue_455(self):
inst = Issue455()
inst.create_f()
a = inst.call_f()
self.assertPreciseEqual(a, np.ones_like(a))
if __name__ == '__main__':
unittest.main()
| TestDynFunc |
python | django__django | tests/backends/test_ddl_references.py | {
"start": 9846,
"end": 13384
} | class ____(TransactionTestCase):
available_apps = []
def setUp(self):
compiler = Person.objects.all().query.get_compiler(connection.alias)
self.editor = connection.schema_editor()
self.expressions = Expressions(
table=Person._meta.db_table,
expressions=Expression... | ExpressionsTests |
python | django__django | tests/model_fields/models.py | {
"start": 4172,
"end": 4269
} | class ____(models.Model):
nbfield = models.BooleanField(null=True, blank=True)
| NullBooleanModel |
python | jazzband__django-simple-history | simple_history/tests/tests/utils.py | {
"start": 3554,
"end": 3662
} | class ____(Enum):
ADD = "add"
CHANGE = "change"
DELETE = "delete"
VIEW = "view"
| PermissionAction |
python | ray-project__ray | python/ray/_private/worker.py | {
"start": 9735,
"end": 10846
} | class ____(HasOptions, Generic[R, T0, T1, T2, T3, T4, T5, T6, T7, T8]):
def __init__(
self, function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7, T8], R]
) -> None:
pass
def remote(
self,
__arg0: "Union[T0, ObjectRef[T0]]",
__arg1: "Union[T1, ObjectRef[T1]]",
_... | RemoteFunction8 |
python | pytorch__pytorch | test/test_testing.py | {
"start": 17200,
"end": 18058
} | class ____(TestCase):
@classmethod
def setUpClass(cls):
# store something on the test class to query during teardown
cls.stored_thing = "called with " + cls.__name__
@classmethod
def tearDownClass(cls):
# throw here so we know teardown was run
raise RuntimeError(cls.stor... | TestFoo |
python | ansible__ansible | test/units/mock/loader.py | {
"start": 969,
"end": 3483
} | class ____(DataLoader):
def __init__(self, file_mapping=None):
file_mapping = {} if file_mapping is None else file_mapping
assert isinstance(file_mapping, dict)
super(DictDataLoader, self).__init__()
self._file_mapping = file_mapping
self._build_known_directories()
... | DictDataLoader |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_univariate.py | {
"start": 6823,
"end": 7730
} | class ____(Benchmark):
"""
Univariate Problem09 objective function.
This class defines the Univariate Problem09 global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\\text{Problem09}}(x) = \\sin(x) + \\sin \\left(\\frac{2}{3} x \\right)
... | Problem09 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramInference2.py | {
"start": 377,
"end": 608
} | class ____(Parent1[float]):
def method1(self, a, b):
reveal_type(self, expected_text="Self@Child1")
reveal_type(a, expected_text="float")
reveal_type(b, expected_text="list[float]")
return a
| Child1 |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 33471,
"end": 33668
} | class ____:
xlCellChangeApplied = 3 # from enum XlCellChangedState
xlCellChanged = 2 # from enum XlCellChangedState
xlCellNotChanged = 1 # from enum XlCellChangedState
| CellChangedState |
python | doocs__leetcode | lcci/16.01.Swap Numbers/Solution.py | {
"start": 0,
"end": 198
} | class ____:
def swapNumbers(self, numbers: List[int]) -> List[int]:
numbers[0] ^= numbers[1]
numbers[1] ^= numbers[0]
numbers[0] ^= numbers[1]
return numbers
| Solution |
python | pytest-dev__pytest-asyncio | docs/reference/markers/class_scoped_loop_strict_mode_example.py | {
"start": 73,
"end": 359
} | class ____:
loop: asyncio.AbstractEventLoop
async def test_remember_loop(self):
TestClassScopedLoop.loop = asyncio.get_running_loop()
async def test_this_runs_in_same_loop(self):
assert asyncio.get_running_loop() is TestClassScopedLoop.loop
| TestClassScopedLoop |
python | facelessuser__pymdown-extensions | pymdownx/progressbar.py | {
"start": 3691,
"end": 4066
} | class ____(AttrListTreeprocessor):
"""Used for AttrList compatibility."""
def run(self, elem):
"""Inline check for attributes at start of tail."""
if elem.tail:
m = self.INLINE_RE.match(elem.tail)
if m:
self.assign_attrs(elem, m.group(1))
... | ProgressBarTreeProcessor |
python | doocs__leetcode | solution/3400-3499/3412.Find Mirror Score of a String/Solution.py | {
"start": 0,
"end": 340
} | class ____:
def calculateScore(self, s: str) -> int:
d = defaultdict(list)
ans = 0
for i, x in enumerate(s):
y = chr(ord("a") + ord("z") - ord(x))
if d[y]:
j = d[y].pop()
ans += i - j
else:
d[x].append(i)
... | Solution |
python | ansible__ansible | test/units/plugins/lookup/test_password.py | {
"start": 15438,
"end": 16204
} | class ____(unittest.TestCase):
def setUp(self):
self.makedirs_safe = password.makedirs_safe
self.os_chmod = password.os.chmod
password.makedirs_safe = self.noop
password.os.chmod = self.noop
def noop(self, *args, **kwargs):
pass
def tearDown(self):
password.... | TestWritePasswordFile |
python | scikit-learn__scikit-learn | sklearn/feature_selection/_univariate_selection.py | {
"start": 24522,
"end": 28332
} | class ____(_BaseFilter):
"""Select features according to the k highest scores.
Read more in the :ref:`User Guide <univariate_feature_selection>`.
Parameters
----------
score_func : callable, default=f_classif
Function taking two arrays X and y, and returning a pair of arrays
(score... | SelectKBest |
python | encode__django-rest-framework | rest_framework/authtoken/models.py | {
"start": 1553,
"end": 1944
} | class ____(Token):
"""
Proxy mapping pk to user pk for use in admin.
"""
@property
def pk(self):
return self.user_id
class Meta:
proxy = 'rest_framework.authtoken' in settings.INSTALLED_APPS
abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS
ver... | TokenProxy |
python | encode__django-rest-framework | tests/test_validators.py | {
"start": 24530,
"end": 32082
} | class ____(TestCase):
def setUp(self):
self.instance = UniqueConstraintModel.objects.create(
race_name='example',
position=1,
global_id=1,
fancy_conditions=1
)
UniqueConstraintModel.objects.create(
race_name='example',
p... | TestUniqueConstraintValidation |
python | getsentry__sentry | src/sentry/integrations/github_enterprise/webhook.py | {
"start": 1916,
"end": 1999
} | class ____(Exception):
"""Webhook payload not found"""
| MissingWebhookPayloadError |
python | apache__airflow | dev/breeze/tests/test_ui_commands.py | {
"start": 9379,
"end": 10427
} | class ____:
def test_remove_extra_translations(self, tmp_path):
from airflow_breeze.commands.ui_commands import remove_extra_translations
de_dir = tmp_path / "de"
de_dir.mkdir()
de_data = {"greeting": "Hallo", "extra": "Extra Key"}
(de_dir / "test.json").write_text(json.dum... | TestRemoveExtraTranslations |
python | getsentry__sentry | src/sentry/seer/endpoints/group_autofix_setup_check.py | {
"start": 3598,
"end": 6383
} | class ____(GroupAiEndpoint):
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ML_AI
enforce_rate_limit = True
rate_limits = RateLimitConfig(
limit_overrides={
"GET": {
RateLimitCategory.IP: RateLimit(limit=200, window=60, concurr... | GroupAutofixSetupCheck |
python | google__jax | jax/_src/internal_test_util/test_harnesses.py | {
"start": 3243,
"end": 3402
} | class ____(NamedTuple):
"""Descriptor for a randomly generated argument.
See description of `Harness`.
"""
shape: tuple[int, ...]
dtype: DType
| RandArg |
python | scipy__scipy | scipy/integrate/_ivp/base.py | {
"start": 8770,
"end": 10004
} | class ____:
"""Base class for local interpolant over step made by an ODE solver.
It interpolates between `t_min` and `t_max` (see Attributes below).
Evaluation outside this interval is not forbidden, but the accuracy is not
guaranteed.
Attributes
----------
t_min, t_max : float
Tim... | DenseOutput |
python | ijl__orjson | test/test_numpy.py | {
"start": 35604,
"end": 35939
} | class ____:
def test_numpy_array_dimension_zero(self):
wrong_endianness = ">" if sys.byteorder == "little" else "<"
array = numpy.array([0, 1, 0.4, 5.7], dtype=f"{wrong_endianness}f8")
with pytest.raises(orjson.JSONEncodeError):
orjson.dumps(array, option=orjson.OPT_SERIALIZE_NUM... | NumpyEndianness |
python | mwaskom__seaborn | seaborn/_statistics.py | {
"start": 18598,
"end": 20817
} | class ____:
def __init__(self, estimator, errorbar=None, **boot_kws):
"""
Data aggregator that produces a weighted estimate and error bar interval.
Parameters
----------
estimator : string
Function (or method name) that maps a vector to a scalar. Currently
... | WeightedAggregator |
python | ethereum__web3.py | tests/integration/go_ethereum/test_goethereum_http.py | {
"start": 3483,
"end": 3904
} | class ____(GoEthereumTxPoolModuleTest):
pass
# -- async -- #
@pytest_asyncio.fixture
async def async_w3(start_geth_process_and_yield_port):
port = start_geth_process_and_yield_port
_w3 = AsyncWeb3(
AsyncHTTPProvider(
f"http://127.0.0.1:{port}", request_kwargs={"timeout": ClientTimeou... | TestGoEthereumTxPoolModuleTest |
python | psf__requests | src/requests/exceptions.py | {
"start": 3709,
"end": 3785
} | class ____(RequestException):
"""Custom retries logic failed"""
| RetryError |
python | astropy__astropy | astropy/units/tests/test_format.py | {
"start": 12861,
"end": 13157
} | class ____(RoundtripBase):
format_ = u_format.FITS
@pytest.mark.parametrize(
"unit",
[u for u in u_format.FITS._units.values() if not isinstance(u, PrefixUnit)],
ids=str,
)
def test_roundtrip(self, unit):
self.check_roundtrip(unit)
| TestRoundtripFITS |
python | tensorflow__tensorflow | tensorflow/python/ops/special_math_ops_test.py | {
"start": 8782,
"end": 10501
} | class ____(test.TestCase, parameterized.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_expint_boundary(self):
self.assertAllClose(-np.inf, special_math_ops.expint(0.))
self.assertTrue(np.isnan(self.evaluate(special_math_ops.expint(np.nan))))
# Check that the domain of definition is [0, inf... | ExpintTest |
python | scrapy__scrapy | tests/test_utils_deprecate.py | {
"start": 8782,
"end": 9875
} | class ____:
def test_old_path_gets_fixed(self):
with warnings.catch_warnings(record=True) as w:
output = update_classpath("scrapy.contrib.debug.Debug")
assert output == "scrapy.extensions.debug.Debug"
assert len(w) == 1
assert "scrapy.contrib.debug.Debug" in str(w[0].mess... | TestUpdateClassPath |
python | Textualize__textual | src/textual/dom.py | {
"start": 2617,
"end": 3326
} | class ____(Exception):
"""Exception raised if you supply a `id` attribute or class name in the wrong format."""
def check_identifiers(description: str, *names: str) -> None:
"""Validate identifier and raise an error if it fails.
Args:
description: Description of where identifier is used for error... | BadIdentifier |
python | jina-ai__jina | tests/integration/docarray_v2/test_streaming.py | {
"start": 405,
"end": 452
} | class ____(BaseDoc):
text: str
| OutputDocument |
python | numba__numba | numba/tests/test_unsafe_intrinsics.py | {
"start": 517,
"end": 2088
} | class ____(TestCase):
"""Tests for numba.unsafe.tuple
"""
def test_tuple_setitem(self):
@njit
def foo(tup, idxs, vals):
out_tup = tup
for i, v in zip(idxs, vals):
out_tup = tuple_setitem(out_tup, i, v)
return tup, out_tup
random.se... | TestTupleIntrinsic |
python | pypa__pip | src/pip/_vendor/rich/control.py | {
"start": 1537,
"end": 6484
} | class ____:
"""A renderable that inserts a control code (non printable but may move cursor).
Args:
*codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a
tuple of ControlType and an integer parameter
"""
__slots__ = ["segment"]
def __init_... | Control |
python | pytorch__pytorch | torch/distributed/elastic/multiprocessing/api.py | {
"start": 14347,
"end": 15102
} | class ____:
"""
Results of a completed run of processes started with ``start_processes()``. Returned by ``PContext``.
Note the following:
1. All fields are mapped by local rank
2. ``return_values`` - only populated for functions (not the binaries).
3. ``stdouts`` - path to stdout.log (empty st... | RunProcsResult |
python | ansible__ansible | test/units/module_utils/basic/test_dict_converters.py | {
"start": 309,
"end": 861
} | class ____(unittest.TestCase):
def test_module_utils_basic_json_dict_converters(self):
from ansible.module_utils.basic import json_dict_unicode_to_bytes, json_dict_bytes_to_unicode
test_data = dict(
item1=u"Fóo",
item2=[u"Bár", u"Bam"],
item3=dict(sub1=u"Súb"),
... | TestTextifyContainers |
python | walkccc__LeetCode | solutions/3559. Number of Ways to Assign Edge Weights II/3559.py | {
"start": 0,
"end": 1380
} | class ____:
def assignEdgeWeights(
self,
edges: list[list[int]],
queries: list[list[int]]
) -> list[int]:
MOD = 1_000_000_007
LOG = 17 # since 2^17 > 1e5
n = len(edges) + 1
ans = []
depth = [0] * (n + 1)
graph = [[] for _ in range(n + 1)]
parent = [[-1] * (n + 1) for _... | Solution |
python | pytorch__pytorch | test/test_nn.py | {
"start": 362828,
"end": 364660
} | class ____(nn.Module):
def __init__(self, pool, unpool):
super().__init__()
self.pool = pool
self.unpool = unpool
def forward(self, input):
return self.unpool(*self.pool(input))
add_test(NewModuleTest(
constructor=lambda: UnpoolingNet(
nn.MaxPool1d(2, return_indice... | UnpoolingNet |
python | google__jax | jax/_src/export/shape_poly.py | {
"start": 50064,
"end": 52498
} | class ____(effects.Effect):
__str__ = lambda _: "ShapeAssertionEffect"
shape_assertion_effect = ShapeAssertionEffect()
effects.lowerable_effects.add_type(ShapeAssertionEffect)
effects.control_flow_allowed_effects.add_type(ShapeAssertionEffect)
effects.remat_allowed_effects.add_type(ShapeAssertionEffect)
effects.cus... | ShapeAssertionEffect |
python | sqlalchemy__sqlalchemy | test/orm/test_lazy_relations.py | {
"start": 29823,
"end": 37576
} | class ____(_fixtures.FixtureTest):
"""test lazyloader on non-existent attribute returns
expected attribute symbols, maintain expected state"""
run_inserts = None
def _unhashable_fixture(self, metadata, load_on_pending=False):
class MyHashType(sa.TypeDecorator):
impl = sa.String(100... | GetterStateTest |
python | ApeWorX__ape | src/ape_ethereum/transactions.py | {
"start": 1591,
"end": 1888
} | class ____(Enum):
"""
Transaction enumerable type constants defined by
`EIP-2718 <https://eips.ethereum.org/EIPS/eip-2718>`__.
"""
STATIC = 0
ACCESS_LIST = 1 # EIP-2930
DYNAMIC = 2 # EIP-1559
SHARED_BLOB = 3 # EIP-4844
SET_CODE = 4 # EIP-7702
| TransactionType |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 58337,
"end": 58400
} | class ____(_TestNorm, _TestNormInt64Base):
pass
| TestNormInt64 |
python | docker__docker-py | docker/models/resource.py | {
"start": 1313,
"end": 2580
} | class ____:
"""
A base class for representing all objects of a particular type on the
server.
"""
#: The type of object this collection represents, set by subclasses
model = None
def __init__(self, client=None):
#: The client pointing at the server that this collection of objects
... | Collection |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_rich_string11.py | {
"start": 315,
"end": 1053
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("rich_string11.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got... | TestCompareXLSXFiles |
python | getsentry__sentry | src/sentry/issues/attributes.py | {
"start": 1215,
"end": 11479
} | class ____:
id: int
project_id: int
status: int
substatus: int | None
first_seen: datetime
num_comments: int
priority: int | None
first_release_id: int | None
def _get_attribute_snapshot_producer():
return get_arroyo_producer(
"sentry.issues.attributes",
Topic.GROUP... | GroupValues |
python | Netflix__metaflow | metaflow/plugins/secrets/secrets_decorator.py | {
"start": 456,
"end": 5000
} | class ____(StepDecorator):
"""
Specifies secrets to be retrieved and injected as environment variables prior to
the execution of a step.
Parameters
----------
sources : List[Union[str, Dict[str, Any]]], default: []
List of secret specs, defining how the secrets are to be retrieved
r... | SecretsDecorator |
python | getsentry__sentry | tests/sentry/uptime/subscriptions/test_tasks.py | {
"start": 2891,
"end": 4774
} | class ____(ConfigPusherTestMixin, metaclass=abc.ABCMeta):
__test__ = Abstract(__module__, __qualname__)
status_translations = {
UptimeSubscription.Status.CREATING: "create",
UptimeSubscription.Status.UPDATING: "update",
UptimeSubscription.Status.DELETING: "delete",
}
@pytest.fi... | BaseUptimeSubscriptionTaskTest |
python | pyqtgraph__pyqtgraph | pyqtgraph/Qt/internals.py | {
"start": 1931,
"end": 8373
} | class ____:
# Note: This class is an internal implementation detail and is not part
# of the public API.
#
# QPainter has a C++ native API that takes an array of objects:
# drawPrimitives(const Primitive *array, int count, ...)
# where "Primitive" is one of QPointF, QLineF, QRectF, Pixma... | PrimitiveArray |
python | numpy__numpy | numpy/ma/tests/test_core.py | {
"start": 212355,
"end": 224477
} | class ____:
# TODO: Test masked_object, masked_equal, ...
def test_masked_values(self):
res = masked_values(np.array([-32768.0]), np.int16(-32768))
assert_equal(res.mask, [True])
res = masked_values(np.inf, np.inf)
assert_equal(res.mask, True)
res = np.ma.masked_value... | TestMaskedWhereAliases |
python | doocs__leetcode | solution/3300-3399/3361.Shift Distance Between Two Strings/Solution.py | {
"start": 0,
"end": 600
} | class ____:
def shiftDistance(
self, s: str, t: str, nextCost: List[int], previousCost: List[int]
) -> int:
m = 26
s1 = [0] * (m << 1 | 1)
s2 = [0] * (m << 1 | 1)
for i in range(m << 1):
s1[i + 1] = s1[i] + nextCost[i % m]
s2[i + 1] = s2[i] + previ... | Solution |
python | ray-project__ray | python/ray/llm/_internal/batch/stages/http_request_stage.py | {
"start": 351,
"end": 6691
} | class ____(StatefulStageUDF):
RETRYABLE_STATUS_CODES = [429, 408, 504, 502, 503]
def __init__(
self,
data_column: str,
expected_input_keys: List[str],
url: str,
additional_header: Optional[Dict[str, Any]] = None,
qps: Optional[int] = None,
max_retries: in... | HttpRequestUDF |
python | pytorch__pytorch | torch/utils/file_baton.py | {
"start": 67,
"end": 2140
} | class ____:
"""A primitive, file-based synchronization utility."""
def __init__(self, lock_file_path, wait_seconds=0.1, warn_after_seconds=None) -> None:
"""
Create a new :class:`FileBaton`.
Args:
lock_file_path: The path to the file used for locking.
wait_secon... | FileBaton |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/hooks/databricks.py | {
"start": 6863,
"end": 8856
} | class ____:
"""Utility class for the SQL statement state concept of Databricks statements."""
SQL_STATEMENT_LIFE_CYCLE_STATES = [
"PENDING",
"RUNNING",
"SUCCEEDED",
"FAILED",
"CANCELED",
"CLOSED",
]
def __init__(
self, state: str = "", error_code... | SQLStatementState |
python | huggingface__transformers | src/transformers/pipelines/keypoint_matching.py | {
"start": 1076,
"end": 1981
} | class ____(TypedDict):
keypoint_image_0: Keypoint
keypoint_image_1: Keypoint
score: float
def validate_image_pairs(images: Any) -> Sequence[Sequence[ImagePair]]:
error_message = (
"Input images must be a one of the following :",
" - A pair of images.",
" - A list of pairs of im... | Match |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/input_manager.py | {
"start": 7485,
"end": 8868
} | class ____:
def __init__(
self,
config_schema: CoercableToConfigSchema = None,
description: Optional[str] = None,
version: Optional[str] = None,
input_config_schema: CoercableToConfigSchema = None,
required_resource_keys: Optional[AbstractSet[str]] = None,
):
... | _InputManagerDecoratorCallable |
python | getsentry__sentry | src/sentry/incidents/models/incident.py | {
"start": 10863,
"end": 12375
} | class ____(Model):
"""
An instance of an alert rule trigger (eg. each time the rule hits the trigger threshold, we create an incident trigger)
NOTE: dissimilar to an AlertRuleTrigger which represents the trigger threshold required to initialize an Incident
"""
__relocation_scope__ = RelocationScope... | IncidentTrigger |
python | pypa__pipenv | pipenv/exceptions.py | {
"start": 10568,
"end": 11017
} | class ____(PipenvException):
def __init__(self, message):
extra = [
"{} {}".format(
click.style("The operation failed...", bold=True, fg="red"),
click.style(
"A dependency conflict was detected and could not be resolved.",
f... | DependencyConflict |
python | allegroai__clearml | clearml/debugging/log.py | {
"start": 12358,
"end": 12473
} | class ____(logging.handlers.TimedRotatingFileHandler, ClearmlLoggerHandler):
pass
| ClearmlTimedRotatingFileHandler |
python | pypa__warehouse | warehouse/events/tags.py | {
"start": 53,
"end": 1262
} | class ____(str, enum.Enum):
"""Base class for Enum representing Event tags.
Tags can be broken into three colon-separated parts:
1. source type
2. subject type
3. action
For example, for event tag "project:role:add":
1. "project" is the source type
2. "role" is the subject type
3. ... | EventTagEnum |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/processors.py | {
"start": 18055,
"end": 18980
} | class ____(Processor):
"""
Insert text after the input.
:param text: This can be either plain text or formatted text
(or a callable that returns any of those).
:param style: style to be applied to this prompt/prefix.
"""
def __init__(self, text: AnyFormattedText, style: str = "") -> No... | AfterInput |
python | coleifer__peewee | tests/prefetch_tests.py | {
"start": 365,
"end": 470
} | class ____(TestModel):
person = ForeignKeyField(Person, backref='notes')
content = TextField()
| Note |
python | keras-team__keras | keras/src/utils/text_dataset_utils_test.py | {
"start": 188,
"end": 14332
} | class ____(testing.TestCase):
def _prepare_directory(
self, num_classes=2, nested_dirs=False, count=16, length=20
):
# Get a unique temp directory
temp_dir = self.get_temp_dir()
# Generate paths to class subdirectories
paths = []
for class_index in range(num_clas... | TextDatasetFromDirectoryTest |
python | scipy__scipy | scipy/signal/tests/test_upfirdn.py | {
"start": 4879,
"end": 13011
} | class ____:
@skip_xp_backends(np_only=True, reason="enough to only test on numpy")
def test_valid_input(self, xp):
assert_raises(ValueError, upfirdn, [1], [1], 1, 0) # up or down < 1
assert_raises(ValueError, upfirdn, [], [1], 1, 1) # h.ndim != 1
assert_raises(ValueError, upfirdn, [[1... | TestUpfirdn |
python | doocs__leetcode | solution/1800-1899/1874.Minimize Product Sum of Two Arrays/Solution.py | {
"start": 0,
"end": 198
} | class ____:
def minProductSum(self, nums1: List[int], nums2: List[int]) -> int:
nums1.sort()
nums2.sort(reverse=True)
return sum(x * y for x, y in zip(nums1, nums2))
| Solution |
python | django__django | django/utils/connection.py | {
"start": 888,
"end": 2554
} | class ____:
settings_name = None
exception_class = ConnectionDoesNotExist
thread_critical = False
def __init__(self, settings=None):
self._settings = settings
self._connections = Local(self.thread_critical)
@cached_property
def settings(self):
self._settings = self.conf... | BaseConnectionHandler |
python | matplotlib__matplotlib | lib/mpl_toolkits/mplot3d/art3d.py | {
"start": 39160,
"end": 58574
} | class ____(PolyCollection):
"""
A collection of 3D polygons.
.. note::
**Filling of 3D polygons**
There is no simple definition of the enclosed surface of a 3D polygon
unless the polygon is planar.
In practice, Matplotlib fills the 2D projection of the polygon. This
... | Poly3DCollection |
python | wandb__wandb | wandb/automations/_filters/operators.py | {
"start": 3443,
"end": 3555
} | class ____(BaseVariadicLogicalOp):
exprs: TupleOf[Union[FilterExpr, Op]] = Field(default=(), alias="$and")
| And |
python | modin-project__modin | modin/core/storage_formats/pandas/parsers.py | {
"start": 13873,
"end": 14808
} | class ____(PandasParser):
@staticmethod
@doc(_doc_parse_func, parameters=_doc_parse_parameters_common2)
def parse(fname, common_read_kwargs, **kwargs):
return PandasParser.generic_parse(
fname,
callback=PandasFWFParser.read_callback,
**common_read_kwargs,
... | PandasFWFParser |
python | numpy__numpy | numpy/random/tests/test_random.py | {
"start": 3808,
"end": 5767
} | class ____:
def _create_rng(self):
seed = 1234567890
prng = random.RandomState(seed)
state = prng.get_state()
return prng, state
def test_basic(self):
prng, state = self._create_rng()
old = prng.tomaxint(16)
prng.set_state(state)
new = prng.tomaxi... | TestSetState |
python | getsentry__sentry | tests/sentry/api/serializers/test_fields.py | {
"start": 1620,
"end": 3910
} | class ____(TestCase):
def test_simple(self) -> None:
data = {"actor_field": f"user:{self.user.id}"}
serializer = DummySerializer(data=data, context={"organization": self.organization})
assert serializer.is_valid()
assert serializer.validated_data["actor_field"].is_user
asse... | TestActorField |
python | lepture__authlib | authlib/integrations/base_client/errors.py | {
"start": 53,
"end": 117
} | class ____(AuthlibBaseError):
error = "oauth_error"
| OAuthError |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-netsuite/source_netsuite/source.py | {
"start": 583,
"end": 7583
} | class ____(AbstractSource):
logger: logging.Logger = logging.getLogger("airbyte")
def auth(self, config: Mapping[str, Any]) -> OAuth1:
# the `realm` param should be in format of: 12345_SB1
realm = config["realm"].replace("-", "_").upper()
return OAuth1(
client_key=config["co... | SourceNetsuite |
python | pennersr__django-allauth | allauth/socialaccount/providers/snapchat/constants.py | {
"start": 27,
"end": 263
} | class ____:
EXTERNAL_ID = "https://auth.snapchat.com/oauth2/api/user.external_id"
DISPLAY_NAME = "https://auth.snapchat.com/oauth2/api/user.display_name"
BITMOJI = "https://auth.snapchat.com/oauth2/api/user.bitmoji.avatar"
| Scope |
python | openai__openai-python | src/openai/resources/fine_tuning/checkpoints/permissions.py | {
"start": 15281,
"end": 15738
} | class ____:
def __init__(self, permissions: Permissions) -> None:
self._permissions = permissions
self.create = _legacy_response.to_raw_response_wrapper(
permissions.create,
)
self.retrieve = _legacy_response.to_raw_response_wrapper(
permissions.retrieve,
... | PermissionsWithRawResponse |
python | numpy__numpy | numpy/matrixlib/tests/test_matrix_linalg.py | {
"start": 1236,
"end": 1298
} | class ____(SolveCases, MatrixTestCase):
pass
| TestSolveMatrix |
python | ApeWorX__ape | src/ape/managers/query.py | {
"start": 3763,
"end": 7648
} | class ____(ManagerAccessMixin):
"""
A singleton that manages query engines and performs queries.
Args:
query (``QueryType``): query to execute
Usage example::
biggest_block_size = chain.blocks.query("size").max()
"""
@cached_property
def engines(self) -> dict[str, QueryA... | QueryManager |
python | encode__django-rest-framework | rest_framework/relations.py | {
"start": 8205,
"end": 9356
} | class ____(RelatedField):
default_error_messages = {
'required': _('This field is required.'),
'does_not_exist': _('Invalid pk "{pk_value}" - object does not exist.'),
'incorrect_type': _('Incorrect type. Expected pk value, received {data_type}.'),
}
def __init__(self, **kwargs):
... | PrimaryKeyRelatedField |
python | psf__black | tests/data/cases/preview_long_strings__regression.py | {
"start": 4647,
"end": 5447
} | class ____:
def foo():
some_func_call(
(
"xx {xxxxxxxxxxx}/xxxxxxxxxxx.xxx xxxx.xxx && xxxxxx -x "
"xxxx, ('xxxxxxx xxxxxx xxxx, xxxx') xxxxxx_xxxxx xxxxxx xxxx; "
"xxxx.xxxx_xxxxxx(['xxxx.xxx'], xxxx.xxxxxxx().xxxxxxxxxx)\" "
),
... | A |
python | PrefectHQ__prefect | src/prefect/server/events/counting.py | {
"start": 995,
"end": 7147
} | class ____(AutoEnum):
week = AutoEnum.auto()
day = AutoEnum.auto()
hour = AutoEnum.auto()
minute = AutoEnum.auto()
second = AutoEnum.auto()
def as_timedelta(self, interval: float) -> Duration:
if self == self.week:
return Duration(days=7 * interval)
elif self == self... | TimeUnit |
python | PrefectHQ__prefect | src/prefect/server/schemas/core.py | {
"start": 32548,
"end": 32903
} | class ____(ORMBaseModel):
"""An ORM representation of saved search data. Represents a set of filter criteria."""
name: str = Field(default=..., description="The name of the saved search.")
filters: list[SavedSearchFilter] = Field(
default_factory=lambda: [],
description="The filter set for ... | SavedSearch |
python | pypa__pipenv | pipenv/patched/pip/_internal/cli/index_command.py | {
"start": 1479,
"end": 4700
} | class ____(CommandContextMixIn):
"""
A class mixin for command classes needing _build_session().
"""
def __init__(self) -> None:
super().__init__()
self._session: Optional[PipSession] = None
@classmethod
def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
... | SessionCommandMixin |
python | sqlalchemy__sqlalchemy | test/orm/test_naturalpks.py | {
"start": 21366,
"end": 22482
} | class ____(_fixtures.FixtureTest):
run_inserts = None
__sparse_driver_backend__ = True
def test_transient_exception(self):
"""An object that goes from a pk value to transient/pending
doesn't count as a "pk" switch.
"""
users, Address, addresses, User = (
self.t... | TransientExceptionTesst |
python | getsentry__sentry | src/sentry/conf/types/kafka_definition.py | {
"start": 253,
"end": 5261
} | class ____(Enum):
"""
These are the default topic names used by Sentry. They must match
the registered values in sentry-kafka-schemas.
"""
EVENTS = "events"
EVENTS_COMMIT_LOG = "snuba-commit-log"
TRANSACTIONS = "transactions"
TRANSACTIONS_COMMIT_LOG = "snuba-transactions-commit-log"
... | Topic |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 39710,
"end": 39877
} | class ____(panel_grid_major_x, panel_grid_major_y):
"""
Major grid lines
Parameters
----------
theme_element : element_line
"""
| panel_grid_major |
python | sympy__sympy | sympy/core/function.py | {
"start": 8464,
"end": 11775
} | class ____(Basic, metaclass=FunctionClass):
"""
Base class for applied functions.
Explanation
===========
Instances of Application represent the result of applying an application of
any type to any object.
"""
is_Function = True
@cacheit
def __new__(cls, *args, **options):
... | Application |
python | cython__cython | Cython/Compiler/CodeGeneration.py | {
"start": 72,
"end": 1068
} | class ____(VisitorTransform):
"""
Finds nodes in a pxd file that should generate code, and
returns them in a StatListNode.
The result is a tuple (StatListNode, ModuleScope), i.e.
everything that is needed from the pxd after it is processed.
A purer approach would be to separately compile the p... | ExtractPxdCode |
python | huggingface__transformers | src/transformers/models/patchtsmixer/modeling_patchtsmixer.py | {
"start": 56666,
"end": 57139
} | class ____(ModelOutput):
r"""
sequences (`torch.FloatTensor` of shape `(batch_size, num_samples, prediction_length, number_channels)`):
Sampled values from the chosen distribution.
"""
sequences: Optional[torch.FloatTensor] = None
@dataclass
@auto_docstring(
custom_intro="""
Base clas... | SamplePatchTSMixerPredictionOutput |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.