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 | django__django | tests/admin_inlines/models.py | {
"start": 8316,
"end": 8608
} | class ____(models.Model):
name = models.CharField(max_length=1)
position = models.PositiveIntegerField(help_text="Position help_text.")
parent = models.ForeignKey(SomeParentModel, models.CASCADE)
readonly_field = models.CharField(max_length=1)
# Models for #30231
| SomeChildModel |
python | numpy__numpy | numpy/_core/tests/test_numerictypes.py | {
"start": 18565,
"end": 19049
} | class ____:
def test_longdouble(self):
assert_(np._core.sctypeDict['float64'] is not np.longdouble)
assert_(np._core.sctypeDict['complex128'] is not np.clongdouble)
def test_ulong(self):
assert np._core.sctypeDict['ulong'] is np.ulong
assert np.dtype(np.ulong) is np.dtype("ulong... | TestSctypeDict |
python | PyCQA__pyflakes | pyflakes/checker.py | {
"start": 17164,
"end": 20101
} | class ____:
names = dir()
# Globally defined names which are not attributes of the builtins module, or
# are only present on some platforms.
_MAGIC_GLOBALS = ['__file__', '__builtins__', '__annotations__', 'WindowsError']
def getNodeName(node):
# Returns node.id, or node.name, or None
if hasattr(node, '... | DetectClassScopedMagic |
python | pytorch__pytorch | test/export/test_sparse.py | {
"start": 1599,
"end": 1715
} | class ____(torch.nn.Module):
def forward(self, x):
return [xi.to_sparse() for xi in x]
| SparseActivationCOO |
python | sympy__sympy | sympy/physics/quantum/spin.py | {
"start": 6905,
"end": 8129
} | class ____(SpinOpBase, Operator):
"""The J- operator."""
_coord = '-'
basis = 'Jz'
def _apply_operator_JzKet(self, ket, **options):
j = ket.j
m = ket.m
if m.is_Number and j.is_Number:
if m <= -j:
return S.Zero
return hbar*sqrt(j*(j + S.One) ... | JminusOp |
python | pypa__pip | src/pip/_vendor/truststore/_windows.py | {
"start": 1260,
"end": 1845
} | class ____(Structure):
_fields_ = (
("cbSize", DWORD),
("RequestedUsage", CERT_USAGE_MATCH),
("RequestedIssuancePolicy", CERT_USAGE_MATCH),
("dwUrlRetrievalTimeout", DWORD),
("fCheckRevocationFreshnessTime", BOOL),
("dwRevocationFreshnessTime", DWORD),
("pftCa... | CERT_CHAIN_PARA |
python | anthropics__anthropic-sdk-python | src/anthropic/types/message_tokens_count.py | {
"start": 155,
"end": 329
} | class ____(BaseModel):
input_tokens: int
"""
The total number of tokens across the provided list of messages, system prompt,
and tools.
"""
| MessageTokensCount |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/__init__.py | {
"start": 2617,
"end": 3510
} | class ____:
def __new__(cls, *new_args, **new_kwargs):
"""__new__(cls, d, e=1) -> DocstringSig
First line of docstring
rest of docstring
"""
def __init__(self, *init_args, **init_kwargs):
"""__init__(self, a, b=1) -> None
First line of docstring
rest of... | DocstringSig |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 3626,
"end": 3699
} | class ____(BaseModel):
text: str
type: str = "summary_text"
| Summary |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_bar12.py | {
"start": 315,
"end": 1380
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_bar12.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_f... | TestCompareXLSXFiles |
python | openai__openai-python | src/openai/_utils/_logs.py | {
"start": 895,
"end": 1351
} | class ____(logging.Filter):
@override
def filter(self, record: logging.LogRecord) -> bool:
if is_dict(record.args) and "headers" in record.args and is_dict(record.args["headers"]):
headers = record.args["headers"] = {**record.args["headers"]}
for header in headers:
... | SensitiveHeadersFilter |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/scoped_css.py | {
"start": 113,
"end": 454
} | class ____(Widget):
DEFAULT_CSS = """
MyWidget {
height: auto;
border: magenta;
}
Label {
border: solid green;
}
"""
def compose(self) -> ComposeResult:
yield Label("foo")
yield Label("bar")
def on_mount(self) -> None:
self.log(self.app.s... | MyWidget |
python | cython__cython | Cython/Compiler/MatchCaseNodes.py | {
"start": 9666,
"end": 12178
} | class ____(PatternNode):
"""
alternatives list of PatternNodes
"""
child_attrs = PatternNode.child_attrs + ["alternatives"]
def get_first_irrefutable(self):
for alternative in self.alternatives:
if alternative.is_irrefutable():
return alternative
retur... | OrPatternNode |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/path_registry.py | {
"start": 11473,
"end": 12502
} | class ____(_CreatesToken):
"""Root registry, defers to mappers so that
paths are maintained per-root-mapper.
"""
__slots__ = ()
inherit_cache = True
path = natural_path = ()
has_entity = False
is_aliased_class = False
is_root = True
is_unnatural = False
def _getitem(
... | RootRegistry |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/tasks.py | {
"start": 16865,
"end": 19949
} | class ____(GoogleCloudBaseOperator):
"""
Deletes a queue from Cloud Tasks, even if it has tasks in it.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudTasksQueueDeleteOperator`
:param location: The location name in whic... | CloudTasksQueueDeleteOperator |
python | encode__django-rest-framework | tests/test_relations_hyperlink.py | {
"start": 2128,
"end": 2441
} | class ____(serializers.HyperlinkedModelSerializer):
class Meta:
model = OneToOneTarget
fields = ('url', 'name', 'nullable_source')
# TODO: Add test that .data cannot be accessed prior to .is_valid
@override_settings(ROOT_URLCONF='tests.test_relations_hyperlink')
| NullableOneToOneTargetSerializer |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 214,
"end": 1334
} | class ____:
params = [
[
# from_dtype == to_dtype
("Float64", "Float64"),
("float64[pyarrow]", "float64[pyarrow]"),
# from non-EA to EA
("float64", "Float64"),
("float64", "float64[pyarrow]"),
# from EA to non-EA
... | AsType |
python | celery__celery | t/unit/worker/test_heartbeat.py | {
"start": 488,
"end": 798
} | class ____:
def call_repeatedly(self, secs, fun, args=(), kwargs={}):
class entry(tuple):
canceled = False
def cancel(self):
self.canceled = True
return entry((secs, fun, args, kwargs))
def cancel(self, entry):
entry.cancel()
| MockTimer |
python | dagster-io__dagster | python_modules/libraries/dagster-fivetran/dagster_fivetran/ops.py | {
"start": 421,
"end": 4124
} | class ____(Config):
connector_id: str = Field(
description=(
"The Fivetran Connector ID that this op will sync. You can retrieve this "
'value from the "Setup" tab of a given connector in the Fivetran UI.'
),
)
poll_interval: float = Field(
default=DEFAULT_POL... | SyncConfig |
python | pyparsing__pyparsing | tests/test_unit.py | {
"start": 394240,
"end": 394851
} | class ____(Test02_WithoutPackrat):
"""
rerun Test2 tests, now with unbounded left recursion cache
"""
def setUp(self):
ParserElement.enable_left_recursion(force=True)
def tearDown(self):
default_suite_context.restore()
def test000_assert_packrat_status(self):
print("Le... | Test09_WithLeftRecursionParsing |
python | kamyu104__LeetCode-Solutions | Python/check-if-two-expression-trees-are-equivalent.py | {
"start": 1560,
"end": 2571
} | class ____(object):
def checkEquivalence(self, root1, root2):
"""
:type root1: Node
:type root2: Node
:rtype: bool
"""
def add_counter(counter, prev, d, val):
if val.isalpha():
counter[ord(val)-ord('a')] += d if prev[0] == '+' else -d
... | Solution2 |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_object_position06.py | {
"start": 315,
"end": 935
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("object_position06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with image(s)."""
workbook =... | TestCompareXLSXFiles |
python | ionelmc__pytest-benchmark | src/pytest_benchmark/csv.py | {
"start": 88,
"end": 1564
} | class ____:
def __init__(self, columns, sort, logger):
self.columns = columns
self.sort = sort
self.logger = logger
def render(self, output_file, groups):
output_file = Path(output_file)
output_file.parent.mkdir(exist_ok=True, parents=True)
if not output_file.su... | CSVResults |
python | pytorch__pytorch | test/inductor/test_codecache.py | {
"start": 67448,
"end": 87604
} | class ____(TestCase):
def setUp(self):
super().setUp()
counters.clear()
PatchCaches.setUp()
CacheArtifactManager.clear()
def tearDown(self):
super().tearDown()
PatchCaches.tearDown()
def reset(self):
AOTAutogradCache.clear()
PyCodeCache.cache... | TestStandaloneCompile |
python | apache__airflow | airflow-core/src/airflow/exceptions.py | {
"start": 2760,
"end": 2864
} | class ____(AirflowException):
"""Raise when name of the stats is invalid."""
| InvalidStatsNameException |
python | gevent__gevent | src/gevent/pywsgi.py | {
"start": 53298,
"end": 56446
} | class ____(object):
"""
An adapter for :class:`logging.Logger` instances
to let them be used with :class:`WSGIServer`.
.. warning:: Unless the entire process is monkey-patched at a very
early part of the lifecycle (before logging is configured),
loggers are likely to not be gevent-coope... | LoggingLogAdapter |
python | run-llama__llama_index | llama-index-core/llama_index/core/schema.py | {
"start": 22105,
"end": 25818
} | class ____(BaseNode):
"""
Provided for backward compatibility.
Note: we keep the field with the typo "seperator" to maintain backward compatibility for
serialized objects.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Make TextNode forward-compatible with Node by suppor... | TextNode |
python | huggingface__transformers | utils/modular_model_converter.py | {
"start": 24709,
"end": 35283
} | class ____(CSTVisitor, ABC):
"""An abstract visitor class which analyses a module, creating a mapping of dependencies for classes, functions and assignments.
Class dependencies are computed with `compute_class_dependencies()`, while function and assignment dependencies are stored in
`self.object_recursive_d... | ModuleMapper |
python | keras-team__keras | keras/src/backend/torch/trainer.py | {
"start": 570,
"end": 17859
} | class ____(base_trainer.Trainer):
def __init__(self):
super().__init__()
self.train_function = None
self.test_function = None
self.predict_function = None
def _should_torch_compile(self):
# require torch>=2.1.0 to enable dynamo since it
# includes many improvemen... | TorchTrainer |
python | PyCQA__pylint | tests/functional/u/unsubscriptable_value.py | {
"start": 2158,
"end": 2405
} | class ____:
def __init__(self):
self.ala = {i for i in range(10)}
self.bala = [i for i in range(10)]
self.portocala = None
def test_unsubscriptable(self):
self.bala[0]
self.portocala[0]
| AbstractClass |
python | wandb__wandb | wandb/sdk/internal/tb_watcher.py | {
"start": 12513,
"end": 16652
} | class ____:
"""Consume tfevents from a priority queue.
There should always only be one of these per run_manager. We wait for 10 seconds of
queued events to reduce the chance of multiple tfevent files triggering out of order
steps.
"""
def __init__(
self,
tbwatcher: TBWatcher,
... | TBEventConsumer |
python | jazzband__prettytable | tests/test_prettytable.py | {
"start": 37774,
"end": 40506
} | class ____:
def test_csv_output(self, helper_table: PrettyTable) -> None:
assert helper_table.get_csv_string(delimiter="\t", header=False) == (
"1\tvalue 1\tvalue2\tvalue3\r\n"
"4\tvalue 4\tvalue5\tvalue6\r\n"
"7\tvalue 7\tvalue8\tvalue9\r\n"
)
assert help... | TestCsvOutput |
python | chroma-core__chroma | chromadb/test/property/test_filtering.py | {
"start": 5318,
"end": 28351
} | class ____(WhereExpr):
"""
Wraps old-style where/where_document dicts for testing.
Converts where_document to use #document field and combines with where using $and.
"""
def __init__(self, where: Optional[Where] = None, where_document: Optional[WhereDocument] = None):
self.where = where
... | LegacyWhereWrapper |
python | wandb__wandb | wandb/vendor/pygments/lexers/jvm.py | {
"start": 812,
"end": 3724
} | class ____(RegexLexer):
"""
For `Java <http://www.sun.com/java/>`_ source code.
"""
name = 'Java'
aliases = ['java']
filenames = ['*.java']
mimetypes = ['text/x-java']
flags = re.MULTILINE | re.DOTALL | re.UNICODE
tokens = {
'root': [
(r'[^\S\n]+', Text),
... | JavaLexer |
python | django__django | tests/auth_tests/test_tokens.py | {
"start": 569,
"end": 7569
} | class ____(TestCase):
def test_make_token(self):
user = User.objects.create_user("tokentestuser", "test2@example.com", "testpw")
p0 = PasswordResetTokenGenerator()
tk1 = p0.make_token(user)
self.assertIs(p0.check_token(user, tk1), True)
def test_10265(self):
"""
... | TokenGeneratorTest |
python | python__mypy | mypyc/irbuild/classdef.py | {
"start": 7287,
"end": 7968
} | class ____:
"""Create IR for a class definition.
This is an abstract base class.
"""
def __init__(self, builder: IRBuilder, cdef: ClassDef) -> None:
self.builder = builder
self.cdef = cdef
self.attrs_to_cache: list[tuple[Lvalue, RType]] = []
@abstractmethod
def add_met... | ClassBuilder |
python | sympy__sympy | sympy/functions/combinatorial/numbers.py | {
"start": 61428,
"end": 62840
} | class ____(DefinedFunction):
r"""
Returns the Legendre symbol `(a / p)`.
For an integer ``a`` and an odd prime ``p``, the Legendre symbol is
defined as
.. math ::
\genfrac(){}{}{a}{p} = \begin{cases}
0 & \text{if } p \text{ divides } a\\
1 & \text{if } a \text{ is... | legendre_symbol |
python | PyCQA__pylint | tests/functional/s/stop_iteration_inside_generator.py | {
"start": 3116,
"end": 4505
} | class ____:
def next(self):
return iter([1, 2, 3])
def some_gen(self):
for value in self.next():
yield value
SomeClassWithNext().some_gen()
def something_invalid():
raise Exception("cannot iterate this")
def invalid_object_passed_to_next():
yield next(something_invalid... | SomeClassWithNext |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/MatplotlibWidget.py | {
"start": 281,
"end": 2210
} | class ____(QtWidgets.QWidget):
"""
Implements a Matplotlib figure inside a QWidget.
Use getFigure() and redraw() to interact with matplotlib.
Example::
mw = MatplotlibWidget()
subplot = mw.getFigure().add_subplot(111)
subplot.plot(x,y)
mw.draw()
"""
parent_defa... | MatplotlibWidget |
python | walkccc__LeetCode | solutions/1915. Number of Wonderful Substrings/1915.py | {
"start": 0,
"end": 484
} | class ____:
def wonderfulSubstrings(self, word: str) -> int:
ans = 0
prefix = 0 # the binary prefix
count = [0] * 1024 # the binary prefix count
count[0] = 1 # the empty string ""
for c in word:
prefix ^= 1 << ord(c) - ord('a')
# All the letters occur even number of times.
an... | Solution |
python | pytorch__pytorch | test/torch_np/numpy_tests/core/test_multiarray.py | {
"start": 240464,
"end": 242913
} | class ____(TestCase):
# all these tests use the WRITEBACKIFCOPY mechanism
def test_argmax_with_out(self):
mat = np.eye(5)
out = np.empty(5, dtype="i2")
res = np.argmax(mat, 0, out=out)
assert_equal(res, range(5))
def test_argmin_with_out(self):
mat = -np.eye(5)
... | TestWritebackIfCopy |
python | pallets__werkzeug | examples/cupoftee/application.py | {
"start": 2182,
"end": 3643
} | class ____:
def __init__(self, database, interval=120):
self.jinja_env = Environment(loader=PackageLoader("cupoftee"), autoescape=True)
self.interval = interval
self.db = Database(database)
self.server_browser = ServerBrowser(self)
self.updater = Thread(None, self.update_serv... | Cup |
python | coleifer__peewee | tests/models.py | {
"start": 155536,
"end": 158278
} | class ____(ModelTestCase):
requires = [CFile, CNote]
def setUp(self):
super(TestCompoundSelectModels, self).setUp()
def generate_ts():
i = [0]
def _inner():
i[0] += 1
return datetime.datetime(2018, 1, i[0])
return _inner
... | TestCompoundSelectModels |
python | Textualize__textual | tests/toggles/test_radioset.py | {
"start": 5677,
"end": 6980
} | class ____(App[None]):
def compose(self) -> ComposeResult:
self.selected = []
with RadioSet():
yield RadioButton("0", disabled=True)
yield RadioButton("1")
yield RadioButton("2", disabled=True)
yield RadioButton("3", disabled=True)
yield Ra... | RadioSetDisabledButtonsApp |
python | ZoranPandovski__al-go-rithms | data_structures/B+tree/btree.py | {
"start": 26,
"end": 708
} | class ____():
def __init__(self, lf):
self.keys = []
self.children = []
self.next = None
self.leaf = lf
def kaatde(self):
mid = len(self.keys) // 2
mval = self.keys[mid]
nw_node = Node(self.leaf)
nw_node.keys = self.keys[mid:] if self.leaf... | Node |
python | pytorch__pytorch | test/torch_np/test_reductions.py | {
"start": 16730,
"end": 18139
} | class ____(TestCase):
"""Run a set of generic tests to verify that cumsum/cumprod are sane."""
@parametrize("func", [np.cumsum, np.cumprod])
def test_bad_axis(self, func):
# Basic check of functionality
m = np.array([[0, 1, 7, 0, 0], [3, 0, 0, 2, 19]])
assert_raises(TypeError, func... | TestGenericCumSumProd |
python | django__django | tests/migrations/test_optimizer.py | {
"start": 281,
"end": 52246
} | class ____(OptimizerTestBase):
"""
Tests the migration optimizer.
"""
def test_none_app_label(self):
optimizer = MigrationOptimizer()
with self.assertRaisesMessage(TypeError, "app_label must be a str"):
optimizer.optimize([], None)
def test_single(self):
"""
... | OptimizerTests |
python | apache__airflow | providers/apache/kafka/src/airflow/providers/apache/kafka/hooks/produce.py | {
"start": 929,
"end": 1550
} | class ____(KafkaBaseHook):
"""
A hook for creating a Kafka Producer.
:param kafka_config_id: The connection object to use, defaults to "kafka_default"
"""
def __init__(self, kafka_config_id=KafkaBaseHook.default_conn_name) -> None:
super().__init__(kafka_config_id=kafka_config_id)
def... | KafkaProducerHook |
python | ansible__ansible | .azure-pipelines/scripts/publish-codecov.py | {
"start": 657,
"end": 4702
} | class ____:
dry_run: bool
path: pathlib.Path
def parse_args() -> Args:
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--dry-run', action='store_true')
parser.add_argument('path', type=pathlib.Path)
args = parser.parse_args()
# Store arguments in a typed dataclass
field... | Args |
python | facebook__pyre-check | client/commands/profile.py | {
"start": 1511,
"end": 2011
} | class ____(Event):
duration: int
def add_phase_duration_to_result(self, result: Dict[str, int]) -> None:
tags = self.metadata.tags
if PHASE_NAME in tags:
phase_name = tags[PHASE_NAME]
result[phase_name] = self.duration
if TRIGGERED_DEPENDENCIES in tags:
... | DurationEvent |
python | run-llama__llama_index | llama-index-core/llama_index/core/query_engine/graph_query_engine.py | {
"start": 568,
"end": 4827
} | class ____(BaseQueryEngine):
"""
Composable graph query engine.
This query engine can operate over a ComposableGraph.
It can take in custom query engines for its sub-indices.
Args:
graph (ComposableGraph): A ComposableGraph object.
custom_query_engines (Optional[Dict[str, BaseQuery... | ComposableGraphQueryEngine |
python | coleifer__peewee | peewee.py | {
"start": 160061,
"end": 160237
} | class ____(Field):
field_type = 'INT'
def adapt(self, value):
try:
return int(value)
except ValueError:
return value
| IntegerField |
python | tensorflow__tensorflow | tensorflow/python/distribute/tpu_replicated_variable_test.py | {
"start": 1269,
"end": 6090
} | class ____(test.TestCase, parameterized.TestCase):
@combinations.generate(combinations.combine(mode=['graph', 'eager']))
def test_tpu_replicated_variable_simple(self):
v0 = variables_lib.Variable([0], name='v0')
v1 = variables_lib.Variable([0], name='v1')
r = tpu_replicated_variable.TPUReplicatedVariab... | TPUReplicatedVariableTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol17.py | {
"start": 657,
"end": 817
} | class ____(Protocol[_T1, _T2, _T3]):
def m1(self, p0: _T1, p1: _T2, p2: _T3) -> _T1: ...
def m2(self) -> _T1: ...
def m3(self) -> _T2: ...
| Protocol2 |
python | openai__openai-python | src/openai/types/beta/realtime/session_update_event_param.py | {
"start": 916,
"end": 1080
} | class ____(TypedDict, total=False):
expires_after: SessionClientSecretExpiresAfter
"""Configuration for the ephemeral token expiration."""
| SessionClientSecret |
python | kamyu104__LeetCode-Solutions | Python/sum-of-subarray-minimums.py | {
"start": 75,
"end": 787
} | class ____(object):
def sumSubarrayMins(self, A):
"""
:type A: List[int]
:rtype: int
"""
M = 10**9 + 7
left, s1 = [0]*len(A), []
for i in xrange(len(A)):
count = 1
while s1 and s1[-1][0] > A[i]:
count += s1.pop()[1]
... | Solution |
python | ansible__ansible | lib/ansible/_internal/_errors/_captured.py | {
"start": 4075,
"end": 4384
} | class ____(AnsibleResultCapturedError):
"""An exception representing error detail captured in a module context and returned from an action's result dictionary."""
_default_message = 'Module failed.'
context = 'target'
@dataclasses.dataclass(**_messages._dataclass_kwargs)
| AnsibleModuleCapturedError |
python | numba__numba | numba/tests/test_parfors.py | {
"start": 47048,
"end": 81359
} | class ____(TestParforsBase):
""" Tests cpython, reduction and various parfors features"""
def test_arraymap(self):
def test_impl(a, x, y):
return a * x + y
self.check_variants(test_impl, lambda: self.gen_linspace_variants(3))
def test_0d_broadcast(self):
def test_impl(... | TestParfors |
python | django__django | tests/update/models.py | {
"start": 123,
"end": 357
} | class ____(models.Model):
name = models.CharField(max_length=20)
value = models.CharField(max_length=20)
another_value = models.CharField(max_length=20, blank=True)
is_active = models.BooleanField(default=True)
| DataPoint |
python | MongoEngine__mongoengine | mongoengine/fields.py | {
"start": 38500,
"end": 39000
} | class ____(DictField):
"""A field that maps a name to a specified field type. Similar to
a DictField, except the 'value' of each item must match the specified
field type.
"""
def __init__(self, field=None, *args, **kwargs):
# XXX ValidationError raised outside the "validate" method.
... | MapField |
python | scipy__scipy | scipy/linalg/tests/test_decomp_lu.py | {
"start": 11321,
"end": 12629
} | class ____:
def setup_method(self):
self.rng = np.random.default_rng(1682281250228846)
def test_lu(self):
a0 = self.rng.random((10, 10))
b = self.rng.random((10,))
for order in ['C', 'F']:
a = np.array(a0, order=order)
x1 = solve(a, b)
lu_a =... | TestLUSolve |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-azurepostgresql/llama_index/vector_stores/azure_postgres/common/_shared.py | {
"start": 1547,
"end": 4431
} | class ____(BaseModel):
"""Base connection information for Azure Database for PostgreSQL connections.
:param application_name: Name of the application connecting to the database.
:type application_name: str
:param host: Hostname of the Azure Database for PostgreSQL server.
:type host: str | None
... | BaseConnectionInfo |
python | numba__numba | numba/core/typing/collections.py | {
"start": 839,
"end": 1111
} | class ____(AbstractTemplate):
key = operator.truth
def generic(self, args, kws):
assert not kws
(val,) = args
if isinstance(val, (types.Sequence)):
return signature(types.boolean, val)
@infer_global(operator.getitem)
| SequenceBool |
python | pypa__pipenv | pipenv/patched/pip/_internal/operations/freeze.py | {
"start": 832,
"end": 8919
} | class ____(NamedTuple):
requirement: str
comments: List[str]
def freeze(
requirement: Optional[List[str]] = None,
local_only: bool = False,
user_only: bool = False,
paths: Optional[List[str]] = None,
isolated: bool = False,
exclude_editable: bool = False,
skip: Container[str] = (),... | _EditableInfo |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-stripe/unit_tests/integration/test_cards.py | {
"start": 3477,
"end": 9128
} | class ____(TestCase):
@HttpMocker()
def test_given_one_page_when_read_then_return_records(self, http_mocker: HttpMocker) -> None:
http_mocker.get(
_cards_request().with_created_gte(_A_START_DATE).with_created_lte(_NOW).with_limit(100).build(),
_cards_response().with_record(_a_car... | FullRefreshTest |
python | matplotlib__matplotlib | lib/matplotlib/scale.py | {
"start": 11927,
"end": 12318
} | class ____(Transform):
input_dims = output_dims = 1
def __init__(self, base):
super().__init__()
self.base = base
def __str__(self):
return f"{type(self).__name__}(base={self.base})"
def transform_non_affine(self, values):
return np.power(self.base, values)
def in... | InvertedLogTransform |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/self1.py | {
"start": 770,
"end": 2251
} | class ____:
x: Self
def method1(self) -> Self:
return self
def method2(self, a: Self) -> None:
x: Self = a
y = Self
def method3(self: Self) -> Self:
# This should generate an error because Self doesn't accept a type arg.
y: Self[int]
return self
# ... | B |
python | readthedocs__readthedocs.org | readthedocs/profiles/views.py | {
"start": 2572,
"end": 2650
} | class ____(SettingsOverrideObject):
_default_class = LoginViewBase
| LoginView |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_textbox18.py | {
"start": 315,
"end": 1579
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("textbox18.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with textbox(s)."""
workbook = Workb... | TestCompareXLSXFiles |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_snippets.py | {
"start": 15460,
"end": 15565
} | class ____:
def __fspath__(self):
return os.path.join(BASE, '_snippets')
| _PathLikeExampleObject |
python | wandb__wandb | wandb/vendor/pygments/lexers/d.py | {
"start": 418,
"end": 6980
} | class ____(RegexLexer):
"""
For D source.
.. versionadded:: 1.2
"""
name = 'D'
filenames = ['*.d', '*.di']
aliases = ['d']
mimetypes = ['text/x-dsrc']
tokens = {
'root': [
(r'\n', Text),
(r'\s+', Text),
# (r'\\\n', Text), # line continuat... | DLexer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 5219,
"end": 5384
} | class ____(ArgumentError):
"""Raised when a dynamically-loaded module (usually a database dialect)
of a particular name cannot be located."""
| NoSuchModuleError |
python | mlflow__mlflow | mlflow/telemetry/events.py | {
"start": 8317,
"end": 8384
} | class ____(Event):
name: str = "ai_command_run"
| AiCommandRunEvent |
python | skorch-dev__skorch | skorch/probabilistic.py | {
"start": 19020,
"end": 25074
} | class ____(_GPRegressorPredictMixin, GPBase):
# pylint: disable=missing-docstring
__doc__ = get_exact_gp_regr_doc(NeuralNet.__doc__)
def __init__(
self,
module,
*args,
likelihood=gpytorch.likelihoods.GaussianLikelihood,
criterion=gpytorch.mlls.Exa... | ExactGPRegressor |
python | sqlalchemy__sqlalchemy | test/orm/test_cascade.py | {
"start": 27094,
"end": 29789
} | class ____(fixtures.MappedTest):
run_inserts = None
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(30... | O2OSingleParentNoFlushTest |
python | doocs__leetcode | solution/1800-1899/1866.Number of Ways to Rearrange Sticks With K Sticks Visible/Solution2.py | {
"start": 0,
"end": 290
} | class ____:
def rearrangeSticks(self, n: int, k: int) -> int:
mod = 10**9 + 7
f = [1] + [0] * k
for i in range(1, n + 1):
for j in range(k, 0, -1):
f[j] = (f[j] * (i - 1) + f[j - 1]) % mod
f[0] = 0
return f[k]
| Solution |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_api_key_index.py | {
"start": 120,
"end": 1027
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-api-key-index"
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
def test_org_admin_can_access(self) -> None:
self.get_success_response(self.organization.slug)
def test_member_no_access(self) -> Non... | OrganizationApiKeyIndex |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 137545,
"end": 140351
} | class ____:
def test_fancy_assign_ndarray(self):
np.random.seed(1234)
D = self.asdense(np.random.rand(5, 7))
S = self.spcreator(D)
X = np.random.rand(2, 3)
I = np.array([[1, 2, 3], [3, 4, 2]])
J = np.array([[5, 6, 3], [2, 3, 1]])
with check_remains_sorted(S... | _TestFancyMultidimAssign |
python | doocs__leetcode | solution/0900-0999/0993.Cousins in Binary Tree/Solution.py | {
"start": 192,
"end": 851
} | class ____:
def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
q = deque([(root, None)])
depth = 0
p1 = p2 = None
d1 = d2 = None
while q:
for _ in range(len(q)):
node, parent = q.popleft()
if node.val == x:
... | Solution |
python | gevent__gevent | src/gevent/tests/test__server_pywsgi.py | {
"start": 2718,
"end": 2826
} | class ____(test__server.TestRawSpawn): # pylint:disable=too-many-ancestors
Settings = Settings
| TestRawSpawn |
python | huggingface__transformers | src/transformers/models/xmod/modeling_xmod.py | {
"start": 1937,
"end": 7914
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.token_type_embeddings = nn... | XmodEmbeddings |
python | python-pillow__Pillow | src/PIL/Image.py | {
"start": 3560,
"end": 3713
} | class ____(IntEnum):
AFFINE = 0
EXTENT = 1
PERSPECTIVE = 2
QUAD = 3
MESH = 4
# resampling filters (also defined in Imaging.h)
| Transform |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_eks.py | {
"start": 1359,
"end": 2015
} | class ____:
def setup_method(self):
self.async_conn_patcher = patch("airflow.providers.amazon.aws.hooks.eks.EksHook.get_async_conn")
self.mock_async_conn = self.async_conn_patcher.start()
self.mock_client = AsyncMock()
self.mock_async_conn.return_value.__aenter__.return_value = self... | TestEksTrigger |
python | wireservice__csvkit | csvkit/convert/fixed.py | {
"start": 4092,
"end": 5739
} | class ____:
"""
Extracts column, start, and length columns from schema rows. Once
instantiated, each time the instance is called with a row, a
``(column,start,length)`` tuple will be returned based on values in that
row and the constructor kwargs.
"""
REQUIRED_COLUMNS = [('column', None), ('... | SchemaDecoder |
python | OmkarPathak__pygorithm | tests/test_binary.py | {
"start": 3553,
"end": 5558
} | class ____(unittest.TestCase):
def test_ascii_to_base16(self):
array = ['54', '68', '65', '20', '51', '75', '69', '63', '6B', '20', '42', '72', '6F', '77', '6E', '20', '46',
'6F', '78', '20', '4A', '75', '6D', '70', '73', '20', '4F', '76', '65', '72', '20', '74', '68', '65',
... | TestASCII |
python | walkccc__LeetCode | solutions/1839. Longest Substring Of All Vowels in Order/1839.py | {
"start": 0,
"end": 377
} | class ____:
def longestBeautifulSubstring(self, word: str) -> int:
ans = 0
count = 1
l = 0
for r in range(1, len(word)):
curr = word[r]
prev = word[r - 1]
if curr >= prev:
if curr > prev:
count += 1
if count == 5:
ans = max(ans, r - l + 1)
e... | Solution |
python | ApeWorX__ape | src/ape/utils/_github.py | {
"start": 1876,
"end": 9873
} | class ____:
# Generic git/github client attributes.
TOKEN_KEY = "GITHUB_ACCESS_TOKEN"
API_URL_PREFIX = "https://api.github.com"
git: GitProcessWrapper = GitProcessWrapper()
# ApeWorX-specific attributes.
ORGANIZATION_NAME = "ApeWorX"
FRAMEWORK_NAME = "ape"
_repo_cache: dict[str, dict] =... | _GithubClient |
python | google__jax | jax/_src/pallas/core.py | {
"start": 3784,
"end": 3962
} | class ____(AbstractSemaphoreTy):
name = "barrier_semaphore"
type = barrier_semaphore
Backend = Literal["mosaic_tpu", "triton", "mosaic_gpu"]
@runtime_checkable
| BarrierSemaphore |
python | neetcode-gh__leetcode | python/0020-valid-parentheses.py | {
"start": 0,
"end": 375
} | class ____:
def isValid(self, s: str) -> bool:
bracketMap = {")": "(", "]": "[", "}": "{"}
stack = []
for c in s:
if c not in bracketMap:
stack.append(c)
continue
if not stack or stack[-1] != bracketMap[c]:
return False... | Solution |
python | getsentry__sentry | tests/sentry/workflow_engine/processors/test_delayed_workflow.py | {
"start": 38036,
"end": 38615
} | class ____(TestDelayedWorkflowBase):
def test_cleanup_redis(self) -> None:
self._push_base_events()
project_client = self.batch_client.for_project(self.project.id)
data = project_client.get_hash_data(batch_key=None)
assert set(data.keys()) == self.workflow_group_dcg_mapping
... | TestCleanupRedisBuffer |
python | viewflow__viewflow | viewflow/jsonstore.py | {
"start": 5733,
"end": 6045
} | class ____(JSONFieldMixin, fields.DateField):
def to_json(self, value):
if value:
assert isinstance(value, (datetime, date))
return value.strftime("%Y-%m-%d")
def from_json(self, value):
if value is not None:
return dateparse.parse_date(value)
| DateField |
python | allegroai__clearml | clearml/automation/optimization.py | {
"start": 9580,
"end": 11290
} | class ____(object):
class Field(object):
def __init__(self, limit: Optional[float] = None) -> ():
self.limit = limit
self.current = {}
def update(self, uid: Union[str, int], value: float) -> ():
if value is not None:
try:
self.... | Budget |
python | tornadoweb__tornado | tornado/test/simple_httpclient_test.py | {
"start": 3270,
"end": 3775
} | class ____(RequestHandler):
def get(self):
if self.request.version.startswith("HTTP/1"):
# Emulate the old HTTP/1.0 behavior of returning a body with no
# content-length. Tornado handles content-length at the framework
# level so we have to go around it.
stre... | NoContentLengthHandler |
python | pennersr__django-allauth | allauth/socialaccount/providers/github/views.py | {
"start": 285,
"end": 1918
} | class ____(OAuth2Adapter):
provider_id = "github"
settings = app_settings.PROVIDERS.get(provider_id, {})
if "GITHUB_URL" in settings:
web_url = settings.get("GITHUB_URL").rstrip("/")
api_url = "{0}/api/v3".format(web_url)
else:
web_url = "https://github.com"
api_url = "h... | GitHubOAuth2Adapter |
python | redis__redis-py | redis/asyncio/connection.py | {
"start": 31812,
"end": 34809
} | class ____:
__slots__ = (
"keyfile",
"certfile",
"cert_reqs",
"include_verify_flags",
"exclude_verify_flags",
"ca_certs",
"ca_data",
"context",
"check_hostname",
"min_version",
"ciphers",
)
def __init__(
self,
... | RedisSSLContext |
python | langchain-ai__langchain | libs/partners/openai/tests/integration_tests/chat_models/test_responses_api.py | {
"start": 7279,
"end": 7321
} | class ____(BaseModel):
response: str
| Foo |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict21.py | {
"start": 202,
"end": 248
} | class ____(TypedDict):
v1: Required[int]
| TD1 |
python | wandb__wandb | wandb/sdk/artifacts/_generated/update_artifact.py | {
"start": 221,
"end": 299
} | class ____(GQLResult):
result: Optional[UpdateArtifactResult]
| UpdateArtifact |
python | google__python-fire | fire/test_components.py | {
"start": 2846,
"end": 3020
} | class ____:
def identity(self, bool_one=False, bool_two=False):
return bool_one, bool_two
def identity2(self, a=None, alpha=None):
return a, alpha
| SimilarArgNames |
python | great-expectations__great_expectations | docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/test_expect_column_values_to_be_in_set.py | {
"start": 476,
"end": 5985
} | class ____(gxe.ExpectColumnValuesToBeInSet):
value_set: List[str] = ["FR", "DE", "CH", "ES", "IT", "BE", "NL", "PL"]
# </snippet>
@pytest.mark.big
def test_expect_column_values_to_be_in_set_fail(
data_context_with_datasource_pandas_engine,
):
context: AbstractDataContext = data_context_with_datasource_pan... | ExpectColumnValuesToBeTwoLetterCountryCode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.