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 | PyCQA__pylint | pylint/checkers/symilar.py | {
"start": 4011,
"end": 5207
} | class ____:
"""The LinesChunk object computes and stores the hash of some consecutive stripped
lines of a lineset.
"""
__slots__ = ("_fileid", "_hash", "_index")
def __init__(self, fileid: str, num_line: int, *lines: Iterable[str]) -> None:
self._fileid: str = fileid
"""The name of... | LinesChunk |
python | django__django | tests/model_enums/tests.py | {
"start": 9445,
"end": 9652
} | class ____(ipaddress.IPv4Network, models.Choices):
LOOPBACK = "127.0.0.0/8", "Loopback"
LINK_LOCAL = "169.254.0.0/16", "Link-Local"
PRIVATE_USE_A = "10.0.0.0/8", "Private-Use (Class A)"
| IPv4Network |
python | Textualize__textual | docs/examples/styles/grid_size_both.py | {
"start": 100,
"end": 390
} | class ____(App):
CSS_PATH = "grid_size_both.tcss"
def compose(self):
yield Grid(
Label("1"),
Label("2"),
Label("3"),
Label("4"),
Label("5"),
)
if __name__ == "__main__":
app = MyApp()
app.run()
| MyApp |
python | huggingface__transformers | src/transformers/generation/candidate_generator.py | {
"start": 58466,
"end": 63937
} | class ____(AssistedCandidateGenerator):
"""
`CandidateGenerator` class to be used for assisted generation and speculative decoding. This class generates
candidates through the use of **the model itself**, exiting early. Can only be used with models that support early
exit, e.g., `facebook/layerskip-llam... | EarlyExitCandidateGenerator |
python | ray-project__ray | release/llm_tests/benchmark/locust.py | {
"start": 292,
"end": 2882
} | class ____:
"""
Usage Example:
```python
config = LoadTestConfig(
host="http://localhost:8000",
provider="vllm",
model="meta-llama/Meta-Llama-3.1-8B-Instruct",
api_key="NONE",
prompt_tokens=550,
max_tokens=150,
user... | LLMLoadTester |
python | numpy__numpy | numpy/ma/tests/test_core.py | {
"start": 99528,
"end": 104604
} | class ____:
# Test class for the application of ufuncs on MaskedArrays.
def _create_data(self):
# Base data definition.
return (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6),
array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),)
@pytest.fixture(autouse=True, sc... | TestUfuncs |
python | encode__django-rest-framework | tests/test_viewsets.py | {
"start": 1082,
"end": 2457
} | class ____(GenericViewSet):
queryset = Action.objects.all()
def list(self, request, *args, **kwargs):
response = Response()
response.view = self
return response
def retrieve(self, request, *args, **kwargs):
response = Response()
response.view = self
return r... | ActionViewSet |
python | huggingface__transformers | src/transformers/models/glm4_moe/modular_glm4_moe.py | {
"start": 12890,
"end": 13061
} | class ____(DeepseekV3ForCausalLM):
pass
__all__ = [
"Glm4MoeConfig",
"Glm4MoePreTrainedModel",
"Glm4MoeModel",
"Glm4MoeForCausalLM",
]
| Glm4MoeForCausalLM |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 191445,
"end": 199215
} | class ____(NopKernel):
"""
There isn't actually a real kernel for concat, we just change the
storage for the upstream data.
"""
@classmethod
def create(cls, inputs: Sequence[IRNode], dim: int) -> StorageBox:
"""
Create the concat kernel from inputs
"""
device = i... | ConcatKernel |
python | pytorch__pytorch | torch/ao/quantization/quantizer/x86_inductor_quantizer.py | {
"start": 13443,
"end": 14503
} | class ____:
r"""Configuration defining the current quantization mode for the quantizer.
All possible current quantization modes are listed below:
----------------------------------------------------------------------------------------------------------
| ... | _CurrentQuantizationMode |
python | pyca__cryptography | src/cryptography/hazmat/primitives/padding.py | {
"start": 1018,
"end": 1435
} | class ____:
def __init__(self, block_size: int):
_byte_padding_check(block_size)
self.block_size = block_size
def padder(self) -> PaddingContext:
return PKCS7PaddingContext(self.block_size)
def unpadder(self) -> PaddingContext:
return PKCS7UnpaddingContext(self.block_size)
... | PKCS7 |
python | sympy__sympy | sympy/utilities/autowrap.py | {
"start": 17636,
"end": 29225
} | class ____(CodeWrapper):
"""Wrapper that uses f2py"""
def __init__(self, *args, **kwargs):
ext_keys = ['include_dirs', 'library_dirs', 'libraries',
'extra_compile_args', 'extra_link_args']
msg = ('The compilation option kwarg {} is not supported with the f2py '
... | F2PyCodeWrapper |
python | huggingface__transformers | src/transformers/models/modernbert/modular_modernbert.py | {
"start": 1963,
"end": 16965
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ModernBertModel`]. It is used to instantiate an ModernBert
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a simila... | ModernBertConfig |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 23806,
"end": 23907
} | class ____(DagsterError):
"""Error raised by invalid metadata parameters."""
| DagsterInvalidMetadata |
python | getsentry__sentry | src/sentry/integrations/analytics.py | {
"start": 1643,
"end": 1809
} | class ____(analytics.Event):
provider: str | None
id: int
organization_id: int
@analytics.eventclass("integration.resolve.pr")
| IntegrationResolveCommitEvent |
python | joke2k__faker | faker/providers/automotive/ar_SA/__init__.py | {
"start": 59,
"end": 2274
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``ar_SA`` locale.
Sources:
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_Saudi_Arabia
.. |license_plate_en| replace::
:meth:`license_plate_en()`
"""
LICENSE_FORMAT_EN = "#### ???"
LICENSE_FORMAT... | Provider |
python | openai__openai-python | src/openai/types/beta/realtime/realtime_response_usage.py | {
"start": 800,
"end": 1541
} | class ____(BaseModel):
input_token_details: Optional[InputTokenDetails] = None
"""Details about the input tokens used in the Response."""
input_tokens: Optional[int] = None
"""
The number of input tokens used in the Response, including text and audio
tokens.
"""
output_token_details: O... | RealtimeResponseUsage |
python | kamyu104__LeetCode-Solutions | Python/longest-subsequence-with-decreasing-adjacent-difference.py | {
"start": 684,
"end": 1248
} | class ____(object):
def longestSubsequence(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
result = 2
mx = max(nums)
dp = [[0]*mx for _ in xrange(mx)]
for x in reversed(nums):
x -= 1
for nx in xrange(len(dp[x])):
... | Solution2 |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF012.py | {
"start": 1035,
"end": 1295
} | class ____(Struct):
mutable_default: list[int] = []
immutable_annotation: Sequence[int] = []
without_annotation = []
class_variable: ClassVar[list[int]] = []
final_variable: Final[list[int]] = []
from pydantic_settings import BaseSettings
| E |
python | astropy__astropy | astropy/io/ascii/core.py | {
"start": 6488,
"end": 6771
} | class ____(ImportError):
"""
Indicates that a dependency for table reading is not present.
An instance of this class is raised whenever an optional reader
with certain required dependencies cannot operate because of
an ImportError.
"""
| OptionalTableImportError |
python | donnemartin__interactive-coding-challenges | stacks_queues/stack_min/test_stack_min.py | {
"start": 18,
"end": 1244
} | class ____(unittest.TestCase):
def test_stack_min(self):
print('Test: Push on empty stack, non-empty stack')
stack = StackMin()
stack.push(5)
self.assertEqual(stack.peek(), 5)
self.assertEqual(stack.minimum(), 5)
stack.push(1)
self.assertEqual(stack.peek(), 1... | TestStackMin |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/trainingpeaks/tests.py | {
"start": 560,
"end": 2955
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = TrainingPeaksProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""{
"Id": 123456,
"FirstName": "John",
"LastName": "Doe",
"Email":... | TrainingPeaksTests |
python | getsentry__sentry | src/sentry/incidents/utils/types.py | {
"start": 387,
"end": 665
} | class ____:
"""
values has format:
{
"value": float,
"source_id": str,
"subscription_id": str,
"timestamp": datetime,
}
"""
entity: str
subscription_id: str
values: Any
timestamp: datetime
| AnomalyDetectionUpdate |
python | google__pytype | pytype/tools/traces/source.py | {
"start": 243,
"end": 626
} | class ____:
"""Base class for traces."""
op: str
symbol: Any
types: tuple[pytd.Node, ...]
def __new__(cls, op, symbol, types):
del op, symbol, types # unused
if cls is AbstractTrace:
raise TypeError("cannot instantiate AbstractTrace")
return super().__new__(cls)
def __repr__(self):
... | AbstractTrace |
python | jazzband__django-oauth-toolkit | tests/test_token_endpoint_cors.py | {
"start": 713,
"end": 6197
} | class ____(TestCase):
"""
Test that CORS headers can be managed by OAuthLib.
The objective is: http request 'Origin' header should be passed to OAuthLib
"""
factory = RequestFactory()
@classmethod
def setUpTestData(cls):
cls.test_user = UserModel.objects.create_user("test_user", "t... | TestTokenEndpointCors |
python | mlflow__mlflow | mlflow/tracing/utils/__init__.py | {
"start": 2057,
"end": 22755
} | class ____(json.JSONEncoder):
"""
Custom JSON encoder for serializing non-OpenTelemetry compatible objects in a trace or span.
Trace may contain types that require custom serialization logic, such as Pydantic models,
non-JSON-serializable types, etc.
"""
def default(self, obj):
try:
... | TraceJSONEncoder |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 20538,
"end": 21059
} | class ____(sgqlc.types.Enum):
"""Properties by which Enterprise Server installation connections can
be ordered.
Enumeration Choices:
* `CREATED_AT`: Order Enterprise Server installations by creation
time
* `CUSTOMER_NAME`: Order Enterprise Server installations by
customer name
* `H... | EnterpriseServerInstallationOrderField |
python | getsentry__sentry | tests/sentry/api/endpoints/test_project_alert_rule_task_details.py | {
"start": 379,
"end": 3937
} | class ____(APITestCase):
def setUp(self) -> None:
self.login_as(user=self.user)
team = self.create_team()
project1 = self.create_project(teams=[team], name="foo", fire_project_created=True)
self.create_project(teams=[team], name="bar", fire_project_created=True)
self.rule = s... | ProjectAlertRuleTaskDetailsTest |
python | sympy__sympy | sympy/codegen/ast.py | {
"start": 5419,
"end": 11601
} | class ____(CodegenAST):
""" Base class for the AST types.
Explanation
===========
Defining fields are set in ``_fields``. Attributes (defined in _fields)
are only allowed to contain instances of Basic (unless atomic, see
``String``). The arguments to ``__new__()`` correspond to the attributes ... | Token |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 112554,
"end": 112679
} | class ____:
xlWithinSheet = 1 # from enum XlSearchWithin
xlWithinWorkbook = 2 # from enum XlSearchWithin
| SearchWithin |
python | django__django | django/forms/widgets.py | {
"start": 12016,
"end": 12122
} | class ____(Input):
input_type = "email"
template_name = "django/forms/widgets/email.html"
| EmailInput |
python | doocs__leetcode | solution/1000-1099/1060.Missing Element in Sorted Array/Solution.py | {
"start": 0,
"end": 489
} | class ____:
def missingElement(self, nums: List[int], k: int) -> int:
def missing(i: int) -> int:
return nums[i] - nums[0] - i
n = len(nums)
if k > missing(n - 1):
return nums[n - 1] + k - missing(n - 1)
l, r = 0, n - 1
while l < r:
mid = ... | Solution |
python | mlflow__mlflow | mlflow/types/agent.py | {
"start": 2770,
"end": 3645
} | class ____(BaseModel):
"""
Format of a ChatAgent interface request.
Args:
messages: A list of :py:class:`ChatAgentMessage` that will be passed to the model.
context (:py:class:`ChatContext`): The context to be used in the chat endpoint. Includes
conversation_id and user_id. **Op... | ChatAgentRequest |
python | dagster-io__dagster | python_modules/dagster-pipes/dagster_pipes/__init__.py | {
"start": 25695,
"end": 26461
} | class ____(PipesLogWriter[T_LogChannel]):
"""Log writers which collects stdout and stderr of the current process should inherit from this class."""
@abstractmethod
def make_channel(
self, params: PipesParams, stream: Literal["stdout", "stderr"]
) -> T_LogChannel:
pass
@contextmanag... | PipesStdioLogWriter |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/schemas/run.py | {
"start": 366,
"end": 773
} | class ____(BaseModel):
"""Single run metadata model."""
id: str
status: DgApiRunStatus
created_at: float # Unix timestamp (seconds since epoch)
started_at: Optional[float] = None # Unix timestamp (seconds since epoch)
ended_at: Optional[float] = None # Unix timestamp (seconds since epoch)
... | DgApiRun |
python | PrefectHQ__prefect | src/prefect/server/schemas/graph.py | {
"start": 614,
"end": 914
} | class ____(PrefectBaseModel):
kind: Literal["flow-run", "task-run"]
id: UUID
label: str
state_type: StateType
start_time: DateTime
end_time: Optional[DateTime]
parents: List[Edge]
children: List[Edge]
encapsulating: List[Edge]
artifacts: List[GraphArtifact]
| Node |
python | huggingface__transformers | src/transformers/models/t5gemma/modeling_t5gemma.py | {
"start": 32754,
"end": 38123
} | class ____(T5GemmaPreTrainedModel):
_can_record_outputs = {
"attentions": OutputRecorder(T5GemmaSelfAttention, index=1),
"cross_attentions": OutputRecorder(T5GemmaCrossAttention, index=1),
"hidden_states": T5GemmaDecoderLayer,
}
def __init__(self, config):
super().__init__(c... | T5GemmaDecoder |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0037_add_htmlfile.py | {
"start": 121,
"end": 534
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0036_remove-auto-doctype"),
]
operations = [
migrations.CreateModel(
name="HTMLFile",
fields=[],
options={
"proxy": True,
"inde... | Migration |
python | jmcnamara__XlsxWriter | xlsxwriter/test/workbook/test_workbook01.py | {
"start": 343,
"end": 1702
} | class ____(unittest.TestCase):
"""
Test assembling a complete Workbook file.
"""
def test_assemble_xml_file(self):
"""Test writing a workbook with 1 worksheet."""
self.maxDiff = None
fh = StringIO()
workbook = Workbook()
workbook._set_filehandle(fh)
wo... | TestAssembleWorkbook |
python | huggingface__transformers | src/transformers/models/mobilevitv2/modeling_mobilevitv2.py | {
"start": 30039,
"end": 33703
} | class ____(MobileViTV2PreTrainedModel):
def __init__(self, config: MobileViTV2Config) -> None:
super().__init__(config)
self.num_labels = config.num_labels
self.mobilevitv2 = MobileViTV2Model(config, expand_output=False)
self.segmentation_head = MobileViTV2DeepLabV3(config)
... | MobileViTV2ForSemanticSegmentation |
python | getsentry__sentry | src/sentry/api/utils.py | {
"start": 2423,
"end": 18839
} | class ____(APIException):
status_code = HTTP_504_GATEWAY_TIMEOUT
def get_datetime_from_stats_period(
stats_period: str, now: datetime.datetime | None = None
) -> datetime.datetime:
if now is None:
now = timezone.now()
parsed_stats_period = parse_stats_period(stats_period)
if parsed_stats_p... | TimeoutException |
python | pyqtgraph__pyqtgraph | pyqtgraph/dockarea/Container.py | {
"start": 143,
"end": 3802
} | class ____(object):
#sigStretchChanged = QtCore.Signal() ## can't do this here; not a QObject.
def __init__(self, area):
object.__init__(self)
self.area = area
self._container = None
self._stretch = (10, 10)
self.stretches = weakref.WeakKeyDictionary()
... | Container |
python | pennersr__django-allauth | allauth/headless/contrib/rest_framework/authentication.py | {
"start": 1125,
"end": 1673
} | class ____(authentication.TokenAuthentication):
@property
def keyword(self) -> str:
"""
See: ``settings.HEADLESS_JWT_AUTHORIZATION_HEADER_SCHEME``.
"""
return app_settings.JWT_AUTHORIZATION_HEADER_SCHEME
def authenticate_credentials(self, key: str):
"""
Vali... | JWTTokenAuthentication |
python | spack__spack | lib/spack/spack/util/environment.py | {
"start": 14248,
"end": 14754
} | class ____(NameModifier):
def execute(self, env: MutableMapping[str, str]):
tty.debug(f"DeprioritizeSystemPaths: {self.name}", level=3)
environment_value = env.get(self.name, "")
directories = environment_value.split(self.separator) if environment_value else []
directories = depriori... | DeprioritizeSystemPaths |
python | encode__django-rest-framework | tests/browsable_api/serializers.py | {
"start": 102,
"end": 221
} | class ____(ModelSerializer):
class Meta:
model = BasicModelWithUsers
fields = '__all__'
| BasicSerializer |
python | ansible__ansible | lib/ansible/module_utils/facts/packages.py | {
"start": 3957,
"end": 4483
} | class ____(PkgMgr):
CLI = None # type: str | None
def __init__(self):
self._cli = None
super(CLIMgr, self).__init__()
def is_available(self, handle_exceptions=True):
found = False
try:
self._cli = get_bin_path(self.CLI)
found = True
except... | CLIMgr |
python | ray-project__ray | python/ray/data/tests/test_iceberg.py | {
"start": 50097,
"end": 52287
} | class ____:
"""Test various overwrite filter scenarios."""
@pytest.mark.parametrize(
"filter_expr,overwrite_col_c,expected_data",
[
# Filter matches nothing (behaves like append)
(
col("col_c") == 999,
[999, 999],
{
... | TestOverwriteScenarios |
python | django__django | tests/model_formsets/models.py | {
"start": 1611,
"end": 1833
} | class ____(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
created = models.DateField(editable=False)
def __str__(self):
return self.name
| AuthorMeeting |
python | google__jax | tests/debugging_primitives_test.py | {
"start": 35738,
"end": 37992
} | class ____(jtu.JaxTestCase):
def test_inspect_sharding_is_called_in_jit_sharded(self):
if jtu.is_cloud_tpu():
raise unittest.SkipTest("Inspect sharding is not supported on libtpu.")
is_called = False
def _cb(sd):
nonlocal is_called
is_called = True
self.assertIsInstance(sd, jax.... | InspectShardingTest |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 142186,
"end": 144453
} | class ____:
def test_sf(self):
# reference values were computed via the reference distribution, e.g.
# mp.dps = 100; LogLaplace(c=c).sf(x).
c = np.array([2.0, 3.0, 5.0])
x = np.array([1e-5, 1e10, 1e15])
ref = [0.99999999995, 5e-31, 5e-76]
assert_allclose(stats.loglap... | TestLogLaplace |
python | python__mypy | mypyc/transform/ir_transform.py | {
"start": 821,
"end": 6757
} | class ____(OpVisitor[Value | None]):
"""Identity transform.
Subclass and override to perform changes to IR.
Subclass IRTransform and override any OpVisitor visit_* methods
that perform any IR changes. The default implementations implement
an identity transform.
A visit method can return None ... | IRTransform |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Display.py | {
"start": 5530,
"end": 6183
} | class ____(CtrlNode):
"""Generates a plot curve from x/y data"""
nodeName = 'PlotCurve'
uiTemplate = [
('color', 'color'),
]
def __init__(self, name):
CtrlNode.__init__(self, name, terminals={
'x': {'io': 'in'},
'y': {'io': 'in'},
'plot': {'io... | PlotCurve |
python | jazzband__django-redis | django_redis/client/herd.py | {
"start": 529,
"end": 799
} | class ____:
"""
Dummy class for use as
marker for herded keys.
"""
pass
def _is_expired(x, herd_timeout: int) -> bool:
if x >= herd_timeout:
return True
val = x + random.randint(1, herd_timeout)
return val >= herd_timeout
| Marker |
python | huggingface__transformers | src/transformers/models/perceiver/modeling_perceiver.py | {
"start": 110381,
"end": 111212
} | class ____(nn.Module):
"""
Module to decode embeddings (for masked language modeling).
Args:
config ([`PerceiverConfig`]):
Model configuration.
"""
def __init__(self, config: PerceiverConfig) -> None:
super().__init__()
self.config = config
self.vocab_si... | PerceiverEmbeddingDecoder |
python | sqlalchemy__sqlalchemy | test/orm/test_deprecations.py | {
"start": 4685,
"end": 8170
} | class ____(QueryTest):
def test_get(self):
User = self.classes.User
s = fixture_session()
with assertions.expect_deprecated_20(query_get_dep):
assert s.query(User).get(19) is None
with assertions.expect_deprecated_20(query_get_dep):
u = s.query(User).get(7)
... | GetTest |
python | ray-project__ray | rllib/core/models/torch/encoder.py | {
"start": 1296,
"end": 2962
} | class ____(TorchModel, Encoder):
def __init__(self, config: MLPEncoderConfig) -> None:
TorchModel.__init__(self, config)
Encoder.__init__(self, config)
# Create the neural network.
self.net = TorchMLP(
input_dim=config.input_dims[0],
hidden_layer_dims=config.... | TorchMLPEncoder |
python | matplotlib__matplotlib | lib/matplotlib/gridspec.py | {
"start": 11812,
"end": 18346
} | class ____(GridSpecBase):
"""
A grid layout to place subplots within a figure.
The location of the grid cells is determined in a similar way to
`.SubplotParams` using *left*, *right*, *top*, *bottom*, *wspace*
and *hspace*.
Indexing a GridSpec instance returns a `.SubplotSpec`.
"""
def... | GridSpec |
python | numba__numba | numba/tests/test_ufuncs.py | {
"start": 59781,
"end": 60762
} | class ____(_LoopTypesTester):
_ufuncs = [np.left_shift]
_required_types = 'bBhHiIlLqQ'
_skip_types = 'fdFDmMO' + _LoopTypesTester._skip_types
def _arg_for_type(self, a_letter_type, index=0):
res = super(self.__class__, self)._arg_for_type(a_letter_type,
... | TestLoopTypesIntLeftShift |
python | walkccc__LeetCode | solutions/152. Maximum Product Subarray/152.py | {
"start": 0,
"end": 532
} | class ____:
def maxProduct(self, nums: list[int]) -> int:
ans = nums[0]
dpMin = nums[0] # the minimum so far
dpMax = nums[0] # the maximum so far
for i in range(1, len(nums)):
num = nums[i]
prevMin = dpMin # dpMin[i - 1]
prevMax = dpMax # dpMax[i - 1]
if num < 0:
d... | Solution |
python | django__django | tests/template_tests/filter_tests/test_title.py | {
"start": 573,
"end": 901
} | class ____(SimpleTestCase):
def test_title(self):
self.assertEqual(title("a nice title, isn't it?"), "A Nice Title, Isn't It?")
def test_unicode(self):
self.assertEqual(title("discoth\xe8que"), "Discoth\xe8que")
def test_non_string_input(self):
self.assertEqual(title(123), "123")
| FunctionTests |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_reflection.py | {
"start": 11183,
"end": 11435
} | class ____:
def __repr__(self):
return "☃"
def test_can_handle_unicode_repr():
def foo(x):
pass
assert repr_call(foo, [Snowman()], {}) == "foo(x=☃)"
assert repr_call(foo, [], {"x": Snowman()}) == "foo(x=☃)"
| BittySnowman |
python | scipy__scipy | scipy/fft/tests/test_helper.py | {
"start": 1171,
"end": 4091
} | class ____:
def test_next_fast_len(self, xp):
np.random.seed(1234)
def nums():
yield from range(1, 1000)
yield 2**5 * 3**5 * 4**5 + 1
for n in nums():
m = next_fast_len(n)
_assert_n_smooth(m, 11)
assert m == next_fast_len(n, Fals... | TestNextFastLen |
python | tornadoweb__tornado | tornado/test/util_test.py | {
"start": 6467,
"end": 7660
} | class ____(unittest.TestCase):
def test_no_inherit_future(self):
# Two files: the first has "from __future__ import annotations", and it executes the second
# which doesn't. The second file should not be affected by the first's __future__ imports.
#
# The annotations future became av... | ExecInTest |
python | PyCQA__pylint | tests/functional/b/broad_exception/broad_exception_raised_trystar.py | {
"start": 128,
"end": 1255
} | class ____(CustomBroadException):
pass
def exploding_apple(apple):
print(f"{apple} is about to explode")
raise Exception("{apple} exploded !") # [broad-exception-raised]
def raise_and_catch_star():
try:
raise Exception("Oh No!!") # [broad-exception-raised]
except* Exception as ex: # [... | CustomNarrowException |
python | wandb__wandb | wandb/sdk/wandb_config.py | {
"start": 469,
"end": 10164
} | class ____:
"""Config object.
Config objects are intended to hold all of the hyperparameters associated
with a wandb run and are saved with the run object when `wandb.init` is
called.
We recommend setting the config once when initializing your run by passing
the `config` parameter to `init`:
... | Config |
python | huggingface__transformers | src/transformers/generation/watermarking.py | {
"start": 2799,
"end": 11084
} | class ____:
r"""
Detector for detection of watermark generated text. The detector needs to be given the exact same settings that were
given during text generation to replicate the watermark greenlist generation and so detect the watermark. This includes
the correct device that was used during text gener... | WatermarkDetector |
python | crytic__slither | slither/printers/summary/variable_order.py | {
"start": 211,
"end": 1669
} | class ____(AbstractPrinter):
ARGUMENT = "variable-order"
HELP = "Print the storage order of the state variables"
WIKI = "https://github.com/trailofbits/slither/wiki/Printer-documentation#variable-order"
def output(self, _filename: str) -> Output:
"""
_filename is not used
Args... | VariableOrder |
python | fluentpython__example-code-2e | 24-class-metaprog/metabunch/nutshell3e/bunch_test.py | {
"start": 40,
"end": 861
} | class ____(Bunch):
""" A point has x and y coordinates, defaulting to 0.0,
and a color, defaulting to 'gray'—and nothing more,
except what Python and the metaclass conspire to add,
such as __init__ and __repr__
"""
x = 0.0
y = 0.0
color = 'gray'
def test_init_defaults():... | Point |
python | tox-dev__tox | src/tox/tox_env/python/pip/req/args.py | {
"start": 489,
"end": 2829
} | class ____(ArgumentParser):
def print_usage(self, file: _SupportsWrite[str] | None = None) -> None:
""" """
def exit(self, status: int = 0, message: str | None = None) -> NoReturn: # noqa: ARG002, PLR6301
message = "" if message is None else message
msg = message.lstrip(": ").rstrip()
... | _OurArgumentParser |
python | django__django | tests/admin_views/admin.py | {
"start": 3759,
"end": 3923
} | class ____(forms.ModelForm):
extra_form_field = forms.BooleanField(required=False)
class Meta:
fields = "__all__"
model = Article
| ArticleForm |
python | bokeh__bokeh | src/bokeh/core/property/descriptors.py | {
"start": 6048,
"end": 7265
} | class ____(AliasPropertyDescriptor[T]):
"""
"""
alias: DeprecatedAlias[T]
def __init__(self, name: str, alias: DeprecatedAlias[T]) -> None:
super().__init__(name, alias)
major, minor, patch = self.alias.since
since = f"{major}.{minor}.{patch}"
self.__doc__ = f"""\
Thi... | DeprecatedAliasPropertyDescriptor |
python | PrefectHQ__prefect | tests/cli/test_transfer.py | {
"start": 4793,
"end": 6614
} | class ____:
"""Test command line argument validation."""
@patch("prefect.cli.transfer.load_profiles")
def test_transfer_source_profile_not_found(self, mock_load_profiles: MagicMock):
"""Test transfer command fails when source profile doesn't exist."""
mock_load_profiles.return_value = Profi... | TestTransferArguments |
python | pytorch__pytorch | torch/fx/experimental/refinement_types.py | {
"start": 0,
"end": 451
} | class ____:
def __init__(self, lhs: object, rhs: object):
self.lhs = lhs
self.rhs = rhs
def __str__(self) -> str:
return f"{self.lhs} = {self.rhs}"
def __repr__(self) -> str:
return f"{self.lhs} = {self.rhs}"
def __eq__(self, other: object) -> bool:
if isinstan... | Equality |
python | pypa__pip | src/pip/_vendor/platformdirs/unix.py | {
"start": 441,
"end": 10458
} | class ____(PlatformDirsABC): # noqa: PLR0904
"""
On Unix/Linux, we follow the `XDG Basedir Spec <https://specifications.freedesktop.org/basedir-spec/basedir-spec-
latest.html>`_.
The spec allows overriding directories with environment variables. The examples shown are the default values,
alongside... | Unix |
python | dagster-io__dagster | examples/experimental/assets_yaml_dsl/assets_yaml_dsl/domain_specific_dsl/stocks_dsl.py | {
"start": 1210,
"end": 1254
} | class ____(NamedTuple):
days: int
| Forecast |
python | protocolbuffers__protobuf | python/google/protobuf/internal/message_listener.py | {
"start": 477,
"end": 1894
} | class ____(object):
"""Listens for modifications made to a message. Meant to be registered via
Message._SetListener().
Attributes:
dirty: If True, then calling Modified() would be a no-op. This can be
used to avoid these calls entirely in the common case.
"""
def Modified(self):
"""C... | MessageListener |
python | PyCQA__pylint | pylint/checkers/refactoring/implicit_booleaness_checker.py | {
"start": 714,
"end": 16768
} | class ____(checkers.BaseChecker):
"""Checks for incorrect usage of comparisons or len() inside conditions.
Incorrect usage of len()
Pep8 states:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
Yes: if not seq:
if seq:
No: if len(seq):... | ImplicitBooleanessChecker |
python | pytorch__pytorch | tools/gdb/pytorch-gdb.py | {
"start": 643,
"end": 1866
} | class ____(gdb.Command): # type: ignore[misc, no-any-unimported]
"""
Print a human readable representation of the given at::Tensor.
Usage: torch-tensor-repr EXP
at::Tensor instances do not have a C++ implementation of a repr method: in
pytorch, this is done by pure-Python code. As such, torch-tens... | TensorRepr |
python | django-import-export__django-import-export | import_export/results.py | {
"start": 339,
"end": 1186
} | class ____:
"""
Base class representing an Error arising from error during data import.
"""
def __init__(self, error, row=None, number=None):
"""
:param error: Instance of an Exception class.
:param row: The row as a dict of fields and values (optional).
:param number: T... | Error |
python | kamyu104__LeetCode-Solutions | Python/find-subarray-with-bitwise-or-closest-to-k.py | {
"start": 102,
"end": 853
} | class ____(object):
def __init__(self, n):
self.__l = 0
self.__n = n
self.__count = [0]*n
def __iadd__(self, num):
self.__l += 1
base = 1
for i in xrange(self.__n):
if num&base:
self.__count[i] += 1
base <<= 1
r... | BitCount |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/sqltypes.py | {
"start": 120411,
"end": 120597
} | class ____(Numeric[_N]):
"""The SQL DECIMAL type.
.. seealso::
:class:`_types.Numeric` - documentation for the base type.
"""
__visit_name__ = "DECIMAL"
| DECIMAL |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/dynamic.py | {
"start": 3528,
"end": 9285
} | class ____(_AbstractCollectionWriter[_T]):
"""A mixin that expects to be mixing in a Query class with
AbstractAppender.
"""
query_class: Optional[Type[Query[_T]]] = None
_order_by_clauses: Tuple[ColumnElement[Any], ...]
def __init__(
self, attr: _DynamicAttributeImpl, state: Instance... | _AppenderMixin |
python | rq__rq | rq/registry.py | {
"start": 778,
"end": 9055
} | class ____:
"""
Base implementation of a job registry, implemented in Redis sorted set.
Each job is stored as a key in the registry, scored by expiration time
(unix timestamp).
"""
job_class = Job
death_penalty_class = UnixSignalDeathPenalty
key_template = 'rq:registry:{0}'
def __i... | BaseRegistry |
python | plotly__plotly.py | plotly/graph_objs/funnelarea/_stream.py | {
"start": 233,
"end": 3526
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "funnelarea"
_path_str = "funnelarea.stream"
_valid_props = {"maxpoints", "token"}
@property
def maxpoints(self):
"""
Sets the maximum number of points to keep on the plots from an
incoming stream. If `maxpoints` is set... | Stream |
python | kamyu104__LeetCode-Solutions | Python/find-the-maximum-length-of-valid-subsequence-i.py | {
"start": 34,
"end": 447
} | class ____(object):
def maximumLength(self, nums):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
k = 2
result = 0
for i in xrange(k):
dp = [0]*k
for x in nums:
dp[x%k] = dp[(i-x)%k]+1
result ... | Solution |
python | viewflow__viewflow | viewflow/workflow/nodes/mixins.py | {
"start": 166,
"end": 734
} | class ____(object):
"""Mixin for an activation of node with NextNodeMixin."""
@Activation.status.transition(source=STATUS.DONE)
def create_next(self):
if self.flow_task._next:
data, seed = {}, None
if self.flow_task._task_data:
data = self.flow_task._task_dat... | NextNodeActivationMixin |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_cond_format21.py | {
"start": 345,
"end": 4898
} | class ____(unittest.TestCase):
"""
Test assembling a complete Worksheet file.
"""
def test_assemble_xml_file(self):
"""Test writing a worksheet with conditional formatting."""
self.maxDiff = None
fh = StringIO()
worksheet = Worksheet()
worksheet._set_filehandle... | TestAssembleWorksheet |
python | kamyu104__LeetCode-Solutions | Python/count-valid-paths-in-a-tree.py | {
"start": 2188,
"end": 3657
} | class ____(object):
def countPaths(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: int
"""
def linear_sieve_of_eratosthenes(n): # Time: O(n), Space: O(n)
primes = []
spf = [-1]*(n+1) # the smallest prime factor
... | Solution2 |
python | huggingface__transformers | src/transformers/activations.py | {
"start": 8001,
"end": 13245
} | class ____(nn.Module):
"""
Applies the xIELU activation function introduced in https://arxiv.org/abs/2411.13010
If the user has installed the nickjbrowning/XIELU wheel, we import xIELU CUDA
Otherwise, we emit a single warning and use xIELU Python
"""
def __init__(
self,
alpha_p... | XIELUActivation |
python | chroma-core__chroma | chromadb/api/types.py | {
"start": 57045,
"end": 57190
} | class ____(BaseModel):
"""Configuration for float inverted index."""
model_config = {"extra": "forbid"}
pass
| FloatInvertedIndexConfig |
python | tensorflow__tensorflow | tensorflow/python/ops/tensor_math_operator_overrides_test.py | {
"start": 907,
"end": 2080
} | class ____(test.TestCase):
def _test_mul_dispatch_factory(self, x, y, expected, name=None):
self.assertAllEqual(expected, tmoo._mul_dispatch_factory(x, y, name=name))
def testNonBooleanTensor(self):
x = constant_op.constant([1, 2, 3])
y = constant_op.constant([4, 5, 6])
expected = constant_op.cons... | SortTest |
python | joke2k__faker | tests/providers/test_bank.py | {
"start": 13044,
"end": 13505
} | class ____:
"""Test de_CH bank provider"""
def test_bban(self, faker, num_samples):
for _ in range(num_samples):
assert re.fullmatch(r"\d{17}", faker.bban())
def test_iban(self, faker, num_samples):
for _ in range(num_samples):
iban = faker.iban()
assert... | TestDeCh |
python | numba__numba | numba/core/ssa.py | {
"start": 7779,
"end": 8714
} | class ____(_BaseHandler):
"""Find all defs and uses of variable in each block
``states["label"]`` is a int; label of the current block
``states["defs"]`` is a Mapping[str, List[Tuple[ir.Assign, int]]]:
- a mapping of the name of the assignee variable to the assignment
IR node and the bloc... | _GatherDefsHandler |
python | python-pillow__Pillow | Tests/test_file_libtiff.py | {
"start": 1219,
"end": 48065
} | class ____(LibTiffTestCase):
def test_version(self) -> None:
version = features.version_codec("libtiff")
assert version is not None
assert re.search(r"\d+\.\d+\.\d+t?$", version)
def test_g4_tiff(self, tmp_path: Path) -> None:
"""Test the ordinary file path load path"""
... | TestFileLibTiff |
python | django__django | tests/admin_views/admin.py | {
"start": 9827,
"end": 11255
} | class ____(admin.ModelAdmin):
actions = ["mail_admin"]
action_form = MediaActionForm
def delete_queryset(self, request, queryset):
SubscriberAdmin.overridden = True
super().delete_queryset(request, queryset)
@admin.action
def mail_admin(self, request, selected):
EmailMessag... | SubscriberAdmin |
python | django__django | django/forms/fields.py | {
"start": 12682,
"end": 13959
} | class ____(IntegerField):
default_error_messages = {
"invalid": _("Enter a number."),
}
def to_python(self, value):
"""
Validate that float() can be called on the input. Return the result
of float() or None for empty values.
"""
value = super(IntegerField, se... | FloatField |
python | PrefectHQ__prefect | src/prefect/exceptions.py | {
"start": 10715,
"end": 10843
} | class ____(PrefectException):
"""
A base class for exceptions related to infrastructure blocks
"""
| InfrastructureError |
python | huggingface__transformers | src/transformers/models/git/configuration_git.py | {
"start": 4368,
"end": 9656
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GitModel`]. It is used to instantiate a GIT model
according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration... | GitConfig |
python | Lightning-AI__lightning | tests/tests_fabric/utilities/test_data.py | {
"start": 2915,
"end": 2962
} | class ____(DataLoader):
pass
| MyBaseDataLoader |
python | django__django | django/contrib/postgres/forms/hstore.py | {
"start": 173,
"end": 1787
} | class ____(forms.CharField):
"""
A field for HStore data which accepts dictionary JSON input.
"""
widget = forms.Textarea
default_error_messages = {
"invalid_json": _("Could not load JSON data."),
"invalid_format": _("Input must be a JSON dictionary."),
}
def prepare_value(... | HStoreField |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.