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 | apache__airflow | providers/amazon/tests/unit/amazon/aws/sensors/test_ecs.py | {
"start": 8630,
"end": 11738
} | class ____(EcsBaseTestCase):
@pytest.mark.parametrize(
("return_state", "expected"),
[
("PROVISIONING", False),
("PENDING", False),
("ACTIVATING", False),
("RUNNING", True),
("DEACTIVATING", False),
("STOPPING", False),
... | TestEcsTaskStateSensor |
python | sympy__sympy | sympy/vector/implicitregion.py | {
"start": 614,
"end": 16158
} | class ____(Basic):
"""
Represents an implicit region in space.
Examples
========
>>> from sympy import Eq
>>> from sympy.abc import x, y, z, t
>>> from sympy.vector import ImplicitRegion
>>> ImplicitRegion((x, y), x**2 + y**2 - 4)
ImplicitRegion((x, y), x**2 + y**2 - 4)
>>> Im... | ImplicitRegion |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/openblas/package.py | {
"start": 217,
"end": 1021
} | class ____(Package):
"""OpenBLAS: An optimized BLAS library"""
homepage = "http://www.openblas.net"
url = "http://github.com/xianyi/OpenBLAS/archive/v0.2.15.tar.gz"
version("0.2.16", md5="b1190f3d3471685f17cfd1ec1d252ac9")
version("0.2.15", md5="b1190f3d3471685f17cfd1ec1d252ac9")
version("0.2.... | Openblas |
python | astropy__astropy | astropy/io/ascii/core.py | {
"start": 57210,
"end": 66609
} | class ____(DefaultSplitter):
def process_line(self, line: str) -> str:
"""Replace tab with space within ``line`` while respecting quoted substrings."""
newline = []
in_quote = False
lastchar = None
for char in line:
if char == self.quotechar and (
... | WhitespaceSplitter |
python | sqlalchemy__sqlalchemy | test/orm/test_core_compilation.py | {
"start": 64420,
"end": 64503
} | class ____(_poly_fixtures._Polymorphic):
run_setup_mappers = "once"
| InheritedTest |
python | joke2k__faker | faker/providers/company/tl_PH/__init__.py | {
"start": 49,
"end": 154
} | class ____(FilPhProvider):
"""No difference from Company Provider for fil_PH locale"""
pass
| Provider |
python | apache__thrift | test/py/TestServer.py | {
"start": 5845,
"end": 6101
} | class ____(object):
def secondtestString(self, argument):
return "testString(\"" + argument + "\")"
# LAST_SEQID is a global because we have one transport and multiple protocols
# running on it (when multiplexed)
LAST_SEQID = None
| SecondHandler |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_kansas_zip.py | {
"start": 1735,
"end": 4062
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Kansas zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
... | ExpectColumnValuesToBeValidKansasZip |
python | paramiko__paramiko | paramiko/sftp_si.py | {
"start": 948,
"end": 12544
} | class ____:
"""
This class defines an interface for controlling the behavior of paramiko
when using the `.SFTPServer` subsystem to provide an SFTP server.
Methods on this class are called from the SFTP session's thread, so you can
block as long as necessary without affecting other sessions (even ot... | SFTPServerInterface |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_contextlib.py | {
"start": 42535,
"end": 46034
} | class ____(ExceptionIsLikeMixin, __TestCase):
@support.requires_docstrings
def test_instance_docs(self):
# Issue 19330: ensure context manager instances have good docstrings
cm_docstring = suppress.__doc__
obj = suppress()
self.assertEqual(obj.__doc__, cm_docstring)
def tes... | TestSuppress |
python | pypa__packaging | tests/test_tags.py | {
"start": 56932,
"end": 66343
} | class ____:
def teardown_method(self) -> None:
# Clear the version cache
tags._glibc_version = [] # type: ignore[attr-defined]
@pytest.mark.parametrize(
("name", "expected"),
[("CPython", "cp"), ("PyPy", "pp"), ("Jython", "jy"), ("IronPython", "ip")],
)
def test_interpr... | TestSysTags |
python | huggingface__transformers | tests/utils/test_core_model_loading.py | {
"start": 7183,
"end": 7313
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.down_proj = DummyParamModule((2, 2))
| DummyMLP |
python | django__django | tests/admin_changelist/models.py | {
"start": 1934,
"end": 2086
} | class ____(models.Model):
name = models.CharField(max_length=30)
members = models.ManyToManyField(ChordsMusician, through="Invitation")
| ChordsBand |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/events/__init__.py | {
"start": 66834,
"end": 67005
} | class ____:
asset_key: AssetKey
previous_health_state: AssetHealthStatus
new_health_state: AssetHealthStatus
@whitelist_for_serdes
@record
| AssetHealthChangedData |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/controls.py | {
"start": 1633,
"end": 3779
} | class ____(metaclass=ABCMeta):
"""
Base class for all user interface controls.
"""
def reset(self) -> None:
# Default reset. (Doesn't have to be implemented.)
pass
def preferred_width(self, max_available_width: int) -> int | None:
return None
def preferred_height(
... | UIControl |
python | sympy__sympy | sympy/matrices/dense.py | {
"start": 903,
"end": 3616
} | class ____(RepMatrix):
"""Matrix implementation based on DomainMatrix as the internal representation"""
#
# DenseMatrix is a superclass for both MutableDenseMatrix and
# ImmutableDenseMatrix. Methods shared by both classes but not for the
# Sparse classes should be implemented here.
#
is_M... | DenseMatrix |
python | python-markdown__markdown | tests/test_syntax/extensions/test_abbr.py | {
"start": 886,
"end": 14722
} | class ____(TestCase):
maxDiff = None
default_kwargs = {'extensions': ['abbr']}
def test_ignore_atomic(self):
self.assertMarkdownRenders(
self.dedent(
"""
This <https://example.com/{YAFR}>
*[YAFR]: Yet Another Feature Request
... | TestAbbr |
python | mlflow__mlflow | tests/genai/judges/test_judge_base.py | {
"start": 260,
"end": 3523
} | class ____(Judge):
def __init__(self, name: str, custom_instructions: str | None = None, **kwargs):
super().__init__(name=name, **kwargs)
self._custom_instructions = custom_instructions
@property
def instructions(self) -> str:
if self._custom_instructions:
return self._c... | MockJudgeImplementation |
python | google__jax | jax/_src/lax/lax.py | {
"start": 369190,
"end": 373344
} | class ____:
allow_conversion: bool = True
@staticmethod
def physical_element_aval(dtype) -> core.ShapedArray:
return core.ShapedArray((), np.dtype('int32'))
@staticmethod
def result_handler(sticky_device, aval):
def handler(_, buf):
buf.aval = core.ShapedArray(buf.shape, buf.dtype)
retur... | BIntRules |
python | doocs__leetcode | solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.py | {
"start": 192,
"end": 733
} | class ____:
def closestValue(self, root: Optional[TreeNode], target: float) -> int:
def dfs(node: Optional[TreeNode]):
if node is None:
return
nxt = abs(target - node.val)
nonlocal ans, diff
if nxt < diff or (nxt == diff and node.val < ans):
... | Solution |
python | mozilla__bleach | tests_website/server.py | {
"start": 210,
"end": 1157
} | class ____(http.server.SimpleHTTPRequestHandler):
# Prevent 'cannot bind to address' errors on restart
allow_reuse_address = True
def do_POST(self):
content_len = int(self.headers.get("content-length", 0))
body = self.rfile.read(content_len)
print("read {} bytes: {}".format(content_... | BleachCleanHandler |
python | run-llama__llama_index | llama-index-core/llama_index/core/schema.py | {
"start": 14687,
"end": 19328
} | class ____(BaseModel):
"""
A container class for media content.
This class represents a generic media resource that can be stored and accessed
in multiple ways - as raw bytes, on the filesystem, or via URL. It also supports
storing vector embeddings for the media content.
Attributes:
e... | MediaResource |
python | pytorch__pytorch | torch/utils/benchmark/utils/_stubs.py | {
"start": 645,
"end": 1026
} | class ____(Protocol):
"""Replicates the valgrind endpoints in `torch._C`.
These bindings are used to collect Callgrind profiles on earlier versions
of PyTorch and will eventually be removed.
"""
__file__: str
__name__: str
def _valgrind_supported_platform(self) -> bool:
...
de... | CallgrindModuleType |
python | doocs__leetcode | solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.py | {
"start": 0,
"end": 358
} | class ____:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
rides.sort(key=lambda x: x[1])
f = [0] * (len(rides) + 1)
for i, (st, ed, tip) in enumerate(rides, 1):
j = bisect_left(rides, st + 1, hi=i, key=lambda x: x[1])
f[i] = max(f[i - 1], f[j] + ed... | Solution |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 20984,
"end": 21084
} | class ____(OpcodeWithArg):
_FLAGS = HAS_ARGUMENT | HAS_CONST | NO_NEXT
__slots__ = ()
| RETURN_CONST |
python | pandas-dev__pandas | pandas/tests/test_algos.py | {
"start": 67406,
"end": 69625
} | class ____:
@pytest.mark.parametrize(
"arr",
[
[np.nan, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 3, np.nan],
[4.0, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 4.0, np.nan],
],
)
def test_scipy_compat(self, arr):
sp_stats = pytest.importorskip("scipy.stats")
... | TestRank |
python | PyCQA__pylint | tests/functional/s/super/super_checks.py | {
"start": 3461,
"end": 3636
} | class ____:
"""type(self) may lead to recursion loop in derived classes"""
def __init__(self):
super(type(self), self).__init__() # [bad-super-call]
| SuperWithType |
python | ray-project__ray | rllib/examples/envs/classes/multi_agent/footsies/utils.py | {
"start": 748,
"end": 805
} | class ____:
p1: str
p2: str
prob: float
| Matchup |
python | pandas-dev__pandas | asv_bench/benchmarks/inference.py | {
"start": 8346,
"end": 8662
} | class ____:
def setup(self):
ints = np.random.randint(0, 60, size=10000)
self.arr = [f"{i} days" for i in ints]
self.arr[-1] = "apple"
def time_convert(self):
to_timedelta(self.arr, errors="coerce")
from .pandas_vb_common import setup # noqa: F401 isort:skip
| ToTimedeltaErrors |
python | pytorch__pytorch | torch/_dynamo/bytecode_transformation.py | {
"start": 1190,
"end": 1991
} | class ____:
start: "Instruction"
end: "Instruction"
target: "Instruction"
depth: int
lasti: bool
def __repr__(self) -> str:
return (
f"InstructionExnTabEntry(start={self.start.short_inst_repr()}, "
f"end={self.end.short_inst_repr()}, "
f"target={self.... | InstructionExnTabEntry |
python | django__django | tests/flatpages_tests/test_views.py | {
"start": 2462,
"end": 5199
} | class ____(TestDataMixin, TestCase):
def test_view_flatpage(self):
"A flatpage can be served through a view"
response = self.client.get("/flatpage_root/flatpage/")
self.assertContains(response, "<p>Isn't it flat!</p>")
def test_view_non_existent_flatpage(self):
"""A nonexistent ... | FlatpageViewTests |
python | pydantic__pydantic | pydantic-core/tests/serializers/test_any.py | {
"start": 13297,
"end": 14931
} | class ____:
def __repr__(self):
return '<Foobar repr>'
def test_unknown_type(any_serializer: SchemaSerializer):
f = Foobar()
assert any_serializer.to_python(f) == f
with pytest.raises(PydanticSerializationError, match="Unable to serialize unknown type: <class '.+Foobar'>"):
any_serial... | Foobar |
python | gevent__gevent | src/gevent/testing/testcase.py | {
"start": 1651,
"end": 3505
} | class ____(object):
@flaky.reraises_flaky_timeout()
def assertTimeoutAlmostEqual(self, first, second, places=None, msg=None, delta=None):
try:
self.assertAlmostEqual(first, second, places=places, msg=msg, delta=delta)
except AssertionError:
flaky.reraiseFlakyTestTimeout()... | TimeAssertMixin |
python | spyder-ide__spyder | external-deps/spyder-kernels/spyder_kernels/comms/commbase.py | {
"start": 2323,
"end": 2921
} | class ____(RuntimeError):
pass
def stacksummary_to_json(stack):
"""StackSummary to json."""
return [
{
"filename": frame.filename,
"lineno": frame.lineno,
"name": frame.name,
"line": frame.line
}
for frame in stack
]
def stacksu... | CommError |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py | {
"start": 2959,
"end": 7113
} | class ____:
CUSTOMIZE_JOB_ARN = "valid_arn"
CUSTOMIZE_JOB_NAME = "testModelJob"
@pytest.fixture
def mock_conn(self) -> Generator[BaseAwsConnection, None, None]:
with mock.patch.object(BedrockHook, "conn") as _conn:
_conn.create_model_customization_job.return_value = {
... | TestBedrockCustomizeModelOperator |
python | pytorch__pytorch | torch/nn/modules/pooling.py | {
"start": 30710,
"end": 35677
} | class ____(_AvgPoolNd):
r"""Applies a 3D average pooling over an input signal composed of several input planes.
In the simplest case, the output value of the layer with input size :math:`(N, C, D, H, W)`,
output :math:`(N, C, D_{out}, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kD, kH, kW)`
can ... | AvgPool3d |
python | pydantic__pydantic | tests/test_main.py | {
"start": 101157,
"end": 109339
} | class ____(BaseModel):
x: int
help_result_string = pydoc.render_doc(Model)
"""
)
assert 'class Model' in module.help_result_string
def test_cannot_use_leading_underscore_field_names():
with pytest.raises(
NameError, match="Fields must not use names with leading underscores; e.g., use 'x' ins... | Model |
python | vyperlang__vyper | vyper/compiler/output_bundle.py | {
"start": 6787,
"end": 9051
} | class ____(OutputBundleWriter):
def __init__(self, compiler_data):
super().__init__(compiler_data)
self._output = {"language": "Vyper", "sources": {}, "settings": {"outputSelection": {}}}
def write_sources(self, sources: dict[str, CompilerInput]):
out = {}
for path, c in source... | SolcJSONWriter |
python | spack__spack | lib/spack/spack/detection/path.py | {
"start": 8821,
"end": 14435
} | class ____:
"""Inspects the file-system looking for packages. Guesses places where to look using PATH."""
def default_path_hints(self) -> List[str]:
return []
def search_patterns(self, *, pkg: Type["spack.package_base.PackageBase"]) -> List[str]:
"""Returns the list of patterns used to mat... | Finder |
python | bokeh__bokeh | src/bokeh/models/axes.py | {
"start": 8636,
"end": 9100
} | class ____(ContinuousAxis):
''' An axis that picks nice numbers for tick locations on a
linear scale. Configured with a ``BasicTickFormatter`` by default.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwa... | LinearAxis |
python | ray-project__ray | python/ray/_private/utils.py | {
"start": 50966,
"end": 58445
} | class ____(contextlib.AbstractContextManager):
"""Context manager that defers SIGINT signals until the context is left."""
# This is used by Ray's task cancellation to defer cancellation interrupts during
# problematic areas, e.g. task argument deserialization.
def __init__(self):
# Whether a S... | DeferSigint |
python | django__django | tests/sessions_tests/tests.py | {
"start": 33593,
"end": 36866
} | class ____(SessionTestsMixin, SimpleTestCase):
backend = FileSession
def setUp(self):
# Do file session tests in an isolated directory, and kill it after
# we're done.
self.original_session_file_path = settings.SESSION_FILE_PATH
self.temp_session_store = settings.SESSION_FILE_PA... | FileSessionTests |
python | ipython__ipython | IPython/core/display.py | {
"start": 12783,
"end": 13414
} | class ____(DisplayObject):
"""Create a text display object given raw data.
Parameters
----------
data : str or unicode
The raw data or a URL or file to load the data from.
url : unicode
A URL to download the data from.
filename : unicode
Path to a local file to load the ... | TextDisplayObject |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/typing/__init__.py | {
"start": 4830,
"end": 4922
} | class ____(TypedDict):
kind: Literal["list"]
inner: DataTypeHeader
| _ListDataTypeHeader |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-mcp/tests/schemas.py | {
"start": 237,
"end": 283
} | class ____(BaseModel):
lst: List[int]
| TestList |
python | miyuchina__mistletoe | test/test_span_token.py | {
"start": 6151,
"end": 6833
} | class ____(unittest.TestCase):
def test_attribute(self):
token = span_token.RawText('some text')
self.assertEqual(token.content, 'some text')
def test_no_children(self):
token = span_token.RawText('some text')
self.assertIsNone(token.children)
def test_valid_html_entities(s... | TestRawText |
python | huggingface__transformers | src/transformers/models/paligemma/configuration_paligemma.py | {
"start": 886,
"end": 5679
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`PaliGemmaForConditionalGeneration`]. It is used to instantiate an
PaliGemmamodel according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults wil... | PaliGemmaConfig |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType24.py | {
"start": 206,
"end": 285
} | class ____(Iterable[T]):
def __iter__(self) -> Iterator[T]: ...
| IterableProxy |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 209549,
"end": 218115
} | class ____(fixtures.TablesTest):
__only_on__ = ("postgresql >= 9.3",)
__backend__ = True
data_type = JSON
@classmethod
def define_tables(cls, metadata):
Table(
"data_table",
metadata,
Column("id", Integer, primary_key=True),
Column("name", St... | JSONRoundTripTest |
python | scikit-learn__scikit-learn | sklearn/metrics/_plot/precision_recall_curve.py | {
"start": 386,
"end": 20526
} | class ____(_BinaryClassifierCurveDisplayMixin):
"""Precision Recall visualization.
It is recommended to use
:func:`~sklearn.metrics.PrecisionRecallDisplay.from_estimator` or
:func:`~sklearn.metrics.PrecisionRecallDisplay.from_predictions` to create
a :class:`~sklearn.metrics.PrecisionRecallDisplay`... | PrecisionRecallDisplay |
python | getsentry__sentry | src/sentry/preprod/size_analysis/models.py | {
"start": 1012,
"end": 1141
} | class ____(str, Enum):
ADDED = "added"
REMOVED = "removed"
INCREASED = "increased"
DECREASED = "decreased"
| DiffType |
python | ApeWorX__ape | src/ape/cli/commands.py | {
"start": 2144,
"end": 5433
} | class ____(click.Command):
"""
A command that uses the :meth:`~ape.cli.options.network_option`.
It will automatically set the network for the duration of the command execution.
"""
def __init__(self, *args, **kwargs):
self._use_cls_types = kwargs.pop("use_cls_types", True)
self._net... | ConnectedProviderCommand |
python | kamyu104__LeetCode-Solutions | Python/string-compression-iii.py | {
"start": 38,
"end": 442
} | class ____(object):
def compressedString(self, word):
"""
:type word: str
:rtype: str
"""
result = []
cnt = 0
for i in xrange(len(word)):
cnt += 1
if cnt == 9 or (i+1 == len(word) or word[i+1] != word[i]):
result.append(... | Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/schema.py | {
"start": 30763,
"end": 32455
} | class ____(BaseComponent):
node: SerializeAsAny[BaseNode]
score: Optional[float] = None
def __str__(self) -> str:
score_str = "None" if self.score is None else f"{self.score: 0.3f}"
return f"{self.node}\nScore: {score_str}\n"
def get_score(self, raise_error: bool = False) -> float:
... | NodeWithScore |
python | pytorch__pytorch | torch/utils/data/_utils/worker.py | {
"start": 4822,
"end": 14260
} | class ____:
seed: int | None = None
# The function `_generate_state` is adapted from `numpy.random.SeedSequence`
# from https://github.com/numpy/numpy/blob/main/numpy/random/bit_generator.pyx
# It's MIT licensed, here is the copyright:
# Copyright (c) 2015 Melissa E. O'Neill
# Copyright (c) 2019 NumPy Developers... | _ResumeIteration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 39737,
"end": 40186
} | class ____(sgqlc.types.Enum):
"""Represents the different GitHub Enterprise Importer (GEI)
migration sources.
Enumeration Choices:
* `AZURE_DEVOPS`: An Azure DevOps migration source.
* `BITBUCKET_SERVER`: A Bitbucket Server migration source.
* `GITHUB_ARCHIVE`: A GitHub Migration API source.
... | MigrationSourceType |
python | dagster-io__dagster | examples/project_analytics/dagster_pypi/resources.py | {
"start": 2151,
"end": 2284
} | class ____(ConfigurableResource):
def get_github_stars(self, _) -> pd.DataFrame:
raise NotImplementedError()
| GithubResource |
python | automl__auto-sklearn | test/test_pipeline/components/classification/test_liblinear.py | {
"start": 165,
"end": 837
} | class ____(BaseClassificationComponentTest):
__test__ = True
res = dict()
res["default_iris"] = 1
res["default_iris_iterative"] = -1
res["default_iris_proba"] = 0.3350793047400861
res["default_iris_sparse"] = 0.56
res["default_digits"] = 0.914996964177292
res["default_digits_places"] =... | LibLinearComponentTest |
python | pypa__hatch | src/hatch/project/frontend/core.py | {
"start": 8509,
"end": 8861
} | class ____:
def __init__(self, project: Project, env: EnvironmentInterface) -> None:
self._project = project
self._env = env
@staticmethod
def inject_data(script: str, data: dict[str, Any]) -> str:
# All scripts have a constant dictionary on top
return script.replace("{}", r... | BuildFrontendScripts |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/sqlite/pysqlite.py | {
"start": 17415,
"end": 23750
} | class ____(SQLiteDialect):
default_paramstyle = "qmark"
supports_statement_cache = True
returns_native_bytes = True
colspecs = util.update_copy(
SQLiteDialect.colspecs,
{
sqltypes.Date: _SQLite_pysqliteDate,
sqltypes.TIMESTAMP: _SQLite_pysqliteTimeStamp,
... | SQLiteDialect_pysqlite |
python | doocs__leetcode | solution/0600-0699/0645.Set Mismatch/Solution.py | {
"start": 0,
"end": 210
} | class ____:
def findErrorNums(self, nums: List[int]) -> List[int]:
n = len(nums)
s1 = (1 + n) * n // 2
s2 = sum(set(nums))
s = sum(nums)
return [s - s2, s1 - s2]
| Solution |
python | getsentry__sentry-python | sentry_sdk/tracing.py | {
"start": 4287,
"end": 6389
} | class ____(str, Enum):
COMPONENT = "component"
CUSTOM = "custom"
ROUTE = "route"
TASK = "task"
URL = "url"
VIEW = "view"
def __str__(self):
# type: () -> str
return self.value
# These are typically high cardinality and the server hates them
LOW_QUALITY_TRANSACTION_SOURCES ... | TransactionSource |
python | walkccc__LeetCode | solutions/3134. Find the Median of the Uniqueness Array/3134.py | {
"start": 0,
"end": 802
} | class ____:
def medianOfUniquenessArray(self, nums: list[int]):
n = len(nums)
subarrayCount = n * (n + 1) // 2
medianCount = (subarrayCount + 1) // 2
# Similar to 992. Subarrays with K Different Integers
def subarraysWithAtMostKDistinct(k: int) -> int:
res = 0
count = collections.Coun... | Solution |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-scrapegraph/tests/test_tools_scrapegraph.py | {
"start": 11707,
"end": 14518
} | class ____:
"""Test Agentic Scraper functionality."""
def test_agentic_scraper_with_schema(self, tool_spec_from_env):
"""Test agentic scraper with schema."""
tool_spec, mock_client = tool_spec_from_env
prompt = "Navigate and extract product info"
url = "https://example.com"
... | TestAgenticScraper |
python | scikit-learn__scikit-learn | sklearn/feature_extraction/image.py | {
"start": 17469,
"end": 23608
} | class ____(TransformerMixin, BaseEstimator):
"""Extracts patches from a collection of images.
Read more in the :ref:`User Guide <image_feature_extraction>`.
.. versionadded:: 0.9
Parameters
----------
patch_size : tuple of int (patch_height, patch_width), default=None
The dimensions o... | PatchExtractor |
python | ray-project__ray | python/ray/tests/chaos/streaming_llm.py | {
"start": 427,
"end": 1039
} | class ____:
def __init__(self, dup_times: int):
self.dup_times = dup_times
async def __call__(self, prompt: str):
for word in prompt.split():
rev = word[::-1]
for _ in range(self.dup_times):
await asyncio.sleep(0.001)
# Ideally we want to ... | ReverseAndDupEachWord |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/json.py | {
"start": 3498,
"end": 4182
} | class ____:
def _format_value(self, value):
raise NotImplementedError()
def bind_processor(self, dialect):
super_proc = self.string_bind_processor(dialect)
def process(value):
value = self._format_value(value)
if super_proc:
value = super_proc(va... | _FormatTypeMixin |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-oci-data-science/tests/test_oci_data_science_client.py | {
"start": 1845,
"end": 3723
} | class ____:
"""Unit tests for _should_retry_exception function."""
def test_http_status_error_in_force_list(self):
"""Ensures it returns True for HTTPStatusError with status in STATUS_FORCE_LIST."""
response_mock = Mock()
response_mock.status_code = 500
original_exception = http... | TestShouldRetryException |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_filter_details.py | {
"start": 49,
"end": 2913
} | class ____(APITestCase):
endpoint = "sentry-api-0-project-filters-details"
method = "put"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def test_put(self) -> None:
org = self.create_organization(name="baz", slug="1", owner=self.user)
team = self... | ProjectFilterDetailsTest |
python | miyuchina__mistletoe | test/test_contrib/test_jira_renderer.py | {
"start": 1357,
"end": 7009
} | class ____(BaseRendererTest):
def setUp(self):
super().setUp()
self.renderer = JiraRenderer()
self.renderer.__enter__()
self.addCleanup(self.renderer.__exit__, None, None, None)
self.sampleOutputExtension = 'jira'
def genRandomString(self, n, hasWhitespace=False):
... | TestJiraRenderer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-analytics-v4/source_google_analytics_v4/source.py | {
"start": 22921,
"end": 26893
} | class ____(AbstractSource):
"""Google Analytics lets you analyze data about customer engagement with your website or application."""
@staticmethod
def get_authenticator(config: Mapping) -> Oauth2Authenticator:
# backwards compatibility, credentials_json used to be in the top level of the connector
... | SourceGoogleAnalyticsV4 |
python | apache__airflow | providers/telegram/tests/unit/telegram/operators/test_telegram.py | {
"start": 1039,
"end": 6923
} | class ____:
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
create_connection_without_db(
Connection(
conn_id="telegram_default",
conn_type="http",
password=TELEGRAM_TOKEN,
)
)
... | TestTelegramOperator |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_dynamic_partition_op_test.py | {
"start": 1348,
"end": 10434
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
@parameterized.parameters([
dict( # empty inputs
data=[],
partitions=[],
num_partitions=0,
expected=[],
expected_ragged_rank=1),
dict( # empty data, num_par... | RaggedSegmentStackOpTest |
python | ray-project__ray | doc/source/ray-core/doc_code/pattern_pipelining.py | {
"start": 245,
"end": 698
} | class ____:
def __init__(self, work_queue):
self.work_queue = work_queue
def process(self, work_item):
print(work_item)
def run(self):
while True:
# Get work from the remote queue.
work_item = ray.get(self.work_queue.get_work_item.remote())
if w... | WorkerWithoutPipelining |
python | apache__airflow | dev/breeze/src/airflow_breeze/global_constants.py | {
"start": 8546,
"end": 8724
} | class ____(SelectiveTestType):
ALWAYS = "Always"
API = "API"
CLI = "CLI"
CORE = "Core"
SERIALIZATION = "Serialization"
OTHER = "Other"
| SelectiveCoreTestType |
python | wandb__wandb | wandb/sdk/internal/handler.py | {
"start": 2182,
"end": 31549
} | class ____:
_consolidated_summary: SummaryDict
_sampled_history: Dict[str, sample.UniformSampleAccumulator]
_partial_history: Dict[str, Any]
_run_proto: Optional[RunRecord]
_settings: SettingsStatic
_record_q: "Queue[Record]"
_result_q: "Queue[Result]"
_stopped: Event
_writer_q: "Que... | HandleManager |
python | numba__numba | numba/cpython/listobj.py | {
"start": 1289,
"end": 4090
} | class ____(object):
@property
def size(self):
return self._payload.size
@size.setter
def size(self, value):
self._payload.size = value
@property
def dirty(self):
return self._payload.dirty
@property
def data(self):
return self._payload._get_ptr_by_name... | _ListPayloadMixin |
python | huggingface__transformers | src/transformers/models/falcon_mamba/modular_falcon_mamba.py | {
"start": 25779,
"end": 25842
} | class ____(MambaBlock):
pass
@auto_docstring
| FalconMambaBlock |
python | aio-libs__aiohttp | aiohttp/web_runner.py | {
"start": 9917,
"end": 10502
} | class ____(BaseRunner[BaseRequest]):
"""Low-level web server runner"""
__slots__ = ("_web_server",)
def __init__(
self,
web_server: Server[BaseRequest],
*,
handle_signals: bool = False,
**kwargs: Any,
) -> None:
super().__init__(handle_signals=handle_sig... | ServerRunner |
python | python-poetry__poetry | src/poetry/console/exceptions.py | {
"start": 4002,
"end": 7669
} | class ____(PoetryConsoleError):
"""
Represents a runtime error in the Poetry console application.
"""
def __init__(
self,
reason: str,
messages: list[ConsoleMessage] | None = None,
exit_code: int = 1,
) -> None:
super().__init__(reason)
self.exit_code... | PoetryRuntimeError |
python | getsentry__sentry | tests/sentry/testutils/helpers/test_features.py | {
"start": 3752,
"end": 7805
} | class ____(TestCase):
"""Test that nested with_feature contexts work correctly with proper precedence."""
def setUp(self) -> None:
self.org = self.create_organization()
def test_nested_context_managers_override(self) -> None:
"""Test that nested context managers properly override outer con... | TestNestedFeatureOverrides |
python | django__django | tests/generic_views/views.py | {
"start": 8332,
"end": 8620
} | class ____(generic.FormView):
form_class = ContactForm
success_url = reverse_lazy("authors_list")
template_name = "generic_views/form.html"
def form_valid(self, form):
form.add_error(None, "There is an error")
return self.form_invalid(form)
| LateValidationView |
python | yandexdataschool__Practical_RL | week02_value_based/mdp.py | {
"start": 359,
"end": 6695
} | class ____:
def __init__(self, transition_probs, rewards, initial_state=None, seed=None):
"""
Defines an MDP. Compatible with gym Env.
:param transition_probs: transition_probs[s][a][s_next] = P(s_next | s, a)
A dict[state -> dict] of dicts[action -> dict] of dicts[next_state -> ... | MDP |
python | ansible__ansible | lib/ansible/executor/powershell/module_manifest.py | {
"start": 1147,
"end": 1453
} | class ____:
content: dataclasses.InitVar[bytes]
path: str
script: str = dataclasses.field(init=False)
def __post_init__(self, content: bytes) -> None:
object.__setattr__(self, 'script', base64.b64encode(content).decode())
@dataclasses.dataclass(frozen=True, kw_only=True)
| _ScriptInfo |
python | fastai__fastai | fastai/torch_core.py | {
"start": 26863,
"end": 36601
} | class ____(nn.Module, metaclass=PrePostInitMeta):
"Same as `nn.Module`, but no need for subclasses to call `super().__init__`"
def __pre_init__(self, *args, **kwargs): super().__init__()
def __init__(self): pass
# %% ../nbs/00_torch_core.ipynb 169
from torch.nn.parallel import DistributedDataParallel
# %%... | Module |
python | cython__cython | runtests.py | {
"start": 34311,
"end": 58849
} | class ____(unittest.TestCase):
def __init__(self, test_directory, workdir, module, module_path, tags, language='c', preparse='id',
expect_log=(),
annotate=False, cleanup_workdir=True,
cleanup_sharedlibs=True, cleanup_failures=True, cython_only=False, test_selector=... | CythonCompileTestCase |
python | tensorflow__tensorflow | tensorflow/python/distribute/numpy_dataset_test.py | {
"start": 935,
"end": 1498
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_creating_var_with_numpy_arrays(self):
with self.cached_session() as session:
x = np.asarray(np.random.random((64, 3)), dtype=np.float32)
initial = np.zeros_like(x)
var_x = variable_v1.VariableV1(initial)
numpy_d... | InitVarFromNumpyTest |
python | mlflow__mlflow | mlflow/tracking/context/databricks_notebook_context.py | {
"start": 423,
"end": 1785
} | class ____(RunContextProvider):
def in_context(self):
return databricks_utils.is_in_databricks_notebook()
def tags(self):
notebook_id = databricks_utils.get_notebook_id()
notebook_path = databricks_utils.get_notebook_path()
webapp_url = databricks_utils.get_webapp_url()
... | DatabricksNotebookRunContext |
python | conda__conda | conda/gateways/connection/session.py | {
"start": 3972,
"end": 4783
} | class ____(type):
"""
Takes advice from https://github.com/requests/requests/issues/1871#issuecomment-33327847
and creates one Session instance per thread.
"""
def __new__(mcs, name, bases, dct):
dct["_thread_local"] = local()
return super().__new__(mcs, name, bases, dct)
def _... | CondaSessionType |
python | django-guardian__django-guardian | guardian/testapp/tests/test_shortcuts.py | {
"start": 62912,
"end": 72361
} | class ____(TestCase):
"""
Tests to investigate the reported issue where get_perms doesn't return a superset of get_user_perms.
"""
def setUp(self):
self.user = User.objects.create_user(username="testuser", email="test@example.com")
self.group = Group.objects.create(name="testgroup")
... | GetPermsVsGetUserPermsTest |
python | pypa__twine | twine/repository.py | {
"start": 1111,
"end": 9020
} | class ____:
def __init__(
self,
repository_url: str,
username: Optional[str],
password: Optional[str],
disable_progress_bar: bool = False,
) -> None:
self.url = repository_url
self.session = make_requests_session()
# requests.Session.auth should b... | Repository |
python | python-attrs__attrs | src/attr/_compat.py | {
"start": 915,
"end": 2829
} | class ____:
"""
Extract type annotations from a callable, returning None whenever there
is none.
"""
__slots__ = ["sig"]
def __init__(self, callable):
try:
self.sig = inspect.signature(callable)
except (ValueError, TypeError): # inspect failed
self.sig ... | _AnnotationExtractor |
python | aio-libs__aiohttp | aiohttp/helpers.py | {
"start": 18455,
"end": 19983
} | class ____:
"""Timeout handle"""
__slots__ = ("_timeout", "_loop", "_ceil_threshold", "_callbacks")
def __init__(
self,
loop: asyncio.AbstractEventLoop,
timeout: float | None,
ceil_threshold: float = 5,
) -> None:
self._timeout = timeout
self._loop = loo... | TimeoutHandle |
python | redis__redis-py | redis/asyncio/connection.py | {
"start": 2417,
"end": 27335
} | class ____:
"""Manages communication to and from a Redis server"""
__slots__ = (
"db",
"username",
"client_name",
"lib_name",
"lib_version",
"credential_provider",
"password",
"socket_timeout",
"socket_connect_timeout",
"redis_conn... | AbstractConnection |
python | keras-team__keras | keras/src/ops/image.py | {
"start": 25505,
"end": 31612
} | class ____(Operation):
def __init__(
self,
size,
strides=None,
dilation_rate=1,
padding="valid",
data_format=None,
*,
name=None,
):
super().__init__(name=name)
if isinstance(size, int):
size = (size, size, size)
... | ExtractPatches3D |
python | scrapy__scrapy | tests/CrawlerProcess/asyncio_enabled_no_reactor.py | {
"start": 308,
"end": 662
} | class ____(scrapy.Spider):
name = "no_request"
async def start(self):
return
yield
process = CrawlerProcess(
settings={
"TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor",
"EXTENSIONS": {ReactorCheckExtension: 0},
}
)
process.crawl(NoRequestsSp... | NoRequestsSpider |
python | sqlalchemy__sqlalchemy | test/orm/dml/test_orm_upd_del_inheritance.py | {
"start": 12523,
"end": 14102
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
@testing.fixture
def inherit_fixture(self, decl_base):
def go(poly_type):
class Person(decl_base):
__tablename__ = "person"
id = Column(Integer, primary_key=True)
... | InheritWPolyTest |
python | walkccc__LeetCode | solutions/3179. Find the N-th Value After K Seconds/3179.py | {
"start": 0,
"end": 126
} | class ____:
def valueAfterKSeconds(self, n: int, k: int) -> int:
return math.comb(n + k - 1, n - 1) % 1_000_000_007
| Solution |
python | celery__celery | celery/backends/mongodb.py | {
"start": 830,
"end": 11465
} | class ____(BaseBackend):
"""MongoDB result backend.
Raises:
celery.exceptions.ImproperlyConfigured:
if module :pypi:`pymongo` is not available.
"""
mongo_host = None
host = 'localhost'
port = 27017
user = None
password = None
database_name = 'celery'
taskmet... | MongoBackend |
python | pytransitions__transitions | transitions/extensions/diagrams.py | {
"start": 12508,
"end": 12698
} | class ____(GraphMachine, HierarchicalMarkupMachine):
"""
A hierarchical state machine with graph support.
"""
transition_cls = NestedGraphTransition
| HierarchicalGraphMachine |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.