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 | pandas-dev__pandas | pandas/tests/series/methods/test_dtypes.py | {
"start": 21,
"end": 209
} | class ____:
def test_dtype(self, datetime_series):
assert datetime_series.dtype == np.dtype("float64")
assert datetime_series.dtypes == np.dtype("float64")
| TestSeriesDtypes |
python | huggingface__transformers | src/transformers/models/vit/modeling_vit.py | {
"start": 12200,
"end": 12720
} | class ____(nn.Module):
def __init__(self, config: ViTConfig):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch... | ViTOutput |
python | falconry__falcon | tests/test_before_hooks.py | {
"start": 12740,
"end": 15207
} | class ____(PiggybackingCollection):
@falcon.before(header_hook)
async def on_post_collection(self, req, resp):
self._sequence += 1
itemid = self._sequence
doc = await req.get_media()
self._items[itemid] = dict(doc, itemid=itemid)
resp.location = f'/items/{itemid}'
... | PiggybackingCollectionAsync |
python | huggingface__transformers | src/transformers/convert_slow_tokenizer.py | {
"start": 36266,
"end": 37481
} | class ____(SpmConverter):
# Inspired from AlbertConverter
def normalizer(self, proto):
list_normalizers = [
normalizers.Replace("``", '"'),
normalizers.Replace("''", '"'),
normalizers.Replace(Regex(" {2,}"), " "),
]
if not self.original_tokenizer.keep_... | RemBertConverter |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/conjecture/shrinking/floats.py | {
"start": 716,
"end": 4147
} | class ____(Shrinker):
def setup(self):
self.debugging_enabled = True
def make_canonical(self, f):
if math.isnan(f):
# Distinguish different NaN bit patterns, while making each equal to itself.
# Wrap in tuple to avoid potential collision with (huge) finite floats.
... | Float |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/property_with_parameters.py | {
"start": 102,
"end": 494
} | class ____:
@property
def attribute(self, param, param1): # [property-with-parameters]
return param + param1
@property
def attribute_keyword_only(self, *, param, param1): # [property-with-parameters]
return param + param1
@property
def attribute_positional_only(self, param, p... | Cls |
python | getsentry__sentry | src/sentry/utils/sdk_crashes/sdk_crash_detection_config.py | {
"start": 1447,
"end": 3206
} | class ____:
"""The SDK crash detection configuration per SDK."""
"""The name of the SDK to detect crashes for."""
sdk_name: SdkName
"""The project to save the detected SDK crashes to"""
project_id: int
"""The percentage of events to sample. 0.0 = 0%, 0.5 = 50% 1.0 = 100%."""
sample_rate: fl... | SDKCrashDetectionConfig |
python | Farama-Foundation__Gymnasium | gymnasium/envs/mujoco/inverted_double_pendulum_v4.py | {
"start": 260,
"end": 2179
} | class ____(MujocoEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
"rgbd_tuple",
],
"render_fps": 20,
}
def __init__(self, **kwargs):
observation_space = Box(low=-np.inf, high=np.inf, sha... | InvertedDoublePendulumEnv |
python | pytest-dev__pytest | testing/plugins_integration/pytest_rerunfailures_integration.py | {
"start": 54,
"end": 304
} | class ____(unittest.TestCase):
first_time = True
def test_fail_the_first_time(self) -> None:
"""Regression test for issue #12424."""
if self.first_time:
type(self).first_time = False
self.fail()
| MyTestCase |
python | facebook__pyre-check | client/coverage_data.py | {
"start": 17390,
"end": 17649
} | class ____(json_mixins.SnakeCaseAndExcludeJsonMixin):
kind: EmptyContainerKind
location: Location
def _matches_names(targets: Sequence[libcst.AssignTarget]) -> bool:
return all(isinstance(t.target, libcst.Name) for t in targets)
| EmptyContainerInfo |
python | PrefectHQ__prefect | src/integrations/prefect-aws/tests/experimental/test_bundles.py | {
"start": 12391,
"end": 16704
} | class ____:
def test_execute_bundle_from_s3(
self, mock_s3_client: MagicMock, mock_bundle_data: dict[str, Any]
):
"""Test execution of a bundle from S3."""
def mock_download_file(bucket: str, key: str, filename: str):
Path(filename).write_text(json.dumps(mock_bundle_data))
... | TestExecuteBundle |
python | PrefectHQ__prefect | src/prefect/server/schemas/states.py | {
"start": 1207,
"end": 1980
} | class ____(PrefectBaseModel):
COMPLETED: int = Field(default=0)
PENDING: int = Field(default=0)
RUNNING: int = Field(default=0)
FAILED: int = Field(default=0)
CANCELLED: int = Field(default=0)
CRASHED: int = Field(default=0)
PAUSED: int = Field(default=0)
CANCELLING: int = Field(default=... | CountByState |
python | walkccc__LeetCode | solutions/115. Distinct Subsequences/115-2.py | {
"start": 0,
"end": 264
} | class ____:
def numDistinct(self, s: str, t: str) -> int:
m = len(s)
n = len(t)
dp = [1] + [0] * n
for i in range(1, m + 1):
for j in range(n, 1 - 1, -1):
if s[i - 1] == t[j - 1]:
dp[j] += dp[j - 1]
return dp[n]
| Solution |
python | walkccc__LeetCode | solutions/775. Global and Local Inversions/775.py | {
"start": 0,
"end": 262
} | class ____:
def isIdealPermutation(self, nums: list[int]) -> bool:
mx = -1 # the number that is most likely > nums[i + 2]
for i in range(len(nums) - 2):
mx = max(mx, nums[i])
if mx > nums[i + 2]:
return False
return True
| Solution |
python | getsentry__sentry | tests/sentry/integrations/api/endpoints/test_organization_integration_channel_validate.py | {
"start": 2385,
"end": 4836
} | class ____(BaseChannelValidateTest):
def setUp(self):
super().setUp()
self.integration = self.create_integration(
organization=self.organization,
provider="discord",
name="Discord Server",
external_id="1234567890",
)
@patch(
"sentr... | DiscordChannelValidateTest |
python | pypa__setuptools | setuptools/_distutils/errors.py | {
"start": 1670,
"end": 2130
} | class ____(DistutilsError):
"""Syntactic/semantic errors in command options, such as use of
mutually conflicting options, or inconsistent options,
badly-spelled values, etc. No distinction is made between option
values originating in the setup script, the command line, config
files, or what-have-yo... | DistutilsOptionError |
python | pytorch__pytorch | tools/experimental/torchfuzz/codegen.py | {
"start": 15861,
"end": 27512
} | class ____(FuzzTemplate):
def __init__(self):
from torchfuzz.checks import EagerVsFullGraphDynamicCompileCheck
super().__init__(
supported_ops=[
"torch.ops.aten.item",
"torch.ops.aten.nonzero",
"torch.ops.aten.masked_select",
... | UnbackedFuzzTemplate |
python | numba__numba | numba/tests/test_lists.py | {
"start": 37341,
"end": 37584
} | class ____(object):
def __init__(self, n):
self.data = [[np.arange(i).astype(np.float64)] for i in range(n)]
def more(self, n):
for i in range(n):
self.data.append([np.arange(i).astype(np.float64)])
| Container |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/error.py | {
"start": 92,
"end": 203
} | class ____(DgError):
"""Error raised when a configuration file fails validation."""
pass
| DgValidationError |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 118388,
"end": 119678
} | class ____(TestCase):
def test_numbers(self):
iterable = [-10, -8, -7, -6, 1, 2, 4, 5, -1, 7]
actual = [list(g) for g in mi.consecutive_groups(iterable)]
expected = [[-10], [-8, -7, -6], [1, 2], [4, 5], [-1], [7]]
self.assertEqual(actual, expected)
def test_custom_ordering(self)... | ConsecutiveGroupsTest |
python | sqlalchemy__sqlalchemy | test/orm/test_core_compilation.py | {
"start": 34732,
"end": 44762
} | class ____(QueryTest, AssertsCompiledSQL):
"""The Query object calls eanble_eagerloads(False) when you call
.subquery(). With Core select, we don't have that information, we instead
have to look at the "toplevel" flag to know where we are. make sure
the many different combinations that these two obje... | LoadersInSubqueriesTest |
python | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/triggers/test_pod.py | {
"start": 3388,
"end": 18162
} | class ____:
@staticmethod
def _mock_pod_result(result_to_mock):
f = Future()
f.set_result(result_to_mock)
return f
def test_serialize(self, trigger):
classpath, kwargs_dict = trigger.serialize()
assert classpath == TRIGGER_PATH
assert kwargs_dict == {
... | TestKubernetesPodTrigger |
python | PyCQA__pylint | tests/functional/u/undefined/undefined_variable.py | {
"start": 3347,
"end": 3451
} | class ____:
""" No op """
NANA = BAT # [undefined-variable]
del BAT # [undefined-variable]
| Ancestor1 |
python | django__django | tests/model_forms/tests.py | {
"start": 74729,
"end": 83981
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.c1 = Category.objects.create(
name="Entertainment", slug="entertainment", url="entertainment"
)
cls.c2 = Category.objects.create(
name="It's a test", slug="its-test", url="test"
)
cls.c... | ModelMultipleChoiceFieldTests |
python | pytorch__pytorch | test/onnx/exporter/test_core.py | {
"start": 336,
"end": 2850
} | class ____(common_utils.TestCase):
@common_utils.parametrize(
"dtype, np_dtype",
[
(torch.bfloat16, ml_dtypes.bfloat16),
(torch.bool, np.bool_),
(torch.complex128, np.complex128),
(torch.complex64, np.complex64),
(torch.float16, np.float16)... | TorchTensorTest |
python | pennersr__django-allauth | allauth/socialaccount/providers/lemonldap/provider.py | {
"start": 352,
"end": 955
} | class ____(OAuth2Provider):
id = "lemonldap"
name = "LemonLDAP::NG"
account_class = LemonLDAPAccount
oauth2_adapter_class = LemonLDAPOAuth2Adapter
def get_default_scope(self):
return ["openid", "profile", "email"]
def extract_uid(self, data):
return str(data["id"])
def ext... | LemonLDAPProvider |
python | huggingface__transformers | src/transformers/models/sam3_tracker/modular_sam3_tracker.py | {
"start": 5668,
"end": 7791
} | class ____(Sam2Model):
_checkpoint_conversion_mapping = {
r"tracker_model.(.+)": r"\1", # the regex allows to remove the prefix, and add it back in revert mode
"detector_model.vision_encoder.backbone.": "vision_encoder.backbone.",
"tracker_neck.": "vision_encoder.neck.",
}
_keys_to_... | Sam3TrackerModel |
python | aio-libs__aiohttp | aiohttp/payload.py | {
"start": 13944,
"end": 14833
} | class ____(BytesPayload):
def __init__(
self,
value: str,
*args: Any,
encoding: str | None = None,
content_type: str | None = None,
**kwargs: Any,
) -> None:
if encoding is None:
if content_type is None:
real_encoding = "utf-8"
... | StringPayload |
python | apache__airflow | airflow-core/src/airflow/executors/workloads.py | {
"start": 5659,
"end": 6327
} | class ____(BaseModel):
"""Execute an async "trigger" process that yields events."""
id: int
ti: TaskInstance | None
"""
The task instance associated with this trigger.
Could be none for asset-based triggers.
"""
classpath: str
"""
Dot-separated name of the module+fn to import... | RunTrigger |
python | mwaskom__seaborn | tests/test_categorical.py | {
"start": 67380,
"end": 86988
} | class ____(SharedAggTests):
func = staticmethod(barplot)
@pytest.fixture
def common_kws(self):
return {"saturation": 1}
def get_last_color(self, ax):
colors = [p.get_facecolor() for p in ax.containers[-1]]
unique_colors = np.unique(colors, axis=0)
assert len(unique_co... | TestBarPlot |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-metaphor/llama_index/tools/metaphor/base.py | {
"start": 188,
"end": 5439
} | class ____(BaseToolSpec):
"""Metaphor tool spec."""
spec_functions = [
"search",
"retrieve_documents",
"search_and_retrieve_documents",
"find_similar",
"current_date",
]
def __init__(self, api_key: str, verbose: bool = True) -> None:
"""Initialize with p... | MetaphorToolSpec |
python | scrapy__scrapy | tests/test_loader.py | {
"start": 621,
"end": 698
} | class ____:
name = attr.ib(default="")
@dataclasses.dataclass
| AttrsNameItem |
python | huggingface__transformers | src/transformers/models/beit/modeling_beit.py | {
"start": 43156,
"end": 46357
} | class ____(nn.Module):
"""
Unified Perceptual Parsing for Scene Understanding. This head is the implementation of
[UPerNet](https://huggingface.co/papers/1807.10221).
Based on OpenMMLab's implementation, found in https://github.com/open-mmlab/mmsegmentation.
"""
def __init__(self, config: Beit... | BeitUperHead |
python | jazzband__django-model-utils | tests/test_managers/test_query_manager.py | {
"start": 102,
"end": 878
} | class ____(TestCase):
def setUp(self) -> None:
data = ((True, True, 0),
(True, False, 4),
(False, False, 2),
(False, True, 3),
(True, True, 1),
(True, False, 5))
for p, c, o in data:
Post.objects.create(publi... | QueryManagerTests |
python | getlogbook__logbook | src/logbook/base.py | {
"start": 10576,
"end": 12338
} | class ____(ContextObject):
"""Allows flags to be pushed on a flag stack. Currently two flags
are available:
`errors`
Can be set to override the current error behaviour. This value is
used when logging calls fail. The default behaviour is spitting
out the stacktrace to stderr but ... | Flags |
python | huggingface__transformers | src/transformers/models/sew_d/modeling_sew_d.py | {
"start": 36447,
"end": 37526
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.attention = SEWDAttention(config)
self.intermediate = SEWDIntermediate(config)
self.output = SEWDOutput(config)
def forward(
self,
hidden_states,
attention_mask,
... | SEWDLayer |
python | django-compressor__django-compressor | compressor/tests/test_offline.py | {
"start": 32170,
"end": 35240
} | class ____(
OfflineCompressTestCaseWithContextGenerator
):
"""
Test offline compressing with ``STATIC_URL`` and ``COMPRESS_URL`` as instances of
*lazy string-alike objects* instead of strings.
In particular, lazy string-alike objects that add ``SCRIPT_NAME`` WSGI param
as URL path prefix.
... | OfflineCompressTestCaseWithLazyStringAlikeUrls |
python | SmileyChris__easy-thumbnails | easy_thumbnails/tests/test_namers.py | {
"start": 224,
"end": 1275
} | class ____(TestCase):
def test_basic(self):
filename = namers.default(
thumbnailer=FakeThumbnailer(),
prepared_options=['100x100', 'q80', 'crop', 'upscale'],
source_filename='source.jpg',
thumbnail_extension='jpg',
)
self.assertEqual(filename,... | Default |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/auto_contrast.py | {
"start": 312,
"end": 3930
} | class ____(BaseImagePreprocessingLayer):
"""Performs the auto-contrast operation on an image.
Auto contrast stretches the values of an image across the entire available
`value_range`. This makes differences between pixels more obvious. An
example of this is if an image only has values `[0, 1]` out of t... | AutoContrast |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 26590,
"end": 29495
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`, *optional*):
Prediction score... | Qwen2_5OmniThinkerCausalLMOutputWithPast |
python | kamyu104__LeetCode-Solutions | Python/form-largest-integer-with-digits-that-add-up-to-target.py | {
"start": 1482,
"end": 1916
} | class ____(object):
def largestNumber(self, cost, target):
"""
:type cost: List[int]
:type target: int
:rtype: str
"""
dp = [0]
for t in xrange(1, target+1):
dp.append(-1)
for i, c in enumerate(cost):
if t-c < 0:
... | Solution3 |
python | Textualize__textual | src/textual/demo/widgets.py | {
"start": 4954,
"end": 6514
} | class ____(containers.VerticalGroup):
"""Demonstrates Inputs."""
ALLOW_MAXIMIZE = True
DEFAULT_CLASSES = "column"
INPUTS_MD = """\
## Inputs and MaskedInputs
Text input fields, with placeholder text, validation, and auto-complete.
Build for intuitive and user-friendly forms.
"""
DEFAULT_CSS = ""... | Inputs |
python | Lightning-AI__lightning | src/lightning/pytorch/profilers/base.py | {
"start": 749,
"end": 1077
} | class ____(Profiler):
"""This class should be used when you don't want the (small) overhead of profiling.
The Trainer uses this class by default.
"""
@override
def start(self, action_name: str) -> None:
pass
@override
def stop(self, action_name: str) -> None:
pass
| PassThroughProfiler |
python | tiangolo__fastapi | docs_src/schema_extra_example/tutorial003_py310.py | {
"start": 84,
"end": 574
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.put("/items/{item_id}")
async def update_item(
item_id: int,
item: Item = Body(
examples=[
{
"name": "Foo",
"description": "A very nice... | Item |
python | numba__numba | numba/cuda/cudadrv/devicearray.py | {
"start": 1741,
"end": 13807
} | class ____(_devicearray.DeviceArray):
"""A on GPU NDArray representation
"""
__cuda_memory__ = True
__cuda_ndarray__ = True # There must be gpu_data attribute
def __init__(self, shape, strides, dtype, stream=0, gpu_data=None):
"""
Args
----
shape
arr... | DeviceNDArrayBase |
python | pypa__pip | src/pip/_vendor/rich/errors.py | {
"start": 74,
"end": 135
} | class ____(Exception):
"""An error in styles."""
| StyleError |
python | kubernetes-client__python | kubernetes/client/models/v1_token_review.py | {
"start": 383,
"end": 7380
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1TokenReview |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 635337,
"end": 635674
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field("SponsorshipNewsletter", graphql_name="node")
| SponsorshipNewsletterEdge |
python | plotly__plotly.py | plotly/graph_objs/scattercarpet/marker/_colorbar.py | {
"start": 233,
"end": 61773
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattercarpet.marker"
_path_str = "scattercarpet.marker.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
... | ColorBar |
python | PyCQA__pylint | pylint/checkers/exceptions.py | {
"start": 9552,
"end": 10952
} | class ____(BaseVisitor):
"""Visitor for handling leaf kinds of a raise value."""
def visit_const(self, node: nodes.Const) -> None:
self._checker.add_message(
"raising-bad-type",
node=self._node,
args=node.value.__class__.__name__,
confidence=INFERENCE,
... | ExceptionRaiseLeafVisitor |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/gather_op_test.py | {
"start": 2145,
"end": 29674
} | class ____(test.TestCase, parameterized.TestCase):
def _buildParams(self, data, dtype):
data = data.astype(dtype.as_numpy_dtype)
# For complex types, add an index-dependent imaginary component so we can
# tell we got the right value.
if dtype.is_complex:
return data + 10j * data
return data... | GatherTest |
python | django__django | tests/auth_tests/test_hashers.py | {
"start": 23838,
"end": 26029
} | class ____(SimpleTestCase):
not_implemented_msg = "subclasses of BasePasswordHasher must provide %s() method"
def setUp(self):
self.hasher = BasePasswordHasher()
def test_load_library_no_algorithm(self):
msg = "Hasher 'BasePasswordHasher' doesn't specify a library attribute"
with s... | BasePasswordHasherTests |
python | simonw__datasette | datasette/events.py | {
"start": 2063,
"end": 2435
} | class ____(Event):
"""
Event name: ``drop-table``
A table has been dropped from the database.
:ivar database: The name of the database where the table was dropped.
:type database: str
:ivar table: The name of the table that was dropped
:type table: str
"""
name = "drop-table"
... | DropTableEvent |
python | getsentry__sentry | tests/sentry/snuba/metrics/test_snql.py | {
"start": 1437,
"end": 24901
} | class ____(TestCase):
def setUp(self) -> None:
self.org_id = 666
self.metric_ids = []
for metric_name in [
TransactionMRI.MEASUREMENTS_LCP.value,
TransactionMRI.DURATION.value,
]:
metric_id = indexer.record(UseCaseID.TRANSACTIONS, self.org_id, metr... | DerivedMetricSnQLTestCase |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-ovhcloud/llama_index/llms/ovhcloud/base.py | {
"start": 507,
"end": 6774
} | class ____(OpenAI):
"""
OVHcloud AI Endpoints LLM.
OVHcloud AI Endpoints provides OpenAI-compatible API endpoints for various models.
You can use the API for free with rate limits if no API key is provided or if it's
an empty string. Otherwise, generate an API key from the OVHcloud manager at
h... | OVHcloud |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_to_have_no_months_missing.py | {
"start": 598,
"end": 1631
} | class ____(ColumnAggregateMetricProvider):
"""Metric that get all unique months from date column"""
metric_name = "column.distinct_months"
@metric_value(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy(
cls,
execution_engine: SqlAlchemyExecutionEngine,
metric_domain_kwargs,
... | ColumnDistinctMonths |
python | google__pytype | pytype/pyc/opcodes.py | {
"start": 16992,
"end": 17137
} | class ____(OpcodeWithArg):
# might re-raise an exception or jump to a finally
_FLAGS = HAS_ARGUMENT | HAS_JUNKNOWN
__slots__ = ()
| POP_FINALLY |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 611988,
"end": 613539
} | class ____(CoercionNode):
# This node is used to force the result of another node
# to be stored in a temporary. It is only used if the
# argument node's result is not already in a temporary.
def __init__(self, arg, env):
CoercionNode.__init__(self, arg)
self.type = self.arg.type.as_... | CoerceToTempNode |
python | spack__spack | lib/spack/spack/platforms/windows.py | {
"start": 229,
"end": 624
} | class ____(Platform):
priority = 101
def __init__(self):
super().__init__("windows")
windows_os = WindowsOs()
self.default_os = str(windows_os)
self.add_operating_system(str(windows_os), windows_os)
@classmethod
def detect(cls):
plat = platform.system().lower()
... | Windows |
python | allegroai__clearml | clearml/backend_api/services/v2_23/frames.py | {
"start": 59168,
"end": 62694
} | class ____(NonStrictDataModel):
"""
:param uri: Data URI
:type uri: str
:param content_type: Content type (e.g. 'image/jpeg', 'image/png')
:type content_type: str
:param width: Width in pixels
:type width: int
:param height: Height in pixels
:type height: int
:param timestamp: Ti... | Preview |
python | facebook__pyre-check | client/commands/servers.py | {
"start": 3682,
"end": 3878
} | class ____:
socket_path: str
def to_json(self) -> Dict[str, object]:
return {"status": "defunct", "socket": self.socket_path}
@dataclasses.dataclass(frozen=True)
| DefunctServerStatus |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 79108,
"end": 80473
} | class ____:
def test_timeframes(self):
assert self.locale._format_timeframe("now", 0) == "اکنون"
# single
assert self.locale._format_timeframe("minute", 1) == "یک دقیقه"
assert self.locale._format_timeframe("hour", 1) == "یک ساعت"
assert self.locale._format_timeframe("day", 1... | TestFarsiLocale |
python | sympy__sympy | sympy/physics/optics/gaussopt.py | {
"start": 6920,
"end": 7488
} | class ____(RayTransferMatrix):
"""
Ray Transfer Matrix for reflection from curved surface.
Parameters
==========
R : radius of curvature (positive for concave)
See Also
========
RayTransferMatrix
Examples
========
>>> from sympy.physics.optics import CurvedMirror
>>... | CurvedMirror |
python | pypa__pipenv | pipenv/vendor/tomlkit/exceptions.py | {
"start": 2004,
"end": 2278
} | class ____(ParseError):
"""
A numeric or date field was improperly specified.
"""
def __init__(self, line: int, col: int) -> None:
message = "Invalid number or date format"
super().__init__(line, col, message=message)
| InvalidNumberOrDateError |
python | pytorch__pytorch | benchmarks/gpt_fast/model.py | {
"start": 8046,
"end": 8491
} | class ____(nn.Module):
def __init__(self, config: ModelArgs) -> None:
super().__init__()
self.w1 = nn.Linear(config.dim, config.intermediate_size, bias=False)
self.w3 = nn.Linear(config.dim, config.intermediate_size, bias=False)
self.w2 = nn.Linear(config.intermediate_size, config.di... | FeedForward |
python | ray-project__ray | rllib/policy/eager_tf_policy.py | {
"start": 4578,
"end": 9800
} | class ____(Policy):
"""Dummy class to recognize any eagerized TFPolicy by its inheritance."""
pass
def _traced_eager_policy(eager_policy_cls):
"""Wrapper class that enables tracing for all eager policy methods.
This is enabled by the `--trace`/`eager_tracing=True` config when
framework=tf2.
... | EagerTFPolicy |
python | great-expectations__great_expectations | great_expectations/data_context/data_context/context_factory.py | {
"start": 1769,
"end": 24946
} | class ____:
"""Singleton class to manage projects in the global namespace."""
__project: AbstractDataContext | None
def __init__(self):
self.__project = None
def get_project( # noqa: PLR0913 # FIXME CoP
self,
project_config: DataContextConfig | Mapping | None = None,
... | ProjectManager |
python | pikepdf__pikepdf | src/pikepdf/models/metadata.py | {
"start": 8890,
"end": 9452
} | class ____(Converter):
"""Convert XMP dates to DocumentInfo."""
@staticmethod
def xmp_from_docinfo(docinfo_val):
"""Derive XMP date from DocumentInfo."""
if docinfo_val == '':
return ''
return decode_pdf_date(docinfo_val).isoformat()
@staticmethod
def docinfo_fr... | DateConverter |
python | keras-team__keras | keras/src/tree/dmtree_impl.py | {
"start": 1322,
"end": 14099
} | class ____:
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is TypeError:
raise ValueError(exc_value).with_traceback(traceback)
return False
def register_tree_node(
cls,
flatten_func=None,
unflatten_func=None,
):
if... | TypeErrorRemapping |
python | ray-project__ray | rllib/examples/checkpoints/onnx_torch_lstm.py | {
"start": 494,
"end": 3994
} | class ____(torch.nn.Module):
def __init__(self, original_model):
super(ONNXCompatibleWrapper, self).__init__()
self.original_model = original_model
def forward(self, a, b0, b1, c):
# Convert the separate tensor inputs back into the list format
# expected by the original model's ... | ONNXCompatibleWrapper |
python | gevent__gevent | src/greentest/3.14/test_httpservers.py | {
"start": 1124,
"end": 1494
} | class ____(NoLogRequestHandler, SimpleHTTPRequestHandler):
pass
def create_https_server(
certfile,
keyfile=None,
password=None,
*,
address=('localhost', 0),
request_handler=DummyRequestHandler,
):
return HTTPSServer(
address, request_handler,
certfile=certfile, keyfile=... | DummyRequestHandler |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/quantization_ops/quantization_ops_test.py | {
"start": 10726,
"end": 12483
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes
def test_invalid_inputs(self):
inputs = constant_op.constant(
np.int32(0), shape=[3, 3, 3, 3], dtype=dtypes.qint32)
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
... | RequantizeOpTest |
python | fluentpython__example-code-2e | 24-class-metaprog/tinyenums/nanoenum.py | {
"start": 726,
"end": 830
} | class ____(type):
def __prepare__(name, bases, **kwargs):
return KeyIsValueDict()
| NanoEnumMeta |
python | joke2k__faker | faker/providers/bank/uk_UA/__init__.py | {
"start": 42,
"end": 2033
} | class ____(BankProvider):
"""Implement bank provider for ``uk_UA`` locale.
Source for rules for bban format:
https://bank.gov.ua/en/iban
Banks list:
https://ubanks.com.ua/adr/
"""
bban_format = "#" * 27
country_code = "UA"
banks = (
"izibank",
"monobank",
"O.... | Provider |
python | tiangolo__fastapi | docs_src/path_operation_configuration/tutorial001_py39.py | {
"start": 112,
"end": 401
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
tags: set[str] = set()
@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
return item
| Item |
python | tensorflow__tensorflow | tensorflow/python/data/ops/optional_ops.py | {
"start": 7423,
"end": 9203
} | class ____(type_spec.TypeSpec):
"""Type specification for `tf.experimental.Optional`.
For instance, `tf.OptionalSpec` can be used to define a tf.function that takes
`tf.experimental.Optional` as an input argument:
>>> @tf.function(input_signature=[tf.OptionalSpec(
... tf.TensorSpec(shape=(), dtype=tf.int3... | OptionalSpec |
python | pytorch__pytorch | benchmarks/dynamo/genai_layers/kernels.py | {
"start": 4039,
"end": 7071
} | class ____(BenchmarkKernel):
def __init__(self, script_args):
super().__init__(script_args)
self.available_backends = ["eager", "compiled", "quack", "liger"]
def get_shapes(self) -> tuple[tuple[int, ...], ...]:
return (
(32768, 256),
(32768, 512),
(32... | CrossEntropyBackward |
python | jazzband__django-polymorphic | src/polymorphic/tests/models.py | {
"start": 8774,
"end": 8842
} | class ____(ProxyBase):
class Meta:
proxy = True
| ProxyChild |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/supers.py | {
"start": 999,
"end": 1100
} | class ____(A):
def f2(self, x):
return "1"
def g1(self):
return super().f1()
| C |
python | FactoryBoy__factory_boy | factory/builder.py | {
"start": 211,
"end": 6584
} | class ____:
"""A set of declarations, including the recursive parameters.
Attributes:
declarations (dict(name => declaration)): the top-level declarations
contexts (dict(name => dict(subfield => value))): the nested parameters related
to a given top-level declaration
This objec... | DeclarationSet |
python | getsentry__sentry | src/sentry/plugins/base/binding_manager.py | {
"start": 149,
"end": 619
} | class ____:
type: type[Any] | None = None
def __init__(self):
self._items = {}
def __iter__(self):
return iter(self._items)
def add(self, item, id):
if self.type and not issubclass(item, self.type):
raise ValueError(f"Invalid type for provider: {type(item)}")
... | ProviderManager |
python | pyca__cryptography | src/cryptography/hazmat/primitives/serialization/ssh.py | {
"start": 18173,
"end": 18985
} | class ____:
"""
The format of a sk-ssh-ed25519@openssh.com public key is:
string "sk-ssh-ed25519@openssh.com"
string public key
string application (user-specified, but typically "ssh:")
"""
def load_public(
self, data: memoryview
) -> tuple[ed25519.Ed25519PublicK... | _SSHFormatSKEd25519 |
python | modin-project__modin | modin/tests/test_utils.py | {
"start": 1284,
"end": 1623
} | class ____:
def method(self):
"""ordinary method (base)"""
def base_method(self):
"""ordinary method in base only"""
@property
def prop(self):
"""property"""
@staticmethod
def static():
"""static method"""
@classmethod
def clsmtd(cls):
"""class... | BaseParent |
python | mwaskom__seaborn | seaborn/_stats/regression.py | {
"start": 1254,
"end": 1283
} | class ____(Stat):
...
| OLSFit |
python | huggingface__transformers | src/transformers/models/dinov3_vit/configuration_dinov3_vit.py | {
"start": 912,
"end": 9121
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`DINOv3Model`]. It is used to instantiate an
DINOv3 model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will y... | DINOv3ViTConfig |
python | tornadoweb__tornado | tornado/auth.py | {
"start": 27029,
"end": 33477
} | class ____(OAuthMixin):
"""Twitter OAuth authentication.
To authenticate with Twitter, register your application with
Twitter at http://twitter.com/apps. Then copy your Consumer Key
and Consumer Secret to the application
`~tornado.web.Application.settings` ``twitter_consumer_key`` and
``twitter... | TwitterMixin |
python | getsentry__sentry | src/sentry/notifications/platform/slack/provider.py | {
"start": 3552,
"end": 4826
} | class ____(NotificationProvider[SlackRenderable]):
key = NotificationProviderKey.SLACK
default_renderer = SlackRenderer
target_class = IntegrationNotificationTarget
target_resource_types = [
NotificationTargetResourceType.CHANNEL,
NotificationTargetResourceType.DIRECT_MESSAGE,
]
... | SlackNotificationProvider |
python | huggingface__transformers | tests/models/roberta/test_modeling_roberta.py | {
"start": 1662,
"end": 14069
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
use_labels=True,
vocab_size=99,
hidden_size=32,
num_hidden_layers=2,
num_attention_head... | RobertaModelTester |
python | getsentry__sentry | tests/sentry/workflow_engine/handlers/condition/test_issue_priority_deescalating_handler.py | {
"start": 625,
"end": 4433
} | class ____(ConditionTestCase):
condition = Condition.ISSUE_PRIORITY_DEESCALATING
def setUp(self) -> None:
super().setUp()
self.group, self.event, self.group_event = self.create_group_event(
group_type_id=MetricIssue.type_id
)
self.event_data = WorkflowEventData(event... | TestIssuePriorityGreaterOrEqualCondition |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess7.py | {
"start": 159,
"end": 350
} | class ____:
def __init__(self):
return
def __getattr__(self, key: str) -> Callable[[str], str]:
return lambda a: a
a = ClassA()
a.foo("hi")
T = TypeVar("T")
| ClassA |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/typed_dict.py | {
"start": 257,
"end": 1518
} | class ____(TypedDict):
foo: int
bar: str
def test_typed_dict_setitem():
d: SimpleTypedDict = {"foo": 0, "bar": ""}
d["bar"] = _test_source()
_test_sink(d["bar"]) # This is an issue.
_test_sink(d["foo"]) # This is NOT an issue.
def test_typed_dict_constructor():
d = SimpleTypedDict(foo=... | SimpleTypedDict |
python | getsentry__sentry | src/sentry/utils/snowflake.py | {
"start": 2300,
"end": 5725
} | class ____:
length: int
name: str
def __post_init__(self) -> None:
if self.length <= 0:
raise Exception("The length should be a positive number")
def validate(self, value: int) -> None:
if value >> self.length != 0:
raise Exception(f"{self.name} exceed max bit v... | SnowflakeBitSegment |
python | streamlit__streamlit | lib/streamlit/runtime/secrets.py | {
"start": 6024,
"end": 7585
} | class ____(Mapping[str, Any]):
"""We use AttrDict to wrap up dictionary values from secrets
to provide dot access to nested secrets.
"""
def __init__(self, value: Mapping[str, Any]) -> None:
self.__dict__["__nested_secrets__"] = dict(value)
@staticmethod
def _maybe_wrap_in_attr_dict(va... | AttrDict |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 80761,
"end": 81973
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"repository_id",
"title",
"body",
"assignee_ids",
"milestone_id",
"label_ids",
"project_ids",
"issue_template",
... | CreateIssueInput |
python | run-llama__llama_index | llama-index-core/tests/multi_modal_llms/test_base_multi_modal_llm_metadata.py | {
"start": 151,
"end": 1147
} | class ____:
def test_default_values(self):
metadata = MultiModalLLMMetadata()
assert metadata.model_name == "unknown"
assert metadata.is_chat_model is False
assert metadata.is_function_calling_model is False
assert metadata.context_window is not None
assert metadata.n... | TestMultiModalLLMMetadata |
python | pyparsing__pyparsing | pyparsing/core.py | {
"start": 148348,
"end": 149348
} | class ____(PositionToken):
"""Token to advance to a specific column of input text; useful for
tabular report scraping.
"""
def __init__(self, colno: int) -> None:
super().__init__()
self.col = colno
def preParse(self, instring: str, loc: int) -> int:
if col(loc, instring) =... | GoToColumn |
python | doocs__leetcode | solution/3000-3099/3093.Longest Common Suffix Queries/Solution.py | {
"start": 0,
"end": 856
} | class ____:
__slots__ = ("children", "length", "idx")
def __init__(self):
self.children = [None] * 26
self.length = inf
self.idx = inf
def insert(self, w: str, i: int):
node = self
if node.length > len(w):
node.length = len(w)
node.idx = i
... | Trie |
python | kamyu104__LeetCode-Solutions | Python/maximum-difference-between-even-and-odd-frequency-ii.py | {
"start": 78,
"end": 1232
} | class ____(object):
def maxDifference(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
def diff(x, y):
prefix1, prefix2, prefix = [0]*(len(s)+1), [0]*(len(s)+1), [0]*(len(s)+1)
for i in xrange(len(s)):
prefix1[i+1] = p... | Solution |
python | huggingface__transformers | src/transformers/models/efficientloftr/modeling_efficientloftr.py | {
"start": 39214,
"end": 60693
} | class ____(EfficientLoFTRPreTrainedModel):
"""EfficientLoFTR dense image matcher
Given two images, we determine the correspondences by:
1. Extracting coarse and fine features through a backbone
2. Transforming coarse features through self and cross attention
3. Matching coarse features to obt... | EfficientLoFTRForKeypointMatching |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 92429,
"end": 93507
} | class ____(fixtures.TestBase):
def test_pickle(self):
data = {"hello": "bla"}
props = util.Properties(data)
for loader, dumper in picklers():
s = dumper(props)
p = loader(s)
eq_(props._data, p._data)
eq_(props.keys(), p.keys())
def test_... | TestProperties |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.