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 | aio-libs__aiohttp | tests/test_websocket_parser.py | {
"start": 764,
"end": 21437
} | class ____(WebSocketReader):
"""WebSocketReader subclass that allows for patching parse_frame."""
def parse_frame(
self, data: bytes
) -> list[tuple[bool, int, bytes | bytearray, int]]:
# This method is overridden to allow for patching in tests.
frames: list[tuple[bool, int, bytes |... | PatchableWebSocketReader |
python | run-llama__llama_index | llama-index-core/llama_index/core/extractors/metadata_extractors.py | {
"start": 9063,
"end": 11947
} | class ____(BaseExtractor):
"""
Questions answered extractor. Node-level extractor.
Extracts `questions_this_excerpt_can_answer` metadata field.
Args:
llm (Optional[LLM]): LLM
questions (int): number of questions to extract
prompt_template (str): template for question extraction,... | QuestionsAnsweredExtractor |
python | scrapy__scrapy | tests/test_utils_defer.py | {
"start": 8299,
"end": 9506
} | class ____:
def test_deferred(self):
d = Deferred()
result = deferred_from_coro(d)
assert isinstance(result, Deferred)
assert result is d
def test_object(self):
result = deferred_from_coro(42)
assert result == 42
@inlineCallbacks
def test_coroutine(self)... | TestDeferredFromCoro |
python | ray-project__ray | rllib/algorithms/tests/test_env_runner_failures.py | {
"start": 1565,
"end": 5579
} | class ____(gym.Env):
"""Env that fails upon calling `step()`, but only for some remote EnvRunner indices.
The EnvRunner indices that should produce the failure (a ValueError) can be
provided by a list (of ints) under the "bad_indices" key in the env's
config.
.. testcode::
:skipif: True
... | FaultInjectEnv |
python | pennersr__django-allauth | allauth/headless/mfa/inputs.py | {
"start": 497,
"end": 565
} | class ____(AuthenticateForm, inputs.Input):
pass
| AuthenticateInput |
python | apache__airflow | providers/sftp/tests/unit/sftp/decorators/sensors/test_sftp.py | {
"start": 1199,
"end": 4686
} | class ____:
@patch("airflow.providers.sftp.sensors.sftp.SFTPHook")
def test_decorator_with_file_path(self, sftp_hook_mock, dag_maker):
sftp_hook_mock.return_value.get_mod_time.return_value = "19700101000000"
file_path = "/path/to/file/2021-09-09.txt"
decorated_func_return = "decorated_fu... | TestSFTPDecoratorSensor |
python | redis__redis-py | tests/test_connect.py | {
"start": 6829,
"end": 8287
} | class ____(socketserver.StreamRequestHandler):
def setup(self):
pass
def finish(self):
pass
def handle(self):
buffer = b""
command = None
command_ptr = None
fragment_length = None
while self.server.is_serving() or buffer:
try:
... | _RedisRequestHandler |
python | numba__numba | numba/core/types/containers.py | {
"start": 1255,
"end": 2053
} | class ____(SimpleIteratorType):
"""
Convenience base class for some container iterators.
Derived classes must implement the *container_class* attribute.
"""
def __init__(self, container):
assert isinstance(container, self.container_class), container
self.container = container
... | BaseContainerIterator |
python | scikit-learn__scikit-learn | doc/sphinxext/autoshortsummary.py | {
"start": 55,
"end": 1891
} | class ____(ModuleLevelDocumenter):
"""An autodocumenter that only renders the short summary of the object."""
# Defines the usage: .. autoshortsummary:: {{ object }}
objtype = "shortsummary"
# Disable content indentation
content_indent = ""
# Avoid being selected as the default documenter for... | ShortSummaryDocumenter |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1151403,
"end": 1151824
} | class ____(ScaleInvalidDataShowAsyOffset):
"""
ScaleInvalidDataShowAsValueyOffset schema wrapper.
Parameters
----------
value : float
Offset for y-position.
"""
_schema = {"$ref": '#/definitions/ScaleInvalidDataShowAsValue<"yOffset">'}
def __init__(self, value: Optional[float]... | ScaleInvalidDataShowAsValueyOffset |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 152558,
"end": 157961
} | class ____(Request):
"""
Delete a task along with any information stored for it (statistics, frame updates etc.)
Unless Force flag is provided, operation will fail if task has objects associated with it - i.e. children tasks
and projects. Models that refer to the deleted task will be updated with a task... | DeleteRequest |
python | numba__numba | numba/tests/test_parallel_backend.py | {
"start": 15628,
"end": 16921
} | class ____(ThreadLayerTestHelper):
"""
Checks that numba.threading_layer() reports correctly.
"""
_DEBUG = False
backends = {'tbb': skip_no_tbb,
'omp': skip_no_omp,
'workqueue': unittest.skipIf(False, '')}
@classmethod
def _inject(cls, backend, backend_guard... | TestThreadingLayerSelection |
python | numba__llvmlite | llvmlite/tests/test_ir.py | {
"start": 125244,
"end": 125840
} | class ____(TestBase):
def test_call_transform(self):
mod = ir.Module()
foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), ()), "foo")
bar = ir.Function(mod, ir.FunctionType(ir.VoidType(), ()), "bar")
builder = ir.IRBuilder()
builder.position_at_end(foo.append_basic_block()... | TestTransforms |
python | walkccc__LeetCode | solutions/408. Valid Word Abbreviation/408.py | {
"start": 0,
"end": 501
} | class ____:
def validWordAbbreviation(self, word: str, abbr: str) -> bool:
i = 0 # word's index
j = 0 # abbr's index
while i < len(word) and j < len(abbr):
if word[i] == abbr[j]:
i += 1
j += 1
continue
if not abbr[j].isdigit() or abbr[j] == '0':
return False
... | Solution |
python | getsentry__sentry-python | tests/test_ai_monitoring.py | {
"start": 12796,
"end": 17383
} | class ____:
def test_client_wraps_truncated_messages_in_annotated_value(self, large_messages):
"""Test that client.py properly wraps truncated messages in AnnotatedValue using scope data"""
from sentry_sdk._types import AnnotatedValue
from sentry_sdk.consts import SPANDATA
class Moc... | TestClientAnnotation |
python | apache__airflow | providers/exasol/tests/unit/exasol/operators/test_exasol.py | {
"start": 996,
"end": 2492
} | class ____:
@mock.patch("airflow.providers.common.sql.operators.sql.SQLExecuteQueryOperator.get_db_hook")
def test_overwrite_autocommit(self, mock_get_db_hook):
operator = ExasolOperator(task_id="TEST", sql="SELECT 1", autocommit=True)
operator.execute({})
mock_get_db_hook.return_value.r... | TestExasol |
python | astropy__astropy | astropy/utils/iers/tests/test_iers.py | {
"start": 796,
"end": 4689
} | class ____:
"""Basic tests that IERS_B returns correct values"""
@pytest.mark.parametrize("iers_cls", (iers.IERS_B, iers.IERS))
def test_simple(self, iers_cls):
"""Test the default behaviour for IERS_B and IERS."""
# Arguably, IERS itself should not be used at all, but it used to
# ... | TestBasic |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/preview.py | {
"start": 98,
"end": 441
} | class ____:
# Black's `Preview.dummy_implementations`
def get_release_info(self): ...
def raw_docstring():
r"""Black's `Preview.accept_raw_docstrings`
a
b
"""
pass
def reference_docstring_newlines():
"""A regular docstring for comparison
a
b
"""
... | CachedRepository |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 59481,
"end": 61690
} | class ____(rv_continuous):
r"""A double Weibull continuous random variable.
%(before_notes)s
Notes
-----
The probability density function for `dweibull` is given by
.. math::
f(x, c) = c / 2 |x|^{c-1} \exp(-|x|^c)
for a real number :math:`x` and :math:`c > 0`.
`dweibull` ta... | dweibull_gen |
python | getsentry__sentry | src/sentry/integrations/discord/integration.py | {
"start": 11261,
"end": 12319
} | class ____:
def __init__(self, params):
self.params = params
super().__init__()
def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase:
if "guild_id" not in request.GET or "code" not in request.GET:
state = pipeline.fetch_state(key=Integr... | DiscordInstallPipeline |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/functions.py | {
"start": 57464,
"end": 58122
} | class ____(GenericFunction[str]):
"""The SQL CONCAT() function, which concatenates strings.
E.g.:
.. sourcecode:: pycon+sql
>>> print(select(func.concat("a", "b")))
{printsql}SELECT concat(:concat_2, :concat_3) AS concat_1
String concatenation in SQLAlchemy is more commonly available... | concat |
python | redis__redis-py | redis/asyncio/multidb/event.py | {
"start": 266,
"end": 1042
} | class ____:
"""
Event fired when an async active database has been changed.
"""
def __init__(
self,
old_database: AsyncDatabase,
new_database: AsyncDatabase,
command_executor,
**kwargs,
):
self._old_database = old_database
self._new_database =... | AsyncActiveDatabaseChanged |
python | walkccc__LeetCode | solutions/17. Letter Combinations of a Phone Number/17.py | {
"start": 0,
"end": 512
} | class ____:
def letterCombinations(self, digits: str) -> list[str]:
if not digits:
return []
digitToLetters = ['', '', 'abc', 'def', 'ghi',
'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
ans = []
def dfs(i: int, path: list[str]) -> None:
if i == len(digits):
ans.appen... | Solution |
python | getsentry__sentry | tests/sentry/core/endpoints/test_team_projects.py | {
"start": 1585,
"end": 19476
} | class ____(APITestCase, TestCase):
endpoint = "sentry-api-0-team-project-index"
method = "post"
def setUp(self) -> None:
super().setUp()
self.team = self.create_team(members=[self.user])
self.data = {"name": "foo", "slug": "bar", "platform": "python"}
self.login_as(user=self... | TeamProjectsCreateTest |
python | ray-project__ray | python/ray/serve/tests/test_multiplex.py | {
"start": 8294,
"end": 19058
} | class ____:
def test_decorator_validation(self):
@serve.multiplexed
async def get_model(model: str):
return
@serve.multiplexed(max_num_models_per_replica=1)
async def get_model2(model: str):
return
@serve.deployment
class MyModel:
... | TestBasicAPI |
python | walkccc__LeetCode | solutions/1698. Number of Distinct Substrings in a String/1698.py | {
"start": 0,
"end": 789
} | class ____:
def countDistinct(self, s: str) -> int:
BASE = 26
HASH = 1_000_000_007
n = len(s)
ans = 0
pow = [1] + [0] * n # pow[i] := BASE^i
hashes = [0] * (n + 1) # hashes[i] := the hash of s[0..i)
def val(c: str) -> int:
return ord(c) - ord('a')
for i in range(1, n + 1)... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol18.py | {
"start": 110,
"end": 174
} | class ____(Protocol): ...
# This should generate an error.
A()
| A |
python | doocs__leetcode | solution/1600-1699/1684.Count the Number of Consistent Strings/Solution2.py | {
"start": 0,
"end": 265
} | class ____:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
def f(w):
return reduce(or_, (1 << (ord(c) - ord('a')) for c in w))
mask = f(allowed)
return sum((mask | f(w)) == mask for w in words)
| Solution |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 3013,
"end": 4087
} | class ____:
def setup(self):
N = 10**3
self.df = DataFrame(np.random.randn(N * 10, N))
self.idx = np.arange(4 * N, 7 * N)
self.dict_idx = {k: k for k in self.idx}
self.df2 = DataFrame(
{
c: {
0: np.random.randint(0, 2, N).astype... | Rename |
python | numpy__numpy | numpy/lib/tests/test_index_tricks.py | {
"start": 426,
"end": 8475
} | class ____:
def test_basic(self):
assert_equal(np.unravel_index(2, (2, 2)), (1, 0))
# test that new shape argument works properly
assert_equal(np.unravel_index(indices=2,
shape=(2, 2)),
(1, 0))
# test that ... | TestRavelUnravelIndex |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 69622,
"end": 72272
} | class ____:
def test_year_full(self):
assert self.locale.year_full(2015) == "2558"
def test_year_abbreviation(self):
assert self.locale.year_abbreviation(2015) == "58"
def test_format_relative_now(self):
result = self.locale._format_relative("ດຽວນີ້", "now", 0)
assert resul... | TestLaotianLocale |
python | sqlalchemy__sqlalchemy | test/orm/test_unitofwork.py | {
"start": 53385,
"end": 64685
} | class ____(_fixtures.FixtureTest):
run_inserts = None
def test_basic(self):
User, users = self.classes.User, self.tables.users
m = self.mapper_registry.map_imperatively(User, users)
# save two users
u = User(name="savetester")
u2 = User(name="savetester2")
wit... | SaveTest |
python | tensorflow__tensorflow | tensorflow/python/keras/layers/convolutional.py | {
"start": 94924,
"end": 104498
} | class ____(Conv2D):
"""Depthwise 2D convolution.
Depthwise convolution is a type of convolution in which a single convolutional
filter is apply to each input channel (i.e. in a depthwise way).
You can understand depthwise convolution as being
the first step in a depthwise separable convolution.
It is impl... | DepthwiseConv2D |
python | doocs__leetcode | solution/2400-2499/2437.Number of Valid Clock Times/Solution2.py | {
"start": 0,
"end": 367
} | class ____:
def countTime(self, time: str) -> int:
def f(s: str, m: int) -> int:
cnt = 0
for i in range(m):
a = s[0] == '?' or (int(s[0]) == i // 10)
b = s[1] == '?' or (int(s[1]) == i % 10)
cnt += a and b
return cnt
... | Solution |
python | facebookresearch__faiss | tests/test_binary_factory.py | {
"start": 277,
"end": 1653
} | class ____(unittest.TestCase):
def test_factory_IVF(self):
index = faiss.index_binary_factory(16, "BIVF10")
assert index.invlists is not None
assert index.nlist == 10
assert index.code_size == 2
def test_factory_Flat(self):
index = faiss.index_binary_factory(16, "BFla... | TestBinaryFactory |
python | allegroai__clearml | clearml/backend_api/services/v2_23/dataviews.py | {
"start": 74052,
"end": 74883
} | class ____(Response):
"""
Response of dataviews.create endpoint.
:param id: New dataview's ID
:type id: str
"""
_service = "dataviews"
_action = "create"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"id": {"description": "New datavie... | CreateResponse |
python | huggingface__transformers | src/transformers/models/grounding_dino/modeling_grounding_dino.py | {
"start": 5537,
"end": 7346
} | class ____(ModelOutput):
r"""
last_hidden_state_vision (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the vision encoder.
last_hidden_state_text (`torch.FloatTensor` of shape `(batch_size, sequence_length, hid... | GroundingDinoEncoderOutput |
python | getsentry__sentry | src/sentry/users/api/endpoints/user_regions.py | {
"start": 1528,
"end": 2633
} | class ____(UserEndpoint):
owner = ApiOwner.HYBRID_CLOUD
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (UserRegionEndpointPermissions,)
def get(self, request: Request, user: RpcUser, **kwargs: Any) -> Response:
"""
Retrieve the Regions a User has... | UserRegionsEndpoint |
python | run-llama__llama_index | llama-index-integrations/postprocessor/llama-index-postprocessor-siliconflow-rerank/llama_index/postprocessor/siliconflow_rerank/base.py | {
"start": 714,
"end": 4982
} | class ____(BaseNodePostprocessor):
model: str = Field(
default="BAAI/bge-reranker-v2-m3",
description="Specifies the model to be used.",
)
base_url: str = Field(
default=DEFAULT_SILICONFLOW_API_URL,
description="The URL of the SiliconFlow Rerank API.",
)
api_key: str ... | SiliconFlowRerank |
python | spyder-ide__spyder | spyder/plugins/completion/providers/languageserver/transport/main.py | {
"start": 3076,
"end": 5862
} | class ____:
"""Manage and intercept SIGTERM and SIGKILL signals."""
def __init__(self):
self.original_sigint = signal.getsignal(signal.SIGINT)
self.original_sigterm = signal.getsignal(signal.SIGTERM)
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM... | SignalManager |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_block_schemas.py | {
"start": 7253,
"end": 13902
} | class ____:
async def test_read_all_block_schemas(self, session, client, block_schemas):
result = await client.post("/block_schemas/filter")
api_schemas = parse_obj_as(List[schemas.core.BlockSchema], result.json())
assert {s.id for s in api_schemas} == {
block_schemas[0].id,
... | TestReadBlockSchema |
python | ansible__ansible | lib/ansible/galaxy/collection/gpg.py | {
"start": 5193,
"end": 5311
} | class ____(GpgBaseError):
"""No passphrase was supplied."""
@dataclass(frozen=True, slots=True)
| GpgMissingPassPhrase |
python | great-expectations__great_expectations | great_expectations/exceptions/exceptions.py | {
"start": 11653,
"end": 11880
} | class ____(BatchDefinitionError):
def __init__(self, name: str) -> None:
super().__init__(
f"BatchDefinition '{name}' not found. Please check the name and try again."
)
| BatchDefinitionNotFoundError |
python | ansible__ansible | test/lib/ansible_test/_internal/host_configs.py | {
"start": 11286,
"end": 12945
} | class ____(RemoteConfig, ControllerHostConfig, PosixConfig):
"""Configuration for a POSIX remote host."""
become: t.Optional[str] = None
def get_defaults(self, context: HostContext) -> PosixRemoteCompletionConfig:
"""Return the default settings."""
# pylint: disable=unexpected-keyword-arg ... | PosixRemoteConfig |
python | pypa__pip | src/pip/_internal/resolution/resolvelib/base.py | {
"start": 3515,
"end": 5047
} | class ____:
@property
def project_name(self) -> NormalizedName:
"""The "project name" of the candidate.
This is different from ``name`` if this candidate contains extras,
in which case ``name`` would contain the ``[...]`` part, while this
refers to the name of the project.
... | Candidate |
python | getsentry__sentry | tests/sentry/tasks/test_post_process.py | {
"start": 3763,
"end": 4231
} | class ____:
def __init__(self, expected, group=None):
self.expected = expected
self.expected_group = group
def __eq__(self, other):
matching_id = other.event_id == self.expected.event_id
if self.expected_group:
return (
matching_id
and... | EventMatcher |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 209654,
"end": 210444
} | class ____(TestCase):
def test_no_iterables(self):
actual = list(mi.filter_map(lambda _: None, []))
expected = []
self.assertEqual(actual, expected)
def test_filter(self):
actual = list(mi.filter_map(lambda _: None, [1, 2, 3]))
expected = []
self.assertEqual(actu... | FilterMapTests |
python | bokeh__bokeh | src/bokeh/core/property/alias.py | {
"start": 1700,
"end": 2639
} | class ____(Property[T]):
"""
Alias another property of a model.
Example:
Consider the following class definitions:
.. code-block:: python
from bokeh.model import Model
from bokeh.properties import Alias, Int
class Parent(Model):
width ... | Alias |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/visitors.py | {
"start": 22320,
"end": 36065
} | class ____(CloningExternalTraversal):
"""Base class for visitor objects which can traverse using
the :func:`.visitors.replacement_traverse` function.
Direct usage of the :func:`.visitors.replacement_traverse` function is
usually preferred.
"""
__slots__ = ()
def replace(
self, el... | ReplacingExternalTraversal |
python | python__mypy | mypy/test/meta/test_update_data.py | {
"start": 703,
"end": 4814
} | class ____(Suite):
def test_update_data(self) -> None:
# Note: We test multiple testcases rather than 'test case per test case'
# so we could also exercise rewriting multiple testcases at once.
result = _run_pytest_update_data(
"""
[case testCorrect]
... | UpdateDataSuite |
python | pandas-dev__pandas | pandas/tests/plotting/test_style.py | {
"start": 197,
"end": 5000
} | class ____:
@pytest.mark.parametrize(
"num_colors, expected",
[
(3, ["red", "green", "blue"]),
(5, ["red", "green", "blue", "red", "green"]),
(7, ["red", "green", "blue", "red", "green", "blue", "red"]),
(2, ["red", "green"]),
(1, ["red"]),... | TestGetStandardColors |
python | bokeh__bokeh | src/bokeh/models/plots.py | {
"start": 3198,
"end": 32624
} | class ____(LayoutDOM):
''' Model representing a plot, containing glyphs, guides, annotations.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
def select(self, *args, **kwargs):
''' Query th... | Plot |
python | kamyu104__LeetCode-Solutions | Python/shortest-impossible-sequence-of-rolls.py | {
"start": 55,
"end": 427
} | class ____(object):
def shortestSequence(self, rolls, k):
"""
:type rolls: List[int]
:type k: int
:rtype: int
"""
l = 0
lookup = set()
for x in rolls:
lookup.add(x)
if len(lookup) != k:
continue
looku... | Solution |
python | doocs__leetcode | solution/0000-0099/0054.Spiral Matrix/Solution.py | {
"start": 0,
"end": 555
} | class ____:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
dirs = (0, 1, 0, -1, 0)
vis = [[False] * n for _ in range(m)]
i = j = k = 0
ans = []
for _ in range(m * n):
ans.append(matrix[i][j])
vis... | Solution |
python | pydata__xarray | xarray/core/indexing.py | {
"start": 61715,
"end": 62087
} | class ____(NumpyIndexingAdapter):
__slots__ = ("array",)
def __init__(self, array):
if not hasattr(array, "__array_function__"):
raise TypeError(
"NdArrayLikeIndexingAdapter must wrap an object that "
"implements the __array_function__ protocol"
)... | NdArrayLikeIndexingAdapter |
python | pandas-dev__pandas | pandas/io/formats/xml.py | {
"start": 9541,
"end": 12100
} | class ____(_BaseXMLFormatter):
"""
Class for formatting data in xml using Python standard library
modules: `xml.etree.ElementTree` and `xml.dom.minidom`.
"""
def _build_tree(self) -> bytes:
from xml.etree.ElementTree import (
Element,
SubElement,
tostring... | EtreeXMLFormatter |
python | gevent__gevent | src/greentest/3.13/test_queue.py | {
"start": 22429,
"end": 22523
} | class ____(LifoQueueTest, unittest.TestCase):
queue = py_queue
@need_c_queue
| PyLifoQueueTest |
python | facebookresearch__faiss | tests/external_module_test.py | {
"start": 295,
"end": 566
} | class ____(unittest.TestCase):
"""test if we can construct a custom IDSelector"""
def test_IDSelector(self):
ids = external_module.IDSelectorModulo(3)
self.assertFalse(ids.is_member(1))
self.assertTrue(ids.is_member(3))
| TestCustomIDSelector |
python | huggingface__transformers | src/transformers/models/markuplm/feature_extraction_markuplm.py | {
"start": 924,
"end": 6443
} | class ____(FeatureExtractionMixin):
r"""
Constructs a MarkupLM feature extractor. This can be used to get a list of nodes and corresponding xpaths from HTML
strings.
This feature extractor inherits from [`~feature_extraction_utils.PreTrainedFeatureExtractor`] which contains most
of the main methods... | MarkupLMFeatureExtractor |
python | django__django | tests/sites_tests/tests.py | {
"start": 904,
"end": 8807
} | class ____(TestCase):
databases = {"default", "other"}
@classmethod
def setUpTestData(cls):
cls.site = Site(id=settings.SITE_ID, domain="example.com", name="example.com")
cls.site.save()
def setUp(self):
Site.objects.clear_cache()
self.addCleanup(Site.objects.clear_cach... | SitesFrameworkTests |
python | weaviate__weaviate-python-client | weaviate/auth.py | {
"start": 971,
"end": 1832
} | class ____:
"""Using username and password for authentication with Resource Owner Password flow.
For some providers the scope needs to contain "offline_access" (and "openid" which is automatically added) to return
a refresh token. Without a refresh token the authentication will expire once the lifetime of ... | _ClientPassword |
python | huggingface__transformers | examples/pytorch/speech-recognition/run_speech_recognition_ctc.py | {
"start": 10925,
"end": 32867
} | class ____:
"""
Data collator that will dynamically pad the inputs received.
Args:
processor (:class:`~transformers.AutoProcessor`)
The processor used for processing the data.
padding (:obj:`bool`, :obj:`str` or :class:`~transformers.tokenization_utils_base.PaddingStrategy`, `opt... | DataCollatorCTCWithPadding |
python | huggingface__transformers | tests/models/qwen2_vl/test_modeling_qwen2_vl.py | {
"start": 5544,
"end": 14840
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
"""
Model tester for `Qwen2VLForConditionalGeneration`.
"""
all_model_classes = (
(
Qwen2VLModel,
Qwen2VLForConditionalGeneration,
)
if is_torch_available()
... | Qwen2VLModelTest |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/envs/unity_aec_env.py | {
"start": 211,
"end": 2494
} | class ____(UnityPettingzooBaseEnv, AECEnv):
"""
Unity AEC (PettingZoo) environment wrapper.
"""
def __init__(self, env: BaseEnv, seed: Optional[int] = None):
"""
Initializes a Unity AEC environment wrapper.
:param env: The UnityEnvironment that is being wrapped.
:param ... | UnityAECEnv |
python | scipy__scipy | scipy/special/tests/test_iv_ratio.py | {
"start": 5612,
"end": 10108
} | class ____:
@pytest.mark.parametrize('v,x,r', [
(0.5, 0.16666666666666666, 0.8348595870753707),
(0.5, 0.3333333333333333, 0.6784872624683657),
(0.5, 0.5, 0.5378828427399902),
(0.5, 0.6666666666666666, 0.4172170546520899),
(0.5, 0.8333333333333335, 0.3177382097618302),
... | TestIvRatioC |
python | huggingface__transformers | src/transformers/models/tvp/processing_tvp.py | {
"start": 1030,
"end": 2488
} | class ____(ProcessorMixin):
r"""
Constructs an TVP processor which wraps a TVP image processor and a Bert tokenizer into a single processor.
[`TvpProcessor`] offers all the functionalities of [`TvpImageProcessor`] and [`BertTokenizerFast`]. See the
[`~TvpProcessor.__call__`] and [`~TvpProcessor.decode`... | TvpProcessor |
python | scipy__scipy | scipy/linalg/tests/test_decomp.py | {
"start": 48554,
"end": 49383
} | class ____(TestSVD_GESDD):
lapack_driver = 'gesvd'
# Allocating an array of such a size leads to _ArrayMemoryError(s)
# since the maximum memory that can be in 32-bit (WASM) is 4GB
@pytest.mark.skipif(IS_WASM, reason="out of memory in WASM")
@pytest.mark.xfail_on_32bit("out of memory in 32-bit CI workflow")
@pyte... | TestSVD_GESVD |
python | sqlalchemy__sqlalchemy | test/sql/test_metadata.py | {
"start": 58903,
"end": 60783
} | class ____(fixtures.TestBase):
def test_metadata_info(self):
m1 = MetaData()
eq_(m1.info, {})
m1 = MetaData(info={"foo": "bar"})
eq_(m1.info, {"foo": "bar"})
def test_foreignkey_constraint_info(self):
fkc = ForeignKeyConstraint(["a"], ["b"], name="bar")
eq_(fkc.... | InfoTest |
python | encode__httpx | httpx/_auth.py | {
"start": 3600,
"end": 4316
} | class ____(Auth):
"""
Allows the 'auth' argument to be passed as a (username, password) pair,
and uses HTTP Basic authentication.
"""
def __init__(self, username: str | bytes, password: str | bytes) -> None:
self._auth_header = self._build_auth_header(username, password)
def auth_flow(... | BasicAuth |
python | tiangolo__fastapi | fastapi/responses.py | {
"start": 722,
"end": 1216
} | class ____(JSONResponse):
"""
JSON response using the high-performance ujson library to serialize data to JSON.
Read more about it in the
[FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/).
"""
def render(self, content: Any) ... | UJSONResponse |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/output/base.py | {
"start": 365,
"end": 6087
} | class ____(metaclass=ABCMeta):
"""
Base class defining the output interface for a
:class:`~prompt_toolkit.renderer.Renderer`.
Actual implementations are
:class:`~prompt_toolkit.output.vt100.Vt100_Output` and
:class:`~prompt_toolkit.output.win32.Win32Output`.
"""
stdout: TextIO | None =... | Output |
python | wandb__wandb | wandb/sdk/artifacts/artifact.py | {
"start": 3606,
"end": 106891
} | class ____:
"""Flexible and lightweight building block for dataset and model versioning.
Construct an empty W&B Artifact. Populate an artifacts contents with methods that
begin with `add`. Once the artifact has all the desired files, you can call
`run.log_artifact()` to log it.
Args:
name ... | Artifact |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/utils/compare.py | {
"start": 2415,
"end": 2468
} | class ____(HashMixin, dict):
pass
| DictWithHashMixin |
python | django-import-export__django-import-export | tests/core/tests/test_resources/test_relationships.py | {
"start": 279,
"end": 1416
} | class ____(TestCase):
def setUp(self):
self.user = User.objects.create(username="foo")
self.role = Role.objects.create(user=self.user)
self.person = Person.objects.create(role=self.role)
def test_export(self):
class MyPersonResource(resources.ModelResource):
role = f... | ForeignKeyWidgetFollowRelationship |
python | mlflow__mlflow | mlflow/projects/_project_spec.py | {
"start": 7386,
"end": 9661
} | class ____:
"""A project specification loaded from an MLproject file in the passed-in directory."""
def __init__(
self,
name,
env_type=None,
env_config_path=None,
entry_points=None,
docker_env=None,
databricks_spark_job_spec=None,
):
self.env_... | Project |
python | getsentry__sentry | tests/sentry/backup/test_imports.py | {
"start": 33038,
"end": 39059
} | class ____(ImportTestCase):
"""
Ensures that only models with the allowed relocation scopes are actually imported.
"""
@staticmethod
def verify_model_inclusion(scope: ImportScope):
"""
Ensure all in-scope models are included, and that no out-of-scope models are included.
Add... | ScopingTests |
python | walkccc__LeetCode | solutions/2653. Sliding Subarray Beauty/2653.py | {
"start": 0,
"end": 607
} | class ____:
def getSubarrayBeauty(self, nums: list[int], k: int, x: int) -> list[int]:
ans = []
count = [0] * 50 # count[i] := the frequency of (i + 50)
for i, num in enumerate(nums):
if num < 0:
count[num + 50] += 1
if i - k >= 0 and nums[i - k] < 0:
count[nums[i - k] + 50] ... | Solution |
python | doocs__leetcode | lcof/面试题44. 数字序列中某一位的数字/Solution2.py | {
"start": 0,
"end": 289
} | class ____:
def findNthDigit(self, n: int) -> int:
if n < 10:
return n
n -= 10
k, p = 2, 10
while n >= 9 * k * p:
n -= 9 * k * p
k += 1
p *= 10
x = p + n // k
return int(str(x)[n % k])
| Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/pickleable.py | {
"start": 614,
"end": 648
} | class ____(User):
pass
| EmailUser |
python | pytorch__pytorch | torch/_dynamo/variables/higher_order_ops.py | {
"start": 106671,
"end": 109265
} | class ____(TorchHigherOrderOperatorVariable):
def _call_function(
self,
tx: "InstructionTranslator",
args: "list[VariableTracker]",
kwargs: "dict[str, VariableTracker]",
) -> "VariableTracker":
from .builder import wrap_fx_proxy
# This is operator for delegation ... | ExecutorchCallDelegateHigherOrderVariable |
python | huggingface__transformers | src/transformers/models/unispeech/modular_unispeech.py | {
"start": 5439,
"end": 8968
} | class ____(PreTrainedModel):
config: UniSpeechConfig
base_model_prefix = "unispeech"
main_input_name = "input_values"
input_modalities = "audio"
supports_gradient_checkpointing = True
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
@torch.no_grad()
d... | UniSpeechPreTrainedModel |
python | pandas-dev__pandas | pandas/tests/indexing/test_chaining_and_caching.py | {
"start": 2280,
"end": 12646
} | class ____:
def test_setitem_chained_setfault(self):
# GH6026
data = ["right", "left", "left", "left", "right", "left", "timeout"]
df = DataFrame({"response": np.array(data)})
mask = df.response == "timeout"
with tm.raises_chained_assignment_error():
df.response[... | TestChaining |
python | pandas-dev__pandas | pandas/tests/indexes/period/test_indexing.py | {
"start": 7452,
"end": 11785
} | class ____:
def test_get_loc_msg(self):
idx = period_range("2000-1-1", freq="Y", periods=10)
bad_period = Period("2012", "Y")
with pytest.raises(KeyError, match=r"^Period\('2012', 'Y-DEC'\)$"):
idx.get_loc(bad_period)
try:
idx.get_loc(bad_period)
exce... | TestGetLoc |
python | numpy__numpy | numpy/_core/tests/test_numeric.py | {
"start": 142747,
"end": 145402
} | class ____:
# expected shape indexed by (axis, start) for array of
# shape (1, 2, 3, 4)
tgtshape = {(0, 0): (1, 2, 3, 4), (0, 1): (1, 2, 3, 4),
(0, 2): (2, 1, 3, 4), (0, 3): (2, 3, 1, 4),
(0, 4): (2, 3, 4, 1),
(1, 0): (2, 1, 3, 4), (1, 1): (1, 2, 3, 4),
... | TestRollaxis |
python | scikit-learn__scikit-learn | sklearn/tree/_export.py | {
"start": 6214,
"end": 13999
} | class ____:
def __init__(
self,
max_depth=None,
feature_names=None,
class_names=None,
label="all",
filled=False,
impurity=True,
node_ids=False,
proportion=False,
rounded=False,
precision=3,
fontsize=None,
):
... | _BaseTreeExporter |
python | allegroai__clearml | clearml/backend_api/services/v2_20/tasks.py | {
"start": 197293,
"end": 201061
} | class ____(Response):
"""
Response of tasks.dequeue_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "tasks"
_action = "dequeue_many"
_version = "2.20"
_schema = {
"definitions": {},
... | DequeueManyResponse |
python | huggingface__transformers | src/transformers/models/evolla/modeling_evolla.py | {
"start": 21046,
"end": 21612
} | class ____(PreTrainedModel):
config: SaProtConfig
_no_split_modules = ["EvollaSaProtLayer"]
_supports_flash_attn = True
_supports_sdpa = True
_supports_flex_attn = True
_supports_attention_backend = True
_can_record_outputs = {
"hidden_states": EvollaSaProtLayer,
"attentions... | EvollaSaProtPreTrainedModel |
python | pytorch__pytorch | torch/jit/_trace.py | {
"start": 49932,
"end": 53296
} | class ____(ScriptModule):
_disable_script_meta = True
def __init__(self, orig, id_set=None, _compilation_unit=None):
# XXX: orig can be a nn.Module or a function!
super().__init__()
assert isinstance(orig, torch.nn.Module)
# Copy a subset of `orig` to a temporary nn.Module.
... | TracedModule |
python | wandb__wandb | wandb/vendor/pygments/lexers/archetype.py | {
"start": 6344,
"end": 8732
} | class ____(AtomsLexer):
"""
Lexer for cADL syntax.
.. versionadded:: 2.1
"""
name = 'cADL'
aliases = ['cadl']
filenames = ['*.cadl']
tokens = {
'path': [
# attribute name
(r'[a-z_]\w*', Name.Class),
(r'/', Punctuation),
(r'\[', Pu... | CadlLexer |
python | sqlalchemy__sqlalchemy | test/sql/test_types.py | {
"start": 93691,
"end": 98239
} | class ____(fixtures.TablesTest, AssertsExecutionResults):
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
global MyPickleType
class MyPickleType(types.TypeDecorator):
impl = PickleType
cache_ok = True
def process_bind_par... | BinaryTest |
python | kamyu104__LeetCode-Solutions | Python/minimum-array-sum.py | {
"start": 151,
"end": 1681
} | class ____(object):
def minArraySum(self, nums, k, op1, op2):
"""
:type nums: List[int]
:type k: int
:type op1: int
:type op2: int
:rtype: int
"""
nums.sort()
left = next((i for i in xrange(len(nums)) if nums[i] >= k), len(nums))
right... | Solution |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/system.py | {
"start": 9728,
"end": 10480
} | class ____(PlanOrchestrationContext, IStepContext):
"""Context for the orchestration of a step.
This context assumes inability to run user code directly. Thus, it does not include any resource
information.
"""
def __init__(
self,
plan_data: PlanData,
log_manager: DagsterLog... | StepOrchestrationContext |
python | google__pytype | pytype/datatypes_test.py | {
"start": 129,
"end": 1086
} | class ____(unittest.TestCase):
"""Test AccessTrackingDict."""
def setUp(self):
super().setUp()
self.d = datatypes.AccessTrackingDict({"a": 1, "b": 2})
def test_get(self):
v = self.d["a"]
(item,) = self.d.accessed_subset.items()
self.assertEqual(item, ("a", 1))
self.assertEqual(v, 1)
d... | AccessTrackingDictTest |
python | huggingface__transformers | src/transformers/models/glm4v/modeling_glm4v.py | {
"start": 16756,
"end": 23546
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Glm4vTextConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
se... | Glm4vTextRotaryEmbedding |
python | allegroai__clearml | clearml/backend_api/services/v2_13/models.py | {
"start": 124923,
"end": 126783
} | class ____(Response):
"""
Response of models.update endpoint.
:param updated: Number of models updated (0 or 1)
:type updated: int
:param fields: Updated fields names and values
:type fields: dict
"""
_service = "models"
_action = "update"
_version = "2.13"
_schema = {
... | UpdateResponse |
python | pytorch__pytorch | torch/nn/parallel/distributed.py | {
"start": 7997,
"end": 9235
} | class ____(Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(ctx, ddp_weakref, *inputs):
# set_materialize_grads(False) will ensure that None gradients stay as
# None and are not filled with zeros.
ctx.set_materialize_grads(False)
ctx.ddp_weakref = ddp_wea... | _DDPSink |
python | py-pdf__pypdf | pypdf/generic/_data_structures.py | {
"start": 3110,
"end": 8414
} | class ____(list[Any], PdfObject):
def replicate(
self,
pdf_dest: PdfWriterProtocol,
) -> "ArrayObject":
arr = cast(
"ArrayObject",
self._reference_clone(ArrayObject(), pdf_dest, False),
)
for data in self:
if hasattr(data, "replicate"):... | ArrayObject |
python | plotly__plotly.py | plotly/graph_objs/indicator/_number.py | {
"start": 233,
"end": 4745
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "indicator"
_path_str = "indicator.number"
_valid_props = {"font", "prefix", "suffix", "valueformat"}
@property
def font(self):
"""
Set the font used to display main number
The 'font' property is an instance of Font
... | Number |
python | streamlit__streamlit | lib/streamlit/elements/lib/js_number.py | {
"start": 670,
"end": 737
} | class ____(Exception): # noqa: N818
pass
| JSNumberBoundsException |
python | astropy__astropy | astropy/coordinates/builtin_frames/ecliptic.py | {
"start": 6978,
"end": 7773
} | class ____(BaseEclipticFrame):
"""
Heliocentric mean ecliptic coordinates. These origin of the coordinates are the
center of the sun, with the x axis pointing in the direction of
the *mean* (not true) equinox as at the time specified by the ``equinox``
attribute (as seen from Earth), and the xy-pla... | HeliocentricMeanEcliptic |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.