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 | kamyu104__LeetCode-Solutions | Python/serialize-and-deserialize-binary-tree.py | {
"start": 1474,
"end": 2569
} | class ____(object):
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def gen_preorder(node):
if not node:
yield '#'
else:
yield str(node.val)
for n in gen_preorder(node.left):
yield n
for n in gen_preorder(node.right):
yield n
return ' '.join(gen_preorder(root))
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def builder(chunk_iter):
val = next(chunk_iter)
if val == '#':
return None
node = TreeNode(int(val))
node.left = builder(chunk_iter)
node.right = builder(chunk_iter)
return node
# https://stackoverflow.com/a/42373311/568901
chunk_iter = iter(data.split())
return builder(chunk_iter)
| Codec2 |
python | PrefectHQ__prefect | tests/server/models/test_deployments.py | {
"start": 27539,
"end": 49016
} | class ____:
async def test_schedule_runs_inserts_in_db(self, deployment, session):
scheduled_runs = await models.deployments.schedule_runs(
session, deployment_id=deployment.id
)
assert len(scheduled_runs) == PREFECT_API_SERVICES_SCHEDULER_MIN_RUNS.value()
query_result = await session.execute(
sa.select(orm_models.FlowRun).where(
orm_models.FlowRun.state.has(
orm_models.FlowRunState.type == StateType.SCHEDULED
)
)
)
db_scheduled_runs = query_result.scalars().all()
assert {r.id for r in db_scheduled_runs} == set(scheduled_runs)
expected_times = {
start_of_day(now("UTC")) + datetime.timedelta(days=i + 1)
for i in range(PREFECT_API_SERVICES_SCHEDULER_MIN_RUNS.value())
}
actual_times = set()
for run_id in scheduled_runs:
run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=run_id
)
actual_times.add(run.state.state_details.scheduled_time)
assert actual_times == expected_times
async def test_schedule_runs_is_idempotent(self, flow, deployment, session):
scheduled_runs = await models.deployments.schedule_runs(
session, deployment_id=deployment.id
)
assert len(scheduled_runs) == PREFECT_API_SERVICES_SCHEDULER_MIN_RUNS.value()
second_scheduled_runs = await models.deployments.schedule_runs(
session, deployment_id=deployment.id
)
assert len(second_scheduled_runs) == 0
# only max runs runs were inserted
query_result = await session.execute(
sa.select(orm_models.FlowRun).where(
orm_models.FlowRun.flow_id == flow.id,
orm_models.FlowRun.state.has(
orm_models.FlowRunState.type == StateType.SCHEDULED
),
)
)
db_scheduled_runs = query_result.scalars().all()
assert len(db_scheduled_runs) == PREFECT_API_SERVICES_SCHEDULER_MIN_RUNS.value()
async def test_schedule_n_runs(self, flow, deployment, session):
scheduled_runs = await models.deployments.schedule_runs(
session, deployment_id=deployment.id, min_runs=5
)
assert len(scheduled_runs) == 5
async def test_schedule_does_not_error_if_theres_no_schedule(
self, flow, flow_function, session
):
deployment = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="My Deployment",
flow_id=flow.id,
),
)
scheduled_runs = await models.deployments.schedule_runs(
session, deployment_id=deployment.id, max_runs=3
)
assert scheduled_runs == []
@pytest.mark.parametrize("tags", [[], ["foo"]])
async def test_schedule_runs_applies_tags(self, tags, flow, flow_function, session):
deployment = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="My Deployment",
schedules=[
schemas.core.DeploymentSchedule(
schedule=schemas.schedules.IntervalSchedule(
interval=datetime.timedelta(days=1)
),
active=True,
),
],
flow_id=flow.id,
tags=tags,
),
)
scheduled_runs = await models.deployments.schedule_runs(
session, deployment_id=deployment.id, max_runs=2
)
assert len(scheduled_runs) == 2
for run_id in scheduled_runs:
run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=run_id
)
assert run.tags == ["auto-scheduled"] + tags
@pytest.mark.parametrize("tags", [[], ["foo"]])
async def test_schedule_runs_does_not_set_auto_schedule_tags(
self, tags, flow, flow_function, session
):
deployment = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="My Deployment",
schedules=[
schemas.core.DeploymentSchedule(
schedule=schemas.schedules.IntervalSchedule(
interval=datetime.timedelta(days=1)
),
active=True,
),
],
flow_id=flow.id,
tags=tags,
),
)
scheduled_runs = await models.deployments.schedule_runs(
session,
deployment_id=deployment.id,
max_runs=2,
auto_scheduled=False,
)
assert len(scheduled_runs) == 2
for run_id in scheduled_runs:
run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=run_id
)
assert run.tags == tags
run.auto_scheduled = False
async def test_schedule_runs_applies_work_queue(self, flow, flow_function, session):
deployment = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="My Deployment",
schedules=[
schemas.core.DeploymentSchedule(
schedule=schemas.schedules.IntervalSchedule(
interval=datetime.timedelta(days=1)
),
active=True,
),
],
flow_id=flow.id,
work_queue_name="wq-test-runs",
),
)
scheduled_runs = await models.deployments.schedule_runs(
session, deployment_id=deployment.id, max_runs=2
)
assert len(scheduled_runs) == 2
for run_id in scheduled_runs:
run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=run_id
)
assert run.work_queue_name == "wq-test-runs"
@pytest.mark.parametrize("parameters", [{}, {"foo": "bar"}])
async def test_schedule_runs_applies_parameters(
self, parameters, flow, flow_function, session
):
deployment = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="My Deployment",
schedules=[
schemas.core.DeploymentSchedule(
schedule=schemas.schedules.IntervalSchedule(
interval=datetime.timedelta(days=1)
),
active=True,
),
],
flow_id=flow.id,
parameters=parameters,
),
)
scheduled_runs = await models.deployments.schedule_runs(
session, deployment_id=deployment.id, max_runs=2
)
assert len(scheduled_runs) == 2
for run_id in scheduled_runs:
run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=run_id
)
assert run.parameters == parameters
async def test_schedule_runs_with_end_time(self, flow, deployment, session):
scheduled_runs = await models.deployments.schedule_runs(
session,
deployment_id=deployment.id,
end_time=now("UTC") + datetime.timedelta(days=17),
# set min runs very high to ensure we keep generating runs until we hit the end time
# note that end time has precedence over min runs
min_runs=100,
)
assert len(scheduled_runs) == 17
async def test_schedule_runs_with_end_time_but_no_min_runs(
self, flow, deployment, session
):
scheduled_runs = await models.deployments.schedule_runs(
session,
deployment_id=deployment.id,
end_time=now("UTC") + datetime.timedelta(days=17),
)
# because min_runs is 3, we should only get 3 runs because it satisfies the constraints
assert len(scheduled_runs) == 3
async def test_schedule_runs_with_min_time(self, flow, deployment, session):
scheduled_runs = await models.deployments.schedule_runs(
session,
deployment_id=deployment.id,
min_time=datetime.timedelta(days=17),
)
assert len(scheduled_runs) == 18
async def test_schedule_runs_with_start_time(self, flow, deployment, session):
scheduled_runs = await models.deployments.schedule_runs(
session,
deployment_id=deployment.id,
start_time=now("UTC") + datetime.timedelta(days=100),
end_time=now("UTC") + datetime.timedelta(days=110),
# set min runs very high to ensure we keep generating runs until we hit the end time
# note that end time has precedence over min runs
min_runs=100,
)
assert len(scheduled_runs) == 10
expected_times = {
start_of_day(now("UTC")) + datetime.timedelta(days=i + 1)
for i in range(100, 110)
}
actual_times = set()
for run_id in scheduled_runs:
run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=run_id
)
actual_times.add(run.state.state_details.scheduled_time)
assert actual_times == expected_times
async def test_schedule_runs_with_times_and_max_number(
self, flow, deployment, session
):
scheduled_runs = await models.deployments.schedule_runs(
session,
deployment_id=deployment.id,
start_time=now("UTC") + datetime.timedelta(days=100),
end_time=now("UTC") + datetime.timedelta(days=150),
max_runs=3,
)
assert len(scheduled_runs) == 3
expected_times = {
start_of_day(now("UTC")) + datetime.timedelta(days=i + 1)
for i in range(100, 103)
}
actual_times = set()
for run_id in scheduled_runs:
run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=run_id
)
actual_times.add(run.state.state_details.scheduled_time)
assert actual_times == expected_times
async def test_backfill(self, flow, deployment, session):
# backfills are just schedules for past dates...
scheduled_runs = await models.deployments.schedule_runs(
session,
deployment_id=deployment.id,
start_time=now("UTC") - datetime.timedelta(days=1000),
end_time=now("UTC") - datetime.timedelta(days=990),
# set min runs very high to ensure we keep generating runs until we hit the end time
# note that end time has precedence over min runs
min_runs=100,
)
assert len(scheduled_runs) == 10
expected_times = {
start_of_day(now("UTC")) - datetime.timedelta(days=i)
for i in range(990, 1000)
}
actual_times = set()
for run_id in scheduled_runs:
run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=run_id
)
actual_times.add(run.state.state_details.scheduled_time)
assert actual_times == expected_times
async def test_run_details_are_applied_to_scheduled_runs(self, deployment, session):
await models.deployments.schedule_runs(
session,
deployment_id=deployment.id,
)
all_runs = await models.flow_runs.read_flow_runs(session)
assert all_runs
for r in all_runs:
assert r.state_type == schemas.states.StateType.SCHEDULED
assert r.expected_start_time is not None
assert r.expected_start_time == r.next_scheduled_start_time
async def test_scheduling_multiple_batches_correctly_updates_runs(
self, session, deployment, flow_function, flow, db
):
# ensures that updating flow run states works correctly and doesn't set
# any to None inadvertently
deployment_2 = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="My second deployment",
flow_id=flow.id,
schedules=[
schemas.core.DeploymentSchedule(
schedule=schemas.schedules.IntervalSchedule(
interval=datetime.timedelta(days=1)
)
)
],
),
)
# delete all runs
await session.execute(sa.delete(orm_models.FlowRun))
# schedule runs
await models.deployments.schedule_runs(
session=session, deployment_id=deployment.id
)
result = await session.execute(
sa.select(sa.func.count(orm_models.FlowRun.id)).where(
orm_models.FlowRun.state_id.is_(None)
)
)
# no runs with missing states
assert result.scalar() == 0
# schedule more runs from a different deployment
await models.deployments.schedule_runs(
session=session, deployment_id=deployment_2.id
)
result = await session.execute(
sa.select(sa.func.count(orm_models.FlowRun.id)).where(
orm_models.FlowRun.state_id.is_(None)
)
)
# no runs with missing states
assert result.scalar() == 0
async def test_deployment_flow_run_labels_utility_function(self, session, flow):
"""Test the with_system_labels_for_deployment_flow_run utility function."""
# Create a deployment with custom labels
deployment = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="test-deployment",
flow_id=flow.id,
labels={
"deployment.custom": "value",
"environment": "test",
},
),
)
# Test the utility function with user-supplied labels
labels = await models.deployments.with_system_labels_for_deployment_flow_run(
session=session,
deployment=deployment,
user_supplied_labels={"user": "custom"},
)
# Verify all expected labels are present
assert labels["prefect.flow.id"] == str(flow.id)
assert labels["prefect.deployment.id"] == str(deployment.id)
assert labels["deployment.custom"] == "value"
assert labels["environment"] == "test"
assert labels["user"] == "custom"
# Test without user-supplied labels
labels_no_user = (
await models.deployments.with_system_labels_for_deployment_flow_run(
session=session, deployment=deployment, user_supplied_labels=None
)
)
# Verify system and deployment labels are present
assert labels_no_user["prefect.flow.id"] == str(flow.id)
assert labels_no_user["prefect.deployment.id"] == str(deployment.id)
assert labels_no_user["deployment.custom"] == "value"
assert labels_no_user["environment"] == "test"
assert "user" not in labels_no_user
async def test_manual_and_scheduled_flow_runs_have_consistent_labels(
self, session, flow
):
"""Test that manual and scheduled flow runs get consistent labels."""
# Create a deployment with custom labels and schedules
deployment = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="test-deployment",
flow_id=flow.id,
labels={
"deployment.env": "production",
"deployment.team": "data",
},
schedules=[
schemas.core.DeploymentSchedule(
schedule=schemas.schedules.IntervalSchedule(
interval=datetime.timedelta(days=1),
anchor_date=datetime.datetime(2020, 1, 1),
),
active=True,
)
],
),
)
# Create a manual flow run
manual_flow_run = await models.flow_runs.create_flow_run(
session=session,
flow_run=schemas.core.FlowRun(
flow_id=flow.id,
deployment_id=deployment.id,
labels={"run.type": "manual"},
),
)
# Create scheduled flow runs
scheduled_run_ids = await models.deployments.schedule_runs(
session=session,
deployment_id=deployment.id,
min_runs=1,
max_runs=1,
)
assert len(scheduled_run_ids) == 1
scheduled_flow_run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=scheduled_run_ids[0]
)
# Both runs should have the same system labels
expected_system_labels = {
"prefect.flow.id": str(flow.id),
"prefect.deployment.id": str(deployment.id),
}
# Both runs should have the same deployment labels
expected_deployment_labels = {
"deployment.env": "production",
"deployment.team": "data",
}
# Verify manual run has all expected labels
for key, value in expected_system_labels.items():
assert manual_flow_run.labels[key] == value
for key, value in expected_deployment_labels.items():
assert manual_flow_run.labels[key] == value
# Manual run should have its custom label
assert manual_flow_run.labels["run.type"] == "manual"
# Verify scheduled run has all expected labels
for key, value in expected_system_labels.items():
assert scheduled_flow_run.labels[key] == value
for key, value in expected_deployment_labels.items():
assert scheduled_flow_run.labels[key] == value
# Scheduled run should NOT have the manual run's custom label
assert "run.type" not in scheduled_flow_run.labels
# Verify that both runs have labels (not None)
assert manual_flow_run.labels is not None
assert scheduled_flow_run.labels is not None
# Both runs should have at least the system and deployment labels
assert len(manual_flow_run.labels) >= 4 # system + deployment + run.type
assert len(scheduled_flow_run.labels) >= 4 # system + deployment labels
async def test_scheduled_flow_runs_inherit_deployment_labels(self, session, flow):
"""Test that scheduled flow runs inherit labels from their deployment."""
# Create a deployment with multiple label types and schedules
deployment = await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
name="test-deployment",
flow_id=flow.id,
labels={
"project": "analytics",
"owner": "team-data",
"priority": "high",
"cost-center": "engineering",
},
schedules=[
schemas.core.DeploymentSchedule(
schedule=schemas.schedules.IntervalSchedule(
interval=datetime.timedelta(days=1),
anchor_date=datetime.datetime(2020, 1, 1),
),
active=True,
)
],
),
)
# Create scheduled flow runs
scheduled_run_ids = await models.deployments.schedule_runs(
session=session,
deployment_id=deployment.id,
min_runs=2,
max_runs=2,
)
assert len(scheduled_run_ids) == 2
# Check that all scheduled runs have the deployment labels
for run_id in scheduled_run_ids:
scheduled_run = await models.flow_runs.read_flow_run(
session=session, flow_run_id=run_id
)
# Should have system labels
assert scheduled_run.labels["prefect.flow.id"] == str(flow.id)
assert scheduled_run.labels["prefect.deployment.id"] == str(deployment.id)
# Should have all deployment labels
assert scheduled_run.labels["project"] == "analytics"
assert scheduled_run.labels["owner"] == "team-data"
assert scheduled_run.labels["priority"] == "high"
assert scheduled_run.labels["cost-center"] == "engineering"
# Should be auto-scheduled
assert scheduled_run.auto_scheduled is True
assert "auto-scheduled" in scheduled_run.tags
| TestScheduledRuns |
python | PyCQA__pylint | doc/data/messages/i/implicit-flag-alias/good.py | {
"start": 27,
"end": 102
} | class ____(IntFlag):
READ = 1
WRITE = 2
EXECUTE = 4
| FilePermissions |
python | huggingface__transformers | tests/repo_utils/test_check_docstrings.py | {
"start": 914,
"end": 4978
} | class ____(unittest.TestCase):
def test_replace_default_in_arg_description(self):
# Standard docstring with default.
desc_with_default = "`float`, *optional*, defaults to 2.0"
self.assertEqual(
replace_default_in_arg_description(desc_with_default, 2.0), "`float`, *optional*, defaults to 2.0"
)
self.assertEqual(
replace_default_in_arg_description(desc_with_default, 1.0), "`float`, *optional*, defaults to 1.0"
)
self.assertEqual(replace_default_in_arg_description(desc_with_default, inspect._empty), "`float`")
# Standard docstring with default but optional is not using the stars.
desc_with_default_typo = "`float`, `optional`, defaults to 2.0"
self.assertEqual(
replace_default_in_arg_description(desc_with_default_typo, 2.0), "`float`, *optional*, defaults to 2.0"
)
self.assertEqual(
replace_default_in_arg_description(desc_with_default_typo, 1.0), "`float`, *optional*, defaults to 1.0"
)
# If the default is None we do not erase the value in the docstring.
self.assertEqual(
replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*, defaults to 2.0"
)
# If the default is None (and set as such in the docstring), we do not include it.
desc_with_default = "`float`, *optional*, defaults to None"
self.assertEqual(replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*")
desc_with_default = "`float`, *optional*, defaults to `None`"
self.assertEqual(replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*")
# Operations are not replaced, but put in backtiks.
desc_with_default = "`float`, *optional*, defaults to 1/255"
self.assertEqual(
replace_default_in_arg_description(desc_with_default, 1 / 255), "`float`, *optional*, defaults to `1/255`"
)
desc_with_default = "`float`, *optional*, defaults to `1/255`"
self.assertEqual(
replace_default_in_arg_description(desc_with_default, 1 / 255), "`float`, *optional*, defaults to `1/255`"
)
desc_with_optional = "`float`, *optional*"
self.assertEqual(
replace_default_in_arg_description(desc_with_optional, 2.0), "`float`, *optional*, defaults to 2.0"
)
self.assertEqual(
replace_default_in_arg_description(desc_with_optional, 1.0), "`float`, *optional*, defaults to 1.0"
)
self.assertEqual(replace_default_in_arg_description(desc_with_optional, None), "`float`, *optional*")
self.assertEqual(replace_default_in_arg_description(desc_with_optional, inspect._empty), "`float`")
desc_with_no_optional = "`float`"
self.assertEqual(
replace_default_in_arg_description(desc_with_no_optional, 2.0), "`float`, *optional*, defaults to 2.0"
)
self.assertEqual(
replace_default_in_arg_description(desc_with_no_optional, 1.0), "`float`, *optional*, defaults to 1.0"
)
self.assertEqual(replace_default_in_arg_description(desc_with_no_optional, None), "`float`, *optional*")
self.assertEqual(replace_default_in_arg_description(desc_with_no_optional, inspect._empty), "`float`")
def test_get_default_description(self):
# Fake function to have arguments to test.
def _fake_function(a, b: int, c=1, d: float = 2.0, e: str = "blob"):
pass
params = inspect.signature(_fake_function).parameters
assert get_default_description(params["a"]) == "`<fill_type>`"
assert get_default_description(params["b"]) == "`int`"
assert get_default_description(params["c"]) == "`<fill_type>`, *optional*, defaults to 1"
assert get_default_description(params["d"]) == "`float`, *optional*, defaults to 2.0"
assert get_default_description(params["e"]) == '`str`, *optional*, defaults to `"blob"`'
| CheckDostringsTested |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 124518,
"end": 134374
} | class ____(OutputSpec):
"""
Layout base class
Carries tensor meta-information including offset and
whether it is pinned.
"""
def __init__(
self,
device: torch.device,
dtype: torch.dtype,
size: Sequence[Expr],
stride: Optional[Sequence[Expr]] = None,
offset: Expr = Integer(0),
is_pinned: bool = False,
) -> None:
if stride is None:
stride = FlexibleLayout.contiguous_strides(size)
# pyrefly: ignore [read-only]
self.device = device
self.dtype = dtype
assert len(size) == len(stride), f"size={size}, stride={stride}"
assert all(isinstance(s, (Expr, int)) for s in size)
self._size = size
self._stride = stride
self._offset = offset
self.is_pinned = is_pinned
# is_pinned implies cpu
assert (not self.is_pinned) or (self.device.type == "cpu")
@property
def size(self) -> Sequence[Expr]:
return self._size
@size.setter
def size(self, value: Sequence[Expr]) -> None:
self._size = value
@property
def stride(self) -> Sequence[Expr]:
return self._stride
@stride.setter
def stride(self, value: Sequence[Expr]) -> None:
self._stride = value
@property
def offset(self) -> Expr:
return self._offset
@offset.setter
def offset(self, value: Expr) -> None:
self._offset = value
def __str__(self) -> str:
offset = ""
if self.offset != 0:
offset = f", offset={self.offset}"
device_index_str = "" if self.device.index is None else f":{self.device.index}"
is_pinned_str = ""
if self.is_pinned:
is_pinned_str = f", is_pinned={self.is_pinned}"
return (
f"{type(self).__name__}('{self.device.type}{device_index_str}', {self.dtype}, "
f"size={self.size}, stride={self.stride}{offset}{is_pinned_str})"
)
__repr__ = __str__
def get_device(self) -> torch.device:
return self.device
def get_example(self) -> torch.Tensor:
with V.fake_mode:
return torch.empty_strided(
convert_shape_to_symint(self.size),
convert_shape_to_symint(self.stride),
dtype=self.dtype,
device=self.device,
pin_memory=self.is_pinned,
)
def is_contiguous(self) -> bool:
return is_contiguous_strides_for_shape(self.stride, self.size)
@staticmethod
def is_channels_last_contiguous(
shape: Sequence[_IntLike], strides: Sequence[_IntLike]
) -> bool:
ndim = len(shape)
if ndim not in [4, 5] or shape[1] == 1:
return False
for left, right, size in zip(
strides, make_channels_last_strides_for(shape), shape
):
if size != 1 and left != right:
return False
return True
def is_transposed(self) -> bool:
for left, right, size in zip(
self.stride,
reversed(FlexibleLayout.contiguous_strides(list(reversed(self.size)))),
self.size,
):
if size != 1 and left != right:
return False
return True
def is_stride_ordered(self, order: Sequence[int]) -> bool:
assert len(self.stride) == len(order)
# ignore dimensions of size 1, they dont affect layout
non_1_indices = [
i
for i, dim in enumerate(self.size)
if V.graph.sizevars.size_hint(dim, fallback=2) != 1
]
stride = [self.stride[i] for i in non_1_indices]
order: Sequence[int] = [order[i] for i in non_1_indices]
def sorted_indices(arr: Sequence[int]) -> Sequence[int]:
sorted_arr = sorted(arr)
return [sorted_arr.index(element) for element in arr]
# since we may have removed dimensions, need to re-sort & re-index order
order = sorted_indices(order)
# reorder the stride given order
stride_ordered = [-1] * len(order)
for i in range(len(order)):
stride_ordered[order[i]] = stride[i]
# check if it is in ascending order
for i in range(len(order) - 1):
expr = stride_ordered[i] > stride_ordered[i + 1]
if not isinstance(expr, bool):
expr = V.graph._shape_env.evaluate_expr(
stride_ordered[i] > stride_ordered[i + 1], size_oblivious=True
)
if expr:
return False
return True
def is_channels_last_stride_ordered(self) -> bool:
# create channels_last order(NCHW, NCDHW, the C is the first order).
order = [0] + list(reversed(range(1, len(self.stride) - 1)))
order = [len(order)] + order
return self.is_stride_ordered(order)
@staticmethod
def _pad_strides(
in_strides: Sequence[int], size: Sequence[Expr], dtype: torch.dtype
) -> Sequence[int]:
"""
The padding does not change stride order but makes sure all strides larger
than the threshold are multiple of align.
"""
align = get_align_for_dtype(dtype)
if len(in_strides) == 0:
return in_strides
if not config.pad_channels_last and Layout.is_channels_last_contiguous(
size, in_strides
):
return in_strides
current_fx_node = V.get_current_node()
if hasattr(current_fx_node, "meta") and current_fx_node.meta.get(
"dislike_padding", False
):
return in_strides
# Skip padding the strides for dynamic shapes based on config.pad_dynamic_shape
# Checking both shape and strides, as there are cases where only one is dynamic
is_dynamic = not all(
isinstance(s, (int, sympy.Integer))
for s in itertools.chain(in_strides, size)
)
if not config.pad_dynamic_shapes and is_dynamic:
return in_strides
shape_env = V.graph._shape_env if hasattr(V.graph, "_shape_env") else None
def contains_unbacked_symints(expr: sympy.Expr | int) -> bool:
if shape_env is None:
return False
if not isinstance(expr, sympy.Expr):
return False
return any(shape_env.is_unbacked_symint(s) for s in expr.free_symbols)
# Skip padding the strides when it contains unbacked symints for now.
if shape_env and any(contains_unbacked_symints(s) for s in in_strides):
return in_strides
stride_order = get_stride_order(in_strides, shape_env)
fill_order = stride_order2fill_order(stride_order)
new_strides = [0 for _ in range(len(in_strides))]
# since we pad when the layout is flexible, we can decide the
# smallest stride to be 1.
new_strides[fill_order[0]] = 1
padded = False
for rank, idx in enumerate(fill_order[1:], start=1):
prev_idx = fill_order[rank - 1]
stride = new_strides[prev_idx] * size[prev_idx]
# Static stride and meets padding conditions OR
# Dynamic stride and config.pad_dynamic_shape=True
require_padding = (
isinstance(stride, (int, sympy.Integer))
and stride > config.padding_stride_threshold
and stride % align != 0
) or (isinstance(stride, sympy.Expr) and config.pad_dynamic_shapes)
new_strides[idx] = stride
if require_padding:
new_strides[idx] = ceildiv(stride, align) * align
padded = True
if not padded:
# Consider a tensor with shape [256, 1, 5, 5]
# Avoid strides like [25, 5, 5, 1] being padded to equivalent strides
# [25, 25, 5, 1].
return in_strides
# pyrefly: ignore [bad-assignment]
metrics.num_comprehensive_padding += 1
return new_strides
def pad_strides(self) -> None:
assert isinstance(self, FlexibleLayout), type(self)
assert self.stride is not None
self.stride = self._pad_strides(self.stride, self.size, self.dtype)
def should_pad_strides(self) -> bool:
return config.comprehensive_padding and isinstance(self, FlexibleLayout)
def as_fixed(self) -> FixedLayout:
if isinstance(self, FixedLayout):
return self
if self.should_pad_strides():
self.pad_strides()
return FixedLayout(
self.device,
self.dtype,
self.size,
self.stride,
self.offset,
self.is_pinned,
)
def make_indexer(self) -> Callable[[Sequence[Expr]], Expr]:
assert FlexibleLayout.allow_indexing, (
f"convert {type(self).__name__} to FixedLayout first"
)
return self.as_fixed().make_indexer()
def __eq__(self, other: object) -> bool:
return (
isinstance(other, Layout)
and self.device == other.device
and self.dtype == other.dtype
and self.size == other.size
and self.stride == other.stride
and self.offset == other.offset
and self.is_pinned == other.is_pinned
)
def storage_size(self) -> Expr:
return compute_required_storage_length(self.size, self.stride, self.offset) # type: ignore[arg-type]
@cache_on_self_and_args("Layout")
def get_free_symbol_uses(
self, unbacked_only: bool = False
) -> OrderedSet[sympy.Symbol]:
return (
get_free_symbols(self.size, unbacked_only)
| get_free_symbols(self.stride, unbacked_only)
| get_free_symbols(self.offset, unbacked_only)
)
| Layout |
python | pytest-dev__pytest | testing/test_terminal.py | {
"start": 15929,
"end": 22175
} | class ____:
def test_collectonly_basic(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
def test_func():
pass
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(
[
"<Dir test_collectonly_basic0>",
" <Module test_collectonly_basic.py>",
" <Function test_func>",
]
)
def test_collectonly_skipped_module(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
pytest.skip("hello")
"""
)
result = pytester.runpytest("--collect-only", "-rs")
result.stdout.fnmatch_lines(["*ERROR collecting*"])
def test_collectonly_displays_test_description(
self, pytester: Pytester, dummy_yaml_custom_test
) -> None:
"""Used dummy_yaml_custom_test for an Item without ``obj``."""
pytester.makepyfile(
"""
def test_with_description():
''' This test has a description.
more1.
more2.'''
"""
)
result = pytester.runpytest("--collect-only", "--verbose")
result.stdout.fnmatch_lines(
[
"<Dir test_collectonly_displays_test_description0>",
" <YamlFile test1.yaml>",
" <YamlItem test1.yaml>",
" <Module test_collectonly_displays_test_description.py>",
" <Function test_with_description>",
" This test has a description.",
" ",
" more1.",
" more2.",
],
consecutive=True,
)
def test_collectonly_failed_module(self, pytester: Pytester) -> None:
pytester.makepyfile("""raise ValueError(0)""")
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*raise ValueError*", "*1 error*"])
def test_collectonly_fatal(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_collectstart(collector):
assert 0, "urgs"
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*INTERNAL*args*"])
assert result.ret == 3
def test_collectonly_simple(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
def test_func1():
pass
class TestClass(object):
def test_method(self):
pass
"""
)
result = pytester.runpytest("--collect-only", p)
# assert stderr.startswith("inserting into sys.path")
assert result.ret == 0
result.stdout.fnmatch_lines(
[
"*<Module *.py>",
"* <Function test_func1>",
"* <Class TestClass>",
"* <Function test_method>",
]
)
def test_collectonly_error(self, pytester: Pytester) -> None:
p = pytester.makepyfile("import Errlkjqweqwe")
result = pytester.runpytest("--collect-only", p)
assert result.ret == 2
result.stdout.fnmatch_lines(
textwrap.dedent(
"""\
*ERROR*
*ImportError*
*No module named *Errlk*
*1 error*
"""
).strip()
)
def test_collectonly_missing_path(self, pytester: Pytester) -> None:
"""Issue 115: failure in parseargs will cause session not to
have the items attribute."""
result = pytester.runpytest("--collect-only", "uhm_missing_path")
assert result.ret == 4
result.stderr.fnmatch_lines(
["*ERROR: file or directory not found: uhm_missing_path"]
)
def test_collectonly_quiet(self, pytester: Pytester) -> None:
pytester.makepyfile("def test_foo(): pass")
result = pytester.runpytest("--collect-only", "-q")
result.stdout.fnmatch_lines(["*test_foo*"])
def test_collectonly_more_quiet(self, pytester: Pytester) -> None:
pytester.makepyfile(test_fun="def test_foo(): pass")
result = pytester.runpytest("--collect-only", "-qq")
result.stdout.fnmatch_lines(["*test_fun.py: 1*"])
def test_collect_only_summary_status(self, pytester: Pytester) -> None:
"""Custom status depending on test selection using -k or -m. #7701."""
pytester.makepyfile(
test_collect_foo="""
def test_foo(): pass
""",
test_collect_bar="""
def test_foobar(): pass
def test_bar(): pass
""",
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines("*== 3 tests collected in * ==*")
result = pytester.runpytest("--collect-only", "test_collect_foo.py")
result.stdout.fnmatch_lines("*== 1 test collected in * ==*")
result = pytester.runpytest("--collect-only", "-k", "foo")
result.stdout.fnmatch_lines("*== 2/3 tests collected (1 deselected) in * ==*")
result = pytester.runpytest("--collect-only", "-k", "test_bar")
result.stdout.fnmatch_lines("*== 1/3 tests collected (2 deselected) in * ==*")
result = pytester.runpytest("--collect-only", "-k", "invalid")
result.stdout.fnmatch_lines("*== no tests collected (3 deselected) in * ==*")
pytester.mkdir("no_tests_here")
result = pytester.runpytest("--collect-only", "no_tests_here")
result.stdout.fnmatch_lines("*== no tests collected in * ==*")
pytester.makepyfile(
test_contains_error="""
raise RuntimeError
""",
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines("*== 3 tests collected, 1 error in * ==*")
result = pytester.runpytest("--collect-only", "-k", "foo")
result.stdout.fnmatch_lines(
"*== 2/3 tests collected (1 deselected), 1 error in * ==*"
)
| TestCollectonly |
python | doocs__leetcode | solution/0800-0899/0846.Hand of Straights/Solution2.py | {
"start": 0,
"end": 498
} | class ____:
def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
if len(hand) % groupSize:
return False
cnt = Counter(hand)
sd = SortedDict(cnt)
while sd:
x = next(iter(sd))
for y in range(x, x + groupSize):
if y not in sd:
return False
if sd[y] == 1:
del sd[y]
else:
sd[y] -= 1
return True
| Solution |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/models/metadata.py | {
"start": 1443,
"end": 1530
} | class ____(PydanticDictMixin, ConnectorMetadataDefinitionV0):
pass
| MetadataDefinition |
python | django__django | tests/admin_views/tests.py | {
"start": 308491,
"end": 309585
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.superuser = User.objects.create_superuser(
username="super", password="secret", email="super@example.com"
)
def setUp(self):
self.client.force_login(self.superuser)
def test_limit_choices_to_as_callable(self):
"""Test for ticket 2445 changes to admin."""
threepwood = Character.objects.create(
username="threepwood",
last_action=datetime.datetime.today() + datetime.timedelta(days=1),
)
marley = Character.objects.create(
username="marley",
last_action=datetime.datetime.today() - datetime.timedelta(days=1),
)
response = self.client.get(reverse("admin:admin_views_stumpjoke_add"))
# The allowed option should appear twice; the limited option should not
# appear.
self.assertContains(response, threepwood.username, count=2)
self.assertNotContains(response, marley.username)
@override_settings(ROOT_URLCONF="admin_views.urls")
| LimitChoicesToInAdminTest |
python | huggingface__transformers | tests/models/auto/test_processor_auto.py | {
"start": 2623,
"end": 20998
} | class ____(unittest.TestCase):
vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]
def setUp(self):
transformers.dynamic_module_utils.TIME_OUT_REMOTE_CODE = 0
def test_processor_from_model_shortcut(self):
processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
self.assertIsInstance(processor, Wav2Vec2Processor)
def test_processor_from_local_directory_from_repo(self):
with tempfile.TemporaryDirectory() as tmpdirname:
model_config = Wav2Vec2Config()
processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
# save in new folder
model_config.save_pretrained(tmpdirname)
processor.save_pretrained(tmpdirname)
processor = AutoProcessor.from_pretrained(tmpdirname)
self.assertIsInstance(processor, Wav2Vec2Processor)
def test_processor_from_local_subfolder_from_repo(self):
with tempfile.TemporaryDirectory() as tmpdirname:
processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
processor.save_pretrained(f"{tmpdirname}/processor_subfolder")
processor = Wav2Vec2Processor.from_pretrained(tmpdirname, subfolder="processor_subfolder")
self.assertIsInstance(processor, Wav2Vec2Processor)
def test_processor_from_local_directory_from_extractor_config(self):
with tempfile.TemporaryDirectory() as tmpdirname:
# copy relevant files
copyfile(SAMPLE_PROCESSOR_CONFIG, os.path.join(tmpdirname, FEATURE_EXTRACTOR_NAME))
copyfile(SAMPLE_VOCAB, os.path.join(tmpdirname, "vocab.json"))
copyfile(SAMPLE_CONFIG, os.path.join(tmpdirname, "config.json"))
processor = AutoProcessor.from_pretrained(tmpdirname)
self.assertIsInstance(processor, Wav2Vec2Processor)
def test_subcomponent_get_config_dict_saved_as_nested_config(self):
"""
Tests that we can get config dict of a subcomponents of a processor,
even if they were saved as nested dict in `processor_config.json`
"""
# Test feature extractor first
with tempfile.TemporaryDirectory() as tmpdirname:
processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h")
processor.save_pretrained(tmpdirname)
config_dict_1 = get_feature_extractor_config(tmpdirname)
feature_extractor_1 = Wav2Vec2FeatureExtractor(**config_dict_1)
self.assertIsInstance(feature_extractor_1, Wav2Vec2FeatureExtractor)
config_dict_2, _ = FeatureExtractionMixin.get_feature_extractor_dict(tmpdirname)
feature_extractor_2 = Wav2Vec2FeatureExtractor(**config_dict_2)
self.assertIsInstance(feature_extractor_2, Wav2Vec2FeatureExtractor)
self.assertEqual(config_dict_1, config_dict_2)
# Test image and video processors next
with tempfile.TemporaryDirectory() as tmpdirname:
processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-0.5b-ov-hf")
processor.save_pretrained(tmpdirname)
config_dict_1 = get_image_processor_config(tmpdirname)
image_processor_1 = SiglipImageProcessor(**config_dict_1)
self.assertIsInstance(image_processor_1, SiglipImageProcessor)
config_dict_2, _ = ImageProcessingMixin.get_image_processor_dict(tmpdirname)
image_processor_2 = SiglipImageProcessor(**config_dict_2)
self.assertIsInstance(image_processor_2, SiglipImageProcessor)
self.assertEqual(config_dict_1, config_dict_2)
config_dict_1 = get_video_processor_config(tmpdirname)
video_processor_1 = LlavaOnevisionVideoProcessor(**config_dict_1)
self.assertIsInstance(video_processor_1, LlavaOnevisionVideoProcessor)
config_dict_2, _ = BaseVideoProcessor.get_video_processor_dict(tmpdirname)
video_processor_2 = LlavaOnevisionVideoProcessor(**config_dict_2)
self.assertIsInstance(video_processor_2, LlavaOnevisionVideoProcessor)
self.assertEqual(config_dict_1, config_dict_2)
def test_processor_from_processor_class(self):
with tempfile.TemporaryDirectory() as tmpdirname:
feature_extractor = Wav2Vec2FeatureExtractor()
tokenizer = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h")
processor = Wav2Vec2Processor(feature_extractor, tokenizer)
# save in new folder
processor.save_pretrained(tmpdirname)
if not os.path.isfile(os.path.join(tmpdirname, PROCESSOR_NAME)):
# create one manually in order to perform this test's objective
config_dict = {"processor_class": "Wav2Vec2Processor"}
with open(os.path.join(tmpdirname, PROCESSOR_NAME), "w") as fp:
json.dump(config_dict, fp)
# drop `processor_class` in tokenizer config
with open(os.path.join(tmpdirname, TOKENIZER_CONFIG_FILE)) as f:
config_dict = json.load(f)
config_dict.pop("processor_class")
with open(os.path.join(tmpdirname, TOKENIZER_CONFIG_FILE), "w") as f:
f.write(json.dumps(config_dict))
processor = AutoProcessor.from_pretrained(tmpdirname)
self.assertIsInstance(processor, Wav2Vec2Processor)
def test_processor_from_tokenizer_processor_class(self):
with tempfile.TemporaryDirectory() as tmpdirname:
feature_extractor = Wav2Vec2FeatureExtractor()
tokenizer = AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h")
processor = Wav2Vec2Processor(feature_extractor, tokenizer)
# save in new folder
processor.save_pretrained(tmpdirname)
# drop `processor_class` in processor
with open(os.path.join(tmpdirname, PROCESSOR_NAME)) as f:
config_dict = json.load(f)
config_dict.pop("processor_class")
with open(os.path.join(tmpdirname, PROCESSOR_NAME), "w") as f:
f.write(json.dumps(config_dict))
processor = AutoProcessor.from_pretrained(tmpdirname)
self.assertIsInstance(processor, Wav2Vec2Processor)
def test_processor_from_local_directory_from_model_config(self):
with tempfile.TemporaryDirectory() as tmpdirname:
model_config = Wav2Vec2Config(processor_class="Wav2Vec2Processor")
model_config.save_pretrained(tmpdirname)
# copy relevant files
copyfile(SAMPLE_VOCAB, os.path.join(tmpdirname, "vocab.json"))
# create empty sample processor
with open(os.path.join(tmpdirname, FEATURE_EXTRACTOR_NAME), "w") as f:
f.write("{}")
processor = AutoProcessor.from_pretrained(tmpdirname)
self.assertIsInstance(processor, Wav2Vec2Processor)
def test_from_pretrained_dynamic_processor(self):
# If remote code is not set, we will time out when asking whether to load the model.
with self.assertRaises(ValueError):
processor = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor_updated")
# If remote code is disabled, we can't load this config.
with self.assertRaises(ValueError):
processor = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor_updated", trust_remote_code=False
)
processor = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor_updated", trust_remote_code=True
)
self.assertTrue(processor.special_attribute_present)
self.assertEqual(processor.__class__.__name__, "NewProcessor")
feature_extractor = processor.feature_extractor
self.assertTrue(feature_extractor.special_attribute_present)
self.assertEqual(feature_extractor.__class__.__name__, "NewFeatureExtractor")
tokenizer = processor.tokenizer
self.assertTrue(tokenizer.special_attribute_present)
self.assertEqual(tokenizer.__class__.__name__, "NewTokenizerFast")
new_processor = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor", trust_remote_code=True, use_fast=False
)
new_tokenizer = new_processor.tokenizer
self.assertTrue(new_tokenizer.special_attribute_present)
self.assertEqual(new_tokenizer.__class__.__name__, "NewTokenizerFast")
def test_new_processor_registration(self):
try:
AutoConfig.register("custom", CustomConfig)
AutoFeatureExtractor.register(CustomConfig, CustomFeatureExtractor)
AutoTokenizer.register(CustomConfig, slow_tokenizer_class=CustomTokenizer)
AutoProcessor.register(CustomConfig, CustomProcessor)
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(ValueError):
AutoProcessor.register(Wav2Vec2Config, Wav2Vec2Processor)
# Now that the config is registered, it can be used as any other config with the auto-API
feature_extractor = CustomFeatureExtractor.from_pretrained(SAMPLE_PROCESSOR_CONFIG_DIR)
with tempfile.TemporaryDirectory() as tmp_dir:
vocab_file = os.path.join(tmp_dir, "vocab.txt")
with open(vocab_file, "w", encoding="utf-8") as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens]))
tokenizer = CustomTokenizer(vocab_file)
processor = CustomProcessor(feature_extractor, tokenizer)
with tempfile.TemporaryDirectory() as tmp_dir:
processor.save_pretrained(tmp_dir)
new_processor = AutoProcessor.from_pretrained(tmp_dir)
self.assertIsInstance(new_processor, CustomProcessor)
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
if CustomConfig in PROCESSOR_MAPPING._extra_content:
del PROCESSOR_MAPPING._extra_content[CustomConfig]
if CustomConfig in MODEL_FOR_AUDIO_TOKENIZATION_MAPPING._extra_content:
del MODEL_FOR_AUDIO_TOKENIZATION_MAPPING._extra_content[CustomConfig]
def test_from_pretrained_dynamic_processor_conflict(self):
class NewFeatureExtractor(Wav2Vec2FeatureExtractor):
special_attribute_present = False
class NewTokenizer(BertTokenizer):
special_attribute_present = False
class NewProcessor(ProcessorMixin):
special_attribute_present = False
def __init__(self, feature_extractor, tokenizer):
super().__init__(feature_extractor, tokenizer)
try:
AutoConfig.register("custom", CustomConfig)
AutoFeatureExtractor.register(CustomConfig, NewFeatureExtractor)
AutoTokenizer.register(CustomConfig, slow_tokenizer_class=NewTokenizer)
AutoProcessor.register(CustomConfig, NewProcessor)
# If remote code is not set, the default is to use local classes.
processor = AutoProcessor.from_pretrained("hf-internal-testing/test_dynamic_processor_updated")
self.assertEqual(processor.__class__.__name__, "NewProcessor")
self.assertFalse(processor.special_attribute_present)
self.assertFalse(processor.feature_extractor.special_attribute_present)
self.assertFalse(processor.tokenizer.special_attribute_present)
# If remote code is disabled, we load the local ones.
processor = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor_updated", trust_remote_code=False
)
self.assertEqual(processor.__class__.__name__, "NewProcessor")
self.assertFalse(processor.special_attribute_present)
self.assertFalse(processor.feature_extractor.special_attribute_present)
self.assertFalse(processor.tokenizer.special_attribute_present)
# If remote is enabled, we load from the Hub.
processor = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor_updated", trust_remote_code=True
)
self.assertEqual(processor.__class__.__name__, "NewProcessor")
self.assertTrue(processor.special_attribute_present)
self.assertTrue(processor.feature_extractor.special_attribute_present)
self.assertTrue(processor.tokenizer.special_attribute_present)
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
if CustomConfig in PROCESSOR_MAPPING._extra_content:
del PROCESSOR_MAPPING._extra_content[CustomConfig]
if CustomConfig in MODEL_FOR_AUDIO_TOKENIZATION_MAPPING._extra_content:
del MODEL_FOR_AUDIO_TOKENIZATION_MAPPING._extra_content[CustomConfig]
def test_from_pretrained_dynamic_processor_with_extra_attributes(self):
class NewFeatureExtractor(Wav2Vec2FeatureExtractor):
pass
class NewTokenizer(BertTokenizer):
pass
class NewProcessor(ProcessorMixin):
def __init__(self, feature_extractor, tokenizer, processor_attr_1=1, processor_attr_2=True):
super().__init__(feature_extractor, tokenizer)
self.processor_attr_1 = processor_attr_1
self.processor_attr_2 = processor_attr_2
try:
AutoConfig.register("custom", CustomConfig)
AutoFeatureExtractor.register(CustomConfig, NewFeatureExtractor)
AutoTokenizer.register(CustomConfig, slow_tokenizer_class=NewTokenizer)
AutoProcessor.register(CustomConfig, NewProcessor)
# If remote code is not set, the default is to use local classes.
processor = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor_updated", processor_attr_2=False
)
self.assertEqual(processor.__class__.__name__, "NewProcessor")
self.assertEqual(processor.processor_attr_1, 1)
self.assertEqual(processor.processor_attr_2, False)
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
if CustomConfig in PROCESSOR_MAPPING._extra_content:
del PROCESSOR_MAPPING._extra_content[CustomConfig]
if CustomConfig in MODEL_FOR_AUDIO_TOKENIZATION_MAPPING._extra_content:
del MODEL_FOR_AUDIO_TOKENIZATION_MAPPING._extra_content[CustomConfig]
def test_dynamic_processor_with_specific_dynamic_subcomponents(self):
class NewFeatureExtractor(Wav2Vec2FeatureExtractor):
pass
class NewTokenizer(BertTokenizer):
pass
class NewProcessor(ProcessorMixin):
def __init__(self, feature_extractor, tokenizer):
super().__init__(feature_extractor, tokenizer)
try:
AutoConfig.register("custom", CustomConfig)
AutoFeatureExtractor.register(CustomConfig, NewFeatureExtractor)
AutoTokenizer.register(CustomConfig, slow_tokenizer_class=NewTokenizer)
AutoProcessor.register(CustomConfig, NewProcessor)
# If remote code is not set, the default is to use local classes.
processor = AutoProcessor.from_pretrained(
"hf-internal-testing/test_dynamic_processor_updated",
)
self.assertEqual(processor.__class__.__name__, "NewProcessor")
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
if CustomConfig in TOKENIZER_MAPPING._extra_content:
del TOKENIZER_MAPPING._extra_content[CustomConfig]
if CustomConfig in PROCESSOR_MAPPING._extra_content:
del PROCESSOR_MAPPING._extra_content[CustomConfig]
if CustomConfig in MODEL_FOR_AUDIO_TOKENIZATION_MAPPING._extra_content:
del MODEL_FOR_AUDIO_TOKENIZATION_MAPPING._extra_content[CustomConfig]
def test_auto_processor_creates_tokenizer(self):
processor = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-bert")
self.assertEqual(processor.__class__.__name__, "BertTokenizer")
def test_auto_processor_creates_image_processor(self):
processor = AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-convnext")
self.assertEqual(processor.__class__.__name__, "ConvNextImageProcessor")
def test_auto_processor_save_load(self):
processor = AutoProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-0.5b-ov-hf")
with tempfile.TemporaryDirectory() as tmp_dir:
processor.save_pretrained(tmp_dir)
second_processor = AutoProcessor.from_pretrained(tmp_dir)
self.assertEqual(second_processor.__class__.__name__, processor.__class__.__name__)
@is_staging_test
| AutoFeatureExtractorTest |
python | PrefectHQ__prefect | src/prefect/logging/handlers.py | {
"start": 11746,
"end": 13547
} | class ____(StreamHandler):
def __init__(
self,
stream: TextIO | None = None,
highlighter: type[Highlighter] = PrefectConsoleHighlighter,
styles: dict[str, str] | None = None,
level: int | str = logging.NOTSET,
):
"""
The default console handler for Prefect, which highlights log levels,
web and file URLs, flow and task (run) names, and state types in the
local console (terminal).
Highlighting can be toggled on/off with the PREFECT_LOGGING_COLORS setting.
For finer control, use logging.yml to add or remove styles, and/or
adjust colors.
"""
super().__init__(stream=stream)
styled_console = PREFECT_LOGGING_COLORS.value()
markup_console = PREFECT_LOGGING_MARKUP.value()
if styled_console:
highlighter_instance = highlighter()
theme = Theme(styles, inherit=False)
else:
highlighter_instance = NullHighlighter()
theme = Theme(inherit=False)
if isinstance(level, str):
self.level: int = logging.getLevelNamesMapping()[level]
else:
self.level: int = level
self.console: Console = Console(
highlighter=highlighter_instance,
theme=theme,
file=self.stream,
markup=markup_console,
)
def emit(self, record: logging.LogRecord) -> None:
try:
message = self.format(record)
self.console.print(message, soft_wrap=True)
except RecursionError:
# This was copied over from logging.StreamHandler().emit()
# https://bugs.python.org/issue36272
raise
except Exception:
self.handleError(record)
| PrefectConsoleHandler |
python | getsentry__sentry | tests/sentry/utils/test_exceptions.py | {
"start": 15625,
"end": 16953
} | class ____:
def test_basic_functionality_minimal_mocking(self) -> None:
with patch("sentry_sdk.new_scope") as mock_scope:
mock_scope_instance = Mock()
mock_scope.return_value.__enter__ = Mock(return_value=mock_scope_instance)
mock_scope.return_value.__exit__ = Mock(return_value=None)
# Use a single-element list to capture the processor
captured_processors: list[Callable[[Any, Any], Any]] = []
mock_scope_instance.add_error_processor = captured_processors.append
# Use the context manager with exception type as key
with set_sentry_exception_levels({ValueError: "warning"}):
pass
# Basic validation that processor was captured
assert len(captured_processors) == 1
processor = captured_processors[0]
# Test that it correctly processes a ValueError
event = {"level": "error", "other_data": "preserved"}
exc = ValueError("test error")
exc_info = (ValueError, exc, None)
result = processor(event, exc_info)
# Verify the level was changed and other data preserved
assert result["level"] == "warning"
assert result["other_data"] == "preserved"
| TestSetSentryExceptionLevels |
python | google__pytype | pytype/tools/analyze_project/config_test.py | {
"start": 3008,
"end": 3813
} | class ____(TestBase):
"""Test Config."""
def test_populate_from(self):
conf = config.Config()
self._validate_empty_contents(conf)
conf.populate_from(
types.SimpleNamespace(**{k: 42 for k in config.ITEMS}))
for k in config.ITEMS:
self.assertEqual(getattr(conf, k), 42)
def test_populate_from_none(self):
conf = config.Config()
self._validate_empty_contents(conf)
# None is a valid value.
conf.populate_from(
types.SimpleNamespace(**{k: None for k in config.ITEMS}))
for k in config.ITEMS:
self.assertIsNone(getattr(conf, k))
def test_populate_from_empty(self):
conf = config.Config()
conf.populate_from(object())
self._validate_empty_contents(conf)
def test_str(self):
str(config.Config()) # smoke test
| TestConfig |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/hooks/kinesis_analytics.py | {
"start": 891,
"end": 2287
} | class ____(AwsBaseHook):
"""
Interact with Amazon Kinesis Analytics V2.
Provide thin wrapper around :external+boto3:py:class:`boto3.client("kinesisanalyticsv2") <KinesisAnalyticsV2.Client>`.
Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.
.. seealso::
- :class:`airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook`
"""
APPLICATION_START_INTERMEDIATE_STATES: tuple[str, ...] = ("STARTING", "UPDATING", "AUTOSCALING")
APPLICATION_START_FAILURE_STATES: tuple[str, ...] = (
"DELETING",
"STOPPING",
"READY",
"FORCE_STOPPING",
"ROLLING_BACK",
"MAINTENANCE",
"ROLLED_BACK",
)
APPLICATION_START_SUCCESS_STATES: tuple[str, ...] = ("RUNNING",)
APPLICATION_STOP_INTERMEDIATE_STATES: tuple[str, ...] = (
"STARTING",
"UPDATING",
"AUTOSCALING",
"RUNNING",
"STOPPING",
"FORCE_STOPPING",
)
APPLICATION_STOP_FAILURE_STATES: tuple[str, ...] = (
"DELETING",
"ROLLING_BACK",
"MAINTENANCE",
"ROLLED_BACK",
)
APPLICATION_STOP_SUCCESS_STATES: tuple[str, ...] = ("READY",)
def __init__(self, *args, **kwargs) -> None:
kwargs["client_type"] = "kinesisanalyticsv2"
super().__init__(*args, **kwargs)
| KinesisAnalyticsV2Hook |
python | numpy__numpy | numpy/distutils/fcompiler/intel.py | {
"start": 6100,
"end": 6570
} | class ____(IntelVisualFCompiler):
compiler_type = 'intelvem'
description = 'Intel Visual Fortran Compiler for 64-bit apps'
version_match = simple_version_match(start=r'Intel\(R\).*?64,')
def get_flags_arch(self):
return []
if __name__ == '__main__':
from distutils import log
log.set_verbosity(2)
from numpy.distutils import customized_fcompiler
print(customized_fcompiler(compiler='intel').get_version())
| IntelEM64VisualFCompiler |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 113632,
"end": 118867
} | class ____(Request):
"""
Update existing artifacts (search by key/mode) and add new ones
:param task: Task ID
:type task: str
:param artifacts: Artifacts to add or update
:type artifacts: Sequence[Artifact]
:param force: If set to True then both new and running task artifacts can be
edited. Otherwise only the new task ones. Default is False
:type force: bool
"""
_service = "tasks"
_action = "add_or_update_artifacts"
_version = "2.23"
_schema = {
"definitions": {
"artifact": {
"properties": {
"content_size": {
"description": "Raw data length in bytes",
"type": "integer",
},
"display_data": {
"description": "User-defined list of key/value pairs, sorted",
"items": {"items": {"type": "string"}, "type": "array"},
"type": "array",
},
"hash": {
"description": "Hash of entire raw data",
"type": "string",
},
"key": {"description": "Entry key", "type": "string"},
"mode": {
"$ref": "#/definitions/artifact_mode_enum",
"description": "System defined input/output indication",
},
"timestamp": {
"description": "Epoch time when artifact was created",
"type": "integer",
},
"type": {
"description": "System defined type",
"type": "string",
},
"type_data": {
"$ref": "#/definitions/artifact_type_data",
"description": "Additional fields defined by the system",
},
"uri": {"description": "Raw data location", "type": "string"},
},
"required": ["key", "type"],
"type": "object",
},
"artifact_mode_enum": {
"default": "output",
"enum": ["input", "output"],
"type": "string",
},
"artifact_type_data": {
"properties": {
"content_type": {
"description": "System defined raw data content type",
"type": ["string", "null"],
},
"data_hash": {
"description": "Hash of raw data, without any headers or descriptive parts",
"type": ["string", "null"],
},
"preview": {
"description": "Description or textual data",
"type": ["string", "null"],
},
},
"type": "object",
},
},
"properties": {
"artifacts": {
"description": "Artifacts to add or update",
"items": {"$ref": "#/definitions/artifact"},
"type": "array",
},
"force": {
"description": (
"If set to True then both new and running task artifacts can be edited. Otherwise only the new task"
" ones. Default is False"
),
"type": "boolean",
},
"task": {"description": "Task ID", "type": "string"},
},
"required": ["task", "artifacts"],
"type": "object",
}
def __init__(self, task, artifacts, force=None, **kwargs):
super(AddOrUpdateArtifactsRequest, self).__init__(**kwargs)
self.task = task
self.artifacts = artifacts
self.force = force
@schema_property("task")
def task(self):
return self._property_task
@task.setter
def task(self, value):
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("artifacts")
def artifacts(self):
return self._property_artifacts
@artifacts.setter
def artifacts(self, value):
if value is None:
self._property_artifacts = None
return
self.assert_isinstance(value, "artifacts", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [Artifact.from_dict(v) if isinstance(v, dict) else v for v in value]
else:
self.assert_isinstance(value, "artifacts", Artifact, is_array=True)
self._property_artifacts = value
@schema_property("force")
def force(self):
return self._property_force
@force.setter
def force(self, value):
if value is None:
self._property_force = None
return
self.assert_isinstance(value, "force", (bool,))
self._property_force = value
| AddOrUpdateArtifactsRequest |
python | tensorflow__tensorflow | tensorflow/lite/python/lite.py | {
"start": 131716,
"end": 133571
} | class ____:
"""Convert a TensorFlow model into `output_format`.
This class has been deprecated. Please use `lite.TFLiteConverter` instead.
"""
@classmethod
@_deprecation.deprecated(
None, "Use `lite.TFLiteConverter.from_session` instead."
)
def from_session(cls, sess, input_tensors, output_tensors):
"""Creates a TocoConverter class from a TensorFlow Session."""
return TFLiteConverter.from_session(sess, input_tensors, output_tensors)
@classmethod
@_deprecation.deprecated(
None, "Use `lite.TFLiteConverter.from_frozen_graph` instead."
)
def from_frozen_graph(
cls, graph_def_file, input_arrays, output_arrays, input_shapes=None
):
"""Creates a TocoConverter class from a file containing a frozen graph."""
return TFLiteConverter.from_frozen_graph(
graph_def_file, input_arrays, output_arrays, input_shapes
)
@classmethod
@_deprecation.deprecated(
None, "Use `lite.TFLiteConverter.from_saved_model` instead."
)
def from_saved_model(
cls,
saved_model_dir,
input_arrays=None,
input_shapes=None,
output_arrays=None,
tag_set=None,
signature_key=None,
):
"""Creates a TocoConverter class from a SavedModel."""
return TFLiteConverter.from_saved_model(
saved_model_dir,
input_arrays,
input_shapes,
output_arrays,
tag_set,
signature_key,
)
@classmethod
@_deprecation.deprecated(
None, "Use `lite.TFLiteConverter.from_keras_model_file` instead."
)
def from_keras_model_file(
cls, model_file, input_arrays=None, input_shapes=None, output_arrays=None
):
"""Creates a TocoConverter class from a tf.keras model file."""
return TFLiteConverter.from_keras_model_file(
model_file, input_arrays, input_shapes, output_arrays
)
| TocoConverter |
python | pydantic__pydantic | tests/mypy/modules/root_models.py | {
"start": 481,
"end": 526
} | class ____(RootModel[T | None]):
pass
| Maybe |
python | django-compressor__django-compressor | compressor/filters/base.py | {
"start": 1816,
"end": 3720
} | class ____(FilterBase):
"""
A filter which takes function path in `callback` attribute, imports it
and uses that function to filter output string::
class MyFilter(CallbackOutputFilter):
callback = 'path.to.my.callback'
Callback should be a function which takes a string as first argument and
returns a string.
"""
callback = None
args = []
kwargs = {}
dependencies = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.callback is None:
raise ImproperlyConfigured(
"The callback filter %s must define a 'callback' attribute."
% self.__class__.__name__
)
try:
mod_name, func_name = get_mod_func(self.callback)
func = getattr(import_module(mod_name), func_name)
except (ImportError, TypeError):
if self.dependencies:
if len(self.dependencies) == 1:
warning = "dependency (%s) is" % self.dependencies[0]
else:
warning = "dependencies (%s) are" % ", ".join(
[dep for dep in self.dependencies]
)
else:
warning = ""
raise ImproperlyConfigured(
"The callback %s couldn't be imported. Make sure the %s "
"correctly installed." % (self.callback, warning)
)
except AttributeError as e:
raise ImproperlyConfigured(
"An error occurred while importing the "
"callback filter %s: %s" % (self, e)
)
else:
self._callback_func = func
def output(self, **kwargs):
ret = self._callback_func(self.content, *self.args, **self.kwargs)
assert isinstance(ret, str)
return ret
| CallbackOutputFilter |
python | pennersr__django-allauth | allauth/socialaccount/providers/dataporten/views.py | {
"start": 248,
"end": 2576
} | class ____(OAuth2Adapter):
provider_id = "dataporten"
access_token_url = "https://auth.dataporten.no/oauth/token" # nosec
authorize_url = "https://auth.dataporten.no/oauth/authorization"
profile_url = "https://auth.dataporten.no/userinfo"
groups_url = "https://groups-api.dataporten.no/groups/"
def complete_login(self, request, app, token, **kwargs):
"""
Arguments:
request - The get request to the callback URL
/accounts/dataporten/login/callback.
app - The corresponding SocialApp model instance
token - A token object with access token given in token.token
Returns:
Should return a dict with user information intended for parsing
by the methods of the DataportenProvider view, i.e.
extract_uid(), extract_extra_data(), and extract_common_fields()
"""
# The authentication header
headers = {"Authorization": "Bearer " + token.token}
# Userinfo endpoint, for documentation see:
# https://docs.dataporten.no/docs/oauth-authentication/
userinfo_response = (
get_adapter()
.get_requests_session()
.get(
self.profile_url,
headers=headers,
)
)
# Raise exception for 4xx and 5xx response codes
userinfo_response.raise_for_status()
# The endpoint returns json-data and it needs to be decoded
extra_data = userinfo_response.json()["user"]
# Finally test that the audience property matches the client id
# for validification reasons, as instructed by the Dataporten docs
# if the userinfo-response is used for authentication
if userinfo_response.json()["audience"] != app.client_id:
raise ProviderException(
"Dataporten returned a user with an audience field \
which does not correspond to the client id of the \
application."
)
return self.get_provider().sociallogin_from_response(
request,
extra_data,
)
oauth2_login = OAuth2LoginView.adapter_view(DataportenOAuth2Adapter)
oauth2_callback = OAuth2CallbackView.adapter_view(DataportenOAuth2Adapter)
| DataportenOAuth2Adapter |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/io.py | {
"start": 18596,
"end": 21831
} | class ____:
"""
Parquet metadata container.
Parameters
----------
paths
Parquet-dataset paths.
max_footer_samples
Maximum number of file footers to sample metadata from.
"""
__slots__ = (
"column_names",
"max_footer_samples",
"mean_size_per_file",
"num_row_groups_per_file",
"paths",
"row_count",
"sample_paths",
)
paths: tuple[str, ...]
"""Parquet-dataset paths."""
max_footer_samples: int
"""Maximum number of file footers to sample metadata from."""
row_count: ColumnStat[int]
"""Total row-count estimate."""
num_row_groups_per_file: tuple[int, ...]
"""Number of row groups in each sampled file."""
mean_size_per_file: dict[str, ColumnStat[int]]
"""Average column storage size in a single file."""
column_names: tuple[str, ...]
"""All column names found it the dataset."""
sample_paths: tuple[str, ...]
"""Sampled file paths."""
def __init__(self, paths: tuple[str, ...], max_footer_samples: int):
self.paths = paths
self.max_footer_samples = max_footer_samples
self.row_count = ColumnStat[int]()
self.num_row_groups_per_file = ()
self.mean_size_per_file = {}
self.column_names = ()
stride = (
max(1, int(len(paths) / max_footer_samples)) if max_footer_samples else 1
)
self.sample_paths = paths[: stride * max_footer_samples : stride]
if not self.sample_paths:
# No paths to sample from
return
total_file_count = len(self.paths)
sampled_file_count = len(self.sample_paths)
exact: bool = False
sample_metadata = plc.io.parquet_metadata.read_parquet_metadata(
plc.io.SourceInfo(list(self.sample_paths))
)
if total_file_count == sampled_file_count:
# We know the "exact" row_count from our sample
row_count = sample_metadata.num_rows()
exact = True
else:
# We must estimate/extrapolate the row_count from our sample
num_rows_per_sampled_file = int(
sample_metadata.num_rows() / sampled_file_count
)
row_count = num_rows_per_sampled_file * total_file_count
num_row_groups_per_sampled_file = sample_metadata.num_rowgroups_per_file()
rowgroup_offsets_per_file = list(
itertools.accumulate(num_row_groups_per_sampled_file, initial=0)
)
column_sizes_per_file = {
name: [
sum(uncompressed_sizes[start:end])
for (start, end) in itertools.pairwise(rowgroup_offsets_per_file)
]
for name, uncompressed_sizes in sample_metadata.columnchunk_metadata().items()
}
self.column_names = tuple(column_sizes_per_file)
self.mean_size_per_file = {
name: ColumnStat[int](value=int(statistics.mean(sizes)))
for name, sizes in column_sizes_per_file.items()
}
self.num_row_groups_per_file = tuple(num_row_groups_per_sampled_file)
self.row_count.value = row_count
self.row_count.exact = exact
| ParquetMetadata |
python | tensorflow__tensorflow | tensorflow/python/ops/summary_ops_v2.py | {
"start": 9227,
"end": 11931
} | class ____(metaclass=abc.ABCMeta):
"""Interface representing a stateful summary writer object."""
def set_as_default(self, step=None):
"""Enables this summary writer for the current thread.
For convenience, if `step` is not None, this function also sets a default
value for the `step` parameter used in summary-writing functions elsewhere
in the API so that it need not be explicitly passed in every such
invocation. The value can be a constant or a variable.
Note: when setting `step` in a @tf.function, the step value will be
captured at the time the function is traced, so changes to the step outside
the function will not be reflected inside the function unless using
a `tf.Variable` step.
Args:
step: An `int64`-castable default step value, or `None`. When not `None`,
the current step is modified to the given value. When `None`, the
current step is not modified.
"""
self.as_default(step).__enter__()
def as_default(self, step=None):
"""Returns a context manager that enables summary writing.
For convenience, if `step` is not None, this function also sets a default
value for the `step` parameter used in summary-writing functions elsewhere
in the API so that it need not be explicitly passed in every such
invocation. The value can be a constant or a variable.
Note: when setting `step` in a @tf.function, the step value will be
captured at the time the function is traced, so changes to the step outside
the function will not be reflected inside the function unless using
a `tf.Variable` step.
For example, `step` can be used as:
```python
with writer_a.as_default(step=10):
tf.summary.scalar(tag, value) # Logged to writer_a with step 10
with writer_b.as_default(step=20):
tf.summary.scalar(tag, value) # Logged to writer_b with step 20
tf.summary.scalar(tag, value) # Logged to writer_a with step 10
```
Args:
step: An `int64`-castable default step value, or `None`. When not `None`,
the current step is captured, replaced by a given one, and the original
one is restored when the context manager exits. When `None`, the current
step is not modified (and not restored when the context manager exits).
Returns:
The context manager.
"""
return _SummaryContextManager(self, step)
def init(self):
"""Initializes the summary writer."""
raise NotImplementedError()
def flush(self):
"""Flushes any buffered data."""
raise NotImplementedError()
def close(self):
"""Flushes and closes the summary writer."""
raise NotImplementedError()
| SummaryWriter |
python | python__mypy | test-data/unit/plugins/magic_method.py | {
"start": 492,
"end": 851
} | class ____(Plugin):
def get_method_hook(self, fullname: str) -> Optional[Callable[[MethodContext], Type]]:
if fullname == 'builtins.int.__add__':
return type_add
if fullname == 'builtins.int.__radd__':
return type_radd
return None
def plugin(version: str) -> type[TestPlugin]:
return TestPlugin
| TestPlugin |
python | kamyu104__LeetCode-Solutions | Python/walking-robot-simulation.py | {
"start": 33,
"end": 815
} | class ____(object):
def robotSim(self, commands, obstacles):
"""
:type commands: List[int]
:type obstacles: List[List[int]]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
x, y, i = 0, 0, 0
lookup = set(map(tuple, obstacles))
result = 0
for cmd in commands:
if cmd == -2:
i = (i-1) % 4
elif cmd == -1:
i = (i+1) % 4
else:
for k in xrange(cmd):
if (x+directions[i][0], y+directions[i][1]) not in lookup:
x += directions[i][0]
y += directions[i][1]
result = max(result, x*x + y*y)
return result
| Solution |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-dashscope/tests/test_dashscope.py | {
"start": 408,
"end": 1339
} | class ____:
def __init__(self, data: dict):
self.status_code = data["status_code"]
self.output = SimpleNamespace(**data["output"])
def __repr__(self) -> str:
return f"<FakeDashscopeResponse status_code={self.status_code}>"
@pytest.fixture()
def dashscope_llm():
return DashScope(api_key="test")
@pytest.fixture()
def dashscope_api_response():
return {
"status_code": 200,
"request_id": "4438deec-2d21-9b9c-b405-a47459fd8f75",
"code": "",
"message": "",
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {"role": "assistant", "content": "hi, there!"},
}
]
},
"usage": {"total_tokens": 161, "output_tokens": 91, "input_tokens": 70},
}
@pytest.fixture()
def prompt() -> str:
return "hi, there!"
| FakeDashscopeResponse |
python | pandas-dev__pandas | pandas/tests/extension/test_arrow.py | {
"start": 7810,
"end": 40579
} | class ____(base.ExtensionTests):
def _construct_for_combine_add(self, left, right):
dtype = left.dtype
# in a couple cases, addition is not dtype-preserving
if dtype == "bool[pyarrow]":
dtype = pandas_dtype("int64[pyarrow]")
elif dtype == "int8[pyarrow]" and isinstance(right, type(left)):
dtype = pandas_dtype("int64[pyarrow]")
if isinstance(right, type(left)):
return left._from_sequence(
[a + b for (a, b) in zip(list(left), list(right))],
dtype=dtype,
)
else:
return left._from_sequence(
[a + right for a in list(left)],
dtype=dtype,
)
def test_compare_scalar(self, data, comparison_op):
ser = pd.Series(data)
self._compare_other(ser, data, comparison_op, data[0])
@pytest.mark.parametrize("na_action", [None, "ignore"])
def test_map(self, data_missing, na_action, using_nan_is_na):
if data_missing.dtype.kind in "mM":
result = data_missing.map(lambda x: x, na_action=na_action)
expected = data_missing.to_numpy(dtype=object)
tm.assert_numpy_array_equal(result, expected)
else:
result = data_missing.map(lambda x: x, na_action=na_action)
if data_missing.dtype == "float32[pyarrow]" and using_nan_is_na:
# map roundtrips through objects, which converts to float64
expected = data_missing.to_numpy(dtype="float64", na_value=np.nan)
else:
expected = data_missing.to_numpy()
tm.assert_numpy_array_equal(result, expected)
def test_astype_str(self, data, request, using_infer_string):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_binary(pa_dtype):
request.applymarker(
pytest.mark.xfail(
reason=f"For {pa_dtype} .astype(str) decodes.",
)
)
elif not using_infer_string and (
(pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is None)
or pa.types.is_duration(pa_dtype)
):
request.applymarker(
pytest.mark.xfail(
reason="pd.Timestamp/pd.Timedelta repr different from numpy repr",
)
)
super().test_astype_str(data)
def test_from_dtype(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_string(pa_dtype) or pa.types.is_decimal(pa_dtype):
if pa.types.is_string(pa_dtype):
reason = "ArrowDtype(pa.string()) != StringDtype('pyarrow')"
else:
reason = f"pyarrow.type_for_alias cannot infer {pa_dtype}"
request.applymarker(
pytest.mark.xfail(
reason=reason,
)
)
super().test_from_dtype(data)
def test_from_sequence_pa_array(self, data):
# https://github.com/pandas-dev/pandas/pull/47034#discussion_r955500784
# data._pa_array = pa.ChunkedArray
result = type(data)._from_sequence(data._pa_array, dtype=data.dtype)
tm.assert_extension_array_equal(result, data)
assert isinstance(result._pa_array, pa.ChunkedArray)
result = type(data)._from_sequence(
data._pa_array.combine_chunks(), dtype=data.dtype
)
tm.assert_extension_array_equal(result, data)
assert isinstance(result._pa_array, pa.ChunkedArray)
def test_from_sequence_pa_array_notimplemented(self, request):
dtype = ArrowDtype(pa.month_day_nano_interval())
with pytest.raises(NotImplementedError, match="Converting strings to"):
ArrowExtensionArray._from_sequence_of_strings(["12-1"], dtype=dtype)
def test_from_sequence_of_strings_pa_array(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None:
_require_timezone_database(request)
pa_array = data._pa_array.cast(pa.string())
result = type(data)._from_sequence_of_strings(pa_array, dtype=data.dtype)
tm.assert_extension_array_equal(result, data)
pa_array = pa_array.combine_chunks()
result = type(data)._from_sequence_of_strings(pa_array, dtype=data.dtype)
tm.assert_extension_array_equal(result, data)
def check_accumulate(self, ser, op_name, skipna):
result = getattr(ser, op_name)(skipna=skipna)
pa_type = ser.dtype.pyarrow_dtype
if pa.types.is_temporal(pa_type):
# Just check that we match the integer behavior.
if pa_type.bit_width == 32:
int_type = "int32[pyarrow]"
else:
int_type = "int64[pyarrow]"
ser = ser.astype(int_type)
result = result.astype(int_type)
result = result.astype("Float64")
expected = getattr(ser.astype("Float64"), op_name)(skipna=skipna)
tm.assert_series_equal(result, expected, check_dtype=False)
def _supports_accumulation(self, ser: pd.Series, op_name: str) -> bool:
# error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has no
# attribute "pyarrow_dtype"
pa_type = ser.dtype.pyarrow_dtype # type: ignore[union-attr]
if pa.types.is_binary(pa_type) or pa.types.is_decimal(pa_type):
if op_name in ["cumsum", "cumprod", "cummax", "cummin"]:
return False
elif pa.types.is_string(pa_type):
if op_name == "cumprod":
return False
elif pa.types.is_boolean(pa_type):
if op_name in ["cumprod", "cummax", "cummin"]:
return False
elif pa.types.is_temporal(pa_type):
if op_name == "cumsum" and not pa.types.is_duration(pa_type):
return False
elif op_name == "cumprod":
return False
return True
@pytest.mark.parametrize("skipna", [True, False])
def test_accumulate_series(self, data, all_numeric_accumulations, skipna, request):
pa_type = data.dtype.pyarrow_dtype
op_name = all_numeric_accumulations
if pa.types.is_string(pa_type) and op_name in ["cumsum", "cummin", "cummax"]:
# https://github.com/pandas-dev/pandas/pull/60633
# Doesn't fit test structure, tested in series/test_cumulative.py instead.
return
ser = pd.Series(data)
if not self._supports_accumulation(ser, op_name):
# The base class test will check that we raise
return super().test_accumulate_series(
data, all_numeric_accumulations, skipna
)
if all_numeric_accumulations == "cumsum" and (
pa.types.is_boolean(pa_type) or pa.types.is_decimal(pa_type)
):
request.applymarker(
pytest.mark.xfail(
reason=f"{all_numeric_accumulations} not implemented for {pa_type}",
raises=TypeError,
)
)
self.check_accumulate(ser, op_name, skipna)
def _supports_reduction(self, ser: pd.Series, op_name: str) -> bool:
if op_name == "kurt" or (pa_version_under20p0 and op_name == "skew"):
return False
dtype = ser.dtype
# error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has
# no attribute "pyarrow_dtype"
pa_dtype = dtype.pyarrow_dtype # type: ignore[union-attr]
if pa.types.is_temporal(pa_dtype) and op_name in ["sum", "var", "prod", "skew"]:
if pa.types.is_duration(pa_dtype) and op_name in ["sum"]:
# summing timedeltas is one case that *is* well-defined
pass
else:
return False
elif pa.types.is_binary(pa_dtype) and op_name in ["sum", "skew"]:
return False
elif (
pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
) and op_name in ["mean", "median", "prod", "std", "sem", "var", "skew"]:
return False
if (
pa.types.is_temporal(pa_dtype)
and not pa.types.is_duration(pa_dtype)
and op_name in ["any", "all"]
):
# xref GH#34479 we support this in our non-pyarrow datetime64 dtypes,
# but it isn't obvious we _should_. For now, we keep the pyarrow
# behavior which does not support this.
return False
if pa.types.is_boolean(pa_dtype) and op_name in [
"median",
"std",
"var",
"skew",
"kurt",
"sem",
]:
return False
return True
def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool):
# error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has no
# attribute "pyarrow_dtype"
pa_dtype = ser.dtype.pyarrow_dtype # type: ignore[union-attr]
if pa.types.is_integer(pa_dtype) or pa.types.is_floating(pa_dtype):
alt = ser.astype("Float64")
else:
# TODO: in the opposite case, aren't we testing... nothing? For
# e.g. date/time dtypes trying to calculate 'expected' by converting
# to object will raise for mean, std etc
alt = ser
# TODO: in the opposite case, aren't we testing... nothing?
if op_name == "count":
result = getattr(ser, op_name)()
expected = getattr(alt, op_name)()
else:
result = getattr(ser, op_name)(skipna=skipna)
expected = getattr(alt, op_name)(skipna=skipna)
tm.assert_almost_equal(result, expected)
@pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_boolean(
self, data, all_boolean_reductions, skipna, na_value, request
):
pa_dtype = data.dtype.pyarrow_dtype
xfail_mark = pytest.mark.xfail(
raises=TypeError,
reason=(
f"{all_boolean_reductions} is not implemented in "
f"pyarrow={pa.__version__} for {pa_dtype}"
),
)
if pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype):
# We *might* want to make this behave like the non-pyarrow cases,
# but have not yet decided.
request.applymarker(xfail_mark)
return super().test_reduce_series_boolean(data, all_boolean_reductions, skipna)
def _get_expected_reduction_dtype(self, arr, op_name: str, skipna: bool):
pa_type = arr._pa_array.type
if op_name in ["max", "min"]:
cmp_dtype = arr.dtype
elif pa.types.is_temporal(pa_type):
if op_name in ["std", "sem"]:
if pa.types.is_duration(pa_type):
cmp_dtype = arr.dtype
elif pa.types.is_date(pa_type):
cmp_dtype = ArrowDtype(pa.duration("s"))
elif pa.types.is_time(pa_type):
cmp_dtype = ArrowDtype(pa.duration(pa_type.unit))
else:
cmp_dtype = ArrowDtype(pa.duration(pa_type.unit))
else:
cmp_dtype = arr.dtype
elif arr.dtype.name == "decimal128(7, 3)[pyarrow]":
if op_name == "sum" and not pa_version_under21p0:
# https://github.com/apache/arrow/pull/44184
cmp_dtype = ArrowDtype(pa.decimal128(38, 3))
elif op_name not in ["median", "var", "std", "sem", "skew"]:
cmp_dtype = arr.dtype
else:
cmp_dtype = "float64[pyarrow]"
elif op_name in ["median", "var", "std", "mean", "skew", "sem"]:
cmp_dtype = "float64[pyarrow]"
elif op_name in ["sum", "prod"] and pa.types.is_boolean(pa_type):
cmp_dtype = "uint64[pyarrow]"
elif op_name == "sum" and pa.types.is_string(pa_type):
cmp_dtype = arr.dtype
else:
cmp_dtype = {
"i": "int64[pyarrow]",
"u": "uint64[pyarrow]",
"f": "float64[pyarrow]",
}[arr.dtype.kind]
return cmp_dtype
@pytest.mark.filterwarnings("ignore::RuntimeWarning")
@pytest.mark.parametrize("skipna", [True, False])
def test_reduce_series_numeric(self, data, all_numeric_reductions, skipna, request):
if (
not pa_version_under20p0
and skipna
and all_numeric_reductions == "skew"
and (
pa.types.is_integer(data.dtype.pyarrow_dtype)
or pa.types.is_floating(data.dtype.pyarrow_dtype)
)
):
request.applymarker(
pytest.mark.xfail(
reason="https://github.com/apache/arrow/issues/45733",
)
)
return super().test_reduce_series_numeric(data, all_numeric_reductions, skipna)
@pytest.mark.parametrize("skipna", [True, False])
def test_reduce_frame(self, data, all_numeric_reductions, skipna, request):
op_name = all_numeric_reductions
if op_name == "skew" and pa_version_under20p0:
if data.dtype._is_numeric:
mark = pytest.mark.xfail(reason="skew not implemented")
request.applymarker(mark)
elif (
op_name in ["std", "sem"]
and pa.types.is_date64(data._pa_array.type)
and skipna
):
# overflow
mark = pytest.mark.xfail(reason="Cannot cast")
request.applymarker(mark)
return super().test_reduce_frame(data, all_numeric_reductions, skipna)
@pytest.mark.parametrize("typ", ["int64", "uint64", "float64"])
def test_median_not_approximate(self, typ):
# GH 52679
result = pd.Series([1, 2], dtype=f"{typ}[pyarrow]").median()
assert result == 1.5
def test_construct_from_string_own_name(self, dtype, request):
pa_dtype = dtype.pyarrow_dtype
if pa.types.is_decimal(pa_dtype):
request.applymarker(
pytest.mark.xfail(
raises=NotImplementedError,
reason=f"pyarrow.type_for_alias cannot infer {pa_dtype}",
)
)
if pa.types.is_string(pa_dtype):
# We still support StringDtype('pyarrow') over ArrowDtype(pa.string())
msg = r"string\[pyarrow\] should be constructed by StringDtype"
with pytest.raises(TypeError, match=msg):
dtype.construct_from_string(dtype.name)
return
super().test_construct_from_string_own_name(dtype)
def test_is_dtype_from_name(self, dtype, request):
pa_dtype = dtype.pyarrow_dtype
if pa.types.is_string(pa_dtype):
# We still support StringDtype('pyarrow') over ArrowDtype(pa.string())
assert not type(dtype).is_dtype(dtype.name)
else:
if pa.types.is_decimal(pa_dtype):
request.applymarker(
pytest.mark.xfail(
raises=NotImplementedError,
reason=f"pyarrow.type_for_alias cannot infer {pa_dtype}",
)
)
super().test_is_dtype_from_name(dtype)
def test_construct_from_string_another_type_raises(self, dtype):
msg = r"'another_type' must end with '\[pyarrow\]'"
with pytest.raises(TypeError, match=msg):
type(dtype).construct_from_string("another_type")
def test_get_common_dtype(self, dtype, request):
pa_dtype = dtype.pyarrow_dtype
if (
pa.types.is_date(pa_dtype)
or pa.types.is_time(pa_dtype)
or (pa.types.is_timestamp(pa_dtype) and pa_dtype.tz is not None)
or pa.types.is_binary(pa_dtype)
or pa.types.is_decimal(pa_dtype)
):
request.applymarker(
pytest.mark.xfail(
reason=(
f"{pa_dtype} does not have associated numpy "
f"dtype findable by find_common_type"
)
)
)
super().test_get_common_dtype(dtype)
def test_is_not_string_type(self, dtype):
pa_dtype = dtype.pyarrow_dtype
if pa.types.is_string(pa_dtype):
assert is_string_dtype(dtype)
else:
super().test_is_not_string_type(dtype)
@pytest.mark.xfail(
reason="GH 45419: pyarrow.ChunkedArray does not support views.", run=False
)
def test_view(self, data):
super().test_view(data)
def test_fillna_no_op_returns_copy(self, data):
data = data[~data.isna()]
valid = data[0]
result = data.fillna(valid)
assert result is not data
tm.assert_extension_array_equal(result, data)
def test_fillna_readonly(self, data_missing):
data = data_missing.copy()
data._readonly = True
# by default fillna(copy=True), then this works fine
result = data.fillna(data_missing[1])
assert result[0] == data_missing[1]
tm.assert_extension_array_equal(data, data_missing)
# fillna(copy=False) is generally not honored by Arrow-backed array,
# but always returns new data -> same result as above
result = data.fillna(data_missing[1])
assert result[0] == data_missing[1]
tm.assert_extension_array_equal(data, data_missing)
@pytest.mark.xfail(
reason="GH 45419: pyarrow.ChunkedArray does not support views", run=False
)
def test_transpose(self, data):
super().test_transpose(data)
@pytest.mark.xfail(
reason="GH 45419: pyarrow.ChunkedArray does not support views", run=False
)
def test_setitem_preserves_views(self, data):
super().test_setitem_preserves_views(data)
@pytest.mark.parametrize("dtype_backend", ["pyarrow", no_default])
@pytest.mark.parametrize("engine", ["c", "python"])
def test_EA_types(self, engine, data, dtype_backend, request, using_nan_is_na):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_decimal(pa_dtype):
request.applymarker(
pytest.mark.xfail(
raises=NotImplementedError,
reason=f"Parameterized types {pa_dtype} not supported.",
)
)
elif pa.types.is_timestamp(pa_dtype) and pa_dtype.unit in ("us", "ns"):
request.applymarker(
pytest.mark.xfail(
raises=ValueError,
reason="https://github.com/pandas-dev/pandas/issues/49767",
)
)
elif pa.types.is_binary(pa_dtype):
request.applymarker(
pytest.mark.xfail(reason="CSV parsers don't correctly handle binary")
)
df = pd.DataFrame({"with_dtype": pd.Series(data, dtype=str(data.dtype))})
if not using_nan_is_na:
csv_output = df.to_csv(index=False, na_rep="NA")
else:
csv_output = df.to_csv(index=False, na_rep=np.nan)
if pa.types.is_binary(pa_dtype):
csv_output = BytesIO(csv_output)
else:
csv_output = StringIO(csv_output)
result = pd.read_csv(
csv_output,
dtype={"with_dtype": str(data.dtype)},
engine=engine,
dtype_backend=dtype_backend,
)
expected = df
tm.assert_frame_equal(result, expected)
def test_invert(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if not (
pa.types.is_boolean(pa_dtype)
or pa.types.is_integer(pa_dtype)
or pa.types.is_string(pa_dtype)
):
request.applymarker(
pytest.mark.xfail(
raises=pa.ArrowNotImplementedError,
reason=f"pyarrow.compute.invert does support {pa_dtype}",
)
)
if PY312 and pa.types.is_boolean(pa_dtype):
with tm.assert_produces_warning(
DeprecationWarning, match="Bitwise inversion", check_stacklevel=False
):
super().test_invert(data)
else:
super().test_invert(data)
@pytest.mark.parametrize("periods", [1, -2])
def test_diff(self, data, periods, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_unsigned_integer(pa_dtype) and periods == 1:
request.applymarker(
pytest.mark.xfail(
raises=pa.ArrowInvalid,
reason=(
f"diff with {pa_dtype} and periods={periods} will overflow"
),
)
)
super().test_diff(data, periods)
def test_value_counts_returns_pyarrow_int64(self, data):
# GH 51462
data = data[:10]
result = data.value_counts()
assert result.dtype == ArrowDtype(pa.int64())
_combine_le_expected_dtype = "bool[pyarrow]"
def get_op_from_name(self, op_name):
short_opname = op_name.strip("_")
if short_opname == "rtruediv":
# use the numpy version that won't raise on division by zero
def rtruediv(x, y):
return np.divide(y, x)
return rtruediv
elif short_opname == "rfloordiv":
return lambda x, y: np.floor_divide(y, x)
return tm.get_op_from_name(op_name)
# TODO: use EA._cast_pointwise_result, same with other test files that
# override this
def _cast_pointwise_result(self, op_name: str, obj, other, pointwise_result):
# BaseOpsUtil._combine can upcast expected dtype
# (because it generates expected on python scalars)
# while ArrowExtensionArray maintains original type
expected = pointwise_result
if op_name in ["eq", "ne", "lt", "le", "gt", "ge"]:
return pointwise_result.astype("boolean[pyarrow]")
original_dtype = tm.get_dtype(expected)
was_frame = False
if isinstance(expected, pd.DataFrame):
was_frame = True
expected_data = expected.iloc[:, 0]
else:
expected_data = expected
# the pointwise method will have retained our original dtype, while
# the op(ser, other) version will have cast to 64bit
if type(other) is int and op_name not in ["__floordiv__"]:
if original_dtype.kind == "f":
return expected.astype("float64[pyarrow]")
else:
return expected.astype("int64[pyarrow]")
elif type(other) is float:
return expected.astype("float64[pyarrow]")
# error: Item "ExtensionDtype" of "dtype[Any] | ExtensionDtype" has
# no attribute "pyarrow_dtype"
orig_pa_type = original_dtype.pyarrow_dtype # type: ignore[union-attr]
if not was_frame and isinstance(other, pd.Series):
# i.e. test_arith_series_with_array
if not (
pa.types.is_floating(orig_pa_type)
or (
pa.types.is_integer(orig_pa_type)
and op_name not in ["__truediv__", "__rtruediv__"]
)
or pa.types.is_duration(orig_pa_type)
or pa.types.is_timestamp(orig_pa_type)
or pa.types.is_date(orig_pa_type)
or pa.types.is_decimal(orig_pa_type)
):
# base class _combine always returns int64, while
# ArrowExtensionArray does not upcast
return expected
elif not (
(op_name == "__floordiv__" and pa.types.is_integer(orig_pa_type))
or pa.types.is_duration(orig_pa_type)
or pa.types.is_timestamp(orig_pa_type)
or pa.types.is_date(orig_pa_type)
or pa.types.is_decimal(orig_pa_type)
):
# base class _combine always returns int64, while
# ArrowExtensionArray does not upcast
return expected
pa_expected = pa.array(expected_data._values)
if pa.types.is_decimal(pa_expected.type) and pa.types.is_decimal(orig_pa_type):
# decimal precision can resize in the result type depending on data
# just compare the float values
alt = getattr(obj, op_name)(other)
alt_dtype = tm.get_dtype(alt)
assert isinstance(alt_dtype, ArrowDtype)
if op_name == "__pow__" and isinstance(other, Decimal):
# TODO: would it make more sense to retain Decimal here?
alt_dtype = ArrowDtype(pa.float64())
elif (
op_name == "__pow__"
and isinstance(other, pd.Series)
and other.dtype == original_dtype
):
# TODO: would it make more sense to retain Decimal here?
alt_dtype = ArrowDtype(pa.float64())
else:
assert pa.types.is_decimal(alt_dtype.pyarrow_dtype)
return expected.astype(alt_dtype)
else:
pa_expected = pa_expected.cast(orig_pa_type)
pd_expected = type(expected_data._values)(pa_expected)
if was_frame:
expected = pd.DataFrame(
pd_expected, index=expected.index, columns=expected.columns
)
else:
expected = pd.Series(pd_expected)
return expected
def _is_temporal_supported(self, opname, pa_dtype):
return (
(
opname in ("__add__", "__radd__")
or (
opname
in ("__truediv__", "__rtruediv__", "__floordiv__", "__rfloordiv__")
and not pa_version_under14p0
)
)
and pa.types.is_duration(pa_dtype)
) or (opname in ("__sub__", "__rsub__") and pa.types.is_temporal(pa_dtype))
def _get_expected_exception(
self, op_name: str, obj, other
) -> type[Exception] | tuple[type[Exception], ...] | None:
if op_name in ("__divmod__", "__rdivmod__"):
return (NotImplementedError, TypeError)
exc: type[Exception] | tuple[type[Exception], ...] | None
dtype = tm.get_dtype(obj)
# error: Item "dtype[Any]" of "dtype[Any] | ExtensionDtype" has no
# attribute "pyarrow_dtype"
pa_dtype = dtype.pyarrow_dtype # type: ignore[union-attr]
arrow_temporal_supported = self._is_temporal_supported(op_name, pa_dtype)
if op_name in {
"__mod__",
"__rmod__",
}:
exc = (NotImplementedError, TypeError)
elif arrow_temporal_supported:
exc = None
elif op_name in ["__add__", "__radd__"] and (
pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
):
exc = None
elif not (
pa.types.is_floating(pa_dtype)
or pa.types.is_integer(pa_dtype)
or pa.types.is_decimal(pa_dtype)
):
exc = TypeError
else:
exc = None
return exc
def _get_arith_xfail_marker(self, opname, pa_dtype):
mark = None
arrow_temporal_supported = self._is_temporal_supported(opname, pa_dtype)
if opname == "__rpow__" and (
pa.types.is_floating(pa_dtype)
or pa.types.is_integer(pa_dtype)
or pa.types.is_decimal(pa_dtype)
):
mark = pytest.mark.xfail(
reason=(
f"GH#29997: 1**pandas.NA == 1 while 1**pyarrow.NA == NULL "
f"for {pa_dtype}"
)
)
elif arrow_temporal_supported and (
pa.types.is_time(pa_dtype)
or (
opname
in ("__truediv__", "__rtruediv__", "__floordiv__", "__rfloordiv__")
and pa.types.is_duration(pa_dtype)
)
):
mark = pytest.mark.xfail(
raises=TypeError,
reason=(
f"{opname} not supported betweenpd.NA and {pa_dtype} Python scalar"
),
)
elif opname == "__rfloordiv__" and (
pa.types.is_integer(pa_dtype) or pa.types.is_decimal(pa_dtype)
):
mark = pytest.mark.xfail(
raises=pa.ArrowInvalid,
reason="divide by 0",
)
elif opname == "__rtruediv__" and pa.types.is_decimal(pa_dtype):
mark = pytest.mark.xfail(
raises=pa.ArrowInvalid,
reason="divide by 0",
)
return mark
def test_arith_series_with_scalar(self, data, all_arithmetic_operators, request):
pa_dtype = data.dtype.pyarrow_dtype
if all_arithmetic_operators == "__rmod__" and pa.types.is_binary(pa_dtype):
pytest.skip("Skip testing Python string formatting")
mark = self._get_arith_xfail_marker(all_arithmetic_operators, pa_dtype)
if mark is not None:
request.applymarker(mark)
super().test_arith_series_with_scalar(data, all_arithmetic_operators)
def test_arith_frame_with_scalar(self, data, all_arithmetic_operators, request):
pa_dtype = data.dtype.pyarrow_dtype
if all_arithmetic_operators == "__rmod__" and (
pa.types.is_string(pa_dtype) or pa.types.is_binary(pa_dtype)
):
pytest.skip("Skip testing Python string formatting")
mark = self._get_arith_xfail_marker(all_arithmetic_operators, pa_dtype)
if mark is not None:
request.applymarker(mark)
super().test_arith_frame_with_scalar(data, all_arithmetic_operators)
def test_arith_series_with_array(self, data, all_arithmetic_operators, request):
pa_dtype = data.dtype.pyarrow_dtype
if all_arithmetic_operators in (
"__sub__",
"__rsub__",
) and pa.types.is_unsigned_integer(pa_dtype):
request.applymarker(
pytest.mark.xfail(
raises=pa.ArrowInvalid,
reason=(
f"Implemented pyarrow.compute.subtract_checked "
f"which raises on overflow for {pa_dtype}"
),
)
)
mark = self._get_arith_xfail_marker(all_arithmetic_operators, pa_dtype)
if mark is not None:
request.applymarker(mark)
op_name = all_arithmetic_operators
ser = pd.Series(data)
# pd.Series([ser.iloc[0]] * len(ser)) may not return ArrowExtensionArray
# since ser.iloc[0] is a python scalar
other = pd.Series(pd.array([ser.iloc[0]] * len(ser), dtype=data.dtype))
self.check_opname(ser, op_name, other)
def test_add_series_with_extension_array(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa_dtype.equals("int8"):
request.applymarker(
pytest.mark.xfail(
raises=pa.ArrowInvalid,
reason=f"raises on overflow for {pa_dtype}",
)
)
super().test_add_series_with_extension_array(data)
def test_invalid_other_comp(self, data, comparison_op):
# GH 48833
with pytest.raises(
NotImplementedError, match=".* not implemented for <class 'object'>"
):
comparison_op(data, object())
@pytest.mark.parametrize("masked_dtype", ["boolean", "Int64", "Float64"])
def test_comp_masked_numpy(self, masked_dtype, comparison_op):
# GH 52625
data = [1, 0, None]
ser_masked = pd.Series(data, dtype=masked_dtype)
ser_pa = pd.Series(data, dtype=f"{masked_dtype.lower()}[pyarrow]")
result = comparison_op(ser_pa, ser_masked)
if comparison_op in [operator.lt, operator.gt, operator.ne]:
exp = [False, False, None]
else:
exp = [True, True, None]
expected = pd.Series(exp, dtype=ArrowDtype(pa.bool_()))
tm.assert_series_equal(result, expected)
def test_loc_setitem_with_expansion_preserves_ea_index_dtype(self, data, request):
pa_dtype = data.dtype.pyarrow_dtype
if pa.types.is_date(pa_dtype):
mark = pytest.mark.xfail(
reason="GH#62343 incorrectly casts to timestamp[ms][pyarrow]"
)
request.applymarker(mark)
super().test_loc_setitem_with_expansion_preserves_ea_index_dtype(data)
| TestArrowArray |
python | ansible__ansible | lib/ansible/modules/hostname.py | {
"start": 26052,
"end": 26173
} | class ____(Hostname):
platform = 'FreeBSD'
distribution = None
strategy_class = FreeBSDStrategy
| FreeBSDHostname |
python | davidhalter__parso | test/test_parser_tree.py | {
"start": 204,
"end": 8273
} | class ____:
FIXTURES = [
('def my_function(x, y, z) -> str:\n return x + y * z\n', {
'name': 'my_function',
'call_sig': 'my_function(x, y, z)',
'params': ['x', 'y', 'z'],
'annotation': "str",
}),
('lambda x, y, z: x + y * z\n', {
'name': '<lambda>',
'call_sig': '<lambda>(x, y, z)',
'params': ['x', 'y', 'z'],
}),
]
@pytest.fixture(params=FIXTURES)
def node(self, request):
parsed = parse(dedent(request.param[0]), version='3.10')
request.keywords['expected'] = request.param[1]
child = parsed.children[0]
if child.type == 'simple_stmt':
child = child.children[0]
return child
@pytest.fixture()
def expected(self, request, node):
return request.keywords['expected']
def test_name(self, node, expected):
if node.type != 'lambdef':
assert isinstance(node.name, tree.Name)
assert node.name.value == expected['name']
def test_params(self, node, expected):
assert isinstance(node.get_params(), list)
assert all(isinstance(x, tree.Param) for x in node.get_params())
assert [str(x.name.value) for x in node.get_params()] == [x for x in expected['params']]
def test_is_generator(self, node, expected):
assert node.is_generator() is expected.get('is_generator', False)
def test_yields(self, node, expected):
assert node.is_generator() == expected.get('yields', False)
def test_annotation(self, node, expected):
expected_annotation = expected.get('annotation', None)
if expected_annotation is None:
assert node.annotation is None
else:
assert node.annotation.value == expected_annotation
def test_end_pos_line(each_version):
# jedi issue #150
s = "x()\nx( )\nx( )\nx ( )\n"
module = parse(s, version=each_version)
for i, simple_stmt in enumerate(module.children[:-1]):
expr_stmt = simple_stmt.children[0]
assert expr_stmt.end_pos == (i + 1, i + 3)
def test_default_param(each_version):
func = parse('def x(foo=42): pass', version=each_version).children[0]
param, = func.get_params()
assert param.default.value == '42'
assert param.annotation is None
assert not param.star_count
def test_annotation_param(each_version):
func = parse('def x(foo: 3): pass', version=each_version).children[0]
param, = func.get_params()
assert param.default is None
assert param.annotation.value == '3'
assert not param.star_count
def test_annotation_params(each_version):
func = parse('def x(foo: 3, bar: 4): pass', version=each_version).children[0]
param1, param2 = func.get_params()
assert param1.default is None
assert param1.annotation.value == '3'
assert not param1.star_count
assert param2.default is None
assert param2.annotation.value == '4'
assert not param2.star_count
def test_default_and_annotation_param(each_version):
func = parse('def x(foo:3=42): pass', version=each_version).children[0]
param, = func.get_params()
assert param.default.value == '42'
assert param.annotation.value == '3'
assert not param.star_count
def get_yield_exprs(code, version):
return list(parse(code, version=version).children[0].iter_yield_exprs())
def get_return_stmts(code):
return list(parse(code).children[0].iter_return_stmts())
def get_raise_stmts(code, child):
return list(parse(code).children[child].iter_raise_stmts())
def test_yields(each_version):
y, = get_yield_exprs('def x(): yield', each_version)
assert y.value == 'yield'
assert y.type == 'keyword'
y, = get_yield_exprs('def x(): (yield 1)', each_version)
assert y.type == 'yield_expr'
y, = get_yield_exprs('def x(): [1, (yield)]', each_version)
assert y.type == 'keyword'
def test_yield_from():
y, = get_yield_exprs('def x(): (yield from 1)', '3.8')
assert y.type == 'yield_expr'
def test_returns():
r, = get_return_stmts('def x(): return')
assert r.value == 'return'
assert r.type == 'keyword'
r, = get_return_stmts('def x(): return 1')
assert r.type == 'return_stmt'
def test_raises():
code = """
def single_function():
raise Exception
def top_function():
def inner_function():
raise NotImplementedError()
inner_function()
raise Exception
def top_function_three():
try:
raise NotImplementedError()
except NotImplementedError:
pass
raise Exception
"""
r = get_raise_stmts(code, 0) # Lists in a simple Function
assert len(list(r)) == 1
r = get_raise_stmts(code, 1) # Doesn't Exceptions list in closures
assert len(list(r)) == 1
r = get_raise_stmts(code, 2) # Lists inside try-catch
assert len(list(r)) == 2
@pytest.mark.parametrize(
'code, name_index, is_definition, include_setitem', [
('x = 3', 0, True, False),
('x.y = 3', 0, False, False),
('x.y = 3', 1, True, False),
('x.y = u.v = z', 0, False, False),
('x.y = u.v = z', 1, True, False),
('x.y = u.v = z', 2, False, False),
('x.y = u.v, w = z', 3, True, False),
('x.y = u.v, w = z', 4, True, False),
('x.y = u.v, w = z', 5, False, False),
('x, y = z', 0, True, False),
('x, y = z', 1, True, False),
('x, y = z', 2, False, False),
('x, y = z', 2, False, False),
('x[0], y = z', 2, False, False),
('x[0] = z', 0, False, False),
('x[0], y = z', 0, False, False),
('x[0], y = z', 2, False, True),
('x[0] = z', 0, True, True),
('x[0], y = z', 0, True, True),
('x: int = z', 0, True, False),
('x: int = z', 1, False, False),
('x: int = z', 2, False, False),
('x: int', 0, True, False),
('x: int', 1, False, False),
]
)
def test_is_definition(code, name_index, is_definition, include_setitem):
module = parse(code, version='3.8')
name = module.get_first_leaf()
while True:
if name.type == 'name':
if name_index == 0:
break
name_index -= 1
name = name.get_next_leaf()
assert name.is_definition(include_setitem=include_setitem) == is_definition
def test_iter_funcdefs():
code = dedent('''
def normal(): ...
async def asyn(): ...
@dec
def dec_normal(): ...
@dec1
@dec2
async def dec_async(): ...
def broken
''')
module = parse(code, version='3.8')
func_names = [f.name.value for f in module.iter_funcdefs()]
assert func_names == ['normal', 'asyn', 'dec_normal', 'dec_async']
def test_with_stmt_get_test_node_from_name():
code = "with A as X.Y, B as (Z), C as Q[0], D as Q['foo']: pass"
with_stmt = parse(code, version='3').children[0]
tests = [
with_stmt.get_test_node_from_name(name).value
for name in with_stmt.get_defined_names(include_setitem=True)
]
assert tests == ["A", "B", "C", "D"]
sample_module = parse('x + y')
sample_node = sample_module.children[0]
sample_leaf = sample_node.children[0]
@pytest.mark.parametrize(
'node,node_types,expected_ancestor', [
(sample_module, ('file_input',), None),
(sample_node, ('arith_expr',), None),
(sample_node, ('file_input', 'eval_input'), sample_module),
(sample_leaf, ('name',), None),
(sample_leaf, ('arith_expr',), sample_node),
(sample_leaf, ('file_input',), sample_module),
(sample_leaf, ('file_input', 'arith_expr'), sample_node),
(sample_leaf, ('shift_expr',), None),
(sample_leaf, ('name', 'shift_expr',), None),
(sample_leaf, (), None),
]
)
def test_search_ancestor(node, node_types, expected_ancestor):
assert node.search_ancestor(*node_types) is expected_ancestor
assert search_ancestor(node, *node_types) is expected_ancestor # deprecated
| TestsFunctionAndLambdaParsing |
python | realpython__materials | python-selenium/src/bandcamp/web/locators.py | {
"start": 251,
"end": 370
} | class ____:
ITEM = (By.CLASS_NAME, "results-grid-item")
PAGINATION_BUTTON = (By.ID, "view-more")
| TrackListLocator |
python | dagster-io__dagster | python_modules/dagster/dagster/components/utils/defs_state.py | {
"start": 2033,
"end": 2617
} | class ____:
key: str
management_type: DefsStateManagementType
refresh_if_dev: bool
@classmethod
def from_args(cls, args: DefsStateConfigArgs, default_key: str) -> "DefsStateConfig":
return cls(
key=args.key or default_key,
management_type=args.management_type,
refresh_if_dev=args.refresh_if_dev,
)
ResolvedDefsStateConfig = Annotated[
DefsStateConfigArgs,
Resolver.default(
description="Configuration for determining how state is stored and persisted for this component."
),
]
| DefsStateConfig |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 48943,
"end": 51404
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("custom_job.CustomJobHook"))
def test_execute(self, mock_hook):
op = DeleteCustomTrainingJobOperator(
task_id=TASK_ID,
training_pipeline_id=TRAINING_PIPELINE_ID,
custom_job_id=CUSTOM_JOB_ID,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
op.execute(context={})
mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
mock_hook.return_value.delete_training_pipeline.assert_called_once_with(
training_pipeline=TRAINING_PIPELINE_ID,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
mock_hook.return_value.delete_custom_job.assert_called_once_with(
custom_job=CUSTOM_JOB_ID,
region=GCP_LOCATION,
project_id=GCP_PROJECT,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@pytest.mark.db_test
def test_templating(self, create_task_instance_of_operator, session):
ti = create_task_instance_of_operator(
DeleteCustomTrainingJobOperator,
# Templated fields
training_pipeline_id="{{ 'training-pipeline-id' }}",
custom_job_id="{{ 'custom_job_id' }}",
region="{{ 'region' }}",
project_id="{{ 'project_id' }}",
impersonation_chain="{{ 'impersonation-chain' }}",
# Other parameters
dag_id="test_template_body_templating_dag",
task_id="test_template_body_templating_task",
)
session.add(ti)
session.commit()
ti.render_templates()
task: DeleteCustomTrainingJobOperator = ti.task
assert task.training_pipeline_id == "training-pipeline-id"
assert task.custom_job_id == "custom_job_id"
assert task.region == "region"
assert task.project_id == "project_id"
assert task.impersonation_chain == "impersonation-chain"
assert task.training_pipeline_id == "training-pipeline-id"
assert task.custom_job_id == "custom_job_id"
| TestVertexAIDeleteCustomTrainingJobOperator |
python | getsentry__sentry | src/sentry/identity/gitlab/provider.py | {
"start": 2162,
"end": 4581
} | class ____(OAuth2Provider):
key = IntegrationProviderSlug.GITLAB.value
name = "Gitlab"
oauth_scopes = ("api",)
def build_identity(self, data):
data = data["data"]
return {
"type": IntegrationProviderSlug.GITLAB.value,
"id": data["user"]["id"],
"email": data["user"]["email"],
"scopes": sorted(data["scope"].split(",")),
"data": self.get_oauth_data(data),
}
def get_refresh_token_params(
self, refresh_token: str, identity: Identity | RpcIdentity, **kwargs: Any
) -> dict[str, str | None]:
client_id = identity.data.get("client_id")
client_secret = identity.data.get("client_secret")
return {
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"redirect_uri": absolute_uri("/extensions/gitlab/setup/"),
"client_id": client_id,
"client_secret": client_secret,
}
def refresh_identity(self, identity: Identity | RpcIdentity, **kwargs: Any) -> None:
refresh_token = identity.data.get("refresh_token")
refresh_token_url = kwargs.get("refresh_token_url")
if not refresh_token:
raise IdentityNotValid("Missing refresh token")
if not refresh_token_url:
raise IdentityNotValid("Missing refresh token url")
req = self.get_refresh_token(
refresh_token=refresh_token,
url=refresh_token_url,
identity=identity,
verify_ssl=kwargs["verify_ssl"],
)
try:
body = safe_urlread(req)
payload = orjson.loads(body)
except Exception as e:
# JSONDecodeError's will happen when we get a 301
# from GitLab, and won't have the `code` attribute
# we use the req.status_code instead in that case
error_status = getattr(e, "code", req.status_code)
self.logger.info(
"gitlab.refresh-identity-failure",
extra={
"identity_id": identity.id,
"error_status": error_status,
"error_message": str(e),
},
)
payload = {}
identity.data.update(get_oauth_data(payload))
identity_service.update_data(identity_id=identity.id, data=identity.data)
| GitlabIdentityProvider |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 30815,
"end": 31123
} | class ____(Expr):
"""Mark the wrapped expression as safe (wrap it as `Markup`)."""
fields = ("expr",)
expr: Expr
def as_const(self, eval_ctx: EvalContext | None = None) -> Markup:
eval_ctx = get_eval_context(self, eval_ctx)
return Markup(self.expr.as_const(eval_ctx))
| MarkSafe |
python | kamyu104__LeetCode-Solutions | Python/teemo-attacking.py | {
"start": 29,
"end": 406
} | class ____(object):
def findPoisonedDuration(self, timeSeries, duration):
"""
:type timeSeries: List[int]
:type duration: int
:rtype: int
"""
result = duration * len(timeSeries)
for i in xrange(1, len(timeSeries)):
result -= max(0, duration - (timeSeries[i] - timeSeries[i-1]))
return result
| Solution |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/base.py | {
"start": 46480,
"end": 72428
} | class ____(compiler.SQLCompiler):
dialect: MySQLDialect
render_table_with_column_in_update_from = True
"""Overridden from base SQLCompiler value"""
extract_map = compiler.SQLCompiler.extract_map.copy()
extract_map.update({"milliseconds": "millisecond"})
def default_from(self) -> str:
"""Called when a ``SELECT`` statement has no froms,
and no ``FROM`` clause is to be appended.
"""
if self.stack:
stmt = self.stack[-1]["selectable"]
if stmt._where_criteria: # type: ignore[attr-defined]
return " FROM DUAL"
return ""
def visit_random_func(self, fn: random, **kw: Any) -> str:
return "rand%s" % self.function_argspec(fn)
def visit_rollup_func(self, fn: rollup[Any], **kw: Any) -> str:
clause = ", ".join(
elem._compiler_dispatch(self, **kw) for elem in fn.clauses
)
return f"{clause} WITH ROLLUP"
def visit_aggregate_strings_func(
self, fn: aggregate_strings, **kw: Any
) -> str:
order_by = getattr(fn.clauses, "aggregate_order_by", None)
cl = list(fn.clauses)
expr, delimeter = cl[0:2]
literal_exec = dict(kw)
literal_exec["literal_execute"] = True
if order_by is not None:
return (
f"group_concat({expr._compiler_dispatch(self, **kw)} "
f"ORDER BY {order_by._compiler_dispatch(self, **kw)} "
f"SEPARATOR "
f"{delimeter._compiler_dispatch(self, **literal_exec)})"
)
else:
return (
f"group_concat({expr._compiler_dispatch(self, **kw)} "
f"SEPARATOR "
f"{delimeter._compiler_dispatch(self, **literal_exec)})"
)
def visit_sequence(self, sequence: sa_schema.Sequence, **kw: Any) -> str:
return "nextval(%s)" % self.preparer.format_sequence(sequence)
def visit_sysdate_func(self, fn: sysdate, **kw: Any) -> str:
return "SYSDATE()"
def _render_json_extract_from_binary(
self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
) -> str:
# note we are intentionally calling upon the process() calls in the
# order in which they appear in the SQL String as this is used
# by positional parameter rendering
if binary.type._type_affinity is sqltypes.JSON:
return "JSON_EXTRACT(%s, %s)" % (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
)
# for non-JSON, MySQL doesn't handle JSON null at all so it has to
# be explicit
case_expression = "CASE JSON_EXTRACT(%s, %s) WHEN 'null' THEN NULL" % (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
)
if binary.type._type_affinity is sqltypes.Integer:
type_expression = (
"ELSE CAST(JSON_EXTRACT(%s, %s) AS SIGNED INTEGER)"
% (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
)
)
elif binary.type._type_affinity in (sqltypes.Numeric, sqltypes.Float):
binary_type = cast(sqltypes.Numeric[Any], binary.type)
if (
binary_type.scale is not None
and binary_type.precision is not None
):
# using DECIMAL here because MySQL does not recognize NUMERIC
type_expression = (
"ELSE CAST(JSON_EXTRACT(%s, %s) AS DECIMAL(%s, %s))"
% (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
binary_type.precision,
binary_type.scale,
)
)
else:
# FLOAT / REAL not added in MySQL til 8.0.17
type_expression = (
"ELSE JSON_EXTRACT(%s, %s)+0.0000000000000000000000"
% (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
)
)
elif binary.type._type_affinity is sqltypes.Boolean:
# the NULL handling is particularly weird with boolean, so
# explicitly return true/false constants
type_expression = "WHEN true THEN true ELSE false"
elif binary.type._type_affinity is sqltypes.String:
# (gord): this fails with a JSON value that's a four byte unicode
# string. SQLite has the same problem at the moment
# (zzzeek): I'm not really sure. let's take a look at a test case
# that hits each backend and maybe make a requires rule for it?
type_expression = "ELSE JSON_UNQUOTE(JSON_EXTRACT(%s, %s))" % (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
)
else:
# other affinity....this is not expected right now
type_expression = "ELSE JSON_EXTRACT(%s, %s)" % (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
)
return case_expression + " " + type_expression + " END"
def visit_json_getitem_op_binary(
self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
) -> str:
return self._render_json_extract_from_binary(binary, operator, **kw)
def visit_json_path_getitem_op_binary(
self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
) -> str:
return self._render_json_extract_from_binary(binary, operator, **kw)
def visit_on_duplicate_key_update(
self, on_duplicate: OnDuplicateClause, **kw: Any
) -> str:
statement: ValuesBase = self.current_executable
cols: list[elements.KeyedColumnElement[Any]]
if on_duplicate._parameter_ordering:
parameter_ordering = [
coercions.expect(roles.DMLColumnRole, key)
for key in on_duplicate._parameter_ordering
]
ordered_keys = set(parameter_ordering)
cols = [
statement.table.c[key]
for key in parameter_ordering
if key in statement.table.c
] + [c for c in statement.table.c if c.key not in ordered_keys]
else:
cols = list(statement.table.c)
clauses = []
requires_mysql8_alias = statement.select is None and (
self.dialect._requires_alias_for_on_duplicate_key
)
if requires_mysql8_alias:
if statement.table.name.lower() == "new": # type: ignore[union-attr] # noqa: E501
_on_dup_alias_name = "new_1"
else:
_on_dup_alias_name = "new"
on_duplicate_update = {
coercions.expect_as_key(roles.DMLColumnRole, key): value
for key, value in on_duplicate.update.items()
}
# traverses through all table columns to preserve table column order
for column in (col for col in cols if col.key in on_duplicate_update):
val = on_duplicate_update[column.key]
def replace(
element: ExternallyTraversible, **kw: Any
) -> Optional[ExternallyTraversible]:
if (
isinstance(element, elements.BindParameter)
and element.type._isnull
):
return element._with_binary_element_type(column.type)
elif (
isinstance(element, elements.ColumnClause)
and element.table is on_duplicate.inserted_alias
):
if requires_mysql8_alias:
column_literal_clause = (
f"{_on_dup_alias_name}."
f"{self.preparer.quote(element.name)}"
)
else:
column_literal_clause = (
f"VALUES({self.preparer.quote(element.name)})"
)
return literal_column(column_literal_clause)
else:
# element is not replaced
return None
val = visitors.replacement_traverse(val, {}, replace)
value_text = self.process(val.self_group(), use_schema=False)
name_text = self.preparer.quote(column.name)
clauses.append("%s = %s" % (name_text, value_text))
non_matching = set(on_duplicate_update) - {c.key for c in cols}
if non_matching:
util.warn(
"Additional column names not matching "
"any column keys in table '%s': %s"
% (
self.statement.table.name, # type: ignore[union-attr]
(", ".join("'%s'" % c for c in non_matching)),
)
)
if requires_mysql8_alias:
return (
f"AS {_on_dup_alias_name} "
f"ON DUPLICATE KEY UPDATE {', '.join(clauses)}"
)
else:
return f"ON DUPLICATE KEY UPDATE {', '.join(clauses)}"
def visit_concat_op_expression_clauselist(
self, clauselist: elements.ClauseList, operator: Any, **kw: Any
) -> str:
return "concat(%s)" % (
", ".join(self.process(elem, **kw) for elem in clauselist.clauses)
)
def visit_concat_op_binary(
self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
) -> str:
return "concat(%s, %s)" % (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
)
_match_valid_flag_combinations = frozenset(
(
# (boolean_mode, natural_language, query_expansion)
(False, False, False),
(True, False, False),
(False, True, False),
(False, False, True),
(False, True, True),
)
)
_match_flag_expressions = (
"IN BOOLEAN MODE",
"IN NATURAL LANGUAGE MODE",
"WITH QUERY EXPANSION",
)
def visit_mysql_match(self, element: expression.match, **kw: Any) -> str:
return self.visit_match_op_binary(element, element.operator, **kw)
def visit_match_op_binary(
self, binary: expression.match, operator: Any, **kw: Any
) -> str:
"""
Note that `mysql_boolean_mode` is enabled by default because of
backward compatibility
"""
modifiers = binary.modifiers
boolean_mode = modifiers.get("mysql_boolean_mode", True)
natural_language = modifiers.get("mysql_natural_language", False)
query_expansion = modifiers.get("mysql_query_expansion", False)
flag_combination = (boolean_mode, natural_language, query_expansion)
if flag_combination not in self._match_valid_flag_combinations:
flags = (
"in_boolean_mode=%s" % boolean_mode,
"in_natural_language_mode=%s" % natural_language,
"with_query_expansion=%s" % query_expansion,
)
flags_str = ", ".join(flags)
raise exc.CompileError("Invalid MySQL match flags: %s" % flags_str)
match_clause = self.process(binary.left, **kw)
against_clause = self.process(binary.right, **kw)
if any(flag_combination):
flag_expressions = compress(
self._match_flag_expressions,
flag_combination,
)
against_clause = " ".join([against_clause, *flag_expressions])
return "MATCH (%s) AGAINST (%s)" % (match_clause, against_clause)
def get_from_hint_text(
self, table: selectable.FromClause, text: Optional[str]
) -> Optional[str]:
return text
def visit_typeclause(
self,
typeclause: elements.TypeClause,
type_: Optional[TypeEngine[Any]] = None,
**kw: Any,
) -> Optional[str]:
if type_ is None:
type_ = typeclause.type.dialect_impl(self.dialect)
if isinstance(type_, sqltypes.TypeDecorator):
return self.visit_typeclause(typeclause, type_.impl, **kw) # type: ignore[arg-type] # noqa: E501
elif isinstance(type_, sqltypes.Integer):
if getattr(type_, "unsigned", False):
return "UNSIGNED INTEGER"
else:
return "SIGNED INTEGER"
elif isinstance(type_, sqltypes.TIMESTAMP):
return "DATETIME"
elif isinstance(
type_,
(
sqltypes.DECIMAL,
sqltypes.DateTime,
sqltypes.Date,
sqltypes.Time,
),
):
return self.dialect.type_compiler_instance.process(type_)
elif isinstance(type_, sqltypes.String) and not isinstance(
type_, (ENUM, SET)
):
adapted = CHAR._adapt_string_for_cast(type_)
return self.dialect.type_compiler_instance.process(adapted)
elif isinstance(type_, sqltypes._Binary):
return "BINARY"
elif isinstance(type_, sqltypes.JSON):
return "JSON"
elif isinstance(type_, sqltypes.NUMERIC):
return self.dialect.type_compiler_instance.process(type_).replace(
"NUMERIC", "DECIMAL"
)
elif (
isinstance(type_, sqltypes.Float)
and self.dialect._support_float_cast
):
return self.dialect.type_compiler_instance.process(type_)
else:
return None
def visit_cast(self, cast: elements.Cast[Any], **kw: Any) -> str:
type_ = self.process(cast.typeclause)
if type_ is None:
util.warn(
"Datatype %s does not support CAST on MySQL/MariaDb; "
"the CAST will be skipped."
% self.dialect.type_compiler_instance.process(
cast.typeclause.type
)
)
return self.process(cast.clause.self_group(), **kw)
return "CAST(%s AS %s)" % (self.process(cast.clause, **kw), type_)
def render_literal_value(
self, value: Optional[str], type_: TypeEngine[Any]
) -> str:
value = super().render_literal_value(value, type_)
if self.dialect._backslash_escapes:
value = value.replace("\\", "\\\\")
return value
# override native_boolean=False behavior here, as
# MySQL still supports native boolean
def visit_true(self, expr: elements.True_, **kw: Any) -> str:
return "true"
def visit_false(self, expr: elements.False_, **kw: Any) -> str:
return "false"
def get_select_precolumns(
self, select: selectable.Select[Any], **kw: Any
) -> str:
"""Add special MySQL keywords in place of DISTINCT.
.. deprecated:: 1.4 This usage is deprecated.
:meth:`_expression.Select.prefix_with` should be used for special
keywords at the start of a SELECT.
"""
if isinstance(select._distinct, str):
util.warn_deprecated(
"Sending string values for 'distinct' is deprecated in the "
"MySQL dialect and will be removed in a future release. "
"Please use :meth:`.Select.prefix_with` for special keywords "
"at the start of a SELECT statement",
version="1.4",
)
return select._distinct.upper() + " "
return super().get_select_precolumns(select, **kw)
def visit_join(
self,
join: selectable.Join,
asfrom: bool = False,
from_linter: Optional[compiler.FromLinter] = None,
**kwargs: Any,
) -> str:
if from_linter:
from_linter.edges.add((join.left, join.right))
if join.full:
join_type = " FULL OUTER JOIN "
elif join.isouter:
join_type = " LEFT OUTER JOIN "
else:
join_type = " INNER JOIN "
return "".join(
(
self.process(
join.left, asfrom=True, from_linter=from_linter, **kwargs
),
join_type,
self.process(
join.right, asfrom=True, from_linter=from_linter, **kwargs
),
" ON ",
self.process(join.onclause, from_linter=from_linter, **kwargs), # type: ignore[arg-type] # noqa: E501
)
)
def for_update_clause(
self, select: selectable.GenerativeSelect, **kw: Any
) -> str:
assert select._for_update_arg is not None
if select._for_update_arg.read:
if self.dialect.use_mysql_for_share:
tmp = " FOR SHARE"
else:
tmp = " LOCK IN SHARE MODE"
else:
tmp = " FOR UPDATE"
if select._for_update_arg.of and self.dialect.supports_for_update_of:
tables: util.OrderedSet[elements.ClauseElement] = util.OrderedSet()
for c in select._for_update_arg.of:
tables.update(sql_util.surface_selectables_only(c))
tmp += " OF " + ", ".join(
self.process(table, ashint=True, use_schema=False, **kw)
for table in tables
)
if select._for_update_arg.nowait:
tmp += " NOWAIT"
if select._for_update_arg.skip_locked:
tmp += " SKIP LOCKED"
return tmp
def limit_clause(
self, select: selectable.GenerativeSelect, **kw: Any
) -> str:
# MySQL supports:
# LIMIT <limit>
# LIMIT <offset>, <limit>
# and in server versions > 3.3:
# LIMIT <limit> OFFSET <offset>
# The latter is more readable for offsets but we're stuck with the
# former until we can refine dialects by server revision.
limit_clause, offset_clause = (
select._limit_clause,
select._offset_clause,
)
if limit_clause is None and offset_clause is None:
return ""
elif offset_clause is not None:
# As suggested by the MySQL docs, need to apply an
# artificial limit if one wasn't provided
# https://dev.mysql.com/doc/refman/5.0/en/select.html
if limit_clause is None:
# TODO: remove ??
# hardwire the upper limit. Currently
# needed consistent with the usage of the upper
# bound as part of MySQL's "syntax" for OFFSET with
# no LIMIT.
return " \n LIMIT %s, %s" % (
self.process(offset_clause, **kw),
"18446744073709551615",
)
else:
return " \n LIMIT %s, %s" % (
self.process(offset_clause, **kw),
self.process(limit_clause, **kw),
)
else:
assert limit_clause is not None
# No offset provided, so just use the limit
return " \n LIMIT %s" % (self.process(limit_clause, **kw),)
def update_post_criteria_clause(
self, update_stmt: Update, **kw: Any
) -> Optional[str]:
limit = update_stmt.kwargs.get("%s_limit" % self.dialect.name, None)
supertext = super().update_post_criteria_clause(update_stmt, **kw)
if limit is not None:
limit_text = f"LIMIT {int(limit)}"
if supertext is not None:
return f"{limit_text} {supertext}"
else:
return limit_text
else:
return supertext
def delete_post_criteria_clause(
self, delete_stmt: Delete, **kw: Any
) -> Optional[str]:
limit = delete_stmt.kwargs.get("%s_limit" % self.dialect.name, None)
supertext = super().delete_post_criteria_clause(delete_stmt, **kw)
if limit is not None:
limit_text = f"LIMIT {int(limit)}"
if supertext is not None:
return f"{limit_text} {supertext}"
else:
return limit_text
else:
return supertext
def visit_mysql_dml_limit_clause(
self, element: DMLLimitClause, **kw: Any
) -> str:
kw["literal_execute"] = True
return f"LIMIT {self.process(element._limit_clause, **kw)}"
def update_tables_clause(
self,
update_stmt: Update,
from_table: _DMLTableElement,
extra_froms: list[selectable.FromClause],
**kw: Any,
) -> str:
kw["asfrom"] = True
return ", ".join(
t._compiler_dispatch(self, **kw)
for t in [from_table] + list(extra_froms)
)
def update_from_clause(
self,
update_stmt: Update,
from_table: _DMLTableElement,
extra_froms: list[selectable.FromClause],
from_hints: Any,
**kw: Any,
) -> None:
return None
def delete_table_clause(
self,
delete_stmt: Delete,
from_table: _DMLTableElement,
extra_froms: list[selectable.FromClause],
**kw: Any,
) -> str:
"""If we have extra froms make sure we render any alias as hint."""
ashint = False
if extra_froms:
ashint = True
return from_table._compiler_dispatch(
self, asfrom=True, iscrud=True, ashint=ashint, **kw
)
def delete_extra_from_clause(
self,
delete_stmt: Delete,
from_table: _DMLTableElement,
extra_froms: list[selectable.FromClause],
from_hints: Any,
**kw: Any,
) -> str:
"""Render the DELETE .. USING clause specific to MySQL."""
kw["asfrom"] = True
return "USING " + ", ".join(
t._compiler_dispatch(self, fromhints=from_hints, **kw)
for t in [from_table] + extra_froms
)
def visit_empty_set_expr(
self, element_types: list[TypeEngine[Any]], **kw: Any
) -> str:
return (
"SELECT %(outer)s FROM (SELECT %(inner)s) "
"as _empty_set WHERE 1!=1"
% {
"inner": ", ".join(
"1 AS _in_%s" % idx
for idx, type_ in enumerate(element_types)
),
"outer": ", ".join(
"_in_%s" % idx for idx, type_ in enumerate(element_types)
),
}
)
def visit_is_distinct_from_binary(
self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
) -> str:
return "NOT (%s <=> %s)" % (
self.process(binary.left),
self.process(binary.right),
)
def visit_is_not_distinct_from_binary(
self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
) -> str:
return "%s <=> %s" % (
self.process(binary.left),
self.process(binary.right),
)
def _mariadb_regexp_flags(
self, flags: str, pattern: elements.ColumnElement[Any], **kw: Any
) -> str:
return "CONCAT('(?', %s, ')', %s)" % (
self.render_literal_value(flags, sqltypes.STRINGTYPE),
self.process(pattern, **kw),
)
def _regexp_match(
self,
op_string: str,
binary: elements.BinaryExpression[Any],
operator: Any,
**kw: Any,
) -> str:
assert binary.modifiers is not None
flags = binary.modifiers["flags"]
if flags is None:
return self._generate_generic_binary(binary, op_string, **kw)
elif self.dialect.is_mariadb:
return "%s%s%s" % (
self.process(binary.left, **kw),
op_string,
self._mariadb_regexp_flags(flags, binary.right),
)
else:
text = "REGEXP_LIKE(%s, %s, %s)" % (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
self.render_literal_value(flags, sqltypes.STRINGTYPE),
)
if op_string == " NOT REGEXP ":
return "NOT %s" % text
else:
return text
def visit_regexp_match_op_binary(
self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
) -> str:
return self._regexp_match(" REGEXP ", binary, operator, **kw)
def visit_not_regexp_match_op_binary(
self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
) -> str:
return self._regexp_match(" NOT REGEXP ", binary, operator, **kw)
def visit_regexp_replace_op_binary(
self, binary: elements.BinaryExpression[Any], operator: Any, **kw: Any
) -> str:
assert binary.modifiers is not None
flags = binary.modifiers["flags"]
if flags is None:
return "REGEXP_REPLACE(%s, %s)" % (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
)
elif self.dialect.is_mariadb:
return "REGEXP_REPLACE(%s, %s, %s)" % (
self.process(binary.left, **kw),
self._mariadb_regexp_flags(flags, binary.right.clauses[0]),
self.process(binary.right.clauses[1], **kw),
)
else:
return "REGEXP_REPLACE(%s, %s, %s)" % (
self.process(binary.left, **kw),
self.process(binary.right, **kw),
self.render_literal_value(flags, sqltypes.STRINGTYPE),
)
| MySQLCompiler |
python | graphql-python__graphene | graphene/types/tests/test_field.py | {
"start": 210,
"end": 4104
} | class ____:
value = "value"
value_func = staticmethod(lambda: "value_func")
def value_method(self):
return "value_method"
def test_field_basic():
MyType = object()
args = {"my arg": Argument(True)}
def resolver():
return None
deprecation_reason = "Deprecated now"
description = "My Field"
my_default = "something"
field = Field(
MyType,
name="name",
args=args,
resolver=resolver,
description=description,
deprecation_reason=deprecation_reason,
default_value=my_default,
)
assert field.name == "name"
assert field.args == args
assert field.resolver == resolver
assert field.deprecation_reason == deprecation_reason
assert field.description == description
assert field.default_value == my_default
def test_field_required():
MyType = object()
field = Field(MyType, required=True)
assert isinstance(field.type, NonNull)
assert field.type.of_type == MyType
def test_field_default_value_not_callable():
MyType = object()
try:
Field(MyType, default_value=lambda: True)
except AssertionError as e:
# substring comparison for py 2/3 compatibility
assert "The default value can not be a function but received" in str(e)
def test_field_source():
MyType = object()
field = Field(MyType, source="value")
assert field.resolver(MyInstance(), None) == MyInstance.value
def test_field_source_dict_or_attr():
MyType = object()
field = Field(MyType, source="value")
assert field.resolver(MyInstance(), None) == MyInstance.value
assert field.resolver({"value": MyInstance.value}, None) == MyInstance.value
def test_field_with_lazy_type():
MyType = object()
field = Field(lambda: MyType)
assert field.type == MyType
def test_field_with_lazy_partial_type():
MyType = object()
field = Field(partial(lambda: MyType))
assert field.type == MyType
def test_field_with_string_type():
field = Field("graphene.types.tests.utils.MyLazyType")
assert field.type == MyLazyType
def test_field_not_source_and_resolver():
MyType = object()
with raises(Exception) as exc_info:
Field(MyType, source="value", resolver=lambda: None)
assert (
str(exc_info.value)
== "A Field cannot have a source and a resolver in at the same time."
)
def test_field_source_func():
MyType = object()
field = Field(MyType, source="value_func")
assert field.resolver(MyInstance(), None) == MyInstance.value_func()
def test_field_source_method():
MyType = object()
field = Field(MyType, source="value_method")
assert field.resolver(MyInstance(), None) == MyInstance().value_method()
def test_field_source_as_argument():
MyType = object()
field = Field(MyType, source=String())
assert "source" in field.args
assert field.args["source"].type == String
def test_field_name_as_argument():
MyType = object()
field = Field(MyType, name=String())
assert "name" in field.args
assert field.args["name"].type == String
def test_field_source_argument_as_kw():
MyType = object()
deprecation_reason = "deprecated"
field = Field(
MyType,
b=NonNull(True),
c=Argument(None, deprecation_reason=deprecation_reason),
a=NonNull(False),
)
assert list(field.args) == ["b", "c", "a"]
assert isinstance(field.args["b"], Argument)
assert isinstance(field.args["b"].type, NonNull)
assert field.args["b"].type.of_type is True
assert isinstance(field.args["c"], Argument)
assert field.args["c"].type is None
assert field.args["c"].deprecation_reason == deprecation_reason
assert isinstance(field.args["a"], Argument)
assert isinstance(field.args["a"].type, NonNull)
assert field.args["a"].type.of_type is False
| MyInstance |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 10492,
"end": 11095
} | class ____(Stmt):
"""The for loop. `target` is the target for the iteration (usually a
:class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
of nodes that are used as loop-body, and `else_` a list of nodes for the
`else` block. If no else node exists it has to be an empty list.
For filtered nodes an expression can be stored as `test`, otherwise `None`.
"""
fields = ("target", "iter", "body", "else_", "test", "recursive")
target: Node
iter: Node
body: t.List[Node]
else_: t.List[Node]
test: t.Optional[Node]
recursive: bool
| For |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-rki-covid/source_rki_covid/source.py | {
"start": 6624,
"end": 8631
} | class ____(IncrementalRkiCovidStream):
"""Docs: https://api.corona-zahlen.org/germany/germany/history/incidence/:days"""
primary_key = None
def __init__(self, config, **kwargs):
super().__init__(**kwargs)
self.start_date = config.get("start_date")
@property
def source_defined_cursor(self) -> bool:
return False
@property
def cursor_field(self) -> str:
return "date"
def date_to_int(self, start_date) -> int:
diff = datetime.now() - datetime.strptime(start_date, "%Y-%m-%d")
if diff.days <= 0:
return 1
return diff.days
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:
if not current_stream_state:
current_stream_state = {self.cursor_field: self.start_date}
return {self.cursor_field: max(latest_record.get(self.cursor_field, ""), current_stream_state.get(self.cursor_field, ""))}
def read_records(self, stream_state: Mapping[str, Any] = None, **kwargs) -> Iterable[Mapping[str, Any]]:
records = super().read_records(stream_state=stream_state, **kwargs)
if stream_state:
for record in records:
if record[self.cursor_field] > stream_state.get(self.cursor_field):
yield record
else:
yield from records
def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]:
if response.json().get("data"):
return response.json().get("data")
return [{}]
def path(
self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None
) -> str:
if self.start_date:
return "germany/history/incidence/" + str(self.date_to_int(self.start_date))
return "germany/history/incidence/"
# source: germany/history/deaths/:days | Incremental
| GermanHistoryIncidence |
python | huggingface__transformers | src/transformers/models/ernie/modeling_ernie.py | {
"start": 61983,
"end": 65530
} | class ____(ErniePreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.ernie = ErnieModel(config, add_pooling_layer=False)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
token_type_ids: Optional[torch.Tensor] = None,
task_type_ids: Optional[torch.Tensor] = None,
position_ids: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
start_positions: Optional[torch.Tensor] = None,
end_positions: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
r"""
task_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Task type embedding is a special embedding to represent the characteristic of different tasks, such as
word-aware pre-training task, structure-aware pre-training task and semantic-aware pre-training task. We
assign a `task_type_id` to each task and the `task_type_id` is in the range `[0,
config.task_type_vocab_size-1]
"""
outputs = self.ernie(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
task_type_ids=task_type_ids,
position_ids=position_ids,
inputs_embeds=inputs_embeds,
return_dict=True,
**kwargs,
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
return QuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
__all__ = [
"ErnieForCausalLM",
"ErnieForMaskedLM",
"ErnieForMultipleChoice",
"ErnieForNextSentencePrediction",
"ErnieForPreTraining",
"ErnieForQuestionAnswering",
"ErnieForSequenceClassification",
"ErnieForTokenClassification",
"ErnieModel",
"ErniePreTrainedModel",
]
| ErnieForQuestionAnswering |
python | walkccc__LeetCode | solutions/2641. Cousins in Binary Tree II/2641.py | {
"start": 0,
"end": 1026
} | class ____:
def replaceValueInTree(self, root: TreeNode | None) -> TreeNode | None:
levelSums = []
def dfs(root: TreeNode | None, level: int) -> None:
if not root:
return
if len(levelSums) == level:
levelSums.append(0)
levelSums[level] += root.val
dfs(root.left, level + 1)
dfs(root.right, level + 1)
def replace(
root: TreeNode | None,
level: int, curr: TreeNode | None,
) -> TreeNode | None:
nextLevel = level + 1
nextLevelCousinsSum = (
(levelSums[nextLevel] if nextLevel < len(levelSums) else 0) -
(root.left.val if root.left else 0) -
(root.right.val if root.right else 0))
if root.left:
curr.left = TreeNode(nextLevelCousinsSum)
replace(root.left, level + 1, curr.left)
if root.right:
curr.right = TreeNode(nextLevelCousinsSum)
replace(root.right, level + 1, curr.right)
return curr
dfs(root, 0)
return replace(root, 0, TreeNode(0))
| Solution |
python | astropy__astropy | astropy/modeling/tests/test_fitting_parallel.py | {
"start": 25357,
"end": 33525
} | class ____:
def test_basic(self):
# Make sure that fitting with units works
data = (
gaussian(
np.arange(21)[:, None],
np.array([2, 1.8]),
np.array([5, 10]),
np.array([1, 1.1]),
)
* u.Jy
)
model = Gaussian1D(amplitude=1.5 * u.Jy, mean=7 * u.um, stddev=0.002 * u.mm)
fitter = LevMarLSQFitter()
model_fit = parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
world=(1000 * np.arange(21) * u.nm,),
scheduler="synchronous",
)
assert_quantity_allclose(model_fit.amplitude.quantity, [2, 1.8] * u.Jy)
assert_quantity_allclose(model_fit.mean.quantity, [5, 10] * u.um)
assert_quantity_allclose(model_fit.stddev.quantity, [1.0, 1.1] * u.um)
def test_units_no_input_units(self):
# Make sure that fitting with units works for models without input_units defined
data = (np.repeat(3, 20)).reshape((20, 1)) * u.Jy
model = Const1D(1 * u.mJy)
fitter = LevMarLSQFitter()
assert not model.input_units
model_fit = parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
world=(1000 * np.arange(20) * u.nm,),
scheduler="synchronous",
)
assert_quantity_allclose(model_fit.amplitude.quantity, 3 * u.Jy)
def test_units_with_wcs(self):
data = gaussian(np.arange(20), 2, 10, 1).reshape((20, 1)) * u.Jy
model = Gaussian1D(amplitude=1.5 * u.Jy, mean=7 * u.um, stddev=0.002 * u.mm)
fitter = LevMarLSQFitter()
wcs = WCS(naxis=2)
wcs.wcs.ctype = "OFFSET", "WAVE"
wcs.wcs.crval = 10, 0.1
wcs.wcs.crpix = 1, 1
wcs.wcs.cdelt = 10, 0.1
wcs.wcs.cunit = "deg", "um"
model_fit = parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
world=wcs,
scheduler="synchronous",
)
assert_allclose(model_fit.amplitude.quantity, 2 * u.Jy)
assert_allclose(model_fit.mean.quantity, 1.1 * u.um)
assert_allclose(model_fit.stddev.quantity, 0.1 * u.um)
def test_units_with_wcs_2d(self):
# Fit a 2D model with mixed units to a dataset
N = 3
P = 20
Q = 10
wcs = WCS(naxis=3)
wcs.wcs.ctype = "OFFSET", "WEIGHTS", "WAVE"
wcs.wcs.crval = 10, 0.1, 0.2
wcs.wcs.crpix = 1, 1, 1
wcs.wcs.cdelt = 10, 0.1, 0.2
wcs.wcs.cunit = "deg", "kg", "mm"
rng = np.random.default_rng(12345)
x = wcs.pixel_to_world(0, 0, np.arange(P))[2]
y = wcs.pixel_to_world(0, np.arange(Q), 0)[1]
slope_x = [1, 3, 2] * u.Jy / u.mm
slope_y = [-1, 2, 3] * u.Jy / u.kg
intercept = [5, 6, 7] * u.Jy
data = slope_x * x[:, None, None] + slope_y * y[None, :, None] + intercept
# At this point, the data has shape (P, Q, N)
model = Planar2D(
slope_x=slope_x * rng.uniform(0.9, 1.1, N),
slope_y=slope_y * rng.uniform(0.9, 1.1, N),
intercept=intercept * rng.uniform(0.9, 1.1, N),
)
fitter = LevMarLSQFitter()
model_fit = parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=(0, 1),
world=wcs,
scheduler="synchronous",
)
assert_allclose(model_fit.slope_x.quantity, slope_x)
assert_allclose(model_fit.slope_y.quantity, slope_y)
assert_allclose(model_fit.intercept.quantity, intercept)
def test_skip_empty_data(tmp_path):
# Test when one of the datasets being fit is all NaN
data = gaussian(
np.arange(21)[:, None],
np.array([2, 1.8]),
np.array([5, 10]),
np.array([1, 1.1]),
)
data[:, 1] = np.nan
model = Gaussian1D(amplitude=1.5, mean=7, stddev=2)
fitter = TRFLSQFitter()
model_fit = parallel_fit_dask(
data=data,
model=model,
fitter=fitter,
fitting_axes=0,
diagnostics="error+warn",
diagnostics_path=tmp_path,
scheduler="synchronous",
)
# If we don't properly skip empty data sections, then the fitting would fail
# and populate the diagnostics directory.
assert len(sorted(tmp_path.iterdir())) == 0
assert_allclose(model_fit.amplitude.value, [2, np.nan])
assert_allclose(model_fit.mean.value, [5, np.nan])
assert_allclose(model_fit.stddev.value, [1.0, np.nan])
def test_world_wcs_axis_correlation():
# Regression test for a bug that caused the world coordinates to not be
# properly extracted from a WCS object if the axis correlation matrix
# resulted in a difference in order between pixel and world coordinates.
model = Gaussian1D()
fitter = TRFLSQFitter()
data = gaussian(
np.arange(1, 6)[:, None],
np.array([5, 5]),
np.array([3, 2]),
np.array([1, 1]),
).T
common_kwargs = dict(data=data, model=model, fitter=fitter, scheduler="synchronous")
# First case: a simple WCS - as the fitting axis is 1 in Numpy order, this
# means we should use the world coordinates for the first WCS dimension. In
# this case, the Gaussian means should be 3 and 2.
wcs1 = WCS(naxis=2)
wcs1.wcs.cdelt = 1, 2
model_fit = parallel_fit_dask(fitting_axes=1, world=wcs1, **common_kwargs)
assert_allclose(model_fit.mean, [3, 2])
# Second case: as above, but WCS axes swapped. In this case, the means
# should be 6 and 4.
wcs1 = WCS(naxis=2)
wcs1.wcs.cdelt = 2, 1
model_fit = parallel_fit_dask(fitting_axes=1, world=wcs1, **common_kwargs)
assert_allclose(model_fit.mean, [6, 4])
# Third case: as in first case, but this time we set the PC matrix such
# that the world axes are in a different order to their corresponding pixel
# axis. In this case, the means should be 6 and 4 because fitting_axes=1
# should correspond to the second WCS dimension.
wcs3 = WCS(naxis=2)
wcs3.wcs.cdelt = 1, 2
wcs3.wcs.pc = [[0, 1], [1, 0]]
model_fit = parallel_fit_dask(fitting_axes=1, world=wcs1, **common_kwargs)
assert_allclose(model_fit.mean, [6, 4])
def test_support_nddata():
data = gaussian(np.arange(20), 2, 10, 1).reshape((20, 1)) * u.Jy
# Introduce outliers
data[10, 0] = 1000.0 * u.Jy
# Mask the outliers (invalid is True)
mask = data > 100.0 * u.Jy
model = Gaussian1D(amplitude=1.5 * u.Jy, mean=7 * u.um, stddev=0.002 * u.mm)
fitter = LevMarLSQFitter()
wcs = WCS(naxis=2)
wcs.wcs.ctype = "OFFSET", "WAVE"
wcs.wcs.crval = 10, 0.1
wcs.wcs.crpix = 1, 1
wcs.wcs.cdelt = 10, 0.1
wcs.wcs.cunit = "deg", "um"
nd_data = NDData(
data=data,
wcs=wcs,
mask=mask,
)
model_fit = parallel_fit_dask(
data=nd_data,
model=model,
fitter=fitter,
fitting_axes=0,
scheduler="synchronous",
)
assert_allclose(model_fit.amplitude.quantity, 2 * u.Jy)
assert_allclose(model_fit.mean.quantity, 1.1 * u.um)
assert_allclose(model_fit.stddev.quantity, 0.1 * u.um)
def test_support_nddata_uncert():
data = np.repeat(np.array([1, 2, 4]), 2).reshape((2, -1), order="F").T
uncert = (
np.repeat(np.array([1 / 7**0.5, 1 / 2**0.5, 1]), 2)
.reshape((2, -1), order="F")
.T
)
model = Const1D(0)
fitter = LevMarLSQFitter()
wcs = WCS(naxis=2)
wcs.wcs.ctype = "OFFSET", "WAVE"
wcs.wcs.crval = 10, 1
wcs.wcs.crpix = 1, 1
wcs.wcs.cdelt = 10, 1
wcs.wcs.cunit = "deg", "m"
nd_data = NDData(
data=data,
wcs=wcs,
uncertainty=StdDevUncertainty(uncert),
)
model_fit = parallel_fit_dask(
data=nd_data,
model=model,
fitter=fitter,
fitting_axes=0,
scheduler="synchronous",
)
assert_allclose(model_fit.amplitude, 1.5)
| TestUnits |
python | astropy__astropy | astropy/time/formats.py | {
"start": 45569,
"end": 50386
} | class ____(TimeUnique):
"""
ymdhms: A Time format to represent Time as year, month, day, hour,
minute, second (thus the name ymdhms).
Acceptable inputs must have keys or column names in the "YMDHMS" set of
``year``, ``month``, ``day`` ``hour``, ``minute``, ``second``:
- Dict with keys in the YMDHMS set
- NumPy structured array, record array or astropy Table, or single row
of those types, with column names in the YMDHMS set
One can supply a subset of the YMDHMS values, for instance only 'year',
'month', and 'day'. Inputs have the following defaults::
'month': 1, 'day': 1, 'hour': 0, 'minute': 0, 'second': 0
When the input is supplied as a ``dict`` then each value can be either a
scalar value or an array. The values will be broadcast to a common shape.
Example::
>>> from astropy.time import Time
>>> t = Time({'year': 2015, 'month': 2, 'day': 3,
... 'hour': 12, 'minute': 13, 'second': 14.567},
... scale='utc')
>>> t.iso
'2015-02-03 12:13:14.567'
>>> t.ymdhms.year
np.int32(2015)
"""
name = "ymdhms"
def _check_val_type(self, val1, val2):
"""
This checks inputs for the YMDHMS format.
It is bit more complex than most format checkers because of the flexible
input that is allowed. Also, it actually coerces ``val1`` into an appropriate
dict of ndarrays that can be used easily by ``set_jds()``. This is useful
because it makes it easy to get default values in that routine.
Parameters
----------
val1 : ndarray or None
val2 : ndarray or None
Returns
-------
val1_as_dict, val2 : val1 as dict or None, val2 is always None
"""
if val2 is not None:
raise ValueError("val2 must be None for ymdhms format")
ymdhms = ["year", "month", "day", "hour", "minute", "second"]
if val1.dtype.names:
# Convert to a dict of ndarray
val1_as_dict = {name: val1[name] for name in val1.dtype.names}
elif val1.shape == (0,):
# Input was empty list [], so set to None and set_jds will handle this
return None, None
elif (
val1.dtype.kind == "O"
and val1.shape == ()
and isinstance(val1.item(), dict)
):
# Code gets here for input as a dict. The dict input
# can be either scalar values or N-d arrays.
# Extract the item (which is a dict) and broadcast values to the
# same shape here.
names = val1.item().keys()
values = val1.item().values()
val1_as_dict = dict(zip(names, np.broadcast_arrays(*values)))
else:
raise ValueError("input must be dict or table-like")
# Check that the key names now are good.
names = val1_as_dict.keys()
required_names = ymdhms[: len(names)]
def comma_repr(vals):
return ", ".join(repr(val) for val in vals)
bad_names = set(names) - set(ymdhms)
if bad_names:
raise ValueError(
f"{comma_repr(bad_names)} not allowed as YMDHMS key name(s)"
)
if set(names) != set(required_names):
raise ValueError(
f"for {len(names)} input key names "
f"you must supply {comma_repr(required_names)}"
)
return val1_as_dict, val2
def set_jds(self, val1, val2):
if val1 is None:
# Input was empty list []
jd1 = np.array([], dtype=np.float64)
jd2 = np.array([], dtype=np.float64)
else:
jd1, jd2 = erfa.dtf2d(
self.scale.upper().encode("ascii"),
val1["year"],
val1.get("month", 1),
val1.get("day", 1),
val1.get("hour", 0),
val1.get("minute", 0),
val1.get("second", 0),
)
self.jd1, self.jd2 = day_frac(jd1, jd2)
@property
def value(self):
scale = self.scale.upper().encode("ascii")
iys, ims, ids, ihmsfs = erfa.d2dtf(scale, 9, self.jd1, self.jd2)
out = np.empty(
self.jd1.shape,
dtype=[
("year", "i4"),
("month", "i4"),
("day", "i4"),
("hour", "i4"),
("minute", "i4"),
("second", "f8"),
],
)
out["year"] = iys
out["month"] = ims
out["day"] = ids
out["hour"] = ihmsfs["h"]
out["minute"] = ihmsfs["m"]
out["second"] = ihmsfs["s"] + ihmsfs["f"] * 10 ** (-9)
return out.view(np.recarray)
| TimeYMDHMS |
python | spyder-ide__spyder | spyder/plugins/mainmenu/api.py | {
"start": 3559,
"end": 3826
} | class ____:
Top = 'top_section'
Pane = 'pane_section'
Toolbar = 'toolbar_section'
Layout = 'layout_section'
Bottom = 'bottom_section'
# For backward compat with plugins targeting Spyder <6.1
ViewMenuSections = WindowMenuSections
| WindowMenuSections |
python | pennersr__django-allauth | allauth/socialaccount/providers/vk/provider.py | {
"start": 746,
"end": 1451
} | class ____(OAuth2Provider):
id = "vk"
name = "VK"
account_class = VKAccount
oauth2_adapter_class = VKOAuth2Adapter
pkce_enabled_default = True
def get_default_scope(self):
scope = []
if app_settings.QUERY_EMAIL:
scope.append("email")
return scope
def extract_uid(self, data):
return str(data["user_id"])
def extract_common_fields(self, data):
return dict(
email=data.get("email"),
last_name=data.get("last_name"),
username=data.get("screen_name"),
first_name=data.get("first_name"),
phone=data.get("phone"),
)
provider_classes = [VKProvider]
| VKProvider |
python | huggingface__transformers | src/transformers/models/altclip/modeling_altclip.py | {
"start": 16218,
"end": 17898
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList([AltRobertaLayer(config) for i in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
@can_return_tuple
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
output_attentions: Optional[bool] = False,
output_hidden_states: Optional[bool] = False,
return_dict: Optional[bool] = True,
**kwargs,
) -> Union[tuple[torch.Tensor], BaseModelOutput]:
all_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_outputs = layer_module(
hidden_states=hidden_states,
attention_mask=attention_mask,
output_attentions=output_attentions,
**kwargs,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_self_attentions = all_self_attentions + (layer_outputs[1],)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
return BaseModelOutput(
last_hidden_state=hidden_states,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
)
# Copied from transformers.models.roberta.modeling_roberta.RobertaPooler
| AltRobertaEncoder |
python | kamyu104__LeetCode-Solutions | Python/convert-sorted-list-to-binary-search-tree.py | {
"start": 292,
"end": 1007
} | class ____(object):
head = None
# @param head, a list node
# @return a tree node
def sortedListToBST(self, head):
current, length = head, 0
while current is not None:
current, length = current.next, length + 1
self.head = head
return self.sortedListToBSTRecu(0, length)
def sortedListToBSTRecu(self, start, end):
if start == end:
return None
mid = start + (end - start) / 2
left = self.sortedListToBSTRecu(start, mid)
current = TreeNode(self.head.val)
current.left = left
self.head = self.head.next
current.right = self.sortedListToBSTRecu(mid + 1, end)
return current
| Solution |
python | tensorflow__tensorflow | tensorflow/python/checkpoint/functional_saver.py | {
"start": 8663,
"end": 28095
} | class ____:
"""Saves checkpoints directly from multiple devices.
Note that this is a low-level utility which stores Tensors in the keys
specified by `SaveableObject`s. Higher-level utilities for object-based
checkpointing are built on top of it.
"""
def __init__(
self,
serialized_tensors: Mapping[base.Trackable, sharding_util.Shard],
registered_savers: "RegisteredSaversDict | None" = None,
call_with_mapped_captures: "MappedCapturesCallable | None" = None):
"""Specify a list of `SaveableObject`s to save and restore.
Args:
serialized_tensors: A dictionary mapping `Trackable` to a tensor dict,
which maps checkpoint_key -> (slice_spec ->) -> Tensor/SaveSpec. The
`Trackable` key is used to get the `restore_from_tensors` function,
and may be `None` if the tensor is not meant to be restored.
registered_savers: A dictionary mapping `registration.RegisteredSaver`
namedtuples to a dictionary of named Trackables. The keys of the
Trackable dictionary are string names that uniquely identify the
Trackable in the checkpoint.
call_with_mapped_captures: TODO
"""
self._shardable_tensors_by_task: MutableMapping[
device_lib.DeviceSpec,
MutableSequence[sharding_util.ShardableTensor]] = {}
# Keep these two data structures so that we can map restored tensors to
# the Trackable restore functions.
self._keys_to_restore_fn: MutableMapping[
TensorKeyAndSliceSpec, RestoreFn] = {}
self._restore_fn_to_keys: MutableMapping[
RestoreFn, MutableSequence[TensorKeyAndSliceSpec]] = {}
unique_tasks = set()
for obj, tensor_dict in serialized_tensors.items():
restore_fn = _restore_noop if obj is None else obj._restore_from_tensors
# Divide tensor_dict by task.
for checkpoint_key, tensor_slice_dict in tensor_dict.items():
if not isinstance(tensor_slice_dict, dict):
# Make sure that maybe_tensor is structured as {slice_spec -> tensor}.
tensor_slice_dict = {"": tensor_slice_dict}
for slice_spec, tensor_save_spec in tensor_slice_dict.items():
tensor_value = None
if not isinstance(tensor_save_spec, saveable_object.SaveSpec):
tensor_value = tensor_save_spec
tensor_save_spec = saveable_object.SaveSpec(
tensor=tensor_value,
slice_spec=slice_spec,
name=checkpoint_key,
dtype=tensor_save_spec.dtype,
device=tensor_save_spec.device)
if (checkpoint_key, slice_spec) in self._keys_to_restore_fn:
raise ValueError(
"Received multiple tensors with the same checkpoint key and "
"slice spec. This is invalid because one will overwrite the "
"other in the checkpoint. This indicates a bug in the "
"Checkpoint key-generation.")
self._keys_to_restore_fn[(checkpoint_key, slice_spec)] = restore_fn
self._restore_fn_to_keys.setdefault(restore_fn, []).append(
(checkpoint_key, slice_spec))
if isinstance(tensor_save_spec.device, str):
device = device_lib.DeviceSpec.from_string(tensor_save_spec.device)
task = device_lib.DeviceSpec.from_string(
saveable_object_util.set_cpu0(tensor_save_spec.device))
else:
device = tensor_save_spec.device
task = device_lib.DeviceSpec.from_string(
saveable_object_util.set_cpu0(device.to_string()))
self._shardable_tensors_by_task.setdefault(task, []).append(
sharding_util.ShardableTensor(
_tensor_save_spec=tensor_save_spec,
tensor=tensor_value,
dtype=tensor_save_spec.dtype,
device=device,
name=tensor_save_spec.name,
shape=None,
slice_spec=slice_spec.strip(),
checkpoint_key=checkpoint_key,
trackable=obj))
unique_tasks.add(
saveable_object_util.set_cpu0(device.to_string()))
self._num_unique_tasks = len(unique_tasks)
self._registered_savers = {}
if registered_savers:
for registered_name, trackables in registered_savers.items():
save_fn = _get_mapped_registered_save_fn(
registration.get_save_function(registered_name),
trackables, call_with_mapped_captures)
restore_fn = _get_mapped_registered_restore_fn(
registration.get_restore_function(registered_name),
trackables, call_with_mapped_captures)
self._registered_savers[registered_name] = (save_fn, restore_fn)
@classmethod
def from_saveables(
cls,
saveables: Sequence[base.Trackable],
registered_savers: "RegisteredSaversDict | None" = None,
call_with_mapped_captures: "MappedCapturesCallable | None" = None
) -> "MultiDeviceSaver":
"""Constructs a MultiDeviceSaver from a list of `SaveableObject`s."""
serialized_tensors = object_identity.ObjectIdentityDictionary()
for saveable in saveables:
trackable = saveable_object_util.SaveableCompatibilityConverter(
saveable, saveables=[saveable])
serialized_tensors[trackable] = trackable._serialize_to_tensors() # pylint: disable=protected-access
return cls(serialized_tensors, registered_savers, call_with_mapped_captures)
def to_proto(self) -> saver_pb2.SaverDef:
"""Serializes to a SaverDef referencing the current graph."""
filename_tensor = array_ops.placeholder(
shape=[], dtype=dtypes.string, name="saver_filename")
save_tensor = self._traced_save(filename_tensor)
restore_op = self._traced_restore(filename_tensor).op
return saver_pb2.SaverDef(
filename_tensor_name=filename_tensor.name,
save_tensor_name=save_tensor.name,
restore_op_name=restore_op.name,
version=saver_pb2.SaverDef.V2)
@def_function.function(
input_signature=(tensor_spec.TensorSpec(shape=(), dtype=dtypes.string),),
autograph=False)
def _traced_save(self, file_prefix: tensor_lib.Tensor) -> tensor_lib.Tensor:
save_op = self.save(file_prefix)
with ops.device("cpu:0"):
with ops.control_dependencies([save_op]):
return array_ops.identity(file_prefix)
@def_function.function(
input_signature=(tensor_spec.TensorSpec(shape=(), dtype=dtypes.string),),
autograph=False)
def _traced_restore(
self, file_prefix: tensor_lib.Tensor) -> tensor_lib.Tensor:
restore_ops = self.restore(file_prefix)
with ops.device("cpu:0"):
with ops.control_dependencies(restore_ops.values()):
return array_ops.identity(file_prefix)
def _get_shards_by_task(
self,
sharding_callback: sharding_util.ShardingCallback
) -> Sequence[tuple[str, Sequence[sharding_util.Shard]]]:
"""Calls the sharding callback with shardable_tensors.
Args:
sharding_callback: ShardingCallback. The callback function wrapper that
splits shardable_tensors into shards.
Returns:
A list of (task, shards) tuples.
"""
def wrap_tensor(shardable_tensor):
tensor_val = shardable_tensor.tensor
tensor_shape = shardable_tensor.shape
save_spec = shardable_tensor._tensor_save_spec # pylint: disable=protected-access
with ops.device(shardable_tensor.device):
save_spec_tensor = save_spec.tensor
if tensor_val is None and save_spec_tensor is None:
# A tensor value of `None` indicates that this SaveableObject gets
# recorded in the object graph, but that no value is saved in the
# checkpoint.
return None
elif save_spec_tensor is not None:
# Pull the tensor value from _tensor_save_spec.
tensor_val = save_spec_tensor
tensor_shape = save_spec_tensor.shape
# Propagate the save spec name and/or slice spec when they are tensors.
# This makes sure properties like `layout` for dtensor names/slice specs
# are preserved during sharding.
if isinstance(save_spec.name, tensor_lib.Tensor):
tensor_val._wrapped_name = save_spec.name # pylint: disable=protected-access
if isinstance(shardable_tensor.slice_spec, tensor_lib.Tensor):
tensor_val._wrapped_slice_spec = save_spec.slice_spec # pylint: disable=protected-access
return dataclasses.replace(
shardable_tensor,
tensor=tensor_val,
shape=tensor_shape)
shardable_tensors_by_task = {
task: [shardable_tensor
for shardable_tensor in map(wrap_tensor, shardable_tensors)
if shardable_tensor is not None]
for task, shardable_tensors in self._shardable_tensors_by_task.items()}
sharding_callback = (
sharding_callback or sharding_policies.ShardByTaskPolicy())
metrics.SetShardingCallbackDescription(
description=sharding_callback.description)
callback_start_time = time.time() * 1e6
shards_by_task = []
for task, shardable_tensors in shardable_tensors_by_task.items():
shards_by_task.append((task, sharding_callback(shardable_tensors)))
callback_end_time = time.time() * 1e6
callback_duration = math.ceil(callback_end_time - callback_start_time)
metrics.AddShardingCallbackDuration(
callback_duration=max(1, callback_duration)) # in microseconds
logging.info("Sharding callback duration: %s microseconds",
callback_duration)
return shards_by_task
def save(
self,
file_prefix: tensor_lib.Tensor,
options: "checkpoint_options.CheckpointOptions | None" = None
) -> ops.Operation:
"""Save the saveable objects to a checkpoint with `file_prefix`.
Args:
file_prefix: A string or scalar string Tensor containing the prefix to
save under.
options: Optional `CheckpointOptions` object.
Returns:
An `Operation`, or None when executing eagerly.
"""
options = options or checkpoint_options.CheckpointOptions()
# IMPLEMENTATION DETAILS: most clients should skip.
#
# Suffix for any well-formed "checkpoint_prefix", when sharded.
# Transformations:
# * Users pass in "save_path" in save() and restore(). Say "myckpt".
# * checkpoint_prefix gets fed <save_path><sharded_suffix>.
#
# Example:
# During runtime, a temporary directory is first created, which contains
# files
#
# <train dir>/myckpt_temp/
# part-?????-of-?????{.index, .data-00000-of-00001}
#
# Before .save() finishes, they will be (hopefully, atomically) renamed to
#
# <train dir>/
# myckpt{.index, .data-?????-of-?????}
#
# Filesystems with eventual consistency (such as S3), don't need a
# temporary location. Using a temporary directory in those cases might
# cause situations where files are not available during copy.
#
# Users only need to interact with the user-specified prefix, which is
# "<train dir>/myckpt" in this case. Save() and Restore() work with the
# prefix directly, instead of any physical pathname. (On failure and
# subsequent restore, an outdated and orphaned temporary directory can be
# safely removed.)
with ops.device("CPU"):
sharded_suffix = array_ops.where(
string_ops.regex_full_match(file_prefix, "^s3://.*"),
constant_op.constant(".part"),
constant_op.constant("_temp/part"))
tmp_checkpoint_prefix = string_ops.string_join(
[file_prefix, sharded_suffix])
registered_paths = {
saver_name: registered_saver_filename(file_prefix, saver_name)
for saver_name in self._registered_savers
}
def save_fn() -> ops.Operation:
saved_prefixes = []
# Save with the registered savers. These run before default savers due to
# the API contract.
for saver_name, (save_fn, _) in self._registered_savers.items():
maybe_saved_prefixes = save_fn(registered_paths[saver_name])
if maybe_saved_prefixes is not None:
flattened_saved_prefixes = nest.flatten(maybe_saved_prefixes)
if not all(
tensor_util.is_tf_type(x) and x.dtype == dtypes.string
for x in flattened_saved_prefixes):
raise ValueError(
"Registered saver must return a (maybe empty) list of "
f"string type tensors. Got {maybe_saved_prefixes}.")
saved_prefixes.extend(flattened_saved_prefixes)
shards_by_task = self._get_shards_by_task(
options.experimental_sharding_callback)
num_shards = sum([len(shards) for _, shards in shards_by_task])
metrics.AddNumCheckpointShardsWritten(num_shards=num_shards)
num_shards_tensor = constant_op.constant(num_shards, name="num_shards")
sharded_saves = []
shard_idx = 0
for task, shards in shards_by_task:
for shard in shards:
with ops.device(task):
shard_prefix = sharded_filename(tmp_checkpoint_prefix, shard_idx,
num_shards_tensor)
shard_idx += 1
saved_prefixes.append(shard_prefix)
sharded_saves.append(
_single_shard_save(shard_prefix, shard, task, options))
with ops.control_dependencies(sharded_saves):
# Merge on the io_device if specified, otherwise co-locates the merge op
# with the last device used.
tensor_device_spec = list(self._shardable_tensors_by_task.keys())[-1]
merge_device_spec = (
options.experimental_io_device or
saveable_object_util.set_cpu0(tensor_device_spec.to_string()))
with ops.device(merge_device_spec):
# V2 format write path consists of a metadata merge step. Once
# merged, attempts to delete the temporary directory,
# "<user-fed prefix>_temp".
return gen_io_ops.merge_v2_checkpoints(
saved_prefixes, file_prefix, delete_old_dirs=True)
# Since this will causes a function re-trace on each save, limit this to the
# cases where it is needed: eager and when there are multiple tasks. Note
# that the retrace is needed to ensure we pickup the latest values of
# options like experimental_io_device.
if context.executing_eagerly() and self._num_unique_tasks > 1:
# Explicitly place the identity op on the first device.
@def_function.function(jit_compile=False)
def tf_function_save() -> None:
save_fn()
tf_function_save()
else:
return save_fn()
def restore(
self,
file_prefix: tensor_lib.Tensor,
options: "checkpoint_options.CheckpointOptions | None" = None
) -> Mapping[str, ops.Operation]:
"""Restore the saveable objects from a checkpoint with `file_prefix`.
Args:
file_prefix: A string or scalar string Tensor containing the prefix for
files to read from.
options: Optional `CheckpointOptions` object.
Returns:
When not run eagerly or when saving on a single device, returns a
dictionary mapping from SaveableObject names to restore operations;
otherwise, returns an empty dict.
"""
options = options or checkpoint_options.CheckpointOptions()
def restore_fn() -> Mapping[str, ops.Operation]:
restore_fn_inputs = {}
restore_fn_input_count = {
fn: len(keys) for fn, keys in self._restore_fn_to_keys.items()}
restore_ops = {}
for task, shard in self._shardable_tensors_by_task.items():
with ops.device(task):
# Load values from checkpoint
restored_tensor_dict = _single_shard_restore(
file_prefix, shard, options)
# Map restored tensors to the corresponding restore_fn, and see if
# all inputs have all been loaded. Call `restore_fn` if that is the
# case.
for ckpt_key, slice_and_tensor in restored_tensor_dict.items():
for slice_spec, tensor in slice_and_tensor.items():
restore_fn = self._keys_to_restore_fn[(ckpt_key,
slice_spec)]
# Processing the returned restored_tensor_dict to prepare for
# the Trackable `restore` function. The `restore` function
# expects a map of `string name (checkpoint_key) -> Tensor`.
# Unless there is a slice_spec, in which case the map will be of
# `string name (checkpoint_key)-> slice_spec -> Tensor`.
if slice_spec:
(restore_fn_inputs.setdefault(restore_fn, {}).setdefault(
ckpt_key, {})[slice_spec]) = tensor
else:
restore_fn_inputs.setdefault(restore_fn,
{})[ckpt_key] = tensor
restore_fn_input_count[restore_fn] -= 1
if restore_fn_input_count[restore_fn] == 0:
restored_tensors = {}
# Extracts the substring after the "/.ATTRIBUTES/" in the
# ckpt_key from restore_fn_inputs[restore_fn] to
# restored_tensors. For example, if
# restore_fn_input[restore_fn] is dict
# { "/.ATTIBUTES/a": Tensor}, restored_tensors will be
# changed to dict {"a": Tensor}
for ckpt_key, tensor in restore_fn_inputs[restore_fn].items():
restored_tensors[trackable_utils.extract_local_name(
ckpt_key)] = tensor
ret = restore_fn(restored_tensors)
if isinstance(ret, dict):
restore_ops.update(ret)
# Run registered restore methods after the default restore ops.
for _, (_, restore_fn) in self._registered_savers.items():
restore_fn(file_prefix)
return restore_ops
has_custom_device_saver = False
for sts in self._shardable_tensors_by_task.values():
if any([context.is_custom_device(st.device.to_string()) for st in sts]):
has_custom_device_saver = True
break
# Since this will cause a function re-trace on each restore, limit this to
# cases where it is needed: eager and when there are multiple tasks or any
# device_spec is a custom device. Note that the retrace is needed to ensure
# we pickup the latest values of options like experimental_io_device.
#
# We run in a function when there is a custom device saver because custom
# devices, such as DTensor, usually do a sharded save and restore.
# Doing a sharded save and restore requires knowledge about what shards
# of variables we are restoring to. In practice, this means that custom
# devices need the AssignVariableOps along with the Restore op within the
# same graph to infer shapes and shard specs for Restore op.
if context.executing_eagerly() and (self._num_unique_tasks > 1 or
has_custom_device_saver):
@def_function.function(jit_compile=False, autograph=False)
def tf_function_restore() -> Mapping[str, ops.Operation]:
restore_fn()
return {}
restore_ops = tf_function_restore()
else:
restore_ops = restore_fn()
return restore_ops
| MultiDeviceSaver |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-mistral-rs/llama_index/llms/mistral_rs/base.py | {
"start": 2837,
"end": 12662
} | class ____(CustomLLM):
r"""
MistralRS LLM.
Examples:
Install `mistralrs` following instructions:
https://github.com/EricLBuehler/mistral.rs/blob/master/mistralrs-pyo3/README.md#installation-from-pypi
Then `pip install llama-index-llms-mistral-rs`
This LLM provides automatic chat templating as an option. If you do not provide `messages_to_prompt`,
mistral.rs will automatically determine one. You can specify a JINJA chat template by passing it in
`model_kwargs` in the `chat_template` key.
```python
from llama_index.llms.mistral_rs import MistralRS
from mistralrs import Which
llm = MistralRS(
which = Which.XLora(
model_id=None, # Automatically determine from ordering file
tokenizer_json=None,
repeat_last_n=64,
xlora_model_id="lamm-mit/x-lora"
order="xlora-paper-ordering.json", # Make sure you copy the ordering file from `mistral.rs/orderings`
tgt_non_granular_index=None,
arch=Architecture.Mistral,
),
temperature=0.1,
max_new_tokens=256,
context_window=3900,
generate_kwargs={},
verbose=True,
)
response = llm.complete("Hello, how are you?")
print(str(response))
```
"""
model_url: Optional[str] = Field(description="local")
model_path: Optional[str] = Field(description="local")
temperature: float = Field(
default=DEFAULT_TEMPERATURE,
description="The temperature to use for sampling.",
ge=0.0,
le=1.0,
)
max_new_tokens: int = Field(
default=DEFAULT_NUM_OUTPUTS,
description="The maximum number of tokens to generate.",
gt=0,
)
context_window: int = Field(
default=DEFAULT_CONTEXT_WINDOW,
description="The maximum number of context tokens for the model.",
gt=0,
)
generate_kwargs: Dict[str, Any] = Field(
default_factory=dict, description="Kwargs used for generation."
)
model_kwargs: Dict[str, Any] = Field(
default_factory=dict, description="Kwargs used for model initialization."
)
_runner: "Runner" = PrivateAttr("Mistral.rs model runner.")
_has_messages_to_prompt: bool = PrivateAttr("If `messages_to_prompt` is provided.")
def __init__(
self,
which: "Which",
temperature: float = DEFAULT_TEMPERATURE,
max_new_tokens: int = DEFAULT_NUM_OUTPUTS,
context_window: int = DEFAULT_CONTEXT_WINDOW,
top_k: int = DEFAULT_TOPK,
top_p: int = DEFAULT_TOPP,
frequency_penalty: Optional[float] = None,
presence_penalty: Optional[float] = None,
in_situ_quant: Optional[str] = None,
max_seqs: int = DEFAULT_MAX_SEQS,
token_source: str = "cache",
prefix_cache_n: str = DEFAULT_PREFIX_CACHE_N,
no_kv_cache: bool = False,
chat_template: Optional[str] = None,
top_logprobs: Optional[int] = None,
callback_manager: Optional[CallbackManager] = None,
generate_kwargs: Optional[Dict[str, Any]] = None,
system_prompt: Optional[str] = None,
messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None,
completion_to_prompt: Optional[Callable[[str], str]] = None,
pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT,
output_parser: Optional[BaseOutputParser] = None,
) -> None:
generate_kwargs = generate_kwargs or {}
generate_kwargs.update(
{
"temperature": temperature,
"max_tokens": max_new_tokens,
"top_k": top_k,
"top_p": top_p,
"top_logprobs": top_logprobs,
"logprobs": top_logprobs is not None,
"frequency_penalty": frequency_penalty,
"presence_penalty": presence_penalty,
}
)
super().__init__(
model_path="local",
model_url="local",
temperature=temperature,
context_window=context_window,
max_new_tokens=max_new_tokens,
callback_manager=callback_manager,
generate_kwargs=generate_kwargs,
model_kwargs={},
verbose=True,
system_prompt=system_prompt,
messages_to_prompt=messages_to_prompt,
completion_to_prompt=completion_to_prompt,
pydantic_program_mode=pydantic_program_mode,
output_parser=output_parser,
)
self._runner = Runner(
which=which,
token_source=token_source,
max_seqs=max_seqs,
prefix_cache_n=prefix_cache_n,
no_kv_cache=no_kv_cache,
chat_template=chat_template,
in_situ_quant=in_situ_quant,
)
self._has_messages_to_prompt = messages_to_prompt is not None
@classmethod
def class_name(cls) -> str:
return "MistralRS"
@property
def metadata(self) -> LLMMetadata:
"""LLM metadata."""
return LLMMetadata(
context_window=self.context_window,
num_output=self.max_new_tokens,
model_name=self.model_path,
)
@llm_chat_callback()
def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse:
try:
from mistralrs import ChatCompletionRequest
except ImportError as e:
raise ValueError(
"Missing `mistralrs` package. Install via `pip install mistralrs`."
) from e
if self._has_messages_to_prompt:
messages = self.messages_to_prompt(messages)
else:
messages = llama_index_to_mistralrs_messages(messages)
self.generate_kwargs.update({"stream": False})
request = ChatCompletionRequest(
messages=messages,
model="",
logit_bias=None,
**self.generate_kwargs,
)
response = self._runner.send_chat_completion_request(request)
return CompletionResponse(
text=response.choices[0].message.content,
logprobs=extract_logprobs(response),
)
@llm_chat_callback()
def stream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseGen:
try:
from mistralrs import ChatCompletionRequest
except ImportError as e:
raise ValueError(
"Missing `mistralrs` package. Install via `pip install mistralrs`."
) from e
if self._has_messages_to_prompt:
messages = self.messages_to_prompt(messages)
else:
messages = llama_index_to_mistralrs_messages(messages)
self.generate_kwargs.update({"stream": True})
request = ChatCompletionRequest(
messages=messages,
model="",
logit_bias=None,
**self.generate_kwargs,
)
streamer = self._runner.send_chat_completion_request(request)
def gen() -> CompletionResponseGen:
text = ""
for response in streamer:
delta = response.choices[0].delta.content
text += delta
yield ChatResponse(
message=ChatMessage(
role=MessageRole.ASSISTANT,
content=delta,
),
delta=delta,
logprobs=extract_logprobs_stream(response),
)
return gen()
@llm_completion_callback()
def complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
try:
from mistralrs import ChatCompletionRequest
except ImportError as e:
raise ValueError(
"Missing `mistralrs` package. Install via `pip install mistralrs`."
) from e
self.generate_kwargs.update({"stream": False})
if not formatted:
prompt = self.completion_to_prompt(prompt)
request = ChatCompletionRequest(
messages=prompt,
model="",
logit_bias=None,
**self.generate_kwargs,
)
completion_response = self._runner.send_chat_completion_request(request)
return CompletionResponse(
text=completion_response.choices[0].message.content,
logprobs=extract_logprobs(completion_response),
)
@llm_completion_callback()
def stream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseGen:
try:
from mistralrs import ChatCompletionRequest
except ImportError as e:
raise ValueError(
"Missing `mistralrs` package. Install via `pip install mistralrs`."
) from e
self.generate_kwargs.update({"stream": True})
if not formatted:
prompt = self.completion_to_prompt(prompt)
request = ChatCompletionRequest(
messages=prompt,
model="",
logit_bias=None,
**self.generate_kwargs,
)
streamer = self._runner.send_chat_completion_request(request)
def gen() -> CompletionResponseGen:
text = ""
for response in streamer:
delta = response.choices[0].delta.content
text += delta
yield CompletionResponse(
delta=delta,
text=text,
logprobs=extract_logprobs_stream(response),
)
return gen()
| MistralRS |
python | PrefectHQ__prefect | src/prefect/testing/fixtures.py | {
"start": 8040,
"end": 8290
} | class ____:
connections: int
path: Optional[str]
events: List[Event]
token: Optional[str]
filter: Optional[EventFilter]
def __init__(self):
self.connections = 0
self.path = None
self.events = []
| Recorder |
python | google__pytype | pytype/errors/errors_test.py | {
"start": 437,
"end": 6509
} | class ____(unittest.TestCase):
@errors._error_name(_TEST_ERROR)
def test_init(self):
e = errors.Error(
errors.SEVERITY_ERROR,
_MESSAGE,
filename="foo.py",
line=123,
methodname="foo",
keyword="here",
)
self.assertEqual(errors.SEVERITY_ERROR, e._severity)
self.assertEqual(_MESSAGE, e._message)
self.assertEqual(e._name, _TEST_ERROR)
self.assertEqual("foo.py", e._filename)
self.assertEqual(123, e._line)
self.assertEqual("foo", e._methodname)
self.assertEqual("here", e.keyword)
@errors._error_name(_TEST_ERROR)
def test_with_stack(self):
# Opcode of None.
e = errors.Error.with_stack(
None, errors.SEVERITY_ERROR, _MESSAGE, keyword="here"
)
self.assertEqual(errors.SEVERITY_ERROR, e._severity)
self.assertEqual(_MESSAGE, e._message)
self.assertEqual(e._name, _TEST_ERROR)
self.assertIsNone(e._filename)
self.assertEqual(0, e._line)
self.assertIsNone(e._methodname)
self.assertEqual("here", e.keyword)
# Opcode of None.
op = test_utils.FakeOpcode("foo.py", 123, 123, 0, 0, "foo")
e = errors.Error.with_stack(
op.to_stack(), errors.SEVERITY_ERROR, _MESSAGE, keyword="here"
)
self.assertEqual(errors.SEVERITY_ERROR, e._severity)
self.assertEqual(_MESSAGE, e._message)
self.assertEqual(e._name, _TEST_ERROR)
self.assertEqual("foo.py", e._filename)
self.assertEqual(123, e._line)
self.assertEqual("foo", e._methodname)
self.assertEqual("here", e.keyword)
@errors._error_name(_TEST_ERROR)
def test_no_traceback_stack_len_1(self):
# Stack of length 1
op = test_utils.FakeOpcode("foo.py", 123, 123, 0, 0, "foo")
error = errors.Error.with_stack(op.to_stack(), errors.SEVERITY_ERROR, "")
self.assertIsNone(error._traceback)
@errors._error_name(_TEST_ERROR)
def test_no_traceback_no_opcode(self):
# Frame without opcode
op = test_utils.FakeOpcode("foo.py", 123, 123, 0, 0, "foo")
stack = [frame_state.SimpleFrame(), frame_state.SimpleFrame(op)]
error = errors.Error.with_stack(stack, errors.SEVERITY_ERROR, "")
self.assertIsNone(error._traceback)
@errors._error_name(_TEST_ERROR)
def test_traceback(self):
stack = test_utils.fake_stack(errors.MAX_TRACEBACK_LENGTH + 1)
error = errors.Error.with_stack(stack, errors.SEVERITY_ERROR, "")
self.assertMultiLineEqual(
error._traceback,
textwrap.dedent("""
Called from (traceback):
line 0, in function0
line 1, in function1
line 2, in function2""").lstrip(),
)
@errors._error_name(_TEST_ERROR)
def test_truncated_traceback(self):
stack = test_utils.fake_stack(errors.MAX_TRACEBACK_LENGTH + 2)
error = errors.Error.with_stack(stack, errors.SEVERITY_ERROR, "")
self.assertMultiLineEqual(
error._traceback,
textwrap.dedent("""
Called from (traceback):
line 0, in function0
...
line 3, in function3""").lstrip(),
)
def test__error_name(self):
# This should be true as long as at least one method is annotated with
# _error_name(_TEST_ERROR).
self.assertIn(_TEST_ERROR, errors._ERROR_NAMES)
def test_no_error_name(self):
# It is illegal to create an error outside of an @error_name annotation.
self.assertRaises(
AssertionError, errors.Error, errors.SEVERITY_ERROR, _MESSAGE, src=""
)
@errors._error_name(_TEST_ERROR)
def test_str(self):
e = errors.Error(
errors.SEVERITY_ERROR,
_MESSAGE,
filename="foo.py",
line=1,
endline=1,
col=1,
endcol=2,
methodname="foo",
src="",
)
self.assertEqual(
str(e),
textwrap.dedent(
"""foo.py:1:2: \x1b[1m\x1b[31merror\x1b[39m\x1b[0m: in foo: """
+ """an error message on 'here' [test-error]"""
),
)
@errors._error_name(_TEST_ERROR)
def test_write_to_csv(self):
errorlog = make_errorlog()
op = test_utils.FakeOpcode("foo.py", 123, 123, 0, 0, "foo")
message, details = "This is an error", 'with\nsome\ndetails: "1", 2, 3'
errorlog.error(op.to_stack(), message, details + "0")
errorlog.error(op.to_stack(), message, details + "1")
with test_utils.Tempdir() as d:
filename = d.create_file("errors.csv")
with open(filename, "w") as fi:
errorlog.print_to_csv_file(fi)
with open(filename) as fi:
rows = list(csv.reader(fi, delimiter=","))
self.assertEqual(len(rows), 2)
for i, row in enumerate(rows):
filename, lineno, name, actual_message, actual_details = row
self.assertEqual(filename, "foo.py")
self.assertEqual(lineno, "123")
self.assertEqual(name, _TEST_ERROR)
self.assertEqual(actual_message, message)
self.assertEqual(actual_details, details + str(i))
@errors._error_name(_TEST_ERROR)
def test_write_to_csv_with_traceback(self):
errorlog = make_errorlog()
stack = test_utils.fake_stack(2)
errorlog.error(stack, "", "some\ndetails")
with test_utils.Tempdir() as d:
filename = d.create_file("errors.csv")
with open(filename, "w") as fi:
errorlog.print_to_csv_file(fi)
with open(filename) as fi:
((_, _, _, _, actual_details),) = list(csv.reader(fi, delimiter=","))
self.assertMultiLineEqual(
actual_details,
textwrap.dedent("""
some
details
Called from (traceback):
line 0, in function0""").lstrip(),
)
@errors._error_name(_TEST_ERROR)
def test_color(self):
e = errors.Error(
errors.SEVERITY_ERROR,
_MESSAGE,
filename="foo.py",
line=123,
methodname="foo",
keyword="here",
src="",
)
color_snippet = "'here' [\x1b[1m\x1b[31mtest-error\x1b[39m\x1b[0m]"
self.assertIn(color_snippet, e.as_string(color=True))
self.assertNotIn(color_snippet, e.as_string())
self.assertEqual(str(e), e.as_string())
| ErrorTest |
python | apache__airflow | task-sdk/src/airflow/sdk/exceptions.py | {
"start": 4281,
"end": 4551
} | class ____(_AirflowExecuteWithInactiveAssetExecption):
"""Raise when the task is executed with inactive assets in its inlet or outlet."""
main_message = "Task has the following inactive assets in its inlets or outlets"
| AirflowInactiveAssetInInletOrOutletException |
python | django__django | tests/urlpatterns/test_resolvers.py | {
"start": 367,
"end": 863
} | class ____(SimpleTestCase):
def test_str(self):
self.assertEqual(str(RoutePattern(_("translated/"))), "translated/")
def test_has_converters(self):
self.assertEqual(len(RoutePattern("translated/").converters), 0)
self.assertEqual(len(RoutePattern(_("translated/")).converters), 0)
self.assertEqual(len(RoutePattern("translated/<int:foo>").converters), 1)
self.assertEqual(len(RoutePattern(_("translated/<int:foo>")).converters), 1)
| RoutePatternTests |
python | django__django | tests/model_options/apps.py | {
"start": 346,
"end": 441
} | class ____(AppConfig):
name = "model_options"
default_auto_field = None
| ModelPKNoneConfig |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-vertex-endpoint/llama_index/embeddings/vertex_endpoint/base.py | {
"start": 518,
"end": 6170
} | class ____(BaseEmbedding):
endpoint_id: str = Field(description="Vertex AI endpoint ID")
project_id: str = Field(description="GCP Project ID")
location: str = Field(description="GCP Region for Vertex AI")
endpoint_kwargs: Dict[str, Any] = Field(
default_factory=dict,
description="Additional kwargs for the predict request.",
)
model_kwargs: Dict[str, Any] = Field(
default_factory=dict,
description="kwargs to pass to the model.",
)
content_handler: BaseIOHandler = Field(
default=DEFAULT_IO_HANDLER,
description="used to format input/output",
)
service_account_file: Optional[str] = Field(
default=None, description="Path to the service account JSON file."
)
service_account_info: Optional[Dict[str, str]] = Field(
default=None, description="Directly provide service account credentials."
)
timeout: Optional[float] = Field(
default=60.0,
description="Timeout for API requests in seconds.",
ge=0,
)
_client: aiplatform.Endpoint = PrivateAttr()
_verbose: bool = PrivateAttr()
def __init__(
self,
endpoint_id: str,
project_id: str,
location: str,
content_handler: BaseIOHandler = DEFAULT_IO_HANDLER,
endpoint_kwargs: Optional[Dict[str, Any]] = {},
model_kwargs: Optional[Dict[str, Any]] = {},
service_account_file: Optional[str] = None,
service_account_info: Optional[Dict[str, str]] = None,
timeout: Optional[float] = 60.0,
embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE,
callback_manager: Optional[CallbackManager] = None,
verbose: bool = False,
):
super().__init__(
endpoint_id=endpoint_id,
embed_batch_size=embed_batch_size,
callback_manager=callback_manager,
project_id=project_id,
location=location,
content_handler=content_handler,
endpoint_kwargs=endpoint_kwargs or {},
model_kwargs=model_kwargs or {},
timeout=timeout,
)
# Initialize the client
if service_account_file:
credentials = service_account.Credentials.from_service_account_file(
service_account_file
)
elif service_account_info:
credentials = service_account.Credentials.from_service_account_info(
service_account_info
)
else:
credentials = None # Use default application credentials if not provided
try:
self._client = aiplatform.Endpoint(
endpoint_name=endpoint_id,
project=project_id,
location=location,
credentials=credentials,
)
except Exception as e:
raise ValueError("Please verify the provided credentials.") from (e)
self._verbose = verbose
@classmethod
def class_name(cls) -> str:
return "VertexEndpointEmbedding"
def _get_embedding(self, payload: List[str], **kwargs: Any) -> List[Embedding]:
# Combine model kwargs with any additional kwargs passed to the function
endpoint_kwargs = {**self.endpoint_kwargs, **{"timeout": self.timeout}}
model_kwargs = {**self.model_kwargs, **kwargs}
# Directly send the input payload to the endpoint
response = self._client.predict(
instances=self.content_handler.serialize_input(payload),
parameters=model_kwargs,
**endpoint_kwargs,
)
# Assuming response contains the embeddings in a field called 'predictions'
return self.content_handler.deserialize_output(response)
async def _aget_embedding(
self, payload: List[str], **kwargs: Any
) -> List[Embedding]:
# Combine model kwargs with any additional kwargs passed to the function
endpoint_kwargs = {**self.endpoint_kwargs, **{"timeout": self.timeout}}
model_kwargs = {**self.model_kwargs, **kwargs}
# Directly send the input payload to the endpoint
response = await self._client.predict_async(
instances=self.content_handler.serialize_input(payload),
parameters=model_kwargs,
**endpoint_kwargs,
)
# Assuming response contains the embeddings in a field called 'predictions'
return self.content_handler.deserialize_output(response)
def _get_query_embedding(self, query: str, **kwargs: Any) -> Embedding:
query = query.replace("\n", " ")
return self._get_embedding([query], **kwargs)[0]
def _get_text_embedding(self, text: str, **kwargs: Any) -> Embedding:
text = text.replace("\n", " ")
return self._get_embedding([text], **kwargs)[0]
def _get_text_embeddings(self, texts: List[str], **kwargs: Any) -> List[Embedding]:
texts = [text.replace("\n", " ") for text in texts]
return self._get_embedding(texts, **kwargs)
async def _aget_query_embedding(self, query: str, **kwargs: Any) -> Embedding:
query = query.replace("\n", " ")
return await self._aget_embedding([query], **kwargs)[0]
async def _aget_text_embedding(self, text: str, **kwargs: Any) -> Embedding:
text = text.replace("\n", " ")
return await self._aget_embedding([text], **kwargs)[0]
async def _aget_text_embeddings(
self, texts: List[str], **kwargs: Any
) -> List[Embedding]:
texts = [text.replace("\n", " ") for text in texts]
return await self._aget_embedding(texts, **kwargs)
| VertexEndpointEmbedding |
python | ray-project__ray | rllib/algorithms/dqn/dqn_catalog.py | {
"start": 392,
"end": 7426
} | class ____(Catalog):
"""The catalog class used to build models for DQN Rainbow.
`DQNCatalog` provides the following models:
- Encoder: The encoder used to encode the observations.
- Target_Encoder: The encoder used to encode the observations
for the target network.
- Af Head: Either the head of the advantage stream, if a dueling
architecture is used or the head of the Q-function. This is
a multi-node head with `action_space.n` many nodes in case
of expectation learning and `action_space.n` times the number
of atoms (`num_atoms`) in case of distributional Q-learning.
- Vf Head (optional): The head of the value function in case a
dueling architecture is chosen. This is a single node head.
If no dueling architecture is used, this head does not exist.
Any custom head can be built by overridng the `build_af_head()` and
`build_vf_head()`. Alternatively, the `AfHeadConfig` or `VfHeadConfig`
can be overridden to build custom logic during `RLModule` runtime.
All heads can optionally use distributional learning. In this case the
number of output neurons corresponds to the number of actions times the
number of support atoms of the discrete distribution.
Any module built for exploration or inference is built with the flag
`ìnference_only=True` and does not contain any target networks. This flag can
be set in a `SingleAgentModuleSpec` through the `inference_only` boolean flag.
"""
@override(Catalog)
def __init__(
self,
observation_space: gym.Space,
action_space: gym.Space,
model_config_dict: dict,
view_requirements: dict = None,
):
"""Initializes the DQNCatalog.
Args:
observation_space: The observation space of the Encoder.
action_space: The action space for the Af Head.
model_config_dict: The model config to use.
"""
assert view_requirements is None, (
"Instead, use the new ConnectorV2 API to pick whatever information "
"you need from the running episodes"
)
super().__init__(
observation_space=observation_space,
action_space=action_space,
model_config_dict=model_config_dict,
)
# The number of atoms to be used for distributional Q-learning.
self.num_atoms: bool = self._model_config_dict["num_atoms"]
# Advantage and value streams have MLP heads. Note, the advantage
# stream will has an output dimension that is the product of the
# action space dimension and the number of atoms to approximate the
# return distribution in distributional reinforcement learning.
self.af_head_config = self._get_head_config(
output_layer_dim=int(self.action_space.n * self.num_atoms)
)
self.vf_head_config = self._get_head_config(output_layer_dim=1)
@OverrideToImplementCustomLogic
def build_af_head(self, framework: str) -> Model:
"""Build the A/Q-function head.
Note, if no dueling architecture is chosen, this will
be the Q-function head.
The default behavior is to build the head from the `af_head_config`.
This can be overridden to build a custom policy head as a means to
configure the behavior of a `DQNRLModule` implementation.
Args:
framework: The framework to use. Either "torch" or "tf2".
Returns:
The advantage head in case a dueling architecutre is chosen or
the Q-function head in the other case.
"""
return self.af_head_config.build(framework=framework)
@OverrideToImplementCustomLogic
def build_vf_head(self, framework: str) -> Model:
"""Build the value function head.
Note, this function is only called in case of a dueling architecture.
The default behavior is to build the head from the `vf_head_config`.
This can be overridden to build a custom policy head as a means to
configure the behavior of a `DQNRLModule` implementation.
Args:
framework: The framework to use. Either "torch" or "tf2".
Returns:
The value function head.
"""
return self.vf_head_config.build(framework=framework)
@override(Catalog)
def get_action_dist_cls(self, framework: str) -> "TorchCategorical":
# We only implement DQN Rainbow for Torch.
if framework != "torch":
raise ValueError("DQN Rainbow is only supported for framework `torch`.")
else:
return TorchCategorical
def _get_head_config(self, output_layer_dim: int):
"""Returns a head config.
Args:
output_layer_dim: Integer defining the output layer dimension.
This is 1 for the Vf-head and `action_space.n * num_atoms`
for the Af(Qf)-head.
Returns:
A `MLPHeadConfig`.
"""
# Return the appropriate config.
return MLPHeadConfig(
input_dims=self.latent_dims,
hidden_layer_dims=self._model_config_dict["head_fcnet_hiddens"],
# Note, `"post_fcnet_activation"` is `"relu"` by definition.
hidden_layer_activation=self._model_config_dict["head_fcnet_activation"],
# TODO (simon): Not yet available.
# hidden_layer_use_layernorm=self._model_config_dict[
# "hidden_layer_use_layernorm"
# ],
# hidden_layer_use_bias=self._model_config_dict["hidden_layer_use_bias"],
hidden_layer_weights_initializer=self._model_config_dict[
"head_fcnet_kernel_initializer"
],
hidden_layer_weights_initializer_config=self._model_config_dict[
"head_fcnet_kernel_initializer_kwargs"
],
hidden_layer_bias_initializer=self._model_config_dict[
"head_fcnet_bias_initializer"
],
hidden_layer_bias_initializer_config=self._model_config_dict[
"head_fcnet_bias_initializer_kwargs"
],
output_layer_activation="linear",
output_layer_dim=output_layer_dim,
# TODO (simon): Not yet available.
# output_layer_use_bias=self._model_config_dict["output_layer_use_bias"],
output_layer_weights_initializer=self._model_config_dict[
"head_fcnet_kernel_initializer"
],
output_layer_weights_initializer_config=self._model_config_dict[
"head_fcnet_kernel_initializer_kwargs"
],
output_layer_bias_initializer=self._model_config_dict[
"head_fcnet_bias_initializer"
],
output_layer_bias_initializer_config=self._model_config_dict[
"head_fcnet_bias_initializer_kwargs"
],
)
| DQNCatalog |
python | huggingface__transformers | tests/utils/test_model_output.py | {
"start": 6424,
"end": 6920
} | class ____(unittest.TestCase):
def test_direct_model_output(self):
# Check that direct usage of ModelOutput instantiates without errors
ModelOutput({"a": 1.1})
def test_subclass_no_dataclass(self):
# Check that a subclass of ModelOutput without @dataclass is invalid
# A valid subclass is inherently tested other unit tests above.
with self.assertRaises(TypeError):
ModelOutputTestNoDataclass(a=1.1, b=2.2, c=3.3)
| ModelOutputSubclassTester |
python | PrefectHQ__prefect | src/integrations/prefect-redis/prefect_redis/messaging.py | {
"start": 1451,
"end": 2236
} | class ____(PrefectBaseSettings):
"""Settings for the Redis messaging publisher.
No settings are required to be set by the user but any of the settings can be
overridden by the user using environment variables.
Example:
```
PREFECT_REDIS_MESSAGING_PUBLISHER_BATCH_SIZE=10
PREFECT_REDIS_MESSAGING_PUBLISHER_PUBLISH_EVERY=10
PREFECT_REDIS_MESSAGING_PUBLISHER_DEDUPLICATE_BY=message_id
```
"""
model_config = build_settings_config(
(
"redis",
"messaging",
"publisher",
),
)
batch_size: int = Field(default=5)
publish_every: TimeDelta = Field(default=timedelta(seconds=10))
deduplicate_by: Optional[str] = Field(default=None)
| RedisMessagingPublisherSettings |
python | zarr-developers__zarr-python | src/zarr/codecs/blosc.py | {
"start": 994,
"end": 1176
} | class ____(TypedDict):
"""Configuration for the V2 Blosc codec"""
cname: CName
clevel: int
shuffle: int
blocksize: int
typesize: NotRequired[int]
| BloscConfigV2 |
python | google__jax | jax/_src/numpy/array_methods.py | {
"start": 32629,
"end": 50745
} | class ____:
"""Helper object to call indexed update functions for an (advanced) index.
This object references a source array and a specific indexer into that array.
Methods on this object return copies of the source array that have been
modified at the positions specified by the indexer.
"""
__slots__ = ("array", "index")
array: Array
index: scatter.Index
def __init__(self, array: Array, index: scatter.Index):
self.array = array
self.index = index
def __repr__(self) -> str:
return f"_IndexUpdateRef({self.array!r}, {self.index!r})"
def get(self, *, indices_are_sorted: bool = False, unique_indices: bool = False,
mode: str | lax_slicing.GatherScatterMode | None = None,
fill_value: ArrayLike | None = None,
out_sharding: Sharding | PartitionSpec | None = None,
wrap_negative_indices: bool = True):
"""Equivalent to ``x[idx]``.
Returns the value of ``x`` that would result from the NumPy-style
:mod:indexing <numpy.doc.indexing>` ``x[idx]``. This function differs from
the usual array indexing syntax in that it allows additional keyword
arguments ``indices_are_sorted`` and ``unique_indices`` to be passed.
See :func:`jax.numpy.ndarray.at` for details.
"""
if out_sharding is not None:
assert isinstance(out_sharding, (NamedSharding, PartitionSpec))
out_sharding = canonicalize_sharding(out_sharding, '.get')
return indexing.rewriting_take(self.array, self.index,
indices_are_sorted=indices_are_sorted,
unique_indices=unique_indices, mode=mode,
fill_value=fill_value,
normalize_indices=wrap_negative_indices,
out_sharding=out_sharding)
def set(self, values: ArrayLike, *, indices_are_sorted: bool = False,
unique_indices: bool = False,
mode: str | lax_slicing.GatherScatterMode | None = None,
out_sharding: Sharding | PartitionSpec | None = None,
wrap_negative_indices: bool = True) -> None:
"""Pure equivalent of ``x[idx] = y``.
Returns the value of ``x`` that would result from the NumPy-style
:mod:`indexed assignment <numpy.doc.indexing>` ``x[idx] = y``.
See :func:`jax.numpy.ndarray.at` for details.
"""
if out_sharding is not None:
assert isinstance(out_sharding, (NamedSharding, PartitionSpec))
out_sharding = canonicalize_sharding(out_sharding, '.set')
return scatter._scatter_update(
self.array, self.index, values, lax_slicing.scatter,
indices_are_sorted=indices_are_sorted, unique_indices=unique_indices,
mode=mode, out_sharding=out_sharding, # type: ignore
normalize_indices=wrap_negative_indices)
def apply(self, func: Callable[[ArrayLike], Array], *,
indices_are_sorted: bool = False, unique_indices: bool = False,
mode: str | lax_slicing.GatherScatterMode | None = None,
wrap_negative_indices: bool = True) -> Array:
"""Pure equivalent of ``func.at(x, idx)`` for a unary ufunc ``func``.
Returns the value of ``x`` that would result from applying the unary
function ``func`` to ``x`` at the given indices. This is similar to
``x.at[idx].set(func(x[idx]))``, but differs in the case of repeated indices:
in ``x.at[idx].apply(func)``, repeated indices result in the function being
applied multiple times.
Note that in the current implementation, ``scatter_apply`` is not compatible
with automatic differentiation.
See :func:`jax.numpy.ndarray.at` for details.
"""
def _scatter_apply(x, indices, y, dims, **kwargs):
return lax_slicing.scatter_apply(x, indices, func, dims, update_shape=y.shape, **kwargs)
return scatter._scatter_update(
self.array, self.index, lax._zero(self.array), _scatter_apply,
indices_are_sorted=indices_are_sorted, unique_indices=unique_indices,
mode=mode, normalize_indices=wrap_negative_indices)
def add(self, values: ArrayLike, *,
indices_are_sorted: bool = False, unique_indices: bool = False,
mode: str | lax_slicing.GatherScatterMode | None = None,
out_sharding: Sharding | PartitionSpec | None = None,
wrap_negative_indices: bool = True) -> Array:
"""Pure equivalent of ``x[idx] += y``.
Returns the value of ``x`` that would result from the NumPy-style
:mod:indexed assignment <numpy.doc.indexing>` ``x[idx] += y``.
See :func:`jax.numpy.ndarray.at` for details.
"""
if out_sharding is not None:
assert isinstance(out_sharding, (NamedSharding, PartitionSpec))
out_sharding = canonicalize_sharding(out_sharding, '.add')
return scatter._scatter_update(
self.array, self.index, values, lax_slicing.scatter_add,
indices_are_sorted=indices_are_sorted, unique_indices=unique_indices,
mode=mode, out_sharding=out_sharding, # type: ignore
normalize_indices=wrap_negative_indices)
def subtract(self, values: ArrayLike, *,
indices_are_sorted: bool = False, unique_indices: bool = False,
mode: str | lax_slicing.GatherScatterMode | None = None,
wrap_negative_indices: bool = True) -> Array:
"""Pure equivalent of ``x[idx] -= y``.
Returns the value of ``x`` that would result from the NumPy-style
:mod:indexed assignment <numpy.doc.indexing>` ``x[idx] -= y``.
See :func:`jax.numpy.ndarray.at` for details.
"""
return scatter._scatter_update(self.array, self.index, values,
lax_slicing.scatter_sub,
indices_are_sorted=indices_are_sorted,
unique_indices=unique_indices, mode=mode,
normalize_indices=wrap_negative_indices)
def multiply(self, values: ArrayLike, *,
indices_are_sorted: bool = False, unique_indices: bool = False,
mode: str | lax_slicing.GatherScatterMode | None = None,
wrap_negative_indices: bool = True) -> Array:
"""Pure equivalent of ``x[idx] *= y``.
Returns the value of ``x`` that would result from the NumPy-style
:mod:indexed assignment <numpy.doc.indexing>` ``x[idx] *= y``.
See :func:`jax.numpy.ndarray.at` for details.
"""
return scatter._scatter_update(self.array, self.index, values,
lax_slicing.scatter_mul,
indices_are_sorted=indices_are_sorted,
unique_indices=unique_indices,
mode=mode, normalize_indices=wrap_negative_indices)
mul = multiply
def divide(self, values: ArrayLike, *,
indices_are_sorted: bool = False, unique_indices: bool = False,
mode: str | lax_slicing.GatherScatterMode | None = None,
wrap_negative_indices: bool = True) -> Array:
"""Pure equivalent of ``x[idx] /= y``.
Returns the value of ``x`` that would result from the NumPy-style
:mod:indexed assignment <numpy.doc.indexing>` ``x[idx] /= y``.
See :func:`jax.numpy.ndarray.at` for details.
"""
return ufuncs.divide(
self.array,
scatter._scatter_update(array_creation.ones_like(self.array), self.index, values,
lax_slicing.scatter_mul,
indices_are_sorted=indices_are_sorted,
unique_indices=unique_indices, mode=mode,
normalize_indices=wrap_negative_indices))
def power(self, values: ArrayLike, *,
indices_are_sorted: bool = False, unique_indices: bool = False,
mode: str | lax_slicing.GatherScatterMode | None = None,
wrap_negative_indices: bool = True) -> Array:
"""Pure equivalent of ``x[idx] **= y``.
Returns the value of ``x`` that would result from the NumPy-style
:mod:indexed assignment <numpy.doc.indexing>` ``x[idx] **= y``.
See :func:`jax.numpy.ndarray.at` for details.
"""
return ufuncs.power(
self.array,
scatter._scatter_update(array_creation.ones_like(self.array), self.index, values,
lax_slicing.scatter_mul,
indices_are_sorted=indices_are_sorted,
unique_indices=unique_indices, mode=mode,
normalize_indices=wrap_negative_indices))
def min(self, values: ArrayLike, *,
indices_are_sorted: bool = False, unique_indices: bool = False,
mode: str | lax_slicing.GatherScatterMode | None = None,
wrap_negative_indices: bool = True) -> Array:
"""Pure equivalent of ``x[idx] = minimum(x[idx], y)``.
Returns the value of ``x`` that would result from the NumPy-style
:mod:indexed assignment <numpy.doc.indexing>`
``x[idx] = minimum(x[idx], y)``.
See :func:`jax.numpy.ndarray.at` for details.
"""
return scatter._scatter_update(self.array, self.index, values,
lax_slicing.scatter_min,
indices_are_sorted=indices_are_sorted,
unique_indices=unique_indices, mode=mode,
normalize_indices=wrap_negative_indices)
def max(self, values: ArrayLike, *,
indices_are_sorted: bool = False, unique_indices: bool = False,
mode: str | lax_slicing.GatherScatterMode | None = None,
wrap_negative_indices: bool = True) -> Array:
"""Pure equivalent of ``x[idx] = maximum(x[idx], y)``.
Returns the value of ``x`` that would result from the NumPy-style
:mod:indexed assignment <numpy.doc.indexing>`
``x[idx] = maximum(x[idx], y)``.
See :func:`jax.numpy.ndarray.at` for details.
"""
return scatter._scatter_update(self.array, self.index, values,
lax_slicing.scatter_max,
indices_are_sorted=indices_are_sorted,
unique_indices=unique_indices, mode=mode,
normalize_indices=wrap_negative_indices)
_array_operators = {
"getitem": _getitem,
"setitem": _unimplemented_setitem,
"copy": _copy,
"deepcopy": _deepcopy,
"neg": lambda self: ufuncs.negative(self),
"pos": lambda self: ufuncs.positive(self),
"eq": _defer_to_unrecognized_arg("==", ufuncs.equal),
"ne": _defer_to_unrecognized_arg("!=", ufuncs.not_equal),
"lt": _defer_to_unrecognized_arg("<", ufuncs.less),
"le": _defer_to_unrecognized_arg("<=", ufuncs.less_equal),
"gt": _defer_to_unrecognized_arg(">", ufuncs.greater),
"ge": _defer_to_unrecognized_arg(">=", ufuncs.greater_equal),
"abs": lambda self: ufuncs.abs(self),
"add": _defer_to_unrecognized_arg("+", ufuncs.add),
"radd": _defer_to_unrecognized_arg("+", ufuncs.add, swap=True),
"sub": _defer_to_unrecognized_arg("-", ufuncs.subtract),
"rsub": _defer_to_unrecognized_arg("-", ufuncs.subtract, swap=True),
"mul": _defer_to_unrecognized_arg("*", ufuncs.multiply),
"rmul": _defer_to_unrecognized_arg("*", ufuncs.multiply, swap=True),
"truediv": _defer_to_unrecognized_arg("/", ufuncs.true_divide),
"rtruediv": _defer_to_unrecognized_arg("/", ufuncs.true_divide, swap=True),
"floordiv": _defer_to_unrecognized_arg("//", ufuncs.floor_divide),
"rfloordiv": _defer_to_unrecognized_arg("//", ufuncs.floor_divide, swap=True),
"divmod": _defer_to_unrecognized_arg("divmod", ufuncs.divmod),
"rdivmod": _defer_to_unrecognized_arg("divmod", ufuncs.divmod, swap=True),
"mod": _defer_to_unrecognized_arg("%", ufuncs.mod),
"rmod": _defer_to_unrecognized_arg("%", ufuncs.mod, swap=True),
"pow": _defer_to_unrecognized_arg("**", ufuncs.power),
"rpow": _defer_to_unrecognized_arg("**", ufuncs.power, swap=True),
"matmul": _defer_to_unrecognized_arg("@", tensor_contractions.matmul),
"rmatmul": _defer_to_unrecognized_arg("@", tensor_contractions.matmul, swap=True),
"and": _defer_to_unrecognized_arg("&", ufuncs.bitwise_and),
"rand": _defer_to_unrecognized_arg("&", ufuncs.bitwise_and, swap=True),
"or": _defer_to_unrecognized_arg("|", ufuncs.bitwise_or),
"ror": _defer_to_unrecognized_arg("|", ufuncs.bitwise_or, swap=True),
"xor": _defer_to_unrecognized_arg("^", ufuncs.bitwise_xor),
"rxor": _defer_to_unrecognized_arg("^", ufuncs.bitwise_xor, swap=True),
"invert": lambda self: ufuncs.bitwise_not(self),
"lshift": _defer_to_unrecognized_arg("<<", ufuncs.left_shift),
"rshift": _defer_to_unrecognized_arg(">>", ufuncs.right_shift),
"rlshift": _defer_to_unrecognized_arg("<<", ufuncs.left_shift, swap=True),
"rrshift": _defer_to_unrecognized_arg(">>", ufuncs.right_shift, swap=True),
"round": _operator_round,
}
_array_methods = {
"__array_namespace__": array_api_metadata.__array_namespace__,
"all": _all,
"any": _any,
"argmax": _argmax,
"argmin": _argmin,
"argpartition": _argpartition,
"argsort": _argsort,
"astype": _astype,
"choose": _choose,
"clip": _clip,
"compress": _compress,
"conj": _conj,
"conjugate": _conjugate,
"copy": _copy,
"cumprod": _cumprod,
"cumsum": _cumsum,
"diagonal": _diagonal,
"dot": _dot,
"flatten": _flatten,
"item": _item,
"max": _max,
"mean": _mean,
"min": _min,
"nonzero": _nonzero,
"prod": _prod,
"ptp": _ptp,
"ravel": _flatten,
"repeat": _repeat,
"reshape": _reshape,
"round": _round,
"searchsorted": _searchsorted,
"sort": _sort,
"squeeze": _squeeze,
"std": _std,
"sum": _sum,
"swapaxes": _swapaxes,
"take": _take,
"to_device": _to_device,
"trace": _trace,
"transpose": _transpose,
"var": _var,
"view": _view,
# Methods exposed in order to avoid circular imports
"_split": lax_numpy.split, # used in jacfwd/jacrev
"_multi_slice": _multi_slice, # used in pxla for sharding
}
_impl_only_array_methods = {
"_chunk_iter": _chunk_iter,
"_unstack": _unstack,
}
_array_properties = {
"flat": _notimplemented_flat,
"T": _transpose_property,
"mT": _matrix_transpose_property,
"real": _real_property,
"imag": _imag_property,
"nbytes": _nbytes_property,
"itemsize": _itemsize_property,
"at": _IndexUpdateHelper,
}
def _set_shaped_array_attributes(shaped_array):
# Set up operator, method, and property forwarding on Tracer instances
# containing
# ShapedArray avals by following the forwarding conventions for Tracer.
# Forward operators using a single-underscore-prefix naming convention:
for operator_name, function in _array_operators.items():
setattr(shaped_array, f"_{operator_name}", staticmethod(function))
# Forward methods and properties using core.{aval_method, aval_property}:
for method_name, method in _array_methods.items():
setattr(shaped_array, method_name, core.aval_method(method))
for prop_name, prop in _array_properties.items():
setattr(shaped_array, prop_name, core.aval_property(prop))
setattr(shaped_array, "_array_module", staticmethod(__array_module__))
def _forward_operator_to_aval(name):
def op(self, *args):
return getattr(self.aval, f"_{name}")(self, *args)
return op
def _forward_method_to_aval(name):
def meth(self, *args, **kwargs):
__tracebackhide__ = True
return getattr(self.aval, name).fun(self, *args, **kwargs)
return meth
def _forward_property_to_aval(name):
@property
def prop(self):
return getattr(self.aval, name).fget(self)
return prop
def _set_tracer_aval_forwarding(tracer, exclude=()):
for operator_name in _array_operators:
if operator_name not in exclude:
setattr(tracer, f"__{operator_name}__", _forward_operator_to_aval(operator_name))
for method_name in _array_methods:
if method_name not in exclude:
setattr(tracer, method_name, _forward_method_to_aval(method_name))
for prop_name in _array_properties:
if prop_name not in exclude:
setattr(tracer, prop_name, _forward_property_to_aval(prop_name))
def _set_array_base_attributes(array_impl, include=None, exclude=None):
# Forward operators, methods, and properties on Array to lax_numpy
# functions (with no Tracers involved; this forwarding is direct)
def maybe_setattr(attr_name, target):
if exclude is not None and attr_name in exclude:
return
if not include or attr_name in include:
setattr(array_impl, attr_name, target)
for operator_name, function in _array_operators.items():
maybe_setattr(f"__{operator_name}__", function)
for method_name, method in _array_methods.items():
maybe_setattr(method_name, method)
for prop_name, prop in _array_properties.items():
maybe_setattr(prop_name, property(prop))
for name, func in _impl_only_array_methods.items():
setattr(array_impl, name, func)
def _set_array_attributes(array_impl):
setattr(array_impl, "__array_module__", __array_module__)
def _make_abstract_method(name, func):
@abc.abstractmethod
@wraps(func)
def method(*args, **kwargs):
raise NotImplementedError(f"Cannot call abstract method {name}")
return method
def _set_array_abstract_methods(basearray):
for operator_name, function in _array_operators.items():
setattr(basearray, f"__{operator_name}__",
_make_abstract_method(f"__{operator_name}__", function))
for method_name, method in _array_methods.items():
setattr(basearray, method_name,
_make_abstract_method(method_name, method))
for prop_name, prop in _array_properties.items():
setattr(basearray, prop_name,
property(_make_abstract_method(prop_name, prop)))
def register_jax_array_methods():
"""Call this function once to register methods of JAX arrays"""
_set_shaped_array_attributes(core.ShapedArray)
_set_shaped_array_attributes(core.DShapedArray)
_set_array_base_attributes(ArrayImpl, exclude={'__getitem__'})
_set_tracer_aval_forwarding(core.Tracer, exclude={*_impl_only_array_methods, "at"})
_set_array_attributes(ArrayImpl)
_set_array_abstract_methods(Array)
| _IndexUpdateRef |
python | scipy__scipy | scipy/sparse/tests/test_64bit.py | {
"start": 5304,
"end": 6494
} | class ____(RunAll64Bit):
# inheritance of pytest test classes does not separate marks for subclasses.
# So we define these functions in both Array and Matrix versions.
@pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
def test_resiliency_limit_10(self, cls, method_name):
self._check_resiliency(cls, method_name, maxval_limit=10)
@pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
def test_resiliency_all_32(self, cls, method_name):
self._check_resiliency(cls, method_name, fixed_dtype=np.int32)
@pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
def test_resiliency_all_64(self, cls, method_name):
self._check_resiliency(cls, method_name, fixed_dtype=np.int64)
@pytest.mark.fail_slow(2)
@pytest.mark.parametrize('cls,method_name', cases_64bit("spmatrix"))
def test_resiliency_random(self, cls, method_name):
# Resiliency check that sparse deals with varying index data types.
self._check_resiliency(cls, method_name)
# Extra: LIL and DOK classes. no direct get_index_dtype, but convert to classes that do
@pytest.mark.xslow
| Test64BitMatrixSameAsArray |
python | PyCQA__pylint | tests/functional/r/raising/raising_non_exception.py | {
"start": 282,
"end": 378
} | class ____:
"""Not an actual exception."""
raise Exc from missing # [raising-non-exception]
| Exc |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/manyvariants/package.py | {
"start": 217,
"end": 1022
} | class ____(Package):
"""
A package with 4 different variants of different arities to test the
`match_variants` argument to `can_splice`
"""
homepage = "https://www.test.com"
has_code = False
version("2.0.1")
version("2.0.0")
version("1.0.1")
version("1.0.0")
variant("a", default=True)
variant("b", default=False)
variant("c", values=("v1", "v2", "v3"), multi=False, default="v1")
variant("d", values=("v1", "v2", "v3"), multi=False, default="v1")
can_splice("manyvariants@1.0.0", when="@1.0.1", match_variants="*")
can_splice("manyvariants@2.0.0+a~b", when="@2.0.1~a+b", match_variants=["c", "d"])
can_splice("manyvariants@2.0.0 c=v1 d=v1", when="@2.0.1+a+b")
def install(self, spec, prefix):
touch(prefix.bar)
| Manyvariants |
python | pandas-dev__pandas | pandas/tests/window/test_rolling.py | {
"start": 61725,
"end": 62205
} | class ____(BaseIndexer):
def __init__(self, start, end):
self._start = start
self._end = end
super().__init__()
def get_window_bounds(
self, num_values=None, min_periods=None, center=None, closed=None, step=None
):
if num_values is None:
num_values = len(self._start)
start = np.clip(self._start, 0, num_values)
end = np.clip(self._end, 0, num_values)
return start, end
| PrescribedWindowIndexer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/hybrid.py | {
"start": 62279,
"end": 64567
} | class ____(Comparator[_T]):
def __init__(
self,
cls: Type[Any],
expression: Union[_HasClauseElement[_T], SQLColumnExpression[_T]],
hybrid: hybrid_property[_T],
):
self.cls = cls
self.expression = expression
self.hybrid = hybrid
def __getattr__(self, key: str) -> Any:
return getattr(self.expression, key)
@util.ro_non_memoized_property
def info(self) -> _InfoType:
return self.hybrid.info
def _bulk_update_tuples(
self,
value: Any,
) -> Sequence[Tuple[_DMLColumnArgument, Any]]:
if isinstance(self.expression, attributes.QueryableAttribute):
return self.expression._bulk_update_tuples(value)
elif self.hybrid.update_expr is not None:
return self.hybrid.update_expr(self.cls, value)
else:
return [(self.expression, value)]
def _bulk_dml_setter(self, key: str) -> Optional[Callable[..., Any]]:
"""return a callable that will process a bulk INSERT value"""
meth = None
def prop(mapping: MutableMapping[str, Any]) -> None:
nonlocal meth
value = mapping[key]
if meth is None:
if self.hybrid.bulk_dml_setter is None:
raise exc.InvalidRequestError(
"Can't evaluate bulk DML statement; please "
"supply a bulk_dml decorated function"
)
meth = self.hybrid.bulk_dml_setter
meth(self.cls, mapping, value)
return prop
@util.non_memoized_property
def property(self) -> MapperProperty[_T]:
# this accessor is not normally used, however is accessed by things
# like ORM synonyms if the hybrid is used in this context; the
# .property attribute is not necessarily accessible
return self.expression.property # type: ignore
def operate(
self, op: OperatorType, *other: Any, **kwargs: Any
) -> ColumnElement[Any]:
return op(self.expression, *other, **kwargs)
def reverse_operate(
self, op: OperatorType, other: Any, **kwargs: Any
) -> ColumnElement[Any]:
return op(other, self.expression, **kwargs) # type: ignore
| ExprComparator |
python | pydata__xarray | xarray/core/coordinates.py | {
"start": 1247,
"end": 6049
} | class ____(Mapping[Hashable, "T_DataArray"]):
_data: DataWithCoords
__slots__ = ("_data",)
def __getitem__(self, key: Hashable) -> T_DataArray:
raise NotImplementedError()
@property
def _names(self) -> set[Hashable]:
raise NotImplementedError()
@property
def dims(self) -> Frozen[Hashable, int] | tuple[Hashable, ...]:
raise NotImplementedError()
@property
def dtypes(self) -> Frozen[Hashable, np.dtype]:
raise NotImplementedError()
@property
def indexes(self) -> Indexes[pd.Index]:
"""Mapping of pandas.Index objects used for label based indexing.
Raises an error if this Coordinates object has indexes that cannot
be coerced to pandas.Index objects.
See Also
--------
Coordinates.xindexes
"""
return self._data.indexes
@property
def xindexes(self) -> Indexes[Index]:
"""Mapping of :py:class:`~xarray.indexes.Index` objects
used for label based indexing.
"""
return self._data.xindexes
@property
def variables(self):
raise NotImplementedError()
def _update_coords(self, coords, indexes):
raise NotImplementedError()
def _drop_coords(self, coord_names):
raise NotImplementedError()
def __iter__(self) -> Iterator[Hashable]:
# needs to be in the same order as the dataset variables
for k in self.variables:
if k in self._names:
yield k
def __len__(self) -> int:
return len(self._names)
def __contains__(self, key: Hashable) -> bool:
return key in self._names
def __repr__(self) -> str:
return formatting.coords_repr(self)
def to_dataset(self) -> Dataset:
raise NotImplementedError()
def to_index(self, ordered_dims: Sequence[Hashable] | None = None) -> pd.Index:
"""Convert all index coordinates into a :py:class:`pandas.Index`.
Parameters
----------
ordered_dims : sequence of hashable, optional
Possibly reordered version of this object's dimensions indicating
the order in which dimensions should appear on the result.
Returns
-------
pandas.Index
Index subclass corresponding to the outer-product of all dimension
coordinates. This will be a MultiIndex if this object is has more
than more dimension.
"""
if ordered_dims is None:
ordered_dims = list(self.dims)
elif set(ordered_dims) != set(self.dims):
raise ValueError(
"ordered_dims must match dims, but does not: "
f"{ordered_dims} vs {self.dims}"
)
if len(ordered_dims) == 0:
raise ValueError("no valid index for a 0-dimensional object")
elif len(ordered_dims) == 1:
(dim,) = ordered_dims
return self._data.get_index(dim)
else:
indexes = [self._data.get_index(k) for k in ordered_dims]
# compute the sizes of the repeat and tile for the cartesian product
# (taken from pandas.core.reshape.util)
index_lengths = np.fromiter(
(len(index) for index in indexes), dtype=np.intp
)
cumprod_lengths = np.cumprod(index_lengths)
if cumprod_lengths[-1] == 0:
# if any factor is empty, the cartesian product is empty
repeat_counts = np.zeros_like(cumprod_lengths)
else:
# sizes of the repeats
repeat_counts = cumprod_lengths[-1] / cumprod_lengths
# sizes of the tiles
tile_counts = np.roll(cumprod_lengths, 1)
tile_counts[0] = 1
# loop over the indexes
# for each MultiIndex or Index compute the cartesian product of the codes
code_list = []
level_list = []
names = []
for i, index in enumerate(indexes):
if isinstance(index, pd.MultiIndex):
codes, levels = index.codes, index.levels
else:
code, level = pd.factorize(index)
codes = [code]
levels = [level]
# compute the cartesian product
code_list += [
np.tile(np.repeat(code, repeat_counts[i]), tile_counts[i])
for code in codes
]
level_list += levels
names += index.names
return pd.MultiIndex(
levels=level_list, # type: ignore[arg-type,unused-ignore]
codes=[list(c) for c in code_list],
names=names,
)
| AbstractCoordinates |
python | ZoranPandovski__al-go-rithms | data_structures/b_tree/Python/binaryTree.py | {
"start": 108,
"end": 226
} | class ____(object):
def __init__(self,data=None):
self.val = data
self.left = self.right = None
| Node |
python | google__flatbuffers | grpc/examples/python/greeter/server.py | {
"start": 596,
"end": 1554
} | class ____(greeter_grpc_fb.GreeterServicer):
def __init__(self):
self.greetings = ["Hi", "Hallo", "Ciao"]
def SayHello(self, request, context):
r = HelloRequest.HelloRequest().GetRootAs(request, 0)
reply = "Unknown"
if r.Name():
reply = r.Name()
return build_reply("welcome " + reply.decode("UTF-8"))
def SayManyHellos(self, request, context):
r = HelloRequest.HelloRequest().GetRootAs(request, 0)
reply = "Unknown"
if r.Name():
reply = r.Name()
for greeting in self.greetings:
print(type(reply))
yield build_reply(greeting + " " + reply.decode("UTF-8"))
def serve():
args = parser.parse_args()
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
greeter_grpc_fb.add_GreeterServicer_to_server(GreeterServicer(), server)
server.add_insecure_port("[::]:" + args.port)
server.start()
server.wait_for_termination()
if __name__ == "__main__":
serve()
| GreeterServicer |
python | pandas-dev__pandas | asv_bench/benchmarks/frame_methods.py | {
"start": 7109,
"end": 7608
} | class ____:
params = [["dict", "list", "series", "split", "records", "index"]]
param_names = ["orient"]
def setup(self, orient):
data = np.random.randint(0, 1000, size=(10000, 4))
self.int_df = DataFrame(data)
self.datetimelike_df = self.int_df.astype("timedelta64[ns]")
def time_to_dict_ints(self, orient):
self.int_df.to_dict(orient=orient)
def time_to_dict_datetimelike(self, orient):
self.datetimelike_df.to_dict(orient=orient)
| ToDict |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-zhipuai/llama_index/embeddings/zhipuai/base.py | {
"start": 284,
"end": 4007
} | class ____(BaseEmbedding):
"""
ZhipuAI LLM.
Visit https://open.bigmodel.cn to get more information about ZhipuAI.
Examples:
`pip install llama-index-embeddings-zhipuai`
```python
from llama_index.embeddings.zhipuai import ZhipuAIEmbedding
embedding = ZhipuAIEmbedding(model="embedding-2", api_key="YOUR API KEY")
response = embedding.get_general_text_embedding("who are you?")
print(response)
```
"""
model: str = Field(description="The ZhipuAI model to use.")
api_key: Optional[str] = Field(
default=None,
description="The API key to use for the ZhipuAI API.",
)
dimensions: Optional[int] = Field(
default=1024,
description=(
"The number of dimensions the resulting output embeddings should have. "
"Only supported in embedding-3 and later models. embedding-2 is fixed at 1024."
),
)
timeout: Optional[float] = Field(
default=None,
description="The timeout to use for the ZhipuAI API.",
)
_client: Optional[ZhipuAIClient] = PrivateAttr()
def __init__(
self,
model: str,
api_key: str,
dimensions: Optional[int] = 1024,
timeout: Optional[int] = None,
callback_manager: Optional[CallbackManager] = None,
**kwargs: Any,
) -> None:
super().__init__(
model=model,
dimensions=dimensions,
timeout=timeout,
callback_manager=callback_manager,
**kwargs,
)
self._client = ZhipuAIClient(api_key=api_key)
@classmethod
def class_name(cls) -> str:
return "ZhipuAIEmbedding"
def _get_query_embedding(self, query: str) -> List[float]:
"""Get query embedding."""
return self.get_general_text_embedding(query)
async def _aget_query_embedding(self, query: str) -> List[float]:
"""The asynchronous version of _get_query_embedding."""
return await self.aget_general_text_embedding(query)
def _get_text_embedding(self, text: str) -> List[float]:
"""Get text embedding."""
return self.get_general_text_embedding(text)
async def _aget_text_embedding(self, text: str) -> List[float]:
"""Asynchronously get text embedding."""
return await self.aget_general_text_embedding(text)
def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Get text embeddings."""
embeddings_list: List[List[float]] = []
for text in texts:
embeddings = self.get_general_text_embedding(text)
embeddings_list.append(embeddings)
return embeddings_list
async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Asynchronously get text embeddings."""
return await asyncio.gather(
*[self.aget_general_text_embedding(text) for text in texts]
)
def get_general_text_embedding(self, text: str) -> List[float]:
"""Get ZhipuAI embeddings."""
response = self._client.embeddings.create(
model=self.model,
input=text,
dimensions=self.dimensions,
timeout=self.timeout,
)
return response.data[0].embedding
async def aget_general_text_embedding(self, text: str) -> List[float]:
"""Asynchronously get ZhipuAI embeddings."""
response = await asyncio.to_thread(
self._client.embeddings.create,
model=self.model,
input=text,
dimensions=self.dimensions,
timeout=self.timeout,
)
return response.data[0].embedding
| ZhipuAIEmbedding |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/subclass_parametrization.py | {
"start": 638,
"end": 4124
} | class ____(torch.nn.Module):
def forward(self, *tensors) -> torch.Tensor: # type: ignore[no-untyped-def]
todo: list[torch.Tensor] = list(tensors)
def _unwrap_tensor_subclasses(subclass_meta, tensors, offset): # type: ignore[no-untyped-def]
if subclass_meta is None:
return tensors[offset], offset + 1
inner_tensors = {}
for attr, meta in subclass_meta.attrs.items():
built_tensor, offset = _unwrap_tensor_subclasses(meta, tensors, offset)
inner_tensors[attr] = built_tensor
rebuilt = subclass_meta.class_type.__tensor_unflatten__(
inner_tensors,
subclass_meta.metadata,
subclass_meta.outer_size,
subclass_meta.outer_stride,
)
return rebuilt, offset
return _unwrap_tensor_subclasses(self.subclass_meta, todo, 0)[0]
def right_inverse(self, tensor: torch.Tensor) -> list[torch.Tensor]:
assert type(tensor) is not torch.Tensor
plain_tensors: list[torch.Tensor] = []
def _create_subclass_meta(tensor, idx, plain_tensor_container): # type: ignore[no-untyped-def]
if type(tensor) is torch.Tensor:
plain_tensor_container.append(tensor)
return None, idx + 1
inner_tensors_attrnames, metadata = tensor.__tensor_flatten__() # type: ignore[attr-defined]
new_idx = idx
attr_to_meta = {}
for attr in inner_tensors_attrnames:
val = getattr(tensor, attr)
subclass_meta, new_idx = _create_subclass_meta(
val, new_idx, plain_tensor_container
)
attr_to_meta[attr] = subclass_meta
return (
SubclassCreationMeta(
start_idx=idx,
num_tensors=new_idx - idx,
class_type=type(tensor),
attrs=attr_to_meta,
metadata=metadata,
outer_size=tensor.size(),
outer_stride=tensor.stride(),
),
new_idx,
)
self.subclass_meta = _create_subclass_meta(tensor, 0, plain_tensors)[0]
return plain_tensors
def unwrap_tensor_subclass_parameters(module: torch.nn.Module) -> torch.nn.Module:
"""
Model transformation that replaces all the parameters that are subclasses to plain tensors.
This reduces runtime overhead of flattening/unflattening the parameters.
This transformation adds parametrization with `torch.nn.utils.parametrize`.
The FQNs of the subclass parameters will be changed and state_dict will become incompatible with the original model.
E.g.
Original model state_dict: {"p1": torch.testing._internal.TwoTensor}
becomes: {"parametrizations.p2.original0": torch.Tensor, "parametrizations.p2.original1": torch.Tensor}
"""
for name, tensor in itertools.chain(
list(module.named_parameters(recurse=False)),
# pyrefly: ignore [no-matching-overload]
list(module.named_buffers(recurse=False)),
):
if is_traceable_wrapper_subclass(tensor):
torch.nn.utils.parametrize.register_parametrization(
module, name, UnwrapTensorSubclass()
)
for child in module.children():
unwrap_tensor_subclass_parameters(child)
return module
| UnwrapTensorSubclass |
python | pytorch__pytorch | torch/fx/passes/shape_prop.py | {
"start": 3294,
"end": 8326
} | class ____(torch.fx.Interpreter):
"""
Execute an FX graph Node-by-Node and
record the shape and type of the result
into the corresponding node.
Example:
In this example, we record the shape
and data type of a module given
an example input ``torch.randn(50, D_in)``.
We print the name, shape and dtype of each node.
class TwoLayerNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
super().__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def forward(self, x):
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred
N, D_in, H, D_out = 64, 1000, 100, 10
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)
model = TwoLayerNet(D_in, H, D_out)
gm = torch.fx.symbolic_trace(model)
sample_input = torch.randn(50, D_in)
ShapeProp(gm).propagate(sample_input)
for node in gm.graph.nodes:
print(node.name, node.meta['tensor_meta'].dtype,
node.meta['tensor_meta'].shape)
The output of this code is:
x torch.float32 torch.Size([50, 1000])
linear1 torch.float32 torch.Size([50, 100])
clamp_1 torch.float32 torch.Size([50, 100])
linear2 torch.float32 torch.Size([50, 10])
output torch.float32 torch.Size([50, 10])
Args:
module (GraphModule): The module to be executed
fake_mode (FakeTensorMode): A fake mode for copying the gm
"""
def __init__(self, gm, fake_mode=None):
super().__init__(gm)
if fake_mode is None:
fake_mode = detect_fake_mode()
if fake_mode is not None:
from torch._dynamo.utils import deepcopy_to_fake_tensor
# Note:
# We need fake execution cause the inputs are fake, however, we cannot fakify the module
# - because we need to write to the tensor_meta of the real module. So we fakify to
# produce a result (L131 below), to extract tensor meta, and then keep going.
#
# If we were to fakify, we would write to the wrong node, and then downstream fusion
# would be missing the tensor_meta.
#
# See torch/_inductor/overrides.py for where this is called upstream of fusion.
self.fake_module = deepcopy_to_fake_tensor(self.module, fake_mode)
self.fake_mode = fake_mode
else:
self.fake_module = None
self.fake_mode = None
self.real_module = self.module
def run_node(self, n: Node) -> Any:
from torch.fx.experimental.symbolic_shapes import (
compute_unbacked_bindings,
rebind_unbacked,
)
try:
if self.fake_module is not None:
# Hacky swap. Alternatively, we could do this with overriding
# call_module and get_attr.
self.module = self.fake_module
try:
if self.fake_mode is not None:
with self.fake_mode, enable_python_dispatcher():
result = super().run_node(n)
rebind_unbacked(self.fake_mode.shape_env, n, result)
else:
result = super().run_node(n)
finally:
self.module = self.real_module
except Exception as e:
traceback.print_exc()
raise RuntimeError(
f"ShapeProp error for: node={n.format_node()} with meta={n.meta}"
) from e
found_tensor = False
def extract_tensor_meta(obj):
if isinstance(obj, torch.Tensor):
nonlocal found_tensor
found_tensor = True
return _extract_tensor_metadata(obj)
else:
return obj
meta = map_aggregate(result, extract_tensor_meta)
if found_tensor:
n.meta["tensor_meta"] = meta
if self.fake_mode:
if (shape_env := self.fake_mode.shape_env) and (
symbol_to_path := compute_unbacked_bindings(shape_env, result)
):
n.meta["unbacked_bindings"] = symbol_to_path
n.meta["type"] = type(result)
return result
def propagate(self, *args):
"""
Run `module` via interpretation and return the result and
record the shape and type of each node.
Args:
*args (Tensor): the sample input.
Returns:
Any: The value returned from executing the Module
"""
if self.fake_mode is not None:
fake_args = [
self.fake_mode.from_tensor(t) if isinstance(t, torch.Tensor) else t
for t in args
]
else:
fake_args = args
return super().run(*fake_args)
| ShapeProp |
python | doocs__leetcode | solution/0100-0199/0106.Construct Binary Tree from Inorder and Postorder Traversal/Solution.py | {
"start": 192,
"end": 682
} | class ____:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
def dfs(i: int, j: int, n: int) -> Optional[TreeNode]:
if n <= 0:
return None
v = postorder[j + n - 1]
k = d[v]
l = dfs(i, j, k - i)
r = dfs(k + 1, j + k - i, n - k + i - 1)
return TreeNode(v, l, r)
d = {v: i for i, v in enumerate(inorder)}
return dfs(0, 0, len(inorder))
| Solution |
python | google__jax | jax/experimental/pallas/ops/gpu/hopper_mixed_type_matmul_mgpu.py | {
"start": 1218,
"end": 12605
} | class ____:
tile_m: int
tile_n: int
tile_k: int
max_concurrent_steps: int
epi_tile_n: int | None = 64 # This needs to be lowered for for small N.
epi_tile_m: int | None = 64
grid_minor_dim: MatmulDimension = MatmulDimension.N
grid_tile_width: int = 1
wg_dimension: MatmulDimension = MatmulDimension.N
cluster_dimension: None | MatmulDimension = None
def mixed_matmul_kernel(
a: jax.Array, b: jax.Array, *, out_dtype: jnp.dtype, config: TuningConfig
) -> jax.Array:
"""Mixed-type matrix multiplication kernel for Hopper GPUs.
Specifically, this kernel implements the function
(a.as_dtype(b.dtype) @ b).astype(out_dtype).
"""
if a.dtype == b.dtype:
raise ValueError(
f"Mixed matmul LHS and RHS have the same dtype {a.dtype}. For such "
"matrix multiplications, use the `hopper_matmul_mgpu` kernel instead."
)
match (a.dtype, b.dtype):
case (jnp.int8, jnp.bfloat16):
pass
case (jnp.int8, jnp.float16):
pass
case _, _:
# We do support more combinations, but we haven't benchmarked them
# yet---so we raise for the time being.
raise NotImplementedError(
f"Unbenchmarked dtype combination: {a.dtype=} and {b.dtype=}"
)
m, k = a.shape
k2, n = b.shape
if k != k2:
raise ValueError(
f"Matmul LHS and RHS have incompatible shapes {a.shape} vs {b.shape}"
)
tile_m, tile_n, tile_k = config.tile_m, config.tile_n, config.tile_k
epi_tile_n = config.epi_tile_n or tile_n
epi_tile_m = config.epi_tile_m or tile_m
if tile_n % epi_tile_n != 0:
raise ValueError(f"{tile_n=} must be divisible by {epi_tile_n=}")
if tile_m % epi_tile_m != 0:
raise ValueError(f"{tile_m=} must be divisible by {epi_tile_m=}")
a_bits = dtypes.itemsize_bits(a.dtype)
b_bits = dtypes.itemsize_bits(b.dtype)
out_bits = dtypes.itemsize_bits(out_dtype)
a_swizzle = plgpu.find_swizzle(tile_k * a_bits, "lhs")
b_swizzle = plgpu.find_swizzle(tile_n * b_bits, "rhs")
out_swizzle = plgpu.find_swizzle(epi_tile_n * out_bits, "out")
a_transforms = (
plgpu.TilingTransform((8, a_swizzle * 8 // a_bits)),
plgpu.SwizzleTransform(a_swizzle),
)
b_transforms = (
plgpu.TilingTransform((8, b_swizzle * 8 // b_bits)),
plgpu.SwizzleTransform(b_swizzle),
)
out_transforms = (
plgpu.TilingTransform((8, out_swizzle * 8 // out_bits)),
plgpu.SwizzleTransform(out_swizzle),
)
max_concurrent_steps = config.max_concurrent_steps
cta_tile_m = tile_m * (1 + (config.wg_dimension == MatmulDimension.M))
cta_tile_n = tile_n * (1 + (config.wg_dimension == MatmulDimension.N))
cluster_tile_m = cta_tile_m * (1 + (config.cluster_dimension == MatmulDimension.M))
cluster_tile_n = cta_tile_n * (1 + (config.cluster_dimension == MatmulDimension.N))
if m % cluster_tile_m != 0:
raise ValueError(f"{m=} must be divisible by {cluster_tile_m} for the given config")
if n % cluster_tile_n != 0:
raise ValueError(f"{n=} must be divisible by {cluster_tile_n} for the given config")
if k % tile_k != 0:
raise ValueError(f"{k=} must be divisible by {tile_k=}")
m_iters = m // cluster_tile_m
n_iters = n // cluster_tile_n
k_iters = k // tile_k
def kernel(a_gmem, b_gmem, out_gmem, out_smem):
def get_pipeline(pipeline_body, compute_context):
return plgpu.emit_pipeline_warp_specialized(
pipeline_body,
grid=(k_iters,),
memory_registers=40,
in_specs=[
plgpu.BlockSpec(
(cta_tile_m, tile_k),
lambda k: (0, k),
transforms=a_transforms,
memory_space=plgpu.SMEM,
collective_axes=("cluster",)
if config.cluster_dimension == MatmulDimension.N
else (),
),
plgpu.BlockSpec(
(tile_k, cta_tile_n),
lambda k: (k, 0),
transforms=b_transforms,
memory_space=plgpu.SMEM,
collective_axes=("cluster",)
if config.cluster_dimension == MatmulDimension.M
else (),
),
],
wg_axis="wg",
num_compute_wgs=2,
max_concurrent_steps=max_concurrent_steps,
compute_context=compute_context,
)
# Functions don't influence the allocations necessary to run the pipeline.
ignore = lambda *_, **__: None
@functools.partial(
pl.run_scoped,
pipeline_allocs=get_pipeline(ignore, ignore).get_allocations(a_gmem, b_gmem),
collective_axes="wg",
)
def _pipeline_scope(pipeline_allocs):
wg_idx = lax.axis_index("wg")
cta_idx = lax.axis_index("cluster")
@plgpu.nd_loop((m_iters * n_iters,), collective_axes="cluster_grid")
def _mn_loop(loop_info: plgpu.NDLoopInfo):
(lin_idx,) = loop_info.index
m_cluster_idx, n_cluster_idx = plgpu.planar_snake(
lin_idx,
(m_iters, n_iters),
config.grid_minor_dim,
config.grid_tile_width,
)
m_idx = m_cluster_idx
n_idx = n_cluster_idx
if config.cluster_dimension == MatmulDimension.M:
m_idx = m_cluster_idx * 2 + cta_idx
elif config.cluster_dimension == MatmulDimension.N:
n_idx = n_cluster_idx * 2 + cta_idx
cta_m_slice = pl.ds(m_idx * cta_tile_m, cta_tile_m)
cta_n_slice = pl.ds(n_idx * cta_tile_n, cta_tile_n)
if config.wg_dimension == MatmulDimension.M:
wg_m_slice = pl.ds(wg_idx * tile_m, tile_m)
wg_n_slice = slice(None)
else:
wg_m_slice = slice(None)
wg_n_slice = pl.ds(wg_idx * tile_n, tile_n) # type: ignore
def compute_context(eval_pipeline):
@functools.partial(
pl.run_scoped, acc_ref=plgpu.ACC((tile_m, tile_n), jnp.float32)
)
def _acc_scope(acc_ref):
eval_pipeline(acc_ref)
acc = acc_ref[...].astype(out_dtype)
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
for epi_mi in range(tile_m // epi_tile_m):
for epi_ni in range(tile_n // epi_tile_n):
epi_m_slice = slice(epi_mi * epi_tile_m, (epi_mi + 1) * epi_tile_m)
epi_n_slice = slice(epi_ni * epi_tile_n, (epi_ni + 1) * epi_tile_n)
slot = (epi_mi * (tile_n // epi_tile_n) + epi_ni) % 2
plgpu.wait_smem_to_gmem(1, wait_read_only=True)
out_smem[wg_idx, slot] = acc[epi_m_slice, epi_n_slice]
plgpu.commit_smem()
plgpu.copy_smem_to_gmem(
out_smem.at[wg_idx, slot],
out_gmem.at[cta_m_slice, cta_n_slice]
.at[wg_m_slice, wg_n_slice]
.at[epi_m_slice, epi_n_slice],
)
def mma_body(_, a_smem, b_smem, acc_ref):
with jax.named_scope("smem_load"):
a_reg = a_smem[wg_m_slice]
with jax.named_scope("dequant"):
a_reg = a_reg.astype(b.dtype)
with jax.named_scope("wgmma"):
plgpu.wgmma(acc_ref, a_reg, b_smem.at[:, wg_n_slice])
with jax.named_scope("wgmma_wait"):
plgpu.wgmma_wait(0)
return acc_ref
get_pipeline(mma_body, compute_context)(
a_gmem.at[cta_m_slice, :],
b_gmem.at[:, cta_n_slice],
allocations=pipeline_allocs,
)
# Await all transfers before we exit.
plgpu.wait_smem_to_gmem(0, wait_read_only=True)
# We don't need multiple slots if there's only one epilogue tile.
num_out_slots = min(2, (tile_m * tile_n) // (epi_tile_m * epi_tile_n))
num_sms = backend.get_default_device().core_count
cluster_size = 1 + (config.cluster_dimension is not None)
f = plgpu.kernel(
kernel,
out_shape=jax.ShapeDtypeStruct((m, n), out_dtype),
grid=(num_sms // cluster_size,),
grid_names=("cluster_grid",),
cluster=(cluster_size,),
cluster_names=("cluster",),
num_threads=3,
thread_name="wg",
scratch_shapes=dict(
out_smem=plgpu.SMEM(
(2, num_out_slots, epi_tile_m, epi_tile_n),
out_dtype,
transforms=out_transforms,
)
),
)
return f(a, b)
def reference(
a: jax.Array, b: jax.Array, *, out_dtype: jnp.dtype
) -> jax.Array:
"""Reference implementation of a mixed-type matrix multiplication."""
return jax.numpy.dot(a, b, preferred_element_type=jnp.float32).astype(
out_dtype
)
def main(_) -> None:
problem_it = [(4096, 8192, 4096)]
for M, N, K in problem_it:
print(f"==== {M=} {N=} {K=} ====")
matmul_flops = 2 * M * N * K
peak_flops = 990e12 # f16 TensorCore peak = 990 TFLOPS
a = jax.random.randint(
jax.random.key(0), minval=-128, maxval=127, shape=(M, K), dtype=jnp.int8
)
b = jax.random.uniform(jax.random.key(1), (K, N), jnp.bfloat16)
ref = reference(a, b, out_dtype=jnp.bfloat16)
tuning_it = itertools.product(
(64, 128, 256,), # tile_m
(64, 128), # tile_n
(64, 128), # tile_k
(4,), # max_concurrent_steps
(True,), # Tiled epilogue
(MatmulDimension.M, MatmulDimension.N), # grid_minor_dim
(4, 8, 16), # grid_tile_width
MatmulDimension, # wg_dimension
# Consider adding MatmulDimension here to try out collective TMA kernels
(None,) # cluster_dimension
)
best_util = 0.0
best_runtime = float("inf")
for tile_m, tile_n, tile_k, max_concurrent_steps, tiled_epilogue, grid_minor_dim, grid_tile_width, wg_dimension, cluster_dimension in tuning_it:
config = TuningConfig(
tile_m=tile_m,
tile_n=tile_n,
tile_k=tile_k,
max_concurrent_steps=max_concurrent_steps,
epi_tile_n=64 if tiled_epilogue else None,
epi_tile_m=64 if tiled_epilogue else None,
grid_minor_dim=grid_minor_dim,
grid_tile_width=grid_tile_width,
wg_dimension=wg_dimension,
cluster_dimension=cluster_dimension,
)
try:
out, runtimes_ms = profiler.measure(
functools.partial(
mixed_matmul_kernel, out_dtype=jnp.bfloat16, config=config
),
iterations=10,
)(a, b)
assert runtimes_ms is not None
runtime_ms = statistics.median(runtimes_ms)
except ValueError as e:
if "exceeds available shared memory" in e.args[0]: # Ignore SMEM OOMs.
continue
raise
np.testing.assert_allclose(out, ref)
runtime_us = runtime_ms * 1e3 # type: ignore
optimal_time = matmul_flops / peak_flops * 1e6 # us
achieved_tc_util = optimal_time / runtime_us * 100
if achieved_tc_util > best_util:
best_runtime = runtime_us
best_util = achieved_tc_util
print(
f"{tile_m=} {tile_n=} {tile_k=} {max_concurrent_steps=} {tiled_epilogue=} {grid_minor_dim=} {grid_tile_width=} {wg_dimension=} {cluster_dimension=}:"
f" {runtime_us:<7.1f}us = {achieved_tc_util:4.1f}% TC utilization"
)
print(f"\tBest: {best_runtime:<7.1f}us = {best_util:4.1f}% TC utilization")
if __name__ == "__main__":
from absl import app
jax.config.config_with_absl()
app.run(main)
| TuningConfig |
python | walkccc__LeetCode | solutions/3470. Permutations IV/3470.py | {
"start": 0,
"end": 742
} | class ____:
def permute(self, n: int, k: int) -> list[int]:
ans = []
isLookingForEven = True
remainingNumbers = list(range(1, n + 1))
for turn in range(n):
remainingPermutations = (math.factorial((n - 1 - turn) // 2) *
math.factorial((n - turn) // 2))
found = False
for index, number in enumerate(remainingNumbers):
if number % 2 != isLookingForEven and (turn > 0 or n % 2 == 1):
continue
if k <= remainingPermutations:
ans.append(remainingNumbers.pop(index))
isLookingForEven = ans[-1] % 2 == 0
found = True
break
k -= remainingPermutations
if not found:
return []
return ans
| Solution |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 65037,
"end": 66717
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(50)),
)
Table(
"addresses",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("user_id", Integer),
Column("email", String(50)),
)
@classmethod
def setup_classes(cls):
class User(cls.Comparable):
pass
class Address(cls.Comparable):
pass
def test_backref(self):
User, Address, users, addresses = (
self.classes.User,
self.classes.Address,
self.tables.users,
self.tables.addresses,
)
self.mapper_registry.map_imperatively(
User,
users,
properties={
"addresses": relationship(
Address,
primaryjoin=addresses.c.user_id == users.c.id,
foreign_keys=addresses.c.user_id,
backref="user",
)
},
)
self.mapper_registry.map_imperatively(Address, addresses)
sess = fixture_session()
u1 = User(name="u1", addresses=[Address(email="a1")])
sess.add(u1)
sess.commit()
eq_(
sess.query(Address).all(),
[Address(email="a1", user=User(name="u1"))],
)
| BackrefPropagatesForwardsArgs |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 15749,
"end": 15945
} | class ____(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField(max_length=255, unique=True)
history = HistoricalRecords(table_name="contacts_history")
| Contact |
python | Pylons__pyramid | tests/test_view.py | {
"start": 6035,
"end": 8777
} | class ____(BaseTest, unittest.TestCase):
def _makeOne(self, *args, **kw):
from pyramid.view import exception_view_config
return exception_view_config(*args, **kw)
def test_ctor(self):
inst = self._makeOne(context=Exception, path_info='path_info')
self.assertEqual(
inst.__dict__, {'context': Exception, 'path_info': 'path_info'}
)
def test_ctor_positional_exception(self):
inst = self._makeOne(Exception, path_info='path_info')
self.assertEqual(
inst.__dict__, {'context': Exception, 'path_info': 'path_info'}
)
def test_ctor_positional_extras(self):
from pyramid.exceptions import ConfigurationError
self.assertRaises(
ConfigurationError, lambda: self._makeOne(Exception, True)
)
def test_it_function(self):
def view(request): # pragma: no cover
pass
decorator = self._makeOne(context=Exception, renderer='renderer')
venusian = DummyVenusian()
decorator.venusian = venusian
wrapped = decorator(view)
self.assertTrue(wrapped is view)
config = call_venusian(venusian)
settings = config.settings
self.assertEqual(
settings,
[
{
'venusian': venusian,
'context': Exception,
'renderer': 'renderer',
'_info': 'codeinfo',
'view': None,
}
],
)
def test_it_class(self):
decorator = self._makeOne()
venusian = DummyVenusian()
decorator.venusian = venusian
decorator.venusian.info.scope = 'class'
class view:
pass
wrapped = decorator(view)
self.assertTrue(wrapped is view)
config = call_venusian(venusian)
settings = config.settings
self.assertEqual(len(settings), 1)
self.assertEqual(len(settings[0]), 4)
self.assertEqual(settings[0]['venusian'], venusian)
self.assertEqual(settings[0]['view'], None) # comes from call_venusian
self.assertEqual(settings[0]['attr'], 'view')
self.assertEqual(settings[0]['_info'], 'codeinfo')
def test_call_with_venusian_args(self):
decorator = self._makeOne(_depth=1, _category='foo')
venusian = DummyVenusian()
decorator.venusian = venusian
def foo(): # pragma: no cover
pass
decorator(foo)
attachments = venusian.attachments
category = attachments[0][2]
depth = attachments[0][3]
self.assertEqual(depth, 2)
self.assertEqual(category, 'foo')
| Test_exception_view_config |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_autofilter10.py | {
"start": 315,
"end": 2701
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("autofilter10.xlsx")
self.set_text_file("autofilter_data.txt")
def test_create_file(self):
"""
Test the creation of a simple XlsxWriter file with an autofilter.
This test checks a filter list + blanks.
"""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
# Set the autofilter.
worksheet.autofilter("A1:D51")
# Add filter criteria.
worksheet.filter_column_list(0, ["North", "South", "East", "Blanks"])
# Open a text file with autofilter example data.
textfile = open(self.txt_filename)
# Read the headers from the first line of the input file.
headers = textfile.readline().strip("\n").split()
# Write out the headers.
worksheet.write_row("A1", headers)
# Start writing data after the headers.
row = 1
# Read the rest of the text file and write it to the worksheet.
for line in textfile:
# Split the input data based on whitespace.
data = line.strip("\n").split()
# Convert the number data from the text file.
for i, item in enumerate(data):
try:
data[i] = float(item)
except ValueError:
pass
# Simulate a blank cell in the data.
if row == 6:
data[0] = ""
# Get some of the field data.
region = data[0]
# Check for rows that match the filter.
if (
region == "North"
or region == "South"
or region == "East"
or region == ""
):
# Row matches the filter, no further action required.
pass
else:
# We need to hide rows that don't match the filter.
worksheet.set_row(row, options={"hidden": True})
# Write out the row data.
worksheet.write_row(row, 0, data)
# Move on to the next worksheet row.
row += 1
textfile.close()
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py | {
"start": 1787,
"end": 1912
} | class ____(BaseModel, extra=1):
# MYPY: error: Invalid value for "Config.extra" [pydantic-config]
pass
| KwargsBadExtraModel |
python | readthedocs__readthedocs.org | readthedocs/builds/migrations/0021_make_hidden_field_not_null.py | {
"start": 149,
"end": 651
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("builds", "0020_migrate_null_hidden_field"),
]
operations = [
migrations.AlterField(
model_name="version",
name="hidden",
field=models.BooleanField(
default=False,
help_text="Hide this version from the version (flyout) menu and search results?",
verbose_name="Hidden",
),
),
]
| Migration |
python | coleifer__peewee | tests/models.py | {
"start": 100180,
"end": 110788
} | class ____(ModelTestCase):
requires = [Category]
def setUp(self):
super(TestCTEIntegration, self).setUp()
CC = Category.create
root = CC(name='root')
p1 = CC(name='p1', parent=root)
p2 = CC(name='p2', parent=root)
p3 = CC(name='p3', parent=root)
c11 = CC(name='c11', parent=p1)
c12 = CC(name='c12', parent=p1)
c31 = CC(name='c31', parent=p3)
@skip_if(IS_SQLITE_OLD or (IS_MYSQL and not IS_MYSQL_ADVANCED_FEATURES)
or IS_CRDB)
@requires_models(Member)
def test_docs_example(self):
f = Member.create(name='founder')
gen2_1 = Member.create(name='g2-1', recommendedby=f)
gen2_2 = Member.create(name='g2-2', recommendedby=f)
gen2_3 = Member.create(name='g2-3', recommendedby=f)
gen3_1_1 = Member.create(name='g3-1-1', recommendedby=gen2_1)
gen3_1_2 = Member.create(name='g3-1-2', recommendedby=gen2_1)
gen3_3_1 = Member.create(name='g3-3-1', recommendedby=gen2_3)
# Get recommender chain for 331.
base = (Member
.select(Member.recommendedby)
.where(Member.id == gen3_3_1.id)
.cte('recommenders', recursive=True, columns=('recommender',)))
MA = Member.alias()
recursive = (MA
.select(MA.recommendedby)
.join(base, on=(MA.id == base.c.recommender)))
cte = base.union_all(recursive)
query = (cte
.select_from(cte.c.recommender, Member.name)
.join(Member, on=(cte.c.recommender == Member.id))
.order_by(Member.id.desc()))
self.assertEqual([m.name for m in query], ['g2-3', 'founder'])
@skip_if(IS_SQLITE_OLD or (IS_MYSQL and not IS_MYSQL_ADVANCED_FEATURES))
def test_simple_cte(self):
cte = (Category
.select(Category.name, Category.parent)
.cte('catz', columns=('name', 'parent')))
cte_sql = ('WITH "catz" ("name", "parent") AS ('
'SELECT "t1"."name", "t1"."parent_id" '
'FROM "category" AS "t1") '
'SELECT "catz"."name", "catz"."parent" AS "pname" '
'FROM "catz" '
'ORDER BY "catz"."name"')
query = (Category
.select(cte.c.name, cte.c.parent.alias('pname'))
.from_(cte)
.order_by(cte.c.name)
.with_cte(cte))
self.assertSQL(query, cte_sql, [])
query2 = (cte.select_from(cte.c.name, cte.c.parent.alias('pname'))
.order_by(cte.c.name))
self.assertSQL(query2, cte_sql, [])
self.assertEqual([(row.name, row.pname) for row in query], [
('c11', 'p1'),
('c12', 'p1'),
('c31', 'p3'),
('p1', 'root'),
('p2', 'root'),
('p3', 'root'),
('root', None)])
self.assertEqual([(row.name, row.pname) for row in query],
[(row.name, row.pname) for row in query2])
@skip_if(IS_SQLITE_OLD or (IS_MYSQL and not IS_MYSQL_ADVANCED_FEATURES))
def test_cte_join(self):
cte = (Category
.select(Category.name)
.cte('parents', columns=('name',)))
query = (Category
.select(Category.name, cte.c.name.alias('pname'))
.join(cte, on=(Category.parent == cte.c.name))
.order_by(Category.name)
.with_cte(cte))
self.assertSQL(query, (
'WITH "parents" ("name") AS ('
'SELECT "t1"."name" FROM "category" AS "t1") '
'SELECT "t2"."name", "parents"."name" AS "pname" '
'FROM "category" AS "t2" '
'INNER JOIN "parents" ON ("t2"."parent_id" = "parents"."name") '
'ORDER BY "t2"."name"'), [])
self.assertEqual([(c.name, c.parents['pname']) for c in query], [
('c11', 'p1'),
('c12', 'p1'),
('c31', 'p3'),
('p1', 'root'),
('p2', 'root'),
('p3', 'root'),
])
@skip_if(IS_SQLITE_OLD or IS_MYSQL or IS_CRDB, 'requires recursive cte')
def test_recursive_cte(self):
def get_parents(cname):
C1 = Category.alias()
C2 = Category.alias()
level = SQL('1').cast('integer').alias('level')
path = C1.name.cast('text').alias('path')
base = (C1
.select(C1.name, C1.parent, level, path)
.where(C1.name == cname)
.cte('parents', recursive=True))
rlevel = (base.c.level + 1).alias('level')
rpath = base.c.path.concat('->').concat(C2.name).alias('path')
recursive = (C2
.select(C2.name, C2.parent, rlevel, rpath)
.from_(base)
.join(C2, on=(C2.name == base.c.parent_id)))
cte = base + recursive
query = (cte
.select_from(cte.c.name, cte.c.level, cte.c.path)
.order_by(cte.c.level))
self.assertSQL(query, (
'WITH RECURSIVE "parents" AS ('
'SELECT "t1"."name", "t1"."parent_id", '
'CAST(1 AS integer) AS "level", '
'CAST("t1"."name" AS text) AS "path" '
'FROM "category" AS "t1" '
'WHERE ("t1"."name" = ?) '
'UNION ALL '
'SELECT "t2"."name", "t2"."parent_id", '
'("parents"."level" + ?) AS "level", '
'(("parents"."path" || ?) || "t2"."name") AS "path" '
'FROM "parents" '
'INNER JOIN "category" AS "t2" '
'ON ("t2"."name" = "parents"."parent_id")) '
'SELECT "parents"."name", "parents"."level", "parents"."path" '
'FROM "parents" '
'ORDER BY "parents"."level"'), [cname, 1, '->'])
return query
data = [row for row in get_parents('c31').tuples()]
self.assertEqual(data, [
('c31', 1, 'c31'),
('p3', 2, 'c31->p3'),
('root', 3, 'c31->p3->root')])
data = [(c.name, c.level, c.path)
for c in get_parents('c12').namedtuples()]
self.assertEqual(data, [
('c12', 1, 'c12'),
('p1', 2, 'c12->p1'),
('root', 3, 'c12->p1->root')])
query = get_parents('root')
data = [(r.name, r.level, r.path) for r in query]
self.assertEqual(data, [('root', 1, 'root')])
@skip_if(IS_SQLITE_OLD or IS_MYSQL or IS_CRDB, 'requires recursive cte')
def test_recursive_cte2(self):
hierarchy = (Category
.select(Category.name, Value(0).alias('level'))
.where(Category.parent.is_null(True))
.cte(name='hierarchy', recursive=True))
C = Category.alias()
recursive = (C
.select(C.name, (hierarchy.c.level + 1).alias('level'))
.join(hierarchy, on=(C.parent == hierarchy.c.name)))
cte = hierarchy.union_all(recursive)
query = (cte
.select_from(cte.c.name, cte.c.level)
.order_by(cte.c.name))
self.assertEqual([(r.name, r.level) for r in query], [
('c11', 2),
('c12', 2),
('c31', 2),
('p1', 1),
('p2', 1),
('p3', 1),
('root', 0)])
@skip_if(IS_SQLITE_OLD or IS_MYSQL or IS_CRDB, 'requires recursive cte')
def test_recursive_cte_docs_example(self):
# Define the base case of our recursive CTE. This will be categories that
# have a null parent foreign-key.
Base = Category.alias()
level = Value(1).cast('integer').alias('level')
path = Base.name.cast('text').alias('path')
base_case = (Base
.select(Base.name, Base.parent, level, path)
.where(Base.parent.is_null())
.cte('base', recursive=True))
# Define the recursive terms.
RTerm = Category.alias()
rlevel = (base_case.c.level + 1).alias('level')
rpath = base_case.c.path.concat('->').concat(RTerm.name).alias('path')
recursive = (RTerm
.select(RTerm.name, RTerm.parent, rlevel, rpath)
.join(base_case, on=(RTerm.parent == base_case.c.name)))
# The recursive CTE is created by taking the base case and UNION ALL with
# the recursive term.
cte = base_case.union_all(recursive)
# We will now query from the CTE to get the categories, their levels, and
# their paths.
query = (cte
.select_from(cte.c.name, cte.c.level, cte.c.path)
.order_by(cte.c.path))
data = [(obj.name, obj.level, obj.path) for obj in query]
self.assertEqual(data, [
('root', 1, 'root'),
('p1', 2, 'root->p1'),
('c11', 3, 'root->p1->c11'),
('c12', 3, 'root->p1->c12'),
('p2', 2, 'root->p2'),
('p3', 2, 'root->p3'),
('c31', 3, 'root->p3->c31')])
@requires_models(Sample)
@skip_if(IS_SQLITE_OLD or IS_MYSQL, 'sqlite too old for ctes, mysql flaky')
def test_cte_reuse_aggregate(self):
data = (
(1, (1.25, 1.5, 1.75)),
(2, (2.1, 2.3, 2.5, 2.7, 2.9)),
(3, (3.5, 3.5)))
with self.database.atomic():
for counter, values in data:
(Sample
.insert_many([(counter, value) for value in values],
fields=[Sample.counter, Sample.value])
.execute())
cte = (Sample
.select(Sample.counter, fn.AVG(Sample.value).alias('avg_value'))
.group_by(Sample.counter)
.cte('count_to_avg', columns=('counter', 'avg_value')))
query = (Sample
.select(Sample.counter,
(Sample.value - cte.c.avg_value).alias('diff'))
.join(cte, on=(Sample.counter == cte.c.counter))
.where(Sample.value > cte.c.avg_value)
.order_by(Sample.value)
.with_cte(cte))
self.assertEqual([(a, round(b, 2)) for a, b in query.tuples()], [
(1, .25),
(2, .2),
(2, .4)])
@skip_if(not IS_SQLITE_15, 'requires row-values')
| TestCTEIntegration |
python | sympy__sympy | sympy/stats/random_matrix_models.py | {
"start": 3950,
"end": 4647
} | class ____(GaussianEnsembleModel):
@property
def normalization_constant(self):
n = self.dimension
return 2**(S(n)/2) * pi**(S(n**2)/2)
def density(self, expr):
n, ZGUE = self.dimension, self.normalization_constant
h_pspace = RandomMatrixPSpace('P', model=self)
H = RandomMatrixSymbol('H', n, n, pspace=h_pspace)
return Lambda(H, exp(-S(n)/2 * Trace(H**2))/ZGUE)(expr)
def joint_eigen_distribution(self):
return self._compute_joint_eigen_distribution(S(2))
def level_spacing_distribution(self):
s = Dummy('s')
f = (32/pi**2)*(s**2)*exp((-4/pi)*s**2)
return Lambda(s, f)
| GaussianUnitaryEnsembleModel |
python | sympy__sympy | sympy/core/numbers.py | {
"start": 95258,
"end": 96660
} | class ____(IntegerConstant, metaclass=Singleton):
"""The number negative one.
NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``.
Examples
========
>>> from sympy import S, Integer
>>> Integer(-1) is S.NegativeOne
True
See Also
========
One
References
==========
.. [1] https://en.wikipedia.org/wiki/%E2%88%921_%28number%29
"""
is_number = True
p = -1
q = 1
__slots__ = ()
def __getnewargs__(self):
return ()
@staticmethod
def __abs__():
return S.One
@staticmethod
def __neg__():
return S.One
def _eval_power(self, expt):
if expt.is_odd:
return S.NegativeOne
if expt.is_even:
return S.One
if isinstance(expt, Number):
if isinstance(expt, Float):
return Float(-1.0)**expt
if expt is S.NaN:
return S.NaN
if expt in (S.Infinity, S.NegativeInfinity):
return S.NaN
if expt is S.Half:
return S.ImaginaryUnit
if isinstance(expt, Rational):
if expt.q == 2:
return S.ImaginaryUnit**Integer(expt.p)
i, r = divmod(expt.p, expt.q)
if i:
return self**i*self**Rational(r, expt.q)
return
| NegativeOne |
python | Unity-Technologies__ml-agents | ml-agents-envs/tests/simple_test_envs.py | {
"start": 934,
"end": 10473
} | class ____(BaseEnv):
"""
Very simple "game" - the agent has a position on [-1, 1], gets a reward of 1 if it reaches 1, and a reward of -1 if
it reaches -1. The position is incremented by the action amount (clamped to [-step_size, step_size]).
"""
def __init__(
self,
brain_names,
step_size=STEP_SIZE,
num_visual=0,
num_vector=1,
num_var_len=0,
vis_obs_size=VIS_OBS_SIZE,
vec_obs_size=OBS_SIZE,
var_len_obs_size=VAR_LEN_SIZE,
action_sizes=(1, 0),
goal_indices=None,
):
super().__init__()
self.num_visual = num_visual
self.num_vector = num_vector
self.num_var_len = num_var_len
self.vis_obs_size = vis_obs_size
self.vec_obs_size = vec_obs_size
self.var_len_obs_size = var_len_obs_size
self.goal_indices = goal_indices
continuous_action_size, discrete_action_size = action_sizes
discrete_tuple = tuple(2 for _ in range(discrete_action_size))
action_spec = ActionSpec(continuous_action_size, discrete_tuple)
self.total_action_size = (
continuous_action_size + discrete_action_size
) # to set the goals/positions
self.action_spec = action_spec
self.behavior_spec = BehaviorSpec(self._make_observation_specs(), action_spec)
self.action_spec = action_spec
self.names = brain_names
self.positions: Dict[str, List[float]] = {}
self.step_count: Dict[str, float] = {}
self._side_channel_manager = SideChannelManager([])
# Concatenate the arguments for a consistent random seed
seed = (
brain_names,
step_size,
num_visual,
num_vector,
num_var_len,
vis_obs_size,
vec_obs_size,
var_len_obs_size,
action_sizes,
)
self.random = random.Random(str(seed))
self.goal: Dict[str, int] = {}
self.action = {}
self.rewards: Dict[str, float] = {}
self.final_rewards: Dict[str, List[float]] = {}
self.step_result: Dict[str, Tuple[DecisionSteps, TerminalSteps]] = {}
self.agent_id: Dict[str, int] = {}
self.step_size = step_size # defines the difficulty of the test
# Allow to be used as a UnityEnvironment during tests
self.academy_capabilities = None
for name in self.names:
self.agent_id[name] = 0
self.goal[name] = self.random.choice([-1, 1])
self.rewards[name] = 0
self.final_rewards[name] = []
self._reset_agent(name)
self.action[name] = None
self.step_result[name] = None
def _make_observation_specs(self) -> List[ObservationSpec]:
obs_shape: List[Any] = []
for _ in range(self.num_vector):
obs_shape.append((self.vec_obs_size,))
for _ in range(self.num_visual):
obs_shape.append(self.vis_obs_size)
for _ in range(self.num_var_len):
obs_shape.append(self.var_len_obs_size)
obs_spec = create_observation_specs_with_shapes(obs_shape)
if self.goal_indices is not None:
for i in range(len(obs_spec)):
if i in self.goal_indices:
obs_spec[i] = ObservationSpec(
shape=obs_spec[i].shape,
dimension_property=obs_spec[i].dimension_property,
observation_type=ObservationType.GOAL_SIGNAL,
name=obs_spec[i].name,
)
return obs_spec
def _make_obs(self, value: float) -> List[np.ndarray]:
obs = []
for _ in range(self.num_vector):
obs.append(np.ones((1, self.vec_obs_size), dtype=np.float32) * value)
for _ in range(self.num_visual):
obs.append(np.ones((1,) + self.vis_obs_size, dtype=np.float32) * value)
for _ in range(self.num_var_len):
obs.append(np.ones((1,) + self.var_len_obs_size, dtype=np.float32) * value)
return obs
@property
def behavior_specs(self):
behavior_dict = {}
for n in self.names:
behavior_dict[n] = self.behavior_spec
return BehaviorMapping(behavior_dict)
def set_action_for_agent(self, behavior_name, agent_id, action):
pass
def set_actions(self, behavior_name, action):
self.action[behavior_name] = action
def get_steps(self, behavior_name):
return self.step_result[behavior_name]
def _take_action(self, name: str) -> bool:
deltas = []
_act = self.action[name]
if self.action_spec.continuous_size > 0 and not _act:
for _cont in _act.continuous[0]:
deltas.append(_cont)
if self.action_spec.discrete_size > 0 and not _act:
for _disc in _act.discrete[0]:
deltas.append(1 if _disc else -1)
for i, _delta in enumerate(deltas):
_delta = clamp(_delta, -self.step_size, self.step_size)
self.positions[name][i] += _delta
self.positions[name][i] = clamp(self.positions[name][i], -1, 1)
self.step_count[name] += 1
# Both must be in 1.0 to be done
done = all(pos >= 1.0 or pos <= -1.0 for pos in self.positions[name])
return done
def _generate_mask(self):
action_mask = None
if self.action_spec.discrete_size > 0:
# LL-Python API will return an empty dim if there is only 1 agent.
ndmask = np.array(2 * self.action_spec.discrete_size * [False], dtype=bool)
ndmask = np.expand_dims(ndmask, axis=0)
action_mask = [ndmask]
return action_mask
def _compute_reward(self, name: str, done: bool) -> float:
if done:
reward = 0.0
for _pos in self.positions[name]:
reward += (SUCCESS_REWARD * _pos * self.goal[name]) / len(
self.positions[name]
)
else:
reward = -TIME_PENALTY
return reward
def _reset_agent(self, name):
self.goal[name] = self.random.choice([-1, 1])
self.positions[name] = [0.0 for _ in range(self.total_action_size)]
self.step_count[name] = 0
self.rewards[name] = 0
self.agent_id[name] = self.agent_id[name] + 1
def _make_batched_step(
self, name: str, done: bool, reward: float, group_reward: float
) -> Tuple[DecisionSteps, TerminalSteps]:
m_vector_obs = self._make_obs(self.goal[name])
m_reward = np.array([reward], dtype=np.float32)
m_agent_id = np.array([self.agent_id[name]], dtype=np.int32)
m_group_id = np.array([0], dtype=np.int32)
m_group_reward = np.array([group_reward], dtype=np.float32)
action_mask = self._generate_mask()
decision_step = DecisionSteps(
m_vector_obs, m_reward, m_agent_id, action_mask, m_group_id, m_group_reward
)
terminal_step = TerminalSteps.empty(self.behavior_spec)
if done:
self.final_rewards[name].append(self.rewards[name])
# self._reset_agent(name)
# new_vector_obs = self._make_obs(self.goal[name])
# (
# new_reward,
# new_done,
# new_agent_id,
# new_action_mask,
# new_group_id,
# new_group_reward,
# ) = self._construct_reset_step(name)
# decision_step = DecisionSteps(
# new_vector_obs,
# new_reward,
# new_agent_id,
# new_action_mask,
# new_group_id,
# new_group_reward,
# )
decision_step = DecisionSteps([], [], [], [], [], [])
terminal_step = TerminalSteps(
m_vector_obs,
m_reward,
np.array([False], dtype=bool),
m_agent_id,
m_group_id,
m_group_reward,
)
return (decision_step, terminal_step)
def _construct_reset_step(
self, name: str
) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
new_reward = np.array([0.0], dtype=np.float32)
new_done = np.array([False], dtype=bool)
new_agent_id = np.array([self.agent_id[name]], dtype=np.int32)
new_action_mask = self._generate_mask()
new_group_id = np.array([0], dtype=np.int32)
new_group_reward = np.array([0.0], dtype=np.float32)
return (
new_reward,
new_done,
new_agent_id,
new_action_mask,
new_group_id,
new_group_reward,
)
def step(self) -> None:
assert all(action is not None for action in self.action.values())
for name in self.names:
done = self._take_action(name)
reward = self._compute_reward(name, done)
self.rewards[name] += reward
self.step_result[name] = self._make_batched_step(name, done, reward, 0.0)
def reset(self) -> None: # type: ignore
for name in self.names:
self._reset_agent(name)
self.step_result[name] = self._make_batched_step(name, False, 0.0, 0.0)
@property
def reset_parameters(self) -> Dict[str, str]:
return {}
def close(self):
pass
| SimpleEnvironment |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_variables.py | {
"start": 21248,
"end": 21857
} | class ____:
async def test_delete_variable(
self,
client: AsyncClient,
variable,
):
res = await client.delete(
f"/variables/name/{variable.name}",
)
assert res.status_code == 204
res = await client.get(
f"/variables/name/{variable.name}",
)
assert res.status_code == 404
async def test_does_not_exist(
self,
client: AsyncClient,
):
res = await client.delete(
"/variables/name/doesntexist",
)
assert res.status_code == 404
| TestDeleteVariableByName |
python | crytic__slither | slither/detectors/statements/deprecated_calls.py | {
"start": 773,
"end": 7788
} | class ____(AbstractDetector):
"""
Use of Deprecated Standards
"""
ARGUMENT = "deprecated-standards"
HELP = "Deprecated Solidity Standards"
IMPACT = DetectorClassification.INFORMATIONAL
CONFIDENCE = DetectorClassification.HIGH
LANGUAGE = "solidity"
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#deprecated-standards"
WIKI_TITLE = "Deprecated standards"
WIKI_DESCRIPTION = "Detect the usage of deprecated standards."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
contract ContractWithDeprecatedReferences {
// Deprecated: Change block.blockhash() -> blockhash()
bytes32 globalBlockHash = block.blockhash(0);
// Deprecated: Change constant -> view
function functionWithDeprecatedThrow() public constant {
// Deprecated: Change msg.gas -> gasleft()
if(msg.gas == msg.value) {
// Deprecated: Change throw -> revert()
throw;
}
}
// Deprecated: Change constant -> view
function functionWithDeprecatedReferences() public constant {
// Deprecated: Change sha3() -> keccak256()
bytes32 sha3Result = sha3("test deprecated sha3 usage");
// Deprecated: Change callcode() -> delegatecall()
address(this).callcode();
// Deprecated: Change suicide() -> selfdestruct()
suicide(address(0));
}
}
```"""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Replace all uses of deprecated symbols."
# The format for the following deprecated lists is [(detecting_signature, original_text, recommended_text)]
DEPRECATED_SOLIDITY_VARIABLE = [
("block.blockhash", "block.blockhash()", "blockhash()"),
("msg.gas", "msg.gas", "gasleft()"),
]
DEPRECATED_SOLIDITY_FUNCTIONS = [
("suicide(address)", "suicide()", "selfdestruct()"),
("sha3()", "sha3()", "keccak256()"),
]
DEPRECATED_NODE_TYPES = [(NodeType.THROW, "throw", "revert()")]
DEPRECATED_LOW_LEVEL_CALLS = [("callcode", "callcode", "delegatecall")]
def detect_deprecation_in_expression(
self, expression: Expression
) -> List[Tuple[str, str, str]]:
"""Detects if an expression makes use of any deprecated standards.
Returns:
list of tuple: (detecting_signature, original_text, recommended_text)"""
# Perform analysis on this expression
export = ExportValues(expression)
export_values = export.result()
# Define our results list
results = []
# Check if there is usage of any deprecated solidity variables or functions
for dep_var in self.DEPRECATED_SOLIDITY_VARIABLE:
if SolidityVariableComposed(dep_var[0]) in export_values:
results.append(dep_var)
for dep_func in self.DEPRECATED_SOLIDITY_FUNCTIONS:
if SolidityFunction(dep_func[0]) in export_values:
results.append(dep_func)
return results
def detect_deprecated_references_in_node(
self, node: Node
) -> List[Tuple[Union[str, NodeType], str, str]]:
"""Detects if a node makes use of any deprecated standards.
Returns:
list of tuple: (detecting_signature, original_text, recommended_text)"""
# Define our results list
results: List[Tuple[Union[str, NodeType], str, str]] = []
# If this node has an expression, we check the underlying expression.
if node.expression:
results += self.detect_deprecation_in_expression(node.expression)
# Check if there is usage of any deprecated solidity variables or functions
for dep_node in self.DEPRECATED_NODE_TYPES:
if node.type == dep_node[0]:
results.append(dep_node)
return results
def detect_deprecated_references_in_contract(
self, contract: Contract
) -> List[
Union[
Tuple[StateVariable, List[Tuple[str, str, str]]],
Tuple[Node, List[Tuple[Union[str, NodeType], str, str]]],
]
]:
"""Detects the usage of any deprecated built-in symbols.
Returns:
list of tuple: (state_variable | node, (detecting_signature, original_text, recommended_text))"""
results: List[
Union[
Tuple[StateVariable, List[Tuple[str, str, str]]],
Tuple[Node, List[Tuple[Union[str, NodeType], str, str]]],
]
] = []
for state_variable in contract.state_variables_declared:
if state_variable.expression:
deprecated_results = self.detect_deprecation_in_expression(
state_variable.expression
)
if deprecated_results:
results.append((state_variable, deprecated_results))
# Loop through all functions + modifiers in this contract.
# pylint: disable=too-many-nested-blocks
for function in contract.functions_and_modifiers_declared:
# Loop through each node in this function.
for node in function.nodes:
# Detect deprecated references in the node.
deprecated_results_node = self.detect_deprecated_references_in_node(node)
# Detect additional deprecated low-level-calls.
for ir in node.irs:
if isinstance(ir, LowLevelCall):
for dep_llc in self.DEPRECATED_LOW_LEVEL_CALLS:
if ir.function_name == dep_llc[0]:
deprecated_results_node.append(dep_llc)
# If we have any results from this iteration, add them to our results list.
if deprecated_results_node:
results.append((node, deprecated_results_node))
return results
def _detect(self) -> List[Output]:
"""Detects if an expression makes use of any deprecated standards.
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'deprecated_references'}
"""
results = []
for contract in self.contracts:
deprecated_references = self.detect_deprecated_references_in_contract(contract)
if deprecated_references:
for deprecated_reference in deprecated_references:
source_object = deprecated_reference[0]
deprecated_entries = deprecated_reference[1]
info: DETECTOR_INFO = ["Deprecated standard detected ", source_object, ":\n"]
for (_dep_id, original_desc, recommended_disc) in deprecated_entries:
info += [
f'\t- Usage of "{original_desc}" should be replaced with "{recommended_disc}"\n'
]
res = self.generate_result(info)
results.append(res)
return results
| DeprecatedStandards |
python | doocs__leetcode | lcof2/剑指 Offer II 102. 加减的目标值/Solution.py | {
"start": 0,
"end": 581
} | class ____:
def findTargetSumWays(self, nums: List[int], target: int) -> int:
if target < -1000 or target > 1000:
return 0
n = len(nums)
dp = [[0] * 2001 for i in range(n)]
dp[0][nums[0] + 1000] += 1
dp[0][-nums[0] + 1000] += 1
for i in range(1, n):
for j in range(-1000, 1001):
if dp[i - 1][j + 1000] > 0:
dp[i][j + nums[i] + 1000] += dp[i - 1][j + 1000]
dp[i][j - nums[i] + 1000] += dp[i - 1][j + 1000]
return dp[n - 1][target + 1000]
| Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI046.py | {
"start": 90,
"end": 155
} | class ____(typing.Protocol):
bar: int
_T = TypeVar("_T")
| _Bar |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 9336,
"end": 9568
} | class ____(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
choice = models.ForeignKey(Choice, on_delete=models.CASCADE, related_name="voters")
def __str__(self):
return "Voter object"
| Voter |
python | ray-project__ray | python/ray/llm/tests/serve/utils/testing_utils.py | {
"start": 403,
"end": 7643
} | class ____:
"""Reusable validation logic for LLM responses."""
@staticmethod
def get_expected_content(
api_type: str, max_tokens: int, lora_model_id: str = ""
) -> str:
"""Get expected content based on API type."""
expected_content = " ".join(f"test_{i}" for i in range(max_tokens))
if lora_model_id:
expected_content = f"[lora_model] {lora_model_id}: {expected_content}"
return expected_content
@staticmethod
def validate_non_streaming_response(
response: Union[ChatCompletionResponse, CompletionResponse],
api_type: str,
max_tokens: int,
lora_model_id: str = "",
):
"""Validate non-streaming responses."""
expected_content = LLMResponseValidator.get_expected_content(
api_type, max_tokens, lora_model_id
)
if api_type == "chat":
assert isinstance(response, ChatCompletionResponse)
assert response.choices[0].message.content == expected_content
elif api_type == "completion":
assert isinstance(response, CompletionResponse)
assert response.choices[0].text == expected_content
@staticmethod
def validate_streaming_chunks(
chunks: List[str], api_type: str, max_tokens: int, lora_model_id: str = ""
):
"""Validate streaming response chunks."""
# Should have max_tokens + 1 chunks (tokens + [DONE])
assert len(chunks) == max_tokens + 1
# Validate each chunk except the last [DONE] chunk
for chunk_iter, chunk in enumerate(chunks[:-1]):
pattern = r"data: (.*)\n\n"
match = re.match(pattern, chunk)
assert match is not None
chunk_data = json.loads(match.group(1))
expected_chunk = f"test_{chunk_iter}"
if lora_model_id and chunk_iter == 0:
expected_chunk = f"[lora_model] {lora_model_id}: {expected_chunk}"
if api_type == "chat":
delta = chunk_data["choices"][0]["delta"]
if chunk_iter == 0:
assert delta["role"] == "assistant"
else:
assert delta["role"] is None
assert delta["content"].strip() == expected_chunk
elif api_type == "completion":
text = chunk_data["choices"][0]["text"]
assert text.strip() == expected_chunk
@staticmethod
def validate_embedding_response(
response: EmbeddingResponse, expected_dimensions: Optional[int] = None
):
"""Validate embedding responses."""
assert isinstance(response, EmbeddingResponse)
assert response.object == "list"
assert len(response.data) == 1
assert response.data[0].object == "embedding"
assert isinstance(response.data[0].embedding, list)
assert (
len(response.data[0].embedding) > 0
) # Should have some embedding dimensions
assert response.data[0].index == 0
# Check dimensions if specified
if expected_dimensions:
assert len(response.data[0].embedding) == expected_dimensions
@staticmethod
def validate_score_response(response: ScoreResponse):
"""Validate score responses."""
assert isinstance(response, ScoreResponse)
assert response.object == "list"
assert len(response.data) >= 1
# Validate each score data element
for i, score_data in enumerate(response.data):
assert score_data.object == "score"
assert isinstance(score_data.score, float)
assert score_data.index == i # Index should match position in list
@staticmethod
def validate_transcription_response(
response: Union[TranscriptionResponse, List[str]],
temperature: float,
language: Optional[str] = None,
lora_model_id: str = "",
):
"""Validate transcription responses for both streaming and non-streaming."""
if isinstance(response, list):
# Streaming response - validate chunks
LLMResponseValidator.validate_transcription_streaming_chunks(
response, temperature, language, lora_model_id
)
else:
# Non-streaming response
assert isinstance(response, TranscriptionResponse)
assert hasattr(response, "text")
assert isinstance(response.text, str)
assert len(response.text) > 0
# Check that the response contains expected language and temperature info
expected_text = f"Mock transcription in {language} language with temperature {temperature}"
if lora_model_id:
expected_text = f"[lora_model] {lora_model_id}: {expected_text}"
assert response.text == expected_text
# Validate usage information
if hasattr(response, "usage"):
assert hasattr(response.usage, "seconds")
assert hasattr(response.usage, "type")
assert response.usage.seconds > 0
assert response.usage.type == "duration"
@staticmethod
def validate_transcription_streaming_chunks(
chunks: List[str],
temperature: float,
language: Optional[str] = None,
lora_model_id: str = "",
):
"""Validate streaming transcription response chunks."""
# Should have at least one chunk (transcription text) + final chunk + [DONE]
assert len(chunks) >= 3
# Validate each chunk except the last [DONE] chunk
transcription_chunks = []
for chunk in chunks[:-1]: # Exclude the final [DONE] chunk
pattern = r"data: (.*)\n\n"
match = re.match(pattern, chunk)
assert match is not None
chunk_data = json.loads(match.group(1))
# Validate chunk structure
assert "id" in chunk_data
assert "object" in chunk_data
assert chunk_data["object"] == "transcription.chunk"
assert "delta" in chunk_data
assert chunk_data["delta"] is None
assert "type" in chunk_data
assert chunk_data["type"] is None
assert "logprobs" in chunk_data
assert chunk_data["logprobs"] is None
assert "choices" in chunk_data
assert len(chunk_data["choices"]) == 1
choice = chunk_data["choices"][0]
assert "delta" in choice
assert "content" in choice["delta"]
# Collect text for final validation
if choice["delta"]["content"]:
transcription_chunks.append(choice["delta"]["content"])
# Validate final transcription text
full_transcription = "".join(transcription_chunks)
expected_text = (
f"Mock transcription in {language} language with temperature {temperature}"
)
if lora_model_id:
expected_text = f"[lora_model] {lora_model_id}: {expected_text}"
assert full_transcription.strip() == expected_text.strip()
# Validate final [DONE] chunk
assert chunks[-1] == "data: [DONE]\n\n"
| LLMResponseValidator |
python | dagster-io__dagster | python_modules/libraries/dagster-k8s/dagster_k8s/executor.py | {
"start": 8650,
"end": 17354
} | class ____(StepHandler):
@property
def name(self):
return "K8sStepHandler"
def __init__(
self,
image: Optional[str],
container_context: K8sContainerContext,
load_incluster_config: bool,
kubeconfig_file: Optional[str],
k8s_client_batch_api=None,
k8s_client_core_api=None,
per_step_k8s_config=None,
enable_owner_references=False,
):
super().__init__()
self._executor_image = check.opt_str_param(image, "image")
self._executor_container_context = check.inst_param(
container_context, "container_context", K8sContainerContext
)
self._kubeconfig_file = None
if load_incluster_config:
check.invariant(
kubeconfig_file is None,
"`kubeconfig_file` is set but `load_incluster_config` is True.",
)
kubernetes.config.load_incluster_config()
else:
check.opt_str_param(kubeconfig_file, "kubeconfig_file")
kubernetes.config.load_kube_config(kubeconfig_file)
self._kubeconfig_file = kubeconfig_file
self._api_client = DagsterKubernetesClient.production_client(
batch_api_override=k8s_client_batch_api,
core_api_override=k8s_client_core_api,
)
self._per_step_k8s_config = check.opt_dict_param(
per_step_k8s_config, "per_step_k8s_config", key_type=str, value_type=dict
)
self._enable_owner_references = enable_owner_references
def _get_step_key(self, step_handler_context: StepHandlerContext) -> str:
step_keys_to_execute = cast(
"list[str]", step_handler_context.execute_step_args.step_keys_to_execute
)
assert len(step_keys_to_execute) == 1, "Launching multiple steps is not currently supported"
return step_keys_to_execute[0]
def _get_container_context(
self, step_handler_context: StepHandlerContext
) -> K8sContainerContext:
step_key = self._get_step_key(step_handler_context)
context = K8sContainerContext.create_for_run(
step_handler_context.dagster_run,
cast("K8sRunLauncher", step_handler_context.instance.run_launcher),
include_run_tags=False, # For now don't include job-level dagster-k8s/config tags in step pods
)
context = context.merge(self._executor_container_context)
user_defined_k8s_config = get_user_defined_k8s_config(
step_handler_context.step_tags[step_key]
)
step_context = step_handler_context.get_step_context(step_key)
op_name = step_context.step.op_name
per_op_override = UserDefinedDagsterK8sConfig.from_dict(
self._per_step_k8s_config.get(op_name, {})
)
return context.merge(K8sContainerContext(run_k8s_config=user_defined_k8s_config)).merge(
K8sContainerContext(run_k8s_config=per_op_override)
)
def _get_k8s_step_job_name(self, step_handler_context: StepHandlerContext):
step_key = self._get_step_key(step_handler_context)
name_key = get_k8s_job_name(
step_handler_context.execute_step_args.run_id,
step_key,
)
if step_handler_context.execute_step_args.known_state:
retry_state = step_handler_context.execute_step_args.known_state.get_retry_state()
if retry_state.get_attempt_count(step_key):
return "dagster-step-%s-%d" % (name_key, retry_state.get_attempt_count(step_key)) # noqa: UP031
return f"dagster-step-{name_key}"
@cached_method
def _detect_current_name_and_uid(
self,
) -> Optional[tuple[str, str]]:
"""Get the current pod's pod name and uid, if available."""
from dagster_k8s.utils import detect_current_namespace
hostname = os.getenv("HOSTNAME")
if not hostname:
return None
namespace = detect_current_namespace(self._kubeconfig_file)
if not namespace:
return None
pod = self._api_client.get_pod_by_name(pod_name=hostname, namespace=namespace)
return pod.metadata.name, pod.metadata.uid
def launch_step(self, step_handler_context: StepHandlerContext) -> Iterator[DagsterEvent]:
step_key = self._get_step_key(step_handler_context)
job_name = self._get_k8s_step_job_name(step_handler_context)
pod_name = job_name
container_context = self._get_container_context(step_handler_context)
job_config = container_context.get_k8s_job_config(
self._executor_image, step_handler_context.instance.run_launcher
)
args = step_handler_context.execute_step_args.get_command_args(
skip_serialized_namedtuple=True
)
if not job_config.job_image:
job_config = job_config.with_image(
step_handler_context.execute_step_args.job_origin.repository_origin.container_image
)
if not job_config.job_image:
raise Exception("No image included in either executor config or the job")
run = step_handler_context.dagster_run
labels = {
"dagster/job": run.job_name,
"dagster/op": step_key,
"dagster/run-id": step_handler_context.execute_step_args.run_id,
}
if run.remote_job_origin:
labels["dagster/code-location"] = (
run.remote_job_origin.repository_origin.code_location_origin.location_name
)
deployment_name_env_var = get_deployment_id_label(container_context.run_k8s_config)
if deployment_name_env_var:
labels["dagster/deployment-name"] = deployment_name_env_var
owner_references = []
if self._enable_owner_references:
my_pod = self._detect_current_name_and_uid()
if my_pod:
owner_references = [OwnerReference(kind="Pod", name=my_pod[0], uid=my_pod[1])]
job = construct_dagster_k8s_job(
job_config=job_config,
args=args,
job_name=job_name,
pod_name=pod_name,
component="step_worker",
user_defined_k8s_config=container_context.run_k8s_config,
labels=labels,
env_vars=[
*step_handler_context.execute_step_args.get_command_env(),
{
"name": "DAGSTER_RUN_JOB_NAME",
"value": run.job_name,
},
{"name": "DAGSTER_RUN_STEP_KEY", "value": step_key},
],
owner_references=owner_references,
)
yield DagsterEvent.step_worker_starting(
step_handler_context.get_step_context(step_key),
message=f'Executing step "{step_key}" in Kubernetes job {job_name}.',
metadata={
"Kubernetes Job name": MetadataValue.text(job_name),
},
)
namespace = check.not_none(container_context.namespace)
self._api_client.create_namespaced_job_with_retries(body=job, namespace=namespace)
def check_step_health(self, step_handler_context: StepHandlerContext) -> CheckStepHealthResult:
step_key = self._get_step_key(step_handler_context)
job_name = self._get_k8s_step_job_name(step_handler_context)
container_context = self._get_container_context(step_handler_context)
status = self._api_client.get_job_status(
namespace=container_context.namespace, # pyright: ignore[reportArgumentType]
job_name=job_name,
)
if not status:
return CheckStepHealthResult.unhealthy(
reason=f"Kubernetes job {job_name} for step {step_key} could not be found."
)
if status.failed:
return CheckStepHealthResult.unhealthy(
reason=f"Discovered failed Kubernetes job {job_name} for step {step_key}.",
)
return CheckStepHealthResult.healthy()
def terminate_step(self, step_handler_context: StepHandlerContext) -> Iterator[DagsterEvent]:
step_key = self._get_step_key(step_handler_context)
job_name = self._get_k8s_step_job_name(step_handler_context)
container_context = self._get_container_context(step_handler_context)
yield DagsterEvent.engine_event(
step_handler_context.get_step_context(step_key),
message=f"Deleting Kubernetes job {job_name} for step",
event_specific_data=EngineEventData(),
)
self._api_client.delete_job(job_name=job_name, namespace=container_context.namespace)
| K8sStepHandler |
python | keras-team__keras | keras/src/utils/backend_utils_test.py | {
"start": 163,
"end": 1847
} | class ____(testing.TestCase):
@parameterized.named_parameters(
("numpy", "numpy"),
("jax", "jax"),
("tensorflow", "tensorflow"),
("torch", "torch"),
)
def test_dynamic_backend(self, name):
dynamic_backend = backend_utils.DynamicBackend()
x = np.random.uniform(size=[1, 2, 3]).astype("float32")
if name == "numpy":
dynamic_backend.set_backend(name)
if backend.backend() != "numpy":
with self.assertRaisesRegex(
NotImplementedError,
"Currently, we cannot dynamically import the numpy backend",
):
y = dynamic_backend.numpy.log10(x)
else:
y = dynamic_backend.numpy.log10(x)
self.assertIsInstance(y, np.ndarray)
elif name == "jax":
import jax
dynamic_backend.set_backend(name)
y = dynamic_backend.numpy.log10(x)
self.assertIsInstance(y, jax.Array)
elif name == "tensorflow":
import tensorflow as tf
dynamic_backend.set_backend(name)
y = dynamic_backend.numpy.log10(x)
self.assertIsInstance(y, tf.Tensor)
elif name == "torch":
import torch
dynamic_backend.set_backend(name)
y = dynamic_backend.numpy.log10(x)
self.assertIsInstance(y, torch.Tensor)
def test_dynamic_backend_invalid_name(self):
dynamic_backend = backend_utils.DynamicBackend()
with self.assertRaisesRegex(ValueError, "Available backends are"):
dynamic_backend.set_backend("abc")
| BackendUtilsTest |
python | pandas-dev__pandas | pandas/tests/extension/array_with_attr/array.py | {
"start": 702,
"end": 2481
} | class ____(ExtensionArray):
dtype = FloatAttrDtype()
__array_priority__ = 1000
def __init__(self, values, attr=None) -> None:
if not isinstance(values, np.ndarray):
raise TypeError("Need to pass a numpy array of float64 dtype as values")
if not values.dtype == "float64":
raise TypeError("Need to pass a numpy array of float64 dtype as values")
self.data = values
self.attr = attr
@classmethod
def _from_sequence(cls, scalars, *, dtype=None, copy=False):
if not copy:
data = np.asarray(scalars, dtype="float64")
else:
data = np.array(scalars, dtype="float64", copy=copy)
return cls(data)
def __getitem__(self, item):
if isinstance(item, numbers.Integral):
return self.data[item]
else:
# slice, list-like, mask
item = pd.api.indexers.check_array_indexer(self, item)
return type(self)(self.data[item], self.attr)
def __len__(self) -> int:
return len(self.data)
def isna(self):
return np.isnan(self.data)
def take(self, indexer, allow_fill=False, fill_value=None):
from pandas.api.extensions import take
data = self.data
if allow_fill and fill_value is None:
fill_value = self.dtype.na_value
result = take(data, indexer, fill_value=fill_value, allow_fill=allow_fill)
return type(self)(result, self.attr)
def copy(self):
return type(self)(self.data.copy(), self.attr)
@classmethod
def _concat_same_type(cls, to_concat):
data = np.concatenate([x.data for x in to_concat])
attr = to_concat[0].attr if len(to_concat) else None
return cls(data, attr)
| FloatAttrArray |
python | huggingface__transformers | tests/models/roformer/test_tokenization_roformer.py | {
"start": 880,
"end": 3802
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "junnyu/roformer_chinese_small"
tokenizer_class = RoFormerTokenizer
rust_tokenizer_class = RoFormerTokenizerFast
space_between_special_tokens = True
test_rust_tokenizer = True
@classmethod
def setUpClass(cls):
super().setUpClass()
tokenizer = cls.tokenizer_class.from_pretrained("junnyu/roformer_chinese_base")
tokenizer.save_pretrained(cls.tmpdirname)
@classmethod
def get_tokenizer(cls, pretrained_name=None, **kwargs):
pretrained_name = pretrained_name or cls.tmpdirname
return cls.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
@classmethod
def get_rust_tokenizer(cls, pretrained_name=None, **kwargs):
pretrained_name = pretrained_name or cls.tmpdirname
return cls.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
def get_chinese_input_output_texts(self):
input_text = "永和服装饰品有限公司,今天天气非常好"
output_text = "永和 服装 饰品 有限公司 , 今 天 天 气 非常 好"
return input_text, output_text
def test_tokenizer(self):
tokenizer = self.get_tokenizer()
input_text, output_text = self.get_chinese_input_output_texts()
tokens = tokenizer.tokenize(input_text)
self.assertListEqual(tokens, output_text.split())
input_tokens = tokens + [tokenizer.unk_token]
exp_tokens = [22943, 21332, 34431, 45904, 117, 306, 1231, 1231, 2653, 33994, 1266, 100]
self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), exp_tokens)
def test_rust_tokenizer(self): # noqa: F811
tokenizer = self.get_rust_tokenizer()
input_text, output_text = self.get_chinese_input_output_texts()
tokens = tokenizer.tokenize(input_text)
self.assertListEqual(tokens, output_text.split())
input_tokens = tokens + [tokenizer.unk_token]
exp_tokens = [22943, 21332, 34431, 45904, 117, 306, 1231, 1231, 2653, 33994, 1266, 100]
self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), exp_tokens)
@unittest.skip(reason="Cannot train new tokenizer via Tokenizers lib")
def test_training_new_tokenizer(self):
pass
@unittest.skip(reason="Cannot train new tokenizer via Tokenizers lib")
def test_training_new_tokenizer_with_special_tokens_change(self):
pass
def test_save_slow_from_fast_and_reload_fast(self):
for cls in [RoFormerTokenizer, RoFormerTokenizerFast]:
original = cls.from_pretrained("alchemab/antiberta2")
self.assertEqual(original.encode("生活的真谛是"), [1, 4, 4, 4, 4, 4, 4, 2])
with tempfile.TemporaryDirectory() as tmp_dir:
original.save_pretrained(tmp_dir)
new = cls.from_pretrained(tmp_dir)
self.assertEqual(new.encode("生活的真谛是"), [1, 4, 4, 4, 4, 4, 4, 2])
| RoFormerTokenizationTest |
python | pytorch__pytorch | test/test_privateuseone_python_backend.py | {
"start": 3411,
"end": 4093
} | class ____(TestCase):
@classmethod
def setupClass(cls):
pass
def test_accessing_is_pinned(self):
a_cpu = torch.randn((2, 2))
# Assert this don't throw:
_ = a_cpu.is_pinned()
def test_backend_simple(self):
a_cpu = torch.randn((2, 2))
b_cpu = torch.randn((2, 2))
# Assert this don't throw:
a = a_cpu.to("privateuseone")
b = b_cpu.to("privateuseone")
a.requires_grad = True
b.requires_grad = True
c = (a + b).sum()
c.backward()
self.assertTrue(np.allclose(a.grad.raw_data, np.ones((2, 2))))
if __name__ == "__main__":
run_tests()
| PrivateUse1BackendTest |
python | scipy__scipy | scipy/cluster/tests/test_hierarchy.py | {
"start": 30028,
"end": 32985
} | class ____:
def test_is_monotonic_empty(self, xp):
# Tests is_monotonic(Z) on an empty linkage.
Z = xp.zeros((0, 4), dtype=xp.float64)
assert_raises(ValueError, is_monotonic, Z)
def test_is_monotonic_1x4(self, xp):
# Tests is_monotonic(Z) on 1x4 linkage. Expecting True.
Z = xp.asarray([[0, 1, 0.3, 2]], dtype=xp.float64)
assert is_monotonic(Z)
def test_is_monotonic_2x4_T(self, xp):
# Tests is_monotonic(Z) on 2x4 linkage. Expecting True.
Z = xp.asarray([[0, 1, 0.3, 2],
[2, 3, 0.4, 3]], dtype=xp.float64)
assert is_monotonic(Z)
def test_is_monotonic_2x4_F(self, xp):
# Tests is_monotonic(Z) on 2x4 linkage. Expecting False.
Z = xp.asarray([[0, 1, 0.4, 2],
[2, 3, 0.3, 3]], dtype=xp.float64)
assert not is_monotonic(Z)
def test_is_monotonic_3x4_T(self, xp):
# Tests is_monotonic(Z) on 3x4 linkage. Expecting True.
Z = xp.asarray([[0, 1, 0.3, 2],
[2, 3, 0.4, 2],
[4, 5, 0.6, 4]], dtype=xp.float64)
assert is_monotonic(Z)
def test_is_monotonic_3x4_F1(self, xp):
# Tests is_monotonic(Z) on 3x4 linkage (case 1). Expecting False.
Z = xp.asarray([[0, 1, 0.3, 2],
[2, 3, 0.2, 2],
[4, 5, 0.6, 4]], dtype=xp.float64)
assert not is_monotonic(Z)
def test_is_monotonic_3x4_F2(self, xp):
# Tests is_monotonic(Z) on 3x4 linkage (case 2). Expecting False.
Z = xp.asarray([[0, 1, 0.8, 2],
[2, 3, 0.4, 2],
[4, 5, 0.6, 4]], dtype=xp.float64)
assert not is_monotonic(Z)
def test_is_monotonic_3x4_F3(self, xp):
# Tests is_monotonic(Z) on 3x4 linkage (case 3). Expecting False
Z = xp.asarray([[0, 1, 0.3, 2],
[2, 3, 0.4, 2],
[4, 5, 0.2, 4]], dtype=xp.float64)
assert not is_monotonic(Z)
def test_is_monotonic_tdist_linkage1(self, xp):
# Tests is_monotonic(Z) on clustering generated by single linkage on
# tdist data set. Expecting True.
Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
assert is_monotonic(Z)
def test_is_monotonic_tdist_linkage2(self, xp):
# Tests is_monotonic(Z) on clustering generated by single linkage on
# tdist data set. Perturbing. Expecting False.
Z = xp.asarray(linkage(hierarchy_test_data.ytdist, 'single'))
Z = xpx.at(Z)[2, 2].set(0.0)
assert not is_monotonic(Z)
def test_is_monotonic_Q_linkage(self, xp):
# Tests is_monotonic(Z) on clustering generated by single linkage on
# Q data set. Expecting True.
X = hierarchy_test_data.Q_X
Z = xp.asarray(linkage(X, 'single'))
assert is_monotonic(Z)
@make_xp_test_case(maxdists)
| TestIsMonotonic |
python | apache__airflow | providers/qdrant/src/airflow/providers/qdrant/hooks/qdrant.py | {
"start": 1070,
"end": 4938
} | class ____(BaseHook):
"""
Hook for interfacing with a Qdrant instance.
:param conn_id: The connection id to use when connecting to Qdrant. Defaults to `qdrant_default`.
"""
conn_name_attr = "conn_id"
conn_type = "qdrant"
default_conn_name = "qdrant_default"
hook_name = "Qdrant"
@classmethod
def get_connection_form_widgets(cls) -> dict[str, Any]:
"""Return connection widgets to add to connection form."""
from flask_appbuilder.fieldwidgets import BS3TextFieldWidget
from flask_babel import lazy_gettext
from wtforms import BooleanField, IntegerField, StringField
return {
"url": StringField(
lazy_gettext("URL"),
widget=BS3TextFieldWidget(),
description="Optional. Qualified URL of the Qdrant instance."
"Example: https://xyz-example.eu-central.aws.cloud.qdrant.io:6333",
),
"grpc_port": IntegerField(
lazy_gettext("GPRC Port"),
widget=BS3TextFieldWidget(),
description="Optional. Port of the gRPC interface.",
default=6334,
),
"prefer_gprc": BooleanField(
lazy_gettext("Prefer GRPC"),
widget=BS3TextFieldWidget(),
description="Optional. Whether to use gPRC interface whenever possible in custom methods.",
default=False,
),
"https": BooleanField(
lazy_gettext("HTTPS"),
widget=BS3TextFieldWidget(),
description="Optional. Whether to use HTTPS(SSL) protocol.",
),
"prefix": StringField(
lazy_gettext("Prefix"),
widget=BS3TextFieldWidget(),
description="Optional. Prefix to the REST URL path."
"Example: `service/v1` will result in http://localhost:6333/service/v1/{qdrant-endpoint} for REST API.",
),
}
@classmethod
def get_ui_field_behaviour(cls) -> dict[str, Any]:
"""Return custom field behaviour."""
return {
"hidden_fields": ["schema", "login", "extra"],
"relabeling": {"password": "API Key"},
}
def __init__(self, conn_id: str = default_conn_name, **kwargs) -> None:
super().__init__(**kwargs)
self.conn_id = conn_id
def get_conn(self) -> QdrantClient:
"""Get a Qdrant client instance for interfacing with the database."""
connection = self.get_connection(self.conn_id)
host = connection.host or None
port = connection.port or 6333
api_key = connection.password
extra = connection.extra_dejson
url = extra.get("url", None)
grpc_port = extra.get("grpc_port", 6334)
prefer_gprc = extra.get("prefer_gprc", False)
https = extra.get("https", None)
prefix = extra.get("prefix", None)
return QdrantClient(
host=host,
port=port,
url=url,
api_key=api_key,
grpc_port=grpc_port,
prefer_grpc=prefer_gprc,
https=https,
prefix=prefix,
)
@cached_property
def conn(self) -> QdrantClient:
"""Get a Qdrant client instance for interfacing with the database."""
return self.get_conn()
def verify_connection(self) -> tuple[bool, str]:
"""Check the connection to the Qdrant instance."""
try:
self.conn.get_collections()
return True, "Connection established!"
except (UnexpectedResponse, RpcError, ValueError) as e:
return False, str(e)
def test_connection(self) -> tuple[bool, str]:
"""Test the connection to the Qdrant instance."""
return self.verify_connection()
| QdrantHook |
python | pytorch__pytorch | test/distributed/tensor/parallel/test_micro_pipeline_tp.py | {
"start": 18500,
"end": 20336
} | class ____(TestCase):
def setUp(self):
torch._inductor.config._micro_pipeline_tp = True
self.rank = 0
self.world_size = 4
torch.cuda.set_device("cuda:0")
store = FakeStore()
dist.init_process_group(
backend="fake",
world_size=self.world_size,
rank=self.rank,
store=store,
)
def tearDown(self):
dist.destroy_process_group()
@unittest.skipIf(not HAS_GPU, "Inductor+gpu needs triton and recent GPU arch")
@fresh_cache()
def test_extra_collectives(self):
device_mesh = DeviceMesh(
"cuda",
torch.arange(0, self.world_size).view(2, -1),
mesh_dim_names=("tp", "other"),
)
def func(inp: torch.Tensor, w1: torch.Tensor, w2: torch.Tensor) -> torch.Tensor:
hidden = all_gather_tensor(inp, 0, (device_mesh, 0)) @ w1.t()
full_hidden = all_gather_tensor(hidden, 0, (device_mesh, 1))
full_hidden /= full_hidden.pow(2).sum().sqrt()
hidden = reduce_scatter_tensor(full_hidden, "avg", 0, (device_mesh, 1))
return reduce_scatter_tensor(hidden @ w2.t(), "avg", 0, (device_mesh, 0))
inp = torch.rand(8, 10, device="cuda")
w1 = torch.rand(7, 10, device="cuda")
w2 = torch.rand(10, 7, device="cuda")
with _test_mode(group_names={device_mesh["tp"].get_group().group_name}):
compiled = torch.compile(func)
code = run_and_get_triton_code(compiled, inp, w1, w2)
self.assertIn("fused_all_gather_matmul", code)
self.assertIn("all_gather_into_tensor", code)
self.assertIn("fused_matmul_reduce_scatter", code)
self.assertIn("reduce_scatter_tensor", code)
if __name__ == "__main__":
run_tests()
| MicroPipelineTP4GPUTest |
python | lepture__authlib | authlib/deprecate.py | {
"start": 18,
"end": 506
} | class ____(DeprecationWarning):
pass
warnings.simplefilter("always", AuthlibDeprecationWarning)
def deprecate(message, version=None, link_uid=None, link_file=None, stacklevel=3):
if version:
message += f"\nIt will be compatible before version {version}."
if link_uid and link_file:
message += f"\nRead more <https://git.io/{link_uid}#file-{link_file}-md>"
warnings.warn(AuthlibDeprecationWarning(message), stacklevel=stacklevel)
| AuthlibDeprecationWarning |
python | bokeh__bokeh | src/bokeh/models/mappers.py | {
"start": 9071,
"end": 9952
} | class ____(ContinuousColorMapper):
''' Map numbers in a range [*low*, *high*] into a sequence of colors
(a palette) on a natural logarithm scale.
For example, if the range is [0, 25] and the palette is
``['red', 'green', 'blue']``, the values would be mapped as follows::
x < 0 : 'red' # values < low are clamped
0 <= x < 2.72 : 'red' # math.e ** 1
2.72 <= x < 7.39 : 'green' # math.e ** 2
7.39 <= x < 20.09 : 'blue' # math.e ** 3
20.09 <= x : 'blue' # values > high are clamped
.. warning::
The ``LogColorMapper`` only works for images with scalar values that are
non-negative.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
@abstract
| LogColorMapper |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.