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 | astropy__astropy | astropy/modeling/projections.py | {
"start": 39265,
"end": 39466
} | class ____(Sky2PixProjection, QuadCube):
r"""
Quadrilateralized spherical cube projection - sky to pixel.
Corresponds to the ``QSC`` projection in FITS WCS.
"""
| Sky2Pix_QuadSphericalCube |
python | pandas-dev__pandas | pandas/tests/indexes/datetimes/methods/test_asof.py | {
"start": 128,
"end": 1155
} | class ____:
def test_asof_partial(self):
index = date_range("2010-01-01", periods=2, freq="ME")
expected = Timestamp("2010-02-28")
result = index.asof("2010-02")
assert result == expected
assert not isinstance(result, Index)
def test_asof(self):
index = date_range("2020-01-01", periods=10)
dt = index[0]
assert index.asof(dt) == dt
assert isna(index.asof(dt - timedelta(1)))
dt = index[-1]
assert index.asof(dt + timedelta(1)) == dt
dt = index[0].to_pydatetime()
assert isinstance(index.asof(dt), Timestamp)
def test_asof_datetime_string(self):
# GH#50946
dti = date_range("2021-08-05", "2021-08-10", freq="1D")
key = "2021-08-09"
res = dti.asof(key)
exp = dti[4]
assert res == exp
# add a non-midnight time caused a bug
dti2 = DatetimeIndex(list(dti) + ["2021-08-11 00:00:01"])
res = dti2.asof(key)
assert res == exp
| TestAsOf |
python | pytorch__pytorch | test/distributed/pipelining/model_registry.py | {
"start": 3798,
"end": 4405
} | class ____(torch.nn.Module):
default_dhid = 512
default_batch_size = 256
def __init__(self, d_hid: int = default_dhid):
super().__init__()
self.mm_param1 = self.mm_param0 = torch.nn.Parameter(torch.randn(d_hid, d_hid))
self.lin1 = self.lin0 = torch.nn.Linear(d_hid, d_hid)
def forward(self, x, y):
x = torch.mm(x, self.mm_param0)
x = x + y
x = self.lin0(x)
x = torch.relu(x)
pipe_split()
x = torch.mm(x, self.mm_param1)
x = self.lin1(x)
x = torch.relu(x)
return x
# MLP Layer
| ModelWithParamAlias |
python | openai__openai-python | src/openai/types/audio/translation.py | {
"start": 149,
"end": 193
} | class ____(BaseModel):
text: str
| Translation |
python | django__django | tests/gis_tests/geogapp/models.py | {
"start": 329,
"end": 566
} | class ____(NamedModel):
point = models.PointField(geography=True, unique=True)
class Meta:
required_db_features = {
"supports_geography",
"supports_geometry_field_unique_index",
}
| CityUnique |
python | python-openxml__python-docx | tests/image/test_image.py | {
"start": 10926,
"end": 11922
} | class ____:
def it_defines_content_type_as_an_abstract_property(self):
base_image_header = BaseImageHeader(None, None, None, None)
with pytest.raises(NotImplementedError):
base_image_header.content_type
def it_defines_default_ext_as_an_abstract_property(self):
base_image_header = BaseImageHeader(None, None, None, None)
with pytest.raises(NotImplementedError):
base_image_header.default_ext
def it_knows_the_image_dimensions(self):
px_width, px_height = 42, 24
image_header = BaseImageHeader(px_width, px_height, None, None)
assert image_header.px_width == px_width
assert image_header.px_height == px_height
def it_knows_the_horz_and_vert_dpi_of_the_image(self):
horz_dpi, vert_dpi = 42, 24
image_header = BaseImageHeader(None, None, horz_dpi, vert_dpi)
assert image_header.horz_dpi == horz_dpi
assert image_header.vert_dpi == vert_dpi
| DescribeBaseImageHeader |
python | django__django | tests/proxy_model_inheritance/tests.py | {
"start": 280,
"end": 1113
} | class ____(TransactionTestCase):
"""
Proxy model inheritance across apps can result in migrate not creating the
table for the proxied model (as described in #12286). This test creates two
dummy apps and calls migrate, then verifies that the table has been
created.
"""
available_apps = []
def test_table_exists(self):
with extend_sys_path(os.path.dirname(os.path.abspath(__file__))):
with self.modify_settings(INSTALLED_APPS={"append": ["app1", "app2"]}):
call_command("migrate", verbosity=0, run_syncdb=True)
from app1.models import ProxyModel
from app2.models import NiceModel
self.assertEqual(NiceModel.objects.count(), 0)
self.assertEqual(ProxyModel.objects.count(), 0)
| ProxyModelInheritanceTests |
python | doocs__leetcode | solution/3000-3099/3086.Minimum Moves to Pick K Ones/Solution.py | {
"start": 0,
"end": 1398
} | class ____:
def minimumMoves(self, nums: List[int], k: int, maxChanges: int) -> int:
n = len(nums)
cnt = [0] * (n + 1)
s = [0] * (n + 1)
for i, x in enumerate(nums, 1):
cnt[i] = cnt[i - 1] + x
s[i] = s[i - 1] + i * x
ans = inf
max = lambda x, y: x if x > y else y
min = lambda x, y: x if x < y else y
for i, x in enumerate(nums, 1):
t = 0
need = k - x
for j in (i - 1, i + 1):
if need > 0 and 1 <= j <= n and nums[j - 1] == 1:
need -= 1
t += 1
c = min(need, maxChanges)
need -= c
t += c * 2
if need <= 0:
ans = min(ans, t)
continue
l, r = 2, max(i - 1, n - i)
while l <= r:
mid = (l + r) >> 1
l1, r1 = max(1, i - mid), max(0, i - 2)
l2, r2 = min(n + 1, i + 2), min(n, i + mid)
c1 = cnt[r1] - cnt[l1 - 1]
c2 = cnt[r2] - cnt[l2 - 1]
if c1 + c2 >= need:
t1 = c1 * i - (s[r1] - s[l1 - 1])
t2 = s[r2] - s[l2 - 1] - c2 * i
ans = min(ans, t + t1 + t2)
r = mid - 1
else:
l = mid + 1
return ans
| Solution |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/vector/dict_info_to_list.py | {
"start": 313,
"end": 6628
} | class ____(VectorWrapper):
"""Converts infos of vectorized environments from ``dict`` to ``List[dict]``.
This wrapper converts the info format of a
vector environment from a dictionary to a list of dictionaries.
This wrapper is intended to be used around vectorized
environments. If using other wrappers that perform
operation on info like `RecordEpisodeStatistics` this
need to be the outermost wrapper.
i.e. ``DictInfoToList(RecordEpisodeStatistics(vector_env))``
Example:
>>> import numpy as np
>>> dict_info = {
... "k": np.array([0., 0., 0.5, 0.3]),
... "_k": np.array([False, False, True, True])
... }
...
>>> list_info = [{}, {}, {"k": 0.5}, {"k": 0.3}]
Example for vector environments:
>>> import numpy as np
>>> import gymnasium as gym
>>> envs = gym.make_vec("CartPole-v1", num_envs=3)
>>> obs, info = envs.reset(seed=123)
>>> info
{}
>>> envs = DictInfoToList(envs)
>>> obs, info = envs.reset(seed=123)
>>> info
[{}, {}, {}]
Another example for vector environments:
>>> import numpy as np
>>> import gymnasium as gym
>>> envs = gym.make_vec("HalfCheetah-v5", num_envs=2)
>>> _ = envs.reset(seed=123)
>>> _ = envs.action_space.seed(123)
>>> _, _, _, _, infos = envs.step(envs.action_space.sample())
>>> infos
{'x_position': array([0.03332211, 0.10172355]), '_x_position': array([ True, True]), 'x_velocity': array([-0.06296527, 0.89345848]), '_x_velocity': array([ True, True]), 'reward_forward': array([-0.06296527, 0.89345848]), '_reward_forward': array([ True, True]), 'reward_ctrl': array([-0.24503504, -0.21944423], dtype=float32), '_reward_ctrl': array([ True, True])}
>>> envs = DictInfoToList(envs)
>>> _ = envs.reset(seed=123)
>>> _ = envs.action_space.seed(123)
>>> _, _, _, _, infos = envs.step(envs.action_space.sample())
>>> infos # doctest: +ELLIPSIS
[{'x_position': np.float64(0.0333221...), 'x_velocity': np.float64(-0.0629652...), 'reward_forward': np.float64(-0.0629652...), 'reward_ctrl': np.float32(-0.2450350...)}, {'x_position': np.float64(0.1017235...), 'x_velocity': np.float64(0.8934584...), 'reward_forward': np.float64(0.8934584...), 'reward_ctrl': np.float32(-0.2194442...)}]
Change logs:
* v0.24.0 - Initially added as ``VectorListInfo``
* v1.0.0 - Renamed to ``DictInfoToList``
"""
def __init__(self, env: VectorEnv):
"""This wrapper will convert the info into the list format.
Args:
env (Env): The environment to apply the wrapper
"""
super().__init__(env)
def step(
self, actions: ActType
) -> tuple[ObsType, ArrayType, ArrayType, ArrayType, list[dict[str, Any]]]:
"""Steps through the environment, convert dict info to list."""
observation, reward, terminated, truncated, infos = self.env.step(actions)
assert isinstance(infos, dict)
list_info = self._convert_info_to_list(infos)
return observation, reward, terminated, truncated, list_info
def reset(
self,
*,
seed: int | list[int] | None = None,
options: dict[str, Any] | None = None,
) -> tuple[ObsType, list[dict[str, Any]]]:
"""Resets the environment using kwargs."""
obs, infos = self.env.reset(seed=seed, options=options)
assert isinstance(infos, dict)
list_info = self._convert_info_to_list(infos)
return obs, list_info
def _convert_info_to_list(self, vector_infos: dict) -> list[dict[str, Any]]:
"""Convert the dict info to list.
Convert the dict info of the vectorized environment
into a list of dictionaries where the i-th dictionary
has the info of the i-th environment.
Args:
vector_infos (dict): info dict coming from the env.
Returns:
list_info (list): converted info.
"""
list_info = [{} for _ in range(self.num_envs)]
for key, value in vector_infos.items():
if key.startswith("_"):
continue
binary_key = f"_{key}"
if isinstance(value, dict):
value_list_info = self._convert_info_to_list(value)
assert (
len(value_list_info) == self.num_envs
), f"Expects {value_list_info} to have length equal to the num-envs ({self.num_envs}), actual length is {len(value_list_info)}"
if binary_key in vector_infos:
assert (
len(vector_infos[binary_key]) == self.num_envs
), f"Expects {vector_infos[binary_key]} to have length equal to the num-envs ({self.num_envs}), actual length is {len(vector_infos[binary_key])}"
for env_num, (env_info, has_info) in enumerate(
zip(value_list_info, vector_infos[binary_key])
):
if has_info:
list_info[env_num][key] = env_info
else:
for env_num, sub_value in enumerate(value_list_info):
list_info[env_num][key] = sub_value
else:
assert isinstance(value, np.ndarray)
assert (
len(value) == self.num_envs
), f"Expects {value} to have length equal to the num-envs ({self.num_envs}), actual length is {len(value)}"
if binary_key in vector_infos:
assert (
len(vector_infos[binary_key]) == self.num_envs
), f"Expects {vector_infos[binary_key]} to have length equal to the num-envs ({self.num_envs}), actual length is {len(vector_infos[binary_key])}"
for env_num, has_info in enumerate(vector_infos[binary_key]):
if has_info:
list_info[env_num][key] = value[env_num]
else:
for env_num, sub_value in enumerate(value):
list_info[env_num][key] = sub_value
return list_info
| DictInfoToList |
python | sqlalchemy__sqlalchemy | test/perf/compiled_extensions/result.py | {
"start": 441,
"end": 5535
} | class ____(Case):
@classmethod
def init_class(cls):
# 3-col
cls.def3_plain = Definition(list("abc"))
cls.def3_1proc = Definition(list("abc"), [None, str, None])
cls.def3_tf = Definition(list("abc"), tuplefilter=itemgetter(1, 2))
cls.def3_1proc_tf = Definition(
list("abc"), [None, str, None], itemgetter(1, 2)
)
cls.data3_100 = [(i, i + i, i - 1) for i in range(100)]
cls.data3_1000 = [(i, i + i, i - 1) for i in range(1000)]
cls.data3_10000 = [(i, i + i, i - 1) for i in range(10000)]
cls.make_test_cases("row3col", "def3_", "data3_")
# 21-col
cols = [f"c_{i}" for i in range(21)]
cls.def21_plain = Definition(cols)
cls.def21_7proc = Definition(cols, [None, str, None] * 7)
cls.def21_tf = Definition(
cols, tuplefilter=itemgetter(1, 2, 9, 17, 18)
)
cls.def21_7proc_tf = Definition(
cols, [None, str, None] * 7, itemgetter(1, 2, 9, 17, 18)
)
cls.data21_100 = [(i, i + i, i - 1) * 7 for i in range(100)]
cls.data21_1000 = [(i, i + i, i - 1) * 7 for i in range(1000)]
cls.data21_10000 = [(i, i + i, i - 1) * 7 for i in range(10000)]
cls.make_test_cases("row21col", "def21_", "data21_")
@classmethod
def make_test_cases(cls, prefix: str, def_prefix: str, data_prefix: str):
all_defs = [
(k, v) for k, v in vars(cls).items() if k.startswith(def_prefix)
]
all_data = [
(k, v) for k, v in vars(cls).items() if k.startswith(data_prefix)
]
assert all_defs and all_data
def make_case(name, definition, data, number):
init_args = cls.get_init_args_callable(definition, data)
def go_all(self):
result = self.impl(*init_args())
result.all()
setattr(cls, name + "_all", test_case(go_all, number=number))
def go_all_uq(self):
result = self.impl(*init_args()).unique()
result.all()
setattr(cls, name + "_all_uq", test_case(go_all_uq, number=number))
def go_iter(self):
result = self.impl(*init_args())
for _ in result:
pass
setattr(cls, name + "_iter", test_case(go_iter, number=number))
def go_iter_uq(self):
result = self.impl(*init_args()).unique()
for _ in result:
pass
setattr(
cls, name + "_iter_uq", test_case(go_iter_uq, number=number)
)
def go_many(self):
result = self.impl(*init_args())
while result.fetchmany(10):
pass
setattr(cls, name + "_many", test_case(go_many, number=number))
def go_many_uq(self):
result = self.impl(*init_args()).unique()
while result.fetchmany(10):
pass
setattr(
cls, name + "_many_uq", test_case(go_many_uq, number=number)
)
def go_one(self):
result = self.impl(*init_args())
while result.fetchone() is not None:
pass
setattr(cls, name + "_one", test_case(go_one, number=number))
def go_one_uq(self):
result = self.impl(*init_args()).unique()
while result.fetchone() is not None:
pass
setattr(cls, name + "_one_uq", test_case(go_one_uq, number=number))
def go_scalar_all(self):
result = self.impl(*init_args())
result.scalars().all()
setattr(
cls, name + "_sc_all", test_case(go_scalar_all, number=number)
)
def go_scalar_iter(self):
result = self.impl(*init_args())
rs = result.scalars()
for _ in rs:
pass
setattr(
cls,
name + "_sc_iter",
test_case(go_scalar_iter, number=number),
)
def go_scalar_many(self):
result = self.impl(*init_args())
rs = result.scalars()
while rs.fetchmany(10):
pass
setattr(
cls,
name + "_sc_many",
test_case(go_scalar_many, number=number),
)
for (def_name, definition), (data_name, data) in product(
all_defs, all_data
):
name = (
f"{prefix}_{def_name.removeprefix(def_prefix)}_"
f"{data_name.removeprefix(data_prefix)}"
)
number = 500 if data_name.endswith("10000") else None
make_case(name, definition, data, number)
@classmethod
def get_init_args_callable(
cls, definition: Definition, data: list
) -> Callable:
raise NotImplementedError
| _CommonResult |
python | getsentry__sentry | src/sentry/workflow_engine/buffer/batch_client.py | {
"start": 4508,
"end": 6113
} | class ____:
"""
Project-specific client for interacting with batch processing of delayed workflows.
This is used for managing the hash (aka dictionary) of group-to-event data used to
aggregate event data that needs to be processed.
"""
def __init__(self, project_id: int, buffer: RedisHashSortedSetBuffer) -> None:
self.project_id = project_id
self._buffer = buffer
def _filters(self, batch_key: str | None) -> Mapping[str, int | str]:
filters: dict[str, int | str] = {"project_id": self.project_id}
if batch_key:
filters["batch_key"] = batch_key
return filters
def delete_hash_fields(self, batch_key: str | None, fields: list[str]) -> None:
"""Delete specific fields from the workflow hash."""
self._buffer.delete_hash(model=Workflow, filters=self._filters(batch_key), fields=fields)
def get_hash_length(self, batch_key: str | None = None) -> int:
"""Get the number of fields in the workflow hash."""
return self._buffer.get_hash_length(model=Workflow, filters=self._filters(batch_key))
def get_hash_data(self, batch_key: str | None = None) -> dict[str, str]:
"""Fetch all group-to-event data from the workflow hash."""
return self._buffer.get_hash(model=Workflow, filters=self._filters(batch_key))
def push_to_hash(self, batch_key: str | None, data: dict[str, str]) -> None:
"""Push data to the workflow hash in bulk."""
self._buffer.push_to_hash_bulk(model=Workflow, filters=self._filters(batch_key), data=data)
| ProjectDelayedWorkflowClient |
python | huggingface__transformers | src/transformers/models/swin/modeling_swin.py | {
"start": 5202,
"end": 7250
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Classification (or regression if config.num_labels==1) loss.
logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
Classification (or regression if config.num_labels==1) scores (before SoftMax).
reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
shape `(batch_size, hidden_size, height, width)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
include the spatial dimensions.
"""
loss: Optional[torch.FloatTensor] = None
logits: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
def window_partition(input_feature, window_size):
"""
Partitions the given input into windows.
"""
batch_size, height, width, num_channels = input_feature.shape
input_feature = input_feature.view(
batch_size, height // window_size, window_size, width // window_size, window_size, num_channels
)
windows = input_feature.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, num_channels)
return windows
def window_reverse(windows, window_size, height, width):
"""
Merges windows to produce higher resolution features.
"""
num_channels = windows.shape[-1]
windows = windows.view(-1, height // window_size, width // window_size, window_size, window_size, num_channels)
windows = windows.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, height, width, num_channels)
return windows
| SwinImageClassifierOutput |
python | doocs__leetcode | solution/2400-2499/2405.Optimal Partition of String/Solution.py | {
"start": 0,
"end": 267
} | class ____:
def partitionString(self, s: str) -> int:
ans, mask = 1, 0
for x in map(lambda c: ord(c) - ord("a"), s):
if mask >> x & 1:
ans += 1
mask = 0
mask |= 1 << x
return ans
| Solution |
python | ray-project__ray | python/ray/tune/schedulers/pb2_utils.py | {
"start": 225,
"end": 5744
} | class ____(Kern):
"""Time varying squared exponential kernel.
For more info see the TV-GP-UCB paper:
http://proceedings.mlr.press/v51/bogunovic16.pdf
"""
def __init__(
self, input_dim, variance=1.0, lengthscale=1.0, epsilon=0.0, active_dims=None
):
super().__init__(input_dim, active_dims, "time_se")
self.variance = Param("variance", variance)
self.lengthscale = Param("lengthscale", lengthscale)
self.epsilon = Param("epsilon", epsilon)
self.link_parameters(self.variance, self.lengthscale, self.epsilon)
def K(self, X, X2):
# time must be in the far left column
if self.epsilon > 0.5: # 0.5
self.epsilon = 0.5
if X2 is None:
X2 = np.copy(X)
T1 = X[:, 0].reshape(-1, 1)
T2 = X2[:, 0].reshape(-1, 1)
dists = pairwise_distances(T1, T2, "cityblock")
timekernel = (1 - self.epsilon) ** (0.5 * dists)
X = X[:, 1:]
X2 = X2[:, 1:]
RBF = self.variance * np.exp(
-np.square(euclidean_distances(X, X2)) / self.lengthscale
)
return RBF * timekernel
def Kdiag(self, X):
return self.variance * np.ones(X.shape[0])
def update_gradients_full(self, dL_dK, X, X2):
if X2 is None:
X2 = np.copy(X)
T1 = X[:, 0].reshape(-1, 1)
T2 = X2[:, 0].reshape(-1, 1)
X = X[:, 1:]
X2 = X2[:, 1:]
dist2 = np.square(euclidean_distances(X, X2)) / self.lengthscale
dvar = np.exp(-np.square((euclidean_distances(X, X2)) / self.lengthscale))
dl = -(
2 * euclidean_distances(X, X2) ** 2 * self.variance * np.exp(-dist2)
) * self.lengthscale ** (-2)
n = pairwise_distances(T1, T2, "cityblock") / 2
deps = -n * (1 - self.epsilon) ** (n - 1)
self.variance.gradient = np.sum(dvar * dL_dK)
self.lengthscale.gradient = np.sum(dl * dL_dK)
self.epsilon.gradient = np.sum(deps * dL_dK)
def normalize(data, wrt):
"""Normalize data to be in range (0,1), with respect to (wrt) boundaries,
which can be specified.
"""
return (data - np.min(wrt, axis=0)) / (
np.max(wrt, axis=0) - np.min(wrt, axis=0) + 1e-8
)
def standardize(data):
"""Standardize to be Gaussian N(0,1). Clip final values."""
data = (data - np.mean(data, axis=0)) / (np.std(data, axis=0) + 1e-8)
return np.clip(data, -2, 2)
def UCB(m, m1, x, fixed, kappa=None):
"""UCB acquisition function. Interesting points to note:
1) We concat with the fixed points, because we are not optimizing wrt
these. This is the Reward and Time, which we can't change. We want
to find the best hyperparameters *given* the reward and time.
2) We use m to get the mean and m1 to get the variance. If we already
have trials running, then m1 contains this information. This reduces
the variance at points currently running, even if we don't have
their label.
Ref: https://jmlr.org/papers/volume15/desautels14a/desautels14a.pdf
"""
c1 = 0.2
c2 = 0.4
beta_t = c1 + max(0, np.log(c2 * m.X.shape[0]))
kappa = np.sqrt(beta_t) if kappa is None else kappa
xtest = np.concatenate((fixed.reshape(-1, 1), np.array(x).reshape(-1, 1))).T
try:
preds = m.predict(xtest)
preds = m.predict(xtest)
mean = preds[0][0][0]
except ValueError:
mean = -9999
try:
preds = m1.predict(xtest)
var = preds[1][0][0]
except ValueError:
var = 0
return mean + kappa * var
def optimize_acq(func, m, m1, fixed, num_f):
"""Optimize acquisition function."""
opts = {"maxiter": 200, "maxfun": 200, "disp": False}
T = 10
best_value = -999
best_theta = m1.X[0, :]
bounds = [(0, 1) for _ in range(m.X.shape[1] - num_f)]
for ii in range(T):
x0 = np.random.uniform(0, 1, m.X.shape[1] - num_f)
res = minimize(
lambda x: -func(m, m1, x, fixed),
x0,
bounds=bounds,
method="L-BFGS-B",
options=opts,
)
val = func(m, m1, res.x, fixed)
if val > best_value:
best_value = val
best_theta = res.x
return np.clip(best_theta, 0, 1)
def select_length(Xraw, yraw, bounds, num_f):
"""Select the number of datapoints to keep, using cross validation"""
min_len = 200
if Xraw.shape[0] < min_len:
return Xraw.shape[0]
else:
length = min_len - 10
scores = []
while length + 10 <= Xraw.shape[0]:
length += 10
base_vals = np.array(list(bounds.values())).T
X_len = Xraw[-length:, :]
y_len = yraw[-length:]
oldpoints = X_len[:, :num_f]
old_lims = np.concatenate(
(np.max(oldpoints, axis=0), np.min(oldpoints, axis=0))
).reshape(2, oldpoints.shape[1])
limits = np.concatenate((old_lims, base_vals), axis=1)
X = normalize(X_len, limits)
y = standardize(y_len).reshape(y_len.size, 1)
kernel = TV_SquaredExp(
input_dim=X.shape[1], variance=1.0, lengthscale=1.0, epsilon=0.1
)
m = GPy.models.GPRegression(X, y, kernel)
m.optimize(messages=True)
scores.append(m.log_likelihood())
idx = np.argmax(scores)
length = (idx + int((min_len / 10))) * 10
return length
| TV_SquaredExp |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/components/workspace_component/component.py | {
"start": 6447,
"end": 6652
} | class ____(dg.Model):
by_name: Annotated[
Sequence[str],
pydantic.Field(..., description="A list of connection names to include in the collection."),
]
| AirbyteConnectionSelectorByName |
python | getsentry__sentry | src/sentry/integrations/opsgenie/handlers/opsgenie_handler.py | {
"start": 818,
"end": 1795
} | class ____(IntegrationActionHandler):
group = ActionHandler.Group.NOTIFICATION
provider_slug = IntegrationProviderSlug.OPSGENIE
config_schema = ONCALL_ACTION_CONFIG_SCHEMA
data_schema = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"properties": {
"priority": {
"type": "string",
"description": "The priority of the opsgenie action",
"enum": [*OPSGENIE_CUSTOM_PRIORITIES],
},
"additionalProperties": False,
},
}
@staticmethod
def get_config_transformer() -> ConfigTransformer | None:
return TargetTypeConfigTransformer.from_config_schema(OpsgenieActionHandler.config_schema)
@staticmethod
def execute(
job: WorkflowEventData,
action: Action,
detector: Detector,
) -> None:
execute_via_group_type_registry(job, action, detector)
| OpsgenieActionHandler |
python | pandas-dev__pandas | pandas/tests/libs/test_hashtable.py | {
"start": 1379,
"end": 8930
} | class ____:
def test_get_set_contains_len(self, table_type, dtype):
index = 5
table = table_type(55)
assert len(table) == 0
assert index not in table
table.set_item(index, 42)
assert len(table) == 1
assert index in table
assert table.get_item(index) == 42
table.set_item(index + 1, 41)
assert index in table
assert index + 1 in table
assert len(table) == 2
assert table.get_item(index) == 42
assert table.get_item(index + 1) == 41
table.set_item(index, 21)
assert index in table
assert index + 1 in table
assert len(table) == 2
assert table.get_item(index) == 21
assert table.get_item(index + 1) == 41
assert index + 2 not in table
table.set_item(index + 1, 21)
assert index in table
assert index + 1 in table
assert len(table) == 2
assert table.get_item(index) == 21
assert table.get_item(index + 1) == 21
with pytest.raises(KeyError, match=str(index + 2)):
table.get_item(index + 2)
def test_get_set_contains_len_mask(self, table_type, dtype):
if table_type == ht.PyObjectHashTable:
pytest.skip("Mask not supported for object")
index = 5
table = table_type(55, uses_mask=True)
assert len(table) == 0
assert index not in table
table.set_item(index, 42)
assert len(table) == 1
assert index in table
assert table.get_item(index) == 42
with pytest.raises(KeyError, match="NA"):
table.get_na()
table.set_item(index + 1, 41)
table.set_na(41)
assert pd.NA in table
assert index in table
assert index + 1 in table
assert len(table) == 3
assert table.get_item(index) == 42
assert table.get_item(index + 1) == 41
assert table.get_na() == 41
table.set_na(21)
assert index in table
assert index + 1 in table
assert len(table) == 3
assert table.get_item(index + 1) == 41
assert table.get_na() == 21
assert index + 2 not in table
with pytest.raises(KeyError, match=str(index + 2)):
table.get_item(index + 2)
def test_map_keys_to_values(self, table_type, dtype, writable):
# only Int64HashTable has this method
if table_type == ht.Int64HashTable:
N = 77
table = table_type()
keys = np.arange(N).astype(dtype)
vals = np.arange(N).astype(np.int64) + N
keys.flags.writeable = writable
vals.flags.writeable = writable
table.map_keys_to_values(keys, vals)
for i in range(N):
assert table.get_item(keys[i]) == i + N
def test_map_locations(self, table_type, dtype, writable):
N = 8
table = table_type()
keys = (np.arange(N) + N).astype(dtype)
keys.flags.writeable = writable
table.map_locations(keys)
for i in range(N):
assert table.get_item(keys[i]) == i
def test_map_locations_mask(self, table_type, dtype, writable):
if table_type == ht.PyObjectHashTable:
pytest.skip("Mask not supported for object")
N = 129 # must be > 128 to test GH#58924
table = table_type(uses_mask=True)
keys = (np.arange(N) + N).astype(dtype)
keys.flags.writeable = writable
mask = np.concatenate([np.repeat(False, N - 1), [True]], axis=0)
table.map_locations(keys, mask)
for i in range(N - 1):
assert table.get_item(keys[i]) == i
with pytest.raises(KeyError, match=re.escape(str(keys[N - 1]))):
table.get_item(keys[N - 1])
assert table.get_na() == N - 1
def test_lookup(self, table_type, dtype, writable):
N = 3
table = table_type()
keys = (np.arange(N) + N).astype(dtype)
keys.flags.writeable = writable
table.map_locations(keys)
result = table.lookup(keys)
expected = np.arange(N)
tm.assert_numpy_array_equal(result.astype(np.int64), expected.astype(np.int64))
def test_lookup_wrong(self, table_type, dtype):
if dtype in (np.int8, np.uint8):
N = 100
else:
N = 512
table = table_type()
keys = (np.arange(N) + N).astype(dtype)
table.map_locations(keys)
wrong_keys = np.arange(N).astype(dtype)
result = table.lookup(wrong_keys)
assert np.all(result == -1)
def test_lookup_mask(self, table_type, dtype, writable):
if table_type == ht.PyObjectHashTable:
pytest.skip("Mask not supported for object")
N = 3
table = table_type(uses_mask=True)
keys = (np.arange(N) + N).astype(dtype)
mask = np.array([False, True, False])
keys.flags.writeable = writable
table.map_locations(keys, mask)
result = table.lookup(keys, mask)
expected = np.arange(N)
tm.assert_numpy_array_equal(result.astype(np.int64), expected.astype(np.int64))
result = table.lookup(np.array([1 + N]).astype(dtype), np.array([False]))
tm.assert_numpy_array_equal(
result.astype(np.int64), np.array([-1], dtype=np.int64)
)
def test_unique(self, table_type, dtype, writable):
if dtype in (np.int8, np.uint8):
N = 88
else:
N = 1000
table = table_type()
expected = (np.arange(N) + N).astype(dtype)
keys = np.repeat(expected, 5)
keys.flags.writeable = writable
unique = table.unique(keys)
tm.assert_numpy_array_equal(unique, expected)
def test_tracemalloc_works(self, table_type, dtype):
if dtype in (np.int8, np.uint8):
N = 256
else:
N = 30000
keys = np.arange(N).astype(dtype)
with activated_tracemalloc():
table = table_type()
table.map_locations(keys)
used = get_allocated_khash_memory()
my_size = table.sizeof()
assert used == my_size
del table
assert get_allocated_khash_memory() == 0
def test_tracemalloc_for_empty(self, table_type, dtype):
with activated_tracemalloc():
table = table_type()
used = get_allocated_khash_memory()
my_size = table.sizeof()
assert used == my_size
del table
assert get_allocated_khash_memory() == 0
def test_get_state(self, table_type, dtype):
table = table_type(1000)
state = table.get_state()
assert state["size"] == 0
assert state["n_occupied"] == 0
assert "n_buckets" in state
assert "upper_bound" in state
@pytest.mark.parametrize("N", range(1, 110, 4))
def test_no_reallocation(self, table_type, dtype, N):
keys = np.arange(N).astype(dtype)
preallocated_table = table_type(N)
n_buckets_start = preallocated_table.get_state()["n_buckets"]
preallocated_table.map_locations(keys)
n_buckets_end = preallocated_table.get_state()["n_buckets"]
# original number of buckets was enough:
assert n_buckets_start == n_buckets_end
# check with clean table (not too much preallocated)
clean_table = table_type()
clean_table.map_locations(keys)
assert n_buckets_start == clean_table.get_state()["n_buckets"]
| TestHashTable |
python | PrefectHQ__prefect | tests/server/api/test_logs.py | {
"start": 3285,
"end": 5968
} | class ____:
@pytest.fixture()
async def logs(self, client, log_data):
await client.post(CREATE_LOGS_URL, json=log_data)
@pytest.fixture()
async def single_flow_run_log(self, client):
flow_run_logs = [
LogCreate(
name="prefect.flow_run",
level=80,
message="Full speed ahead!",
timestamp=NOW,
flow_run_id=uuid1(),
).model_dump(mode="json")
]
await client.post(CREATE_LOGS_URL, json=flow_run_logs)
yield flow_run_logs[0]
@pytest.fixture()
async def single_task_run_log(self, client):
flow_run_logs = [
LogCreate(
name="prefect.flow_run",
level=80,
message="Full speed ahead!",
timestamp=NOW,
flow_run_id=uuid1(),
task_run_id=uuid1(),
).model_dump(mode="json")
]
await client.post(CREATE_LOGS_URL, json=flow_run_logs)
yield flow_run_logs[0]
async def test_read_logs(self, client, logs):
response = await client.post(READ_LOGS_URL)
assert len(response.json()) == 2
async def test_read_logs_applies_log_filter(
self, logs, log_data, client, task_run_id
):
log_filter = {"logs": {"task_run_id": {"any_": [str(task_run_id)]}}}
response = await client.post(READ_LOGS_URL, json=log_filter)
data = response.json()
assert len(data) == 1
for log in data:
assert log["task_run_id"] == str(task_run_id)
async def test_read_logs_offset(self, client, logs):
response = await client.post(READ_LOGS_URL, json={"offset": 1, "limit": 1})
data = response.json()
assert len(data) == 1
async def test_read_logs_returns_empty_list(self, client):
response = await client.post(READ_LOGS_URL)
data = response.json()
assert data == []
async def test_read_logs_sort_by_timestamp_asc(self, client, logs):
response = await client.post(READ_LOGS_URL, json={"sort": "TIMESTAMP_ASC"})
api_logs = [Log(**log_data) for log_data in response.json()]
assert api_logs[0].timestamp < api_logs[1].timestamp
assert api_logs[0].message == "Ahoy, captain"
async def test_read_logs_sort_by_timestamp_desc(self, client, logs):
response = await client.post(READ_LOGS_URL, json={"sort": "TIMESTAMP_DESC"})
api_logs = [Log(**log_data) for log_data in response.json()]
assert api_logs[0].timestamp > api_logs[1].timestamp
assert api_logs[0].message == "Black flag ahead, captain!"
| TestReadLogs |
python | astropy__astropy | astropy/utils/masked/tests/test_function_helpers.py | {
"start": 34626,
"end": 36363
} | class ____(MaskedArraySetup):
def test_average(self):
o = np.average(self.ma)
assert_masked_equal(o, self.ma.mean())
o = np.average(self.ma, weights=self.mb, axis=-1)
expected = np.average(self.a, weights=self.b, axis=-1)
expected_mask = (self.mask_a | self.mask_b).any(-1)
assert_array_equal(o.unmasked, expected)
assert_array_equal(o.mask, expected_mask)
@pytest.mark.parametrize("kwargs", [{}, {"axis": 0}])
def test_ptp(self, kwargs):
o = np.ptp(self.ma, **kwargs)
expected = self.ma.max(**kwargs) - self.ma.min(**kwargs)
assert_array_equal(o.unmasked, expected.unmasked)
assert_array_equal(o.mask, expected.mask)
out = np.zeros_like(expected)
o2 = np.ptp(self.ma, out=out, **kwargs)
assert o2 is out
assert_array_equal(o2.unmasked, expected.unmasked)
assert_array_equal(o2.mask, expected.mask)
if NUMPY_LT_2_0:
# Method is removed in numpy 2.0.
o3 = self.ma.ptp(**kwargs)
assert_array_equal(o3.unmasked, expected.unmasked)
assert_array_equal(o3.mask, expected.mask)
def test_trace(self):
o = np.trace(self.ma)
expected = np.trace(self.a)
expected_mask = np.trace(self.mask_a).astype(bool)
assert_array_equal(o.unmasked, expected)
assert_array_equal(o.mask, expected_mask)
@pytest.mark.parametrize("axis", [0, 1, None])
def test_count_nonzero(self, axis):
o = np.count_nonzero(self.ma, axis=axis)
expected = np.count_nonzero(self.ma.filled(0), axis=axis)
assert_array_equal(o, expected)
@pytest.mark.filterwarnings("ignore:all-nan")
| TestReductionLikeFunctions |
python | Pylons__pyramid | tests/test_scripts/test_proutes.py | {
"start": 210,
"end": 25691
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.scripts.proutes import PRoutesCommand
return PRoutesCommand
def _makeOne(self):
cmd = self._getTargetClass()([])
cmd.bootstrap = dummy.DummyBootstrap()
cmd.get_config_loader = dummy.DummyLoader()
cmd.args.config_uri = '/foo/bar/myapp.ini#myapp'
return cmd
def _makeRegistry(self):
from pyramid.registry import Registry
registry = Registry()
registry.introspector = DummyIntrospector()
return registry
def _makeConfig(self, *arg, **kw):
from pyramid.config import Configurator
config = Configurator(*arg, **kw)
return config
def test_good_args(self):
cmd = self._getTargetClass()([])
cmd.bootstrap = dummy.DummyBootstrap()
cmd.get_config_loader = dummy.DummyLoader()
cmd.args.config_uri = '/foo/bar/myapp.ini#myapp'
cmd.args.config_args = ('a=1',)
route = dummy.DummyRoute('a', '/a')
mapper = dummy.DummyMapper(route)
cmd._get_mapper = lambda *arg: mapper
registry = self._makeRegistry()
cmd.bootstrap = dummy.DummyBootstrap(registry=registry)
L = []
cmd.out = lambda msg: L.append(msg)
cmd.run()
self.assertTrue('<unknown>' in ''.join(L))
def test_bad_args(self):
cmd = self._getTargetClass()([])
cmd.bootstrap = dummy.DummyBootstrap()
cmd.get_config_loader = dummy.DummyLoader()
cmd.args.config_uri = '/foo/bar/myapp.ini#myapp'
cmd.args.config_vars = ('a',)
route = dummy.DummyRoute('a', '/a')
mapper = dummy.DummyMapper(route)
cmd._get_mapper = lambda *arg: mapper
self.assertRaises(ValueError, cmd.run)
def test_no_routes(self):
command = self._makeOne()
mapper = dummy.DummyMapper()
command._get_mapper = lambda *arg: mapper
L = []
command.out = L.append
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(L, [])
def test_no_mapper(self):
command = self._makeOne()
command._get_mapper = lambda *arg: None
L = []
command.out = L.append
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(L, [])
def test_single_route_no_route_registered(self):
command = self._makeOne()
route = dummy.DummyRoute('a', '/a')
mapper = dummy.DummyMapper(route)
command._get_mapper = lambda *arg: mapper
registry = self._makeRegistry()
command.bootstrap = dummy.DummyBootstrap(registry=registry)
L = []
command.out = L.append
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
self.assertEqual(L[-1].split(), ['a', '/a', '<unknown>', '*'])
def test_route_with_no_slash_prefix(self):
command = self._makeOne()
route = dummy.DummyRoute('a', 'a')
mapper = dummy.DummyMapper(route)
command._get_mapper = lambda *arg: mapper
L = []
command.out = L.append
registry = self._makeRegistry()
command.bootstrap = dummy.DummyBootstrap(registry=registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
self.assertEqual(L[-1].split(), ['a', '/a', '<unknown>', '*'])
def test_single_route_no_views_registered(self):
from zope.interface import Interface
from pyramid.interfaces import IRouteRequest
registry = self._makeRegistry()
def view(): # pragma: no cover
pass
class IMyRoute(Interface):
pass
registry.registerUtility(IMyRoute, IRouteRequest, name='a')
command = self._makeOne()
route = dummy.DummyRoute('a', '/a')
mapper = dummy.DummyMapper(route)
command._get_mapper = lambda *arg: mapper
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
self.assertEqual(L[-1].split()[:3], ['a', '/a', '<unknown>'])
def test_single_route_one_view_registered(self):
from zope.interface import Interface
from pyramid.interfaces import IRouteRequest, IView, IViewClassifier
registry = self._makeRegistry()
def view(): # pragma: no cover
pass
class IMyRoute(Interface):
pass
registry.registerAdapter(
view, (IViewClassifier, IMyRoute, Interface), IView, ''
)
registry.registerUtility(IMyRoute, IRouteRequest, name='a')
command = self._makeOne()
route = dummy.DummyRoute('a', '/a')
mapper = dummy.DummyMapper(route)
command._get_mapper = lambda *arg: mapper
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()[:3]
self.assertEqual(
compare_to, ['a', '/a', 'tests.test_scripts.test_proutes.view']
)
def test_one_route_with_long_name_one_view_registered(self):
from zope.interface import Interface
from pyramid.interfaces import IRouteRequest, IView, IViewClassifier
registry = self._makeRegistry()
def view(): # pragma: no cover
pass
class IMyRoute(Interface):
pass
registry.registerAdapter(
view, (IViewClassifier, IMyRoute, Interface), IView, ''
)
registry.registerUtility(
IMyRoute, IRouteRequest, name='very_long_name_123'
)
command = self._makeOne()
route = dummy.DummyRoute(
'very_long_name_123', '/and_very_long_pattern_as_well'
)
mapper = dummy.DummyMapper(route)
command._get_mapper = lambda *arg: mapper
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()[:3]
self.assertEqual(
compare_to,
[
'very_long_name_123',
'/and_very_long_pattern_as_well',
'tests.test_scripts.test_proutes.view',
],
)
def test_class_view(self):
from pyramid.renderers import null_renderer as nr
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b')
config.add_view(
route_name='foo',
view=dummy.DummyView,
attr='view',
renderer=nr,
request_method='POST',
)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = [
'foo',
'/a/b',
'tests.test_scripts.dummy.DummyView.view',
'POST',
]
self.assertEqual(compare_to, expected)
def test_single_route_one_view_registered_with_factory(self):
from zope.interface import Interface
from pyramid.interfaces import IRouteRequest, IView, IViewClassifier
registry = self._makeRegistry()
def view(): # pragma: no cover
pass
class IMyRoot(Interface):
pass
class IMyRoute(Interface):
pass
registry.registerAdapter(
view, (IViewClassifier, IMyRoute, IMyRoot), IView, ''
)
registry.registerUtility(IMyRoute, IRouteRequest, name='a')
command = self._makeOne()
def factory(request): # pragma: no cover
pass
route = dummy.DummyRoute('a', '/a', factory=factory)
mapper = dummy.DummyMapper(route)
command._get_mapper = lambda *arg: mapper
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
self.assertEqual(L[-1].split()[:3], ['a', '/a', '<unknown>'])
def test_single_route_multiview_registered(self):
from zope.interface import Interface
from pyramid.interfaces import (
IMultiView,
IRouteRequest,
IViewClassifier,
)
registry = self._makeRegistry()
def view(): # pragma: no cover
pass
class IMyRoute(Interface):
pass
multiview1 = dummy.DummyMultiView(
view, context='context', view_name='a1'
)
registry.registerAdapter(
multiview1, (IViewClassifier, IMyRoute, Interface), IMultiView, ''
)
registry.registerUtility(IMyRoute, IRouteRequest, name='a')
command = self._makeOne()
route = dummy.DummyRoute('a', '/a')
mapper = dummy.DummyMapper(route)
command._get_mapper = lambda *arg: mapper
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()[:3]
view_module = 'tests.test_scripts.dummy'
view_str = '<tests.test_scripts.dummy.DummyMultiView'
final = f'{view_module}.{view_str}'
self.assertEqual(compare_to, ['a', '/a', final])
def test__get_mapper(self):
from pyramid.urldispatch import RoutesMapper
command = self._makeOne()
registry = self._makeRegistry()
result = command._get_mapper(registry)
self.assertEqual(result.__class__, RoutesMapper)
def test_one_route_all_methods_view_only_post(self):
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b')
config.add_view(
route_name='foo', view=view1, renderer=nr, request_method='POST'
)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = [
'foo',
'/a/b',
'tests.test_scripts.test_proutes.view1',
'POST',
]
self.assertEqual(compare_to, expected)
def test_one_route_only_post_view_all_methods(self):
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b', request_method='POST')
config.add_view(route_name='foo', view=view1, renderer=nr)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = [
'foo',
'/a/b',
'tests.test_scripts.test_proutes.view1',
'POST',
]
self.assertEqual(compare_to, expected)
def test_one_route_only_post_view_post_and_get(self):
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b', request_method='POST')
config.add_view(
route_name='foo',
view=view1,
renderer=nr,
request_method=('POST', 'GET'),
)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = [
'foo',
'/a/b',
'tests.test_scripts.test_proutes.view1',
'POST',
]
self.assertEqual(compare_to, expected)
def test_route_request_method_mismatch(self):
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b', request_method='POST')
config.add_view(
route_name='foo', view=view1, renderer=nr, request_method='GET'
)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = [
'foo',
'/a/b',
'tests.test_scripts.test_proutes.view1',
'<route',
'mismatch>',
]
self.assertEqual(compare_to, expected)
def test_route_static_views(self):
config = self._makeConfig(autocommit=True)
config.add_static_view('static', 'static', cache_max_age=3600)
path2 = os.path.normpath('/var/www/static')
config.add_static_view(name='static2', path=path2)
config.add_static_view(
name='pyramid_scaffold',
path='pyramid:scaffolds/starter/+package+/static',
)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 5)
expected = [
[
'__static/',
'/static/*subpath',
'tests.test_scripts:static/',
'*',
],
['__static2/', '/static2/*subpath', path2 + os.sep, '*'],
[
'__pyramid_scaffold/',
'/pyramid_scaffold/*subpath',
'pyramid:scaffolds/starter/+package+/static/',
'*',
],
]
for index, line in enumerate(L[2:]):
data = line.split()
self.assertEqual(data, expected[index])
def test_route_no_view(self):
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b', request_method='POST')
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = ['foo', '/a/b', '<unknown>', 'POST']
self.assertEqual(compare_to, expected)
def test_route_as_wsgiapp(self):
from pyramid.wsgi import wsgiapp2
config1 = self._makeConfig(autocommit=True)
def view1(context, request): # pragma: no cover
return 'view1'
config1.add_route('foo', '/a/b', request_method='POST')
config1.add_view(view=view1, route_name='foo')
config2 = self._makeConfig(autocommit=True)
config2.add_route('foo', '/a/b', request_method='POST')
config2.add_view(wsgiapp2(config1.make_wsgi_app()), route_name='foo')
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config2.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = ['foo', '/a/b', '<wsgiapp>', 'POST']
self.assertEqual(compare_to, expected)
def test_route_is_get_view_request_method_not_post(self):
from pyramid.config import not_
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b', request_method='GET')
config.add_view(
route_name='foo',
view=view1,
renderer=nr,
request_method=not_('POST'),
)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = [
'foo',
'/a/b',
'tests.test_scripts.test_proutes.view1',
'GET',
]
self.assertEqual(compare_to, expected)
def test_view_request_method_not_post(self):
from pyramid.config import not_
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b')
config.add_view(
route_name='foo',
view=view1,
renderer=nr,
request_method=not_('POST'),
)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = [
'foo',
'/a/b',
'tests.test_scripts.test_proutes.view1',
'!POST,*',
]
self.assertEqual(compare_to, expected)
def test_view_glob(self):
from pyramid.config import not_
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
def view2(context, request): # pragma: no cover
return 'view2'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b')
config.add_view(
route_name='foo',
view=view1,
renderer=nr,
request_method=not_('POST'),
)
config.add_route('bar', '/b/a')
config.add_view(
route_name='bar',
view=view2,
renderer=nr,
request_method=not_('POST'),
)
command = self._makeOne()
command.args.glob = '*foo*'
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = [
'foo',
'/a/b',
'tests.test_scripts.test_proutes.view1',
'!POST,*',
]
self.assertEqual(compare_to, expected)
def test_good_format(self):
from pyramid.config import not_
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b')
config.add_view(
route_name='foo',
view=view1,
renderer=nr,
request_method=not_('POST'),
)
command = self._makeOne()
command.args.glob = '*foo*'
command.args.format = 'method,name'
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = ['!POST,*', 'foo']
self.assertEqual(compare_to, expected)
self.assertEqual(L[0].split(), ['Method', 'Name'])
def test_bad_format(self):
from pyramid.config import not_
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b')
config.add_view(
route_name='foo',
view=view1,
renderer=nr,
request_method=not_('POST'),
)
command = self._makeOne()
command.args.glob = '*foo*'
command.args.format = 'predicates,name,pattern'
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
expected = (
"You provided invalid formats ['predicates']. "
"Available formats are ['name', 'pattern', 'view', 'method']"
)
result = command.run()
self.assertEqual(result, 2)
self.assertEqual(L[0], expected)
def test_config_format_ini_newlines(self):
from pyramid.config import not_
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b')
config.add_view(
route_name='foo',
view=view1,
renderer=nr,
request_method=not_('POST'),
)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
command.get_config_loader = dummy.DummyLoader(
{'proutes': {'format': 'method\nname'}}
)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = ['!POST,*', 'foo']
self.assertEqual(compare_to, expected)
self.assertEqual(L[0].split(), ['Method', 'Name'])
def test_config_format_ini_spaces(self):
from pyramid.config import not_
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b')
config.add_view(
route_name='foo',
view=view1,
renderer=nr,
request_method=not_('POST'),
)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
command.get_config_loader = dummy.DummyLoader(
{'proutes': {'format': 'method name'}}
)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = ['!POST,*', 'foo']
self.assertEqual(compare_to, expected)
self.assertEqual(L[0].split(), ['Method', 'Name'])
def test_config_format_ini_commas(self):
from pyramid.config import not_
from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
config = self._makeConfig(autocommit=True)
config.add_route('foo', '/a/b')
config.add_view(
route_name='foo',
view=view1,
renderer=nr,
request_method=not_('POST'),
)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
command.get_config_loader = dummy.DummyLoader(
{'proutes': {'format': 'method,name'}}
)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = ['!POST,*', 'foo']
self.assertEqual(compare_to, expected)
self.assertEqual(L[0].split(), ['Method', 'Name'])
def test_static_routes_included_in_list(self):
config = self._makeConfig(autocommit=True)
config.add_route('foo', 'http://example.com/bar.aspx', static=True)
command = self._makeOne()
L = []
command.out = L.append
command.bootstrap = dummy.DummyBootstrap(registry=config.registry)
result = command.run()
self.assertEqual(result, 0)
self.assertEqual(len(L), 3)
compare_to = L[-1].split()
expected = ['foo', 'http://example.com/bar.aspx', '<unknown>', '*']
self.assertEqual(compare_to, expected)
| TestPRoutesCommand |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 297348,
"end": 299002
} | class ____(ExternKernel):
def codegen(self, wrapper: PythonWrapperCodegen) -> None:
wrapper.codegen_multi_output(self)
if not self.skip_size_stride_alignment_checks:
self.codegen_size_asserts(wrapper)
self.codegen_alignment_asserts(wrapper)
def __init__(
self,
layout: OutputSpec,
input: IRNode,
indices: list[tuple[Any, ...]],
skip_size_stride_alignment_checks: bool = False,
) -> None:
super().__init__(None, layout, [input], ())
self.name = V.graph.register_buffer(self)
V.graph.register_operation(self)
self.indices = indices
self.skip_size_stride_alignment_checks = skip_size_stride_alignment_checks
@cache_on_self_and_args("MultiOutput")
def get_free_symbol_uses(
self, unbacked_only: bool = False
) -> OrderedSet[sympy.Symbol]:
input_node = self.inputs[0]
assert isinstance(input_node, IRNode), input_node
return input_node.get_free_symbol_uses(unbacked_only)
def should_allocate(self) -> bool:
return len(self.inputs) == 1 and (
isinstance(self.inputs[0], CppTemplateBuffer) # Grouped GEMM
)
def get_inputs_that_alias_output(self) -> Sequence[str]:
return [
inp.get_name()
for inp in self.inputs
if isinstance(inp, FallbackKernel)
and len(inp.get_inputs_that_alias_output()) > 0
]
# We just use a normal dataclass for MutableBox/TensorBox/StorageBox since
# they're mainly lowering-time constructs that we expect to mutate and such.
@dataclasses.dataclass
| MultiOutput |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_field_call.py | {
"start": 878,
"end": 1146
} | class ____:
field() # [invalid-field-call]
dc.field() # [invalid-field-call]
mc.field()
a: float = field(init=False)
b: float = dc.field(init=False)
c: list[float] = [field(), field()] # [invalid-field-call, invalid-field-call]
@dc.dataclass
| DC |
python | pypa__warehouse | tests/common/db/organizations.py | {
"start": 3923,
"end": 4409
} | class ____(WarehouseFactory):
class Meta:
model = OrganizationManualActivation
organization_id = factory.SelfAttribute("organization.id")
organization = factory.SubFactory(OrganizationFactory)
seat_limit = 10
expires = factory.LazyFunction(
lambda: datetime.date.today() + datetime.timedelta(days=365)
)
created_by_id = factory.SelfAttribute("created_by.id")
created_by = factory.SubFactory(UserFactory)
| OrganizationManualActivationFactory |
python | PrefectHQ__prefect | tests/test_tasks.py | {
"start": 103195,
"end": 105548
} | class ____:
async def test_user_logs_are_sent_to_orion(self, prefect_client):
@task
def my_task():
logger = get_run_logger()
logger.info("Hello world!")
@flow
def my_flow():
my_task()
my_flow()
# Logs don't always show up immediately with the new engine
logs = await _wait_for_logs(prefect_client)
assert "Hello world!" in {log.message for log in logs}
async def test_tracebacks_are_logged(self, prefect_client):
@task
def my_task():
logger = get_run_logger()
try:
x + y # noqa: F821
except Exception:
logger.error("There was an issue", exc_info=True)
@flow
def my_flow():
my_task()
my_flow()
logs = await _wait_for_logs(prefect_client)
error_log = [log.message for log in logs if log.level == 40].pop()
assert "NameError" in error_log
assert "x + y" in error_log
async def test_opt_out_logs_are_not_sent_to_api(self, prefect_client):
@task
def my_task():
logger = get_run_logger()
logger.info("Hello world!", extra={"send_to_api": False})
@flow
def my_flow():
my_task()
my_flow()
logs = await _wait_for_logs(prefect_client)
assert "Hello world!" not in {log.message for log in logs}
async def test_logs_are_given_correct_ids(self, prefect_client):
@task
def my_task():
logger = get_run_logger()
logger.info("Hello world!")
@flow
def my_flow():
return my_task(return_state=True)
task_state = my_flow()
flow_run_id = task_state.state_details.flow_run_id
task_run_id = task_state.state_details.task_run_id
logs = await _wait_for_logs(prefect_client, flow_run_id=flow_run_id)
assert logs, "There should be logs"
assert all([log.flow_run_id == flow_run_id for log in logs]), str(
[log for log in logs]
)
task_run_logs = [log for log in logs if log.task_run_id is not None]
assert task_run_logs, f"There should be task run logs in {logs}"
assert all([log.task_run_id == task_run_id for log in task_run_logs])
| TestTaskRunLogs |
python | Netflix__metaflow | metaflow/plugins/aws/batch/batch_client.py | {
"start": 1895,
"end": 1978
} | class ____(MetaflowException):
headline = "AWS Batch job error"
| BatchJobException |
python | ApeWorX__ape | src/ape/pytest/fixtures.py | {
"start": 14866,
"end": 17301
} | class ____(ManagerAccessMixin):
# NOTE: Avoid including links, markdown, or rst in method-docs
# for fixtures, as they are used in output from the command
# `ape test -q --fixture` (`pytest -q --fixture`).
def __init__(self, config_wrapper: "ConfigWrapper", isolation_manager: "IsolationManager"):
self.config_wrapper = config_wrapper
self.isolation_manager = isolation_manager
@pytest.fixture(scope="session")
def accounts(self) -> list["TestAccountAPI"]:
"""
A collection of pre-funded accounts.
"""
return self.account_manager.test_accounts
@pytest.fixture(scope="session")
def compilers(self):
"""
Access compiler manager directly.
"""
return self.compiler_manager
@pytest.fixture(scope="session")
def chain(self) -> "ChainManager":
"""
Manipulate the blockchain, such as mine or change the pending timestamp.
"""
return self.chain_manager
@pytest.fixture(scope="session")
def networks(self) -> "NetworkManager":
"""
Connect to other networks in your tests.
"""
return self.network_manager
@pytest.fixture(scope="session")
def project(self) -> "ProjectManager":
"""
Access contract types and dependencies.
"""
return self.local_project
@pytest.fixture(scope="session")
def Contract(self):
"""
Instantiate a reference to an on-chain contract
using its address (same as ``ape.Contract``).
"""
return self.chain_manager.contracts.instance_at
@pytest.fixture(scope="session")
def _session_isolation(self) -> Iterator[None]:
yield from self.isolation_manager.isolation(Scope.SESSION)
@pytest.fixture(scope="package")
def _package_isolation(self) -> Iterator[None]:
yield from self.isolation_manager.isolation(Scope.PACKAGE)
@pytest.fixture(scope="module")
def _module_isolation(self) -> Iterator[None]:
yield from self.isolation_manager.isolation(Scope.MODULE)
@pytest.fixture(scope="class")
def _class_isolation(self) -> Iterator[None]:
yield from self.isolation_manager.isolation(Scope.CLASS)
@pytest.fixture(scope="function")
def _function_isolation(self) -> Iterator[None]:
yield from self.isolation_manager.isolation(Scope.FUNCTION)
@dataclass
| PytestApeFixtures |
python | RaRe-Technologies__gensim | gensim/test/test_corpora.py | {
"start": 20025,
"end": 23437
} | class ____(CorpusTestCase):
def setUp(self):
self.corpus_class = textcorpus.TextCorpus
self.file_extension = '.txt'
def test_load_with_metadata(self):
fname = datapath('testcorpus.' + self.file_extension.lstrip('.'))
corpus = self.corpus_class(fname)
corpus.metadata = True
self.assertEqual(len(corpus), 9)
docs = list(corpus)
self.assertEqual(len(docs), 9)
for i, docmeta in enumerate(docs):
doc, metadata = docmeta
self.assertEqual(metadata[0], i)
def test_default_preprocessing(self):
lines = [
"Šéf chomutovských komunistů dostal poštou bílý prášek",
"this is a test for stopwords",
"zf tooth spaces "
]
expected = [
['Sef', 'chomutovskych', 'komunistu', 'dostal', 'postou', 'bily', 'prasek'],
['test', 'stopwords'],
['tooth', 'spaces']
]
corpus = self.corpus_from_lines(lines)
texts = list(corpus.get_texts())
self.assertEqual(expected, texts)
def corpus_from_lines(self, lines):
fpath = tempfile.mktemp()
with codecs.open(fpath, 'w', encoding='utf8') as f:
f.write('\n'.join(lines))
return self.corpus_class(fpath)
def test_sample_text(self):
lines = ["document%d" % i for i in range(10)]
corpus = self.corpus_from_lines(lines)
corpus.tokenizer = lambda text: text.split()
docs = [doc for doc in corpus.get_texts()]
sample1 = list(corpus.sample_texts(1))
self.assertEqual(len(sample1), 1)
self.assertIn(sample1[0], docs)
sample2 = list(corpus.sample_texts(len(lines)))
self.assertEqual(len(sample2), len(corpus))
for i in range(len(corpus)):
self.assertEqual(sample2[i], ["document%s" % i])
with self.assertRaises(ValueError):
list(corpus.sample_texts(len(corpus) + 1))
with self.assertRaises(ValueError):
list(corpus.sample_texts(-1))
def test_sample_text_length(self):
lines = ["document%d" % i for i in range(10)]
corpus = self.corpus_from_lines(lines)
corpus.tokenizer = lambda text: text.split()
sample1 = list(corpus.sample_texts(1, length=1))
self.assertEqual(sample1[0], ["document0"])
sample2 = list(corpus.sample_texts(2, length=2))
self.assertEqual(sample2[0], ["document0"])
self.assertEqual(sample2[1], ["document1"])
def test_sample_text_seed(self):
lines = ["document%d" % i for i in range(10)]
corpus = self.corpus_from_lines(lines)
sample1 = list(corpus.sample_texts(5, seed=42))
sample2 = list(corpus.sample_texts(5, seed=42))
self.assertEqual(sample1, sample2)
def test_save(self):
pass
def test_serialize(self):
pass
def test_serialize_compressed(self):
pass
def test_indexing(self):
pass
# Needed for the test_custom_tokenizer is the TestWikiCorpus class.
# Cannot be nested due to serializing.
def custom_tokenizer(content, token_min_len=2, token_max_len=15, lower=True):
return [
to_unicode(token.lower()) if lower else to_unicode(token) for token in content.split()
if token_min_len <= len(token) <= token_max_len and not token.startswith('_')
]
| TestTextCorpus |
python | PyCQA__flake8 | src/flake8/plugins/finder.py | {
"start": 826,
"end": 1312
} | class ____(NamedTuple):
"""Represents a plugin after being imported."""
plugin: Plugin
obj: Any
parameters: dict[str, bool]
@property
def entry_name(self) -> str:
"""Return the name given in the packaging metadata."""
return self.plugin.entry_point.name
@property
def display_name(self) -> str:
"""Return the name for use in user-facing / error messages."""
return f"{self.plugin.package}[{self.entry_name}]"
| LoadedPlugin |
python | readthedocs__readthedocs.org | readthedocs/projects/admin.py | {
"start": 13843,
"end": 14306
} | class ____(admin.ModelAdmin):
list_display = (
"name",
"value",
"domain_name",
"project_slug",
)
raw_id_fields = ("domain",)
search_fields = ("name", "domain__name", "project__slug")
model = HTTPHeader
def domain_name(self, http_header):
return http_header.domain.domain
def project_slug(self, http_header):
return http_header.domain.project.slug
@admin.register(Feature)
| HTTPHeaderAdmin |
python | realpython__materials | queue/src/queues.py | {
"start": 585,
"end": 666
} | class ____(Queue):
def dequeue(self):
return self._elements.pop()
| Stack |
python | crytic__slither | slither/tools/mutator/mutators/MIA.py | {
"start": 302,
"end": 2028
} | class ____(AbstractMutator): # pylint: disable=too-few-public-methods
NAME = "MIA"
HELP = '"if" construct around statement'
def _mutate(self) -> Dict:
result: Dict = {}
for function in self.contract.functions_and_modifiers_declared:
for node in function.nodes:
if not self.should_mutate_node(node):
continue
if node.type == NodeType.IF:
# Get the string
start = node.expression.source_mapping.start
stop = start + node.expression.source_mapping.length
old_str = node.source_mapping.content
line_no = node.source_mapping.lines
# Replace the expression with true and false
for value in ["true", "false"]:
new_str = value
create_patch_with_line(
result,
self.in_file,
start,
stop,
old_str,
new_str,
line_no[0],
)
if not isinstance(node.expression, UnaryOperation):
new_str = str(UnaryOperationType.BANG) + "(" + old_str + ")"
create_patch_with_line(
result,
self.in_file,
start,
stop,
old_str,
new_str,
line_no[0],
)
return result
| MIA |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride1.py | {
"start": 13095,
"end": 13213
} | class ____(Base7[T]):
# This should generate an error.
def method1(self, x: S) -> S:
return x
| Derived7_1 |
python | google__jax | jax/_src/core.py | {
"start": 21277,
"end": 24569
} | class ____:
name: str
# set for multi-output primitives.
multiple_results: bool = False
# set for call primitives processed in final style.
call_primitive: bool = False
# set for map primitives processed in final style.
map_primitive: bool = False
# set for ref primitives
ref_primitive: bool = False
# set for primitives that can skip canonicalization of values
skip_canonicalization: bool = False
is_effectful = None
def __init__(self, name: str):
self.name = name
def __repr__(self):
return f'{self.name}'
def bind(self, *args, **params):
args = args if self.skip_canonicalization else map(canonicalize_value, args)
return self._true_bind(*args, **params)
def _true_bind(self, *args, **params):
for arg in args:
if isinstance(arg, Tracer) and not arg._trace.is_valid():
raise escaped_tracer_error(arg)
# TODO: figure out how to handle function arguments for this assert
# assert (not config.enable_checks.value or
# all(isinstance(arg, Tracer) or valid_jaxtype(arg) for arg in args)), args
# This is equivalent to "with take_current_trace()", but the bind() code
# is called frequently and it's slightly faster to avoid using a context
# manager object.
prev_trace = trace_ctx.trace
trace_ctx.set_trace(eval_trace)
try:
return self.bind_with_trace(prev_trace, args, params)
finally:
trace_ctx.set_trace(prev_trace)
def bind_with_trace(self, trace, args, params):
# TODO(mattjj,dougalm): remove this block?
try: in_type = map(typeof, args)
except: pass # try lojax error message
else:
if self.is_high(*in_type, **params) and trace.requires_low:
with set_current_trace(trace):
return self.to_lojax(*args, **params) # type: ignore
return trace.process_primitive(self, args, params)
trace.process_primitive(self, args, params) # may raise lojax error
raise Exception(f"couldn't apply typeof to args: {args}")
def def_impl(self, impl):
self.impl = impl
return impl
def def_abstract_eval(self, abstract_eval):
self.abstract_eval = _effect_free_abstract_eval(abstract_eval)
return abstract_eval
def def_effectful_abstract_eval(self, effectful_abstract_eval):
self.abstract_eval = effectful_abstract_eval
return effectful_abstract_eval
def def_effectful_abstract_eval2(self, abstract_eval):
self.abstract_eval = _generic_effectful_abstract_eval(abstract_eval, self)
return abstract_eval
def def_bind_with_trace(self, bind_with_trace):
self.bind_with_trace = bind_with_trace
return bind_with_trace
def impl(self, *args, **params):
raise NotImplementedError("Evaluation rule for '{}' not implemented"
.format(self.name))
def abstract_eval(self, *args, **params):
raise NotImplementedError("Abstract evaluation for '{}' not implemented"
.format(self.name))
def get_bind_params(self, params):
return [], params
def is_high(self, *avals, **params) -> bool:
return False
def _effect_free_abstract_eval(abstract_eval):
def abstract_eval_(*args, **kwargs):
return abstract_eval(*args, **kwargs), no_effects
return abstract_eval_
@dataclass(frozen=True)
| Primitive |
python | astropy__astropy | astropy/visualization/interval.py | {
"start": 6813,
"end": 7813
} | class ____(BaseInterval):
"""
Interval based on a symmetric radius away from a midpoint.
Parameters
----------
radius : float or None
The amount the interval extends to either side of the midpoint, so the total
interval is twice this value. If None, the radius is automatically
determined such that the resulting interval contains both the image minimum
and maximum (ignoring NaNs).
midpoint : float, optional
The midpoint of the symmetric interval. Defaults to zero.
"""
def __init__(self, radius=None, *, midpoint=0):
self.radius = radius
self.midpoint = midpoint
def get_limits(self, values):
radius = self.radius
if radius is None:
values = self._process_values(values)
radius = np.max(
[np.max(values) - self.midpoint, self.midpoint - np.min(values)]
)
return self.midpoint - radius, self.midpoint + radius
| SymmetricInterval |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol1.py | {
"start": 486,
"end": 569
} | class ____(Protocol[T_contra]):
def send(self, data: T_contra) -> int: ...
| Sender |
python | pandas-dev__pandas | pandas/tests/frame/test_subclass.py | {
"start": 26131,
"end": 26245
} | class ____(DataFrame):
"""A subclass of DataFrame that does not define a constructor."""
| SimpleDataFrameSubClass |
python | pyparsing__pyparsing | examples/antlr_grammar_tests.py | {
"start": 138,
"end": 2964
} | class ____(unittest.TestCase):
def testOptionsSpec(self):
text = """options {
language = Python;
}"""
antlr_grammar.optionsSpec.parse_string(text) # @UndefinedVariable
def testTokensSpec(self):
text = """tokens {
PLUS = '+' ;
MINUS = '-' ;
MULT = '*' ;
DIV = '/' ;
}"""
antlr_grammar.tokensSpec.parse_string(text) # @UndefinedVariable
def testBlock(self):
text = """( PLUS | MINUS )"""
antlr_grammar.block.parse_string(text) # @UndefinedVariable
def testRule(self):
text = """expr : term ( ( PLUS | MINUS ) term )* ;"""
antlr_grammar.rule.parse_string(text) # @UndefinedVariable
def testLexerRule(self):
text = """fragment DIGIT : '0'..'9' ;"""
antlr_grammar.rule.parse_string(text) # @UndefinedVariable
def testLexerRule2(self):
text = """WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { $channel = HIDDEN; } ;"""
# antlr_grammar.rule.parse_string(text) #@UndefinedVariable
def testGrammar(self):
text = """grammar SimpleCalc;
options {
language = Python;
}
tokens {
PLUS = '+' ;
MINUS = '-' ;
MULT = '*' ;
DIV = '/' ;
}
/*------------------------------------------------------------------
* PARSER RULES
*------------------------------------------------------------------*/
expr : term ( ( PLUS | MINUS ) term )* ;
term : factor ( ( MULT | DIV ) factor )* ;
factor : NUMBER ;
/*------------------------------------------------------------------
* LEXER RULES
*------------------------------------------------------------------*/
NUMBER : (DIGIT)+ ;
/* WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { $channel = HIDDEN; } ; */
fragment DIGIT : '0'..'9' ;"""
antlrGrammarTree = antlr_grammar.grammarDef.parse_string(
text
) # @UndefinedVariable
pyparsingRules = antlr_grammar.antlrConverter(antlrGrammarTree)
pyparsingRule = pyparsingRules["expr"]
pyparsingTree = pyparsingRule.parse_string("2 - 5 * 42 + 7 / 25")
pyparsingTreeList = pyparsingTree.as_list()
print(pyparsingTreeList)
self.assertEqual(
pyparsingTreeList,
[
[
[["2"], []],
[
["-", [["5"], [["*", ["4", "2"]]]]],
["+", [["7"], [["/", ["2", "5"]]]]],
],
]
],
)
if __name__ == "__main__":
# import sys;sys.argv = ['', 'Test.testOptionsSpec']
unittest.main()
| Test |
python | fluentpython__example-code | 12-inheritance/diamond.py | {
"start": 123,
"end": 186
} | class ____(A):
def pong(self):
print('PONG:', self)
| C |
python | ansible__ansible | lib/ansible/plugins/test/core.py | {
"start": 9862,
"end": 11201
} | class ____(object):
""" Ansible core jinja2 tests """
def tests(self):
return {
# failure testing
'failed': failed,
'failure': failed,
'succeeded': success,
'success': success,
'successful': success,
'reachable': reachable,
'unreachable': unreachable,
'timedout': timedout,
# changed testing
'changed': changed,
'change': changed,
# skip testing
'skipped': skipped,
'skip': skipped,
# async testing
'finished': finished,
'started': started,
# regex
'match': match,
'search': search,
'regex': regex,
# version comparison
'version_compare': version_compare,
'version': version_compare,
# lists
'any': any,
'all': all,
# truthiness
'truthy': truthy,
'falsy': falsy,
# vault
'vault_encrypted': vault_encrypted,
'vaulted_file': vaulted_file,
# overrides that require special arg handling
'defined': wrapped_test_defined,
'undefined': wrapped_test_undefined,
}
| TestModule |
python | kamyu104__LeetCode-Solutions | Python/array-with-elements-not-equal-to-average-of-neighbors.py | {
"start": 133,
"end": 2182
} | class ____(object):
def rearrangeArray(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
mid = left
while mid <= right:
if nums[mid] == target:
mid += 1
elif compare(nums[mid], target):
nums[left], nums[mid] = nums[mid], nums[left]
left += 1
mid += 1
else:
nums[mid], nums[right] = nums[right], nums[mid]
right -= 1
return left, right
left, right = 0, len(nums)-1
while left <= right:
pivot_idx = randint(left, right)
pivot_left, pivot_right = tri_partition(nums, left, right, nums[pivot_idx], compare)
if pivot_left <= n <= pivot_right:
return
elif pivot_left > n:
right = pivot_left-1
else: # pivot_right < n.
left = pivot_right+1
def reversedTriPartitionWithVI(nums, val):
def idx(i, N):
return (1 + 2 * (i)) % N
N = len(nums)//2 * 2 + 1
i, j, n = 0, 0, len(nums) - 1
while j <= n:
if nums[idx(j, N)] > val:
nums[idx(i, N)], nums[idx(j, N)] = nums[idx(j, N)], nums[idx(i, N)]
i += 1
j += 1
elif nums[idx(j, N)] < val:
nums[idx(j, N)], nums[idx(n, N)] = nums[idx(n, N)], nums[idx(j, N)]
n -= 1
else:
j += 1
mid = (len(nums)-1)//2
nth_element(nums, mid)
reversedTriPartitionWithVI(nums, nums[mid])
return nums
# Time: O(nlogn)
# Space: O(n)
# Sorting and reorder solution
| Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_23/tasks.py | {
"start": 27664,
"end": 30662
} | class ____(NonStrictDataModel):
"""
:param filtering_rules: List of FilterRule ('OR' connection)
:type filtering_rules: Sequence[FilterRule]
:param output_rois: 'all_in_frame' - all rois for a frame are returned
'only_filtered' - only rois which led this frame to be selected
'frame_per_roi' - single roi per frame. Frame can be returned multiple times
with a different roi each time.
Note: this should be used for Training tasks only
Note: frame_per_roi implies that only filtered rois will be returned
:type output_rois: OutputRoisEnum
"""
_schema = {
"properties": {
"filtering_rules": {
"description": "List of FilterRule ('OR' connection)",
"items": {"$ref": "#/definitions/filter_rule"},
"type": ["array", "null"],
},
"output_rois": {
"description": (
"'all_in_frame' - all rois for a frame are returned\n\n'only_filtered' - only rois which led this"
" frame to be selected\n\n'frame_per_roi' - single roi per frame. Frame can be returned multiple"
" times with a different roi each time.\n\nNote: this should be used for Training tasks"
" only\n\nNote: frame_per_roi implies that only filtered rois will be returned\n "
),
"oneOf": [{"$ref": "#/definitions/output_rois_enum"}, {"type": "null"}],
},
},
"type": "object",
}
def __init__(self, filtering_rules=None, output_rois=None, **kwargs):
super(Filtering, self).__init__(**kwargs)
self.filtering_rules = filtering_rules
self.output_rois = output_rois
@schema_property("filtering_rules")
def filtering_rules(self):
return self._property_filtering_rules
@filtering_rules.setter
def filtering_rules(self, value):
if value is None:
self._property_filtering_rules = None
return
self.assert_isinstance(value, "filtering_rules", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [
FilterRule.from_dict(v) if isinstance(v, dict) else v for v in value
]
else:
self.assert_isinstance(value, "filtering_rules", FilterRule, is_array=True)
self._property_filtering_rules = value
@schema_property("output_rois")
def output_rois(self):
return self._property_output_rois
@output_rois.setter
def output_rois(self, value):
if value is None:
self._property_output_rois = None
return
if isinstance(value, six.string_types):
try:
value = OutputRoisEnum(value)
except ValueError:
pass
else:
self.assert_isinstance(value, "output_rois", enum.Enum)
self._property_output_rois = value
| Filtering |
python | apache__airflow | providers/dbt/cloud/src/airflow/providers/dbt/cloud/hooks/dbt.py | {
"start": 4397,
"end": 4516
} | class ____(AirflowException):
"""An exception that indicates a job run failed to complete."""
| DbtCloudJobRunException |
python | numba__numba | numba/tests/test_dispatcher.py | {
"start": 2249,
"end": 19254
} | class ____(BaseTest):
def test_equality(self):
@jit
def foo(x):
return x
@jit
def bar(x):
return x
# Written this way to verify `==` returns a bool (gh-5838). Using
# `assertTrue(foo == foo)` or `assertEqual(foo, foo)` would defeat the
# purpose of this test.
self.assertEqual(foo == foo, True)
self.assertEqual(foo == bar, False)
self.assertEqual(foo == None, False) # noqa: E711
def test_dyn_pyfunc(self):
@jit
def foo(x):
return x
foo(1)
[cr] = foo.overloads.values()
# __module__ must be match that of foo
self.assertEqual(cr.entry_point.__module__, foo.py_func.__module__)
def test_no_argument(self):
@jit
def foo():
return 1
# Just make sure this doesn't crash
foo()
def test_coerce_input_types(self):
# Issue #486: do not allow unsafe conversions if we can still
# compile other specializations.
c_add = jit(nopython=True)(add)
self.assertPreciseEqual(c_add(123, 456), add(123, 456))
self.assertPreciseEqual(c_add(12.3, 45.6), add(12.3, 45.6))
self.assertPreciseEqual(c_add(12.3, 45.6j), add(12.3, 45.6j))
self.assertPreciseEqual(c_add(12300000000, 456), add(12300000000, 456))
# Now force compilation of only a single specialization
c_add = jit('(i4, i4)', nopython=True)(add)
self.assertPreciseEqual(c_add(123, 456), add(123, 456))
# Implicit (unsafe) conversion of float to int
self.assertPreciseEqual(c_add(12.3, 45.6), add(12, 45))
with self.assertRaises(TypeError):
# Implicit conversion of complex to int disallowed
c_add(12.3, 45.6j)
def test_ambiguous_new_version(self):
"""Test compiling new version in an ambiguous case
"""
@jit
def foo(a, b):
return a + b
INT = 1
FLT = 1.5
self.assertAlmostEqual(foo(INT, FLT), INT + FLT)
self.assertEqual(len(foo.overloads), 1)
self.assertAlmostEqual(foo(FLT, INT), FLT + INT)
self.assertEqual(len(foo.overloads), 2)
self.assertAlmostEqual(foo(FLT, FLT), FLT + FLT)
self.assertEqual(len(foo.overloads), 3)
# The following call is ambiguous because (int, int) can resolve
# to (float, int) or (int, float) with equal weight.
self.assertAlmostEqual(foo(1, 1), INT + INT)
self.assertEqual(len(foo.overloads), 4, "didn't compile a new "
"version")
def test_lock(self):
"""
Test that (lazy) compiling from several threads at once doesn't
produce errors (see issue #908).
"""
errors = []
@jit
def foo(x):
return x + 1
def wrapper():
try:
self.assertEqual(foo(1), 2)
except Exception as e:
errors.append(e)
threads = [threading.Thread(target=wrapper) for i in range(16)]
for t in threads:
t.start()
for t in threads:
t.join()
self.assertFalse(errors)
def test_explicit_signatures(self):
f = jit("(int64,int64)")(add)
# Approximate match (unsafe conversion)
self.assertPreciseEqual(f(1.5, 2.5), 3)
self.assertEqual(len(f.overloads), 1, f.overloads)
f = jit(["(int64,int64)", "(float64,float64)"])(add)
# Exact signature matches
self.assertPreciseEqual(f(1, 2), 3)
self.assertPreciseEqual(f(1.5, 2.5), 4.0)
# Approximate match (int32 -> float64 is a safe conversion)
self.assertPreciseEqual(f(np.int32(1), 2.5), 3.5)
# No conversion
with self.assertRaises(TypeError) as cm:
f(1j, 1j)
self.assertIn("No matching definition", str(cm.exception))
self.assertEqual(len(f.overloads), 2, f.overloads)
# A more interesting one...
f = jit(["(float32,float32)", "(float64,float64)"])(add)
self.assertPreciseEqual(f(np.float32(1), np.float32(2**-25)), 1.0)
self.assertPreciseEqual(f(1, 2**-25), 1.0000000298023224)
# Fail to resolve ambiguity between the two best overloads
f = jit(["(float32,float64)",
"(float64,float32)",
"(int64,int64)"])(add)
with self.assertRaises(TypeError) as cm:
f(1.0, 2.0)
# The two best matches are output in the error message, as well
# as the actual argument types.
self.assertRegex(
str(cm.exception),
r"Ambiguous overloading for <function add [^>]*> "
r"\(float64, float64\):\n"
r"\(float32, float64\) -> float64\n"
r"\(float64, float32\) -> float64"
)
# The integer signature is not part of the best matches
self.assertNotIn("int64", str(cm.exception))
def test_signature_mismatch(self):
tmpl = ("Signature mismatch: %d argument types given, but function "
"takes 2 arguments")
with self.assertRaises(TypeError) as cm:
jit("()")(add)
self.assertIn(tmpl % 0, str(cm.exception))
with self.assertRaises(TypeError) as cm:
jit("(intc,)")(add)
self.assertIn(tmpl % 1, str(cm.exception))
with self.assertRaises(TypeError) as cm:
jit("(intc,intc,intc)")(add)
self.assertIn(tmpl % 3, str(cm.exception))
# With forceobj=True, an empty tuple is accepted
jit("()", forceobj=True)(add)
with self.assertRaises(TypeError) as cm:
jit("(intc,)", forceobj=True)(add)
self.assertIn(tmpl % 1, str(cm.exception))
def test_matching_error_message(self):
f = jit("(intc,intc)")(add)
with self.assertRaises(TypeError) as cm:
f(1j, 1j)
self.assertEqual(str(cm.exception),
"No matching definition for argument type(s) "
"complex128, complex128")
def test_disabled_compilation(self):
@jit
def foo(a):
return a
foo.compile("(float32,)")
foo.disable_compile()
with self.assertRaises(RuntimeError) as raises:
foo.compile("(int32,)")
self.assertEqual(str(raises.exception), "compilation disabled")
self.assertEqual(len(foo.signatures), 1)
def test_disabled_compilation_through_list(self):
@jit(["(float32,)", "(int32,)"])
def foo(a):
return a
with self.assertRaises(RuntimeError) as raises:
foo.compile("(complex64,)")
self.assertEqual(str(raises.exception), "compilation disabled")
self.assertEqual(len(foo.signatures), 2)
def test_disabled_compilation_nested_call(self):
@jit(["(intp,)"])
def foo(a):
return a
@jit
def bar():
foo(1)
foo(np.ones(1)) # no matching definition
with self.assertRaises(errors.TypingError) as raises:
bar()
m = r".*Invalid use of.*with parameters \(array\(float64, 1d, C\)\).*"
self.assertRegex(str(raises.exception), m)
def test_fingerprint_failure(self):
"""
Failure in computing the fingerprint cannot affect a nopython=False
function. On the other hand, with nopython=True, a ValueError should
be raised to report the failure with fingerprint.
"""
def foo(x):
return x
# Empty list will trigger failure in compile_fingerprint
errmsg = 'cannot compute fingerprint of empty list'
with self.assertRaises(ValueError) as raises:
_dispatcher.compute_fingerprint([])
self.assertIn(errmsg, str(raises.exception))
# It should work in objmode
objmode_foo = jit(forceobj=True)(foo)
self.assertEqual(objmode_foo([]), [])
# But, not in nopython=True
strict_foo = jit(nopython=True)(foo)
with self.assertRaises(ValueError) as raises:
strict_foo([])
self.assertIn(errmsg, str(raises.exception))
# Test in loop lifting context
@jit(forceobj=True)
def bar():
object() # force looplifting
x = []
for i in range(10):
x = objmode_foo(x)
return x
self.assertEqual(bar(), [])
# Make sure it was looplifted
[cr] = bar.overloads.values()
self.assertEqual(len(cr.lifted), 1)
def test_serialization(self):
"""
Test serialization of Dispatcher objects
"""
@jit(nopython=True)
def foo(x):
return x + 1
self.assertEqual(foo(1), 2)
# get serialization memo
memo = Dispatcher._memo
Dispatcher._recent.clear()
memo_size = len(memo)
# pickle foo and check memo size
serialized_foo = pickle.dumps(foo)
# increases the memo size
self.assertEqual(memo_size + 1, len(memo))
# unpickle
foo_rebuilt = pickle.loads(serialized_foo)
self.assertEqual(memo_size + 1, len(memo))
self.assertIs(foo, foo_rebuilt)
# do we get the same object even if we delete all the explicit
# references?
id_orig = id(foo_rebuilt)
del foo
del foo_rebuilt
self.assertEqual(memo_size + 1, len(memo))
new_foo = pickle.loads(serialized_foo)
self.assertEqual(id_orig, id(new_foo))
# now clear the recent cache
ref = weakref.ref(new_foo)
del new_foo
Dispatcher._recent.clear()
self.assertEqual(memo_size, len(memo))
# show that deserializing creates a new object
pickle.loads(serialized_foo)
self.assertIs(ref(), None)
@needs_lapack
@unittest.skipIf(_is_armv7l, "Unaligned loads unsupported")
def test_misaligned_array_dispatch(self):
# for context see issue #2937
def foo(a):
return np.linalg.matrix_power(a, 1)
jitfoo = jit(nopython=True)(foo)
n = 64
r = int(np.sqrt(n))
dt = np.int8
count = np.complex128().itemsize // dt().itemsize
tmp = np.arange(n * count + 1, dtype=dt)
# create some arrays as Cartesian production of:
# [F/C] x [aligned/misaligned]
C_contig_aligned = tmp[:-1].view(np.complex128).reshape(r, r)
C_contig_misaligned = tmp[1:].view(np.complex128).reshape(r, r)
F_contig_aligned = C_contig_aligned.T
F_contig_misaligned = C_contig_misaligned.T
# checking routine
def check(name, a):
a[:, :] = np.arange(n, dtype=np.complex128).reshape(r, r)
expected = foo(a)
got = jitfoo(a)
np.testing.assert_allclose(expected, got)
# The checks must be run in this order to create the dispatch key
# sequence that causes invalid dispatch noted in #2937.
# The first two should hit the cache as they are aligned, supported
# order and under 5 dimensions. The second two should end up in the
# fallback path as they are misaligned.
check("C_contig_aligned", C_contig_aligned)
check("F_contig_aligned", F_contig_aligned)
check("C_contig_misaligned", C_contig_misaligned)
check("F_contig_misaligned", F_contig_misaligned)
@unittest.skipIf(_is_armv7l, "Unaligned loads unsupported")
def test_immutability_in_array_dispatch(self):
# RO operation in function
def foo(a):
return np.sum(a)
jitfoo = jit(nopython=True)(foo)
n = 64
r = int(np.sqrt(n))
dt = np.int8
count = np.complex128().itemsize // dt().itemsize
tmp = np.arange(n * count + 1, dtype=dt)
# create some arrays as Cartesian production of:
# [F/C] x [aligned/misaligned]
C_contig_aligned = tmp[:-1].view(np.complex128).reshape(r, r)
C_contig_misaligned = tmp[1:].view(np.complex128).reshape(r, r)
F_contig_aligned = C_contig_aligned.T
F_contig_misaligned = C_contig_misaligned.T
# checking routine
def check(name, a, disable_write_bit=False):
a[:, :] = np.arange(n, dtype=np.complex128).reshape(r, r)
if disable_write_bit:
a.flags.writeable = False
expected = foo(a)
got = jitfoo(a)
np.testing.assert_allclose(expected, got)
# all of these should end up in the fallback path as they have no write
# bit set
check("C_contig_aligned", C_contig_aligned, disable_write_bit=True)
check("F_contig_aligned", F_contig_aligned, disable_write_bit=True)
check("C_contig_misaligned", C_contig_misaligned,
disable_write_bit=True)
check("F_contig_misaligned", F_contig_misaligned,
disable_write_bit=True)
@needs_lapack
@unittest.skipIf(_is_armv7l, "Unaligned loads unsupported")
def test_misaligned_high_dimension_array_dispatch(self):
def foo(a):
return np.linalg.matrix_power(a[0, 0, 0, 0, :, :], 1)
jitfoo = jit(nopython=True)(foo)
def check_properties(arr, layout, aligned):
self.assertEqual(arr.flags.aligned, aligned)
if layout == "C":
self.assertEqual(arr.flags.c_contiguous, True)
if layout == "F":
self.assertEqual(arr.flags.f_contiguous, True)
n = 729
r = 3
dt = np.int8
count = np.complex128().itemsize // dt().itemsize
tmp = np.arange(n * count + 1, dtype=dt)
# create some arrays as Cartesian production of:
# [F/C] x [aligned/misaligned]
C_contig_aligned = tmp[:-1].view(np.complex128).\
reshape(r, r, r, r, r, r)
check_properties(C_contig_aligned, 'C', True)
C_contig_misaligned = tmp[1:].view(np.complex128).\
reshape(r, r, r, r, r, r)
check_properties(C_contig_misaligned, 'C', False)
F_contig_aligned = C_contig_aligned.T
check_properties(F_contig_aligned, 'F', True)
F_contig_misaligned = C_contig_misaligned.T
check_properties(F_contig_misaligned, 'F', False)
# checking routine
def check(name, a):
a[:, :] = np.arange(n, dtype=np.complex128).\
reshape(r, r, r, r, r, r)
expected = foo(a)
got = jitfoo(a)
np.testing.assert_allclose(expected, got)
# these should all hit the fallback path as the cache is only for up to
# 5 dimensions
check("F_contig_misaligned", F_contig_misaligned)
check("C_contig_aligned", C_contig_aligned)
check("F_contig_aligned", F_contig_aligned)
check("C_contig_misaligned", C_contig_misaligned)
def test_dispatch_recompiles_for_scalars(self):
# for context #3612, essentially, compiling a lambda x:x for a
# numerically wide type (everything can be converted to a complex128)
# and then calling again with e.g. an int32 would lead to the int32
# being converted to a complex128 whereas it ought to compile an int32
# specialization.
def foo(x):
return x
# jit and compile on dispatch for 3 scalar types, expect 3 signatures
jitfoo = jit(nopython=True)(foo)
jitfoo(np.complex128(1 + 2j))
jitfoo(np.int32(10))
jitfoo(np.bool_(False))
self.assertEqual(len(jitfoo.signatures), 3)
expected_sigs = [(types.complex128,), (types.int32,), (types.bool_,)]
self.assertEqual(jitfoo.signatures, expected_sigs)
# now jit with signatures so recompilation is forbidden
# expect 1 signature and type conversion
jitfoo = jit([(types.complex128,)], nopython=True)(foo)
jitfoo(np.complex128(1 + 2j))
jitfoo(np.int32(10))
jitfoo(np.bool_(False))
self.assertEqual(len(jitfoo.signatures), 1)
expected_sigs = [(types.complex128,)]
self.assertEqual(jitfoo.signatures, expected_sigs)
def test_dispatcher_raises_for_invalid_decoration(self):
# For context see https://github.com/numba/numba/issues/4750.
@jit(nopython=True)
def foo(x):
return x
with self.assertRaises(TypeError) as raises:
jit(foo)
err_msg = str(raises.exception)
self.assertIn(
"A jit decorator was called on an already jitted function", err_msg)
self.assertIn("foo", err_msg)
self.assertIn(".py_func", err_msg)
with self.assertRaises(TypeError) as raises:
jit(BaseTest)
err_msg = str(raises.exception)
self.assertIn("The decorated object is not a function", err_msg)
self.assertIn(f"{type(BaseTest)}", err_msg)
| TestDispatcher |
python | pytorch__pytorch | torch/nn/utils/rnn.py | {
"start": 442,
"end": 753
} | class ____(NamedTuple):
data: torch.Tensor
batch_sizes: torch.Tensor
sorted_indices: torch.Tensor | None
unsorted_indices: torch.Tensor | None
def bind(optional: _T | None, fn: Callable[[_T], _R]) -> _R | None:
if optional is None:
return None
return fn(optional)
| PackedSequence_ |
python | has2k1__plotnine | plotnine/_mpl/offsetbox.py | {
"start": 1134,
"end": 2355
} | class ____(AuxTransformBox):
"""
DPI Corrected AuxTransformBox
"""
def __init__(self, aux_transform):
super().__init__(aux_transform)
self.dpi_transform = Affine2D()
self._dpi_corrected = False
def get_transform(self):
"""
Return the [](`~matplotlib.transforms.Transform`) applied
to the children
"""
return (
self.aux_transform
+ self.dpi_transform
+ self.ref_offset_transform
+ self.offset_transform
)
def _correct_dpi(self, renderer):
if not self._dpi_corrected:
dpi_cor = renderer.points_to_pixels(1.0)
self.dpi_transform.clear()
self.dpi_transform.scale(dpi_cor, dpi_cor)
self._dpi_corrected = True
def get_bbox(self, renderer):
self._correct_dpi(renderer)
return super().get_bbox(renderer)
def draw(self, renderer):
"""
Draw the children
"""
self._correct_dpi(renderer)
for c in self.get_children():
c.draw(renderer)
_bbox_artist(self, renderer, fill=False, props=dict(pad=0.0))
self.stale = False
| DPICorAuxTransformBox |
python | realpython__materials | inheritance-and-composition/inheritance/hr.py | {
"start": 0,
"end": 334
} | class ____:
def calculate_payroll(self, employees):
print("Calculating Payroll")
print("===================")
for employee in employees:
print(f"Payroll for: {employee.id} - {employee.name}")
print(f"- Check amount: {employee.calculate_payroll()}")
print("")
| PayrollSystem |
python | django-haystack__django-haystack | test_haystack/multipleindex/search_indexes.py | {
"start": 145,
"end": 293
} | class ____(indexes.SearchIndex):
text = indexes.CharField(document=True, model_attr="body")
def get_model(self):
return Foo
| BaseIndex |
python | walkccc__LeetCode | solutions/528. Random Pick with Weight/528-2.py | {
"start": 0,
"end": 202
} | class ____:
def __init__(self, w: list[int]):
self.prefix = list(itertools.accumulate(w))
def pickIndex(self) -> int:
return bisect_left(self.prefix, random.random() * self.prefix[-1])
| Solution |
python | viewflow__viewflow | viewflow/workflow/flow/views/mixins.py | {
"start": 2770,
"end": 3436
} | class ____(object):
"""List of templates for a task view."""
template_filename = None
def get_template_names(self):
if self.template_name is None:
flow_task = self.request.activation.flow_task
opts = flow_task.flow_class.instance
assert not self.template_name
return (
f"{opts.app_label}/{opts.app_label}/{flow_task.name}_{self.template_filename}",
f"{opts.app_label}/{opts.flow_label}/{self.template_filename}",
f"viewflow/workflow/{self.template_filename}",
)
else:
return [self.template_name]
| TaskViewTemplateNames |
python | automl__auto-sklearn | scripts/02_retrieve_metadata.py | {
"start": 6554,
"end": 9379
} | class ____(AbstractDataManager):
def __init__(self, info, feat_type=None):
super().__init__("Test")
self._info = info
self.feat_type = feat_type
def main():
parser = ArgumentParser()
parser.add_argument("--working-directory", type=str, required=True)
parser.add_argument("--cutoff", type=int, default=-1)
parser.add_argument("--only-best", type=bool, default=True)
args = parser.parse_args()
working_directory = args.working_directory
cutoff = args.cutoff
only_best = args.only_best
for task_type in ("classification", "regression"):
if task_type == "classification":
metadata_sets = itertools.product(
[0, 1],
[BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION],
CLASSIFICATION_METRICS,
)
input_directory = os.path.join(
working_directory, "configuration", "classification"
)
elif task_type == "regression":
metadata_sets = itertools.product([0, 1], [REGRESSION], REGRESSION_METRICS)
input_directory = os.path.join(
working_directory, "configuration", "regression"
)
else:
raise ValueError(task_type)
output_dir = os.path.join(working_directory, "configuration_results")
for sparse, task, metric in metadata_sets:
print(TASK_TYPES_TO_STRING[task], metric, sparse)
output_dir_ = os.path.join(
output_dir,
"%s_%s_%s"
% (metric, TASK_TYPES_TO_STRING[task], "sparse" if sparse else "dense"),
)
configuration_space = pipeline.get_configuration_space(
DummyDatamanager(
info={"is_sparse": sparse, "task": task},
feat_type={"A": "numerical", "B": "categorical"}
)
)
outputs, configurations = retrieve_matadata(
validation_directory=input_directory,
metric=metric,
cutoff=cutoff,
configuration_space=configuration_space,
only_best=only_best,
)
if len(outputs) == 0:
print(
"No output found for %s, %s, %s"
% (
metric,
TASK_TYPES_TO_STRING[task],
"sparse" if sparse else "dense",
)
)
continue
try:
os.makedirs(output_dir_)
except:
pass
write_output(
outputs, configurations, output_dir_, configuration_space, metric
)
if __name__ == "__main__":
main()
| DummyDatamanager |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_composer.py | {
"start": 2657,
"end": 4748
} | class ____:
@mock.patch(COMPOSER_STRING.format("Environment.to_dict"))
@mock.patch(COMPOSER_STRING.format("CloudComposerHook"))
def test_execute(self, mock_hook, to_dict_mode) -> None:
op = CloudComposerCreateEnvironmentOperator(
task_id=TASK_ID,
project_id=TEST_GCP_PROJECT,
region=TEST_GCP_REGION,
environment_id=TEST_ENVIRONMENT_ID,
environment=TEST_ENVIRONMENT,
gcp_conn_id=TEST_GCP_CONN_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
op.execute(mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_hook.return_value.create_environment.assert_called_once_with(
project_id=TEST_GCP_PROJECT,
region=TEST_GCP_REGION,
environment=TEST_ENVIRONMENT,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
@mock.patch(COMPOSER_STRING.format("Environment.to_dict"))
@mock.patch(COMPOSER_STRING.format("CloudComposerHook"))
@mock.patch(COMPOSER_TRIGGERS_STRING.format("CloudComposerAsyncHook"))
def test_execute_deferrable(self, mock_trigger_hook, mock_hook, to_dict_mode):
op = CloudComposerCreateEnvironmentOperator(
task_id=TASK_ID,
project_id=TEST_GCP_PROJECT,
region=TEST_GCP_REGION,
environment_id=TEST_ENVIRONMENT_ID,
environment=TEST_ENVIRONMENT,
gcp_conn_id=TEST_GCP_CONN_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
deferrable=True,
)
with pytest.raises(TaskDeferred) as exc:
op.execute(mock.MagicMock())
assert isinstance(exc.value.trigger, CloudComposerExecutionTrigger)
assert exc.value.method_name == GOOGLE_DEFAULT_DEFERRABLE_METHOD_NAME
| TestCloudComposerCreateEnvironmentOperator |
python | Netflix__metaflow | test/cmd/develop/test_stub_generator.py | {
"start": 290,
"end": 370
} | class ____(typing.Generic[T]):
"""Generic test class"""
pass
| GenericClass |
python | django__django | tests/model_fields/test_imagefield.py | {
"start": 12567,
"end": 12861
} | class ____(ImageFieldTwoDimensionsTests):
"""
Tests behavior of an ImageField where the dimensions fields are
defined before the ImageField.
"""
PersonModel = PersonDimensionsFirst
@skipIf(Image is None, "Pillow is required to test ImageField")
| ImageFieldDimensionsFirstTests |
python | streamlit__streamlit | lib/tests/streamlit/components/v2/test_default_state.py | {
"start": 1062,
"end": 6376
} | class ____(DeltaGeneratorTestCase):
"""Integration tests for `default` using the public component API."""
def setUp(self) -> None:
"""Set up a fresh component manager patched into the Runtime singleton."""
super().setUp()
self.mock_component_manager = BidiComponentManager()
self.runtime_patcher = patch.object(
Runtime, "instance", return_value=MagicMock()
)
self.mock_runtime = self.runtime_patcher.start()
self.mock_runtime.return_value.bidi_component_registry = (
self.mock_component_manager
)
def tearDown(self) -> None:
"""Tear down the runtime patcher."""
super().tearDown()
self.runtime_patcher.stop()
def test_component_with_default_basic(self) -> None:
"""Test basic `default` functionality with the public API."""
# Declare a component
my_component = component(
"test_component",
js="console.log('test');",
)
# Create mock callbacks
on_value_change = MagicMock()
on_enabled_change = MagicMock()
# Use the component with default
result = my_component(
default={
"value": 42,
"enabled": False,
},
on_value_change=on_value_change,
on_enabled_change=on_enabled_change,
)
# Verify defaults are applied
assert result["value"] == 42
assert result["enabled"] is False
def test_component_default_validation(self) -> None:
"""Test that `default` key validation works with the public API."""
# Declare a component
my_component = component(
"validation_test_component",
js="console.log('validation test');",
)
# Create callback for only one state
on_valid_change = MagicMock()
# Try to use invalid default
with pytest.raises(StreamlitAPIException) as exc_info:
my_component(
default={
"valid": "this is ok",
"invalid": "this should fail",
},
on_valid_change=on_valid_change,
)
# Verify the error message
error_message = str(exc_info.value)
assert "invalid" in error_message
assert "not a valid state name" in error_message
def test_component_default_with_data(self) -> None:
"""Test that `default` works correctly with the `data` parameter."""
# Declare a component
my_component = component(
"data_and_defaults_component",
js="console.log('data and defaults');",
)
# Create callbacks
on_selection_change = MagicMock()
on_mode_change = MagicMock()
# Use both data and default
result = my_component(
data={"items": ["a", "b", "c"]},
default={
"selection": [],
"mode": "single",
},
on_selection_change=on_selection_change,
on_mode_change=on_mode_change,
)
# Verify defaults are applied
assert result["selection"] == []
assert result["mode"] == "single"
# Verify the proto contains both data and component setup
delta = self.get_delta_from_queue()
bidi_component_proto = delta.new_element.bidi_component
assert bidi_component_proto.component_name.endswith(
"data_and_defaults_component"
)
def test_component_default_complex_types(self) -> None:
"""Test `default` with complex data types like lists and dicts."""
# Declare a component
my_component = component(
"complex_types_component",
js="console.log('complex types');",
)
# Create callbacks
on_items_change = MagicMock()
on_config_change = MagicMock()
# Complex default values
default_items = [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}]
default_config = {
"theme": "dark",
"settings": {"auto_save": True, "timeout": 30},
}
# Use the component
result = my_component(
default={
"items": default_items,
"config": default_config,
},
on_items_change=on_items_change,
on_config_change=on_config_change,
)
# Verify complex defaults are preserved
assert result["items"] == default_items
assert result["config"] == default_config
assert result["config"]["settings"]["auto_save"] is True
def test_component_default_none_values(self) -> None:
"""Test `default` with None values using the public API."""
# Declare a component
my_component = component(
"none_values_component",
js="console.log('none values');",
)
# Create callback
on_nullable_change = MagicMock()
# Use None as default value
result = my_component(
default={"nullable": None},
on_nullable_change=on_nullable_change,
)
# Verify None is properly handled
assert result["nullable"] is None
| DefaultStateIntegrationTest |
python | kamyu104__LeetCode-Solutions | Python/maximum-rows-covered-by-columns.py | {
"start": 70,
"end": 903
} | class ____(object):
def maximumRows(self, matrix, numSelect):
"""
:type matrix: List[List[int]]
:type numSelect: int
:rtype: int
"""
def next_popcount(n): # reference: https://massivealgorithms.blogspot.com/2014/06/hakmem-item-175.html
lowest_bit = n&-n
left_bits = n+lowest_bit
changed_bits = n^left_bits
right_bits = (changed_bits//lowest_bit)>>2
return left_bits|right_bits
masks = [reduce(lambda m, c: m|(matrix[r][-1-c]<<c), xrange(len(matrix[0])), 0) for r in xrange(len(matrix))]
result = 0
mask = (1<<numSelect)-1
while mask < 1<<len(matrix[0]):
result = max(result, sum((m&mask) == m for m in masks))
mask = next_popcount(mask)
return result
| Solution |
python | python__mypy | mypy/visitor.py | {
"start": 8972,
"end": 18558
} | class ____(Generic[T], ExpressionVisitor[T], StatementVisitor[T], PatternVisitor[T]):
"""Empty base class for parse tree node visitors.
The T type argument specifies the return type of the visit
methods. As all methods defined here raise by default,
subclasses do not always need to override all the methods.
"""
# Not in superclasses:
def visit_mypy_file(self, o: mypy.nodes.MypyFile, /) -> T:
raise NotImplementedError()
# TODO: We have a visit_var method, but no visit_typeinfo or any
# other non-Statement SymbolNode (accepting those will raise a
# runtime error). Maybe this should be resolved in some direction.
def visit_var(self, o: mypy.nodes.Var, /) -> T:
raise NotImplementedError()
# Module structure
def visit_import(self, o: mypy.nodes.Import, /) -> T:
raise NotImplementedError()
def visit_import_from(self, o: mypy.nodes.ImportFrom, /) -> T:
raise NotImplementedError()
def visit_import_all(self, o: mypy.nodes.ImportAll, /) -> T:
raise NotImplementedError()
# Definitions
def visit_func_def(self, o: mypy.nodes.FuncDef, /) -> T:
raise NotImplementedError()
def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef, /) -> T:
raise NotImplementedError()
def visit_class_def(self, o: mypy.nodes.ClassDef, /) -> T:
raise NotImplementedError()
def visit_global_decl(self, o: mypy.nodes.GlobalDecl, /) -> T:
raise NotImplementedError()
def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl, /) -> T:
raise NotImplementedError()
def visit_decorator(self, o: mypy.nodes.Decorator, /) -> T:
raise NotImplementedError()
def visit_type_alias(self, o: mypy.nodes.TypeAlias, /) -> T:
raise NotImplementedError()
def visit_placeholder_node(self, o: mypy.nodes.PlaceholderNode, /) -> T:
raise NotImplementedError()
# Statements
def visit_block(self, o: mypy.nodes.Block, /) -> T:
raise NotImplementedError()
def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt, /) -> T:
raise NotImplementedError()
def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt, /) -> T:
raise NotImplementedError()
def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt, /) -> T:
raise NotImplementedError()
def visit_while_stmt(self, o: mypy.nodes.WhileStmt, /) -> T:
raise NotImplementedError()
def visit_for_stmt(self, o: mypy.nodes.ForStmt, /) -> T:
raise NotImplementedError()
def visit_return_stmt(self, o: mypy.nodes.ReturnStmt, /) -> T:
raise NotImplementedError()
def visit_assert_stmt(self, o: mypy.nodes.AssertStmt, /) -> T:
raise NotImplementedError()
def visit_del_stmt(self, o: mypy.nodes.DelStmt, /) -> T:
raise NotImplementedError()
def visit_if_stmt(self, o: mypy.nodes.IfStmt, /) -> T:
raise NotImplementedError()
def visit_break_stmt(self, o: mypy.nodes.BreakStmt, /) -> T:
raise NotImplementedError()
def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt, /) -> T:
raise NotImplementedError()
def visit_pass_stmt(self, o: mypy.nodes.PassStmt, /) -> T:
raise NotImplementedError()
def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt, /) -> T:
raise NotImplementedError()
def visit_try_stmt(self, o: mypy.nodes.TryStmt, /) -> T:
raise NotImplementedError()
def visit_with_stmt(self, o: mypy.nodes.WithStmt, /) -> T:
raise NotImplementedError()
def visit_match_stmt(self, o: mypy.nodes.MatchStmt, /) -> T:
raise NotImplementedError()
def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt, /) -> T:
raise NotImplementedError()
# Expressions (default no-op implementation)
def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T:
raise NotImplementedError()
def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T:
raise NotImplementedError()
def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T:
raise NotImplementedError()
def visit_float_expr(self, o: mypy.nodes.FloatExpr, /) -> T:
raise NotImplementedError()
def visit_complex_expr(self, o: mypy.nodes.ComplexExpr, /) -> T:
raise NotImplementedError()
def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr, /) -> T:
raise NotImplementedError()
def visit_star_expr(self, o: mypy.nodes.StarExpr, /) -> T:
raise NotImplementedError()
def visit_name_expr(self, o: mypy.nodes.NameExpr, /) -> T:
raise NotImplementedError()
def visit_member_expr(self, o: mypy.nodes.MemberExpr, /) -> T:
raise NotImplementedError()
def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr, /) -> T:
raise NotImplementedError()
def visit_yield_expr(self, o: mypy.nodes.YieldExpr, /) -> T:
raise NotImplementedError()
def visit_call_expr(self, o: mypy.nodes.CallExpr, /) -> T:
raise NotImplementedError()
def visit_op_expr(self, o: mypy.nodes.OpExpr, /) -> T:
raise NotImplementedError()
def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr, /) -> T:
raise NotImplementedError()
def visit_cast_expr(self, o: mypy.nodes.CastExpr, /) -> T:
raise NotImplementedError()
def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr, /) -> T:
raise NotImplementedError()
def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr, /) -> T:
raise NotImplementedError()
def visit_reveal_expr(self, o: mypy.nodes.RevealExpr, /) -> T:
raise NotImplementedError()
def visit_super_expr(self, o: mypy.nodes.SuperExpr, /) -> T:
raise NotImplementedError()
def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr, /) -> T:
raise NotImplementedError()
def visit_unary_expr(self, o: mypy.nodes.UnaryExpr, /) -> T:
raise NotImplementedError()
def visit_list_expr(self, o: mypy.nodes.ListExpr, /) -> T:
raise NotImplementedError()
def visit_dict_expr(self, o: mypy.nodes.DictExpr, /) -> T:
raise NotImplementedError()
def visit_tuple_expr(self, o: mypy.nodes.TupleExpr, /) -> T:
raise NotImplementedError()
def visit_set_expr(self, o: mypy.nodes.SetExpr, /) -> T:
raise NotImplementedError()
def visit_index_expr(self, o: mypy.nodes.IndexExpr, /) -> T:
raise NotImplementedError()
def visit_type_application(self, o: mypy.nodes.TypeApplication, /) -> T:
raise NotImplementedError()
def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr, /) -> T:
raise NotImplementedError()
def visit_list_comprehension(self, o: mypy.nodes.ListComprehension, /) -> T:
raise NotImplementedError()
def visit_set_comprehension(self, o: mypy.nodes.SetComprehension, /) -> T:
raise NotImplementedError()
def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension, /) -> T:
raise NotImplementedError()
def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr, /) -> T:
raise NotImplementedError()
def visit_slice_expr(self, o: mypy.nodes.SliceExpr, /) -> T:
raise NotImplementedError()
def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr, /) -> T:
raise NotImplementedError()
def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr, /) -> T:
raise NotImplementedError()
def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr, /) -> T:
raise NotImplementedError()
def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr, /) -> T:
raise NotImplementedError()
def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr, /) -> T:
raise NotImplementedError()
def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr, /) -> T:
raise NotImplementedError()
def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr, /) -> T:
raise NotImplementedError()
def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr, /) -> T:
raise NotImplementedError()
def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr, /) -> T:
raise NotImplementedError()
def visit__promote_expr(self, o: mypy.nodes.PromoteExpr, /) -> T:
raise NotImplementedError()
def visit_await_expr(self, o: mypy.nodes.AwaitExpr, /) -> T:
raise NotImplementedError()
def visit_temp_node(self, o: mypy.nodes.TempNode, /) -> T:
raise NotImplementedError()
# Patterns
def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T:
raise NotImplementedError()
def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T:
raise NotImplementedError()
def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T:
raise NotImplementedError()
def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern, /) -> T:
raise NotImplementedError()
def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern, /) -> T:
raise NotImplementedError()
def visit_starred_pattern(self, o: mypy.patterns.StarredPattern, /) -> T:
raise NotImplementedError()
def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern, /) -> T:
raise NotImplementedError()
def visit_class_pattern(self, o: mypy.patterns.ClassPattern, /) -> T:
raise NotImplementedError()
| NodeVisitor |
python | neetcode-gh__leetcode | python/0007-reverse-integer.py | {
"start": 0,
"end": 663
} | class ____:
def reverse(self, x: int) -> int:
# Integer.MAX_VALUE = 2147483647 (end with 7)
# Integer.MIN_VALUE = -2147483648 (end with -8 )
MIN = -2147483648 # -2^31,
MAX = 2147483647 # 2^31 - 1
res = 0
while x:
digit = int(math.fmod(x, 10)) # (python dumb) -1 % 10 = 9
x = int(x / 10) # (python dumb) -1 // 10 = -1
if res > MAX // 10 or (res == MAX // 10 and digit > MAX % 10):
return 0
if res < MIN // 10 or (res == MIN // 10 and digit < MIN % 10):
return 0
res = (res * 10) + digit
return res
| Solution |
python | airbytehq__airbyte | airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/utils/compare.py | {
"start": 2468,
"end": 2938
} | class ____(HashMixin, list):
pass
def make_hashable(obj) -> str:
"""
Simplify comparison of nested dicts/lists
:param obj value for comparison
:param exclude_fields if value is Mapping, some fields can be excluded
"""
if isinstance(obj, Mapping):
# If value is Mapping, some fields can be excluded
return DictWithHashMixin(obj)
if isinstance(obj, List):
return ListWithHashMixin(obj)
return obj
| ListWithHashMixin |
python | numba__llvmlite | llvmlite/tests/test_ir.py | {
"start": 3407,
"end": 11746
} | class ____(TestBase):
proto = \
"""i32 @"my_func"(i32 %".1", i32 %".2", double %".3", ptr %".4")""" \
if not ir_layer_typed_pointers_enabled else \
"""i32 @"my_func"(i32 %".1", i32 %".2", double %".3", i32* %".4")"""
def test_declare(self):
# A simple declaration
func = self.function()
asm = self.descr(func).strip()
self.assertEqual(asm.strip(), "declare %s" % self.proto)
def test_declare_attributes(self):
# Now with function attributes
func = self.function()
func.attributes.add("optsize")
func.attributes.add("alwaysinline")
func.attributes.add("convergent")
func.attributes.alignstack = 16
tp_pers = ir.FunctionType(int8, (), var_arg=True)
pers = ir.Function(self.module(), tp_pers, '__gxx_personality_v0')
func.attributes.personality = pers
asm = self.descr(func).strip()
if not ir_layer_typed_pointers_enabled:
self.assertEqual(asm,
("declare %s alwaysinline convergent optsize "
"alignstack(16) "
"personality ptr @\"__gxx_personality_v0\"") %
self.proto)
else:
self.assertEqual(asm,
("declare %s alwaysinline convergent optsize "
"alignstack(16) personality "
"i8 (...)* @\"__gxx_personality_v0\"") %
self.proto)
# Check pickling
self.assert_pickle_correctly(func)
def test_function_attributes(self):
# Now with parameter attributes
func = self.function()
func.args[0].add_attribute("zeroext")
func.args[1].attributes.dereferenceable = 5
func.args[1].attributes.dereferenceable_or_null = 10
func.args[3].attributes.align = 4
func.args[3].add_attribute("nonnull")
func.return_value.add_attribute("noalias")
asm = self.descr(func).strip()
if not ir_layer_typed_pointers_enabled:
self.assertEqual(asm,
"""declare noalias i32 @"my_func"(i32 zeroext %".1", i32 dereferenceable(5) dereferenceable_or_null(10) %".2", double %".3", ptr nonnull align 4 %".4")""" # noqa E501
)
else:
self.assertEqual(asm,
"""declare noalias i32 @"my_func"(i32 zeroext %".1", i32 dereferenceable(5) dereferenceable_or_null(10) %".2", double %".3", i32* nonnull align 4 %".4")""" # noqa E501
)
# Check pickling
self.assert_pickle_correctly(func)
def test_function_metadata(self):
# Now with function metadata
module = self.module()
func = self.function(module)
func.set_metadata('dbg', module.add_metadata([]))
asm = self.descr(func).strip()
self.assertEqual(asm,
f'declare {self.proto} !dbg !0'
)
# Check pickling
self.assert_pickle_correctly(func)
def test_function_section(self):
# Test function with section
func = self.function()
func.section = "a_section"
asm = self.descr(func).strip()
self.assertEqual(asm,
f'declare {self.proto} section "a_section"'
)
# Check pickling
self.assert_pickle_correctly(func)
def test_function_section_meta(self):
# Test function with section and metadata
module = self.module()
func = self.function(module)
func.section = "a_section"
func.set_metadata('dbg', module.add_metadata([]))
asm = self.descr(func).strip()
self.assertEqual(asm,
f'declare {self.proto} section "a_section" !dbg !0'
)
# Check pickling
self.assert_pickle_correctly(func)
def test_function_attr_meta(self):
# Test function with attributes and metadata
module = self.module()
func = self.function(module)
func.attributes.add("alwaysinline")
func.set_metadata('dbg', module.add_metadata([]))
asm = self.descr(func).strip()
self.assertEqual(asm,
f'declare {self.proto} alwaysinline !dbg !0'
)
# Check pickling
self.assert_pickle_correctly(func)
def test_function_attr_section(self):
# Test function with attributes and section
func = self.function()
func.attributes.add("optsize")
func.section = "a_section"
asm = self.descr(func).strip()
self.assertEqual(asm,
f'declare {self.proto} optsize section "a_section"')
# Check pickling
self.assert_pickle_correctly(func)
def test_function_attr_section_meta(self):
# Test function with attributes, section and metadata
module = self.module()
func = self.function(module)
func.attributes.add("alwaysinline")
func.section = "a_section"
func.set_metadata('dbg', module.add_metadata([]))
asm = self.descr(func).strip()
self.assertEqual(asm,
f'declare {self.proto} alwaysinline section "a_section" !dbg !0' # noqa E501
)
# Check pickling
self.assert_pickle_correctly(func)
def test_define(self):
# A simple definition
func = self.function()
func.attributes.add("alwaysinline")
block = func.append_basic_block('my_block')
builder = ir.IRBuilder(block)
builder.ret_void()
asm = self.descr(func)
self.check_descr(asm, """\
define {proto} alwaysinline
{{
my_block:
ret void
}}
""".format(proto=self.proto))
def test_declare_intrinsics(self):
module = self.module()
pint8 = int8.as_pointer()
powi = module.declare_intrinsic('llvm.powi', [dbl])
memset = module.declare_intrinsic('llvm.memset', [pint8, int32])
memcpy = module.declare_intrinsic('llvm.memcpy', [pint8, pint8, int32])
assume = module.declare_intrinsic('llvm.assume')
self.check_descr(self.descr(powi).strip(), """\
declare double @"llvm.powi.f64"(double %".1", i32 %".2")""")
if not ir_layer_typed_pointers_enabled:
self.check_descr(self.descr(memset).strip(), """\
declare void @"llvm.memset.p0.i32"(ptr %".1", i8 %".2", i32 %".3", i1 %".4")""") # noqa E501
self.check_descr(self.descr(memcpy).strip(), """\
declare void @"llvm.memcpy.p0.p0.i32"(ptr %".1", ptr %".2", i32 %".3", i1 %".4")""") # noqa E501
else:
self.check_descr(self.descr(memset).strip(), """\
declare void @"llvm.memset.p0i8.i32"(i8* %".1", i8 %".2", i32 %".3", i1 %".4")""") # noqa E501
self.check_descr(self.descr(memcpy).strip(), """\
declare void @"llvm.memcpy.p0i8.p0i8.i32"(i8* %".1", i8* %".2", i32 %".3", i1 %".4")""") # noqa E501
self.check_descr(self.descr(assume).strip(), """\
declare void @"llvm.assume"(i1 %".1")""")
def test_redeclare_intrinsic(self):
module = self.module()
powi = module.declare_intrinsic('llvm.powi', [dbl])
powi2 = module.declare_intrinsic('llvm.powi', [dbl])
self.assertIs(powi, powi2)
def test_pickling(self):
fn = self.function()
self.assert_pickle_correctly(fn)
def test_alwaysinline_noinline_disallowed(self):
module = self.module()
func = self.function(module)
func.attributes.add('alwaysinline')
msg = "Can't have alwaysinline and noinline"
with self.assertRaisesRegex(ValueError, msg):
func.attributes.add('noinline')
def test_noinline_alwaysinline_disallowed(self):
module = self.module()
func = self.function(module)
func.attributes.add('noinline')
msg = "Can't have alwaysinline and noinline"
with self.assertRaisesRegex(ValueError, msg):
func.attributes.add('alwaysinline')
| TestFunction |
python | lepture__authlib | tests/django/test_oauth1/models.py | {
"start": 766,
"end": 1162
} | class ____(Model):
user = ForeignKey(User, on_delete=CASCADE)
client_id = CharField(max_length=48, db_index=True)
oauth_token = CharField(max_length=84, unique=True, db_index=True)
oauth_token_secret = CharField(max_length=84)
def get_oauth_token(self):
return self.oauth_token
def get_oauth_token_secret(self):
return self.oauth_token_secret
| TokenCredential |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_cloud_storage_transfer_service_async.py | {
"start": 1703,
"end": 10472
} | class ____:
@pytest.mark.asyncio
@mock.patch(f"{TRANSFER_HOOK_PATH}.CloudDataTransferServiceAsyncHook.get_conn")
@mock.patch(f"{TRANSFER_HOOK_PATH}.StorageTransferServiceAsyncClient")
async def test_get_conn(self, mock_async_client, mock_get_conn):
expected_value = "Async Hook"
mock_async_client.return_value = expected_value
mock_get_conn.return_value = expected_value
hook = CloudDataTransferServiceAsyncHook(project_id=TEST_PROJECT_ID)
conn_0 = await hook.get_conn()
assert conn_0 == expected_value
conn_1 = await hook.get_conn()
assert conn_1 == expected_value
assert id(conn_0) == id(conn_1)
@pytest.mark.asyncio
@mock.patch(f"{TRANSFER_HOOK_PATH}.CloudDataTransferServiceAsyncHook.get_conn")
@mock.patch(f"{TRANSFER_HOOK_PATH}.ListTransferJobsRequest")
async def test_get_jobs(self, mock_list_jobs_request, mock_get_conn):
expected_jobs = AsyncMock()
mock_get_conn.return_value.list_transfer_jobs.side_effect = AsyncMock(return_value=expected_jobs)
expected_request = mock.MagicMock()
mock_list_jobs_request.return_value = expected_request
hook = CloudDataTransferServiceAsyncHook(project_id=TEST_PROJECT_ID)
job_names = ["Job0", "Job1"]
jobs = await hook.get_jobs(job_names=job_names)
assert jobs == expected_jobs
mock_list_jobs_request.assert_called_once_with(
filter=json.dumps(dict(project_id=TEST_PROJECT_ID, job_names=job_names))
)
mock_get_conn.return_value.list_transfer_jobs.assert_called_once_with(request=expected_request)
@pytest.mark.asyncio
@mock.patch(f"{TRANSFER_HOOK_PATH}.CloudDataTransferServiceAsyncHook.get_conn")
@mock.patch(f"{TRANSFER_HOOK_PATH}.TransferOperation.deserialize")
async def test_get_last_operation(self, mock_deserialize, mock_conn, hook_async):
latest_operation_name = "Mock operation name"
operation_metadata_value = "Mock metadata value"
get_operation = AsyncMock()
get_operation.return_value = mock.MagicMock(metadata=mock.MagicMock(value=operation_metadata_value))
mock_conn.return_value.transport.operations_client.get_operation = get_operation
expected_operation = mock.MagicMock()
mock_deserialize.return_value = expected_operation
operation = await hook_async.get_latest_operation(
job=mock.MagicMock(latest_operation_name=latest_operation_name)
)
get_operation.assert_called_once_with(latest_operation_name)
mock_deserialize.assert_called_once_with(operation_metadata_value)
assert operation == expected_operation
@pytest.mark.asyncio
@mock.patch(f"{TRANSFER_HOOK_PATH}.CloudDataTransferServiceAsyncHook.get_conn")
@mock.patch(f"{TRANSFER_HOOK_PATH}.TransferOperation.deserialize")
async def test_get_last_operation_none(self, mock_deserialize, mock_conn, hook_async):
latest_operation_name = None
expected_operation = None
get_operation = mock.MagicMock()
mock_conn.return_value.transport.operations_client.get_operation = get_operation
operation = await hook_async.get_latest_operation(
job=mock.MagicMock(latest_operation_name=latest_operation_name)
)
get_operation.assert_not_called()
mock_deserialize.assert_not_called()
assert operation == expected_operation
@pytest.mark.asyncio
@mock.patch(f"{TRANSFER_HOOK_PATH}.CloudDataTransferServiceAsyncHook.get_conn")
@mock.patch(f"{TRANSFER_HOOK_PATH}.MessageToDict")
async def test_list_transfer_operations(self, message_to_dict, mock_conn, hook_async):
expected = [{"name": "op1"}, {"name": "op2"}]
message_to_dict.side_effect = expected
op_with_pb = SimpleNamespace(_pb=mock.sentinel.pb1)
op_without_pb = object()
first_page = mock.MagicMock(next_page_token="token", operations=[op_with_pb])
second_page = mock.MagicMock(next_page_token=None, operations=[op_without_pb])
mock_conn.return_value.list_operations.side_effect = [first_page, second_page]
actual = await hook_async.list_transfer_operations(
request_filter={"project_id": TEST_PROJECT_ID},
)
assert actual == expected
assert mock_conn.return_value.list_operations.call_count == 2
assert message_to_dict.call_args_list == [
mock.call(mock.sentinel.pb1, preserving_proto_field_name=True, use_integers_for_enums=True),
mock.call(op_without_pb, preserving_proto_field_name=True, use_integers_for_enums=True),
]
@pytest.mark.asyncio
@pytest.mark.parametrize(
("statuses", "expected_statuses"),
[
([GcpTransferOperationStatus.ABORTED], (GcpTransferOperationStatus.IN_PROGRESS,)),
(
[GcpTransferOperationStatus.SUCCESS, GcpTransferOperationStatus.ABORTED],
(GcpTransferOperationStatus.IN_PROGRESS,),
),
(
[GcpTransferOperationStatus.PAUSED, GcpTransferOperationStatus.ABORTED],
(GcpTransferOperationStatus.IN_PROGRESS,),
),
],
)
async def test_operations_contain_expected_statuses_red_path(self, statuses, expected_statuses):
def to_name(x):
return x.name if hasattr(x, "name") else x
def proto_int(name: str) -> int:
return int(getattr(TransferOperation.Status, name))
operations = [{"metadata": {"status": proto_int(to_name(s))}} for s in statuses]
expected_names = tuple(to_name(s) for s in expected_statuses)
with pytest.raises(
AirflowException,
match=f"An unexpected operation status was encountered. Expected: {', '.join(expected_names)}",
):
await CloudDataTransferServiceAsyncHook.operations_contain_expected_statuses(
operations,
GcpTransferOperationStatus.IN_PROGRESS,
)
@pytest.mark.asyncio
@pytest.mark.parametrize(
("statuses", "expected_statuses"),
[
([GcpTransferOperationStatus.ABORTED], GcpTransferOperationStatus.ABORTED),
(
[GcpTransferOperationStatus.SUCCESS, GcpTransferOperationStatus.ABORTED],
GcpTransferOperationStatus.ABORTED,
),
(
[GcpTransferOperationStatus.PAUSED, GcpTransferOperationStatus.ABORTED],
GcpTransferOperationStatus.ABORTED,
),
([GcpTransferOperationStatus.ABORTED], (GcpTransferOperationStatus.ABORTED,)),
(
[GcpTransferOperationStatus.SUCCESS, GcpTransferOperationStatus.ABORTED],
(GcpTransferOperationStatus.ABORTED,),
),
(
[GcpTransferOperationStatus.PAUSED, GcpTransferOperationStatus.ABORTED],
(GcpTransferOperationStatus.ABORTED,),
),
],
)
async def test_operations_contain_expected_statuses_green_path(self, statuses, expected_statuses):
to_name = lambda x: x.name if hasattr(x, "name") else x
name_to_proto_int = lambda name: int(getattr(TransferOperation.Status, name))
operations = [{"metadata": {"status": name_to_proto_int(to_name(s))}} for s in statuses]
if isinstance(expected_statuses, (list, tuple, set)):
expected_norm = {to_name(s) for s in expected_statuses}
else:
expected_norm = to_name(expected_statuses)
result = await CloudDataTransferServiceAsyncHook.operations_contain_expected_statuses(
operations, expected_norm
)
assert result is True
@pytest.mark.asyncio
@mock.patch(f"{TRANSFER_HOOK_PATH}.CloudDataTransferServiceAsyncHook.get_conn")
@mock.patch(f"{TRANSFER_HOOK_PATH}.RunTransferJobRequest")
async def test_run_transfer_job(self, mock_run_transfer_job_request, mock_get_conn):
expected_job_result = AsyncMock()
mock_get_conn.return_value.run_transfer_job.side_effect = AsyncMock(return_value=expected_job_result)
expected_request = mock.MagicMock()
mock_run_transfer_job_request.return_value = expected_request
hook = CloudDataTransferServiceAsyncHook(project_id=TEST_PROJECT_ID)
job_name = "Job0"
jobs = await hook.run_transfer_job(job_name=job_name)
assert jobs == expected_job_result
mock_run_transfer_job_request.assert_called_once_with(project_id=TEST_PROJECT_ID, job_name=job_name)
mock_get_conn.return_value.run_transfer_job.assert_called_once_with(request=expected_request)
| TestCloudDataTransferServiceAsyncHook |
python | pytorch__pytorch | test/mobile/model_test/tensor_ops.py | {
"start": 5128,
"end": 7301
} | class ____(torch.nn.Module):
def forward(self):
return self.tensor_indexing_ops()
def tensor_indexing_ops(self):
x = torch.randn(2, 4)
y = torch.randn(4, 4)
t = torch.tensor([[0, 0], [1, 0]])
mask = x.ge(0.5)
i = [0, 1]
return len(
torch.cat((x, x, x), 0),
torch.concat((x, x, x), 0),
torch.conj(x),
torch.chunk(x, 2),
torch.dsplit(torch.randn(2, 2, 4), i),
torch.column_stack((x, x)),
torch.dstack((x, x)),
torch.gather(x, 0, t),
torch.hsplit(x, i),
torch.hstack((x, x)),
torch.index_select(x, 0, torch.tensor([0, 1])),
x.index(t),
torch.masked_select(x, mask),
torch.movedim(x, 1, 0),
torch.moveaxis(x, 1, 0),
torch.narrow(x, 0, 0, 2),
torch.nonzero(x),
torch.permute(x, (0, 1)),
torch.reshape(x, (-1,)),
torch.row_stack((x, x)),
torch.select(x, 0, 0),
torch.scatter(x, 0, t, x),
x.scatter(0, t, x.clone()),
torch.diagonal_scatter(y, torch.ones(4)),
torch.select_scatter(y, torch.ones(4), 0, 0),
torch.slice_scatter(x, x),
torch.scatter_add(x, 0, t, x),
x.scatter_(0, t, y),
x.scatter_add_(0, t, y),
# torch.scatter_reduce(x, 0, t, reduce="sum"),
torch.split(x, 1),
torch.squeeze(x, 0),
torch.stack([x, x]),
torch.swapaxes(x, 0, 1),
torch.swapdims(x, 0, 1),
torch.t(x),
torch.take(x, t),
torch.take_along_dim(x, torch.argmax(x)),
torch.tensor_split(x, 1),
torch.tensor_split(x, [0, 1]),
torch.tile(x, (2, 2)),
torch.transpose(x, 0, 1),
torch.unbind(x),
torch.unsqueeze(x, -1),
torch.vsplit(x, i),
torch.vstack((x, x)),
torch.where(x),
torch.where(t > 0, t, 0),
torch.where(t > 0, t, t),
)
| TensorIndexingOpsModule |
python | huggingface__transformers | src/transformers/models/blt/modeling_blt.py | {
"start": 3602,
"end": 6716
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: BltConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.rope_type = self.config.rope_parameters["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
self.register_buffer("inv_freq", inv_freq, persistent=False)
self.original_inv_freq = inv_freq
@staticmethod
def compute_default_rope_parameters(
config: Optional[BltConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
base = config.rope_parameters["rope_theta"]
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids):
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.repeat_interleave(freqs, 2, dim=-1) # diff from Llama: we interleave() instead of cat()
cos = emb.cos() * self.attention_scaling
sin = emb.sin() * self.attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
# Modified from transformers.models.llama.modeling_llama.LlamaDecoderLayer
| BltRotaryEmbedding |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/lambdas.py | {
"start": 16378,
"end": 21097
} | class ____(
roles.AllowsLambdaRole, ExecutableStatement, LambdaElement
):
"""Represent a composable SQL statement as a :class:`_sql.LambdaElement`.
The :class:`_sql.StatementLambdaElement` is constructed using the
:func:`_sql.lambda_stmt` function::
from sqlalchemy import lambda_stmt
stmt = lambda_stmt(lambda: select(table))
Once constructed, additional criteria can be built onto the statement
by adding subsequent lambdas, which accept the existing statement
object as a single parameter::
stmt += lambda s: s.where(table.c.col == parameter)
.. versionadded:: 1.4
.. seealso::
:ref:`engine_lambda_caching`
"""
if TYPE_CHECKING:
def __init__(
self,
fn: _StmtLambdaType,
role: Type[SQLRole],
opts: Union[Type[LambdaOptions], LambdaOptions] = LambdaOptions,
apply_propagate_attrs: Optional[ClauseElement] = None,
): ...
def __add__(
self, other: _StmtLambdaElementType[Any]
) -> StatementLambdaElement:
return self.add_criteria(other)
def add_criteria(
self,
other: _StmtLambdaElementType[Any],
enable_tracking: bool = True,
track_on: Optional[Any] = None,
track_closure_variables: bool = True,
track_bound_values: bool = True,
) -> StatementLambdaElement:
"""Add new criteria to this :class:`_sql.StatementLambdaElement`.
E.g.::
>>> def my_stmt(parameter):
... stmt = lambda_stmt(
... lambda: select(table.c.x, table.c.y),
... )
... stmt = stmt.add_criteria(lambda: table.c.x > parameter)
... return stmt
The :meth:`_sql.StatementLambdaElement.add_criteria` method is
equivalent to using the Python addition operator to add a new
lambda, except that additional arguments may be added including
``track_closure_values`` and ``track_on``::
>>> def my_stmt(self, foo):
... stmt = lambda_stmt(
... lambda: select(func.max(foo.x, foo.y)),
... track_closure_variables=False,
... )
... stmt = stmt.add_criteria(lambda: self.where_criteria, track_on=[self])
... return stmt
See :func:`_sql.lambda_stmt` for a description of the parameters
accepted.
""" # noqa: E501
opts = self.opts + dict(
enable_tracking=enable_tracking,
track_closure_variables=track_closure_variables,
global_track_bound_values=self.opts.global_track_bound_values,
track_on=track_on,
track_bound_values=track_bound_values,
)
return LinkedLambdaElement(other, parent_lambda=self, opts=opts)
def _execute_on_connection(
self, connection, distilled_params, execution_options
):
if TYPE_CHECKING:
assert isinstance(self._rec.expected_expr, ClauseElement)
if self._rec.expected_expr.supports_execution:
return connection._execute_clauseelement(
self, distilled_params, execution_options
)
else:
raise exc.ObjectNotExecutableError(self)
@property
def _proxied(self) -> Any:
return self._rec_expected_expr
@property
def _with_options(self): # type: ignore[override]
return self._proxied._with_options
@property
def _effective_plugin_target(self):
return self._proxied._effective_plugin_target
@property
def _execution_options(self): # type: ignore[override]
return self._proxied._execution_options
@property
def _all_selected_columns(self):
return self._proxied._all_selected_columns
@property
def is_select(self): # type: ignore[override]
return self._proxied.is_select
@property
def is_update(self): # type: ignore[override]
return self._proxied.is_update
@property
def is_insert(self): # type: ignore[override]
return self._proxied.is_insert
@property
def is_text(self): # type: ignore[override]
return self._proxied.is_text
@property
def is_delete(self): # type: ignore[override]
return self._proxied.is_delete
@property
def is_dml(self): # type: ignore[override]
return self._proxied.is_dml
def spoil(self) -> NullLambdaStatement:
"""Return a new :class:`.StatementLambdaElement` that will run
all lambdas unconditionally each time.
"""
return NullLambdaStatement(self.fn())
| StatementLambdaElement |
python | automl__auto-sklearn | test/fixtures/automl.py | {
"start": 2638,
"end": 3182
} | class ____(AutoML):
def __init__(self) -> None:
self.__class__ = AutoML
self._task = None
self._dask_client = None # type: ignore
self._is_dask_client_internally_created = False
def __del__(self) -> None:
pass
@fixture(scope="function")
def automl_stub() -> AutoMLStub:
"""TODO remove"""
automl = AutoMLStub()
automl._seed = 42
automl._backend = Mock(spec=Backend)
automl._backend.context = Mock()
automl._delete_output_directories = lambda: 0
return automl
| AutoMLStub |
python | celery__celery | celery/local.py | {
"start": 12008,
"end": 12986
} | class ____:
def __init__(self, getter=None, setter=None):
if getter is not None and not isinstance(getter, classmethod):
getter = classmethod(getter)
if setter is not None and not isinstance(setter, classmethod):
setter = classmethod(setter)
self.__get = getter
self.__set = setter
info = getter.__get__(object) # just need the info attrs.
self.__doc__ = info.__doc__
self.__name__ = info.__name__
self.__module__ = info.__module__
def __get__(self, obj, type=None):
if obj and type is None:
type = obj.__class__
return self.__get.__get__(obj, type)()
def __set__(self, obj, value):
if obj is None:
return self
return self.__set.__get__(obj)(value)
def setter(self, setter):
return self.__class__(self.__get, setter)
def reclassmethod(method):
return classmethod(fun_of_method(method))
| class_property |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/freshness.py | {
"start": 7999,
"end": 10636
} | class ____(FreshnessPolicy, IHaveNew):
deadline_cron: str
serializable_lower_bound_delta: SerializableTimeDelta
timezone: str
def __new__(
cls,
deadline_cron: str,
lower_bound_delta: Union[timedelta, SerializableTimeDelta],
timezone: str = "UTC",
):
check.str_param(deadline_cron, "deadline_cron")
check.invariant(is_valid_cron_string(deadline_cron), "Invalid cron string.")
# Handle both construction (with timedelta) and deserialization (with SerializableTimeDelta)
if isinstance(lower_bound_delta, SerializableTimeDelta):
# During deserialization, we already have a SerializableTimeDelta
serializable_lower_bound_delta = lower_bound_delta
actual_lower_bound_delta = lower_bound_delta.to_timedelta()
else:
# During normal construction, we have a timedelta and need to convert it
actual_lower_bound_delta = lower_bound_delta
serializable_lower_bound_delta = SerializableTimeDelta.from_timedelta(lower_bound_delta)
check.invariant(
actual_lower_bound_delta >= timedelta(minutes=1),
f"lower_bound_delta must be greater than or equal to 1 minute, was {actual_lower_bound_delta.total_seconds()} seconds",
)
smallest_cron_interval = get_smallest_cron_interval(deadline_cron)
check.invariant(
actual_lower_bound_delta <= smallest_cron_interval,
f"lower_bound_delta must be less than or equal to the smallest cron interval of ({smallest_cron_interval.total_seconds()} seconds for deadline_cron {deadline_cron}). Provided lower_bound_delta is {actual_lower_bound_delta.total_seconds()} seconds",
)
try:
get_timezone(timezone)
# Would be better to catch a specific exception type here,
# but it's more complicated because we use different timezone libraries
# depending on the Python version.
except Exception:
raise check.CheckError(f"Invalid IANA timezone: {timezone}")
return super().__new__(
cls,
deadline_cron=deadline_cron,
serializable_lower_bound_delta=serializable_lower_bound_delta,
timezone=timezone,
)
@property
def lower_bound_delta(self) -> timedelta:
"""Returns the lower bound delta as a timedelta.
Use this instead of accessing the serializable_lower_bound_delta directly.
"""
return SerializableTimeDelta.to_timedelta(self.serializable_lower_bound_delta)
@whitelist_for_serdes
@record
| CronFreshnessPolicy |
python | scikit-image__scikit-image | tests/skimage/io/test_tifffile.py | {
"start": 1481,
"end": 2665
} | class ____:
def roundtrip(self, dtype, x, use_pathlib=False, **kwargs):
with NamedTemporaryFile(suffix='.tif') as f:
fname = f.name
if use_pathlib:
fname = pathlib.Path(fname)
imsave(fname, x, check_contrast=False, **kwargs)
y = imread(fname)
assert_array_equal(x, y)
shapes = ((10, 10), (10, 10, 3), (10, 10, 4))
dtypes = (np.uint8, np.uint16, np.float32, np.int16, np.float64)
@pytest.mark.parametrize("shape", shapes)
@pytest.mark.parametrize("dtype", dtypes)
@pytest.mark.parametrize("use_pathlib", [False, True])
@pytest.mark.parametrize('explicit_photometric_kwarg', [False, True])
def test_imsave_roundtrip(
self, shape, dtype, use_pathlib, explicit_photometric_kwarg
):
x = np.random.rand(*shape)
if not np.issubdtype(dtype, np.floating):
x = (x * np.iinfo(dtype).max).astype(dtype)
else:
x = x.astype(dtype)
if explicit_photometric_kwarg and x.shape[-1] in [3, 4]:
kwargs = {'photometric': 'rgb'}
else:
kwargs = {}
self.roundtrip(dtype, x, use_pathlib, **kwargs)
| TestSave |
python | scipy__scipy | scipy/linalg/tests/test_decomp.py | {
"start": 49383,
"end": 51112
} | class ____:
@pytest.mark.parametrize('dt', [int, float, np.float32, complex, np.complex64])
def test_empty(self, dt):
for a in [[]], np.empty((2, 0)), np.ones((0, 3)):
a = np.array(a, dtype=dt)
s = svdvals(a)
assert_equal(s, np.empty(0))
s0 = svdvals(np.eye(2, dtype=dt))
assert s.dtype == s0.dtype
def test_simple(self):
a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
s = svdvals(a)
assert_(len(s) == 3)
assert_(s[0] >= s[1] >= s[2])
def test_simple_underdet(self):
a = [[1, 2, 3], [4, 5, 6]]
s = svdvals(a)
assert_(len(s) == 2)
assert_(s[0] >= s[1])
def test_simple_overdet(self):
a = [[1, 2], [4, 5], [3, 4]]
s = svdvals(a)
assert_(len(s) == 2)
assert_(s[0] >= s[1])
def test_simple_complex(self):
a = [[1, 2, 3], [1, 20, 3j], [2, 5, 6]]
s = svdvals(a)
assert_(len(s) == 3)
assert_(s[0] >= s[1] >= s[2])
def test_simple_underdet_complex(self):
a = [[1, 2, 3], [4, 5j, 6]]
s = svdvals(a)
assert_(len(s) == 2)
assert_(s[0] >= s[1])
def test_simple_overdet_complex(self):
a = [[1, 2], [4, 5], [3j, 4]]
s = svdvals(a)
assert_(len(s) == 2)
assert_(s[0] >= s[1])
def test_check_finite(self):
a = [[1, 2, 3], [1, 2, 3], [2, 5, 6]]
s = svdvals(a, check_finite=False)
assert_(len(s) == 3)
assert_(s[0] >= s[1] >= s[2])
@pytest.mark.slow
def test_crash_2609(self):
rng = np.random.default_rng(1234)
a = rng.random((1500, 2800))
# Shouldn't crash:
svdvals(a)
| TestSVDVals |
python | huggingface__transformers | src/transformers/integrations/mxfp4.py | {
"start": 9492,
"end": 25818
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.num_experts = config.num_local_experts
self.intermediate_size = config.intermediate_size
self.hidden_size = config.hidden_size
self.gate_up_proj = nn.Parameter(
torch.zeros(self.num_experts, 2 * self.intermediate_size, self.hidden_size // 32, 16, dtype=torch.uint8),
requires_grad=False,
)
self.gate_up_proj_bias = nn.Parameter(
torch.zeros(self.num_experts, 2 * self.intermediate_size, dtype=torch.float32), requires_grad=False
)
self.down_proj = nn.Parameter(
torch.zeros((self.num_experts, self.hidden_size, self.intermediate_size // 32, 16), dtype=torch.uint8),
requires_grad=False,
)
self.down_proj_bias = nn.Parameter(
torch.zeros(self.num_experts, self.hidden_size, dtype=torch.float32), requires_grad=False
)
self.alpha = 1.702
self.limit = getattr(config, "swiglu_limit", 7.0)
self.gate_up_proj_precision_config = None
self.down_proj_precision_config = None
self.limit = getattr(config, "swiglu_limit", 7.0)
def forward(self, hidden_states: torch.Tensor, routing_data, gather_idx, scatter_idx) -> torch.Tensor:
FnSpecs, FusedActivation, matmul_ogs = (
triton_kernels_hub.matmul_ogs.FnSpecs,
triton_kernels_hub.matmul_ogs.FusedActivation,
triton_kernels_hub.matmul_ogs.matmul_ogs,
)
swiglu_fn = triton_kernels_hub.swiglu.swiglu_fn
with on_device(hidden_states.device):
act = FusedActivation(FnSpecs("swiglu", swiglu_fn, ("alpha", "limit")), (self.alpha, self.limit), 2)
intermediate_cache1 = matmul_ogs(
hidden_states,
self.gate_up_proj,
self.gate_up_proj_bias.to(torch.float32),
routing_data,
gather_indx=gather_idx,
precision_config=self.gate_up_proj_precision_config,
gammas=None,
fused_activation=act,
)
intermediate_cache3 = matmul_ogs(
intermediate_cache1,
self.down_proj,
self.down_proj_bias.to(torch.float32),
routing_data,
scatter_indx=scatter_idx,
precision_config=self.down_proj_precision_config,
gammas=routing_data.gate_scal,
)
return intermediate_cache3
# Adapted from GPT_OSS repo
# TODO: Add absolute link when the repo is public
def routing_torch_dist(
logits,
n_expts_act,
):
import os
GatherIndx, RoutingData, ScatterIndx, compute_expt_data_torch = (
triton_kernels_hub.routing.GatherIndx,
triton_kernels_hub.routing.RoutingData,
triton_kernels_hub.routing.ScatterIndx,
triton_kernels_hub.routing.compute_expt_data_torch,
)
with on_device(logits.device):
world_size = torch.distributed.get_world_size()
rank = int(os.environ.get("LOCAL_RANK", "0"))
replace_value = -1
n_tokens = logits.shape[0]
n_expts_tot = logits.shape[1]
n_local_experts = n_expts_tot // world_size
local_expert_start = rank * n_local_experts
local_expert_end = (rank + 1) * n_local_experts
n_gates_pad = n_tokens * n_expts_act
def topk(vals, k):
tk_indx = torch.argsort(-vals, dim=1, stable=True)[:, :k]
tk_indx = tk_indx.long()
tk_val = torch.take_along_dim(vals, tk_indx, dim=1)
return tk_val, tk_indx.int()
expt_scal, expt_indx = topk(logits, n_expts_act)
expt_scal = torch.softmax(expt_scal, dim=-1)
expt_indx, sort_indices = torch.sort(expt_indx, dim=1)
expt_scal = torch.gather(expt_scal, 1, sort_indices)
# Flatten and mask for local experts
expt_scal = expt_scal.reshape(-1)
hist = torch.histc(expt_indx, bins=n_expts_tot, max=n_expts_tot - 1)[local_expert_start:local_expert_end]
expt_indx = expt_indx.view(-1).to(torch.int32)
# we use a large value to replace the indices that are not in the local expert range
var = 1000
expt_indx = torch.where(expt_indx < local_expert_start, var, expt_indx)
topk_indx = torch.argsort(expt_indx, stable=True).to(torch.int32)
gate_indx = torch.argsort(topk_indx).to(torch.int32)
expt_indx = torch.where(expt_indx < local_expert_end, expt_indx, replace_value)
expt_indx = torch.where(local_expert_start <= expt_indx, expt_indx, replace_value)
gate_indx = torch.where(expt_indx == replace_value, replace_value, gate_indx)
gate_scal = expt_scal[topk_indx]
topk_indx = torch.where(gate_indx[topk_indx] == replace_value, replace_value, topk_indx)
# # Routing metadata for local expert computation
gather_indx = GatherIndx(src_indx=topk_indx.int(), dst_indx=gate_indx.int())
scatter_indx = ScatterIndx(src_indx=gate_indx.int(), dst_indx=topk_indx.int())
expt_data = compute_expt_data_torch(hist, n_local_experts, n_gates_pad)
hit_experts = n_expts_act
return RoutingData(gate_scal, hist, n_local_experts, hit_experts, expt_data), gather_indx, scatter_indx
def mlp_forward(self, hidden_states):
import torch.distributed as dist
if dist.is_available() and dist.is_initialized() and hasattr(self, "_is_hooked"):
routing = routing_torch_dist
else:
routing = triton_kernels_hub.routing.routing
batch_size = hidden_states.shape[0]
hidden_states = hidden_states.reshape(-1, self.router.hidden_dim)
router_logits = nn.functional.linear(hidden_states, self.router.weight, self.router.bias)
with on_device(router_logits.device):
routing_data, gather_idx, scatter_idx = routing(router_logits, self.router.top_k)
routed_out = self.experts(hidden_states, routing_data, gather_idx, scatter_idx)
routed_out = routed_out.reshape(batch_size, -1, self.router.hidden_dim)
return routed_out, router_logits
def should_convert_module(current_key_name, patterns):
current_key_name_str = ".".join(current_key_name)
if not any(
re.match(f"{key}\\.", current_key_name_str) or re.match(f"{key}", current_key_name_str) for key in patterns
):
return True
return False
def dequantize(module, param_name, param_value, target_device, dq_param_name, **kwargs):
from ..integrations.tensor_parallel import shard_and_distribute_module
model = kwargs.get("model")
empty_param = kwargs.get("empty_param")
casting_dtype = kwargs.get("casting_dtype")
to_contiguous = kwargs.get("to_contiguous")
rank = kwargs.get("rank")
device_mesh = kwargs.get("device_mesh")
for proj in ["gate_up_proj", "down_proj"]:
if proj in param_name:
if device_mesh is not None:
param_value = shard_and_distribute_module(
model,
param_value,
empty_param,
dq_param_name,
casting_dtype,
to_contiguous,
rank,
device_mesh,
)
blocks_attr = f"{proj}_blocks"
scales_attr = f"{proj}_scales"
setattr(module, param_name.rsplit(".", 1)[1], param_value)
if hasattr(module, blocks_attr) and hasattr(module, scales_attr):
dequantized = convert_moe_packed_tensors(getattr(module, blocks_attr), getattr(module, scales_attr))
if target_device == "cpu" and torch.cuda.is_available():
torch.cuda.empty_cache()
elif target_device == "cpu" and is_torch_xpu_available():
torch.xpu.empty_cache()
setattr(module, proj, torch.nn.Parameter(dequantized.to(target_device)))
delattr(module, blocks_attr)
delattr(module, scales_attr)
def dequantize_convertops(blocks, scales, target_device):
dequantized = convert_moe_packed_tensors(blocks, scales)
if target_device == "cpu" and torch.cuda.is_available():
torch.cuda.empty_cache()
dequantized = torch.nn.Parameter(dequantized.to(target_device))
return dequantized
def load_and_swizzle_mxfp4(module, param_name, param_value, target_device, triton_kernels_hub, **kwargs):
"""
This transforms the weights obtained using `convert_gpt_oss.py` to load them into `Mxfp4GptOssExperts`.
"""
PrecisionConfig, FlexCtx, InFlexData = (
triton_kernels_hub.matmul_ogs.PrecisionConfig,
triton_kernels_hub.matmul_ogs.FlexCtx,
triton_kernels_hub.matmul_ogs.InFlexData,
)
from ..integrations.tensor_parallel import shard_and_distribute_module
model = kwargs.get("model")
empty_param = kwargs.get("empty_param")
casting_dtype = kwargs.get("casting_dtype")
to_contiguous = kwargs.get("to_contiguous")
rank = kwargs.get("rank")
device_mesh = kwargs.get("device_mesh")
if "blocks" in param_name:
proj = param_name.split(".")[-1].split("_blocks")[0]
if "scales" in param_name:
proj = param_name.split(".")[-1].split("_scales")[0]
if device_mesh is not None:
shard_and_distribute_module(
model, param_value, empty_param, param_name, casting_dtype, to_contiguous, rank, device_mesh
)
else:
setattr(module, param_name.rsplit(".", 1)[1], torch.nn.Parameter(param_value, requires_grad=False))
blocks_attr = f"{proj}_blocks"
scales_attr = f"{proj}_scales"
blocks = getattr(module, blocks_attr) # at this point values were loaded from ckpt
scales = getattr(module, scales_attr)
# Check if both blocks and scales both not on meta device
if blocks.device.type != "meta" and scales.device.type != "meta":
local_experts = blocks.size(0)
if proj == "gate_up_proj":
blocks = blocks.reshape(local_experts, module.intermediate_size * 2, -1)
else:
blocks = blocks.reshape(local_experts, -1, module.intermediate_size // 2)
if getattr(target_device, "type", target_device) == "cpu":
target_device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
blocks = blocks.to(target_device).contiguous()
scales = scales.to(target_device).contiguous()
with on_device(target_device):
triton_weight_tensor, weight_scale = swizzle_mxfp4(
blocks.transpose(-2, -1), scales.transpose(-2, -1), triton_kernels_hub
)
# need to overwrite the shapes for the kernels
if proj == "gate_up_proj":
triton_weight_tensor.shape = torch.Size([local_experts, module.hidden_size, module.intermediate_size * 2])
else:
triton_weight_tensor.shape = torch.Size([local_experts, module.intermediate_size, module.hidden_size])
# triton_weight_tensor is what needs to be passed in oai kernels. It stores the data, the shapes and any more objects. It is like a subtensor
setattr(module, proj, triton_weight_tensor)
setattr(
module,
f"{proj}_precision_config",
PrecisionConfig(weight_scale=weight_scale, flex_ctx=FlexCtx(rhs_data=InFlexData())),
)
# delete blocks and scales
delattr(module, scales_attr)
delattr(module, blocks_attr)
del blocks
def swizzle_mxfp4_convertops(blocks, scales, module, proj, target_device, triton_kernels_hub):
"""
This transforms the weights obtained using `convert_gpt_oss.py` to load them into `Mxfp4GptOssExperts`.
"""
PrecisionConfig, FlexCtx, InFlexData = (
triton_kernels_hub.matmul_ogs.PrecisionConfig,
triton_kernels_hub.matmul_ogs.FlexCtx,
triton_kernels_hub.matmul_ogs.InFlexData,
)
local_experts = blocks.size(0)
if getattr(target_device, "type", target_device) == "cpu":
target_device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
blocks = blocks.to(target_device).contiguous()
scales = scales.to(target_device).contiguous()
if proj == "gate_up_proj":
blocks = blocks.reshape(local_experts, module.intermediate_size * 2, -1)
else:
blocks = blocks.reshape(local_experts, -1, module.intermediate_size // 2)
if getattr(target_device, "type", target_device) == "cpu":
target_device = "cuda"
with on_device(target_device):
triton_weight_tensor, weight_scale = swizzle_mxfp4(
blocks.transpose(-2, -1), scales.transpose(-2, -1), triton_kernels_hub
)
# need to overwrite the shapes for the kernels
if proj == "gate_up_proj":
triton_weight_tensor.shape = torch.Size([local_experts, module.hidden_size, module.intermediate_size * 2])
else:
triton_weight_tensor.shape = torch.Size([local_experts, module.intermediate_size, module.hidden_size])
# triton_weight_tensor is what needs to be passed in oai kernels. It stores the data, the shapes and any more objects. It's like a subtensor
# Since the Experts module registers gate_up_proj and down_proj as nn.Parameters, we need to remove them so we can attach the Triton tensor
if proj in module._parameters:
# Remove the nn.Parameter registration so we can attach the Triton tensor
del module._parameters[proj]
setattr(module, proj, triton_weight_tensor)
setattr(
module,
f"{proj}_precision_config",
PrecisionConfig(weight_scale=weight_scale, flex_ctx=FlexCtx(rhs_data=InFlexData())),
)
def _replace_with_mxfp4_linear(
model,
modules_to_not_convert=None,
current_key_name=None,
quantization_config=None,
has_been_replaced=False,
config=None,
):
if current_key_name is None:
current_key_name = []
for name, module in model.named_children():
current_key_name.append(name)
if not should_convert_module(current_key_name, modules_to_not_convert):
current_key_name.pop(-1)
continue
if module.__class__.__name__ == "GptOssExperts" and not quantization_config.dequantize:
with init_empty_weights():
model._modules[name] = Mxfp4GptOssExperts(config)
has_been_replaced = True
if module.__class__.__name__ == "GptOssMLP" and not quantization_config.dequantize:
from types import MethodType
module.forward = MethodType(mlp_forward, module)
if len(list(module.children())) > 0:
_, has_been_replaced = _replace_with_mxfp4_linear(
module,
modules_to_not_convert,
current_key_name,
quantization_config,
has_been_replaced=has_been_replaced,
config=config,
)
current_key_name.pop(-1)
return model, has_been_replaced
def replace_with_mxfp4_linear(
model,
modules_to_not_convert=None,
current_key_name=None,
quantization_config=None,
config=None,
):
if quantization_config.dequantize:
return model
else:
from kernels import get_kernel
global triton_kernels_hub
triton_kernels_hub = get_kernel("kernels-community/triton_kernels")
modules_to_not_convert = ["lm_head"] if modules_to_not_convert is None else modules_to_not_convert
if quantization_config.modules_to_not_convert is not None:
modules_to_not_convert.extend(quantization_config.modules_to_not_convert)
modules_to_not_convert = list(set(modules_to_not_convert))
model, has_been_replaced = _replace_with_mxfp4_linear(
model,
modules_to_not_convert,
current_key_name,
quantization_config,
config=config,
)
if not has_been_replaced:
logger.warning(
"You are loading your model using mixed-precision FP4 quantization but no linear modules were found in your model."
" Please double check your model architecture, or submit an issue on github if you think this is"
" a bug."
)
return model
| Mxfp4GptOssExperts |
python | google__jax | tests/multiprocess/device_id_test.py | {
"start": 691,
"end": 3082
} | class ____(jt_multiprocess.MultiProcessTest):
def testDeviceIds(self):
# TODO(phawkins): TPU process IDs won't necessarily match the global
# process index.
if not jtu.test_device_matches(["tpu"]):
self.assertEqual(
jax.process_index(),
jt_multiprocess.MULTIPROCESS_TEST_WORKER_ID.value,
)
self.assertLen(
jax.devices(),
jt_multiprocess.NUM_PROCESSES.value * jax.local_device_count(),
)
self.assertEqual(
jax.local_devices()[0].process_index,
jax.process_index(),
)
def testPrimitive(self):
with jax.default_device(jax.local_devices(backend="cpu")[0]):
self.assertEqual(2, jax.lax.neg(jax.lax.neg(2)))
def testJit(self):
"""Verifies that local computation works inside a distributed job."""
x = jax.device_put(1)
self.assertEqual(x, 1)
y = jax.jit(lambda x: x + 1)(x)
self.assertEqual(y, 2)
# TODO(phawkins): this test CHECK-fails on TPU.
@jtu.skip_on_devices("tpu")
def testNonaddressableDeviceToDevicePut(self):
source_device = jax.local_devices(backend="cpu")[0]
x = jax.device_put(0, source_device)
for device in jax.devices():
if device.process_index != jax.process_index():
with self.assertRaisesRegex(
RuntimeError,
"(Cannot copy array to non-addressable device.*|.*is not a local"
" device.*)",
):
jax.device_put(x, device)
def testDefaultDevicePlatformString(self):
with jax.default_device("cpu"):
result = jax.jit(lambda x: x + 1)(1)
self.assertEqual(result.device.platform, "cpu")
self.assertEqual(result.device, jax.local_devices(backend="cpu")[0])
result = jax.jit(lambda x: x + 1)(1)
self.assertEqual(result.device.platform, jax.default_backend())
self.assertEqual(result.device, jax.local_devices()[0])
# def testCrossProcessReduceScatter(self):
# i = multiprocess_test.MULTIPROCESS_TEST_WORKER_ID.value
# n = multiprocess_test.NUM_PROCESSES.value
# f = jax.pmap(
# lambda x: lax.psum_scatter(
# x,
# "i",
# ),
# axis_name="i",
# )
# x = np.arange(n * n).reshape(n, n)
# out = f(x[i : i + 1])
# expected = np.sum(x, axis=0)
# np.testing.assert_allclose(expected[i : i + 1], out)
if __name__ == "__main__":
jt_multiprocess.main()
| DeviceIdTest |
python | numba__numba | numba/tests/test_ufuncs.py | {
"start": 32839,
"end": 45907
} | class ____(BaseUFuncTest, TestCase):
def _check_results(self, expected, got):
self.assertEqual(expected.dtype.kind, got.dtype.kind)
np.testing.assert_array_almost_equal(expected, got)
def unary_op_test(self, operator, nrt=True,
skip_inputs=None, additional_inputs=None,
int_output_type=None, float_output_type=None):
if skip_inputs is None:
skip_inputs = []
if additional_inputs is None:
additional_inputs = []
operator_func = _make_unary_ufunc_op_usecase(operator)
inputs = list(self.inputs)
inputs.extend(additional_inputs)
pyfunc = operator_func
for input_tuple in inputs:
input_operand, input_type = input_tuple
if ((input_type in skip_inputs) or
(not isinstance(input_type, types.Array))):
continue
cfunc = self._compile(pyfunc, (input_type,), nrt=nrt)
expected = pyfunc(input_operand)
got = cfunc(input_operand)
self._check_results(expected, got)
def binary_op_test(self, operator, nrt=True,
skip_inputs=None, additional_inputs=None,
int_output_type=None, float_output_type=None,
positive_rhs=False):
if skip_inputs is None:
skip_inputs = []
if additional_inputs is None:
additional_inputs = []
operator_func = _make_binary_ufunc_op_usecase(operator)
inputs = list(self.inputs)
inputs.extend(additional_inputs)
pyfunc = operator_func
# when generating arbitrary sequences, we use a fixed seed
# for deterministic testing
random_state = np.random.RandomState(1)
for input_tuple in inputs:
input_operand1, input_type = input_tuple
input_dtype = numpy_support.as_dtype(
getattr(input_type, "dtype", input_type))
input_type1 = input_type
if input_type in skip_inputs:
continue
if positive_rhs:
zero = np.zeros(1, dtype=input_dtype)[0]
# If we only use two scalars, the code generator will not
# select the ufunctionalized operator, so we mix it up.
if isinstance(input_type, types.Array):
input_operand0 = input_operand1
input_type0 = input_type
if positive_rhs and np.any(input_operand1 < zero):
continue
else:
input_operand0 = (random_state.uniform(0, 100, 10)).astype(
input_dtype)
input_type0 = typeof(input_operand0)
if positive_rhs and input_operand1 < zero:
continue
args = (input_type0, input_type1)
cfunc = self._compile(pyfunc, args, nrt=nrt)
expected = pyfunc(input_operand0, input_operand1)
got = cfunc(input_operand0, input_operand1)
self._check_results(expected, got)
def bitwise_additional_inputs(self):
# For bitwise operators, we want to check the results for boolean
# arrays (see #1813).
return [
(True, types.boolean),
(False, types.boolean),
(np.array([True, False]), types.Array(types.boolean, 1, 'C')),
]
def binary_int_op_test(self, *args, **kws):
skip_inputs = kws.setdefault('skip_inputs', [])
skip_inputs += [
types.float32, types.float64,
types.Array(types.float32, 1, 'C'),
types.Array(types.float64, 1, 'C'),
]
return self.binary_op_test(*args, **kws)
def binary_bitwise_op_test(self, *args, **kws):
additional_inputs = kws.setdefault('additional_inputs', [])
additional_inputs += self.bitwise_additional_inputs()
return self.binary_int_op_test(*args, **kws)
def inplace_op_test(self, operator, lhs_values, rhs_values,
lhs_dtypes, rhs_dtypes, precise=True):
operator_func = _make_inplace_ufunc_op_usecase(operator)
pyfunc = operator_func
if precise:
assertion = self.assertPreciseEqual
else:
assertion = np.testing.assert_allclose
# The left operand can only be an array, while the right operand
# can be either an array or a scalar
lhs_inputs = [np.array(lhs_values, dtype=dtype)
for dtype in lhs_dtypes]
rhs_arrays = [np.array(rhs_values, dtype=dtype)
for dtype in rhs_dtypes]
rhs_scalars = [dtype(v) for v in rhs_values for dtype in rhs_dtypes]
rhs_inputs = rhs_arrays + rhs_scalars
for lhs, rhs in itertools.product(lhs_inputs, rhs_inputs):
lhs_type = typeof(lhs)
rhs_type = typeof(rhs)
args = (lhs_type, rhs_type)
cfunc = self._compile(pyfunc, args)
expected = lhs.copy()
pyfunc(expected, rhs)
got = lhs.copy()
cfunc(got, rhs)
assertion(got, expected)
def inplace_float_op_test(self, operator, lhs_values, rhs_values,
precise=True):
# Also accept integer inputs for the right operand (they should
# be converted to float).
return self.inplace_op_test(operator, lhs_values, rhs_values,
(np.float32, np.float64),
(np.float32, np.float64, np.int64),
precise=precise)
def inplace_int_op_test(self, operator, lhs_values, rhs_values):
self.inplace_op_test(operator, lhs_values, rhs_values,
(np.int16, np.int32, np.int64),
(np.int16, np.uint32))
def inplace_bitwise_op_test(self, operator, lhs_values, rhs_values):
self.inplace_int_op_test(operator, lhs_values, rhs_values)
self.inplace_op_test(operator, lhs_values, rhs_values,
(np.bool_,), (np.bool_, np.bool_))
# ____________________________________________________________
# Unary operators
def test_unary_positive_array_op(self):
self.unary_op_test('+')
def test_unary_negative_array_op(self):
self.unary_op_test('-')
def test_unary_invert_array_op(self):
self.unary_op_test('~',
skip_inputs=[types.float32, types.float64,
types.Array(types.float32, 1, 'C'),
types.Array(types.float64, 1, 'C')],
additional_inputs=self.bitwise_additional_inputs())
# ____________________________________________________________
# Inplace operators
def test_inplace_add(self):
self.inplace_float_op_test('+=', [-1, 1.5, 3], [-5, 0, 2.5])
self.inplace_float_op_test(operator.iadd, [-1, 1.5, 3], [-5, 0, 2.5])
def test_inplace_sub(self):
self.inplace_float_op_test('-=', [-1, 1.5, 3], [-5, 0, 2.5])
self.inplace_float_op_test(operator.isub, [-1, 1.5, 3], [-5, 0, 2.5])
def test_inplace_mul(self):
self.inplace_float_op_test('*=', [-1, 1.5, 3], [-5, 0, 2.5])
self.inplace_float_op_test(operator.imul, [-1, 1.5, 3], [-5, 0, 2.5])
def test_inplace_floordiv(self):
self.inplace_float_op_test('//=', [-1, 1.5, 3], [-5, 1.25, 2.5])
self.inplace_float_op_test(operator.ifloordiv, [-1, 1.5, 3],
[-5, 1.25, 2.5])
def test_inplace_div(self):
self.inplace_float_op_test('/=', [-1, 1.5, 3], [-5, 0, 2.5])
self.inplace_float_op_test(operator.itruediv, [-1, 1.5, 3],
[-5, 1.25, 2.5])
def test_inplace_remainder(self):
self.inplace_float_op_test('%=', [-1, 1.5, 3], [-5, 2, 2.5])
self.inplace_float_op_test(operator.imod, [-1, 1.5, 3], [-5, 2, 2.5])
def test_inplace_pow(self):
self.inplace_float_op_test('**=', [-1, 1.5, 3], [-5, 2, 2.5],
precise=False)
self.inplace_float_op_test(operator.ipow, [-1, 1.5, 3], [-5, 2, 2.5],
precise=False)
def test_inplace_and(self):
self.inplace_bitwise_op_test('&=', [0, 1, 2, 3, 51],
[0, 13, 16, 42, 255])
self.inplace_bitwise_op_test(operator.iand, [0, 1, 2, 3, 51],
[0, 13, 16, 42, 255])
def test_inplace_or(self):
self.inplace_bitwise_op_test('|=', [0, 1, 2, 3, 51],
[0, 13, 16, 42, 255])
self.inplace_bitwise_op_test(operator.ior, [0, 1, 2, 3, 51],
[0, 13, 16, 42, 255])
def test_inplace_xor(self):
self.inplace_bitwise_op_test('^=', [0, 1, 2, 3, 51],
[0, 13, 16, 42, 255])
self.inplace_bitwise_op_test(operator.ixor, [0, 1, 2, 3, 51],
[0, 13, 16, 42, 255])
def test_inplace_lshift(self):
self.inplace_int_op_test('<<=', [0, 5, -10, -51], [0, 1, 4, 14])
self.inplace_int_op_test(operator.ilshift, [0, 5, -10, -51],
[0, 1, 4, 14])
def test_inplace_rshift(self):
self.inplace_int_op_test('>>=', [0, 5, -10, -51], [0, 1, 4, 14])
self.inplace_int_op_test(operator.irshift, [0, 5, -10, -51],
[0, 1, 4, 14])
def test_unary_positive_array_op_2(self):
'''
Verify that the unary positive operator copies values, and doesn't
just alias to the input array (mirrors normal Numpy/Python
interaction behavior).
'''
# Test originally from @gmarkall
def f(a1):
a2 = +a1
a1[0] = 3
a2[1] = 4
return a2
a1 = np.zeros(10)
a2 = f(a1)
self.assertTrue(a1[0] != a2[0] and a1[1] != a2[1])
a3 = np.zeros(10)
a4 = njit(f)(a3)
self.assertTrue(a3[0] != a4[0] and a3[1] != a4[1])
np.testing.assert_array_equal(a1, a3)
np.testing.assert_array_equal(a2, a4)
# ____________________________________________________________
# Binary operators
def test_add_array_op(self):
self.binary_op_test('+')
def test_subtract_array_op(self):
self.binary_op_test('-')
def test_multiply_array_op(self):
self.binary_op_test('*')
def test_divide_array_op(self):
int_out_type = None
int_out_type = types.float64
self.binary_op_test('/', int_output_type=int_out_type)
def test_floor_divide_array_op(self):
# Avoid floating-point zeros as x // 0.0 can have varying results
# depending on the algorithm (which changed across Numpy versions)
self.inputs = [
(np.uint32(1), types.uint32),
(np.int32(-2), types.int32),
(np.int32(0), types.int32),
(np.uint64(4), types.uint64),
(np.int64(-5), types.int64),
(np.int64(0), types.int64),
(np.float32(-0.5), types.float32),
(np.float32(1.5), types.float32),
(np.float64(-2.5), types.float64),
(np.float64(3.5), types.float64),
(np.array([1,2], dtype='u4'), types.Array(types.uint32, 1, 'C')),
(np.array([3,4], dtype='u8'), types.Array(types.uint64, 1, 'C')),
(np.array([-1,1,5], dtype='i4'), types.Array(types.int32, 1, 'C')),
(np.array([-1,1,6], dtype='i8'), types.Array(types.int64, 1, 'C')),
(np.array([-0.5, 1.5], dtype='f4'),
types.Array(types.float32, 1, 'C')),
(np.array([-2.5, 3.5], dtype='f8'),
types.Array(types.float64, 1, 'C')),
]
self.binary_op_test('//')
def test_remainder_array_op(self):
self.binary_op_test('%')
def test_power_array_op(self):
self.binary_op_test('**', positive_rhs=True)
def test_left_shift_array_op(self):
self.binary_int_op_test('<<', positive_rhs=True)
def test_right_shift_array_op(self):
self.binary_int_op_test('>>', positive_rhs=True)
def test_bitwise_and_array_op(self):
self.binary_bitwise_op_test('&')
def test_bitwise_or_array_op(self):
self.binary_bitwise_op_test('|')
def test_bitwise_xor_array_op(self):
self.binary_bitwise_op_test('^')
def test_equal_array_op(self):
self.binary_op_test('==')
def test_greater_array_op(self):
self.binary_op_test('>')
def test_greater_equal_array_op(self):
self.binary_op_test('>=')
def test_less_array_op(self):
self.binary_op_test('<')
def test_less_equal_array_op(self):
self.binary_op_test('<=')
def test_not_equal_array_op(self):
self.binary_op_test('!=')
| TestArrayOperators |
python | huggingface__transformers | src/transformers/models/fastspeech2_conformer/modeling_fastspeech2_conformer.py | {
"start": 36952,
"end": 42638
} | class ____(nn.Module):
def __init__(self, config: FastSpeech2ConformerConfig):
super().__init__()
use_masking = config.use_masking
use_weighted_masking = config.use_weighted_masking
if use_masking and use_weighted_masking:
raise ValueError("Either use_masking or use_weighted_masking can be True, but not both.")
self.use_masking = use_masking
self.use_weighted_masking = use_weighted_masking
# define criterions
reduction = "none" if self.use_weighted_masking else "mean"
self.l1_criterion = nn.L1Loss(reduction=reduction)
self.mse_criterion = nn.MSELoss(reduction=reduction)
self.duration_criterion = nn.MSELoss(reduction=reduction)
self.log_domain_offset = 1.0
def forward(
self,
outputs_after_postnet,
outputs_before_postnet,
duration_outputs,
pitch_outputs,
energy_outputs,
spectrogram_labels,
duration_labels,
pitch_labels,
energy_labels,
duration_mask,
spectrogram_mask,
):
"""
Args:
outputs_after_postnet (`torch.Tensor` of shape `(batch_size, max_spectrogram_length, num_mel_bins)`):
Batch of outputs after postnet.
outputs_before_postnet (`torch.Tensor` of shape `(batch_size, max_spectrogram_length, num_mel_bins)`):
Batch of outputs before postnet.
duration_outputs (`torch.LongTensor` of shape `(batch_size, max_text_length)`):
Batch of outputs of duration predictor.
pitch_outputs (`torch.Tensor` of shape `(batch_size, max_text_length, 1)`):
Batch of outputs of pitch predictor.
energy_outputs (`torch.Tensor` of shape `(batch_size, max_text_length, 1)`):
Batch of outputs of energy predictor.
spectrogram_labels (`torch.Tensor` of shape `(batch_size, max_spectrogram_length, num_mel_bins)`):
Batch of target features.
duration_labels (`torch.LongTensor` of shape `(batch_size, max_text_length)`): Batch of durations.
pitch_labels (`torch.Tensor` of shape `(batch_size, max_text_length, 1)`):
Batch of target token-averaged pitch.
energy_labels (`torch.Tensor` of shape `(batch_size, max_text_length, 1)`):
Batch of target token-averaged energy.
duration_mask (`torch.LongTensor`):
Mask used to discern which values the duration loss should be calculated for.
spectrogram_mask (`torch.LongTensor`):
Mask used to discern which values the spectrogam loss should be calculated for.
Returns:
`tuple(torch.FloatTensor)`: Tuple of tensors containing, in order, the L1 loss value, duration predictor
loss value, pitch predictor loss value, and energy predictor loss value.
"""
pitch_and_energy_masks = duration_mask.unsqueeze(-1)
# apply mask to remove padded part
if self.use_masking:
outputs_before_postnet = outputs_before_postnet.masked_select(spectrogram_mask)
if outputs_after_postnet is not None:
outputs_after_postnet = outputs_after_postnet.masked_select(spectrogram_mask)
spectrogram_labels = spectrogram_labels.masked_select(spectrogram_mask)
duration_outputs = duration_outputs.masked_select(duration_mask)
duration_labels = duration_labels.masked_select(duration_mask)
pitch_outputs = pitch_outputs.masked_select(pitch_and_energy_masks)
energy_outputs = energy_outputs.masked_select(pitch_and_energy_masks)
pitch_labels = pitch_labels.masked_select(pitch_and_energy_masks)
energy_labels = energy_labels.masked_select(pitch_and_energy_masks)
# calculate loss
l1_loss = self.l1_criterion(outputs_before_postnet, spectrogram_labels)
if outputs_after_postnet is not None:
l1_loss = l1_loss + self.l1_criterion(outputs_after_postnet, spectrogram_labels)
duration_labels = torch.log(duration_labels.float() + self.log_domain_offset)
duration_loss = self.duration_criterion(duration_outputs, duration_labels)
pitch_loss = self.mse_criterion(pitch_outputs, pitch_labels)
energy_loss = self.mse_criterion(energy_outputs, energy_labels)
# make weighted mask and apply it
if self.use_weighted_masking:
spectrogram_mask = nn.functional.pad(
spectrogram_mask.transpose(1, 2),
[0, spectrogram_labels.size(1) - spectrogram_mask.size(1), 0, 0, 0, 0],
value=False,
).transpose(1, 2)
out_weights = spectrogram_mask.float() / spectrogram_mask.sum(dim=1, keepdim=True).float()
out_weights /= spectrogram_labels.size(0) * spectrogram_labels.size(2)
duration_weights = duration_mask.float() / duration_mask.sum(dim=1, keepdim=True).float()
duration_weights /= duration_labels.size(0)
# apply weight
l1_loss = l1_loss.mul(out_weights).masked_select(spectrogram_mask).sum()
duration_loss = duration_loss.mul(duration_weights).masked_select(duration_mask).sum()
pitch_weights = duration_weights.unsqueeze(-1)
pitch_loss = pitch_loss.mul(pitch_weights).masked_select(pitch_and_energy_masks).sum()
energy_loss = energy_loss.mul(pitch_weights).masked_select(pitch_and_energy_masks).sum()
return l1_loss + duration_loss + pitch_loss + energy_loss
@auto_docstring
| FastSpeech2ConformerLoss |
python | pydata__xarray | asv_bench/benchmarks/indexing.py | {
"start": 5616,
"end": 6183
} | class ____:
# https://github.com/pydata/xarray/pull/4560
def setup(self):
self.filepath = "test_indexing_huge_axis_small_slice.nc"
if not os.path.isfile(self.filepath):
xr.Dataset(
{"a": ("x", np.arange(10_000_000))},
coords={"x": np.arange(10_000_000)},
).to_netcdf(self.filepath, format="NETCDF4")
self.ds = xr.open_dataset(self.filepath)
def time_indexing(self):
self.ds.isel(x=slice(100))
def cleanup(self):
self.ds.close()
| HugeAxisSmallSliceIndexing |
python | huggingface__transformers | src/transformers/models/bark/configuration_bark.py | {
"start": 7306,
"end": 11669
} | class ____(PreTrainedConfig):
"""
This is the configuration class to store the configuration of a [`BarkModel`]. It is used to instantiate a Bark
model according to the specified sub-models configurations, defining the model architecture.
Instantiating a configuration with the defaults will yield a similar configuration to that of the Bark
[suno/bark](https://huggingface.co/suno/bark) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
semantic_config ([`BarkSemanticConfig`], *optional*):
Configuration of the underlying semantic sub-model.
coarse_acoustics_config ([`BarkCoarseConfig`], *optional*):
Configuration of the underlying coarse acoustics sub-model.
fine_acoustics_config ([`BarkFineConfig`], *optional*):
Configuration of the underlying fine acoustics sub-model.
codec_config ([`AutoConfig`], *optional*):
Configuration of the underlying codec sub-model.
Example:
```python
>>> from transformers import (
... BarkSemanticConfig,
... BarkCoarseConfig,
... BarkFineConfig,
... BarkModel,
... BarkConfig,
... AutoConfig,
... )
>>> # Initializing Bark sub-modules configurations.
>>> semantic_config = BarkSemanticConfig()
>>> coarse_acoustics_config = BarkCoarseConfig()
>>> fine_acoustics_config = BarkFineConfig()
>>> codec_config = AutoConfig.from_pretrained("facebook/encodec_24khz")
>>> # Initializing a Bark module style configuration
>>> configuration = BarkConfig(
... semantic_config, coarse_acoustics_config, fine_acoustics_config, codec_config
... )
>>> # Initializing a model (with random weights)
>>> model = BarkModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```
"""
model_type = "bark"
sub_configs = {
"semantic_config": BarkSemanticConfig,
"coarse_acoustics_config": BarkCoarseConfig,
"fine_acoustics_config": BarkFineConfig,
"codec_config": AutoConfig,
}
def __init__(
self,
semantic_config: Optional[dict] = None,
coarse_acoustics_config: Optional[dict] = None,
fine_acoustics_config: Optional[dict] = None,
codec_config: Optional[dict] = None,
initializer_range=0.02,
**kwargs,
):
if semantic_config is None:
semantic_config = BarkSemanticConfig()
logger.info("`semantic_config` is `None`. Initializing the `BarkSemanticConfig` with default values.")
elif isinstance(semantic_config, dict):
semantic_config = BarkSemanticConfig(**semantic_config)
if coarse_acoustics_config is None:
coarse_acoustics_config = BarkCoarseConfig()
logger.info(
"`coarse_acoustics_config` is `None`. Initializing the `BarkCoarseConfig` with default values."
)
elif isinstance(coarse_acoustics_config, dict):
coarse_acoustics_config = BarkCoarseConfig(**coarse_acoustics_config)
if fine_acoustics_config is None:
fine_acoustics_config = BarkFineConfig()
logger.info("`fine_acoustics_config` is `None`. Initializing the `BarkFineConfig` with default values.")
elif isinstance(fine_acoustics_config, dict):
fine_acoustics_config = BarkFineConfig(**fine_acoustics_config)
if codec_config is None:
codec_config = CONFIG_MAPPING["encodec"]()
logger.info("`codec_config` is `None`. Initializing the `codec_config` with default values.")
elif isinstance(codec_config, dict):
codec_model_type = codec_config.get("model_type", "encodec")
codec_config = CONFIG_MAPPING[codec_model_type](**codec_config)
self.semantic_config = semantic_config
self.coarse_acoustics_config = coarse_acoustics_config
self.fine_acoustics_config = fine_acoustics_config
self.codec_config = codec_config
self.initializer_range = initializer_range
super().__init__(**kwargs)
__all__ = ["BarkCoarseConfig", "BarkConfig", "BarkFineConfig", "BarkSemanticConfig"]
| BarkConfig |
python | airbytehq__airbyte | airbyte-ci/connectors/connector_ops/connector_ops/utils.py | {
"start": 8012,
"end": 8088
} | class ____(Exception):
pass
@dataclass(frozen=True)
| ConnectorLanguageError |
python | doocs__leetcode | solution/3200-3299/3289.The Two Sneaky Numbers of Digitville/Solution.py | {
"start": 0,
"end": 159
} | class ____:
def getSneakyNumbers(self, nums: List[int]) -> List[int]:
cnt = Counter(nums)
return [x for x, v in cnt.items() if v == 2]
| Solution |
python | huggingface__transformers | src/transformers/models/rag/retrieval_rag.py | {
"start": 3007,
"end": 8275
} | class ____(Index):
"""
An index which can be deserialized from the files built using https://github.com/facebookresearch/DPR. We use
default faiss index parameters as specified in that repository.
Args:
vector_size (`int`):
The dimension of indexed vectors.
index_path (`str`):
A path to a *directory* containing index files compatible with [`~models.rag.retrieval_rag.LegacyIndex`]
"""
INDEX_FILENAME = "hf_bert_base.hnswSQ8_correct_phi_128.c_index"
PASSAGE_FILENAME = "psgs_w100.tsv.pkl"
def __init__(self, vector_size, index_path):
requires_backends(self, ["faiss"])
self.index_id_to_db_id = []
self.index_path = index_path
self.passages = self._load_passages()
self.vector_size = vector_size
self.index = None
self._index_initialized = False
def _resolve_path(self, index_path, filename):
is_local = os.path.isdir(index_path)
try:
# Load from URL or cache if already cached
resolved_archive_file = cached_file(index_path, filename)
except OSError:
msg = (
f"Can't load '{filename}'. Make sure that:\n\n"
f"- '{index_path}' is a correct remote path to a directory containing a file named {filename}\n\n"
f"- or '{index_path}' is the correct path to a directory containing a file named {filename}.\n\n"
)
raise OSError(msg)
if is_local:
logger.info(f"loading file {resolved_archive_file}")
else:
logger.info(f"loading file {filename} from cache at {resolved_archive_file}")
return resolved_archive_file
def _load_passages(self):
logger.info(f"Loading passages from {self.index_path}")
passages_path = self._resolve_path(self.index_path, self.PASSAGE_FILENAME)
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
raise ValueError(
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
"malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
"that could have been tampered with. If you already verified the pickle data and decided to use it, "
"you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
)
with open(passages_path, "rb") as passages_file:
passages = pickle.load(passages_file)
return passages
def _deserialize_index(self):
logger.info(f"Loading index from {self.index_path}")
resolved_index_path = self._resolve_path(self.index_path, self.INDEX_FILENAME + ".index.dpr")
self.index = faiss.read_index(resolved_index_path)
resolved_meta_path = self._resolve_path(self.index_path, self.INDEX_FILENAME + ".index_meta.dpr")
if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
raise ValueError(
"This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
"malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
"that could have been tampered with. If you already verified the pickle data and decided to use it, "
"you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
)
with open(resolved_meta_path, "rb") as metadata_file:
self.index_id_to_db_id = pickle.load(metadata_file)
assert len(self.index_id_to_db_id) == self.index.ntotal, (
"Deserialized index_id_to_db_id should match faiss index size"
)
def is_initialized(self):
return self._index_initialized
def init_index(self):
index = faiss.IndexHNSWFlat(self.vector_size + 1, 512)
index.hnsw.efSearch = 128
index.hnsw.efConstruction = 200
self.index = index
self._deserialize_index()
self._index_initialized = True
def get_doc_dicts(self, doc_ids: np.ndarray):
doc_list = []
for doc_ids_i in doc_ids:
ids = [str(int(doc_id)) for doc_id in doc_ids_i]
docs = [self.passages[doc_id] for doc_id in ids]
doc_list.append(docs)
doc_dicts = []
for docs in doc_list:
doc_dict = {}
doc_dict["title"] = [doc[1] for doc in docs]
doc_dict["text"] = [doc[0] for doc in docs]
doc_dicts.append(doc_dict)
return doc_dicts
def get_top_docs(self, question_hidden_states: np.ndarray, n_docs=5) -> tuple[np.ndarray, np.ndarray]:
aux_dim = np.zeros(len(question_hidden_states), dtype="float32").reshape(-1, 1)
query_nhsw_vectors = np.hstack((question_hidden_states, aux_dim))
_, docs_ids = self.index.search(query_nhsw_vectors, n_docs)
vectors = [[self.index.reconstruct(int(doc_id))[:-1] for doc_id in doc_ids] for doc_ids in docs_ids]
ids = [[int(self.index_id_to_db_id[doc_id]) for doc_id in doc_ids] for doc_ids in docs_ids]
return np.array(ids), np.array(vectors)
| LegacyIndex |
python | numba__numba | numba/np/ufunc/decorators.py | {
"start": 1246,
"end": 6107
} | class ____(_BaseVectorize):
target_registry = DelayedRegistry({'cpu': gufunc.GUFunc,
'parallel': ParallelGUFuncBuilder,})
def __new__(cls, func, signature, **kws):
identity = cls.get_identity(kws)
cache = cls.get_cache(kws)
imp = cls.get_target_implementation(kws)
writable_args = cls.get_writable_args(kws)
if imp is gufunc.GUFunc:
is_dyn = kws.pop('is_dynamic', False)
return imp(func, signature, identity=identity, cache=cache,
is_dynamic=is_dyn, targetoptions=kws,
writable_args=writable_args)
else:
return imp(func, signature, identity=identity, cache=cache,
targetoptions=kws, writable_args=writable_args)
def vectorize(ftylist_or_function=(), **kws):
"""vectorize(ftylist_or_function=(), target='cpu', identity=None, **kws)
A decorator that creates a NumPy ufunc object using Numba compiled
code. When no arguments or only keyword arguments are given,
vectorize will return a Numba dynamic ufunc (DUFunc) object, where
compilation/specialization may occur at call-time.
Args
-----
ftylist_or_function: function or iterable
When the first argument is a function, signatures are dealt
with at call-time.
When the first argument is an iterable of type signatures,
which are either function type object or a string describing
the function type, signatures are finalized at decoration
time.
Keyword Args
------------
target: str
A string for code generation target. Default to "cpu".
identity: int, str, or None
The identity (or unit) value for the element-wise function
being implemented. Allowed values are None (the default), 0, 1,
and "reorderable".
cache: bool
Turns on caching.
Returns
--------
A NumPy universal function
Examples
-------
@vectorize(['float32(float32, float32)',
'float64(float64, float64)'], identity=0)
def sum(a, b):
return a + b
@vectorize
def sum(a, b):
return a + b
@vectorize(identity=1)
def mul(a, b):
return a * b
"""
if isinstance(ftylist_or_function, str):
# Common user mistake
ftylist = [ftylist_or_function]
elif inspect.isfunction(ftylist_or_function):
return dufunc.DUFunc(ftylist_or_function, **kws)
elif ftylist_or_function is not None:
ftylist = ftylist_or_function
def wrap(func):
vec = Vectorize(func, **kws)
for sig in ftylist:
vec.add(sig)
if len(ftylist) > 0:
vec.disable_compile()
return vec.build_ufunc()
return wrap
def guvectorize(*args, **kwargs):
"""guvectorize(ftylist, signature, target='cpu', identity=None, **kws)
A decorator to create NumPy generalized-ufunc object from Numba compiled
code.
Args
-----
ftylist: iterable
An iterable of type signatures, which are either
function type object or a string describing the
function type.
signature: str
A NumPy generalized-ufunc signature.
e.g. "(m, n), (n, p)->(m, p)"
identity: int, str, or None
The identity (or unit) value for the element-wise function
being implemented. Allowed values are None (the default), 0, 1,
and "reorderable".
cache: bool
Turns on caching.
writable_args: tuple
a tuple of indices of input variables that are writable.
target: str
A string for code generation target. Defaults to "cpu".
Returns
--------
A NumPy generalized universal-function
Example
-------
@guvectorize(['void(int32[:,:], int32[:,:], int32[:,:])',
'void(float32[:,:], float32[:,:], float32[:,:])'],
'(x, y),(x, y)->(x, y)')
def add_2d_array(a, b, c):
for i in range(c.shape[0]):
for j in range(c.shape[1]):
c[i, j] = a[i, j] + b[i, j]
"""
if len(args) == 1:
ftylist = []
signature = args[0]
kwargs.setdefault('is_dynamic', True)
elif len(args) == 2:
ftylist = args[0]
signature = args[1]
else:
raise TypeError('guvectorize() takes one or two positional arguments')
if isinstance(ftylist, str):
# Common user mistake
ftylist = [ftylist]
def wrap(func):
guvec = GUVectorize(func, signature, **kwargs)
for fty in ftylist:
guvec.add(fty)
if len(ftylist) > 0:
guvec.disable_compile()
return guvec.build_ufunc()
return wrap
| GUVectorize |
python | ansible__ansible | lib/ansible/parsing/vault/__init__.py | {
"start": 51827,
"end": 58602
} | class ____(AnsibleTaggedObject):
"""
An encrypted string which supports tagging and on-demand decryption.
All methods provided by Python's built-in `str` are supported, all of which operate on the decrypted value.
Any attempt to use this value when it cannot be decrypted will raise an exception.
Despite supporting `str` methods, access to an instance of this type through templating is recommended over direct access.
"""
__slots__ = ('_ciphertext', '_plaintext', '_ansible_tags_mapping')
_subclasses_native_type: t.ClassVar[bool] = False
_empty_tags_as_native: t.ClassVar[bool] = False
_ciphertext: str
_plaintext: str | None
_ansible_tags_mapping: _AnsibleTagsMapping | _EmptyROInternalTagsMapping
def __init__(self, *, ciphertext: str) -> None:
if type(ciphertext) is not str: # pylint: disable=unidiomatic-typecheck
raise TypeError(f'ciphertext must be {str} instead of {type(ciphertext)}')
object.__setattr__(self, '_ciphertext', ciphertext)
object.__setattr__(self, '_plaintext', None)
object.__setattr__(self, '_ansible_tags_mapping', _EMPTY_INTERNAL_TAGS_MAPPING)
@classmethod
def _instance_factory(cls, value: t.Any, tags_mapping: _AnsibleTagsMapping) -> EncryptedString:
instance = EncryptedString.__new__(EncryptedString)
# In 2.18 and earlier, vaulted values were not trusted.
# This maintains backwards compatibility with that.
# Additionally, supporting templating on vaulted values could be problematic for a few cases:
# 1) There's no way to compose YAML tags, so you can't use `!unsafe` and `!vault` together.
# 2) It would make composing `EncryptedString` with a possible future `TemplateString` more difficult.
tags_mapping.pop(TrustedAsTemplate, None)
object.__setattr__(instance, '_ciphertext', value._ciphertext)
object.__setattr__(instance, '_plaintext', value._plaintext)
object.__setattr__(instance, '_ansible_tags_mapping', tags_mapping)
return instance
def __setstate__(self, state: tuple[None, dict[str, t.Any]]) -> None:
for key, value in state[1].items():
object.__setattr__(self, key, value)
def __delattr__(self, item: str) -> t.NoReturn:
raise AttributeError(f'{self.__class__.__name__!r} object is read-only')
def __setattr__(self, key: str, value: object) -> t.NoReturn:
raise AttributeError(f'{self.__class__.__name__!r} object is read-only')
@classmethod
def _init_class(cls) -> None:
"""
Add proxies for the specified `str` methods.
These proxies operate on the plaintext, which is decrypted on-demand.
"""
cls._native_type = cls
operator_method_names = (
'__eq__',
'__ge__',
'__gt__',
'__le__',
'__lt__',
'__ne__',
)
method_names = (
'__add__',
'__contains__',
'__format__',
'__getitem__',
'__hash__',
'__iter__',
'__len__',
'__mod__',
'__mul__',
'__rmod__',
'__rmul__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans', # static, but implemented for simplicity/consistency
'partition',
'removeprefix',
'removesuffix',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill',
)
for method_name in operator_method_names:
setattr(cls, method_name, functools.partialmethod(cls._proxy_str_operator_method, getattr(str, method_name)))
for method_name in method_names:
setattr(cls, method_name, functools.partialmethod(cls._proxy_str_method, getattr(str, method_name)))
def _decrypt(self) -> str:
"""
Attempt to decrypt the ciphertext and return the plaintext, which will be cached.
If decryption fails an exception will be raised and no result will be cached.
"""
if self._plaintext is None:
vault = VaultLib(secrets=VaultSecretsContext.current().secrets)
# use the utility method to ensure that origin tags are available
plaintext = to_text(vault.decrypt(VaultHelper.get_ciphertext(self, with_tags=True))) # raises if the ciphertext cannot be decrypted
# propagate source value tags plus VaultedValue for round-tripping ciphertext
plaintext = AnsibleTagHelper.tag(plaintext, AnsibleTagHelper.tags(self) | {VaultedValue(ciphertext=self._ciphertext)})
object.__setattr__(self, '_plaintext', plaintext)
return self._plaintext
def _as_dict(self) -> t.Dict[str, t.Any]:
return dict(
value=self._ciphertext,
tags=list(self._ansible_tags_mapping.values()),
)
def _native_copy(self) -> str:
return AnsibleTagHelper.untag(self._decrypt())
def _proxy_str_operator_method(self, method: t.Callable, other) -> t.Any:
obj = self._decrypt()
if type(other) is EncryptedString: # pylint: disable=unidiomatic-typecheck
other = other._decrypt()
return method(obj, other)
def _proxy_str_method(self, method: t.Callable, *args, **kwargs) -> t.Any:
obj = self._decrypt()
return method(obj, *args, **kwargs)
def __repr__(self) -> str:
return f'{self.__class__.__name__}(ciphertext={self._ciphertext!r})'
def __str__(self) -> str:
return self._decrypt()
def __float__(self) -> float:
return float(self._decrypt())
def __int__(self) -> int:
return int(self._decrypt())
def __radd__(self, other: t.Any) -> str:
return other + self._decrypt()
def __fspath__(self) -> str:
return self._decrypt()
| EncryptedString |
python | instagram__MonkeyType | tests/test_typing.py | {
"start": 32018,
"end": 32739
} | class ____:
@pytest.mark.parametrize(
'typ, expected',
[
(make_typed_dict(required_fields={'a': int, 'b': str}), Dict[str, Union[int, str]]),
(make_typed_dict(required_fields={}), Dict[Any, Any]),
# Regular TypedDict is left untouched.
(TypedDict('Foo', {'a': TypedDict('Bar', {'b': int})}),
TypedDict('Foo', {'a': TypedDict('Bar', {'b': int})})),
(Dict[str, make_typed_dict(required_fields={'a': int})], Dict[str, Dict[str, int]]),
],
)
def test_rewrite(self, typ, expected):
rewritten = RewriteAnonymousTypedDictToDict().rewrite(typ)
assert rewritten == expected
| TestRewriteAnonymousTypedDictToDict |
python | pytorch__pytorch | test/distributed/tensor/test_matrix_ops.py | {
"start": 1439,
"end": 24311
} | class ____(DTensorTestBase):
@with_comms
def test_addmm(self):
device_mesh = self.build_device_mesh()
shard_spec = [Shard(0)]
replica_spec = [Replicate()]
tensor_to_shard = torch.randn(12, 8)
mat1 = distribute_tensor(tensor_to_shard, device_mesh, shard_spec)
tensor_to_replicate = torch.randn(8, 4)
mat2 = distribute_tensor(tensor_to_replicate, device_mesh, replica_spec)
input_tensor = torch.randn(4)
input = distribute_tensor(input_tensor, device_mesh, replica_spec)
dist_res = torch.addmm(input, mat1, mat2)
local_res = torch.addmm(input_tensor, tensor_to_shard, tensor_to_replicate)
self.assertEqual(dist_res.full_tensor(), local_res)
@with_comms
def test_addmm_empty_operand(self):
device_mesh = self.build_device_mesh()
shard_spec = [Shard(0)]
replica_spec = [Replicate()]
tensor_to_shard = torch.randn(12, 0)
mat1 = distribute_tensor(tensor_to_shard, device_mesh, shard_spec)
tensor_to_replicate = torch.randn(0, 4)
mat2 = distribute_tensor(tensor_to_replicate, device_mesh, replica_spec)
input_tensor = torch.randn(4)
inp = distribute_tensor(input_tensor, device_mesh, replica_spec)
dist_res = torch.addmm(inp, mat1, mat2)
local_res = torch.addmm(input_tensor, tensor_to_shard, tensor_to_replicate)
self.assertEqual(dist_res.full_tensor(), local_res)
@with_comms
def test_addmm_auto_redistribute(self):
device_mesh = self.build_device_mesh()
shard0_spec = [Shard(0)]
shard1_spec = [Shard(1)]
replica_spec = [Replicate()]
tensor_to_shard1 = torch.randn(12, 8, requires_grad=True)
mat1 = distribute_tensor(tensor_to_shard1, device_mesh, shard1_spec)
tensor_to_shard0 = torch.randn(8, 4, requires_grad=True)
mat2 = distribute_tensor(tensor_to_shard0, device_mesh, shard0_spec)
input_tensor = torch.randn(4, requires_grad=True)
input = distribute_tensor(input_tensor, device_mesh, replica_spec)
local_res = torch.addmm(input_tensor, tensor_to_shard1, tensor_to_shard0)
dist_res = torch.addmm(input, mat1, mat2)
# test if addmm output is a partial
self.assertIsInstance(dist_res, DTensor)
self.assertIsInstance(dist_res.placements[0], Partial)
# test if result is the same as tensor
dist_local_res = dist_res.full_tensor()
self.assertEqual(local_res, dist_local_res)
# backward checks
dist_local_res.sum().backward()
local_res.sum().backward()
self.assertIsNotNone(mat2.grad)
self.assertEqual(mat2.grad.full_tensor(), tensor_to_shard0.grad)
@with_comms
def test_mm(self):
device_mesh = self.build_device_mesh()
shard0_spec = Shard(0)
shard1_spec = Shard(1)
replica_spec = Replicate()
t1 = torch.randn(12, 8, requires_grad=True)
t2 = torch.randn(8, 16, requires_grad=True)
local_res = torch.mm(t1, t2)
def test_placement_comb(
placements1: list[Placement], placements2: list[Placement]
) -> None:
dt1 = distribute_tensor(t1, device_mesh, placements1)
dt2 = distribute_tensor(t2, device_mesh, placements2)
dist_res: DTensor = cast(DTensor, torch.mm(dt1, dt2)).redistribute(
device_mesh, [replica_spec]
)
self.assertEqual(dist_res.to_local(), local_res)
# backward
grad_dist_res = torch.ones_like(dist_res)
dist_res.backward(grad_dist_res)
self.assertIsNotNone(dt1.grad)
placement_specs = [shard0_spec, shard1_spec, replica_spec]
shard_specs_comb = list(itertools.product(placement_specs, placement_specs))
for spec in shard_specs_comb:
test_placement_comb([spec[0]], [spec[1]])
@with_comms
@skip_unless_torch_gpu
@unittest.skipIf(
not PLATFORM_SUPPORTS_FP8,
"FP8 is only supported on H100+, SM 8.9 and MI300+ devices",
)
def test_scaled_mm(self):
device_mesh = self.build_device_mesh()
shrd0 = Shard(0)
shrd1 = Shard(1)
repl = Replicate()
part = Partial()
ws = self.world_size
# _scaled_mm requires all dimensions to be multiples of 16. Since we'll
# shard along n and k, we need to ensure this stays true on each rank.
m, n, k = 16, 32 * ws, 16 * ws
t1 = torch.randn(m, k, device=self.device_type, dtype=torch.bfloat16)
t2 = torch.randn(n, k, device=self.device_type, dtype=torch.bfloat16)
for (
output_spec,
t1_spec,
t2_spec,
scale1_shape,
scale2_shape,
scale1_spec,
scale2_spec,
) in [
# Tensor-wise scaling
# Replicated, zero-dim scale
(repl, repl, repl, (), (), repl, repl),
# Column-parallel, two-dim scale
(shrd1, repl, shrd0, (1, 1), (1, 1), repl, repl),
# Row-parallel, one-dim scale
(part, shrd1, shrd1, (1,), (1,), repl, repl),
# Row-wise scaling
# Replicated
(repl, repl, repl, (m, 1), (n, 1), repl, repl),
# Column-parallel
(shrd1, repl, shrd0, (m, 1), (n, 1), repl, shrd0),
# Row-parallel (which actually ends up doing sub-row-wise scaling)
(part, shrd1, shrd1, (m, ws), (n, ws), shrd1, shrd1),
]:
full_ref_res = t1 @ t2.t()
t1_fp8, scale1 = scale_for_fp8(t1, scale1_shape)
t2_fp8, scale2 = scale_for_fp8(t2, scale2_shape)
dist_t1_fp8 = distribute_tensor(t1_fp8, device_mesh, [t1_spec])
dist_t2_fp8 = distribute_tensor(t2_fp8, device_mesh, [t2_spec])
dist_scale1 = distribute_tensor(scale1, device_mesh, [scale1_spec])
dist_scale2 = distribute_tensor(scale2, device_mesh, [scale2_spec])
with CommDebugMode() as comm_mode:
dist_res = cast(
DTensor,
torch._scaled_mm(
dist_t1_fp8,
dist_t2_fp8.t(),
scale_a=dist_scale1,
scale_b=dist_scale2.t(),
out_dtype=torch.bfloat16,
),
)
self.assertEqual(dist_res.placements[0], output_spec)
full_dist_res = dist_res.full_tensor()
# Fp8 matmuls are quite inaccurate, we need high tolerances
self.assertEqual(full_dist_res, full_ref_res, atol=1.5, rtol=7e-2)
self.assertEqual(comm_mode.get_total_counts(), 0)
@with_comms
def test_matmul(self):
device_mesh = self.build_device_mesh()
dim = 128
x = torch.randn(8, dim)
A = torch.randn(dim, dim)
y = torch.matmul(x, A)
# Prepare DTensors
dx = distribute_tensor(x, device_mesh, [Replicate()])
dA = distribute_tensor(A, device_mesh, [Shard(0)])
# Use `inference_mode` to test DTensor's capability of decomposing
# `matmul` op
with torch.inference_mode():
dy = torch.matmul(dx, dA)
self.assertEqual(y, dy.full_tensor())
@with_comms
def test_t(self):
device_mesh = self.build_device_mesh()
shard_spec = [Shard(0)]
tensor_to_transpose = torch.randn(12, 8, requires_grad=True)
mat = distribute_tensor(tensor_to_transpose, device_mesh, shard_spec)
tranposed_mat = mat.t()
self.assertEqual(tranposed_mat.size(), torch.Size([8, 12]))
self.assertEqual(tranposed_mat.placements, [Shard(1)])
tranposed_mat2 = tranposed_mat.t()
self.assertEqual(tranposed_mat2.size(), torch.Size([12, 8]))
self.assertEqual(tranposed_mat2.placements, shard_spec)
@with_comms
def test_t_partial(self):
device_mesh = self.build_device_mesh()
a = torch.randn(12, 8)
b = torch.randn(8, 4)
c = torch.mm(a, b).t()
da = distribute_tensor(a, device_mesh, [Shard(1)])
db = distribute_tensor(b, device_mesh, [Shard(0)])
# mm(da, db) should return a Partial tensor.
# transposing it should keep it Partial
dc = torch.mm(da, db).t()
self.assertTrue(isinstance(dc.placements[0], Partial))
# check that the local and distributed op results match
self.assertEqual(
c,
dc.redistribute(device_mesh, [Replicate()]).to_local(),
)
# baddbmm introduces nan occasionally on CPU: https://github.com/pytorch/pytorch/issues/80588
@with_comms
@skip_unless_torch_gpu
def test_baddbmm(self):
device_mesh = self.build_device_mesh()
tensor = torch.rand(4, 4, 8, device=self.device_type, requires_grad=True)
batch_1 = torch.rand(4, 4, 8, device=self.device_type, requires_grad=True)
batch_2 = torch.rand(4, 8, 8, device=self.device_type, requires_grad=True)
def test_placement_comb(
tensor_placements: list[Placement],
batch_1_placements: list[Placement],
batch_2_placements: list[Placement],
beta: int,
alpha: int,
batch_1_grad: Optional[torch.Tensor],
) -> None:
tensor_dt = distribute_tensor(tensor, device_mesh, tensor_placements)
batch_1_dt = distribute_tensor(batch_1, device_mesh, batch_1_placements)
batch_2_dt = distribute_tensor(batch_2, device_mesh, batch_2_placements)
dist_res = cast(
DTensor,
torch.baddbmm(
tensor_dt, batch_1_dt, batch_2_dt, beta=beta, alpha=alpha
),
).redistribute(device_mesh, [Replicate()])
dist_local_res = dist_res.to_local()
assert not torch.isnan(local_result).any()
assert not torch.isnan(dist_local_res).any()
self.assertEqual(dist_local_res.detach(), local_result.detach())
# TODO: add test backward
# grad_dist_res = torch.ones_like(dist_res)
# dist_res.backward(grad_dist_res)
# self.assertIsNotNone(batch_1_dt.grad)
# batch_1_grad_local = batch_1_dt.grad.redistribute(
# device_mesh, [Replicate()]
# ).to_local()
# self.assertEqual(batch_1_grad_local, batch_1_grad)
shard0_spec = Shard(0)
shard1_spec = Shard(1)
shard2_spec = Shard(2)
replica_spec = Replicate()
shard_specs = [shard0_spec, shard1_spec, shard2_spec, replica_spec]
shard_specs_comb = list(
itertools.product(shard_specs, shard_specs, shard_specs)
)
# If beta is 0, input tensor will be ignored
numeric_params_comb = [
(0.0, 0.5), # zero-beta
(0.8, 0.5), # non-zero-beta
]
for beta, alpha in numeric_params_comb:
local_result = torch.baddbmm(
tensor, batch_1, batch_2, beta=beta, alpha=alpha
)
grad_local_res = torch.ones_like(local_result)
local_result.backward(grad_local_res)
# test all combos
for spec in shard_specs_comb:
test_placement_comb(
[spec[0]], [spec[1]], [spec[2]], beta, alpha, batch_1.grad
)
@with_comms
def test_bmm(self):
device_mesh = self.build_device_mesh()
mat1 = torch.rand(4, 8, 4, device=self.device_type, requires_grad=True)
mat2 = torch.rand(4, 4, 8, device=self.device_type, requires_grad=True)
local_result = torch.bmm(mat1, mat2)
grad_local_res = torch.ones_like(local_result)
local_result.backward(grad_local_res)
def test_placement_comb(
placements1: list[Placement],
placements2: list[Placement],
) -> None:
mat1_dt = distribute_tensor(mat1, device_mesh, placements1)
mat2_dt = distribute_tensor(mat2, device_mesh, placements2)
dist_res = cast(DTensor, torch.bmm(mat1_dt, mat2_dt)).redistribute(
device_mesh, [Replicate()]
)
dist_local_res = dist_res.to_local()
self.assertEqual(dist_local_res, local_result)
# test backward
# TODO: figure out (replicate, shard1) fail on backward
# it generates a different grad shape
grad_dist_res = torch.ones_like(dist_res)
dist_res.backward(grad_dist_res)
self.assertIsNotNone(mat1_dt.grad)
mat1_dt_grad = cast(DTensor, mat1_dt.grad)
mat1_grad_local = mat1_dt_grad.redistribute(
device_mesh, [Replicate()]
).to_local()
self.assertEqual(mat1_grad_local, mat1.grad)
shard0_spec = Shard(0)
shard1_spec = Shard(1)
shard2_spec = Shard(2)
replica_spec = Replicate()
placement_specs = [shard0_spec, shard1_spec, shard2_spec, replica_spec]
shard_specs_comb = list(itertools.product(placement_specs, placement_specs))
# tests that currently pass
for spec in shard_specs_comb:
test_placement_comb([spec[0]], [spec[1]])
@with_comms
@skip_unless_torch_gpu
def test_scaled_dot_product_attention(self):
device_mesh = self.build_device_mesh()
comm_mode = CommDebugMode()
# bsz, n_heads, slen, head_dim
query = torch.rand(
(4, 8, 8, 8),
device=self.device_type,
dtype=torch.bfloat16,
requires_grad=True,
)
key = torch.rand(
(4, 8, 8, 8),
device=self.device_type,
dtype=torch.bfloat16,
requires_grad=True,
)
value = torch.rand(
(4, 8, 8, 8),
device=self.device_type,
dtype=torch.bfloat16,
requires_grad=True,
)
from torch.nn.attention import sdpa_kernel, SDPBackend
available_backends = []
dropout_p = 0.0
# TODO: Add test cases where is_causal=False and an attention mask is provided.
# Gaps include missing op support for aten.masked_fill_.Scalar.
is_causal = True
enable_gqa = False
params = torch.backends.cuda.SDPAParams(
query, key, value, None, dropout_p, is_causal, enable_gqa
)
if torch.backends.cuda.can_use_flash_attention(params, debug=False):
available_backends.append(SDPBackend.FLASH_ATTENTION)
if torch.backends.cuda.can_use_efficient_attention(params, debug=False):
available_backends.append(SDPBackend.EFFICIENT_ATTENTION)
placement_specs = [(Replicate(),), (Shard(0),), (Shard(1),)]
for backend, input_placements in itertools.product(
available_backends, placement_specs
):
dist_query = distribute_tensor(query, device_mesh, input_placements)
dist_key = distribute_tensor(key, device_mesh, input_placements)
dist_value = distribute_tensor(value, device_mesh, input_placements)
with sdpa_kernel(backends=[backend]):
out = F.scaled_dot_product_attention(
query, key, value, dropout_p=dropout_p, is_causal=is_causal
)
with comm_mode:
dist_out = F.scaled_dot_product_attention(
dist_query,
dist_key,
dist_value,
dropout_p=dropout_p,
is_causal=is_causal,
)
self.assertEqual(comm_mode.get_total_counts(), 0)
self.assertEqual(dist_out.placements, input_placements)
self.assertEqual(dist_out.full_tensor(), out)
out.sum().backward()
with comm_mode:
dist_out.sum().backward()
self.assertEqual(comm_mode.get_total_counts(), 0)
self.assertEqual(dist_query.grad.placements, input_placements)
self.assertEqual(dist_query.grad.full_tensor(), query.grad)
self.assertEqual(dist_key.grad.placements, input_placements)
self.assertEqual(dist_key.grad.full_tensor(), key.grad)
self.assertEqual(dist_value.grad.placements, input_placements)
self.assertEqual(dist_value.grad.full_tensor(), value.grad)
query.grad.zero_()
key.grad.zero_()
value.grad.zero_()
@skip_unless_torch_gpu
@with_comms()
def test_dtensor_mm(self):
"""
Test mm with DTensor with 2D mesh.
We need to add the test here since we only test 1D mesh in test_dtensor_ops.py.
Also, we added tests for the corner case where one of the 2D dimension is 1.
# TODO: we need to test more DTensor ops with 2D mesh, especially when 1 of the
mesh dimension of the 2D mesh is 1.
"""
mesh_0 = init_device_mesh(self.device_type, (self.world_size // 2, 2))
mesh_1 = init_device_mesh(self.device_type, (self.world_size, 1))
mesh_2 = init_device_mesh(self.device_type, (1, self.world_size))
for mesh in [mesh_0, mesh_1, mesh_2]:
lhs = torch.randn(256, 128)
rhs = torch.randn(128, 256)
mm_result = lhs @ rhs
lhs_dtensor = distribute_tensor(lhs, mesh, [Shard(dim=0), Replicate()])
rhs_dtensor = distribute_tensor(rhs, mesh, [Replicate(), Shard(dim=1)])
dtensor_result = lhs_dtensor @ rhs_dtensor
self.assertEqual(
dtensor_result.full_tensor(), mm_result, atol=1.5e-5, rtol=1e-6
)
@with_comms
@skip_unless_torch_gpu
def test_tensordot_shampoo(self):
"""
Create a simple test for Shampoo's use case.
"""
device_mesh = self.build_device_mesh()
local_a = torch.randn(4, 4)
local_b = torch.randn(4, 15)
dims = ([0], [0])
local_result = torch.tensordot(local_a, local_b, dims=(dims))
placements = [Replicate(), Shard(0), Shard(1)]
placements_tuples = itertools.product(placements, repeat=2)
for placement1, placement2 in placements_tuples:
dist_a = distribute_tensor(local_a, device_mesh, [placement1])
dist_b = distribute_tensor(local_b, device_mesh, [placement2])
dist_result = torch.tensordot(dist_a, dist_b, dims=dims)
dist_result_full = dist_result.full_tensor()
self.assertEqual(local_result, dist_result_full)
@unittest.skipIf(TEST_WITH_ROCM, "ROCm doesn't support CUTLASS")
@unittest.skipIf(not SM90OrLater, "Grouped gemm supported on SM90")
@with_comms
@skip_unless_torch_gpu
@parametrize(
"kwargs",
[
{
# 2D x 3D case from MoE layer
"inp_shape": (64, 16),
"w1_shape": (2, 16, 32),
"w2_shape": (2, 32, 16),
"inp_placements": [Replicate()],
"w1_placements": [Shard(2)],
"w2_placements": [Shard(1)],
"expected_comm_counts_fwd": 0,
"expected_comm_counts_bwd": 1,
"expected_out_placements": [Partial()],
},
{
# Case that would have invalid strides on inp * mat1 when sharded
"inp_shape": (64, 16),
"w1_shape": (2, 16, 16),
"w2_shape": (2, 16, 16),
"inp_placements": [Replicate()],
"w1_placements": [Shard(2)],
"w2_placements": [Shard(1)],
"expected_comm_counts_fwd": 2,
"expected_comm_counts_bwd": 4,
"expected_out_placements": [Replicate()],
},
],
)
def test_grouped_mm(self, kwargs):
# TODO: torch.nn.functional.grouped_mm can take inputs of dimension (2D, 3D) x (2D, 3D)
# More tests need to be added.
device_mesh = self.build_device_mesh()
comm_mode = CommDebugMode()
dtype = torch.bfloat16
inp = torch.rand(
*kwargs["inp_shape"],
device=self.device_type,
dtype=dtype,
requires_grad=True,
)
w1 = torch.rand(
*kwargs["w1_shape"],
device=self.device_type,
dtype=dtype,
requires_grad=True,
)
w2 = torch.rand(
*kwargs["w2_shape"],
device=self.device_type,
dtype=dtype,
requires_grad=True,
)
offs = torch.tensor([16, 64], device=self.device_type, dtype=torch.int32)
h = F.grouped_mm(inp, w1, offs=offs)
out = F.grouped_mm(h, w2, offs=offs)
dist_inp = distribute_tensor(inp, device_mesh, kwargs["inp_placements"])
# colwise sharded
dist_w1 = distribute_tensor(w1, device_mesh, kwargs["w1_placements"])
# rowwise sharded
dist_w2 = distribute_tensor(w2, device_mesh, kwargs["w2_placements"])
dist_offs = distribute_tensor(offs, device_mesh, [Replicate()])
with comm_mode:
dist_h = F.grouped_mm(dist_inp, dist_w1, offs=dist_offs)
dist_out = F.grouped_mm(dist_h, dist_w2, offs=dist_offs)
self.assertEqual(
comm_mode.get_total_counts(), kwargs["expected_comm_counts_fwd"]
)
self.assertEqual(dist_out.placements, kwargs["expected_out_placements"])
self.assertEqual(dist_out.full_tensor(), out)
out_grad = torch.ones_like(out)
out.backward(out_grad)
dist_out = dist_out.redistribute(device_mesh, [Shard(0)])
dist_out_grad = distribute_tensor(out_grad, device_mesh, [Shard(0)])
with comm_mode:
dist_out.backward(dist_out_grad)
self.assertEqual(
comm_mode.get_total_counts(), kwargs["expected_comm_counts_bwd"]
)
self.assertEqual(
comm_mode.get_comm_counts()[funcol.all_gather_into_tensor],
kwargs["expected_comm_counts_bwd"],
)
self.assertEqual(dist_inp.grad.full_tensor(), inp.grad)
self.assertEqual(dist_w1.grad.full_tensor(), w1.grad)
self.assertEqual(dist_w2.grad.full_tensor(), w2.grad)
instantiate_parametrized_tests(DistMatrixOpsTest)
DistMatrixOpsTestWithLocalTensor = create_local_tensor_test_class(
DistMatrixOpsTest,
)
if __name__ == "__main__":
run_tests()
| DistMatrixOpsTest |
python | ansible__ansible | lib/ansible/errors/__init__.py | {
"start": 1105,
"end": 5923
} | class ____(Exception):
"""
This is the base class for all errors raised from Ansible code,
and can be instantiated with two optional parameters beyond the
error message to control whether detailed information is displayed
when the error occurred while parsing a data file of some kind.
Usage:
raise AnsibleError('some message here', obj=obj)
Where "obj" may be tagged with Origin to provide context for error messages.
"""
_exit_code = ExitCode.GENERIC_ERROR
_default_message = ''
_default_help_text: str | None = None
_include_cause_message = True
"""
When `True`, the exception message will be augmented with cause message(s).
Subclasses doing complex error analysis can disable this to take responsibility for reporting cause messages as needed.
"""
def __init__(
self,
message: str = "",
obj: t.Any = None,
show_content: bool = True,
suppress_extended_error: bool | types.EllipsisType = ...,
orig_exc: BaseException | None = None,
help_text: str | None = None,
) -> None:
# DTFIX-FUTURE: these fallback cases mask incorrect use of AnsibleError.message, what should we do?
if message is None:
message = ''
elif not isinstance(message, str):
message = str(message)
if self._default_message and message:
message = _text_utils.concat_message(self._default_message, message)
elif self._default_message:
message = self._default_message
elif not message:
message = f'Unexpected {type(self).__name__} error.'
super().__init__(message)
self._show_content = show_content
self._message = message
self._help_text_value = help_text or self._default_help_text
self.obj = obj
# deprecated: description='deprecate support for orig_exc, callers should use `raise ... from` only' core_version='2.23'
# deprecated: description='remove support for orig_exc' core_version='2.27'
self.orig_exc = orig_exc
if suppress_extended_error is not ...:
from ..utils.display import Display
if suppress_extended_error:
self._show_content = False
Display().deprecated(
msg=f"The `suppress_extended_error` argument to `{type(self).__name__}` is deprecated.",
version="2.23",
help_text="Use `show_content=False` instead.",
)
@property
def _original_message(self) -> str:
return self._message
@property
def message(self) -> str:
"""
Return the original message with cause message(s) appended.
The cause will not be followed on any `AnsibleError` with `_include_cause_message=False`.
"""
return _error_utils.format_exception_message(self)
@message.setter
def message(self, val) -> None:
self._message = val
@property
def _formatted_source_context(self) -> str | None:
with _error_utils.RedactAnnotatedSourceContext.when(not self._show_content):
if source_context := _error_utils.SourceContext.from_value(self.obj):
return str(source_context)
return None
@property
def _help_text(self) -> str | None:
return self._help_text_value
@_help_text.setter
def _help_text(self, value: str | None) -> None:
self._help_text_value = value
def __str__(self) -> str:
return self.message
def __getstate__(self) -> dict[str, t.Any]:
"""Augment object.__getstate__ to preserve additional values not represented in BaseException.__dict__."""
state = t.cast(dict[str, t.Any], super().__getstate__())
state.update(
args=self.args,
__cause__=self.__cause__,
__context__=self.__context__,
__suppress_context__=self.__suppress_context__,
)
return state
def __reduce__(self) -> tuple[t.Callable, tuple[type], dict[str, t.Any]]:
"""
Enable copy/pickle of AnsibleError derived types by correcting for BaseException's ancient C __reduce__ impl that:
* requires use of a type constructor with positional args
* assumes positional args are passed through from the derived type __init__ to BaseException.__init__ unmodified
* does not propagate args/__cause__/__context__/__suppress_context__
NOTE: This does not preserve the dunder attributes on non-AnsibleError derived cause/context exceptions.
As a result, copy/pickle will discard chained exceptions after the first non-AnsibleError cause/context.
"""
return type(self).__new__, (type(self),), self.__getstate__()
| AnsibleError |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_work_queues.py | {
"start": 38124,
"end": 43941
} | class ____:
@pytest.fixture
async def recently_polled_work_queue(self, session, work_pool):
work_queue = await models.work_queues.create_work_queue(
session=session,
work_queue=schemas.core.WorkQueue(
name="wq-1",
description="All about my work queue",
last_polled=datetime.now(timezone.utc),
work_pool_id=work_pool.id,
priority=1,
),
)
await session.commit()
return work_queue
@pytest.fixture
async def recently_pool_work_queue_in_different_work_pool(self, session):
work_pool = await models.workers.create_work_pool(
session=session,
work_pool=schemas.actions.WorkPoolCreate(
name="another-work-pool",
description="All about my work pool",
type="test",
),
)
work_queue = await models.work_queues.create_work_queue(
session=session,
work_queue=schemas.core.WorkQueue(
name="wq-1",
description="All about my work queue",
last_polled=datetime.now(timezone.utc),
work_pool_id=work_pool.id,
priority=1,
),
)
await session.commit()
return work_queue
@pytest.fixture
async def not_recently_polled_work_queue(self, session, work_pool):
work_queue = await models.work_queues.create_work_queue(
session=session,
work_queue=schemas.core.WorkQueue(
name="wq-1",
description="All about my work queue",
last_polled=datetime.now(timezone.utc) - timedelta(days=1),
work_pool_id=work_pool.id,
priority=2,
),
)
await session.commit()
return work_queue
@pytest.fixture
async def work_queue_with_late_runs(self, session, flow, work_pool):
work_queue = await models.work_queues.create_work_queue(
session=session,
work_queue=schemas.core.WorkQueue(
name="wq-1",
description="All about my work queue",
last_polled=datetime.now(timezone.utc),
work_pool_id=work_pool.id,
priority=1,
),
)
await models.flow_runs.create_flow_run(
session=session,
flow_run=schemas.core.FlowRun(
flow_id=flow.id,
state=schemas.states.Late(
scheduled_time=datetime.now(timezone.utc) - timedelta(minutes=60)
),
work_queue_id=work_queue.id,
),
)
await session.commit()
return work_queue
async def test_read_work_queue_status(self, client, recently_polled_work_queue):
response = await client.get(
f"/work_queues/{recently_polled_work_queue.id}/status"
)
assert response.status_code == status.HTTP_200_OK
parsed_response = parse_obj_as(
schemas.core.WorkQueueStatusDetail, response.json()
)
assert parsed_response.healthy is True
assert parsed_response.late_runs_count == 0
assert parsed_response.last_polled == recently_polled_work_queue.last_polled
async def test_read_work_queue_status_unhealthy_due_to_lack_of_polls(
self, client, not_recently_polled_work_queue
):
response = await client.get(
f"/work_queues/{not_recently_polled_work_queue.id}/status"
)
assert response.status_code == status.HTTP_200_OK
parsed_response = parse_obj_as(
schemas.core.WorkQueueStatusDetail, response.json()
)
assert parsed_response.healthy is False
assert parsed_response.late_runs_count == 0
assert parsed_response.last_polled == not_recently_polled_work_queue.last_polled
async def test_read_work_queue_status_unhealthy_due_to_late_runs(
self, client, work_queue_with_late_runs
):
response = await client.get(
f"/work_queues/{work_queue_with_late_runs.id}/status"
)
assert response.status_code == status.HTTP_200_OK
parsed_response = parse_obj_as(
schemas.core.WorkQueueStatusDetail, response.json()
)
assert parsed_response.healthy is False
assert parsed_response.late_runs_count == 1
assert parsed_response.last_polled == work_queue_with_late_runs.last_polled
async def test_read_work_queue_returns_correct_status_when_work_queues_share_name(
self,
client,
work_queue_with_late_runs,
recently_pool_work_queue_in_different_work_pool,
):
healthy_response = await client.get(
f"/work_queues/{recently_pool_work_queue_in_different_work_pool.id}/status"
)
assert healthy_response.status_code == status.HTTP_200_OK
parsed_healthy_response = parse_obj_as(
schemas.core.WorkQueueStatusDetail, healthy_response.json()
)
assert parsed_healthy_response.healthy is True
unhealthy_response = await client.get(
f"/work_queues/{work_queue_with_late_runs.id}/status"
)
assert unhealthy_response.status_code == status.HTTP_200_OK
parsed_unhealthy_response = parse_obj_as(
schemas.core.WorkQueueStatusDetail, unhealthy_response.json()
)
assert parsed_unhealthy_response.healthy is False
async def test_read_work_queue_status_returns_404_if_does_not_exist(self, client):
response = await client.get(f"/work_queues/{uuid4()}/status")
assert response.status_code == status.HTTP_404_NOT_FOUND
| TestReadWorkQueueStatus |
python | jina-ai__jina | jina/serve/instrumentation/__init__.py | {
"start": 988,
"end": 5239
} | class ____:
"""Instrumentation mixin for OpenTelemetery Tracing and Metrics handling"""
def _setup_instrumentation(
self,
name: str,
tracing: Optional[bool] = False,
traces_exporter_host: Optional[str] = '0.0.0.0',
traces_exporter_port: Optional[int] = 6831,
metrics: Optional[bool] = False,
metrics_exporter_host: Optional[str] = '0.0.0.0',
metrics_exporter_port: Optional[int] = 6831,
) -> None:
self.tracing = tracing
self.metrics = metrics
if tracing:
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
OTLPSpanExporter,
)
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
resource = Resource(attributes=_get_resource_attributes(name))
provider = TracerProvider(resource=resource)
processor = BatchSpanProcessor(
OTLPSpanExporter(
endpoint=f'{traces_exporter_host}:{traces_exporter_port}',
)
)
provider.add_span_processor(processor)
self.tracer_provider = provider
self.tracer = provider.get_tracer(name)
else:
self.tracer_provider = None
self.tracer = None
if metrics:
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import (
OTLPMetricExporter,
)
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource
resource = Resource(attributes=_get_resource_attributes(name))
metric_reader = PeriodicExportingMetricReader(
OTLPMetricExporter(
endpoint=f'{metrics_exporter_host}:{metrics_exporter_port}',
)
)
meter_provider = MeterProvider(
metric_readers=[metric_reader], resource=resource
)
self.meter_provider = meter_provider
self.meter = self.meter_provider.get_meter(name)
else:
self.meter_provider = None
self.meter = None
def aio_tracing_server_interceptors(
self,
) -> Optional[Sequence['ServerInterceptor']]:
"""Create a gRPC aio server interceptor.
:returns: A service-side aio interceptor object.
"""
if self.tracing:
from opentelemetry.instrumentation.grpc._aio_server import (
OpenTelemetryAioServerInterceptor,
)
return [OpenTelemetryAioServerInterceptor(self.tracer)]
else:
return None
def aio_tracing_client_interceptors(
self,
) -> Optional[Sequence['ClientInterceptor']]:
"""Create a gRPC client aio channel interceptor.
:returns: An invocation-side list of aio interceptor objects.
"""
if self.tracing:
from opentelemetry.instrumentation.grpc._aio_client import (
StreamStreamAioClientInterceptor,
StreamUnaryAioClientInterceptor,
UnaryStreamAioClientInterceptor,
UnaryUnaryAioClientInterceptor,
)
return [
UnaryUnaryAioClientInterceptor(self.tracer),
UnaryStreamAioClientInterceptor(self.tracer),
StreamUnaryAioClientInterceptor(self.tracer),
StreamStreamAioClientInterceptor(self.tracer),
]
else:
return None
def tracing_client_interceptor(self) -> Optional['OpenTelemetryClientInterceptor']:
"""
:returns: a gRPC client interceptor with the global tracing provider.
"""
if self.tracing:
from opentelemetry.instrumentation.grpc import (
client_interceptor as grpc_client_interceptor,
)
return grpc_client_interceptor(self.tracer_provider)
else:
return None
| InstrumentationMixin |
python | bokeh__bokeh | src/bokeh/models/formatters.py | {
"start": 11743,
"end": 12027
} | class ____(TickFormatter):
''' Display tick values from categorical ranges as string
values.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| CategoricalTickFormatter |
python | openai__openai-python | src/openai/types/conversations/computer_screenshot_content.py | {
"start": 230,
"end": 632
} | class ____(BaseModel):
file_id: Optional[str] = None
"""The identifier of an uploaded file that contains the screenshot."""
image_url: Optional[str] = None
"""The URL of the screenshot image."""
type: Literal["computer_screenshot"]
"""Specifies the event type.
For a computer screenshot, this property is always set to `computer_screenshot`.
"""
| ComputerScreenshotContent |
python | marshmallow-code__marshmallow | tests/base.py | {
"start": 6804,
"end": 6914
} | class ____(BlogSchema):
user = fields.Nested(UserSchema, exclude=("uppername", "species"))
| BlogSchemaExclude |
python | getsentry__sentry | src/sentry/sdk_updates.py | {
"start": 1328,
"end": 1666
} | class ____:
def __init__(self, sdk_versions=None, deprecated_sdks=None, sdk_supported_modules=None):
self.sdk_versions = sdk_versions or get_sdk_versions()
self.deprecated_sdks = deprecated_sdks or settings.DEPRECATED_SDKS
self.sdk_supported_modules = sdk_supported_modules or SDK_SUPPORTED_MODULES
| SdkIndexState |
python | great-expectations__great_expectations | great_expectations/exceptions/exceptions.py | {
"start": 13559,
"end": 13839
} | class ____(MetricError):
def __init__(self, message, failed_metrics) -> None:
super().__init__(message)
if not isinstance(failed_metrics, Iterable):
failed_metrics = (failed_metrics,)
self.failed_metrics = failed_metrics
| MetricResolutionError |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 6602,
"end": 6646
} | class ____:
def f(self):
return 1
| A |
python | pdm-project__pdm | src/pdm/models/reporter.py | {
"start": 1640,
"end": 3617
} | class ____:
def __init__(self, ui: termui.UI, text: str) -> None:
self.ui = ui
self.console = get_console()
self._spinner = Progress(
SpinnerColumn(termui.SPINNER),
TimeElapsedColumn(),
"{task.description}",
MofNCompleteColumn(),
console=self.console,
)
self._spinner_task = self._spinner.add_task(text, total=None)
self.progress = Progress(
" ",
SpinnerColumn(termui.SPINNER, style="primary"),
"{task.description}",
"[info]{task.fields[text]}",
TaskProgressColumn("[info]{task.percentage:>3.0f}%[/]"),
console=self.console,
)
self.live = Live(self, console=self.console)
def __rich_console__(self, console: Console, options: ConsoleOptions) -> RenderResult:
yield self.progress
yield ""
yield self._spinner
def update_spinner(
self,
*,
total: float | None = None,
completed: float | None = None,
advance: float | None = None,
description: str | None = None,
) -> None:
if self.ui.verbosity >= termui.Verbosity.DETAIL and description is not None:
self.console.print(f" {description}")
self._spinner.update(
self._spinner_task, total=total, completed=completed, advance=advance, description=description
)
self.live.refresh()
def start(self) -> None:
"""Start the progress display."""
if self.ui.verbosity < termui.Verbosity.DETAIL:
self.live.start(refresh=True)
def stop(self) -> None:
"""Stop the progress display."""
self.live.stop()
if not self.console.is_interactive:
self.console.print()
def __enter__(self) -> InstallationStatus:
self.start()
return self
def __exit__(self, *args: Any) -> None:
self.stop()
| InstallationStatus |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py | {
"start": 5720,
"end": 6011
} | class ____(BaseModel):
x: str = Field(..., alias=x_alias)
z: int
model_config = ConfigDict(validate_by_name=True)
DynamicAliasModel2(y='y', z=1)
# MYPY: error: Unexpected keyword argument "y" for "DynamicAliasModel2" [call-arg]
DynamicAliasModel2(x='y', z=1)
| DynamicAliasModel2 |
python | pandas-dev__pandas | asv_bench/benchmarks/arithmetic.py | {
"start": 5412,
"end": 6577
} | class ____:
def setup(self):
N = 10**3
self.df = DataFrame(np.random.randn(N, N))
self.df2 = DataFrame(np.random.randn(N, N))
self.df_int = DataFrame(
np.random.randint(
np.iinfo(np.int16).min, np.iinfo(np.int16).max, size=(N, N)
)
)
self.df2_int = DataFrame(
np.random.randint(
np.iinfo(np.int16).min, np.iinfo(np.int16).max, size=(N, N)
)
)
self.s = Series(np.random.randn(N))
# Division
def time_frame_float_div(self):
self.df // self.df2
def time_frame_float_div_by_zero(self):
self.df / 0
def time_frame_float_floor_by_zero(self):
self.df // 0
def time_frame_int_div_by_zero(self):
self.df_int / 0
# Modulo
def time_frame_int_mod(self):
self.df_int % self.df2_int
def time_frame_float_mod(self):
self.df % self.df2
# Dot product
def time_frame_dot(self):
self.df.dot(self.df2)
def time_series_dot(self):
self.s.dot(self.s)
def time_frame_series_dot(self):
self.df.dot(self.s)
| Ops2 |
python | Netflix__metaflow | metaflow/plugins/kubernetes/kubernetes_client.py | {
"start": 293,
"end": 388
} | class ____(MetaflowException):
headline = "Kubernetes client error"
| KubernetesClientException |
python | pypa__pipenv | pipenv/patched/pip/_internal/network/auth.py | {
"start": 1118,
"end": 1445
} | class ____(ABC):
"""Keyring base provider interface"""
has_keyring: bool
@abstractmethod
def get_auth_info(
self, url: str, username: Optional[str]
) -> Optional[AuthInfo]: ...
@abstractmethod
def save_auth_info(self, url: str, username: str, password: str) -> None: ...
| KeyRingBaseProvider |
python | great-expectations__great_expectations | tests/render/test_renderer_configuration.py | {
"start": 5966,
"end": 10390
} | class ____:
def __str__(self):
raise TypeError("I'm not a string")
@pytest.mark.unit
@pytest.mark.parametrize(
"param_type,value",
[
(RendererValueType.STRING, NotString()),
(RendererValueType.NUMBER, "ABC"),
(RendererValueType.BOOLEAN, 3),
(RendererValueType.ARRAY, 3),
],
)
def test_renderer_configuration_add_param_validation(
param_type: RendererValueType, value: Union[NotString, str, int]
):
expectation_configuration = ExpectationConfiguration(
type="expect_table_row_count_to_equal",
kwargs={"value": value},
)
renderer_configuration = RendererConfiguration(configuration=expectation_configuration)
with pytest.raises(pydantic_error_wrappers.ValidationError) as e:
renderer_configuration.add_param(name="value", param_type=param_type)
if param_type is RendererValueType.STRING:
exception_message = (
f"Value was unable to be represented as a {RendererValueType.STRING}: I'm not a string"
)
else:
exception_message = f"Param type: <{param_type}> does not match value: <{value}>."
assert any(
str(error_wrapper_exc) == exception_message
for error_wrapper_exc in [error_wrapper.exc for error_wrapper in e.value.raw_errors]
)
@pytest.mark.unit
def test_add_param_args():
expectation_configuration = ExpectationConfiguration(
type="expect_column_value_z_scores_to_be_less_than",
kwargs={"column": "foo", "threshold": 2, "double_sided": False, "mostly": 1.0},
)
renderer_configuration = RendererConfiguration(configuration=expectation_configuration)
add_param_args: AddParamArgs = (
("column", RendererValueType.STRING),
("threshold", RendererValueType.NUMBER),
("double_sided", RendererValueType.BOOLEAN),
("mostly", RendererValueType.NUMBER),
)
for name, param_type in add_param_args:
renderer_configuration.add_param(name=name, param_type=param_type)
params = renderer_configuration.params
assert params.column
assert params.threshold
assert params.double_sided
assert params.mostly
@pytest.mark.unit
def test_template_str_setter():
expectation_configuration = ExpectationConfiguration(
type="expect_column_value_z_scores_to_be_less_than",
kwargs={"column": "foo", "threshold": 2, "double_sided": False, "mostly": 1.0},
)
renderer_configuration = RendererConfiguration(configuration=expectation_configuration)
template_str = "My rendered string"
renderer_configuration.template_str = template_str
assert renderer_configuration.template_str == template_str
@pytest.mark.unit
def test_add_array_params():
expectation_configuration = ExpectationConfiguration(
type="expect_column_values_to_match_like_pattern_list",
kwargs={"column": "foo", "like_pattern_list": ["%", "_"], "match_on": "any", "mostly": 1.0},
)
renderer_configuration = RendererConfiguration(configuration=expectation_configuration)
renderer_configuration.add_param(name="like_pattern_list", param_type=RendererValueType.ARRAY)
array_param_name = "like_pattern_list"
param_prefix = array_param_name + "_"
renderer_configuration = Expectation._add_array_params(
array_param_name=array_param_name,
param_prefix=param_prefix,
renderer_configuration=renderer_configuration,
)
params = renderer_configuration.params
assert params.like_pattern_list_0
assert params.like_pattern_list_1
array_string = Expectation._get_array_string(
array_param_name=array_param_name,
param_prefix=param_prefix,
renderer_configuration=renderer_configuration,
)
assert array_string == "$like_pattern_list_0 $like_pattern_list_1"
@pytest.mark.parametrize(
("value", "type"),
[
([1, 2, 3], RendererValueType.ARRAY),
(True, RendererValueType.BOOLEAN),
(datetime.now(tz=timezone.utc), RendererValueType.DATETIME),
(3.14, RendererValueType.NUMBER),
({"foo": "bar"}, RendererValueType.OBJECT),
("hello world!", RendererValueType.STRING),
(uuid.uuid4(), RendererValueType.STRING),
(None, RendererValueType.STRING),
],
)
@pytest.mark.unit
def test_from_value(value: Any, type: RendererValueType) -> None:
assert RendererValueType.from_value(value) == type
| NotString |
python | rq__rq | tests/test_worker.py | {
"start": 57251,
"end": 62437
} | class ____(TimeoutTestCase, RQTestCase):
@slow
def test_idle_worker_warm_shutdown(self):
"""worker with no ongoing job receiving single SIGTERM signal and shutting down"""
w = Worker('foo', connection=self.connection)
self.assertFalse(w._stop_requested)
p = Process(target=kill_worker, args=(os.getpid(), False))
p.start()
w.work()
p.join(1)
self.assertFalse(w._stop_requested)
@slow
def test_working_worker_warm_shutdown(self):
"""worker with an ongoing job receiving single SIGTERM signal, allowing job to finish then shutting down"""
fooq = Queue('foo', connection=self.connection)
w = Worker(fooq)
sentinel_file = '/tmp/.rq_sentinel_warm'
fooq.enqueue(create_file_after_timeout, sentinel_file, 2)
self.assertFalse(w._stop_requested)
p = Process(target=kill_worker, args=(os.getpid(), False))
p.start()
w.work()
p.join(2)
self.assertFalse(p.is_alive())
self.assertTrue(w._stop_requested)
self.assertTrue(os.path.exists(sentinel_file))
self.assertIsNotNone(w.shutdown_requested_date)
self.assertEqual(type(w.shutdown_requested_date).__name__, 'datetime')
@slow
def test_working_worker_cold_shutdown(self):
"""Busy worker shuts down immediately on double SIGTERM signal"""
fooq = Queue('foo', connection=self.connection)
w = Worker(fooq)
sentinel_file = '/tmp/.rq_sentinel_cold'
self.assertFalse(
os.path.exists(sentinel_file), f'{sentinel_file} file should not exist yet, delete that file and try again.'
)
fooq.enqueue(create_file_after_timeout, sentinel_file, 5)
self.assertFalse(w._stop_requested)
p = Process(target=kill_worker, args=(os.getpid(), True))
p.start()
self.assertRaises(SystemExit, w.work)
p.join(1)
self.assertTrue(w._stop_requested)
self.assertFalse(os.path.exists(sentinel_file))
shutdown_requested_date = w.shutdown_requested_date
self.assertIsNotNone(shutdown_requested_date)
self.assertEqual(type(shutdown_requested_date).__name__, 'datetime')
@slow
def test_work_horse_death_sets_job_failed(self):
"""worker with an ongoing job whose work horse dies unexpectedly (before
completing the job) should set the job's status to FAILED
"""
fooq = Queue('foo', connection=self.connection)
self.assertEqual(fooq.count, 0)
w = Worker(fooq)
sentinel_file = '/tmp/.rq_sentinel_work_horse_death'
if os.path.exists(sentinel_file):
os.remove(sentinel_file)
fooq.enqueue(create_file_after_timeout, sentinel_file, 100)
job, queue = w.dequeue_job_and_maintain_ttl(5)
w.fork_work_horse(job, queue)
p = Process(target=wait_and_kill_work_horse, args=(w._horse_pid, 0.5))
p.start()
w.monitor_work_horse(job, queue)
job_status = job.get_status()
p.join(1)
self.assertEqual(job_status, JobStatus.FAILED)
failed_job_registry = FailedJobRegistry(queue=fooq)
self.assertIn(job, failed_job_registry)
self.assertEqual(fooq.count, 0)
@slow
def test_work_horse_force_death(self):
"""Simulate a frozen worker that doesn't observe the timeout properly.
Fake it by artificially setting the timeout of the parent process to
something much smaller after the process is already forked.
"""
fooq = Queue('foo', connection=self.connection)
self.assertEqual(fooq.count, 0)
w = Worker([fooq], job_monitoring_interval=1)
sentinel_file = '/tmp/.rq_sentinel_work_horse_death'
if os.path.exists(sentinel_file):
os.remove(sentinel_file)
job = fooq.enqueue(launch_process_within_worker_and_store_pid, sentinel_file, 100)
_, queue = w.dequeue_job_and_maintain_ttl(5)
w.prepare_job_execution(job)
w.fork_work_horse(job, queue)
job.timeout = 5
time.sleep(1)
with open(sentinel_file) as f:
subprocess_pid = int(f.read().strip())
self.assertTrue(psutil.pid_exists(subprocess_pid))
w.prepare_execution(job)
with mock.patch.object(w, 'handle_work_horse_killed', wraps=w.handle_work_horse_killed) as mocked:
w.monitor_work_horse(job, queue)
self.assertEqual(mocked.call_count, 1)
fudge_factor = 1
total_time = w.job_monitoring_interval + 65 + fudge_factor
right_now = now()
self.assertLess((now() - right_now).total_seconds(), total_time)
self.assertEqual(job.get_status(), JobStatus.FAILED)
failed_job_registry = FailedJobRegistry(queue=fooq)
self.assertIn(job, failed_job_registry)
self.assertEqual(fooq.count, 0)
self.assertFalse(psutil.pid_exists(subprocess_pid))
def schedule_access_self():
q = Queue('default', connection=find_empty_redis_database())
q.enqueue(access_self)
@pytest.mark.skipif(sys.platform == 'darwin', reason='Fails on OS X')
| WorkerShutdownTestCase |
python | agronholm__apscheduler | src/apscheduler/_exceptions.py | {
"start": 1103,
"end": 1230
} | class ____(Exception):
"""
Raised by :meth:`~Scheduler.get_job_result` if the job was
cancelled.
"""
| JobCancelled |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 16347,
"end": 16734
} | class ____(Interface):
def __call__(self, object):
"""Provided with an arbitrary object (a function, class, or
instance), returns a callable with the call signature ``(context,
request)``. The callable returned should itself return a Response
object. An IViewMapper is returned by
:class:`pyramid.interfaces.IViewMapperFactory`."""
| IViewMapper |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.