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 | ansible__ansible | test/units/playbook/test_base.py | {
"start": 1123,
"end": 6408
} | class ____(unittest.TestCase):
ClassUnderTest = base.Base
def setUp(self):
self.assorted_vars = {'var_2_key': 'var_2_value',
'var_1_key': 'var_1_value',
'a_list': ['a_list_1', 'a_list_2'],
'a_dict': {'a_dict_key':... | TestBase |
python | sqlalchemy__sqlalchemy | test/ext/test_extendedattr.py | {
"start": 3111,
"end": 4457
} | class ____(_ExtBase, fixtures.TestBase):
def test_unregister(self, registry):
class MyClassState(instrumentation.InstrumentationManager):
def manage(self, class_, manager):
setattr(class_, "xyz", manager)
def unregister(self, class_, manager):
delattr... | DisposeTest |
python | doocs__leetcode | solution/3400-3499/3446.Sort Matrix by Diagonals/Solution.py | {
"start": 0,
"end": 863
} | class ____:
def sortMatrix(self, grid: List[List[int]]) -> List[List[int]]:
n = len(grid)
for k in range(n - 2, -1, -1):
i, j = k, 0
t = []
while i < n and j < n:
t.append(grid[i][j])
i += 1
j += 1
t.sort... | Solution |
python | pypa__setuptools | setuptools/namespaces.py | {
"start": 3014,
"end": 3171
} | class ____(Installer):
def _get_root(self):
return repr(str(self.egg_path))
def _get_target(self):
return self.egg_link
| DevelopInstaller |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_supervisor.py | {
"start": 97126,
"end": 101544
} | class ____:
def test_no_retries(self):
called = 0
def noop_handler(request: httpx.Request) -> httpx.Response:
nonlocal called
called += 1
return httpx.Response(500)
transport = httpx.MockTransport(noop_handler)
client = InProcessTestSupervisor._C... | TestInProcessClient |
python | great-expectations__great_expectations | tests/core/test_batch_definition.py | {
"start": 1079,
"end": 10430
} | class ____(DataAsset):
@override
def get_batch_identifiers_list(self, batch_request: BatchRequest) -> List[dict]:
raise NotImplementedError
@override
def get_batch(self, batch_request: BatchRequest) -> Batch:
raise NotImplementedError
@pytest.fixture
def mock_data_asset(monkeypatch, m... | DataAssetForTests |
python | scrapy__scrapy | tests/test_downloader_handlers_http_base.py | {
"start": 26669,
"end": 26831
} | class ____(TestSimpleHttpsBase):
"""Connect to HTTPS hosts with IP while certificate uses domain names IDs."""
host = "127.0.0.1"
| TestHttpsInvalidDNSIdBase |
python | realpython__materials | python-callable-instances/logger.py | {
"start": 0,
"end": 232
} | class ____:
def __init__(self, filename):
self.filename = filename
def __call__(self, message):
with open(self.filename, mode="a", encoding="utf-8") as log_file:
log_file.write(message + "\n")
| Logger |
python | gevent__gevent | src/gevent/tests/test__greenlet.py | {
"start": 7719,
"end": 7804
} | class ____(TestRaise_link):
link_method = 'link_exception'
| TestRaise_link_exception |
python | scipy__scipy | scipy/cluster/tests/test_hierarchy.py | {
"start": 14123,
"end": 14645
} | class ____:
def test_leaders_single(self, xp):
# Tests leaders using a flat clustering generated by single linkage.
X = hierarchy_test_data.Q_X
Y = pdist(X)
Z = linkage(Y)
T = fcluster(Z, criterion='maxclust', t=3)
Z = xp.asarray(Z)
T = xp.asarray(T, dtype=xp... | TestLeaders |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_format11.py | {
"start": 315,
"end": 893
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("format11.xlsx")
def test_create_file(self):
"""Test a vertical and horizontal centered format."""
workbook = Workbook(self.got_fil... | TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/112. Path Sum/112.py | {
"start": 0,
"end": 308
} | class ____:
def hasPathSum(self, root: TreeNode, summ: int) -> bool:
if not root:
return False
if root.val == summ and not root.left and not root.right:
return True
return (self.hasPathSum(root.left, summ - root.val) or
self.hasPathSum(root.right, summ - root.val))
| Solution |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0088_remove_monitor_slug_conditions.py | {
"start": 1298,
"end": 2647
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | docker__docker-py | tests/unit/models_networks_test.py | {
"start": 1298,
"end": 2176
} | class ____(unittest.TestCase):
def test_connect(self):
client = make_fake_client()
network = client.networks.get(FAKE_NETWORK_ID)
network.connect(FAKE_CONTAINER_ID)
client.api.connect_container_to_network.assert_called_once_with(
FAKE_CONTAINER_ID,
FAKE_NETWO... | NetworkTest |
python | pytest-dev__pytest | testing/test_assertrewrite.py | {
"start": 74664,
"end": 75514
} | class ____:
class Help:
def bound_method(self): # pragma: no cover
pass
def test_saferepr_bound_method(self):
"""saferepr() of a bound method should show only the method name"""
assert _saferepr(self.Help().bound_method) == "bound_method"
def test_saferepr_unbounded(se... | TestSafereprUnbounded |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/property11.py | {
"start": 510,
"end": 616
} | class ____:
@classmethod
@property
def prop1(cls: type[T]) -> type[T]:
return cls
| Class2 |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 20806,
"end": 21187
} | class ____(VOTableSpecWarning):
"""
The column fields as defined using ``FIELD`` elements do not match
those in the headers of the embedded FITS file. If ``verify`` is not
``'exception'``, the embedded FITS file will take precedence.
"""
message_template = (
"The fields defined in the ... | W19 |
python | mwaskom__seaborn | tests/_stats/test_counting.py | {
"start": 1237,
"end": 8131
} | class ____:
@pytest.fixture
def single_args(self):
groupby = GroupBy(["group"])
class Scale:
scale_type = "continuous"
return groupby, "x", {"x": Scale()}
@pytest.fixture
def triple_args(self):
groupby = GroupBy(["group", "a", "s"])
class Scale:... | TestHist |
python | doocs__leetcode | solution/1000-1099/1065.Index Pairs of a String/Solution.py | {
"start": 0,
"end": 252
} | class ____:
def indexPairs(self, text: str, words: List[str]) -> List[List[int]]:
words = set(words)
n = len(text)
return [
[i, j] for i in range(n) for j in range(i, n) if text[i : j + 1] in words
]
| Solution |
python | kamyu104__LeetCode-Solutions | Python/strange-printer-ii.py | {
"start": 2019,
"end": 3466
} | class ____(object):
def isPrintable(self, targetGrid):
"""
:type targetGrid: List[List[int]]
:rtype: bool
"""
VISITING, VISITED = range(2)
def has_cycle(adj, color, lookup):
lookup[color] = VISITING
for new_color in adj[color]:
... | Solution2 |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pycodestyle/E731.py | {
"start": 1919,
"end": 2250
} | class ____(Enum):
CELSIUS = (lambda deg_c: deg_c)
FAHRENHEIT = (lambda deg_c: deg_c * 9 / 5 + 32)
# Regression test for: https://github.com/astral-sh/ruff/issues/7141
def scope():
# E731
f = lambda: (
i := 1,
)
from dataclasses import dataclass
from typing import Callable
@dataclass
| TemperatureScales |
python | instagram__MonkeyType | tests/test_stubs.py | {
"start": 48964,
"end": 50802
} | class ____:
@pytest.mark.parametrize(
'anno',
[
inspect.Parameter.empty,
inspect.Signature.empty,
'not a type',
int,
],
)
def test_no_imports(self, anno):
"""We shouldn't import any builtins, non-types, or empty annos"""
... | TestGetImportsForAnnotation |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 505310,
"end": 506217
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for Commit."""
__schema__ = github_schema
__field_names__ = ("author_count", "edges", "nodes", "page_info", "total_count")
author_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="authorCount")
"""The total count of a... | ComparisonCommitConnection |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_privacy_urls.py | {
"start": 20835,
"end": 21354
} | class ____(PrivateUserProfileMixin, TestCase):
# Auth protected
default_status_code = 302
def setUp(self):
super().setUp()
self.response_data.update(
{
"/accounts/tokens/create/": {"status_code": 302},
"/accounts/tokens/delete/": {"status_code": ... | PrivateUserProfileUnauthAccessTest |
python | huggingface__transformers | tests/models/detr/test_modeling_detr.py | {
"start": 21967,
"end": 31106
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return DetrImageProcessor.from_pretrained("facebook/detr-resnet-50") if is_vision_available() else None
def test_inference_no_head(self):
model = DetrModel.from_pretrained("facebook/detr-resnet-50").to(torch_... | DetrModelIntegrationTestsTimmBackbone |
python | huggingface__transformers | src/transformers/models/d_fine/modeling_d_fine.py | {
"start": 40207,
"end": 44079
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the decoder of the model.
intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers... | DFineModelOutput |
python | ansible__ansible | test/lib/ansible_test/_internal/util.py | {
"start": 2770,
"end": 3317
} | class ____(enum.Enum):
"""The output stream to use when running a subprocess and redirecting/capturing stdout or stderr."""
ORIGINAL = enum.auto()
AUTO = enum.auto()
def get_buffer(self, original: t.BinaryIO) -> t.BinaryIO:
"""Return the correct output buffer to use, taking into account the gi... | OutputStream |
python | numba__numba | numba/core/types/containers.py | {
"start": 14474,
"end": 14594
} | class ____(BaseContainerIterator):
"""
Type class for list iterators.
"""
container_class = List
| ListIter |
python | realpython__materials | python-protocol/animals_v2.py | {
"start": 263,
"end": 524
} | class ____:
def __init__(self, name):
self.name = name
def eat(self):
print(f"{self.name} is eating.")
def drink(self):
print(f"{self.name} is drinking.")
def make_sound(self):
print(f"{self.name} is meowing.")
| Cat |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/dtrun3/package.py | {
"start": 217,
"end": 492
} | class ____(Package):
"""Simple package which acts as a run dependency"""
homepage = "http://www.example.com"
url = "http://www.example.com/dtrun3-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
depends_on("dtbuild3", type="build")
| Dtrun3 |
python | pypa__warehouse | tests/unit/rate_limiting/test_core.py | {
"start": 3355,
"end": 3590
} | class ____:
def test_basic(self):
limiter = DummyRateLimiter()
assert limiter.test()
assert limiter.hit()
assert limiter.clear() is None
assert limiter.resets_in() is None
| TestDummyRateLimiter |
python | readthedocs__readthedocs.org | readthedocs/organizations/views/public.py | {
"start": 1202,
"end": 1373
} | class ____(CheckOrganizationsEnabled, TemplateView):
"""Wrapper around `TemplateView` to check if organizations are enabled."""
# Organization
| OrganizationTemplateView |
python | wandb__wandb | wandb/sdk/artifacts/artifact_saver.py | {
"start": 1088,
"end": 9644
} | class ____:
_server_artifact: dict | None # TODO better define this dict
def __init__(
self,
api: InternalApi,
digest: str,
manifest_json: dict,
file_pusher: FilePusher,
is_user_created: bool = False,
) -> None:
self._api = api
self._file_pus... | ArtifactSaver |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol45.py | {
"start": 306,
"end": 382
} | class ____:
def __call__(self, item: T, /) -> T:
return item
| Impl1 |
python | joblib__joblib | joblib/test/test_parallel.py | {
"start": 2630,
"end": 23450
} | class ____(Exception):
"""An exception class with non trivial __init__"""
def __init__(self, a, b, c, d):
pass
def exception_raiser(x, custom_exception=False):
if x == 7:
raise (
MyExceptionWithFinickyInit("a", "b", "c", "d")
if custom_exception
else Va... | MyExceptionWithFinickyInit |
python | kamyu104__LeetCode-Solutions | Python/iterator-for-combination.py | {
"start": 63,
"end": 719
} | class ____(object):
def __init__(self, characters, combinationLength):
"""
:type characters: str
:type combinationLength: int
"""
self.__it = itertools.combinations(characters, combinationLength)
self.__curr = None
self.__last = characters[-combinationLength:... | CombinationIterator |
python | pytorch__pytorch | test/torch_np/test_basic.py | {
"start": 1428,
"end": 2381
} | class ____(TestCase):
"""Base for smoke tests of one-arg functions: (array_like) -> (array_like)
Accepts array_likes, torch.Tensors, w.ndarays; returns an ndarray
"""
@parametrize("func", one_arg_funcs)
def test_asarray_tensor(self, func):
t = torch.Tensor([[1.0, 2, 3], [4, 5, 6]])
... | TestOneArr |
python | getsentry__sentry | src/sentry/api/endpoints/project_rule_preview.py | {
"start": 2887,
"end": 2989
} | class ____(BaseGroupSerializerResponse):
inbox: InboxDetails
lastTriggered: int
| _PreviewResponse |
python | pypa__setuptools | setuptools/tests/test_windows_wrappers.py | {
"start": 788,
"end": 1894
} | class ____:
@classmethod
def prep_script(cls, template):
python_exe = subprocess.list2cmdline([sys.executable])
return template % locals()
@classmethod
def create_script(cls, tmpdir):
"""
Create a simple script, foo-script.py
Note that the script starts with a U... | WrapperTester |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 10751,
"end": 10830
} | class ____(BitwiseLogicOperation):
pass
@infer_global(operator.xor)
| BitwiseOr |
python | apache__airflow | airflow-core/src/airflow/triggers/testing.py | {
"start": 907,
"end": 1224
} | class ____(BaseTrigger):
"""
A trigger that always succeeds immediately.
Should only be used for testing.
"""
def serialize(self) -> tuple[str, dict[str, Any]]:
return ("airflow.triggers.testing.SuccessTrigger", {})
async def run(self):
yield TriggerEvent(True)
| SuccessTrigger |
python | TheAlgorithms__Python | scheduling/multi_level_feedback_queue.py | {
"start": 32,
"end": 592
} | class ____:
def __init__(self, process_name: str, arrival_time: int, burst_time: int) -> None:
self.process_name = process_name # process name
self.arrival_time = arrival_time # arrival time of the process
# completion time of finished process or last interrupted time
self.stop_tim... | Process |
python | openai__openai-python | src/openai/types/realtime/realtime_connect_params.py | {
"start": 202,
"end": 288
} | class ____(TypedDict, total=False):
call_id: str
model: str
| RealtimeConnectParams |
python | pymupdf__PyMuPDF | src/__init__.py | {
"start": 834593,
"end": 835582
} | class ____(mupdf.FzDevice2):
def __init__(self, result, layers):
super().__init__()
self.result = result
self.layers = layers
self.layer_name = ""
self.use_virtual_fill_path()
self.use_virtual_stroke_path()
self.use_virtual_fill_text()
self.use_virtual... | JM_new_bbox_device_Device |
python | django__django | tests/model_inheritance/tests.py | {
"start": 23301,
"end": 24316
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.grand_parent = GrandParent.objects.create(
email="grand_parent@example.com",
first_name="grand",
last_name="parent",
)
def test_unique(self):
grand_child = GrandChild(
emai... | InheritanceUniqueTests |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/resolvelib/resolvers.py | {
"start": 864,
"end": 1310
} | class ____(ResolverException):
def __init__(self, candidate, criterion):
super(InconsistentCandidate, self).__init__(candidate, criterion)
self.candidate = candidate
self.criterion = criterion
def __str__(self):
return "Provided candidate {!r} does not satisfy {}".format(
... | InconsistentCandidate |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typePrinter1.py | {
"start": 445,
"end": 586
} | class ____: ...
def func3(v: typePrinter2.IntOrStr | IntOrStr | None):
reveal_type(v, expected_text="int | str | IntOrStr | None")
| IntOrStr |
python | huggingface__transformers | src/transformers/models/hgnet_v2/modular_hgnet_v2.py | {
"start": 9107,
"end": 10188
} | class ____(RTDetrResNetConvLayer):
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: int,
stride: int = 1,
groups: int = 1,
activation: str = "relu",
use_learnable_affine_block: bool = False,
):
super().__init__(in_chann... | HGNetV2ConvLayer |
python | mozilla__bleach | bleach/_vendor/html5lib/_ihatexml.py | {
"start": 12711,
"end": 16728
} | class ____(object):
replacementRegexp = re.compile(r"U[\dA-F]{5,5}")
def __init__(self,
dropXmlnsLocalName=False,
dropXmlnsAttrNs=False,
preventDoubleDashComments=False,
preventDashAtCommentEnd=False,
replaceFormFeedCharacters... | InfosetFilter |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 672030,
"end": 672401
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("client_mutation_id", "project_column")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
project_column = sgqlc.types.Field("ProjectColumn", gra... | UpdateProjectColumnPayload |
python | pandas-dev__pandas | pandas/tests/indexes/timedeltas/test_indexing.py | {
"start": 11637,
"end": 12501
} | class ____:
def test_contains_nonunique(self):
# GH#9512
for vals in (
[0, 1, 0],
[0, 0, -1],
[0, -1, -1],
["00:01:00", "00:01:00", "00:02:00"],
["00:01:00", "00:01:00", "00:00:01"],
):
idx = TimedeltaIndex(vals)
... | TestContains |
python | huggingface__transformers | src/transformers/models/table_transformer/modeling_table_transformer.py | {
"start": 13606,
"end": 15435
} | class ____(nn.Module):
"""
This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
need paper, generalized to work on images.
"""
def __init__(self, embedding_dim=64, temperature=10000, normalize=False, scale=None):
super().__init_... | TableTransformerSinePositionEmbedding |
python | run-llama__llama_index | llama-index-core/llama_index/core/callbacks/schema.py | {
"start": 1417,
"end": 2923
} | class ____(str, Enum):
DOCUMENTS = "documents" # list of documents before parsing
CHUNKS = "chunks" # list of text chunks
NODES = "nodes" # list of nodes
PROMPT = "formatted_prompt" # formatted prompt sent to LLM
MESSAGES = "messages" # list of messages sent to LLM
COMPLETION = "completion"... | EventPayload |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink29.py | {
"start": 315,
"end": 1538
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink29.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Wor... | TestCompareXLSXFiles |
python | ray-project__ray | rllib/utils/exploration/soft_q.py | {
"start": 491,
"end": 2115
} | class ____(StochasticSampling):
"""Special case of StochasticSampling w/ Categorical and temperature param.
Returns a stochastic sample from a Categorical parameterized by the model
output divided by the temperature. Returns the argmax iff explore=False.
"""
def __init__(
self,
act... | SoftQ |
python | astropy__astropy | astropy/io/tests/safeio.py | {
"start": 77,
"end": 360
} | class ____(io.BufferedWriter):
"""File handle to intercept 0-byte writes."""
def write(self, buffer):
nbytes = super().write(buffer)
if nbytes == 0:
raise ValueError("This writer does not allow empty writes")
return nbytes
| CatchZeroByteWriter |
python | Pylons__pyramid | tests/test_path.py | {
"start": 1151,
"end": 2109
} | class ____(unittest.TestCase):
def _callFUT(self, *arg, **kw):
from pyramid.path import caller_module
return caller_module(*arg, **kw)
def test_it_level_1(self):
from . import test_path
result = self._callFUT(1)
self.assertEqual(result, test_path)
def test_it_leve... | TestCallerModule |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-service-now/llama_index/readers/service_now/event.py | {
"start": 2888,
"end": 3495
} | class ____(BaseEvent):
"""Event fired when an attachment is skipped."""
page_id: str = Field(description="ID of the parent page")
attachment_id: str = Field(description="ID of the attachment")
attachment_name: str = Field(description="Name of the attachment")
attachment_type: str = Field(descriptio... | SNOWKBAttachmentSkippedEvent |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/assignment3.py | {
"start": 1035,
"end": 1229
} | class ____(Protocol):
def __call__(self, x: int, y: dict[str, int]) -> int: ...
v1: Adder = lambda x, y: x + y["hi"]
reveal_type(v1, expected_text="(x: int, y: dict[str, int]) -> int")
| Adder |
python | apache__airflow | providers/http/src/airflow/providers/http/exceptions.py | {
"start": 973,
"end": 1084
} | class ____(AirflowException):
"""Exception raised for invalid HTTP methods in Http hook."""
| HttpMethodException |
python | dask__dask | dask/dataframe/dask_expr/_describe.py | {
"start": 2878,
"end": 3362
} | class ____(DescribeNumeric):
_parameters = ["frame", "split_every"]
def _lower(self):
frame = self.frame
vcounts = ValueCounts(frame, split_every=self.split_every, sort=True)
count_unique = Size(Filter(vcounts, vcounts > 0))
stats = [
count_unique,
frame.... | DescribeNonNumeric |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/enum14.py | {
"start": 288,
"end": 351
} | class ____(Enum):
# This should generate an error.
x: B.x
| B |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/cursor.py | {
"start": 52567,
"end": 53882
} | class ____(ResultMetaData):
__slots__ = ()
returns_rows = False
def _we_dont_return_rows(
self, err: Optional[BaseException] = None
) -> NoReturn:
raise exc.ResourceClosedError(
"This result object does not return rows. "
"It has been closed automatically."
... | _NoResultMetaData |
python | huggingface__transformers | src/transformers/models/kosmos2_5/image_processing_kosmos2_5.py | {
"start": 3291,
"end": 14966
} | class ____(BaseImageProcessor):
r"""
Constructs a Kosmos2_5 image processor.
Args:
do_convert_rgb (`bool`, *optional*, defaults to `True`):
Whether to convert the image to RGB.
do_normalize (`bool`, *optional*, defaults to `True`):
Whether to normalize the image. Can... | Kosmos2_5ImageProcessor |
python | huggingface__transformers | tests/models/audio_spectrogram_transformer/test_modeling_audio_spectrogram_transformer.py | {
"start": 8259,
"end": 9459
} | class ____(unittest.TestCase):
@cached_property
def default_feature_extractor(self):
return (
ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593")
if is_torchaudio_available()
else None
)
@slow
def test_inference_audio_classi... | ASTModelIntegrationTest |
python | huggingface__transformers | src/transformers/models/wav2vec2_bert/configuration_wav2vec2_bert.py | {
"start": 813,
"end": 18142
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Wav2Vec2BertModel`]. It is used to
instantiate an Wav2Vec2Bert model according to the specified arguments, defining the model architecture.
Instantiating a configuration with the defaults will yield a si... | Wav2Vec2BertConfig |
python | faif__python-patterns | patterns/other/hsm/hsm.py | {
"start": 2679,
"end": 3142
} | class ____:
def __init__(self, HierachicalStateMachine):
self.hsm = HierachicalStateMachine
def on_switchover(self):
raise UnsupportedTransition
def on_fault_trigger(self):
raise UnsupportedTransition
def on_diagnostics_failed(self):
raise UnsupportedTransition
de... | Unit |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 229661,
"end": 230454
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of EnqueuePullRequest"""
__schema__ = github_schema
__field_names__ = ("pull_request_id", "jump", "expected_head_oid", "client_mutation_id")
pull_request_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="pullRequestId")
"""The ... | EnqueuePullRequestInput |
python | spack__spack | lib/spack/spack/test/cray_manifest.py | {
"start": 1035,
"end": 1856
} | class ____:
def __init__(self, name, hash, prefix, version, arch, compiler, dependencies, parameters):
self.name = name
self.hash = hash
self.prefix = prefix
self.version = version
self.arch = arch
self.compiler = compiler
self.dependencies = dependencies
... | JsonSpecEntry |
python | scipy__scipy | scipy/stats/tests/test_hypotests.py | {
"start": 41078,
"end": 55995
} | class ____(_TestPythranFunc):
def setup_method(self):
self.dtypes = self.ALL_INTEGER + self.ALL_FLOAT
self.arguments = {0: (np.arange(10),
self.ALL_INTEGER + self.ALL_FLOAT),
1: (np.arange(10),
self.ALL_INTEGER + s... | TestSomersD |
python | huggingface__transformers | src/transformers/models/lfm2_moe/modular_lfm2_moe.py | {
"start": 6706,
"end": 9753
} | class ____(MixtralModel):
def __init__(self, config: Lfm2MoeConfig):
super().__init__(config)
self.pos_emb = Lfm2MoeRotaryEmbedding(config)
self.embedding_norm = Lfm2MoeRMSNorm(config.hidden_size, eps=config.norm_eps)
del self.norm
del self.rotary_emb
def forward(
... | Lfm2MoeModel |
python | pytorch__pytorch | torch/ao/quantization/pt2e/port_metadata_pass.py | {
"start": 5324,
"end": 9179
} | class ____(PassBase):
"""
Port metadata for nodes added by quantization flow.
For static quant these are:
- quantizer_per_tensor.default, dequantize_per_tensor.default
- quantizer_per_channel.default, dequantize_per_channel.default
For dynamic quant these are:
- choose_qparams.tensor
- q... | PortNodeMetaForQDQ |
python | walkccc__LeetCode | solutions/270. Closest Binary Search Tree Value/270.py | {
"start": 0,
"end": 550
} | class ____:
def closestValue(self, root: TreeNode | None, target: float) -> int:
# If target < root.val, search the left subtree.
if target < root.val and root.left:
left = self.closestValue(root.left, target)
if abs(left - target) <= abs(root.val - target):
return left
# If target > ... | Solution |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/netiq/tests.py | {
"start": 238,
"end": 969
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = NetIQProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{
"sub": "d4c094dd899ab0408fb9d4c094dd899a",
"acr": "secure/name/password/uri",
... | NetIQTests |
python | pytorch__pytorch | test/higher_order_ops/test_invoke_subgraph.py | {
"start": 8265,
"end": 11286
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[8]", L_y_: "f32[8]", L_mod_buffers_buf_: "f32[8]"):
l_x_ = L_x_
l_y_ = L_y_
l_mod_buffers_buf_ = L_mod_buffers_buf_
subgraph_0 = self.subgraph_0
invoke_subgraph = torch.ops.higher_order.invoke_subgraph(subgraph_0, 'su... | GraphModule |
python | ray-project__ray | rllib/utils/framework.py | {
"start": 7249,
"end": 7391
} | class ____:
def __init__(self) -> None:
self.Model = _FakeTfClassStub
# Fake classes under keras (e.g for tf.keras.Model)
| _KerasStub |
python | PrefectHQ__prefect | src/prefect/client/schemas/objects.py | {
"start": 24545,
"end": 24907
} | class ____(PrefectBaseModel):
"""
Base class for classes that represent inputs to task runs, which
could include, constants, parameters, or other task runs.
"""
model_config: ClassVar[ConfigDict] = ConfigDict(frozen=True)
if not TYPE_CHECKING:
# subclasses provide the concrete type for... | RunInput |
python | django__django | tests/serializers/models/data.py | {
"start": 3597,
"end": 3693
} | class ____(models.Model):
data = models.ManyToManyField("self", symmetrical=False)
| M2MSelfData |
python | dask__distributed | distributed/worker_state_machine.py | {
"start": 18963,
"end": 19032
} | class ____(StateMachineEvent):
__slots__ = ()
@dataclass
| PauseEvent |
python | django__django | tests/admin_checks/tests.py | {
"start": 1076,
"end": 1168
} | class ____(admin.ModelAdmin):
def check(self, **kwargs):
return ["error!"]
| MyAdmin |
python | scrapy__scrapy | tests/mockserver/http.py | {
"start": 785,
"end": 3149
} | class ____(resource.Resource):
def __init__(self):
super().__init__()
self.putChild(b"status", Status())
self.putChild(b"follow", Follow())
self.putChild(b"delay", Delay())
self.putChild(b"partial", Partial())
self.putChild(b"drop", Drop())
self.putChild(b"raw... | Root |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 5336,
"end": 9434
} | class ____(ABC):
@property
@abstractmethod
def action_type(self) -> ActionType:
pass
# Represents the mapping of a target field to a source field {target_field: FieldMapping}
field_mappings: ClassVar[dict[str, FieldMapping]] = {}
def __init__(self, action: dict[str, Any]):
self... | BaseActionTranslator |
python | streamlit__streamlit | lib/tests/streamlit/runtime/caching/cache_data_api_test.py | {
"start": 29427,
"end": 29866
} | class ____(CacheStorageManager):
"""A CacheStorageManager that always fails in check_context."""
def create(self, context: CacheStorageContext) -> CacheStorage:
return DummyCacheStorage()
def clear_all(self) -> None:
pass
def check_context(self, context: CacheStorageContext) -> None:
... | AlwaysFailingTestCacheStorageManager |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/llm_config.py | {
"start": 4216,
"end": 19350
} | class ____(BaseModelExtended):
runtime_env: Optional[Dict[str, Any]] = Field(
default=None,
description=(
"The runtime_env to use for the model deployment replica "
"and the engine workers."
),
)
model_loading_config: Union[Dict[str, Any], ModelLoadingConfig... | LLMConfig |
python | walkccc__LeetCode | solutions/3200. Maximum Height of a Triangle/3200.py | {
"start": 0,
"end": 941
} | class ____:
def maxHeightOfTriangle(self, red: int, blue: int) -> int:
return max(self._maxHeight(red, blue),
self._maxHeight(blue, red))
def _maxHeight(self, n1: int, n2: int) -> int:
"""
Returns the maximum height of a triangle with the odd levels having `n1`
balls and the even lev... | Solution |
python | readthedocs__readthedocs.org | readthedocs/projects/views/private.py | {
"start": 18780,
"end": 19398
} | class ____(ProjectAdminMixin, PrivateViewMixin):
model = ProjectRelationship
form_class = ProjectRelationshipForm
lookup_field = "child__slug"
lookup_url_kwarg = "subproject_slug"
def get_queryset(self):
self.project = self.get_project()
return self.model.objects.filter(parent=self.... | ProjectRelationshipMixin |
python | pytorch__pytorch | torch/export/dynamic_shapes.py | {
"start": 12348,
"end": 12487
} | class ____:
"""
This represents input tensor dimensions.
"""
t_id: int
dim: int
@dataclasses.dataclass
| _ConstraintTarget |
python | scrapy__scrapy | tests/test_loader.py | {
"start": 798,
"end": 871
} | class ____(ItemLoader):
default_item_class = SummaryItem
| NameItemLoader |
python | PrefectHQ__prefect | tests/server/models/test_flow_run_states.py | {
"start": 5069,
"end": 10562
} | class ____:
async def test_create_flow_run_state_succeeds(self, flow_run, session):
flow_run_state = (
await models.flow_runs.set_flow_run_state(
session=session,
flow_run_id=flow_run.id,
state=Running(),
)
).state
asser... | TestCreateFlowRunState |
python | keras-team__keras | keras/src/ops/linalg_test.py | {
"start": 6624,
"end": 11379
} | class ____(testing.TestCase):
def test_cholesky(self):
x = KerasTensor([4, 3, 3])
out = linalg.cholesky(x)
self.assertEqual(out.shape, (4, 3, 3))
x = KerasTensor([10, 20, 15])
with self.assertRaises(ValueError):
linalg.cholesky(x)
def test_cholesky_inverse(s... | LinalgOpsStaticShapeTest |
python | huggingface__transformers | src/transformers/models/glm4v/modular_glm4v.py | {
"start": 23031,
"end": 27469
} | class ____(Glm4RotaryEmbedding):
# Ignore copy
def forward(self, x, position_ids):
# In contrast to other models, GLM4V different position ids for the grids
# So we expand the inv_freq to shape (3, ...)
inv_freq_expanded = self.inv_freq[None, None, :, None].float().expand(3, position_ids... | Glm4vTextRotaryEmbedding |
python | openai__openai-python | src/openai/resources/files.py | {
"start": 29573,
"end": 30436
} | class ____:
def __init__(self, files: AsyncFiles) -> None:
self._files = files
self.create = async_to_streamed_response_wrapper(
files.create,
)
self.retrieve = async_to_streamed_response_wrapper(
files.retrieve,
)
self.list = async_to_streame... | AsyncFilesWithStreamingResponse |
python | aimacode__aima-python | reinforcement_learning4e.py | {
"start": 5692,
"end": 7880
} | class ____:
"""
[Figure 21.4]
The abstract class for a Passive (non-learning) agent that uses
temporal differences to learn utility estimates. Override update_state
method to convert percept to state and reward. The mdp being provided
should be an instance of a subclass of the MDP Class.
im... | PassiveTDAgent |
python | pytorch__pytorch | torch/_inductor/template_heuristics/triton.py | {
"start": 62582,
"end": 62861
} | class ____(MMTemplateConfigMixin):
"""
Ensure that we feed in has_int8_tensor=True
"""
def __init__(self) -> None:
super().__init__()
self.has_int8_tensor = True
# MMPlusMM specific mixin to avoid running _scale_mm_configs
| INT8MMTemplateConfigMixin |
python | tensorflow__tensorflow | tensorflow/python/tpu/tensor_tracer_report.py | {
"start": 7205,
"end": 7883
} | class ____(object):
"""Context manager for writing report file."""
def __init__(self, tt_parameters):
if not tt_parameters.report_file_path:
self._report_file = None
return
try:
self._report_file = gfile.Open(tt_parameters.report_file_path, 'w')
except IOError as e:
raise e
d... | OpenReportFile |
python | python__mypy | mypy/traverser.py | {
"start": 26198,
"end": 26733
} | class ____(TraverserVisitor):
def __init__(self) -> None:
self.found = False
def visit_return_stmt(self, o: ReturnStmt) -> None:
if o.expr is None or isinstance(o.expr, NameExpr) and o.expr.name == "None":
return
self.found = True
def has_return_statement(fdef: FuncBase) -... | ReturnSeeker |
python | wandb__wandb | tests/system_tests/test_artifacts/test_model_workflows.py | {
"start": 67,
"end": 2964
} | class ____:
def wait(self):
pass
def is_draft(self):
return False
def test_offline_link_artifact(user):
run = wandb.init(mode="offline")
with pytest.raises(NotImplementedError):
run.link_artifact(FakeArtifact(), "entity/project/portfolio", "latest")
run.finish()
def test... | FakeArtifact |
python | tensorflow__tensorflow | tensorflow/python/tools/print_selective_registration_header_test.py | {
"start": 2811,
"end": 10286
} | class ____(test.TestCase):
def setUp(self):
_, self.script_name = os.path.split(sys.argv[0])
def WriteGraphFiles(self, graphs):
fnames = []
for i, graph in enumerate(graphs):
fname = os.path.join(self.get_temp_dir(), 'graph%s.pb' % i)
with gfile.GFile(fname, 'wb') as f:
f.write(gra... | PrintOpFilegroupTest |
python | Pylons__pyramid | docs/tutorials/wiki/src/authorization/tutorial/models/__init__.py | {
"start": 321,
"end": 736
} | class ____(Persistent):
def __init__(self, data):
self.data = data
def appmaker(zodb_root):
if 'app_root' not in zodb_root:
app_root = Wiki()
frontpage = Page('This is the front page')
app_root['FrontPage'] = frontpage
frontpage.__name__ = 'FrontPage'
frontpage._... | Page |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_B.py | {
"start": 18535,
"end": 19715
} | class ____(Benchmark):
r"""
Bukin02 objective function.
The Bukin02 [1]_ global optimization problem is a multimodal minimization
problem defined as follows:
.. math::
f_{\text{Bukin02}}(x) = 100 (x_2^2 - 0.01x_1^2 + 1)
+ 0.01(x_1 + 10)^2
with :math:`x_1 \in [-15, -5], x_2 ... | Bukin02 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.