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 | django__django | tests/forms_tests/widget_tests/test_telinput.py | {
"start": 66,
"end": 270
} | class ____(WidgetTest):
widget = TelInput()
def test_render(self):
self.check_html(
self.widget, "telephone", "", html='<input type="tel" name="telephone">'
)
| TelInputTest |
python | astropy__astropy | astropy/utils/tests/test_decorators.py | {
"start": 572,
"end": 749
} | class ____(AstropyDeprecationWarning):
"""
New Warning subclass to be used to test the deprecated decorator's
``warning_type`` parameter.
"""
| NewDeprecationWarning |
python | scrapy__scrapy | tests/mockserver/http_resources.py | {
"start": 6478,
"end": 6764
} | class ____(resource.Resource):
"""
A testing resource which renders itself as the value of the Content-Length
header from the request.
"""
def render(self, request):
return request.requestHeaders.getRawHeaders(b"content-length")[0]
| ContentLengthHeaderResource |
python | PyCQA__pylint | tests/functional/g/genexp_in_class_scope.py | {
"start": 115,
"end": 187
} | class ____:
var1 = []
var2 = list(value*2 for value in var1)
| MyClass |
python | altair-viz__altair | altair/vegalite/v6/schema/_config.py | {
"start": 155885,
"end": 156887
} | class ____(TypedDict, total=False):
"""
:class:`altair.LinearGradient` ``TypedDict`` wrapper.
Parameters
----------
gradient
The type of gradient. Use ``"linear"`` for a linear gradient.
stops
An array of gradient stops defining the gradient color sequence.
id
x1
... | LinearGradientKwds |
python | getsentry__sentry | tests/sentry/sentry_apps/services/test_model.py | {
"start": 1514,
"end": 3090
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(name="foo")
self.org = self.create_organization(owner=self.user)
self.project = self.create_project(slug="boop", organization=self.org)
self.sentry_app = self.create_sentry_app(
... | TestRpcApiApplication |
python | huggingface__transformers | src/transformers/core_model_loading.py | {
"start": 15742,
"end": 17427
} | class ____(WeightTransform):
# Special case of WeightTransform that only renames keys without any conversion.
def convert(
self,
layer_name: str,
model=None,
config=None,
hf_quantizer=None,
missing_keys: Optional[MutableSet[str]] = None,
misc: Optional[Mu... | WeightRenaming |
python | numba__numba | numba/core/typing/builtins.py | {
"start": 18763,
"end": 19342
} | class ____(AbstractTemplate):
key = "static_getitem"
def generic(self, args, kws):
tup, idx = args
ret = None
if not isinstance(tup, types.LiteralStrKeyDict):
return
if isinstance(idx, str):
if idx in tup.fields:
lookup = tup.fields.index(... | StaticGetItemLiteralStrKeyDict |
python | tensorflow__tensorflow | tensorflow/python/platform/flags.py | {
"start": 1975,
"end": 4086
} | class ____:
"""Wrapper class for absl.flags.FLAGS.
The difference is that tf.flags.FLAGS implicitly parses flags with sys.argv
when accessing the FLAGS values before it's explicitly parsed,
while absl.flags.FLAGS raises an exception.
"""
def __init__(self, flags_object):
self.__dict__['__wrapped'] = f... | _FlagValuesWrapper |
python | numba__numba | numba/cuda/stubs.py | {
"start": 4551,
"end": 4835
} | class ____(Stub):
'''
vote_sync_intrinsic(mask, mode, predictate)
Nvvm intrinsic for performing a reduce and broadcast across a warp
docs.nvidia.com/cuda/nvvm-ir-spec/index.html#nvvm-intrin-warp-level-vote
'''
_description_ = '<vote_sync()>'
| vote_sync_intrinsic |
python | doocs__leetcode | solution/2100-2199/2117.Abbreviating the Product of a Range/Solution.py | {
"start": 0,
"end": 939
} | class ____:
def abbreviateProduct(self, left: int, right: int) -> str:
cnt2 = cnt5 = 0
for x in range(left, right + 1):
while x % 2 == 0:
cnt2 += 1
x //= 2
while x % 5 == 0:
cnt5 += 1
x //= 5
c = cnt2 = c... | Solution |
python | run-llama__llama_index | llama-index-integrations/postprocessor/llama-index-postprocessor-dashscope-rerank/llama_index/postprocessor/dashscope_rerank/base.py | {
"start": 635,
"end": 3255
} | class ____(BaseNodePostprocessor):
model: str = Field(description="Dashscope rerank model name.")
top_n: int = Field(description="Top N nodes to return.")
_api_key: Optional[str] = PrivateAttr()
def __init__(
self,
top_n: int = 3,
model: str = "gte-rerank",
return_docume... | DashScopeRerank |
python | plotly__plotly.py | plotly/graph_objs/splom/marker/_colorbar.py | {
"start": 233,
"end": 61588
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "splom.marker"
_path_str = "splom.marker.colorbar"
_valid_props = {
"bgcolor",
"bordercolor",
"borderwidth",
"dtick",
"exponentformat",
"labelalias",
"len",
"lenmode",
"minexponent... | ColorBar |
python | openai__openai-python | src/openai/types/batch_create_params.py | {
"start": 313,
"end": 2053
} | class ____(TypedDict, total=False):
completion_window: Required[Literal["24h"]]
"""The time frame within which the batch should be processed.
Currently only `24h` is supported.
"""
endpoint: Required[
Literal["/v1/responses", "/v1/chat/completions", "/v1/embeddings", "/v1/completions", "/v... | BatchCreateParams |
python | dask__distributed | distributed/diagnostics/plugin.py | {
"start": 13578,
"end": 16823
} | class ____(SchedulerPlugin):
"""Scheduler plugin to install software on the cluster
This accepts an function that installs software on the scheduler and
all workers. You can also optionally ask for the worker to restart
after performing this installation.
.. note::
This will increase the t... | InstallPlugin |
python | pytorch__pytorch | torch/_inductor/codegen/common.py | {
"start": 89535,
"end": 104446
} | class ____(DefaultHandler):
"""A ops handler that proxies calls to `kernel` and its
handler and returns `CSEVariable`s with correct shape and dtype.
"""
name = "CSEProxy"
def __init__(self, kernel: Kernel[Any], parent_handler: OpsHandler[Any]):
super().__init__()
from ..bounds impo... | CSEProxy |
python | paramiko__paramiko | tests/test_sftp.py | {
"start": 3597,
"end": 30045
} | class ____:
def test_file(self, sftp):
"""
verify that we can create a file.
"""
f = sftp.open(sftp.FOLDER + "/test", "w")
try:
assert f.stat().st_size == 0
finally:
f.close()
sftp.remove(sftp.FOLDER + "/test")
def test_close(s... | TestSFTP |
python | kamyu104__LeetCode-Solutions | Python/most-frequent-ids.py | {
"start": 790,
"end": 1491
} | class ____(object):
def mostFrequentIDs(self, nums, freq):
"""
:type nums: List[int]
:type freq: List[int]
:rtype: List[int]
"""
result = []
cnt = collections.Counter()
cnt2 = collections.Counter()
sl = SortedList()
for x, f in itertool... | Solution2 |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 108081,
"end": 118757
} | class ____(Qwen2_5OmniPreTrainedModelForConditionalGeneration, GenerationMixin):
config: Qwen2_5OmniTalkerConfig
base_model_prefix = "talker"
output_modalities = ("audio",)
def __init__(self, config: Qwen2_5OmniTalkerConfig):
super().__init__(config)
self.thinker_to_talker_proj = nn.Li... | Qwen2_5OmniTalkerForConditionalGeneration |
python | aio-libs__aiohttp | aiohttp/http_exceptions.py | {
"start": 2335,
"end": 2564
} | class ____(BadHttpMessage):
def __init__(self, line: str = "", error: str | None = None) -> None:
super().__init__(error or f"Bad status line {line!r}")
self.args = (line,)
self.line = line
| BadStatusLine |
python | huggingface__transformers | src/transformers/models/wav2vec2_conformer/modeling_wav2vec2_conformer.py | {
"start": 34349,
"end": 35573
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
# feature dim might need to be down-projected
if config.output_hidden_size != config.hidden_size:
self.proj = nn.Linear(config.hidden_size, config.output_hidden_size)
self.proj_layer_norm = nn.Laye... | Wav2Vec2ConformerAdapter |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/richlog_scroll.py | {
"start": 123,
"end": 1036
} | class ____(App):
CSS = """
RichLog{
width: 1fr;
height: 10;
}
"""
def compose(self) -> ComposeResult:
with Horizontal():
# Don't scroll on write
yield RichLog(id="richlog1", auto_scroll=False)
# Scroll on write
yield RichLog(id... | RichLogScrollApp |
python | ansible__ansible | test/units/module_utils/common/test_dict_transformations.py | {
"start": 1286,
"end": 1478
} | class ____:
def test_snake_to_camel_reversed(self):
for (k, v) in EXPECTED_REVERSIBLE.items():
assert _snake_to_camel(v, capitalize_first=True) == k
| TestCaseSnakeToCamel |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-reduce-x-to-zero.py | {
"start": 29,
"end": 584
} | class ____(object):
def minOperations(self, nums, x):
"""
:type nums: List[int]
:type x: int
:rtype: int
"""
target = sum(nums)-x
result = -1
curr = left = 0
for right in xrange(len(nums)):
curr += nums[right]
while left... | Solution |
python | Netflix__metaflow | metaflow/sidecar/sidecar_subprocess.py | {
"start": 811,
"end": 938
} | class ____(Exception):
"""raised when trying unable to send message to sidecar in allocated time"""
pass
| MsgTimeoutError |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 270632,
"end": 271905
} | class ____(ConditionalValueDefnumberExprRef):
"""
ConditionalPredicateValueDefnumberExprRef schema wrapper.
Parameters
----------
test : str, dict, :class:`Predicate`, :class:`FieldGTPredicate`, :class:`FieldLTPredicate`, :class:`FieldGTEPredicate`, :class:`FieldLTEPredicate`, :class:`LogicalOrPred... | ConditionalPredicateValueDefnumberExprRef |
python | getsentry__sentry | src/sentry/issues/endpoints/organization_group_search_views.py | {
"start": 2673,
"end": 8734
} | class ____(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
"POST": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.ISSUES
permission_classes = (MemberPermission,)
def get(self, request: Request, organization: Organization) -> Response:
"""
... | OrganizationGroupSearchViewsEndpoint |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/ecs.py | {
"start": 1523,
"end": 1776
} | class ____(_StringCompareEnum):
"""Contains the possible State values of an ECS Cluster."""
ACTIVE = "ACTIVE"
PROVISIONING = "PROVISIONING"
DEPROVISIONING = "DEPROVISIONING"
FAILED = "FAILED"
INACTIVE = "INACTIVE"
| EcsClusterStates |
python | PrefectHQ__prefect | src/prefect/settings/models/api.py | {
"start": 229,
"end": 1796
} | class ____(PrefectBaseSettings):
"""
Settings for interacting with the Prefect API
"""
model_config: ClassVar[SettingsConfigDict] = build_settings_config(("api",))
url: Optional[str] = Field(
default=None,
description="The URL of the Prefect API. If not set, the client will attempt ... | APISettings |
python | pytorch__pytorch | torch/_inductor/codegen/triton.py | {
"start": 20578,
"end": 21410
} | class ____(BlockDescriptorOptions):
def format(self, name: str, roffset=True) -> str:
"""
Codegen a call to tl.make_tensor_descriptor()
Args:
name: variable name for pointer
roffset: unused, but kept for compatibility with BlockPtrOptions.format()
Returns:
... | TensorDescriptorOptions |
python | networkx__networkx | networkx/utils/union_find.py | {
"start": 72,
"end": 3338
} | class ____:
"""Union-find data structure.
Each unionFind instance X maintains a family of disjoint sets of
hashable objects, supporting the following two methods:
- X[item] returns a name for the set containing the given item.
Each set is named by an arbitrarily-chosen one of its members; as
... | UnionFind |
python | huggingface__transformers | src/transformers/models/instructblipvideo/configuration_instructblipvideo.py | {
"start": 1430,
"end": 5427
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`InstructBlipVideoVisionModel`]. It is used to
instantiate a InstructBlipVideo vision encoder according to the specified arguments, defining the model architecture.
Instantiating a configuration defaults ... | InstructBlipVideoVisionConfig |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_profile_numeric_columns_diff_between_inclusive_threshold_range.py | {
"start": 5731,
"end": 13536
} | class ____(
ProfileNumericColumnsDiffExpectation
):
"""Expect a statistic's value for a given column of a DataProfiler difference report to be within the specified threshold, inclusive.
This expectation takes the difference report between the data it is called on and a DataProfiler profile of the same sche... | ExpectProfileNumericColumnsDiffBetweenInclusiveThresholdRange |
python | scipy__scipy | scipy/special/tests/test_gammainc.py | {
"start": 2678,
"end": 4441
} | class ____:
@pytest.mark.parametrize('a, x', INVALID_POINTS)
def test_domain(self, a, x):
assert np.isnan(sc.gammaincc(a, x))
def test_a_eq_0_x_gt_0(self):
assert sc.gammaincc(0, 1) == 0
@pytest.mark.parametrize('a, x, desired', [
(np.inf, 1, 1),
(np.inf, 0, 1),
... | TestGammaincc |
python | gevent__gevent | src/greentest/3.12/test_weakref.py | {
"start": 1323,
"end": 1391
} | class ____:
def __init__(self):
self.cycle = self
| RefCycle |
python | explosion__spaCy | spacy/lang/ja/__init__.py | {
"start": 7550,
"end": 12566
} | class ____(Language):
lang = "ja"
Defaults = JapaneseDefaults
@Japanese.factory(
"morphologizer",
assigns=["token.morph", "token.pos"],
default_config={
"model": DEFAULT_MORPH_MODEL,
"overwrite": True,
"extend": True,
"scorer": {"@scorers": "spacy.morphologizer_scor... | Japanese |
python | coleifer__peewee | peewee.py | {
"start": 111716,
"end": 126889
} | class ____(Database):
field_types = {
'BIGAUTO': FIELD.AUTO,
'BIGINT': FIELD.INT,
'BOOL': FIELD.INT,
'DOUBLE': FIELD.FLOAT,
'SMALLINT': FIELD.INT,
'UUID': FIELD.TEXT}
operations = {
'LIKE': 'GLOB',
'ILIKE': 'LIKE'}
index_schema_prefix = True
... | SqliteDatabase |
python | pytorch__pytorch | test/test_xpu.py | {
"start": 31848,
"end": 33214
} | class ____(TestCase):
def test_is_bf16_supported(self):
self.assertEqual(
torch.xpu.is_bf16_supported(including_emulation=True),
torch.xpu.is_available(),
)
def test_is_tf32_supported(self):
if not torch.xpu.is_available():
self.assertFalse(torch.xpu.... | TestXPUAPISanity |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 146224,
"end": 147151
} | class ____(sgqlc.types.Input):
"""Information about a sponsorship to make for a user or organization
with a GitHub Sponsors profile, as part of sponsoring many users
or organizations at once.
"""
__schema__ = github_schema
__field_names__ = ("sponsorable_id", "sponsorable_login", "amount")
... | BulkSponsorship |
python | getsentry__sentry | src/sentry/incidents/logic.py | {
"start": 44946,
"end": 58996
} | class ____(Exception):
def __init__(self, project_slugs: Collection[str]) -> None:
self.project_slugs = project_slugs
def create_alert_rule_trigger(
alert_rule: AlertRule,
label: str,
alert_threshold: int | float,
) -> AlertRuleTrigger:
"""
Creates a new AlertRuleTrigger
:param ale... | ProjectsNotAssociatedWithAlertRuleError |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/equalization.py | {
"start": 266,
"end": 8659
} | class ____(BaseImagePreprocessingLayer):
"""Preprocessing layer for histogram equalization on image channels.
Histogram equalization is a technique to adjust image intensities to
enhance contrast by effectively spreading out the most frequent
intensity values. This layer applies equalization on a chann... | Equalization |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 75778,
"end": 76699
} | class ____(Request):
"""
Get the tasks's latest scalar values
:param task: Task ID
:type task: str
"""
_service = "events"
_action = "get_task_latest_scalar_values"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {"task": {"description": "Task ID", "t... | GetTaskLatestScalarValuesRequest |
python | pytorch__pytorch | torch/distributed/_tools/ilp_utils.py | {
"start": 6807,
"end": 10094
} | class ____:
def __init__(self, n: int) -> None:
self.nodes: list[Node] = []
self.name2node: dict[str, Node] = {}
self.ad_matrix = np.zeros((n, n))
self.fw_post_order: list[str] = []
def add_node(self, node: Node) -> None:
self.nodes.append(node)
self.name2node[no... | Graph |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 224116,
"end": 224599
} | class ____(sgqlc.types.Input):
"""Ordering options for discussion poll option connections."""
__schema__ = github_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(sgqlc.types.non_null(DiscussionPollOptionOrderField), graphql_name="field")
"""The field to order poll options ... | DiscussionPollOptionOrder |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/executors/kubernetes_executor_types.py | {
"start": 1090,
"end": 1488
} | class ____(TypedDict, total=False):
"""Detailed information about pod/container failure."""
pod_status: str | None
pod_reason: str | None
pod_message: str | None
container_state: str | None
container_reason: str | None
container_message: str | None
exit_code: int | None
container_ty... | FailureDetails |
python | spack__spack | lib/spack/spack/test/conftest.py | {
"start": 65897,
"end": 77326
} | class ____:
has_code = False
name = "mock-bundle"
@pytest.fixture
def mock_directive_bundle():
"""Return a mock bundle package for directive tests."""
return MockBundle()
@pytest.fixture
def clear_directive_functions():
"""Clear all overidden directive functions for subsequent tests."""
yiel... | MockBundle |
python | mlflow__mlflow | tests/langchain/test_langchain_autolog.py | {
"start": 11177,
"end": 11551
} | class ____(BaseCallbackHandler):
def __init__(self):
self.logs = []
def on_chain_start(
self, serialized: dict[str, Any], inputs: dict[str, Any], **kwargs: Any
) -> None:
self.logs.append("chain_start")
def on_chain_end(self, outputs: dict[str, Any], **kwargs: Any) -> None:
... | CustomCallbackHandler |
python | pandas-dev__pandas | pandas/tests/scalar/timestamp/test_constructors.py | {
"start": 3789,
"end": 7367
} | class ____:
def test_timestamp_constructor_invalid_fold_raise(self):
# Test for GH#25057
# Valid fold values are only [None, 0, 1]
msg = "Valid values for the fold argument are None, 0, or 1."
with pytest.raises(ValueError, match=msg):
Timestamp(123, fold=2)
def test... | TestTimestampConstructorFoldKeyword |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_name02.py | {
"start": 315,
"end": 1710
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_name02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_... | TestCompareXLSXFiles |
python | Textualize__textual | docs/examples/styles/background_transparency.py | {
"start": 80,
"end": 736
} | class ____(App):
"""Simple app to exemplify different transparency settings."""
CSS_PATH = "background_transparency.tcss"
def compose(self) -> ComposeResult:
yield Static("10%", id="t10")
yield Static("20%", id="t20")
yield Static("30%", id="t30")
yield Static("40%", id="t4... | BackgroundTransparencyApp |
python | sympy__sympy | sympy/polys/numberfields/modules.py | {
"start": 60743,
"end": 61344
} | class ____(ModuleEndomorphism):
r"""
An inner endomorphism on a module, i.e. the endomorphism corresponding to
multiplication by a fixed element.
"""
def __init__(self, domain, multiplier):
r"""
Parameters
==========
domain : :py:class:`~.Module`
The dom... | InnerEndomorphism |
python | openai__openai-python | src/openai/resources/responses/input_tokens.py | {
"start": 13747,
"end": 14006
} | class ____:
def __init__(self, input_tokens: AsyncInputTokens) -> None:
self._input_tokens = input_tokens
self.count = _legacy_response.async_to_raw_response_wrapper(
input_tokens.count,
)
| AsyncInputTokensWithRawResponse |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_isbn13.py | {
"start": 1566,
"end": 3847
} | class ____(ColumnMapExpectation):
"""Expect column values to conform to the valid ISBN13 format."""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
{
"data": {
"well_formed_isbn13": [... | ExpectColumnValuesToBeValidIsbn13 |
python | kamyu104__LeetCode-Solutions | Python/count-of-smaller-numbers-after-self.py | {
"start": 2517,
"end": 4489
} | class ____(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
res = [0] * len(nums)
bst = self.BST()
# Insert into BST and get left count.
for i in reversed(xrange(len(nums))):
bst.insertNode(nums[i])
... | Solution3 |
python | aio-libs__aiohttp | aiohttp/http_exceptions.py | {
"start": 1626,
"end": 1736
} | class ____(PayloadEncodingError):
"""Not enough data to satisfy content length header."""
| ContentLengthError |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/strategies.py | {
"start": 5879,
"end": 8710
} | class ____(LoaderStrategy):
"""Provide loading behavior for a :class:`.ColumnProperty`."""
__slots__ = "columns", "is_composite"
def __init__(self, parent, strategy_key):
super().__init__(parent, strategy_key)
self.columns = self.parent_property.columns
self.is_composite = hasattr(... | _ColumnLoader |
python | lazyprogrammer__machine_learning_examples | ab_testing/bayesian_bandit.py | {
"start": 543,
"end": 1937
} | class ____:
def __init__(self, p):
self.p = p
self.a = 1
self.b = 1
self.N = 0 # for information only
def pull(self):
return np.random.random() < self.p
def sample(self):
return np.random.beta(self.a, self.b)
def update(self, x):
self.a += x
self.b += 1 - x
self.N += 1
d... | Bandit |
python | django__django | django/utils/text.py | {
"start": 5291,
"end": 5510
} | class ____(TruncateHTMLParser):
def process(self, data):
data = re.split(r"(?<=\S)\s+(?=\S)", data)
output = escape(" ".join(data[: self.remaining]))
return data, output
| TruncateWordsHTMLParser |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/plan/inputs.py | {
"start": 18553,
"end": 20708
} | class ____(MultiStepInputSource, IHaveNew):
"""This step input is fans-in multiple sources in to a single input. The input will receive a list."""
sources: Sequence[StepInputSource]
# deprecated, preserved for back-compat
node_handle: NodeHandle
input_name: str
def __new__(
cls,
... | FromMultipleSources |
python | modin-project__modin | modin/tests/pandas/extensions/test_dataframe_extensions.py | {
"start": 5812,
"end": 6900
} | class ____:
"""
Make sure to test that we override special "dunder" methods like __len__
correctly. python calls these methods with DataFrame.__len__(obj)
rather than getattr(obj, "__len__")().
source: https://docs.python.org/3/reference/datamodel.html#special-lookup
"""
def test_len(self, ... | TestDunders |
python | sqlalchemy__sqlalchemy | test/sql/test_external_traversal.py | {
"start": 54805,
"end": 88759
} | class ____(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = "default"
@classmethod
def setup_test_class(cls):
global t1, t2
t1 = table("table1", column("col1"), column("col2"), column("col3"))
t2 = table("table2", column("col1"), column("col2"), column("col3"))
def test_co... | ClauseAdapterTest |
python | getsentry__sentry | src/sentry/replays/usecases/query/conditions/selector.py | {
"start": 6498,
"end": 6887
} | class ____(ComputedBase):
"""Dead selector composite condition class."""
@staticmethod
def visit_eq(value: list[QueryType]) -> Condition:
return is_dead_click(ClickSelectorComposite.visit_eq(value))
@staticmethod
def visit_neq(value: list[QueryType]) -> Condition:
return is_dead_cl... | DeadClickSelectorComposite |
python | getsentry__sentry | src/sentry/seer/anomaly_detection/types.py | {
"start": 78,
"end": 153
} | class ____(TypedDict):
anomaly_type: str
anomaly_score: float
| Anomaly |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 9231,
"end": 9471
} | class ____(_Permission[ClusterAction]):
def _to_weaviate(self) -> List[WeaviatePermission]:
return [
{
"action": action,
}
for action in self.actions
]
| _ClusterPermission |
python | getsentry__sentry | src/sentry/api/serializers/models/projectownership.py | {
"start": 377,
"end": 632
} | class ____(ProjectOwnershipResponseOptional):
raw: str
fallthrough: bool
dateCreated: datetime
lastUpdated: datetime
isActive: bool
autoAssignment: str
codeownersAutoSync: bool
@register(ProjectOwnership)
| ProjectOwnershipResponse |
python | ApeWorX__ape | tests/functional/conversion/test_encode_structs.py | {
"start": 762,
"end": 3170
} | class ____(Struct):
a: int
b: bytes
c: bool
d: AddressType
e: str # Gets ignored because not in ABI.
EXPECTED = HexBytes(
"0000000000000000000000000000000000000000000000000000000000000001"
"0200000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000... | SimilarStruct |
python | huggingface__transformers | tests/models/funnel/test_modeling_funnel.py | {
"start": 15687,
"end": 17906
} | class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (
(FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
)
def setUp(self):
self.model_tester = FunnelModelTester(self, base=True)
self.config_tester = ConfigTes... | FunnelBaseModelTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_glue.py | {
"start": 6894,
"end": 8249
} | class ____:
EXPECTED_WAITER_NAME = "data_quality_rule_recommendation_run_complete"
RUN_ID = "1234567890abc"
def test_serialization(self):
"""Assert that arguments and classpath are correctly serialized."""
trigger = GlueDataQualityRuleRecommendationRunCompleteTrigger(recommendation_run_id=s... | TestGlueDataQualityRuleRecommendationRunCompleteTrigger |
python | kubernetes-client__python | kubernetes/client/models/v1_port_status.py | {
"start": 383,
"end": 6026
} | 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... | V1PortStatus |
python | PrefectHQ__prefect | tests/server/orchestration/test_global_policy.py | {
"start": 16491,
"end": 18169
} | class ____:
@pytest.mark.parametrize(
"initial_state_type", [states.StateType.PAUSED, states.StateType.PENDING]
)
async def test_rule_unsets_resuming_indicator_on_running(
self,
session,
initial_state_type,
initialize_orchestration,
):
proposed_state_type ... | TestPausingRules |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 10842,
"end": 10980
} | class ____(_NumberBoundError):
code = 'number.not_lt'
msg_template = 'ensure this value is less than {limit_value}'
| NumberNotLtError |
python | Unity-Technologies__ml-agents | ml-agents-envs/mlagents_envs/rpc_communicator.py | {
"start": 1098,
"end": 6729
} | class ____(Communicator):
def __init__(self, worker_id=0, base_port=5005, timeout_wait=30):
"""
Python side of the grpc communication. Python is the server and Unity the client
:int base_port: Baseline port number to connect to Unity environment over. worker_id increments over this.
... | RpcCommunicator |
python | ray-project__ray | python/ray/train/_internal/framework_checkpoint.py | {
"start": 258,
"end": 1491
} | class ____(Checkpoint):
"""A checkpoint to preserve the functionality of legacy
framework-specific checkpoints.
Example:
>>> import tempfile
>>> checkpoint = FrameworkCheckpoint(tempfile.mkdtemp())
>>> checkpoint.get_preprocessor() is None
True
>>> preprocessor = Pr... | FrameworkCheckpoint |
python | rushter__MLAlgorithms | mla/ensemble/gbm.py | {
"start": 1421,
"end": 1632
} | class ____(Loss):
"""Least squares loss"""
def grad(self, actual, predicted):
return actual - predicted
def hess(self, actual, predicted):
return np.ones_like(actual)
| LeastSquaresLoss |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-pgvector/destination_pgvector/pgvector_processor.py | {
"start": 1169,
"end": 1846
} | class ____(SqlConfig):
"""Configuration for the Postgres cache.
Also inherits config from the JsonlWriter, which is responsible for writing files to disk.
"""
host: str
port: int
database: str
username: str
password: SecretString | str
@overrides
def get_sql_alchemy_url(self) ... | PostgresConfig |
python | skorch-dev__skorch | skorch/exceptions.py | {
"start": 741,
"end": 860
} | class ____(SkorchException):
"""Error raised when the predictions of an LLM have low probability"""
| LowProbabilityError |
python | spyder-ide__spyder | installers-conda/build_conda_pkgs.py | {
"start": 8550,
"end": 11898
} | class ____(BuildCondaPkg):
name = "spyder"
norm = False
source = os.environ.get('SPYDER_SOURCE', HERE.parent)
feedstock = "https://github.com/conda-forge/spyder-feedstock"
feedstock_branch = get_spy_feedstock_branch()
def _patch_source(self):
self.logger.info("Patching Spyder source..."... | SpyderCondaPkg |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/self8.py | {
"start": 551,
"end": 643
} | class ____(str):
pass
v1 = str.__new__(MyStr)
reveal_type(v1, expected_text="MyStr")
| MyStr |
python | plotly__plotly.py | plotly/graph_objs/histogram2d/_textfont.py | {
"start": 233,
"end": 9876
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "histogram2d"
_path_str = "histogram2d.textfont"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@propert... | Textfont |
python | psf__black | tests/data/cases/comments2.py | {
"start": 7332,
"end": 7640
} | class ____:
def _init_host(self, parsed) -> None:
if parsed.hostname is None or not parsed.hostname.strip(): # type: ignore
pass
#######################
### SECTION COMMENT ###
#######################
instruction() # comment with bad spacing
# END COMMENTS
# MORE END COMMENTS
| Test |
python | doocs__leetcode | solution/0000-0099/0009.Palindrome Number/Solution.py | {
"start": 0,
"end": 247
} | class ____:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x and x % 10 == 0):
return False
y = 0
while y < x:
y = y * 10 + x % 10
x //= 10
return x in (y, y // 10)
| Solution |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_testdecorators.py | {
"start": 2513,
"end": 12371
} | class ____:
@given(integers())
def test_abs_non_negative(self, x):
assert abs(x) >= 0
assert isinstance(self, TestCases)
@given(x=integers())
def test_abs_non_negative_varargs(self, x, *args):
assert abs(x) >= 0
assert isinstance(self, TestCases)
@given(x=integers()... | TestCases |
python | aio-libs__aiohttp | aiohttp/web_runner.py | {
"start": 3351,
"end": 4250
} | class ____(BaseSite):
__slots__ = ("_path",)
def __init__(
self,
runner: "BaseRunner[Any]",
path: PathLike,
*,
ssl_context: SSLContext | None = None,
backlog: int = 128,
) -> None:
super().__init__(
runner,
ssl_context=ssl_cont... | UnixSite |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/engine/util.py | {
"start": 1257,
"end": 1349
} | class ____(Protocol):
_trans_context_manager: Optional[TransactionalContext]
| _TConsSubject |
python | tiangolo__fastapi | docs_src/sql_databases/tutorial001_py39.py | {
"start": 156,
"end": 1798
} | class ____(SQLModel, table=True):
id: Union[int, None] = Field(default=None, primary_key=True)
name: str = Field(index=True)
age: Union[int, None] = Field(default=None, index=True)
secret_name: str
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
connect_args = {"check_sa... | Hero |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 188051,
"end": 194912
} | class ____:
math_dtypes = [np.int_, np.float64, np.complex128]
def test_constructor1(self):
# unsorted triplet format
row = array([2, 3, 1, 3, 0, 1, 3, 0, 2, 1, 2])
col = array([0, 1, 0, 0, 1, 1, 2, 2, 2, 2, 1])
data = array([6., 10., 3., 9., 1., 4., 11., 2., 8., 5., 7.])
... | BaseTestCOO |
python | readthedocs__readthedocs.org | readthedocs/audit/models.py | {
"start": 2057,
"end": 7743
} | class ____(TimeStampedModel):
"""
Track user actions for audit purposes.
A log can be attached to a user and/or project and organization.
If the user, project or organization are deleted the log will be preserved,
and the deleted user/project/organization can be accessed via the ``log_*`` attribute... | AuditLog |
python | matplotlib__matplotlib | lib/matplotlib/axes/_base.py | {
"start": 7420,
"end": 21579
} | class ____:
"""
Process variable length arguments to `~.Axes.plot`, to support ::
plot(t, s)
plot(t1, s1, t2, s2)
plot(t1, s1, 'ko', t2, s2)
plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3)
an arbitrary number of *x*, *y*, *fmt* are allowed
"""
def __init__(self, output='Line2D')... | _process_plot_var_args |
python | walkccc__LeetCode | solutions/3463. Check If Digits Are Equal in String After Operations II/3463.py | {
"start": 0,
"end": 976
} | class ____:
# Same as 3461. Check If Digits Are Equal in String After Operations I
def hasSameDigits(self, s: str) -> bool:
n = len(s)
num1 = 0
num2 = 0
for i in range(n - 1):
coefficient = self._nCMOD10(n - 2, i)
num1 += (coefficient * (int(s[i]) - 0)) % 10
num1 %= 10
num2 ... | Solution |
python | kamyu104__LeetCode-Solutions | Python/find-root-of-n-ary-tree.py | {
"start": 527,
"end": 917
} | class ____(object):
def findRoot(self, tree):
"""
:type tree: List['Node']
:rtype: 'Node'
"""
root = 0
for node in tree:
root ^= node.val
for child in node.children:
root ^= child.val
for node in tree:
if nod... | Solution2 |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_natural_language.py | {
"start": 2120,
"end": 2587
} | class ____:
@patch("airflow.providers.google.cloud.operators.natural_language.CloudNaturalLanguageHook")
def test_minimal_green_path(self, hook_mock):
hook_mock.return_value.analyze_entity_sentiment.return_value = ANALYZE_ENTITY_SENTIMENT_RESPONSE
op = CloudNaturalLanguageAnalyzeEntitySentimentO... | TestCloudLanguageAnalyzeEntitySentimentOperator |
python | run-llama__llama_index | llama-index-instrumentation/src/llama_index_instrumentation/events/span.py | {
"start": 57,
"end": 298
} | class ____(BaseEvent):
"""
SpanDropEvent.
Args:
err_str (str): Error string.
"""
err_str: str
@classmethod
def class_name(cls) -> str:
"""Class name."""
return "SpanDropEvent"
| SpanDropEvent |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0064_add_feature_future_default_true.py | {
"start": 149,
"end": 830
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0063_extend_domain_from_timestamp_model"),
]
operations = [
migrations.AddField(
model_name="feature",
name="future_default_true",
field=models.BooleanField(
... | Migration |
python | networkx__networkx | networkx/classes/tests/test_reportviews.py | {
"start": 10576,
"end": 11896
} | class ____(TestEdgeDataView):
@classmethod
def setup_class(cls):
cls.G = nx.path_graph(9, create_using=nx.DiGraph())
cls.eview = nx.reportviews.OutEdgeView
def test_repr(self):
ev = self.eview(self.G)(data=True)
rep = (
"OutEdgeDataView([(0, 1, {}), (1, 2, {}), "... | TestOutEdgeDataView |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 35618,
"end": 37372
} | class ____(BaseModel):
type: Literal["LegacySessionTokenAuthenticator"]
header: str = Field(
...,
description="The name of the session token header that will be injected in the request",
examples=["X-Session"],
title="Session Request Header",
)
login_url: str = Field(
... | LegacySessionTokenAuthenticator |
python | django__django | tests/admin_checks/models.py | {
"start": 1350,
"end": 1422
} | class ____(models.Model):
name = models.CharField(max_length=15)
| State |
python | huggingface__transformers | src/transformers/models/phi4_multimodal/modeling_phi4_multimodal.py | {
"start": 53331,
"end": 56629
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Phi4MultimodalConfig, layer_idx: Optional[int] = None):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_... | Phi4MultimodalAttention |
python | jazzband__django-simple-history | simple_history/tests/view.py | {
"start": 2679,
"end": 2772
} | class ____(DeleteView):
model = Poll
success_url = reverse_lazy("poll-list")
| PollDelete |
python | walkccc__LeetCode | solutions/108. Convert Sorted Array to Binary Search Tree/108.py | {
"start": 0,
"end": 336
} | class ____:
def sortedArrayToBST(self, nums: list[int]) -> TreeNode | None:
def build(l: int, r: int) -> TreeNode | None:
if l > r:
return None
m = (l + r) // 2
return TreeNode(nums[m],
build(l, m - 1),
build(m + 1, r))
return build(0, len... | Solution |
python | plotly__plotly.py | plotly/graph_objs/treemap/_legendgrouptitle.py | {
"start": 233,
"end": 2939
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "treemap"
_path_str = "treemap.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be specifi... | Legendgrouptitle |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.