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 | RaRe-Technologies__gensim | gensim/test/test_fasttext.py | {
"start": 69951,
"end": 71742
} | class ____(unittest.TestCase):
"""
This class containts tests that check the following scenario:
+ create binary fastText file model1.bin using facebook_binary (FT)
+ load file model1.bin to variable `model`
+ save `model` to model2.bin using gensim
+ check if files model1.bin and model2.bin ar... | SaveFacebookByteIdentityTest |
python | nedbat__coveragepy | tests/test_data.py | {
"start": 38294,
"end": 38740
} | class ____(CoverageTest):
"""Tests of in-memory CoverageData."""
run_in_temp_dir = False
def test_updating(self) -> None:
# https://github.com/coveragepy/coveragepy/issues/1323
a = CoverageData(no_disk=True)
a.add_lines({"foo.py": [10, 20, 30]})
assert a.measured_files() ==... | NoDiskTest |
python | qdrant__qdrant-client | tests/congruence_tests/test_sparse_search.py | {
"start": 633,
"end": 13959
} | class ____:
__test__ = False
def __init__(self):
self.query_text = generate_random_sparse_vector(sparse_text_vector_size, density=0.3)
self.query_image = generate_random_sparse_vector(sparse_image_vector_size, density=0.2)
self.query_code = generate_random_sparse_vector(sparse_code_vect... | TestSimpleSparseSearcher |
python | getsentry__sentry | src/sentry/snuba/metrics/fields/base.py | {
"start": 9547,
"end": 10137
} | class ____(MetricObject):
"""
Represents a class where the metric object just encapsulates a string name identifier for a
metric
"""
def generate_metric_ids(self, projects: Sequence[Project], use_case_id: UseCaseID) -> set[int]:
return {resolve_weak(use_case_id, org_id_from_projects(project... | RawMetric |
python | joke2k__faker | faker/providers/date_time/da_DK/__init__.py | {
"start": 46,
"end": 771
} | class ____(DateTimeProvider):
DAY_NAMES = {
"0": "mandag",
"1": "tirsdag",
"2": "onsdag",
"3": "torsdag",
"4": "fredag",
"5": "lørdag",
"6": "søndag",
}
MONTH_NAMES = {
"01": "januar",
"02": "februar",
"03": "marts",
"0... | Provider |
python | huggingface__transformers | src/transformers/models/roberta/modeling_roberta.py | {
"start": 24313,
"end": 29744
} | class ____(RobertaPreTrainedModel):
_no_split_modules = ["RobertaEmbeddings", "RobertaLayer"]
def __init__(self, config, add_pooling_layer=True):
r"""
add_pooling_layer (bool, *optional*, defaults to `True`):
Whether to add a pooling layer
"""
super().__init__(config... | RobertaModel |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_axis03.py | {
"start": 315,
"end": 2173
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_axis03.xlsx")
self.ignore_elements = {"xl/charts/chart1.xml": ["<c:formatCode"]}
def test_create_file(self):
"""Test the cre... | TestCompareXLSXFiles |
python | google__jax | jax/experimental/roofline/roofline.py | {
"start": 2681,
"end": 4336
} | class ____:
flops: int = 0
unfused_flops: int = 0
ici_bytes: dict[str, int] = field(default_factory=dict)
ici_latency: dict[str, int] = field(default_factory=dict)
hbm_bytes: int = 0
peak_hbm_bytes: int = 0
unfused_hbm_bytes: int = 0
@classmethod
def zeros(cls) -> RooflineResult:
return cls()
... | RooflineResult |
python | django__django | tests/forms_tests/field_tests/test_slugfield.py | {
"start": 76,
"end": 981
} | class ____(SimpleTestCase):
def test_slugfield_normalization(self):
f = SlugField()
self.assertEqual(f.clean(" aa-bb-cc "), "aa-bb-cc")
def test_slugfield_unicode_normalization(self):
f = SlugField(allow_unicode=True)
self.assertEqual(f.clean("a"), "a")
self.assert... | SlugFieldTest |
python | google__pytype | pytype/abstract/_classes.py | {
"start": 13323,
"end": 25828
} | class ____(
_instance_base.SimpleValue, class_mixin.Class, mixin.LazyMembers
):
"""An abstract wrapper for PyTD class objects.
These are the abstract values for class objects that are described in PyTD.
Attributes:
cls: A pytd.Class
mro: Method resolution order. An iterable of BaseValue.
"""
de... | PyTDClass |
python | numba__numba | numba/cuda/tests/doc_examples/test_matmul.py | {
"start": 475,
"end": 6135
} | class ____(CUDATestCase):
"""
Text matrix multiplication using simple, shared memory/square, and shared
memory/nonsquare cases.
"""
def setUp(self):
# Prevent output from this test showing up when running the test suite
self._captured_stdout = captured_stdout()
self._capture... | TestMatMul |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 12740,
"end": 12856
} | class ____(OpcodeWithArg): # Acts as jump
_FLAGS = HAS_JABS | HAS_ARGUMENT | NO_NEXT
__slots__ = ()
| CONTINUE_LOOP |
python | crytic__slither | slither/core/declarations/function.py | {
"start": 3279,
"end": 73993
} | class ____(SourceMapping, metaclass=ABCMeta): # pylint: disable=too-many-public-methods
"""
Function class
"""
def __init__(self, compilation_unit: "SlitherCompilationUnit") -> None:
super().__init__()
self._internal_scope: List[str] = []
self._name: Optional[str] = None
... | Function |
python | doocs__leetcode | solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution2.py | {
"start": 0,
"end": 288
} | class ____:
def minCost(self, nums: List[int], cost: List[int]) -> int:
arr = sorted(zip(nums, cost))
mid = sum(cost) // 2
s = 0
for x, c in arr:
s += c
if s > mid:
return sum(abs(v - x) * c for v, c in arr)
| Solution |
python | Lightning-AI__lightning | tests/tests_pytorch/trainer/logging_/test_logger_connector.py | {
"start": 6080,
"end": 25161
} | class ____(BoringModel):
def __init__(self, not_supported):
super().__init__()
pl_module_hooks = get_members(LightningModule)
pl_module_hooks.difference_update({"log", "log_dict"})
pl_module_hooks.discard("configure_sharded_model")
# remove `nn.Module` hooks
module_ho... | HookedModel |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 14326,
"end": 14487
} | class ____(SuperMixin, OfflineTestCaseMixin, TestCase):
templates_dir = "test_block_super"
expected_hash = "817b5defb197"
| OfflineCompressBlockSuperTestCase |
python | viewflow__viewflow | tests/fsm/test_fsm__permissions.py | {
"start": 212,
"end": 604
} | class ____(object):
stage = State(ReviewState, default=ReviewState.NEW)
@stage.transition(
source=ReviewState.NEW,
target=ReviewState.REMOVED,
permission=this.can_remove_review
)
def remove(self):
pass
def can_remove_review(self, user):
return State.CONDITIO... | _Publication |
python | prabhupant__python-ds | data_structures/binary_trees/print_spiral_tree_two_stacks.py | {
"start": 0,
"end": 693
} | class ____:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def print_spiral(root):
s1 = []
s2 = []
s1.append(root)
while not len(s1) == 0 or not len(s2) == 0:
while not len(s1) == 0:
temp = s1.pop()
print(temp... | Node |
python | Lightning-AI__lightning | examples/pytorch/servable_module/production.py | {
"start": 1438,
"end": 2120
} | class ____(LightningDataModule):
transform = T.Compose([T.Resize(256), T.CenterCrop(224), T.ToTensor()])
def train_dataloader(self, *args, **kwargs):
trainset = torchvision.datasets.CIFAR10(root=DATASETS_PATH, train=True, download=True, transform=self.transform)
return torch.utils.data.DataLoad... | CIFAR10DataModule |
python | apache__avro | lang/py/avro/errors.py | {
"start": 3996,
"end": 4113
} | class ____(RuntimeError, AvroException):
"""An exception raised when incorrect arguments were passed."""
| UsageError |
python | sqlalchemy__sqlalchemy | test/dialect/mssql/test_reflection.py | {
"start": 38726,
"end": 43164
} | class ____(fixtures.TestBase):
def test_default_schema_name_not_interpreted_as_tokenized(self):
dialect = mssql.dialect()
dialect.server_version_info = base.MS_2014_VERSION
mock_connection = mock.Mock(scalar=lambda sql: "Jonah.The.Whale")
schema_name = dialect._get_default_schema_na... | OwnerPlusDBTest |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 191752,
"end": 191974
} | class ____:
def test_tail(self):
assert_almost_equal(stats.exponpow.cdf(1e-10, 2.), 1e-20)
assert_almost_equal(stats.exponpow.isf(stats.exponpow.sf(5, .8), .8),
5)
| TestExponpow |
python | astropy__astropy | astropy/io/ascii/basic.py | {
"start": 5268,
"end": 5415
} | class ____(BasicHeader):
"""
Reader for header of tables with tab separated header.
"""
splitter_class = TabHeaderSplitter
| TabHeader |
python | redis__redis-py | redis/commands/search/reducers.py | {
"start": 696,
"end": 908
} | class ____(FieldOnlyReducer):
"""
Calculates the smallest value in the given field within the group
"""
NAME = "MIN"
def __init__(self, field: str) -> None:
super().__init__(field)
| min |
python | crytic__slither | slither/slithir/operations/new_contract.py | {
"start": 512,
"end": 3981
} | class ____(Call, OperationWithLValue): # pylint: disable=too-many-instance-attributes
def __init__(
self,
contract_name: UserDefinedType,
lvalue: Union[TemporaryVariableSSA, TemporaryVariable],
names: Optional[List[str]] = None,
) -> None:
"""
#### Parameters
... | NewContract |
python | ansible__ansible | test/lib/ansible_test/_internal/core_ci.py | {
"start": 2558,
"end": 3331
} | class ____(Resource):
"""Details needed to request cloud credentials from Ansible Core CI."""
platform: str
def as_tuple(self) -> tuple[str, str, str, str]:
"""Return the resource as a tuple of platform, version, architecture and provider."""
return self.platform, '', '', self.platform
... | CloudResource |
python | realpython__materials | python-class/mro.py | {
"start": 61,
"end": 125
} | class ____(A):
def method(self):
print("B.method()")
| B |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/buffer.py | {
"start": 1759,
"end": 2077
} | class ____(enum.Enum):
# Reward signals
REWARDS = "rewards"
VALUE_ESTIMATES = "value_estimates"
RETURNS = "returns"
ADVANTAGE = "advantage"
BASELINES = "baselines"
AgentBufferKey = Union[
BufferKey, Tuple[ObservationKeyPrefix, int], Tuple[RewardSignalKeyPrefix, str]
]
| RewardSignalKeyPrefix |
python | PrefectHQ__prefect | src/prefect/_result_records.py | {
"start": 605,
"end": 2044
} | class ____(BaseModel):
"""
Metadata for a result record.
"""
storage_key: Optional[str] = Field(
default=None
) # optional for backwards compatibility
expiration: Optional[DateTime] = Field(default=None)
serializer: Serializer = Field(default_factory=PickleSerializer)
prefect_v... | ResultRecordMetadata |
python | pypa__build | src/build/_exceptions.py | {
"start": 175,
"end": 876
} | class ____(Exception):
"""
Exception raised when a backend operation fails.
"""
def __init__(
self,
exception: Exception,
description: str | None = None,
exc_info: tuple[type[BaseException], BaseException, types.TracebackType] | tuple[None, None, None] = (
No... | BuildBackendException |
python | pypa__warehouse | warehouse/oidc/services.py | {
"start": 3549,
"end": 14031
} | class ____:
def __init__(
self,
session: Session,
publisher: str,
issuer_url: str,
audience: str,
cache_url: str,
metrics: IMetricsService,
):
self.db = session
self.publisher = publisher
self.issuer_url = issuer_url
self.au... | OIDCPublisherService |
python | davidhalter__jedi | test/completion/pep0484_generic_passthroughs.py | {
"start": 3582,
"end": 4164
} | class ____(List):
def get_first(self):
return self[0]
#? str()
CustomList[str]()[0]
#? str()
CustomList[str]().get_first()
#? str()
typed_fully_generic_passthrough(CustomList[str]())[0]
#?
typed_list_generic_passthrough(CustomList[str])[0]
def typed_bound_type_implicit_any_generic_passthrough(x: TType)... | CustomList |
python | getsentry__sentry | src/sentry/sentry_apps/api/parsers/sentry_app_installation.py | {
"start": 166,
"end": 601
} | class ____(Serializer):
status = serializers.CharField()
def validate_status(self, new_status):
# can only set status to installed
if new_status != SentryAppInstallationStatus.INSTALLED_STR:
raise ValidationError(
f"Invalid value '{new_status}' for status. Valid valu... | SentryAppInstallationParser |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/nn_ops/xent_op_d9m_test.py | {
"start": 2830,
"end": 8291
} | class ____(xent_op_test_base.XentOpTestBase):
"""Test that SoftmaxCrossEntropyWithLogits operates reproducibly.
Inheriting from xent_op_test_base.XentTestBase ensures that regular op
functionality is correct when the deterministic code-path is selected.
Note that because nn_ops.softmax_cross_entropy_with_logi... | XentOpDeterministicTest |
python | numba__numba | numba/cuda/tests/cudapy/test_freevar.py | {
"start": 99,
"end": 745
} | class ____(CUDATestCase):
def test_freevar(self):
"""Make sure we can compile the following kernel with freevar reference
in arguments to shared.array
"""
from numba import float32
size = 1024
nbtype = float32
@cuda.jit("(float32[::1], intp)")
def fo... | TestFreeVar |
python | keras-team__keras | keras/src/backend/common/thread_safe_test.py | {
"start": 127,
"end": 908
} | class ____(testing.TestCase):
def test_is_thread_safe(self):
if backend.IS_THREAD_SAFE:
executor = concurrent.futures.ThreadPoolExecutor()
def sum(x, axis):
return ops.sum(x, axis=axis)
futures = []
for i in range(10000):
fut... | TestThreadSafe |
python | walkccc__LeetCode | solutions/3273. Minimum Amount of Damage Dealt to Bob/3273.py | {
"start": 60,
"end": 110
} | class ____:
damage: int
timeTakenDown: int
| Enemy |
python | ZoranPandovski__al-go-rithms | data_structures/Tree/Binary-tree/left-view.py | {
"start": 2505,
"end": 2623
} | class ____:
def __init__(self,val):
self.data = val
self.left = None
self.right = None
''' | Node |
python | pypa__build | tests/test_projectbuilder.py | {
"start": 1962,
"end": 2292
} | class ____(MockDistribution):
def read_text(self, filename):
if filename == 'METADATA':
return textwrap.dedent(
"""
Metadata-Version: 2.2
Name: requireless_dep
Version: 1.0.0
"""
).strip()
| RequirelessMockDistribution |
python | django__django | tests/template_tests/filter_tests/test_linebreaksbr.py | {
"start": 170,
"end": 1037
} | class ____(SimpleTestCase):
"""
The contents in "linebreaksbr" are escaped according to the current
autoescape setting.
"""
@setup({"linebreaksbr01": "{{ a|linebreaksbr }} {{ b|linebreaksbr }}"})
def test_linebreaksbr01(self):
output = self.engine.render_to_string(
"linebrea... | LinebreaksbrTests |
python | tensorflow__tensorflow | tensorflow/python/framework/composite_tensor_test.py | {
"start": 2967,
"end": 3143
} | class ____(CT):
_type_spec_class = CTSpec2
# CompositeTensors with a common supertype are considered to be the same
# structure by tf.nest (e.g. for assert_same_structure).
| CT2 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor26.py | {
"start": 256,
"end": 525
} | class ____(Generic[T, U]):
def __init__(self, t: T, u: U):
pass
def test1(self, ts: list[T], us: list[U]) -> None:
# This should generate an error.
x1: Test1[U, T] = Test1(us, ts)
x2: Test1[list[U], list[T]] = Test1(us, ts)
| Test1 |
python | numba__numba | numba/tests/doc_examples/test_parallel_chunksize.py | {
"start": 348,
"end": 4176
} | class ____(TestCase):
_numba_parallel_test_ = False
def setUp(self):
set_parallel_chunksize(0)
def tearDown(self):
set_parallel_chunksize(0)
def test_unbalanced_example(self):
with captured_stdout():
# magictoken.ex_unbalanced.begin
from numba import (... | ChunksizeExamplesTest |
python | huggingface__transformers | src/transformers/models/wav2vec2_conformer/modular_wav2vec2_conformer.py | {
"start": 28501,
"end": 28656
} | class ____(Wav2Vec2ForPreTraining):
def __init__(self, config: Wav2Vec2ConformerConfig):
super().__init__(config)
| Wav2Vec2ConformerForPreTraining |
python | aio-libs__aiohttp | aiohttp/tracing.py | {
"start": 7718,
"end": 7925
} | class ____:
"""Parameters sent by the `on_request_end` signal"""
method: str
url: URL
headers: "CIMultiDict[str]"
response: ClientResponse
@frozen_dataclass_decorator
| TraceRequestEndParams |
python | spyder-ide__spyder | spyder/plugins/completion/api.py | {
"start": 20970,
"end": 21176
} | class ____:
"""LSP text document saving action causes."""
MANUAL = 1
AFTER_DELAY = 2
FOCUS_OUT = 3
# ----------------------- INTERNAL CONSTANTS ------------------------
| TextDocumentSaveReason |
python | kennethreitz__tablib | src/tablib/packages/dbfpy/dbfnew.py | {
"start": 861,
"end": 2595
} | class ____:
"""Field definition.
This is a simple structure, which contains ``name``, ``type``,
``len``, ``dec`` and ``cls`` fields.
Objects also implement get/setitem magic functions, so fields
could be accessed via sequence interface, where 'name' has
index 0, 'type' index 1, 'len' index 2, ... | _FieldDefinition |
python | pandas-dev__pandas | asv_bench/benchmarks/reshape.py | {
"start": 231,
"end": 684
} | class ____:
params = ["float64", "Float64"]
param_names = ["dtype"]
def setup(self, dtype):
self.df = DataFrame(
np.random.randn(100_000, 3), columns=["A", "B", "C"], dtype=dtype
)
self.df["id1"] = pd.Series(np.random.randint(0, 10, 10000))
self.df["id2"] = pd.Se... | Melt |
python | django__django | tests/utils_tests/test_lazyobject.py | {
"start": 9537,
"end": 12312
} | class ____(LazyObjectTestCase):
# By inheriting from LazyObjectTestCase and redefining the lazy_wrap()
# method which all testcases use, we get to make sure all behaviors
# tested in the parent testcase also apply to SimpleLazyObject.
def lazy_wrap(self, wrapped_object):
return SimpleLazyObject(... | SimpleLazyObjectTestCase |
python | huggingface__transformers | tests/models/blip_2/test_modeling_blip_2.py | {
"start": 52347,
"end": 54762
} | class ____:
def __init__(self, parent, vision_kwargs=None, qformer_kwargs=None, is_training=True):
if vision_kwargs is None:
vision_kwargs = {}
if qformer_kwargs is None:
qformer_kwargs = {"use_qformer_text_input": True}
self.parent = parent
self.vision_model... | Blip2TextRetrievalModelTester |
python | google__jax | tests/pallas/pallas_test.py | {
"start": 32904,
"end": 42702
} | class ____(PallasBaseTest):
def test_pallas_call_kernel_args_mismatch(self):
a = np.arange(256, dtype=np.int32)
f = self.pallas_call(lambda x_ref: None, # Missing o_ref
out_shape=a)
with self.assertRaisesRegex(
TypeError,
"takes 1 positional argument but 2 were gi... | ApiErrorTest |
python | django__django | tests/forms_tests/field_tests/test_multiplechoicefield.py | {
"start": 137,
"end": 3755
} | class ____(SimpleTestCase):
def test_multiplechoicefield_1(self):
f = MultipleChoiceField(choices=[("1", "One"), ("2", "Two")])
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean("")
with self.assertRaisesMessage(ValidationError, "'This field is ... | MultipleChoiceFieldTest |
python | redis__redis-py | redis/commands/search/reducers.py | {
"start": 87,
"end": 310
} | class ____(Reducer):
"""See https://redis.io/docs/interact/search-and-query/search/aggregations/"""
def __init__(self, field: str) -> None:
super().__init__(field)
self._field = field
| FieldOnlyReducer |
python | django-guardian__django-guardian | example_project_custom_group/articles/models.py | {
"start": 1107,
"end": 1404
} | class ____(UserObjectPermissionAbstract):
class Meta(UserObjectPermissionAbstract.Meta):
abstract = False
indexes = [
*UserObjectPermissionAbstract.Meta.indexes,
models.Index(fields=["content_type", "object_pk", "user"]),
]
| BigUserObjectPermission |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_tool_text_editor_20250124_param.py | {
"start": 361,
"end": 1077
} | class ____(TypedDict, total=False):
name: Required[Literal["str_replace_editor"]]
"""Name of the tool.
This is how the tool will be called by the model and in `tool_use` blocks.
"""
type: Required[Literal["text_editor_20250124"]]
allowed_callers: List[Literal["direct", "code_execution_2025082... | BetaToolTextEditor20250124Param |
python | matplotlib__matplotlib | lib/matplotlib/sphinxext/figmpl_directive.py | {
"start": 864,
"end": 9308
} | class ____(Figure):
"""
Implements a directive to allow an optional hidpi image.
Meant to be used with the *plot_srcset* configuration option in conf.py,
and gets set in the TEMPLATE of plot_directive.py
e.g.::
.. figure-mpl:: plot_directive/some_plots-1.png
:alt: bar
... | FigureMpl |
python | fastai__fastai | fastai/tabular/core.py | {
"start": 10134,
"end": 10820
} | class ____(Tabular):
"A `Tabular` object with transforms"
def transform(self, cols, f, all_col=True):
if not all_col: cols = [c for c in cols if c in self.items.columns]
if len(cols) > 0: self[cols] = self[cols].transform(f)
# %% ../../nbs/40_tabular.core.ipynb 52
def _add_prop(cls, nm):
@p... | TabularPandas |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_ordered_dict.py | {
"start": 30035,
"end": 30497
} | class ____:
count = 0 # number of calls to __eq__
trigger = 1 # count value when to trigger side effect
def __eq__(self, other):
if self.__class__.count == self.__class__.trigger:
self.side_effect()
self.__class__.count += 1
return True
def __hash__(self):
... | _TriggerSideEffectOnEqual |
python | walkccc__LeetCode | solutions/1471. The k Strongest Values in an Array/1471.py | {
"start": 0,
"end": 357
} | class ____:
def getStrongest(self, arr: list[int], k: int) -> list[int]:
arr.sort()
ans = []
median = arr[(len(arr) - 1) // 2]
l = 0
r = len(arr) - 1
for _ in range(k):
if median - arr[l] > arr[r] - median:
ans.append(arr[l])
l -= 1
else:
ans.append(arr[r]... | Solution |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 118129,
"end": 119836
} | class ____(ASTBase):
def __init__(self, type: ASTType, init: ASTType) -> None:
assert type
self.type = type
self.init = init
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTTemplateParamConstrainedTypeWithInit):
return NotImplemented
retu... | ASTTemplateParamConstrainedTypeWithInit |
python | keon__algorithms | algorithms/tree/bst/height.py | {
"start": 974,
"end": 1441
} | class ____(unittest.TestCase):
def setUp(self):
self.tree = bst()
self.tree.insert(9)
self.tree.insert(6)
self.tree.insert(12)
self.tree.insert(3)
self.tree.insert(8)
self.tree.insert(10)
self.tree.insert(15)
self.tree.insert(7)
self.tr... | TestSuite |
python | django__django | tests/handlers/tests.py | {
"start": 10792,
"end": 11731
} | class ____(SimpleTestCase):
def test_get_script_name(self):
# Regression test for #23173
# Test first without PATH_INFO
script_name = get_script_name({"SCRIPT_URL": "/foobar/"})
self.assertEqual(script_name, "/foobar/")
script_name = get_script_name({"SCRIPT_URL": "/foobar/"... | ScriptNameTests |
python | pypa__virtualenv | src/virtualenv/util/lock.py | {
"start": 348,
"end": 1525
} | class ____(FileLock):
def __init__(self, lock_file) -> None:
parent = os.path.dirname(lock_file)
if not os.path.isdir(parent):
with suppress(OSError):
os.makedirs(parent)
super().__init__(lock_file)
self.count = 0
self.thread_safe = RLock()
d... | _CountedFileLock |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 46042,
"end": 46116
} | class ____(Exception):
pass
## Error Checking ##
| NVMLLibraryMismatchError |
python | django__django | tests/gis_tests/gdal_tests/test_driver.py | {
"start": 717,
"end": 1932
} | class ____(unittest.TestCase):
def test01_valid_driver(self):
"Testing valid GDAL/OGR Data Source Drivers."
for d in valid_drivers:
dr = Driver(d)
self.assertEqual(d, str(dr))
def test02_invalid_driver(self):
"Testing invalid GDAL/OGR Data Source Drivers."
... | DriverTest |
python | pytorch__pytorch | torch/fx/experimental/partitioner_utils.py | {
"start": 2426,
"end": 2710
} | class ____(NamedTuple):
# Sum of all nodes' memory latency on the critical path
mem_latency_sec: float
# Sum of all nodes' compute latency on the critical path
computer_latency_sec: float
# Latency of the critical path
overall_latency_sec: float
| PartitionLatency |
python | spyder-ide__spyder | spyder/config/user.py | {
"start": 35776,
"end": 35850
} | class ____(UserConfig):
"""Plugin configuration handler."""
| PluginConfig |
python | urllib3__urllib3 | test/test_util.py | {
"start": 37763,
"end": 43233
} | class ____:
"""Test utils that use an SSL backend."""
@pytest.mark.parametrize(
"candidate, requirements",
[
(None, ssl.CERT_REQUIRED),
(ssl.CERT_NONE, ssl.CERT_NONE),
(ssl.CERT_REQUIRED, ssl.CERT_REQUIRED),
("REQUIRED", ssl.CERT_REQUIRED),
... | TestUtilSSL |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol41.py | {
"start": 472,
"end": 556
} | class ____(Protocol):
def __buffer__(self, __flags: int) -> memoryview: ...
| Buffer |
python | mwaskom__seaborn | seaborn/_base.py | {
"start": 56600,
"end": 66543
} | class ____(UserString):
"""
Prevent comparisons elsewhere in the library from using the wrong name.
Errors are simple assertions because users should not be able to trigger
them. If that changes, they should be more verbose.
"""
# TODO we can replace this with typing.Literal on Python 3.8+
... | VariableType |
python | Netflix__metaflow | test/unit/inheritance/test_inheritance.py | {
"start": 4012,
"end": 6302
} | class ____:
"""Test FlowMutator in base class using config from derived class"""
def test_flow_completes(self, mutator_with_derived_config_run):
"""Test that flow completes successfully"""
assert mutator_with_derived_config_run.successful
assert mutator_with_derived_config_run.finished
... | TestMutatorWithDerivedConfig |
python | getsentry__sentry | tests/acceptance/test_create_organization.py | {
"start": 151,
"end": 1134
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user("foo@example.com")
self.login_as(self.user)
def test_simple(self) -> None:
settings.PRIVACY_URL = "https://sentry.io/privacy/"
settings.TERMS_URL = "https://sentry.io/te... | CreateOrganizationTest |
python | python__mypy | mypy/report.py | {
"start": 15074,
"end": 16577
} | class ____(AbstractReporter):
"""Exact line coverage reporter.
This reporter writes a JSON dictionary with one field 'lines' to
the file 'coverage.json' in the specified report directory. The
value of that field is a dictionary which associates to each
source file's absolute pathname the list of li... | LineCoverageReporter |
python | faif__python-patterns | patterns/structural/mvc.py | {
"start": 664,
"end": 1425
} | class ____(Model):
"""The Model is the data layer of the application."""
class Price(float):
"""A polymorphic way to pass a float with a particular
__str__ functionality."""
def __str__(self) -> str:
return f"{self:.2f}"
products = {
"milk": {"price": Price(1.5... | ProductModel |
python | pytorch__pytorch | torch/_inductor/autotune_process.py | {
"start": 29808,
"end": 32123
} | class ____(GPUDeviceBenchmarkMixin, BenchmarkRequest):
"""Benchmark request for CuteDSL (CUTLASS Python DSL) kernels."""
def __init__(
self,
kernel_name: str,
input_tensor_meta: Union[TensorMeta, list[TensorMeta]],
output_tensor_meta: Union[TensorMeta, list[TensorMeta]],
... | CuteDSLBenchmarkRequest |
python | doocs__leetcode | solution/0200-0299/0249.Group Shifted Strings/Solution.py | {
"start": 0,
"end": 418
} | class ____:
def groupStrings(self, strings: List[str]) -> List[List[str]]:
g = defaultdict(list)
for s in strings:
diff = ord(s[0]) - ord("a")
t = []
for c in s:
c = ord(c) - diff
if c < ord("a"):
c += 26
... | Solution |
python | django__django | django/contrib/auth/models.py | {
"start": 18126,
"end": 21304
} | class ____:
id = None
pk = None
username = ""
is_staff = False
is_active = False
is_superuser = False
_groups = EmptyManager(Group)
_user_permissions = EmptyManager(Permission)
def __str__(self):
return "AnonymousUser"
def __eq__(self, other):
return isinstance(... | AnonymousUser |
python | encode__django-rest-framework | tests/test_serializer.py | {
"start": 7640,
"end": 8669
} | class ____:
def test_non_field_error_validate_method(self):
class ExampleSerializer(serializers.Serializer):
char = serializers.CharField()
integer = serializers.IntegerField()
def validate(self, attrs):
raise serializers.ValidationError('Non field error'... | TestValidateMethod |
python | kamyu104__LeetCode-Solutions | Python/bulls-and-cows.py | {
"start": 651,
"end": 958
} | class ____(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
A = sum(imap(operator.eq, secret, guess))
B = sum((Counter(secret) & Counter(guess)).values()) - A
return "%dA%dB" % (A, B)
| Solution2 |
python | huggingface__transformers | src/transformers/convert_slow_tokenizer.py | {
"start": 36216,
"end": 36266
} | class ____(SpmConverter):
pass
| ReformerConverter |
python | great-expectations__great_expectations | great_expectations/render/components.py | {
"start": 6507,
"end": 7222
} | class ____(RenderedContent):
def __init__(self, content_block_type, styling=None) -> None:
self.content_block_type = content_block_type
if styling is None:
styling = {}
self.styling = styling
@override
def to_json_dict(self) -> dict[str, JSONValues]:
"""Returns a... | RenderedComponentContent |
python | ansible__ansible | lib/ansible/plugins/strategy/linear.py | {
"start": 2025,
"end": 17713
} | class ____(StrategyBase):
def _get_next_task_lockstep(self, hosts: list[Host], iterator: PlayIterator) -> list[tuple[Host, Task]]:
"""
Returns a list of (host, task) tuples, where the task may
be a noop task to keep the iterator in lock step across
all hosts.
"""
st... | StrategyModule |
python | langchain-ai__langchain | libs/partners/anthropic/tests/integration_tests/test_chat_models.py | {
"start": 31608,
"end": 35772
} | class ____(TypedDict):
"""Person data as a TypedDict."""
name: str
age: int
nicknames: list[str] | None
@pytest.mark.parametrize("schema", [Person, Person.model_json_schema(), PersonDict])
def test_response_format(schema: dict | type) -> None:
model = ChatAnthropic(
model="claude-sonnet-4... | PersonDict |
python | keras-team__keras | keras/src/ops/image.py | {
"start": 31612,
"end": 35050
} | class ____(Operation):
def __init__(self, order, fill_mode="constant", fill_value=0, *, name=None):
super().__init__(name=name)
self.order = order
self.fill_mode = fill_mode
self.fill_value = fill_value
def call(self, inputs, coordinates):
return backend.image.map_coordi... | MapCoordinates |
python | sympy__sympy | sympy/series/sequences.py | {
"start": 12320,
"end": 13279
} | class ____(SeqBase):
"""Sequence expression class.
Various sequences should inherit from this class.
Examples
========
>>> from sympy.series.sequences import SeqExpr
>>> from sympy.abc import x
>>> from sympy import Tuple
>>> s = SeqExpr(Tuple(1, 2, 3), Tuple(x, 0, 10))
>>> s.gen
... | SeqExpr |
python | protocolbuffers__protobuf | python/google/protobuf/internal/python_message.py | {
"start": 24938,
"end": 55685
} | class ____(property):
__slots__ = ('DESCRIPTOR',)
def __init__(self, descriptor, getter, setter, doc):
property.__init__(self, getter, setter, doc=doc)
self.DESCRIPTOR = descriptor
def _AddPropertiesForRepeatedField(field, cls):
"""Adds a public property for a "repeated" protocol message field. Client... | _FieldProperty |
python | apache__airflow | providers/openlineage/src/airflow/providers/openlineage/utils/utils.py | {
"start": 30468,
"end": 32780
} | class ____(InfoJsonEncodable):
"""Defines encoding BaseOperator/AbstractOperator object to JSON."""
renames = {
"_BaseOperator__from_mapped": "mapped",
"_downstream_task_ids": "downstream_task_ids",
"_upstream_task_ids": "upstream_task_ids",
"_is_setup": "is_setup",
"_is... | TaskInfo |
python | django__django | tests/responses/test_cookie.py | {
"start": 317,
"end": 5274
} | class ____(SimpleTestCase):
def test_near_expiration(self):
"""Cookie will expire when a near expiration time is provided."""
response = HttpResponse()
# There's a timing weakness in this test; The expected result for
# max-age requires that there be a very slight difference between ... | SetCookieTests |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 546827,
"end": 547241
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("CreatedCommitContribution... | CreatedCommitContributionEdge |
python | pydantic__pydantic | pydantic/functional_validators.py | {
"start": 9664,
"end": 18831
} | class ____:
"""!!! abstract "Usage Documentation"
[field *wrap* validators](../concepts/validators.md#field-wrap-validator)
A metadata class that indicates that a validation should be applied **around** the inner validation logic.
Attributes:
func: The validator function.
json_sche... | WrapValidator |
python | walkccc__LeetCode | solutions/1044. Longest Duplicate Substring/1044.py | {
"start": 0,
"end": 1288
} | class ____:
def longestDupSubstring(self, s: str) -> str:
BASE = 26
HASH = 1_000_000_007
bestStart = -1
l = 1
r = len(s)
def val(c: str) -> int:
return ord(c) - ord('a')
# k := the length of the substring to be hashed
def getStart(k: int) -> int | None:
maxPow = pow(BASE,... | Solution |
python | kamyu104__LeetCode-Solutions | Python/minimum-steps-to-convert-string-with-operations.py | {
"start": 68,
"end": 1501
} | class ____(object):
def minOperations(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
n = len(word1)
dp = [[0]*n for _ in xrange(n)]
for i in xrange(2*n-1):
cnt = collections.defaultdict(int)
curr = 1 ... | Solution |
python | Lightning-AI__lightning | src/lightning/fabric/strategies/model_parallel.py | {
"start": 2579,
"end": 14057
} | class ____(ParallelStrategy):
"""Enables user-defined parallelism applied to a model.
.. warning:: This is an :ref:`experimental <versioning:Experimental API>` feature.
Currently supports up to 2D parallelism. Specifically, it supports the combination of
Fully Sharded Data-Parallel 2 (FSDP2) with Ten... | ModelParallelStrategy |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/auth_manager/avp/test_facade.py | {
"start": 2053,
"end": 13079
} | class ____:
def test_avp_client(self, facade):
assert hasattr(facade, "avp_client")
def test_avp_policy_store_id(self, facade):
assert hasattr(facade, "avp_policy_store_id")
@pytest.mark.parametrize(
("entity_id", "context", "user", "expected_entities", "expected_context", "avp_res... | TestAwsAuthManagerAmazonVerifiedPermissionsFacade |
python | getsentry__sentry | tests/sentry/explore/endpoints/test_explore_saved_query_starred.py | {
"start": 175,
"end": 2223
} | class ____(APITestCase, SnubaTestCase):
feature_name = "organizations:visibility-explore-view"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.org = self.create_organization(owner=self.user)
self.project_ids = [
self.create_project(organiz... | ExploreSavedQueryStarredTest |
python | numba__numba | numba/tests/npyufunc/test_vectorize_decor.py | {
"start": 461,
"end": 2220
} | class ____(object):
target = None
wrapper = None
funcs = {
'func1': sinc,
'func2': scaled_sinc,
'func3': vector_add,
}
@classmethod
def _run_and_compare(cls, func, sig, A, *args, **kwargs):
if cls.wrapper is not None:
func = cls.wrapper(func)
... | BaseVectorizeDecor |
python | keras-team__keras | benchmarks/model_benchmark/benchmark_utils.py | {
"start": 28,
"end": 790
} | class ____(keras.callbacks.Callback):
def __init__(self, start_batch=1, stop_batch=None):
self.start_batch = start_batch
self.stop_batch = stop_batch
# Store the throughput of each epoch.
self.state = {"throughput": []}
def on_train_batch_begin(self, batch, logs=None):
... | BenchmarkMetricsCallback |
python | scrapy__scrapy | scrapy/robotstxt.py | {
"start": 3686,
"end": 4342
} | class ____(RobotParser):
def __init__(self, robotstxt_body: bytes, spider: Spider | None):
self.spider: Spider | None = spider
body_decoded = decode_robotstxt(robotstxt_body, spider)
self.rp = Protego.parse(body_decoded)
@classmethod
def from_crawler(cls, crawler: Crawler, robotstxt... | ProtegoRobotParser |
python | gevent__gevent | src/gevent/tests/test__example_wsgiserver_ssl.py | {
"start": 200,
"end": 649
} | class ____(test__example_wsgiserver.Test_wsgiserver):
example = 'wsgiserver_ssl.py'
URL = 'https://%s:8443' % (params.DEFAULT_LOCAL_HOST_ADDR,)
PORT = 8443
_use_ssl = True
if hasattr(ssl, '_create_unverified_context'):
# Disable verification for our self-signed cert
# on Python >= 2... | Test_wsgiserver_ssl |
python | tensorflow__tensorflow | tensorflow/python/data/ops/dataset_ops.py | {
"start": 195794,
"end": 198485
} | class ____(resource_lib.CapturableResource):
"""Allows export of functions capturing a Dataset in SavedModels.
When saving a SavedModel, `tf.saved_model.save` traverses the object
graph. Since Datasets reference _VariantTracker objects, that traversal will
find a _VariantTracker for each Dataset and so know ho... | _VariantTracker |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.