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 | microsoft__pyright | packages/pyright-internal/src/tests/samples/metaclass8.py | {
"start": 251,
"end": 294
} | class ____(Generic[T], metaclass=A[T]): ...
| B |
python | sanic-org__sanic | sanic/worker/constants.py | {
"start": 72,
"end": 200
} | class ____(UpperStrEnum):
"""Available restart orders."""
SHUTDOWN_FIRST = auto()
STARTUP_FIRST = auto()
| RestartOrder |
python | altair-viz__altair | tests/utils/test_schemapi.py | {
"start": 1539,
"end": 1672
} | class ____(SchemaBase):
@classmethod
def _default_wrapper_classes(cls):
return _TestSchema.__subclasses__()
| _TestSchema |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/stackdriver.py | {
"start": 17073,
"end": 20068
} | class ____(GoogleCloudBaseOperator):
"""
Deletes an alerting policy.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:StackdriverDeleteAlertOperator`
:param name: The alerting policy to delete. The format is:
... | StackdriverDeleteAlertOperator |
python | kamyu104__LeetCode-Solutions | Python/partition-string-into-substrings-with-values-at-most-k.py | {
"start": 38,
"end": 439
} | class ____(object):
def minimumPartition(self, s, k):
"""
:type s: str
:type k: int
:rtype: int
"""
result = 1
curr = 0
for c in s:
if int(c) > k:
return -1
if curr*10+int(c) > k:
result += 1
... | Solution |
python | ray-project__ray | python/ray/serve/tests/unit/test_http_util.py | {
"start": 9840,
"end": 13962
} | class ____:
"""Test suite for configure_http_options_with_defaults function."""
def test_basic_configuration_with_mock_env(
self, base_http_options, mock_env_constants
):
"""Test basic configuration with mocked environment constants."""
result = configure_http_options_with_defaults(... | TestConfigureHttpOptionsWithDefaults |
python | huggingface__transformers | src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py | {
"start": 42525,
"end": 46094
} | class ____(nn.Module):
def __init__(self, config: RTDetrV2Config):
super().__init__()
self.normalize_before = config.normalize_before
# self-attention
self.self_attn = RTDetrV2MultiheadAttention(
embed_dim=config.encoder_hidden_dim,
num_heads=config.num_atten... | RTDetrV2EncoderLayer |
python | astropy__astropy | astropy/io/ascii/ecsv.py | {
"start": 1258,
"end": 1600
} | class ____(ECSVHeaderSplitter):
"""Special case splitter used for writing header line to quote all the column names.
This is used if the first column name starts with the ECSV comment regex or if any
column names have leading or trailing whitespace. See issue #18710.
"""
quoting = csv.QUOTE_ALL
| ECSVHeaderSplitterQuoteAll |
python | tensorflow__tensorflow | tensorflow/python/distribute/integration_test/tpu_memory_test.py | {
"start": 1630,
"end": 7979
} | class ____(tf.test.TestCase):
def setUp(self):
super().setUp()
# Clear all cached tensors
context._reset_context()
# Run garbage collection to free any tensors from previous
# runs.
gc.collect()
# Run a small program and copy the result to CPU.
# This causes deferred deallocations to... | TpuMemoryTest |
python | zarr-developers__zarr-python | src/zarr/codecs/numcodecs/_codecs.py | {
"start": 7499,
"end": 7568
} | class ____(_NumcodecsBytesBytesCodec, codec_name="zstd"):
pass
| Zstd |
python | kamyu104__LeetCode-Solutions | Python/number-of-stable-subsequences.py | {
"start": 34,
"end": 557
} | class ____(object):
def countStableSubsequences(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
MOD = 10**9+7
dp = [[0]*2 for _ in xrange(2)] # dp[p][i]: count of subsequences that end with exactly (i+1) consecutive numbers of parity p
for x in nums:
... | Solution |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modular_qwen3_omni_moe.py | {
"start": 100506,
"end": 100545
} | class ____(SnakeBeta):
pass
| SnakeBeta |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/processing_qwen2_5_omni.py | {
"start": 1215,
"end": 1530
} | class ____(VideosKwargs, total=False):
min_pixels: int
max_pixels: int
patch_size: int
temporal_patch_size: int
merge_size: int
min_frames: int
max_frames: int
use_audio_in_video: bool
seconds_per_chunk: float
position_id_per_seconds: Union[int, float]
| Qwen2_5_OmniVideosKwargs |
python | sqlalchemy__sqlalchemy | test/base/test_result.py | {
"start": 27933,
"end": 30886
} | class ____(fixtures.TestBase):
@testing.fixture
def merge_fixture(self):
r1 = result.IteratorResult(
result.SimpleResultMetaData(["user_id", "user_name"]),
iter([(7, "u1"), (8, "u2")]),
)
r2 = result.IteratorResult(
result.SimpleResultMetaData(["user_i... | MergeResultTest |
python | dagster-io__dagster | python_modules/libraries/dagster-aws/dagster_aws/athena/resources.py | {
"start": 564,
"end": 3669
} | class ____:
def __init__(self, client, workgroup="primary", polling_interval=5, max_polls=120):
check.invariant(
polling_interval >= 0, "polling_interval must be greater than or equal to 0"
)
check.invariant(max_polls > 0, "max_polls must be greater than 0")
self.client =... | AthenaClient |
python | aio-libs__aiohttp | aiohttp/web_exceptions.py | {
"start": 7229,
"end": 7291
} | class ____(HTTPClientError):
status_code = 403
| HTTPForbidden |
python | openai__openai-python | src/openai/resources/uploads/uploads.py | {
"start": 23209,
"end": 23758
} | class ____:
def __init__(self, uploads: Uploads) -> None:
self._uploads = uploads
self.create = _legacy_response.to_raw_response_wrapper(
uploads.create,
)
self.cancel = _legacy_response.to_raw_response_wrapper(
uploads.cancel,
)
self.complete... | UploadsWithRawResponse |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 201408,
"end": 204516
} | class ____:
@pytest.mark.parametrize(
("fn", "template_name"),
[
(email.send_recovery_codes_generated_email, "recovery-codes-generated"),
(email.send_recovery_code_used_email, "recovery-code-used"),
(email.send_recovery_code_reminder_email, "recovery-code-reminder... | TestRecoveryCodeEmails |
python | openai__openai-python | src/openai/types/responses/response_function_tool_call_param.py | {
"start": 229,
"end": 941
} | class ____(TypedDict, total=False):
arguments: Required[str]
"""A JSON string of the arguments to pass to the function."""
call_id: Required[str]
"""The unique ID of the function tool call generated by the model."""
name: Required[str]
"""The name of the function to run."""
type: Required... | ResponseFunctionToolCallParam |
python | spyder-ide__spyder | spyder/plugins/projects/widgets/main_widget.py | {
"start": 42228,
"end": 43580
} | class ____(QWidget):
def __init__(self, directory=None):
QWidget.__init__(self)
self.CONF_SECTION = 'project_explorer'
vlayout = QVBoxLayout()
self.setLayout(vlayout)
self.explorer = ProjectExplorerWidget(None, self, self)
if directory is not None:
self.d... | ProjectExplorerTest |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/attributes.py | {
"start": 76580,
"end": 93699
} | class ____(NamedTuple):
"""A 3-tuple of added, unchanged and deleted values,
representing the changes which have occurred on an instrumented
attribute.
The easiest way to get a :class:`.History` object for a particular
attribute on an object is to use the :func:`_sa.inspect` function::
fro... | History |
python | mlflow__mlflow | mlflow/models/rag_signatures.py | {
"start": 845,
"end": 1028
} | class ____:
query: str = "What is mlflow?"
history: list[Message] | None = field(default_factory=list)
@deprecated("mlflow.types.llm.ChatChoice")
@dataclass
| MultiturnChatRequest |
python | eventlet__eventlet | tests/websocket_test.py | {
"start": 22270,
"end": 23353
} | class ____(tests.LimitedTestCase):
def setUp(self):
self.mock_socket = s = mock.Mock()
self.environ = env = dict(HTTP_ORIGIN='http://localhost', HTTP_WEBSOCKET_PROTOCOL='ws',
PATH_INFO='test')
self.test_ws = WebSocket(s, env)
super().setUp()
d... | TestWebSocketObject |
python | pytorch__pytorch | test/profiler/test_cpp_thread.py | {
"start": 2375,
"end": 7614
} | class ____(TestCase):
ThreadCount = 20 # set to 2 for debugging
EventHandler = None
TraceObject = None
@classmethod
def setUpClass(cls) -> None:
super(TestCase, cls).setUpClass()
CppThreadTestCUDA.EventHandler = PythonProfilerEventHandler()
cpp.ProfilerEventHandler.Register... | CppThreadTestCUDA |
python | getsentry__sentry | tests/sentry/utils/test_linksign.py | {
"start": 281,
"end": 3931
} | class ____(TestCase):
def test_link_signing(self) -> None:
base_url = get_local_region().to_url("/")
assert base_url.startswith("http://")
url = linksign.generate_signed_link(self.user.id, "sentry")
assert url.startswith(base_url)
url = linksign.generate_signed_link(
... | LinkSignTestCase |
python | keras-team__keras | guides/making_new_layers_and_models_via_subclassing.py | {
"start": 18507,
"end": 19014
} | class ____(layers.Layer):
"""Converts z, the encoded digit vector, back into a readable digit."""
def __init__(
self, original_dim, intermediate_dim=64, name="decoder", **kwargs
):
super().__init__(name=name, **kwargs)
self.dense_proj = layers.Dense(intermediate_dim, activation="rel... | Decoder |
python | PyCQA__pylint | doc/data/messages/n/non-str-assignment-to-dunder-name/bad.py | {
"start": 0,
"end": 82
} | class ____:
pass
Fruit.__name__ = 1 # [non-str-assignment-to-dunder-name]
| Fruit |
python | django__django | django/db/backends/ddl_references.py | {
"start": 3512,
"end": 4311
} | class ____(Columns):
def __init__(self, table, columns, quote_name, col_suffixes=(), opclasses=()):
self.opclasses = opclasses
super().__init__(table, columns, quote_name, col_suffixes)
def __str__(self):
def col_str(column, idx):
# Index.__init__() guarantees that self.opcl... | IndexColumns |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_actionable_items.py | {
"start": 213,
"end": 2879
} | class ____(APITestCase):
# These tests will not focus on the actual source map debugging functionality as that is covered in
# test_source_map_debug.py. Instead, these tests will focus on the unique parts of this endpoint including the responses,
# and how event errors are handled.
endpoint = "sentry-ap... | ActionableItemsEndpointTestCase |
python | ray-project__ray | python/ray/serve/tests/test_config_files/logging_config_test.py | {
"start": 666,
"end": 1530
} | class ____:
def __init__(self, handle):
self.handle = handle
async def __call__(self):
logger.debug("this_is_debug_info_from_router")
log_info = await self.handle.remote()
if len(logger.handlers) == 2:
log_info["router_log_file"] = logger.handlers[1].target.baseFilen... | Router |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 658275,
"end": 658696
} | class ____(sgqlc.types.Interface):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("viewer_cannot_update_reasons",)
viewer_cannot_update_reasons = sgqlc.types.Field(
sgqlc.types.non_null(
sgqlc.types.list_of(sgqlc.types.non_null(CommentC... | UpdatableComment |
python | jazzband__prettytable | src/prettytable/prettytable.py | {
"start": 2180,
"end": 2248
} | class ____(IntEnum):
FRAME = 0
ALL = 1
NONE = 2
| VRuleStyle |
python | huggingface__transformers | src/transformers/models/glm4v/modeling_glm4v.py | {
"start": 30753,
"end": 31327
} | class ____(PreTrainedModel):
config: Glm4vConfig
base_model_prefix = "model"
input_modalities = ("image", "video", "text")
supports_gradient_checkpointing = True
_no_split_modules = ["Glm4vTextDecoderLayer", "Glm4vVisionBlock"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_... | Glm4vPreTrainedModel |
python | huggingface__transformers | src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py | {
"start": 109698,
"end": 117347
} | class ____(PreTrainedModel):
config: SeamlessM4Tv2Config
main_input_name = "input_embeds"
input_modalities = "audio"
_no_split_modules = []
def __init__(self, config):
super().__init__(config)
self.pad_token_id = config.t2u_pad_token_id
embed_dim = config.unit_embed_dim
... | SeamlessM4Tv2CodeHifiGan |
python | weaviate__weaviate-python-client | weaviate/backup/backup.py | {
"start": 675,
"end": 853
} | class ____(str, Enum):
"""Which backend should be used to write the backup to."""
FILESYSTEM = "filesystem"
S3 = "s3"
GCS = "gcs"
AZURE = "azure"
| BackupStorage |
python | PrefectHQ__prefect | src/prefect/events/schemas/labelling.py | {
"start": 101,
"end": 2131
} | class ____:
"""The LabelDiver supports templating use cases for any Labelled object, by
presenting the labels as a graph of objects that may be accessed by attribute. For
example:
```python
diver = LabelDiver({
'hello.world': 'foo',
'hello.world.again': 'bar'
... | LabelDiver |
python | PrefectHQ__prefect | tests/test_flows.py | {
"start": 156054,
"end": 166284
} | class ____:
@pytest.fixture
def mock_deploy(self, monkeypatch):
mock = AsyncMock()
monkeypatch.setattr("prefect.deployments.runner.deploy", mock)
return mock
@pytest.fixture
def local_flow(self):
@flow
def local_flow_deploy():
pass
return loc... | TestFlowDeploy |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_workflows.py | {
"start": 9131,
"end": 10729
} | class ____:
@mock.patch(BASE_PATH.format("Execution"))
@mock.patch(BASE_PATH.format("WorkflowsHook"))
@mock.patch(BASE_PATH.format("WorkflowsExecutionLink.persist"))
def test_execute(self, mock_link_persist, mock_hook, mock_object):
mock_hook.return_value.create_execution.return_value.name = "na... | TestWorkflowExecutionsCreateExecutionOperator |
python | huggingface__transformers | tests/models/conditional_detr/test_modeling_conditional_detr.py | {
"start": 6642,
"end": 21566
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
ConditionalDetrModel,
ConditionalDetrForObjectDetection,
ConditionalDetrForSegmentation,
)
if is_torch_available()
else ()
)
pipeline_model_mappin... | ConditionalDetrModelTest |
python | modin-project__modin | modin/core/dataframe/algebra/default2pandas/resample.py | {
"start": 1011,
"end": 2078
} | class ____:
"""Builder class for resampled aggregation functions."""
@classmethod
def build_resample(cls, func, squeeze_self):
"""
Build function that resamples time-series data and does aggregation.
Parameters
----------
func : callable
Aggregation func... | Resampler |
python | huggingface__transformers | src/transformers/models/luke/modeling_luke.py | {
"start": 32064,
"end": 32747
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.entity_emb_size)
if isinstance(config.hidden_act, str):
self.transform_act_fn = ACT2FN[config.hidden_act]
else:
self.transform_act_fn = conf... | EntityPredictionHeadTransform |
python | getsentry__sentry | src/sentry/incidents/events.py | {
"start": 316,
"end": 496
} | class ____(BaseIncidentEvent):
prev_status: int
status: int
analytics.register(IncidentCreatedEvent)
analytics.register(IncidentStatusUpdatedEvent)
| IncidentStatusUpdatedEvent |
python | astropy__astropy | astropy/utils/masked/tests/test_table.py | {
"start": 4041,
"end": 6569
} | class ____(TestMaskedArrayTable, MaskedQuantityTableSetup):
# Runs tests from TestMaskedArrayTable as well as some extra ones.
def test_table_operations_requiring_masking(self):
t1 = self.t
t2 = QTable({"ma2": Masked([1, 2] * u.m)})
t12 = hstack([t1, t2], join_type="outer")
asser... | TestMaskedQuantityTable |
python | Pylons__pyramid | docs/quick_tutorial/request_response/tutorial/views.py | {
"start": 122,
"end": 596
} | class ____:
def __init__(self, request):
self.request = request
@view_config(route_name='home')
def home(self):
return HTTPFound(location='/plain')
@view_config(route_name='plain')
def plain(self):
name = self.request.params.get('name', 'No Name Provided')
body = '... | TutorialViews |
python | python-openxml__python-docx | tests/oxml/unitdata/numbering.py | {
"start": 205,
"end": 412
} | class ____(BaseBuilder):
__tag__ = "w:numbering"
__nspfxs__ = ("w",)
__attrs__ = ()
def a_num():
return CT_NumBuilder()
def a_numbering():
return CT_NumberingBuilder()
| CT_NumberingBuilder |
python | catalyst-team__catalyst | examples/detection/criterion.py | {
"start": 4703,
"end": 6942
} | class ____(nn.Module):
def __init__(
self,
num_classes=1,
mask_loss_weight=1.0,
regr_loss_weight=1.0,
size_average=True,
):
"""
Args:
num_classes (int): Number of classes in model.
Default is ``1``.
mask_loss_weight ... | CenterNetCriterion |
python | readthedocs__readthedocs.org | readthedocs/subscriptions/products.py | {
"start": 1937,
"end": 5463
} | class ____:
"""A local representation of a Stripe product."""
stripe_id: str
features: dict[str, RTDProductFeature]
# If this product should be available to users to purchase.
listed: bool = False
# If this product is an extra that can be added to a main plan.
# For example, an extra builde... | RTDProduct |
python | doocs__leetcode | solution/1000-1099/1012.Numbers With Repeated Digits/Solution.py | {
"start": 0,
"end": 604
} | class ____:
def numDupDigitsAtMostN(self, n: int) -> int:
@cache
def dfs(i: int, mask: int, lead: bool, limit: bool) -> int:
if i >= len(s):
return lead ^ 1
up = int(s[i]) if limit else 9
ans = 0
for j in range(up + 1):
... | Solution |
python | mlflow__mlflow | mlflow/telemetry/events.py | {
"start": 3092,
"end": 3387
} | class ____(Event):
name: str = "create_logged_model"
@classmethod
def parse(cls, arguments: dict[str, Any]) -> dict[str, Any] | None:
if flavor := arguments.get("flavor"):
return {"flavor": flavor.removeprefix("mlflow.")}
return None
| CreateLoggedModelEvent |
python | walkccc__LeetCode | solutions/2211. Count Collisions on a Road/2211.py | {
"start": 0,
"end": 289
} | class ____:
def countCollisions(self, directions: str) -> int:
l = 0
r = len(directions) - 1
while l < len(directions) and directions[l] == 'L':
l += 1
while r >= 0 and directions[r] == 'R':
r -= 1
return sum(c != 'S' for c in directions[l:r + 1])
| Solution |
python | django__django | tests/template_tests/test_library.py | {
"start": 4511,
"end": 5715
} | class ____(SimpleTestCase):
def setUp(self):
self.library = Library()
def test_tag(self):
@self.library.tag
def func(parser, token):
return Node()
self.assertEqual(self.library.tags["func"], func)
def test_tag_parens(self):
@self.library.tag()
d... | TagRegistrationTests |
python | facelessuser__pymdown-extensions | pymdownx/tilde.py | {
"start": 4177,
"end": 5060
} | class ____(util.PatternSequenceProcessor):
"""Smart delete and subscript processor."""
PATTERNS = [
util.PatSeqItem(re.compile(SMART_DEL_SUB, re.DOTALL | re.UNICODE), 'double', 'del,sub'),
util.PatSeqItem(re.compile(SMART_SUB_DEL, re.DOTALL | re.UNICODE), 'double', 'sub,del'),
util.PatS... | TildeSmartProcessor |
python | doocs__leetcode | solution/1700-1799/1743.Restore the Array From Adjacent Pairs/Solution2.py | {
"start": 0,
"end": 457
} | class ____:
def restoreArray(self, adjacentPairs: List[List[int]]) -> List[int]:
def dfs(i, fa):
ans.append(i)
for j in g[i]:
if j != fa:
dfs(j, i)
g = defaultdict(list)
for a, b in adjacentPairs:
g[a].append(b)
... | Solution |
python | google__jax | jax/_src/typing.py | {
"start": 1554,
"end": 1629
} | class ____(Protocol):
@property
def size(self, /) -> int: ...
| SupportsSize |
python | jazzband__django-oauth-toolkit | tests/test_application_views.py | {
"start": 7262,
"end": 9539
} | class ____(
TestApplicationRegistrationViewRedirectURIWithWildcard
):
def _test_valid(self, uris):
self.client.login(username="foo_user", password="123456")
form_data = {
"name": "Foo app",
"client_id": "client_id",
"client_secret": "client_secret",
... | TestApplicationRegistrationViewAllowedOriginWithWildcard |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 14331,
"end": 14404
} | class ____(PydanticValueError):
msg_template = 'Invalid JSON'
| JsonError |
python | pytorch__pytorch | test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_utils.py | {
"start": 121,
"end": 530
} | class ____(TestCase):
def test_open_device_dlpack(self):
x_in = torch.randn(2, 3).to("openreg")
capsule = torch.utils.dlpack.to_dlpack(x_in)
x_out = torch.from_dlpack(capsule)
self.assertTrue(x_out.device == x_in.device)
x_in = x_in.to("cpu")
x_out = x_out.to("cpu")
... | TestDLPack |
python | PrefectHQ__prefect | src/prefect/server/services/telemetry.py | {
"start": 707,
"end": 5246
} | class ____(RunInEphemeralServers, RunInWebservers, LoopService):
"""
Sends anonymous data to Prefect to help us improve
It can be toggled off with the PREFECT_SERVER_ANALYTICS_ENABLED setting.
"""
loop_seconds: float = 600
@classmethod
def service_settings(cls) -> ServicesBaseSetting:
... | Telemetry |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_dag_runs.py | {
"start": 10886,
"end": 16441
} | class ____:
def setup_method(self):
clear_db_runs()
def teardown_method(self):
clear_db_runs()
def test_get_previous_dag_run_basic(self, client, session, dag_maker):
"""Test getting the previous DAG run without state filtering."""
dag_id = "test_get_previous_basic"
... | TestGetPreviousDagRun |
python | getsentry__sentry | tests/sentry/monitors/endpoints/test_organization_monitor_environment_details.py | {
"start": 316,
"end": 455
} | class ____(BaseDeleteMonitorTest):
endpoint = "sentry-api-0-organization-monitor-environment-details"
__test__ = True
| DeleteMonitorTest |
python | wandb__wandb | wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/inotify.py | {
"start": 8049,
"end": 8546
} | class ____(BaseObserver):
"""
Observer thread that schedules watching directories and dispatches
calls to event handlers.
"""
def __init__(self, timeout=DEFAULT_OBSERVER_TIMEOUT, generate_full_events=False):
if (generate_full_events):
BaseObserver.__init__(self, emitter_class=In... | InotifyObserver |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_fused_batchnorm_test.py | {
"start": 1452,
"end": 32446
} | class ____(test.TestCase):
def _batch_norm(self, x, mean, var, offset, scale, epsilon):
# We compute the batch norm manually in this function because
# nn_impl.batch_normalization does not support float16 yet.
# TODO(reedwm): Add float16 support to nn_impl.batch_normalization.
inv = math_ops.rsqrt(va... | BatchNormalizationTest |
python | ray-project__ray | python/ray/tune/logger/noop.py | {
"start": 174,
"end": 246
} | class ____(Logger):
def on_result(self, result):
pass
| NoopLogger |
python | google__python-fire | fire/console/console_attr.py | {
"start": 4615,
"end": 4886
} | class ____(ProgressTrackerSymbols):
"""Characters used by progress trackers."""
@property
def spin_marks(self):
return ['|', '/', '-', '\\',]
success = 'OK'
failed = 'X'
interrupted = '-'
not_started = '.'
prefix_length = 3
| ProgressTrackerSymbolsAscii |
python | numba__numba | numba/core/typing/arraydecl.py | {
"start": 24042,
"end": 25112
} | class ____(AbstractTemplate):
key = "static_setitem"
def generic(self, args, kws):
# Resolution of members for record and structured arrays
record, idx, value = args
if isinstance(record, types.Record):
if isinstance(idx, str):
expectedty = record.typeof(idx)... | StaticSetItemRecord |
python | conda__conda | conda/common/_logic.py | {
"start": 1675,
"end": 3615
} | class ____:
"""
Storage for the CNF clauses, represented as a flat int array.
Each clause is terminated by int(0).
"""
def __init__(self):
self._clause_array = array("i")
# Methods append and extend are directly bound for performance reasons,
# to avoid call overhead and loo... | _ClauseArray |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/metrics/data_profiler_metrics/data_profiler_profile_diff.py | {
"start": 414,
"end": 1651
} | class ____(DataProfilerProfileMetricProvider):
metric_name = "data_profiler.profile_diff"
value_keys = ("profile_path",)
@metric_value(engine=PandasExecutionEngine)
def _pandas(
cls,
execution_engine,
metric_domain_kwargs,
metric_value_kwargs,
metrics,
r... | DataProfilerProfileDiff |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 30749,
"end": 31275
} | class ____(PrefectFilterBaseModel):
"""Filter by `TaskRun.state_name`."""
any_: Optional[list[str]] = Field(
default=None, description="A list of task run state names to include"
)
def _get_filter_list(
self, db: "PrefectDBInterface"
) -> Iterable[sa.ColumnExpressionArgument[bool]]... | TaskRunFilterStateName |
python | pandas-dev__pandas | pandas/tests/io/formats/test_to_string.py | {
"start": 571,
"end": 4426
} | class ____:
def test_keyword_deprecation(self):
# GH 57280
msg = (
"Starting with pandas version 4.0 all arguments of to_string "
"except for the argument 'buf' will be keyword-only."
)
s = Series(["a", "b"])
with tm.assert_produces_warning(Pandas4Warn... | TestDataFrameToStringFormatters |
python | google__jax | tests/state_test.py | {
"start": 37070,
"end": 38464
} | class ____(NamedTuple):
ref_aval: shaped_array_ref
ref_shape: Shape
indexed_dims: list[bool]
idx_avals: tuple[core.ShapedArray, ...]
idx_shape: Shape
slice_aval: core.ShapedArray
slice_shape: Shape
@hps.composite
def index_params(draw):
ref_shape = draw(hnp.array_shapes(max_dims=4, max_side=7), label='... | IndexParam |
python | pytorch__pytorch | torch/testing/_internal/common_quantization.py | {
"start": 61718,
"end": 62392
} | class ____(torch.nn.Module):
def __init__(self, mod_type):
super().__init__()
self.qconfig = default_dynamic_qconfig
if mod_type == "GRUCell":
self.mod = torch.nn.GRUCell(2, 2).to(dtype=torch.float)
if mod_type == "LSTMCell":
self.mod = torch.nn.LSTMCell(2, 2)... | RNNCellDynamicModel |
python | realpython__materials | python-split-list/parallel_demo.py | {
"start": 1105,
"end": 3603
} | class ____:
max_iterations: int
escape_radius: float = 2.0
def __contains__(self, c):
return self.stability(c) == 1
def stability(self, c, smooth=False, clamp=True):
value = self.escape_count(c, smooth) / self.max_iterations
return max(0.0, min(value, 1.0)) if clamp else value
... | MandelbrotSet |
python | great-expectations__great_expectations | great_expectations/core/partitioners.py | {
"start": 1175,
"end": 1374
} | class ____(pydantic.BaseModel):
mod: int
column_name: str
sort_ascending: bool = True
method_name: Literal["partition_on_mod_integer"] = "partition_on_mod_integer"
| PartitionerModInteger |
python | kamyu104__LeetCode-Solutions | Python/minimize-the-maximum-edge-weight-of-graph.py | {
"start": 98,
"end": 1176
} | class ____(object):
def minMaxWeight(self, n, edges, threshold):
"""
:type n: int
:type edges: List[List[int]]
:type threshold: int
:rtype: int
"""
def dijkstra():
best = [float("inf")]*len(adj)
best[0] = 0
min_heap = [(best... | Solution |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/resolution_tests/test_resolved_from.py | {
"start": 370,
"end": 7609
} | class ____(dg.Model):
foo: str
def test_nested_resolvable():
class ResolvableComponent(dg.Component, dg.Resolvable, dg.Model):
thing: MyModel
def build_defs(self, context: ComponentLoadContext) -> dg.Definitions:
return dg.Definitions()
c = load_component_for_test(
Re... | MyModel |
python | tensorflow__tensorflow | tensorflow/python/autograph/pyct/error_utils.py | {
"start": 858,
"end": 4376
} | class ____(
collections.namedtuple('FrameInfo',
('filename', 'lineno', 'function_name', 'code',
'is_converted', 'is_allowlisted'))):
__slots__ = ()
def _stack_trace_inside_mapped_code(tb, source_map, converter_filename):
"""Summarizes inner traceback fra... | FrameInfo |
python | django__django | tests/m2m_through/models.py | {
"start": 1940,
"end": 2222
} | class ____(models.Model):
name = models.CharField(max_length=5)
friends = models.ManyToManyField("self", through="Friendship", symmetrical=False)
sym_friends = models.ManyToManyField(
"self", through="SymmetricalFriendship", symmetrical=True
)
| PersonSelfRefM2M |
python | google__jax | jax/_src/export/_export.py | {
"start": 13954,
"end": 14171
} | class ____(Protocol):
def __call__(self, serialized_aux_data: bytes) -> PyTreeAuxData:
"""Deserializes the PyTree node AuxData.
The result will be passed to ``_BuildFromChildren``.
"""
| _DeserializeAuxData |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/type_lookup.py | {
"start": 535,
"end": 5312
} | class ____(
UserDict,
Mapping[ValidTypes, ValidTypes],
):
"""
Dict-like Mapping object that creates keys from values and values from keys.
Because of this, all values must be Hashable.
`NoneType` / `None` is not allowed.
If a Mapping-like object is passed as the first parameter, its key/val... | TypeLookup |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/associationproxy.py | {
"start": 46431,
"end": 47245
} | class ____(_LazyCollectionProtocol[_T]):
def __init__(self, obj: Any, target: str):
self.parent = obj
self.target = target
def __call__(
self,
) -> Union[MutableSet[_T], MutableMapping[Any, _T], MutableSequence[_T]]:
return getattr(self.parent, self.target) # type: ignore[n... | _lazy_collection |
python | pydantic__pydantic | tests/mypy/modules/custom_constructor.py | {
"start": 33,
"end": 259
} | class ____(BaseModel):
id: int
name: str
birth_year: int
def __init__(self, id: int) -> None:
super().__init__(id=id, name='Patrick', birth_year=1991)
Person(1)
Person(id=1)
Person(name='Patrick')
| Person |
python | walkccc__LeetCode | solutions/481. Magical String/481.py | {
"start": 0,
"end": 277
} | class ____:
def magicalString(self, n: int) -> int:
s = [' ', '1', '2', '2']
for i in range(3, n + 1):
if i % 2 == 1:
s.extend(['1'] * (int(s[i])))
else:
s.extend(['2'] * (int(s[i])))
return sum(1 for c in s[:n + 1] if c == '1')
| Solution |
python | cython__cython | Cython/Compiler/AutoDocTransforms.py | {
"start": 1414,
"end": 11974
} | class ____(CythonTransform):
def __init__(self, context):
super().__init__(context)
self.class_name = None
self.class_node = None
def _fmt_expr(self, node):
writer = ExpressionWriter(allow_unknown_nodes=True)
result = writer.write(node)
# print(type(node).__name... | EmbedSignature |
python | jazzband__django-waffle | waffle/tests/test_testutils.py | {
"start": 3456,
"end": 3570
} | class ____(OverrideSwitchMixin, TestCase):
"""
Run tests with Django TestCase
"""
| OverrideSwitchTestCase |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0045_project_max_concurrent_builds.py | {
"start": 149,
"end": 629
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0044_auto_20190703_1300"),
]
operations = [
migrations.AddField(
model_name="project",
name="max_concurrent_builds",
field=models.IntegerField(
... | Migration |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/strings_ops/string_split_op_test.py | {
"start": 9602,
"end": 18960
} | class ____(test_util.TensorFlowTestCase, parameterized.TestCase):
@parameterized.named_parameters([
{"testcase_name": "Simple",
"input": [b"pigs on the wing", b"animals"],
"expected": [[b"pigs", b"on", b"the", b"wing"], [b"animals"]]},
{"testcase_name": "MultiCharSeparator",
"input"... | StringSplitV2OpTest |
python | huggingface__transformers | src/transformers/models/dpt/modeling_dpt.py | {
"start": 16169,
"end": 16715
} | class ____(nn.Module):
def __init__(self, config: DPTConfig):
super().__init__()
self.attention = DPTSelfAttention(config)
self.output = DPTViTSelfOutput(config)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
self_attn_output, _ = self.attention(hidden_states)
... | DPTViTAttention |
python | sqlalchemy__sqlalchemy | test/orm/test_cache_key.py | {
"start": 21404,
"end": 29089
} | class ____(fixtures.CacheKeyFixture, _poly_fixtures._Polymorphic):
run_setup_mappers = "once"
run_inserts = None
run_deletes = None
def test_wp_objects(self):
Person, Manager, Engineer, Boss = self.classes(
"Person", "Manager", "Engineer", "Boss"
)
self._run_cache_k... | PolyCacheKeyTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/storage/kvstore/types.py | {
"start": 223,
"end": 2193
} | class ____(ABC):
"""Base key-value store."""
@abstractmethod
def put(self, key: str, val: dict, collection: str = DEFAULT_COLLECTION) -> None:
pass
@abstractmethod
async def aput(
self, key: str, val: dict, collection: str = DEFAULT_COLLECTION
) -> None:
pass
def p... | BaseKVStore |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Display.py | {
"start": 4038,
"end": 5530
} | class ____(Node):
"""Connection to a Canvas widget."""
nodeName = 'CanvasWidget'
def __init__(self, name):
Node.__init__(self, name, terminals={'In': {'io': 'in', 'multi': True}})
self.canvas = None
self.items = {}
def disconnected(self, localTerm, remoteTerm):
... | CanvasNode |
python | doocs__leetcode | solution/1500-1599/1560.Most Visited Sector in a Circular Track/Solution.py | {
"start": 0,
"end": 255
} | class ____:
def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
if rounds[0] <= rounds[-1]:
return list(range(rounds[0], rounds[-1] + 1))
return list(range(1, rounds[-1] + 1)) + list(range(rounds[0], n + 1))
| Solution |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-databricks/llama_index/embeddings/databricks/base.py | {
"start": 582,
"end": 7426
} | class ____(BaseEmbedding):
"""
Databricks class for text embedding.
Databricks adheres to the OpenAI API, so this integration aligns closely with the existing OpenAIEmbedding class.
Args:
model (str): The unique ID of the embedding model as served by the Databricks endpoint.
endpoint (... | DatabricksEmbedding |
python | jazzband__pip-tools | piptools/build.py | {
"start": 1106,
"end": 1225
} | class ____:
extras: tuple[str, ...]
requirements: tuple[InstallRequirement, ...]
@dataclass
| StaticProjectMetadata |
python | dask__distributed | distributed/tests/test_client.py | {
"start": 57349,
"end": 91282
} | class ____:
def __getstate__(self):
return 1
def __setstate__(self, state):
raise TypeError("hello!")
@pytest.mark.skip
@gen_test()
async def test_badly_serialized_input_stderr(capsys, c):
o = BadlySerializedObject()
future = c.submit(inc, o)
while True:
sleep(0.01)
... | BadlySerializedObject |
python | google__jax | jax/_src/pallas/core.py | {
"start": 36981,
"end": 44902
} | class ____:
"""Encodes the grid parameters for :func:`jax.experimental.pallas.pallas_call`.
See the documentation for :func:`jax.experimental.pallas.pallas_call`,
and also :ref:`pallas_grids_and_blockspecs` for a more detailed
description of the parameters.
"""
# A canonicalized internal version is in Grid... | GridSpec |
python | run-llama__llama_index | llama-index-core/llama_index/core/instrumentation/events/llm.py | {
"start": 3966,
"end": 4491
} | class ____(BaseEvent):
"""
LLMChatStartEvent.
Args:
messages (List[ChatMessage]): List of chat messages.
additional_kwargs (dict): Additional keyword arguments.
model_dict (dict): Model dictionary.
"""
model_config = ConfigDict(protected_namespaces=("pydantic_model_",))
... | LLMChatStartEvent |
python | doocs__leetcode | solution/1200-1299/1217.Minimum Cost to Move Chips to The Same Position/Solution.py | {
"start": 0,
"end": 174
} | class ____:
def minCostToMoveChips(self, position: List[int]) -> int:
a = sum(p % 2 for p in position)
b = len(position) - a
return min(a, b)
| Solution |
python | pyca__cryptography | src/cryptography/hazmat/primitives/_serialization.py | {
"start": 1289,
"end": 1554
} | class ____(utils.Enum):
SubjectPublicKeyInfo = "X.509 subjectPublicKeyInfo with PKCS#1"
PKCS1 = "Raw PKCS#1"
OpenSSH = "OpenSSH"
Raw = "Raw"
CompressedPoint = "X9.62 Compressed Point"
UncompressedPoint = "X9.62 Uncompressed Point"
| PublicFormat |
python | huggingface__transformers | src/transformers/models/altclip/modeling_altclip.py | {
"start": 8945,
"end": 11754
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention... | AltRobertaSelfAttention |
python | scrapy__scrapy | tests/mockserver/dns.py | {
"start": 817,
"end": 1767
} | class ____:
def __enter__(self):
self.proc = Popen(
[sys.executable, "-u", "-m", "tests.mockserver.dns"],
stdout=PIPE,
env=get_script_run_env(),
)
self.host = "127.0.0.1"
self.port = int(
self.proc.stdout.readline().strip().decode("asci... | MockDNSServer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.