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
|
mwaskom__seaborn
|
tests/test_relational.py
|
{
"start": 45291,
"end": 63222
}
|
class ____(SharedAxesLevelTests, Helpers):
func = staticmethod(scatterplot)
def get_last_color(self, ax):
colors = ax.collections[-1].get_facecolors()
unique_colors = np.unique(colors, axis=0)
assert len(unique_colors) == 1
return to_rgba(unique_colors.squeeze())
def test_color(self, long_df):
super().test_color(long_df)
ax = plt.figure().subplots()
self.func(data=long_df, x="x", y="y", facecolor="C5", ax=ax)
assert self.get_last_color(ax) == to_rgba("C5")
ax = plt.figure().subplots()
self.func(data=long_df, x="x", y="y", facecolors="C6", ax=ax)
assert self.get_last_color(ax) == to_rgba("C6")
ax = plt.figure().subplots()
self.func(data=long_df, x="x", y="y", fc="C4", ax=ax)
assert self.get_last_color(ax) == to_rgba("C4")
def test_legend_no_semantics(self, long_df):
ax = scatterplot(long_df, x="x", y="y")
handles, _ = ax.get_legend_handles_labels()
assert not handles
def test_legend_hue(self, long_df):
ax = scatterplot(long_df, x="x", y="y", hue="a")
handles, labels = ax.get_legend_handles_labels()
colors = [h.get_color() for h in handles]
expected_colors = color_palette(n_colors=len(handles))
assert same_color(colors, expected_colors)
assert labels == categorical_order(long_df["a"])
def test_legend_hue_style_same(self, long_df):
ax = scatterplot(long_df, x="x", y="y", hue="a", style="a")
handles, labels = ax.get_legend_handles_labels()
colors = [h.get_color() for h in handles]
expected_colors = color_palette(n_colors=len(labels))
markers = [h.get_marker() for h in handles]
expected_markers = unique_markers(len(handles))
assert same_color(colors, expected_colors)
assert markers == expected_markers
assert labels == categorical_order(long_df["a"])
def test_legend_hue_style_different(self, long_df):
ax = scatterplot(long_df, x="x", y="y", hue="a", style="b")
handles, labels = ax.get_legend_handles_labels()
colors = [h.get_color() for h in handles]
expected_colors = [
"w", *color_palette(n_colors=long_df["a"].nunique()),
"w", *[".2" for _ in long_df["b"].unique()],
]
markers = [h.get_marker() for h in handles]
expected_markers = [
"", *["o" for _ in long_df["a"].unique()],
"", *unique_markers(long_df["b"].nunique()),
]
assert same_color(colors, expected_colors)
assert markers == expected_markers
assert labels == [
"a", *categorical_order(long_df["a"]),
"b", *categorical_order(long_df["b"]),
]
def test_legend_data_hue_size_same(self, long_df):
ax = scatterplot(long_df, x="x", y="y", hue="a", size="a")
handles, labels = ax.get_legend_handles_labels()
colors = [h.get_color() for h in handles]
expected_colors = color_palette(n_colors=len(labels))
sizes = [h.get_markersize() for h in handles]
ms = mpl.rcParams["lines.markersize"] ** 2
expected_sizes = np.sqrt(
[ms * scl for scl in np.linspace(2, 0.5, len(handles))]
).tolist()
assert same_color(colors, expected_colors)
assert sizes == expected_sizes
assert labels == categorical_order(long_df["a"])
assert ax.get_legend().get_title().get_text() == "a"
def test_legend_size_numeric_list(self, long_df):
size_list = [10, 100, 200]
ax = scatterplot(long_df, x="x", y="y", size="s", sizes=size_list)
handles, labels = ax.get_legend_handles_labels()
sizes = [h.get_markersize() for h in handles]
expected_sizes = list(np.sqrt(size_list))
assert sizes == expected_sizes
assert labels == list(map(str, categorical_order(long_df["s"])))
assert ax.get_legend().get_title().get_text() == "s"
def test_legend_size_numeric_dict(self, long_df):
size_dict = {2: 10, 4: 100, 8: 200}
ax = scatterplot(long_df, x="x", y="y", size="s", sizes=size_dict)
handles, labels = ax.get_legend_handles_labels()
sizes = [h.get_markersize() for h in handles]
order = categorical_order(long_df["s"])
expected_sizes = [np.sqrt(size_dict[k]) for k in order]
assert sizes == expected_sizes
assert labels == list(map(str, order))
assert ax.get_legend().get_title().get_text() == "s"
def test_legend_numeric_hue_full(self):
x, y = np.random.randn(2, 40)
z = np.tile(np.arange(20), 2)
ax = scatterplot(x=x, y=y, hue=z, legend="full")
_, labels = ax.get_legend_handles_labels()
assert labels == [str(z_i) for z_i in sorted(set(z))]
assert ax.get_legend().get_title().get_text() == ""
def test_legend_numeric_hue_brief(self):
x, y = np.random.randn(2, 40)
z = np.tile(np.arange(20), 2)
ax = scatterplot(x=x, y=y, hue=z, legend="brief")
_, labels = ax.get_legend_handles_labels()
assert len(labels) < len(set(z))
def test_legend_numeric_size_full(self):
x, y = np.random.randn(2, 40)
z = np.tile(np.arange(20), 2)
ax = scatterplot(x=x, y=y, size=z, legend="full")
_, labels = ax.get_legend_handles_labels()
assert labels == [str(z_i) for z_i in sorted(set(z))]
def test_legend_numeric_size_brief(self):
x, y = np.random.randn(2, 40)
z = np.tile(np.arange(20), 2)
ax = scatterplot(x=x, y=y, size=z, legend="brief")
_, labels = ax.get_legend_handles_labels()
assert len(labels) < len(set(z))
def test_legend_attributes_hue(self, long_df):
kws = {"s": 50, "linewidth": 1, "marker": "X"}
ax = scatterplot(long_df, x="x", y="y", hue="a", **kws)
palette = color_palette()
for i, pt in enumerate(get_legend_handles(ax.get_legend())):
assert same_color(pt.get_color(), palette[i])
assert pt.get_markersize() == np.sqrt(kws["s"])
assert pt.get_markeredgewidth() == kws["linewidth"]
if not _version_predates(mpl, "3.7.0"):
# This attribute is empty on older matplotlibs
# but the legend looks correct so I assume it is a bug
assert pt.get_marker() == kws["marker"]
def test_legend_attributes_style(self, long_df):
kws = {"s": 50, "linewidth": 1, "color": "r"}
ax = scatterplot(long_df, x="x", y="y", style="a", **kws)
for pt in get_legend_handles(ax.get_legend()):
assert pt.get_markersize() == np.sqrt(kws["s"])
assert pt.get_markeredgewidth() == kws["linewidth"]
assert same_color(pt.get_color(), "r")
def test_legend_attributes_hue_and_style(self, long_df):
kws = {"s": 50, "linewidth": 1}
ax = scatterplot(long_df, x="x", y="y", hue="a", style="b", **kws)
for pt in get_legend_handles(ax.get_legend()):
if pt.get_label() not in ["a", "b"]:
assert pt.get_markersize() == np.sqrt(kws["s"])
assert pt.get_markeredgewidth() == kws["linewidth"]
def test_legend_value_error(self, long_df):
with pytest.raises(ValueError, match=r"`legend` must be"):
scatterplot(long_df, x="x", y="y", hue="a", legend="bad_value")
def test_plot(self, long_df, repeated_df):
f, ax = plt.subplots()
p = _ScatterPlotter(data=long_df, variables=dict(x="x", y="y"))
p.plot(ax, {})
points = ax.collections[0]
assert_array_equal(points.get_offsets(), long_df[["x", "y"]].to_numpy())
ax.clear()
p.plot(ax, {"color": "k", "label": "test"})
points = ax.collections[0]
assert same_color(points.get_facecolor(), "k")
assert points.get_label() == "test"
p = _ScatterPlotter(
data=long_df, variables=dict(x="x", y="y", hue="a")
)
ax.clear()
p.plot(ax, {})
points = ax.collections[0]
expected_colors = p._hue_map(p.plot_data["hue"])
assert same_color(points.get_facecolors(), expected_colors)
p = _ScatterPlotter(
data=long_df,
variables=dict(x="x", y="y", style="c"),
)
p.map_style(markers=["+", "x"])
ax.clear()
color = (1, .3, .8)
p.plot(ax, {"color": color})
points = ax.collections[0]
assert same_color(points.get_edgecolors(), [color])
p = _ScatterPlotter(
data=long_df, variables=dict(x="x", y="y", size="a"),
)
ax.clear()
p.plot(ax, {})
points = ax.collections[0]
expected_sizes = p._size_map(p.plot_data["size"])
assert_array_equal(points.get_sizes(), expected_sizes)
p = _ScatterPlotter(
data=long_df,
variables=dict(x="x", y="y", hue="a", style="a"),
)
p.map_style(markers=True)
ax.clear()
p.plot(ax, {})
points = ax.collections[0]
expected_colors = p._hue_map(p.plot_data["hue"])
expected_paths = p._style_map(p.plot_data["style"], "path")
assert same_color(points.get_facecolors(), expected_colors)
assert self.paths_equal(points.get_paths(), expected_paths)
p = _ScatterPlotter(
data=long_df,
variables=dict(x="x", y="y", hue="a", style="b"),
)
p.map_style(markers=True)
ax.clear()
p.plot(ax, {})
points = ax.collections[0]
expected_colors = p._hue_map(p.plot_data["hue"])
expected_paths = p._style_map(p.plot_data["style"], "path")
assert same_color(points.get_facecolors(), expected_colors)
assert self.paths_equal(points.get_paths(), expected_paths)
x_str = long_df["x"].astype(str)
p = _ScatterPlotter(
data=long_df, variables=dict(x="x", y="y", hue=x_str),
)
ax.clear()
p.plot(ax, {})
p = _ScatterPlotter(
data=long_df, variables=dict(x="x", y="y", size=x_str),
)
ax.clear()
p.plot(ax, {})
def test_axis_labels(self, long_df):
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
p = _ScatterPlotter(data=long_df, variables=dict(x="x", y="y"))
p.plot(ax1, {})
assert ax1.get_xlabel() == "x"
assert ax1.get_ylabel() == "y"
p.plot(ax2, {})
assert ax2.get_xlabel() == "x"
assert ax2.get_ylabel() == "y"
assert not ax2.yaxis.label.get_visible()
def test_scatterplot_axes(self, wide_df):
f1, ax1 = plt.subplots()
f2, ax2 = plt.subplots()
ax = scatterplot(data=wide_df)
assert ax is ax2
ax = scatterplot(data=wide_df, ax=ax1)
assert ax is ax1
def test_literal_attribute_vectors(self):
f, ax = plt.subplots()
x = y = [1, 2, 3]
s = [5, 10, 15]
c = [(1, 1, 0, 1), (1, 0, 1, .5), (.5, 1, 0, 1)]
scatterplot(x=x, y=y, c=c, s=s, ax=ax)
points, = ax.collections
assert_array_equal(points.get_sizes().squeeze(), s)
assert_array_equal(points.get_facecolors(), c)
def test_supplied_color_array(self, long_df):
cmap = get_colormap("Blues")
norm = mpl.colors.Normalize()
colors = cmap(norm(long_df["y"].to_numpy()))
keys = ["c", "fc", "facecolor", "facecolors"]
for key in keys:
ax = plt.figure().subplots()
scatterplot(data=long_df, x="x", y="y", **{key: colors})
_draw_figure(ax.figure)
assert_array_equal(ax.collections[0].get_facecolors(), colors)
ax = plt.figure().subplots()
scatterplot(data=long_df, x="x", y="y", c=long_df["y"], cmap=cmap)
_draw_figure(ax.figure)
assert_array_equal(ax.collections[0].get_facecolors(), colors)
def test_hue_order(self, long_df):
order = categorical_order(long_df["a"])
unused = order.pop()
ax = scatterplot(data=long_df, x="x", y="y", hue="a", hue_order=order)
points = ax.collections[0]
assert (points.get_facecolors()[long_df["a"] == unused] == 0).all()
assert [t.get_text() for t in ax.legend_.texts] == order
def test_linewidths(self, long_df):
f, ax = plt.subplots()
scatterplot(data=long_df, x="x", y="y", s=10)
scatterplot(data=long_df, x="x", y="y", s=20)
points1, points2 = ax.collections
assert (
points1.get_linewidths().item() < points2.get_linewidths().item()
)
ax.clear()
scatterplot(data=long_df, x="x", y="y", s=long_df["x"])
scatterplot(data=long_df, x="x", y="y", s=long_df["x"] * 2)
points1, points2 = ax.collections
assert (
points1.get_linewidths().item() < points2.get_linewidths().item()
)
ax.clear()
lw = 2
scatterplot(data=long_df, x="x", y="y", linewidth=lw)
assert ax.collections[0].get_linewidths().item() == lw
def test_size_norm_extrapolation(self):
# https://github.com/mwaskom/seaborn/issues/2539
x = np.arange(0, 20, 2)
f, axs = plt.subplots(1, 2, sharex=True, sharey=True)
slc = 5
kws = dict(sizes=(50, 200), size_norm=(0, x.max()), legend="brief")
scatterplot(x=x, y=x, size=x, ax=axs[0], **kws)
scatterplot(x=x[:slc], y=x[:slc], size=x[:slc], ax=axs[1], **kws)
assert np.allclose(
axs[0].collections[0].get_sizes()[:slc],
axs[1].collections[0].get_sizes()
)
legends = [ax.legend_ for ax in axs]
legend_data = [
{
label.get_text(): handle.get_markersize()
for label, handle in zip(legend.get_texts(), get_legend_handles(legend))
} for legend in legends
]
for key in set(legend_data[0]) & set(legend_data[1]):
if key == "y":
# At some point (circa 3.0) matplotlib auto-added pandas series
# with a valid name into the legend, which messes up this test.
# I can't track down when that was added (or removed), so let's
# just anticipate and ignore it here.
continue
assert legend_data[0][key] == legend_data[1][key]
def test_datetime_scale(self, long_df):
ax = scatterplot(data=long_df, x="t", y="y")
# Check that we avoid weird matplotlib default auto scaling
# https://github.com/matplotlib/matplotlib/issues/17586
ax.get_xlim()[0] > ax.xaxis.convert_units(np.datetime64("2002-01-01"))
def test_unfilled_marker_edgecolor_warning(self, long_df): # GH2636
with warnings.catch_warnings():
warnings.simplefilter("error")
scatterplot(data=long_df, x="x", y="y", marker="+")
def test_short_form_kwargs(self, long_df):
ax = scatterplot(data=long_df, x="x", y="y", ec="g")
pts = ax.collections[0]
assert same_color(pts.get_edgecolors().squeeze(), "g")
def test_scatterplot_vs_relplot(self, long_df, long_semantics):
ax = scatterplot(data=long_df, **long_semantics)
g = relplot(data=long_df, kind="scatter", **long_semantics)
for s_pts, r_pts in zip(ax.collections, g.ax.collections):
assert_array_equal(s_pts.get_offsets(), r_pts.get_offsets())
assert_array_equal(s_pts.get_sizes(), r_pts.get_sizes())
assert_array_equal(s_pts.get_facecolors(), r_pts.get_facecolors())
assert self.paths_equal(s_pts.get_paths(), r_pts.get_paths())
def test_scatterplot_smoke(
self,
wide_df, wide_array,
flat_series, flat_array, flat_list,
wide_list_of_series, wide_list_of_arrays, wide_list_of_lists,
long_df, null_df, object_df
):
f, ax = plt.subplots()
scatterplot(x=[], y=[])
ax.clear()
scatterplot(data=wide_df)
ax.clear()
scatterplot(data=wide_array)
ax.clear()
scatterplot(data=wide_list_of_series)
ax.clear()
scatterplot(data=wide_list_of_arrays)
ax.clear()
scatterplot(data=wide_list_of_lists)
ax.clear()
scatterplot(data=flat_series)
ax.clear()
scatterplot(data=flat_array)
ax.clear()
scatterplot(data=flat_list)
ax.clear()
scatterplot(x="x", y="y", data=long_df)
ax.clear()
scatterplot(x=long_df.x, y=long_df.y)
ax.clear()
scatterplot(x=long_df.x, y="y", data=long_df)
ax.clear()
scatterplot(x="x", y=long_df.y.to_numpy(), data=long_df)
ax.clear()
scatterplot(x="x", y="y", hue="a", data=long_df)
ax.clear()
scatterplot(x="x", y="y", hue="a", style="a", data=long_df)
ax.clear()
scatterplot(x="x", y="y", hue="a", style="b", data=long_df)
ax.clear()
scatterplot(x="x", y="y", hue="a", style="a", data=null_df)
ax.clear()
scatterplot(x="x", y="y", hue="a", style="b", data=null_df)
ax.clear()
scatterplot(x="x", y="y", hue="a", size="a", data=long_df)
ax.clear()
scatterplot(x="x", y="y", hue="a", size="s", data=long_df)
ax.clear()
scatterplot(x="x", y="y", hue="a", size="a", data=null_df)
ax.clear()
scatterplot(x="x", y="y", hue="a", size="s", data=null_df)
ax.clear()
scatterplot(x="x", y="y", hue="f", data=object_df)
ax.clear()
scatterplot(x="x", y="y", hue="c", size="f", data=object_df)
ax.clear()
scatterplot(x="x", y="y", hue="f", size="s", data=object_df)
ax.clear()
|
TestScatterPlotter
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/orm/mapped_collection.py
|
{
"start": 1192,
"end": 2470
}
|
class ____(Generic[_KT]):
"""Plain column getter, stores collection of Column objects
directly.
Serializes to a :class:`._SerializableColumnGetterV2`
which has more expensive __call__() performance
and some rare caveats.
"""
__slots__ = ("cols", "composite")
def __init__(self, cols: Sequence[ColumnElement[_KT]]) -> None:
self.cols = cols
self.composite = len(cols) > 1
def __reduce__(
self,
) -> Tuple[
Type[_SerializableColumnGetterV2[_KT]],
Tuple[Sequence[Tuple[Optional[str], Optional[str]]]],
]:
return _SerializableColumnGetterV2._reduce_from_cols(self.cols)
def _cols(self, mapper: Mapper[_KT]) -> Sequence[ColumnElement[_KT]]:
return self.cols
def __call__(self, value: _KT) -> MissingOr[Union[_KT, Tuple[_KT, ...]]]:
state = base.instance_state(value)
m = base._state_mapper(state)
key: List[_KT] = [
m._get_state_attr_by_column(state, state.dict, col)
for col in self._cols(m)
]
if self.composite:
return tuple(key)
else:
obj = key[0]
if obj is None:
return Missing
else:
return obj
|
_PlainColumnGetter
|
python
|
geekcomputers__Python
|
XORcipher/test_XOR_cipher.py
|
{
"start": 403,
"end": 3971
}
|
class ____(TestCase):
"""
Test XORCipher class.
"""
def setUp(self):
"""
The SetUp call with commented values in the event one needs
to instantiate mocked objects regarding the XORCipher class.
"""
# key = mock.MagicMock()
# self.XORCipher_1 = XORCipher(key)
pass
@mock.patch("XOR_cipher.XORCipher.__init__")
def test__init__(self, mock__init__):
"""
Test the __init__ method with commented values in the event
one needs to instantiate mocked objects on the method.
"""
# self.XORCipher_1.__init__ = mock.MagicMock()
XORCipher.__init__ = mock.MagicMock()
# self.XORCipher_1.__init__(1)
XORCipher.__init__()
# self.XORCipher_1.__init__.assert_called_with(1)
XORCipher.__init__.assert_called()
@mock.patch("XOR_cipher.XORCipher.encrypt")
def test_encrypt(self, mock_encrypt):
"""
Test the encrypt method with mocked values.
"""
ans = mock.MagicMock()
content = mock.MagicMock()
key = mock.MagicMock()
XORCipher.encrypt = mock.MagicMock(return_value=ans)
XORCipher.encrypt(content, key)
XORCipher.encrypt.assert_called_with(content, key)
@mock.patch("XOR_cipher.XORCipher.decrypt")
def test_decrypt(self, mock_decrypt):
"""
Test the decrypt method with mocked values.
"""
ans = mock.MagicMock()
content = mock.MagicMock()
key = mock.MagicMock()
XORCipher.decrypt = mock.MagicMock(return_value=ans)
XORCipher.decrypt(content, key)
XORCipher.decrypt.assert_called_with(content, key)
@mock.patch("XOR_cipher.XORCipher.encrypt_string")
def test_encrypt_string(self, mock_encrypt_string):
"""
Test the encrypt_string method with mocked values.
"""
ans = mock.MagicMock()
content = mock.MagicMock()
key = mock.MagicMock()
XORCipher.encrypt_string = mock.MagicMock(return_value=ans)
XORCipher.encrypt_string(content, key)
XORCipher.encrypt_string.assert_called_with(content, key)
@mock.patch("XOR_cipher.XORCipher.decrypt_string")
def test_decrypt_string(self, mock_decrypt_string):
"""
Test the decrypt_string method with mocked values.
"""
ans = mock.MagicMock()
content = mock.MagicMock()
key = mock.MagicMock()
XORCipher.decrypt_string = mock.MagicMock(return_value=ans)
XORCipher.decrypt_string(content, key)
XORCipher.decrypt_string.assert_called_with(content, key)
@mock.patch("XOR_cipher.XORCipher.encrypt_file")
def test_encrypt_file(self, mock_encrypt_file):
"""
Test the encrypt_file method with mocked values.
"""
file = mock.MagicMock()
key = mock.MagicMock()
XORCipher.encrypt_file = mock.MagicMock(return_value=True)
XORCipher.encrypt_file(file, key)
XORCipher.encrypt_file.assert_called_with(file, key)
@mock.patch("XOR_cipher.XORCipher.decrypt_file")
def test_decrypt_file(self, mock_decrypt_file):
"""
Test the decrypt_file method with mocked values.
"""
file = mock.MagicMock()
key = mock.MagicMock()
XORCipher.decrypt_string = mock.MagicMock(return_value=True)
XORCipher.decrypt_string(file, key)
XORCipher.decrypt_string.assert_called_with(file, key)
if __name__ == "__main__":
unittest.main()
|
TestXORCipher
|
python
|
doocs__leetcode
|
solution/1200-1299/1296.Divide Array in Sets of K Consecutive Numbers/Solution.py
|
{
"start": 0,
"end": 381
}
|
class ____:
def isPossibleDivide(self, nums: List[int], k: int) -> bool:
if len(nums) % k:
return False
cnt = Counter(nums)
for x in sorted(nums):
if cnt[x]:
for y in range(x, x + k):
if cnt[y] == 0:
return False
cnt[y] -= 1
return True
|
Solution
|
python
|
apache__airflow
|
providers/amazon/src/airflow/providers/amazon/aws/sensors/bedrock.py
|
{
"start": 15905,
"end": 21069
}
|
class ____(BedrockBaseSensor[BedrockHook]):
"""
Poll the batch inference job status until it reaches a terminal state; fails if creation fails.
.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:BedrockBatchInferenceSensor`
:param job_arn: The Amazon Resource Name (ARN) of the batch inference job. (templated)
:param success_state: A BedrockBatchInferenceSensor.TargetState; defaults to 'SCHEDULED' (templated)
:param deferrable: If True, the sensor will operate in deferrable more. This mode requires aiobotocore
module to be installed.
(default: False, but can be overridden in config file by setting default_deferrable to True)
:param poke_interval: Polling period in seconds to check for the status of the job. (default: 5)
:param max_retries: Number of times before returning the current state (default: 24)
:param aws_conn_id: The Airflow connection used for AWS credentials.
If this is ``None`` or empty then the default boto3 behaviour is used. If
running Airflow in a distributed manner and aws_conn_id is None or
empty, then default boto3 configuration would be used (and must be
maintained on each worker node).
:param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
:param verify: Whether or not to verify SSL certificates. See:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
:param botocore_config: Configuration dictionary (key-values) for botocore client. See:
https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
"""
class SuccessState:
"""
Target state for the BedrockBatchInferenceSensor.
Bedrock adds batch inference jobs to a queue, and they may take some time to complete.
If you want to wait for the job to complete, use TargetState.COMPLETED, but if you only want
to wait until the service confirms that the job is in the queue, use TargetState.SCHEDULED.
The normal successful progression of states is:
Submitted > Validating > Scheduled > InProgress > PartiallyCompleted > Completed
"""
SCHEDULED = "scheduled"
COMPLETED = "completed"
INTERMEDIATE_STATES: tuple[str, ...] # Defined in __init__ based on target state
FAILURE_STATES: tuple[str, ...] = ("Failed", "Stopped", "PartiallyCompleted", "Expired")
SUCCESS_STATES: tuple[str, ...] # Defined in __init__ based on target state
FAILURE_MESSAGE = "Bedrock batch inference job sensor failed."
INVALID_SUCCESS_STATE_MESSAGE = "success_state must be an instance of TargetState."
aws_hook_class = BedrockHook
template_fields: Sequence[str] = aws_template_fields("job_arn", "success_state")
def __init__(
self,
*,
job_arn: str,
success_state: SuccessState | str = SuccessState.SCHEDULED,
poke_interval: int = 120,
max_retries: int = 75,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.poke_interval = poke_interval
self.max_retries = max_retries
self.job_arn = job_arn
self.success_state = success_state
base_success_states: tuple[str, ...] = ("Completed",)
base_intermediate_states: tuple[str, ...] = ("Submitted", "InProgress", "Stopping", "Validating")
scheduled_state = ("Scheduled",)
self.trigger_class: type[BedrockBaseBatchInferenceTrigger]
if self.success_state == BedrockBatchInferenceSensor.SuccessState.COMPLETED:
intermediate_states = base_intermediate_states + scheduled_state
success_states = base_success_states
self.trigger_class = BedrockBatchInferenceCompletedTrigger
elif self.success_state == BedrockBatchInferenceSensor.SuccessState.SCHEDULED:
intermediate_states = base_intermediate_states
success_states = base_success_states + scheduled_state
self.trigger_class = BedrockBatchInferenceScheduledTrigger
else:
raise ValueError(
"Success states for BedrockBatchInferenceSensor must be set using a BedrockBatchInferenceSensor.SuccessState"
)
BedrockBatchInferenceSensor.INTERMEDIATE_STATES = intermediate_states or base_intermediate_states
BedrockBatchInferenceSensor.SUCCESS_STATES = success_states or base_success_states
def get_state(self) -> str:
return self.hook.conn.get_model_invocation_job(jobIdentifier=self.job_arn)["status"]
def execute(self, context: Context) -> Any:
if self.deferrable:
self.defer(
trigger=self.trigger_class(
job_arn=self.job_arn,
waiter_delay=int(self.poke_interval),
waiter_max_attempts=self.max_retries,
aws_conn_id=self.aws_conn_id,
),
method_name="poke",
)
else:
super().execute(context=context)
|
BedrockBatchInferenceSensor
|
python
|
pandas-dev__pandas
|
pandas/io/common.py
|
{
"start": 29929,
"end": 30542
}
|
class ____(BytesIO, ABC):
"""
Some objects do not support multiple .write() calls (TarFile and ZipFile).
This wrapper writes to the underlying buffer on close.
"""
buffer = BytesIO()
@abstractmethod
def write_to_buffer(self) -> None: ...
def close(self) -> None:
if self.closed:
# already closed
return
if self.getbuffer().nbytes:
# write to buffer
self.seek(0)
with self.buffer:
self.write_to_buffer()
else:
self.buffer.close()
super().close()
|
_BufferedWriter
|
python
|
prabhupant__python-ds
|
data_structures/union_find/uf.py
|
{
"start": 131,
"end": 1916
}
|
class ____:
'''
Union-Find data structure along with required functions. Takes 'n' (integer) as input
which is the total number of nodes in the structure.
'''
def __init__ (self, n):
self.ar = [None] * n
for i in range(n):
self.ar[i] = i
self.size = [1] * n
self.n = n
def root (self, x):
'''
Function used to find root of a node "x"
Input: node number (integer between 0 and n-1)
Output: node number (integer between 0 and n-1)
'''
while self.ar[x] != x:
self.ar[x] = self.ar[self.ar[x]]
x = self.ar[x]
return x
def union (self, a, b):
'''
Function to perform union of the nodes 'a' and 'b'
Input: node number, node number (integers between 0 and n-1)
Output: none
'''
print("Union", a, "and", b)
roa = self.root(a)
rob = self.root(b)
if self.size[roa] < self.size[rob]:
self.ar[roa] = self.ar[rob]
self.size[rob] += self.size[roa]
else:
self.ar[rob] = self.ar[roa]
self.size[roa] += self.size[rob]
def find (self, a, b):
'''
Function to check if 'a' and 'b' are connected
Input: node number, node number (integers between 0 and n-1)
Output: True or False
'''
if self.root (a) == self.root (b):
return True
else:
return False
pass
if __name__ == "__main__":
uf = Union_find (6)
uf.union (1, 2)
print("2 and 3 connected?", uf.find(2, 3))
uf.union (1, 3)
uf.union (4, 5)
print("2 and 4 connected?", uf.find(2, 4))
uf.union (3, 5)
print("2 and 4 connected?", uf.find(2, 4))
|
Union_find
|
python
|
pandas-dev__pandas
|
setup.py
|
{
"start": 5388,
"end": 7780
}
|
class ____(sdist_class):
"""Custom sdist that ensures Cython has compiled all pyx files to c."""
_pyxfiles = [
"pandas/_libs/arrays.pyx",
"pandas/_libs/lib.pyx",
"pandas/_libs/hashtable.pyx",
"pandas/_libs/tslib.pyx",
"pandas/_libs/index.pyx",
"pandas/_libs/internals.pyx",
"pandas/_libs/algos.pyx",
"pandas/_libs/join.pyx",
"pandas/_libs/indexing.pyx",
"pandas/_libs/interval.pyx",
"pandas/_libs/hashing.pyx",
"pandas/_libs/missing.pyx",
"pandas/_libs/testing.pyx",
"pandas/_libs/sparse.pyx",
"pandas/_libs/ops.pyx",
"pandas/_libs/parsers.pyx",
"pandas/_libs/tslibs/base.pyx",
"pandas/_libs/tslibs/ccalendar.pyx",
"pandas/_libs/tslibs/dtypes.pyx",
"pandas/_libs/tslibs/period.pyx",
"pandas/_libs/tslibs/strptime.pyx",
"pandas/_libs/tslibs/np_datetime.pyx",
"pandas/_libs/tslibs/timedeltas.pyx",
"pandas/_libs/tslibs/timestamps.pyx",
"pandas/_libs/tslibs/timezones.pyx",
"pandas/_libs/tslibs/conversion.pyx",
"pandas/_libs/tslibs/fields.pyx",
"pandas/_libs/tslibs/offsets.pyx",
"pandas/_libs/tslibs/parsing.pyx",
"pandas/_libs/tslibs/tzconversion.pyx",
"pandas/_libs/tslibs/vectorized.pyx",
"pandas/_libs/window/indexers.pyx",
"pandas/_libs/writers.pyx",
"pandas/_libs/sas.pyx",
"pandas/_libs/byteswap.pyx",
]
_cpp_pyxfiles = [
"pandas/_libs/window/aggregations.pyx",
]
def initialize_options(self) -> None:
sdist_class.initialize_options(self)
def run(self) -> None:
if "cython" in cmdclass:
self.run_command("cython")
else:
# If we are not running cython then
# compile the extensions correctly
pyx_files = [(self._pyxfiles, "c"), (self._cpp_pyxfiles, "cpp")]
for pyxfiles, extension in pyx_files:
for pyxfile in pyxfiles:
sourcefile = pyxfile[:-3] + extension
msg = (
f"{extension}-source file '{sourcefile}' not found.\n"
"Run 'setup.py cython' before sdist."
)
assert os.path.isfile(sourcefile), msg
sdist_class.run(self)
|
CheckSDist
|
python
|
run-llama__llama_index
|
llama-index-packs/llama-index-packs-code-hierarchy/tests/test_code_hierarchy_with_skeleton.py
|
{
"start": 5312,
"end": 5682
}
|
class ____:
@bar
@barfoo
def bar() -> None:
print("bar")"""
text_node = TextNode(
text=text,
metadata={
"module": "example.foo",
},
)
chunks: List[TextNode] = code_splitter.get_nodes_from_documents([text_node])
# This is the module scope
assert (
chunks[0].text
== f"""\
@foo
|
Foo
|
python
|
crytic__slither
|
slither/detectors/shadowing/local.py
|
{
"start": 615,
"end": 6587
}
|
class ____(AbstractDetector):
"""
Local variable shadowing
"""
ARGUMENT = "shadowing-local"
HELP = "Local variables shadowing"
IMPACT = DetectorClassification.LOW
CONFIDENCE = DetectorClassification.HIGH
WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#local-variable-shadowing"
WIKI_TITLE = "Local variable shadowing"
WIKI_DESCRIPTION = "Detection of shadowing using local variables."
# region wiki_exploit_scenario
WIKI_EXPLOIT_SCENARIO = """
```solidity
pragma solidity ^0.4.24;
contract Bug {
uint owner;
function sensitive_function(address owner) public {
// ...
require(owner == msg.sender);
}
function alternate_sensitive_function() public {
address owner = msg.sender;
// ...
require(owner == msg.sender);
}
}
```
`sensitive_function.owner` shadows `Bug.owner`. As a result, the use of `owner` in `sensitive_function` might be incorrect."""
# endregion wiki_exploit_scenario
WIKI_RECOMMENDATION = "Rename the local variables that shadow another component."
OVERSHADOWED_FUNCTION = "function"
OVERSHADOWED_MODIFIER = "modifier"
OVERSHADOWED_STATE_VARIABLE = "state variable"
OVERSHADOWED_EVENT = "event"
OVERSHADOWED_RETURN_VARIABLE = "return variable"
# pylint: disable=too-many-branches
def detect_shadowing_definitions(
self, contract: Contract
) -> List[
Union[
Tuple[LocalVariable, List[Tuple[str, StateVariable]]],
Tuple[LocalVariable, List[Tuple[str, FunctionContract]]],
Tuple[LocalVariable, List[Tuple[str, Modifier]]],
Tuple[LocalVariable, List[Tuple[str, Event]]],
]
]:
"""Detects if functions, access modifiers, events, state variables, and local variables are named after
reserved keywords. Any such definitions are returned in a list.
Returns:
list of tuple: (type, contract name, definition)"""
result: List[
Union[
Tuple[LocalVariable, List[Tuple[str, StateVariable]]],
Tuple[LocalVariable, List[Tuple[str, FunctionContract]]],
Tuple[LocalVariable, List[Tuple[str, Modifier]]],
Tuple[LocalVariable, List[Tuple[str, Event]]],
]
] = []
# Loop through all functions + modifiers in this contract.
for function in contract.functions + list(contract.modifiers):
# We should only look for functions declared directly in this contract (not in a base contract).
if function.contract_declarer != contract:
continue
# This function was declared in this contract, we check what its local variables might shadow.
for variable in function.variables:
overshadowed = []
for scope_contract in [contract] + contract.inheritance:
# Check functions
for scope_function in scope_contract.functions_declared:
if variable.name == scope_function.name:
overshadowed.append((self.OVERSHADOWED_FUNCTION, scope_function))
# Check modifiers
for scope_modifier in scope_contract.modifiers_declared:
if variable.name == scope_modifier.name:
overshadowed.append((self.OVERSHADOWED_MODIFIER, scope_modifier))
# Check events
for scope_event in scope_contract.events_declared:
if variable.name == scope_event.name:
overshadowed.append((self.OVERSHADOWED_EVENT, scope_event))
# Check state variables
for scope_state_variable in scope_contract.state_variables_declared:
if variable.name == scope_state_variable.name:
overshadowed.append(
(self.OVERSHADOWED_STATE_VARIABLE, scope_state_variable)
)
# Check named return variables
for named_return in function.returns:
# Shadowed local delcarations in the same function will have "_scope_" in their name.
# See `FunctionSolc._add_local_variable`
if (
"_scope_" in variable.name
and variable.name.split("_scope_")[0] == named_return.name
):
overshadowed.append((self.OVERSHADOWED_RETURN_VARIABLE, named_return))
# If we have found any overshadowed objects, we'll want to add it to our result list.
if overshadowed:
result.append((variable, overshadowed))
return result
def _detect(self) -> List[Output]:
"""Detect shadowing local variables
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'}
"""
results = []
for contract in self.contracts:
shadows = self.detect_shadowing_definitions(contract)
if shadows:
for shadow in shadows:
local_variable = shadow[0]
overshadowed = shadow[1]
info: DETECTOR_INFO = [local_variable, " shadows:\n"]
for overshadowed_entry in overshadowed:
info += [
"\t- ",
overshadowed_entry[1],
f" ({overshadowed_entry[0]})\n",
]
# Generate relevant JSON data for this shadowing definition.
res = self.generate_result(info)
results.append(res)
return results
|
LocalShadowing
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-github/source_github/github_schema.py
|
{
"start": 1583630,
"end": 1585200
}
|
class ____(sgqlc.types.Type, UniformResourceLocatable, Node):
"""An executed workflow file for a workflow run."""
__schema__ = github_schema
__field_names__ = ("path", "repository_file_url", "repository_name", "run", "viewer_can_push_repository", "viewer_can_read_repository")
path = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="path")
"""The path of the workflow file relative to its repository."""
repository_file_url = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="repositoryFileUrl")
"""The direct link to the file in the repository which stores the
workflow file.
"""
repository_name = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name="repositoryName")
"""The repository name and owner which stores the workflow file."""
run = sgqlc.types.Field(sgqlc.types.non_null(WorkflowRun), graphql_name="run")
"""The parent workflow run execution for this file."""
viewer_can_push_repository = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="viewerCanPushRepository")
"""If the viewer has permissions to push to the repository which
stores the workflow.
"""
viewer_can_read_repository = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="viewerCanReadRepository")
"""If the viewer has permissions to read the repository which stores
the workflow.
"""
########################################################################
# Unions
########################################################################
|
WorkflowRunFile
|
python
|
html5lib__html5lib-python
|
html5lib/tests/sanitizer.py
|
{
"start": 158,
"end": 439
}
|
class ____(pytest.File):
def collect(self):
with codecs.open(str(self.fspath), "r", encoding="utf-8") as fp:
tests = json.load(fp)
for i, test in enumerate(tests):
yield SanitizerTest.from_parent(self, name=str(i), test=test)
|
SanitizerFile
|
python
|
spyder-ide__spyder
|
spyder/plugins/explorer/widgets/main_widget.py
|
{
"start": 1563,
"end": 15531
}
|
class ____(PluginMainWidget):
"""Explorer widget"""
# --- Signals
# ------------------------------------------------------------------------
sig_dir_opened = Signal(str, str)
"""
This signal is emitted to indicate a folder has been opened.
Parameters
----------
directory: str
The path to the directory opened.
server_id: str
The server identification from where the directory path is reachable.
"""
sig_module_created = Signal(str)
"""
This signal is emitted when a new python module is created.
Parameters
----------
module: str
Path to the new module created.
"""
sig_file_created = Signal(str)
"""
This signal is emitted to request creating a new file with Spyder.
Parameters
----------
path: str
File path to create.
"""
sig_open_file_requested = Signal(str)
"""
This signal is emitted to request opening a new file with Spyder.
Parameters
----------
path: str
File path to run.
"""
sig_removed = Signal(str)
"""
This signal is emitted when a file is removed.
Parameters
----------
path: str
File path removed.
"""
sig_renamed = Signal(str, str)
"""
This signal is emitted when a file is renamed.
Parameters
----------
old_path: str
Old path for renamed file.
new_path: str
New path for renamed file.
"""
sig_tree_removed = Signal(str)
"""
This signal is emitted when a folder is removed.
Parameters
----------
path: str
Folder to remove.
"""
sig_tree_renamed = Signal(str, str)
"""
This signal is emitted when a folder is renamed.
Parameters
----------
old_path: str
Old path for renamed folder.
new_path: str
New path for renamed folder.
"""
sig_run_requested = Signal(str)
"""
This signal is emitted to request running a file.
Parameters
----------
path: str
File path to run.
"""
sig_open_interpreter_requested = Signal(str)
"""
This signal is emitted to request opening an interpreter with the given
path as working directory.
Parameters
----------
path: str
Path to use as working directory of interpreter.
"""
ENABLE_SPINNER = True
def __init__(self, name, plugin, parent=None):
"""
Initialize the widget.
Parameters
----------
name: str
Name of the container.
plugin: SpyderDockablePlugin
Plugin of the container
parent: QWidget
Parent of this widget
"""
super().__init__(name, plugin=plugin, parent=parent)
# Widgets
self.stackwidget = QStackedWidget(parent=self)
self.treewidget = ExplorerTreeWidget(parent=self)
self.remote_treewidget = RemoteExplorer(parent=self)
self.stackwidget.addWidget(self.remote_treewidget)
self.stackwidget.addWidget(self.treewidget)
# Layouts
layout = QHBoxLayout()
layout.addWidget(self.stackwidget)
self.setLayout(layout)
# Signals
self.treewidget.sig_dir_opened.connect(self.sig_dir_opened)
self.remote_treewidget.sig_dir_opened.connect(self.sig_dir_opened)
self.remote_treewidget.sig_start_spinner_requested.connect(
self.start_spinner
)
self.remote_treewidget.sig_stop_spinner_requested.connect(
self.stop_spinner
)
self.treewidget.sig_file_created.connect(self.sig_file_created)
self.treewidget.sig_open_file_requested.connect(
self.sig_open_file_requested)
self.treewidget.sig_module_created.connect(self.sig_module_created)
self.treewidget.sig_open_interpreter_requested.connect(
self.sig_open_interpreter_requested)
self.treewidget.sig_renamed.connect(self.sig_renamed)
self.treewidget.sig_removed.connect(self.sig_removed)
self.treewidget.sig_run_requested.connect(self.sig_run_requested)
self.treewidget.sig_tree_removed.connect(self.sig_tree_removed)
self.treewidget.sig_tree_renamed.connect(self.sig_tree_renamed)
self.treewidget.sig_redirect_stdio_requested.connect(
self.sig_redirect_stdio_requested)
# ---- PluginMainWidget API
# ------------------------------------------------------------------------
def get_focus_widget(self):
"""Define the widget to focus."""
return self.treewidget
def get_title(self):
"""Return the title of the plugin tab."""
return _("Files")
def setup(self):
"""Perform the setup of the plugin's menu and actions."""
# Common actions
self.previous_action = self.create_action(
ExplorerWidgetActions.Previous,
text=_("Previous"),
icon=self.create_icon('previous'),
triggered=self.go_to_previous_directory,
)
self.next_action = self.create_action(
ExplorerWidgetActions.Next,
text=_("Next"),
icon=self.create_icon('next'),
triggered=self.go_to_next_directory,
)
self.parent_action = self.create_action(
ExplorerWidgetActions.Parent,
text=_("Parent"),
icon=self.create_icon('up'),
triggered=self.go_to_parent_directory
)
self.refresh_action = self.create_action(
ExplorerWidgetActions.Refresh,
text=_("Refresh"),
icon=self.create_icon('refresh'),
triggered=lambda: self.refresh(force_current=True)
)
filters_action = self.create_action(
ExplorerWidgetActions.EditNameFilters,
text=_("Edit filter settings..."),
icon=self.create_icon('filter'),
triggered=self.edit_filter,
)
# Common toolbuttons
self.filter_button = self.create_action(
ExplorerWidgetActions.ToggleFilter,
text="",
icon=ima.icon('filter'),
toggled=self.change_filter_state
)
self.filter_button.setCheckable(True)
# Set actions for tree widgets
self.treewidget.previous_action = self.previous_action
self.treewidget.next_action = self.next_action
self.treewidget.filter_button = self.filter_button
self.remote_treewidget.previous_action = self.previous_action
self.remote_treewidget.next_action = self.next_action
self.remote_treewidget.filter_button = self.filter_button
# Setup widgets
self.treewidget.setup()
self.chdir(getcwd_or_home())
# Menu
menu = self.get_options_menu()
hidden_action = self.get_action(DirViewActions.ToggleHiddenFiles)
for item in [hidden_action, filters_action]:
self.add_item_to_menu(
item,
menu=menu,
section=ExplorerWidgetOptionsMenuSections.Common,
)
# Header actions
size_column_action = self.get_action(DirViewActions.ToggleSizeColumn)
type_column_action = self.get_action(DirViewActions.ToggleTypeColumn)
date_column_action = self.get_action(DirViewActions.ToggleDateColumn)
for item in [
size_column_action,
type_column_action,
date_column_action,
]:
self.add_item_to_menu(
item,
menu=menu,
section=ExplorerWidgetOptionsMenuSections.Header,
)
single_click_action = self.get_action(DirViewActions.ToggleSingleClick)
self.add_item_to_menu(
single_click_action,
menu=menu, section=ExplorerWidgetOptionsMenuSections.Files)
# Toolbar
toolbar = self.get_main_toolbar()
for item in [
self.previous_action,
self.next_action,
self.parent_action,
]:
self.add_item_to_toolbar(
item,
toolbar=toolbar,
section=ExplorerWidgetMainToolbarSections.Main,
)
for action in [
self.remote_treewidget.upload_file_action,
self.refresh_action,
self.filter_button,
]:
self.add_corner_widget(action, before=self._options_button)
def update_actions(self):
"""Handle the update of actions of the plugin."""
visible_remote_actions = (
self.get_current_widget() == self.remote_treewidget
)
self.refresh_action.setVisible(visible_remote_actions)
self.remote_treewidget.upload_file_action.setVisible(
visible_remote_actions
)
# ---- Public API
# ------------------------------------------------------------------------
def chdir(self, directory, emit=True, server_id=None):
"""
Set working directory.
Parameters
----------
directory: str
Directory to set as working directory.
emit: bool, optional
Default is True.
server_id: str, optional
The server identification from where the directory is reachable.
Default is None.
"""
if not server_id:
self.treewidget.chdir(directory, emit=emit)
self.stackwidget.setCurrentWidget(self.treewidget)
else:
self.start_spinner()
logger.debug(f"Request ls for {server_id} at {directory}")
@AsyncDispatcher.QtSlot
def remote_ls(future):
self.remote_treewidget.chdir(
directory,
server_id=server_id,
emit=emit,
remote_files_manager=future.result()
)
self._plugin._get_remote_files_manager(server_id).connect(
remote_ls
)
self.stackwidget.setCurrentWidget(self.remote_treewidget)
self.update_actions()
def get_current_folder(self):
"""Get current folder in the tree widget."""
return self.stackwidget.currentWidget().get_current_folder()
def set_current_folder(self, folder):
"""
Set the current folder in the tree widget.
Parameters
----------
folder: str
Folder path to set as current folder.
"""
self.get_current_widget().set_current_folder(folder)
def go_to_parent_directory(self):
"""Move to parent directory."""
self.get_current_widget().go_to_parent_directory()
def go_to_previous_directory(self):
"""Move to previous directory in history."""
self.get_current_widget().go_to_previous_directory()
def go_to_next_directory(self):
"""Move to next directory in history."""
self.get_current_widget().go_to_next_directory()
def refresh(self, new_path=None, force_current=False):
"""
Refresh history.
Parameters
----------
new_path: str, optional
Path to add to history. Default is None.
force_current: bool, optional
Default is True.
"""
self.get_current_widget().refresh(new_path, force_current)
def get_current_widget(self):
"""Get the current widget in stackwidget."""
return self.stackwidget.currentWidget()
@Slot()
def edit_filter(self):
"""Edit name filters."""
# Create Dialog
dialog = QDialog(self)
dialog.resize(500, 300)
dialog.setWindowTitle(_('Edit filter settings'))
# Create dialog contents
description_label = QLabel(
_(
"Filter files by name, extension, or more using "
'<a href="https://en.wikipedia.org/wiki/Glob_(programming)">'
"glob patterns.</a> Please enter the glob patterns of the "
"files you want to show, separated by commas."
)
)
description_label.setOpenExternalLinks(True)
description_label.setWordWrap(True)
filters = QTextEdit(
", ".join(self.get_conf('name_filters')),
parent=self
)
layout = QVBoxLayout()
layout.addWidget(description_label)
layout.addWidget(filters)
def handle_ok():
filter_text = filters.toPlainText()
filter_text = [f.strip() for f in str(filter_text).split(',')]
self.get_current_widget().set_name_filters(filter_text)
dialog.accept()
def handle_reset():
self.get_current_widget().set_name_filters(NAME_FILTERS)
filters.setPlainText(", ".join(self.get_conf('name_filters')))
# Dialog buttons
button_box = SpyderDialogButtonBox(
QDialogButtonBox.Reset
| QDialogButtonBox.Ok
| QDialogButtonBox.Cancel
)
button_box.accepted.connect(handle_ok)
button_box.rejected.connect(dialog.reject)
button_box.button(QDialogButtonBox.Reset).clicked.connect(handle_reset)
layout.addWidget(button_box)
dialog.setLayout(layout)
dialog.show()
def change_filter_state(self):
self.stackwidget.currentWidget().change_filter_state()
def update_history(self, directory):
"""
Update history with directory.
Parameters
----------
directory: str
Path to add to history.
"""
self.treewidget.update_history(directory)
def reset_remote_treewidget(self, server_id):
self.remote_treewidget.reset(server_id)
# =============================================================================
# Tests
# =============================================================================
|
ExplorerWidget
|
python
|
ray-project__ray
|
python/ray/tests/chaos/streaming_llm.py
|
{
"start": 1039,
"end": 2842
}
|
class ____:
def __init__(self, llm):
self.llm = llm.options(stream=True)
@fastapi_app.post("/")
async def handle_request(self, prompt: str) -> StreamingResponse:
logger.info(f'Got prompt with size "{len(prompt)}"')
return StreamingResponse(self.llm.remote(prompt), media_type="text/plain")
@ray.remote(num_cpus=0.1, memory=10 * 1024 * 1024)
def make_http_query(num_words, num_queries):
for _ in range(num_queries):
words = "Lorem ipsum dolor sit amet".split()
prompt_words = [words[i % len(words)] for i in range(num_words)]
prompt = " ".join(prompt_words)
expected_words = [word[::-1] for word in prompt_words for _ in range(2)]
response = requests.post(f"http://localhost:8000/?prompt={prompt}", stream=True)
response.raise_for_status()
content = response.content.decode()
assert content == " ".join(expected_words) + " ", content
def main():
parser = argparse.ArgumentParser(description="Generates HTTP workloads with Ray.")
parser.add_argument("--num_tasks", type=int, required=True, help="Number of tasks.")
parser.add_argument(
"--num_queries_per_task",
type=int,
required=True,
help="Number of queries per task.",
)
parser.add_argument(
"--num_words_per_query",
type=int,
required=True,
help="Number of words per query",
)
args = parser.parse_args()
# Run the serve, run the client, then showdown serve.
llm = ReverseAndDupEachWord.bind(2)
app = Textbot.bind(llm)
serve.run(app)
objs = [
make_http_query.remote(args.num_words_per_query, args.num_queries_per_task)
for _ in range(args.num_tasks)
]
ray.get(objs)
serve.shutdown()
main()
|
Textbot
|
python
|
run-llama__llama_index
|
llama-index-core/llama_index/core/schema.py
|
{
"start": 32455,
"end": 40435
}
|
class ____(Node):
"""
Generic interface for a data document.
This document connects to data sources.
"""
def __init__(self, **data: Any) -> None:
"""
Keeps backward compatibility with old 'Document' versions.
If 'text' was passed, store it in 'text_resource'.
If 'doc_id' was passed, store it in 'id_'.
If 'extra_info' was passed, store it in 'metadata'.
"""
if "doc_id" in data:
value = data.pop("doc_id")
if "id_" in data:
msg = "'doc_id' is deprecated and 'id_' will be used instead"
logging.warning(msg)
else:
data["id_"] = value
if "extra_info" in data:
value = data.pop("extra_info")
if "metadata" in data:
msg = "'extra_info' is deprecated and 'metadata' will be used instead"
logging.warning(msg)
else:
data["metadata"] = value
if data.get("text"):
text = data.pop("text")
if "text_resource" in data:
text_resource = (
data["text_resource"]
if isinstance(data["text_resource"], MediaResource)
else MediaResource.model_validate(data["text_resource"])
)
if (text_resource.text or "").strip() != text.strip():
msg = (
"'text' is deprecated and 'text_resource' will be used instead"
)
logging.warning(msg)
else:
data["text_resource"] = MediaResource(text=text)
super().__init__(**data)
@model_serializer(mode="wrap")
def custom_model_dump(
self, handler: SerializerFunctionWrapHandler, info: SerializationInfo
) -> Dict[str, Any]:
"""For full backward compatibility with the text field, we customize the model serializer."""
data = super().custom_model_dump(handler, info)
exclude_set = set(info.exclude or [])
if "text" not in exclude_set:
data["text"] = self.text
return data
@property
def text(self) -> str:
"""Provided for backward compatibility, it returns the content of text_resource."""
return self.get_content()
@classmethod
def get_type(cls) -> str:
"""Get Document type."""
return ObjectType.DOCUMENT
@property
def doc_id(self) -> str:
"""Get document ID."""
return self.id_
@doc_id.setter
def doc_id(self, id_: str) -> None:
self.id_ = id_
def __str__(self) -> str:
source_text_truncated = truncate_text(
self.get_content().strip(), TRUNCATE_LENGTH
)
source_text_wrapped = textwrap.fill(
f"Text: {source_text_truncated}\n", width=WRAP_WIDTH
)
return f"Doc ID: {self.doc_id}\n{source_text_wrapped}"
@deprecated(
version="0.12.2",
reason="'get_doc_id' is deprecated, access the 'id_' property instead.",
)
def get_doc_id(self) -> str: # pragma: nocover
return self.id_
def to_langchain_format(self) -> LCDocument:
"""Convert struct to LangChain document format."""
from llama_index.core.bridge.langchain import (
Document as LCDocument, # type: ignore
)
metadata = self.metadata or {}
return LCDocument(page_content=self.text, metadata=metadata, id=self.id_)
@classmethod
def from_langchain_format(cls, doc: LCDocument) -> Document:
"""Convert struct from LangChain document format."""
if doc.id:
return cls(text=doc.page_content, metadata=doc.metadata, id_=doc.id)
return cls(text=doc.page_content, metadata=doc.metadata)
def to_haystack_format(self) -> HaystackDocument:
"""Convert struct to Haystack document format."""
from haystack import Document as HaystackDocument # type: ignore
return HaystackDocument(
content=self.text, meta=self.metadata, embedding=self.embedding, id=self.id_
)
@classmethod
def from_haystack_format(cls, doc: HaystackDocument) -> Document:
"""Convert struct from Haystack document format."""
return cls(
text=doc.content, metadata=doc.meta, embedding=doc.embedding, id_=doc.id
)
def to_embedchain_format(self) -> Dict[str, Any]:
"""Convert struct to EmbedChain document format."""
return {
"doc_id": self.id_,
"data": {"content": self.text, "meta_data": self.metadata},
}
@classmethod
def from_embedchain_format(cls, doc: Dict[str, Any]) -> Document:
"""Convert struct from EmbedChain document format."""
return cls(
text=doc["data"]["content"],
metadata=doc["data"]["meta_data"],
id_=doc["doc_id"],
)
def to_semantic_kernel_format(self) -> MemoryRecord:
"""Convert struct to Semantic Kernel document format."""
import numpy as np
from semantic_kernel.memory.memory_record import MemoryRecord # type: ignore
return MemoryRecord(
id=self.id_,
text=self.text,
additional_metadata=self.get_metadata_str(),
embedding=np.array(self.embedding) if self.embedding else None,
)
@classmethod
def from_semantic_kernel_format(cls, doc: MemoryRecord) -> Document:
"""Convert struct from Semantic Kernel document format."""
return cls(
text=doc._text,
metadata={"additional_metadata": doc._additional_metadata},
embedding=doc._embedding.tolist() if doc._embedding is not None else None,
id_=doc._id,
)
def to_vectorflow(self, client: Any) -> None:
"""Send a document to vectorflow, since they don't have a document object."""
# write document to temp file
import tempfile
with tempfile.NamedTemporaryFile() as f:
f.write(self.text.encode("utf-8"))
f.flush()
client.embed(f.name)
@classmethod
def example(cls) -> Document:
return Document(
text=SAMPLE_TEXT,
metadata={"filename": "README.md", "category": "codebase"},
)
@classmethod
def class_name(cls) -> str:
return "Document"
def to_cloud_document(self) -> CloudDocument:
"""Convert to LlamaCloud document type."""
from llama_cloud.types.cloud_document import CloudDocument # type: ignore
return CloudDocument(
text=self.text,
metadata=self.metadata,
excluded_embed_metadata_keys=self.excluded_embed_metadata_keys,
excluded_llm_metadata_keys=self.excluded_llm_metadata_keys,
id=self.id_,
)
@classmethod
def from_cloud_document(
cls,
doc: CloudDocument,
) -> Document:
"""Convert from LlamaCloud document type."""
return Document(
text=doc.text,
metadata=doc.metadata,
excluded_embed_metadata_keys=doc.excluded_embed_metadata_keys,
excluded_llm_metadata_keys=doc.excluded_llm_metadata_keys,
id_=doc.id,
)
def is_image_pil(file_path: str) -> bool:
try:
with Image.open(file_path) as img:
img.verify() # Verify it's a valid image
return True
except (IOError, SyntaxError):
return False
def is_image_url_pil(url: str) -> bool:
try:
response = requests.get(url, stream=True, timeout=(60, 60))
response.raise_for_status() # Raise an exception for bad status codes
# Open image from the response content
img = Image.open(BytesIO(response.content))
img.verify()
return True
except (requests.RequestException, IOError, SyntaxError):
return False
|
Document
|
python
|
bokeh__bokeh
|
src/bokeh/application/handlers/document_lifecycle.py
|
{
"start": 1446,
"end": 2953
}
|
class ____(LifecycleHandler):
''' Calls on_session_destroyed callbacks defined on the Document.
'''
def __init__(self) -> None:
super().__init__()
self._on_session_destroyed = _on_session_destroyed
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
def _on_session_destroyed(session_context: SessionContext) -> None:
'''
Calls any on_session_destroyed callbacks defined on the Document
'''
callbacks = session_context._document.session_destroyed_callbacks
session_context._document.session_destroyed_callbacks = set()
for callback in callbacks:
try:
callback(session_context)
except Exception as e:
log.warning("DocumentLifeCycleHandler on_session_destroyed "
f"callback {callback} failed with following error: {e}")
if callbacks:
# If any session callbacks were defined garbage collect after deleting all references
del callback
del callbacks
import gc
gc.collect()
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
|
DocumentLifecycleHandler
|
python
|
py-pdf__pypdf
|
pypdf/papersizes.py
|
{
"start": 66,
"end": 129
}
|
class ____(NamedTuple):
width: int
height: int
|
Dimensions
|
python
|
pypa__virtualenv
|
src/virtualenv/create/via_global_ref/api.py
|
{
"start": 685,
"end": 4523
}
|
class ____(Creator, ABC):
def __init__(self, options, interpreter) -> None:
super().__init__(options, interpreter)
self.symlinks = self._should_symlink(options)
self.enable_system_site_package = options.system_site
@staticmethod
def _should_symlink(options):
# Priority of where the option is set to follow the order: CLI, env var, file, hardcoded.
# If both set at same level prefers copy over symlink.
copies, symlinks = getattr(options, "copies", False), getattr(options, "symlinks", False)
copy_src, sym_src = options.get_source("copies"), options.get_source("symlinks")
for level in ["cli", "env var", "file", "default"]:
s_opt = symlinks if sym_src == level else None
c_opt = copies if copy_src == level else None
if s_opt is True and c_opt is True:
return False
if s_opt is True:
return True
if c_opt is True:
return False
return False # fallback to copy
@classmethod
def add_parser_arguments(cls, parser, interpreter, meta, app_data):
super().add_parser_arguments(parser, interpreter, meta, app_data)
parser.add_argument(
"--system-site-packages",
default=False,
action="store_true",
dest="system_site",
help="give the virtual environment access to the system site-packages dir",
)
if not meta.can_symlink and not meta.can_copy:
errors = []
if meta.symlink_error:
errors.append(f"symlink: {meta.symlink_error}")
if meta.copy_error:
errors.append(f"copy: {meta.copy_error}")
msg = f"neither symlink or copy method supported: {', '.join(errors)}"
raise RuntimeError(msg)
group = parser.add_mutually_exclusive_group()
if meta.can_symlink:
group.add_argument(
"--symlinks",
default=True,
action="store_true",
dest="symlinks",
help="try to use symlinks rather than copies, when symlinks are not the default for the platform",
)
if meta.can_copy:
group.add_argument(
"--copies",
"--always-copy",
default=not meta.can_symlink,
action="store_true",
dest="copies",
help="try to use copies rather than symlinks, even when symlinks are the default for the platform",
)
def create(self):
self.install_patch()
def install_patch(self):
text = self.env_patch_text()
if text:
pth = self.purelib / "_virtualenv.pth"
LOGGER.debug("create virtualenv import hook file %s", pth)
pth.write_text("import _virtualenv", encoding="utf-8")
dest_path = self.purelib / "_virtualenv.py"
LOGGER.debug("create %s", dest_path)
dest_path.write_text(text, encoding="utf-8")
def env_patch_text(self):
"""Patch the distutils package to not be derailed by its configuration files."""
with self.app_data.ensure_extracted(Path(__file__).parent / "_virtualenv.py") as resolved_path:
text = resolved_path.read_text(encoding="utf-8")
return text.replace('"__SCRIPT_DIR__"', repr(os.path.relpath(str(self.script_dir), str(self.purelib))))
def _args(self):
return [*super()._args(), ("global", self.enable_system_site_package)]
def set_pyenv_cfg(self):
super().set_pyenv_cfg()
self.pyenv_cfg["include-system-site-packages"] = "true" if self.enable_system_site_package else "false"
__all__ = [
"ViaGlobalRefApi",
"ViaGlobalRefMeta",
]
|
ViaGlobalRefApi
|
python
|
python-poetry__poetry
|
src/poetry/mixology/version_solver.py
|
{
"start": 1486,
"end": 5060
}
|
class ____:
"""
A cache of the valid dependencies.
The key observation here is that during the search - except at backtracking
- once we have decided that a dependency is invalid, we never need check it
again.
"""
def __init__(self, provider: Provider) -> None:
self._provider = provider
# self._cache maps a package name to a stack of cached package lists,
# ordered by the decision level which added them to the cache. This is
# done so that when backtracking we can maintain cache entries from
# previous decision levels, while clearing cache entries from only the
# rolled back levels.
#
# In order to maintain the integrity of the cache, `clear_level()`
# needs to be called in descending order as decision levels are
# backtracked so that the correct items can be popped from the stack.
self._cache: dict[DependencyCacheKey, list[list[DependencyPackage]]] = (
collections.defaultdict(list)
)
self._cached_dependencies_by_level: dict[int, list[DependencyCacheKey]] = (
collections.defaultdict(list)
)
self._search_for_cached = functools.lru_cache(maxsize=128)(self._search_for)
def _search_for(
self,
dependency: Dependency,
key: DependencyCacheKey,
) -> list[DependencyPackage]:
cache_entries = self._cache[key]
if cache_entries:
packages = [
p
for p in cache_entries[-1]
if dependency.constraint.allows(p.package.version)
]
else:
packages = None
# provider.search_for() normally does not include pre-release packages
# (unless requested), but will include them if there are no other
# eligible package versions for a version constraint.
#
# Therefore, if the eligible versions have been filtered down to
# nothing, we need to call provider.search_for() again as it may return
# additional results this time.
if not packages:
packages = self._provider.search_for(dependency)
return packages
def search_for(
self,
dependency: Dependency,
decision_level: int,
) -> list[DependencyPackage]:
key = (
dependency.name,
dependency.source_type,
dependency.source_url,
dependency.source_reference,
dependency.source_subdirectory,
)
# We could always use dependency.without_features() here,
# but for performance reasons we only do it if necessary.
packages = self._search_for_cached(
dependency.without_features() if dependency.features else dependency, key
)
if not self._cache[key] or self._cache[key][-1] is not packages:
self._cache[key].append(packages)
self._cached_dependencies_by_level[decision_level].append(key)
if dependency.features and packages:
# Use the cached dependency so that a possible explicit source is set.
return PackageCollection(
packages[0].dependency.with_features(dependency.features), packages
)
return packages
def clear_level(self, level: int) -> None:
if level in self._cached_dependencies_by_level:
self._search_for_cached.cache_clear()
for key in self._cached_dependencies_by_level.pop(level):
self._cache[key].pop()
|
DependencyCache
|
python
|
sympy__sympy
|
sympy/matrices/expressions/matexpr.py
|
{
"start": 18717,
"end": 20833
}
|
class ____(Expr):
parent = property(lambda self: self.args[0])
i = property(lambda self: self.args[1])
j = property(lambda self: self.args[2])
_diff_wrt = True
is_symbol = True
is_commutative = True
def __new__(cls, name, n, m):
n, m = map(_sympify, (n, m))
if isinstance(name, str):
name = Symbol(name)
else:
if isinstance(name, MatrixBase):
if n.is_Integer and m.is_Integer:
return name[n, m]
name = _sympify(name) # change mutable into immutable
else:
name = _sympify(name)
if not isinstance(name.kind, MatrixKind):
raise TypeError("First argument of MatrixElement should be a matrix")
if not getattr(name, 'valid_index', lambda n, m: True)(n, m):
raise IndexError('indices out of range')
obj = Expr.__new__(cls, name, n, m)
return obj
@property
def symbol(self):
return self.args[0]
def doit(self, **hints):
deep = hints.get('deep', True)
if deep:
args = [arg.doit(**hints) for arg in self.args]
else:
args = self.args
return args[0][args[1], args[2]]
@property
def indices(self):
return self.args[1:]
def _eval_derivative(self, v):
if not isinstance(v, MatrixElement):
return self.parent.diff(v)[self.i, self.j]
M = self.args[0]
m, n = self.parent.shape
if M == v.args[0]:
return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \
KroneckerDelta(self.args[2], v.args[2], (0, n-1))
if isinstance(M, Inverse):
from sympy.concrete.summations import Sum
i, j = self.args[1:]
i1, i2 = symbols("z1, z2", cls=Dummy)
Y = M.args[0]
r1, r2 = Y.shape
return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1))
if self.has(v.args[0]):
return None
return S.Zero
|
MatrixElement
|
python
|
pypa__pip
|
tests/functional/test_install_reqs.py
|
{
"start": 29861,
"end": 31654
}
|
class ____:
def test_install_local_project(
self, script: PipTestEnvironment, data: TestData, common_wheels: Path
) -> None:
uri = (data.src / "simplewheel-2.0").as_uri()
script.pip(
"install", "--no-index", "-e", f"simplewheel @ {uri}", "-f", common_wheels
)
script.assert_installed(simplewheel="2.0")
def test_install_local_project_with_extra(
self, script: PipTestEnvironment, data: TestData, common_wheels: Path
) -> None:
uri = (data.src / "requires_simple_extra").as_uri()
script.pip(
"install",
"--no-index",
"-e",
f"requires-simple-extra[extra] @ {uri}",
"-f",
common_wheels,
"-f",
data.packages,
)
script.assert_installed(requires_simple_extra="0.1")
script.assert_installed(simple="1.0")
def test_install_local_git_repo(
self, script: PipTestEnvironment, common_wheels: Path
) -> None:
repo_path = _create_test_package(script.scratch_path, "simple")
url = "git+" + repo_path.as_uri()
script.pip(
"install", "--no-index", "-e", f"simple @ {url}", "-f", common_wheels
)
script.assert_installed(simple="0.1")
@pytest.mark.network
def test_install_remote_git_repo_with_extra(
self, script: PipTestEnvironment, data: TestData, common_wheels: Path
) -> None:
req = "pip-test-package[extra] @ git+https://github.com/pypa/pip-test-package"
script.pip(
"install", "--no-index", "-e", req, "-f", common_wheels, "-f", data.packages
)
script.assert_installed(pip_test_package="0.1.1")
script.assert_installed(simple="3.0")
|
TestEditableDirectURL
|
python
|
astropy__astropy
|
astropy/io/votable/converters.py
|
{
"start": 17278,
"end": 17843
}
|
class ____(VarArray):
"""
Handles a variable-length array of numeric scalars.
"""
def parse(self, value, config=None, pos=None):
if value.strip() == "":
return ma.array([]), False
parts = self._splitter(value, config, pos)
parse = self._base.parse
result = []
result_mask = []
for x in parts:
value, mask = parse(x, config, pos)
result.append(value)
result_mask.append(mask)
return _make_masked_array(result, result_mask), False
|
ScalarVarArray
|
python
|
realpython__materials
|
python-inherit-list-userlist/number_list2.py
|
{
"start": 35,
"end": 843
}
|
class ____(UserList):
def __init__(self, iterable):
super().__init__(self._validate_number(item) for item in iterable)
def __setitem__(self, index, item):
self.data[index] = self._validate_number(item)
def insert(self, index, item):
self.data.insert(index, self._validate_number(item))
def append(self, item):
self.data.append(self._validate_number(item))
def extend(self, other):
if isinstance(other, type(self)):
self.data.extend(other)
else:
self.data.extend(self._validate_number(item) for item in other)
def _validate_number(self, value):
if isinstance(value, (int, float, complex)):
return value
raise TypeError(f"numeric value expected, got {type(value).__name__}")
|
NumberList
|
python
|
openai__openai-python
|
src/openai/types/evals/create_eval_completions_run_data_source_param.py
|
{
"start": 4607,
"end": 4974
}
|
class ____(TypedDict, total=False):
template: Required[Iterable[InputMessagesTemplateTemplate]]
"""A list of chat messages forming the prompt or context.
May include variable references to the `item` namespace, ie {{item.name}}.
"""
type: Required[Literal["template"]]
"""The type of input messages. Always `template`."""
|
InputMessagesTemplate
|
python
|
getsentry__sentry
|
tests/snuba/api/endpoints/test_organization_events_stats.py
|
{
"start": 1099,
"end": 44713
}
|
class ____(APITestCase, SnubaTestCase, SearchIssueTestMixin):
endpoint = "sentry-api-0-organization-events-stats"
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.authed_user = self.user
self.day_ago = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
self.project = self.create_project()
self.project2 = self.create_project()
self.user = self.create_user()
self.user2 = self.create_user()
self.store_event(
data={
"event_id": "a" * 32,
"message": "very bad",
"timestamp": (self.day_ago + timedelta(minutes=1)).isoformat(),
"fingerprint": ["group1"],
"tags": {"sentry:user": self.user.email},
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"message": "oh my",
"timestamp": (self.day_ago + timedelta(hours=1, minutes=1)).isoformat(),
"fingerprint": ["group2"],
"tags": {"sentry:user": self.user2.email},
},
project_id=self.project2.id,
)
self.store_event(
data={
"event_id": "c" * 32,
"message": "very bad",
"timestamp": (self.day_ago + timedelta(hours=1, minutes=2)).isoformat(),
"fingerprint": ["group2"],
"tags": {"sentry:user": self.user2.email},
},
project_id=self.project2.id,
)
self.url = reverse(
"sentry-api-0-organization-events-stats",
kwargs={"organization_id_or_slug": self.project.organization.slug},
)
self.features: dict[str, bool] = {}
def do_request(self, data, url=None, features=None):
if features is None:
features = {"organizations:discover-basic": True}
features.update(self.features)
with self.feature(features):
return self.client.get(self.url if url is None else url, data=data, format="json")
@pytest.mark.querybuilder
def test_simple(self) -> None:
response = self.do_request(
{
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 2}]]
def test_generic_issue(self) -> None:
_, _, group_info = self.store_search_issue(
self.project.id,
self.user.id,
[f"{ProfileFileIOGroupType.type_id}-group1"],
"prod",
self.day_ago,
)
assert group_info is not None
self.store_search_issue(
self.project.id,
self.user.id,
[f"{ProfileFileIOGroupType.type_id}-group1"],
"prod",
self.day_ago + timedelta(hours=1, minutes=1),
)
self.store_search_issue(
self.project.id,
self.user.id,
[f"{ProfileFileIOGroupType.type_id}-group1"],
"prod",
self.day_ago + timedelta(hours=1, minutes=2),
)
with self.feature(
[
"organizations:profiling",
]
):
response = self.do_request(
{
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"query": f"issue:{group_info.group.qualified_short_id}",
"dataset": "issuePlatform",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 2}]]
def test_generic_issue_calculated_interval(self) -> None:
"""Test that a 4h interval returns the correct generic event stats.
This follows a different code path than 1h or 1d as the IssuePlatformTimeSeriesQueryBuilder
does some calculation to create the time column."""
_, _, group_info = self.store_search_issue(
self.project.id,
self.user.id,
[f"{ProfileFileIOGroupType.type_id}-group1"],
"prod",
self.day_ago + timedelta(minutes=1),
)
assert group_info is not None
self.store_search_issue(
self.project.id,
self.user.id,
[f"{ProfileFileIOGroupType.type_id}-group1"],
"prod",
self.day_ago + timedelta(minutes=1),
)
self.store_search_issue(
self.project.id,
self.user.id,
[f"{ProfileFileIOGroupType.type_id}-group1"],
"prod",
self.day_ago + timedelta(minutes=2),
)
with self.feature(
[
"organizations:profiling",
]
):
response = self.do_request(
{
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=4),
"interval": "4h",
"query": f"issue:{group_info.group.qualified_short_id}",
"dataset": "issuePlatform",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [[{"count": 3}], [{"count": 0}]]
def test_errors_dataset(self) -> None:
response = self.do_request(
{
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"dataset": "errors",
"query": "is:unresolved",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 2}]]
def test_errors_dataset_no_query(self) -> None:
response = self.do_request(
{
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"dataset": "errors",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 2}]]
def test_misaligned_last_bucket(self) -> None:
response = self.do_request(
data={
"start": self.day_ago - timedelta(minutes=30),
"end": self.day_ago + timedelta(hours=1, minutes=30),
"interval": "1h",
"partial": "1",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [
[{"count": 0}],
[{"count": 1}],
[{"count": 2}],
]
def test_no_projects(self) -> None:
org = self.create_organization(owner=self.user)
self.login_as(user=self.user)
url = reverse(
"sentry-api-0-organization-events-stats", kwargs={"organization_id_or_slug": org.slug}
)
response = self.do_request({}, url)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
def test_user_count(self) -> None:
self.store_event(
data={
"event_id": "d" * 32,
"message": "something",
"timestamp": (self.day_ago + timedelta(minutes=2)).isoformat(),
"tags": {"sentry:user": self.user2.email},
"fingerprint": ["group2"],
},
project_id=self.project2.id,
)
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "user_count",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [[{"count": 2}], [{"count": 1}]]
def test_discover2_backwards_compatibility(self) -> None:
response = self.do_request(
data={
"project": self.project.id,
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "user_count",
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) > 0
response = self.do_request(
data={
"project": self.project.id,
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "event_count",
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) > 0
def test_with_event_count_flag(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "event_count",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 2}]]
def test_performance_view_feature(self) -> None:
response = self.do_request(
data={
"end": before_now(),
"start": before_now(hours=2),
"query": "project_id:1",
"interval": "30m",
"yAxis": "count()",
},
features={
"organizations:performance-view": True,
"organizations:discover-basic": False,
},
)
assert response.status_code == 200, response.content
def test_apdex_divide_by_zero(self) -> None:
ProjectTransactionThreshold.objects.create(
project=self.project,
organization=self.project.organization,
threshold=600,
metric=TransactionMetric.LCP.value,
)
# Shouldn't count towards apdex
data = load_data(
"transaction",
start_timestamp=self.day_ago + timedelta(minutes=(1)),
timestamp=self.day_ago + timedelta(minutes=(3)),
)
data["transaction"] = "/apdex/new/"
data["user"] = {"email": "1@example.com"}
data["measurements"] = {}
self.store_event(data, project_id=self.project.id)
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "apdex()",
"project": [self.project.id],
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
data = response.data["data"]
# 0 transactions with LCP 0/0
assert [attrs for time, attrs in response.data["data"]] == [
[{"count": 0}],
[{"count": 0}],
]
def test_aggregate_function_apdex(self) -> None:
project1 = self.create_project()
project2 = self.create_project()
events = [
("one", 400, project1.id),
("one", 400, project1.id),
("two", 3000, project2.id),
("two", 1000, project2.id),
("three", 3000, project2.id),
]
for idx, event in enumerate(events):
data = load_data(
"transaction",
start_timestamp=self.day_ago + timedelta(minutes=(1 + idx)),
timestamp=self.day_ago + timedelta(minutes=(1 + idx), milliseconds=event[1]),
)
data["event_id"] = f"{idx}" * 32
data["transaction"] = f"/apdex/new/{event[0]}"
data["user"] = {"email": f"{idx}@example.com"}
self.store_event(data, project_id=event[2])
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "apdex()",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [
[{"count": 0.3}],
[{"count": 0}],
]
ProjectTransactionThreshold.objects.create(
project=project1,
organization=project1.organization,
threshold=100,
metric=TransactionMetric.DURATION.value,
)
ProjectTransactionThreshold.objects.create(
project=project2,
organization=project1.organization,
threshold=100,
metric=TransactionMetric.DURATION.value,
)
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "apdex()",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [
[{"count": 0.2}],
[{"count": 0}],
]
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": ["user_count", "apdex()"],
},
)
assert response.status_code == 200, response.content
assert response.data["user_count"]["order"] == 0
assert [attrs for time, attrs in response.data["user_count"]["data"]] == [
[{"count": 5}],
[{"count": 0}],
]
assert response.data["apdex()"]["order"] == 1
assert [attrs for time, attrs in response.data["apdex()"]["data"]] == [
[{"count": 0.2}],
[{"count": 0}],
]
def test_aggregate_function_count(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "count()",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 2}]]
def test_invalid_aggregate(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "rubbish",
},
)
assert response.status_code == 400, response.content
def test_aggregate_function_user_count(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "count_unique(user)",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [[{"count": 1}], [{"count": 1}]]
def test_aggregate_invalid(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": "nope(lol)",
},
)
assert response.status_code == 400, response.content
def test_throughput_meta(self) -> None:
project = self.create_project()
# Each of these denotes how many events to create in each hour
event_counts = [6, 0, 6, 3, 0, 3]
for hour, count in enumerate(event_counts):
for minute in range(count):
self.store_event(
data={
"event_id": str(uuid.uuid1()),
"message": "very bad",
"timestamp": (
self.day_ago + timedelta(hours=hour, minutes=minute)
).isoformat(),
"fingerprint": ["group1"],
"tags": {"sentry:user": self.user.email},
},
project_id=project.id,
)
for axis in ["epm()", "tpm()"]:
response = self.do_request(
data={
"transformAliasToInputFormat": 1,
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": axis,
"project": project.id,
},
)
meta = response.data["meta"]
assert meta["fields"] == {
"time": "date",
axis: "rate",
}
assert meta["units"] == {"time": None, axis: "1/minute"}
data = response.data["data"]
assert len(data) == 6
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0] / (3600.0 / 60.0)
for axis in ["eps()", "tps()"]:
response = self.do_request(
data={
"transformAliasToInputFormat": 1,
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": axis,
"project": project.id,
},
)
meta = response.data["meta"]
assert meta["fields"] == {
"time": "date",
axis: "rate",
}
assert meta["units"] == {"time": None, axis: "1/second"}
def test_throughput_epm_hour_rollup(self) -> None:
project = self.create_project()
# Each of these denotes how many events to create in each hour
event_counts = [6, 0, 6, 3, 0, 3]
for hour, count in enumerate(event_counts):
for minute in range(count):
self.store_event(
data={
"event_id": str(uuid.uuid1()),
"message": "very bad",
"timestamp": (
self.day_ago + timedelta(hours=hour, minutes=minute)
).isoformat(),
"fingerprint": ["group1"],
"tags": {"sentry:user": self.user.email},
},
project_id=project.id,
)
for axis in ["epm()", "tpm()"]:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=6),
"interval": "1h",
"yAxis": axis,
"project": project.id,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0] / (3600.0 / 60.0)
def test_throughput_epm_day_rollup(self) -> None:
project = self.create_project()
# Each of these denotes how many events to create in each minute
event_counts = [6, 0, 6, 3, 0, 3]
for hour, count in enumerate(event_counts):
for minute in range(count):
self.store_event(
data={
"event_id": str(uuid.uuid1()),
"message": "very bad",
"timestamp": (
self.day_ago + timedelta(hours=hour, minutes=minute)
).isoformat(),
"fingerprint": ["group1"],
"tags": {"sentry:user": self.user.email},
},
project_id=project.id,
)
for axis in ["epm()", "tpm()"]:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=24),
"interval": "24h",
"yAxis": axis,
"project": project.id,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
assert data[0][1][0]["count"] == sum(event_counts) / (86400.0 / 60.0)
def test_throughput_eps_minute_rollup(self) -> None:
project = self.create_project()
# Each of these denotes how many events to create in each minute
event_counts = [6, 0, 6, 3, 0, 3]
for minute, count in enumerate(event_counts):
for second in range(count):
self.store_event(
data={
"event_id": str(uuid.uuid1()),
"message": "very bad",
"timestamp": (
self.day_ago + timedelta(minutes=minute, seconds=second)
).isoformat(),
"fingerprint": ["group1"],
"tags": {"sentry:user": self.user.email},
},
project_id=project.id,
)
for axis in ["eps()", "tps()"]:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=6),
"interval": "1m",
"yAxis": axis,
"project": project.id,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 6
rows = data[0:6]
for test in zip(event_counts, rows):
assert test[1][1][0]["count"] == test[0] / 60.0
def test_throughput_eps_no_rollup(self) -> None:
project = self.create_project()
# Each of these denotes how many events to create in each minute
event_counts = [6, 0, 6, 3, 0, 3]
for minute, count in enumerate(event_counts):
for second in range(count):
self.store_event(
data={
"event_id": str(uuid.uuid1()),
"message": "very bad",
"timestamp": (
self.day_ago + timedelta(minutes=minute, seconds=second)
).isoformat(),
"fingerprint": ["group1"],
"tags": {"sentry:user": self.user.email},
},
project_id=project.id,
)
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(minutes=1),
"interval": "1s",
"yAxis": "eps()",
"project": project.id,
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
# expect 60 data points between time span of 0 and 60 seconds
assert len(data) == 60
rows = data[0:6]
for row in rows:
assert row[1][0]["count"] == 1
def test_transaction_events(self) -> None:
prototype = {
"type": "transaction",
"transaction": "api.issue.delete",
"spans": [],
"contexts": {"trace": {"op": "foobar", "trace_id": "a" * 32, "span_id": "a" * 16}},
"tags": {"important": "yes"},
}
fixtures = (
("d" * 32, before_now(minutes=32)),
("e" * 32, before_now(hours=1, minutes=2)),
("f" * 32, before_now(hours=1, minutes=35)),
)
for fixture in fixtures:
data = prototype.copy()
data["event_id"] = fixture[0]
data["timestamp"] = fixture[1].isoformat()
data["start_timestamp"] = (fixture[1] - timedelta(seconds=1)).isoformat()
self.store_event(data=data, project_id=self.project.id)
for dataset in ["discover", "transactions"]:
response = self.do_request(
data={
"project": self.project.id,
"end": before_now(),
"start": before_now(hours=2),
"query": "event.type:transaction",
"interval": "30m",
"yAxis": "count()",
"dataset": dataset,
},
)
assert response.status_code == 200, response.content
items = [item for time, item in response.data["data"] if item]
# We could get more results depending on where the 30 min
# windows land.
assert len(items) >= 3
def test_project_id_query_filter(self) -> None:
response = self.do_request(
data={
"end": before_now(),
"start": before_now(hours=2),
"query": "project_id:1",
"interval": "30m",
"yAxis": "count()",
},
)
assert response.status_code == 200
def test_latest_release_query_filter(self) -> None:
response = self.do_request(
data={
"project": self.project.id,
"end": before_now(),
"start": before_now(hours=2),
"query": "release:latest",
"interval": "30m",
"yAxis": "count()",
},
)
assert response.status_code == 200
def test_conditional_filter(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"query": "id:{} OR id:{}".format("a" * 32, "b" * 32),
"interval": "30m",
"yAxis": "count()",
},
)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 4
assert data[0][1][0]["count"] == 1
assert data[2][1][0]["count"] == 1
def test_simple_multiple_yaxis(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": ["user_count", "event_count"],
},
)
assert response.status_code == 200, response.content
assert response.data["user_count"]["order"] == 0
assert [attrs for time, attrs in response.data["user_count"]["data"]] == [
[{"count": 1}],
[{"count": 1}],
]
assert response.data["event_count"]["order"] == 1
assert [attrs for time, attrs in response.data["event_count"]["data"]] == [
[{"count": 1}],
[{"count": 2}],
]
def test_equation_yaxis(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": ["equation|count() / 100"],
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
assert [attrs for time, attrs in response.data["data"]] == [
[{"count": 0.01}],
[{"count": 0.02}],
]
def test_eps_equation(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": ["equation|eps() * 2"],
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
assert pytest.approx(0.000556, abs=0.0001) == response.data["data"][0][1][0]["count"]
assert pytest.approx(0.001112, abs=0.0001) == response.data["data"][1][1][0]["count"]
def test_epm_equation(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": ["equation|epm() * 2"],
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
assert pytest.approx(0.03334, abs=0.01) == response.data["data"][0][1][0]["count"]
assert pytest.approx(0.06667, abs=0.01) == response.data["data"][1][1][0]["count"]
def test_equation_mixed_multi_yaxis(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": ["count()", "equation|count() * 100"],
},
)
assert response.status_code == 200, response.content
assert response.data["count()"]["order"] == 0
assert [attrs for time, attrs in response.data["count()"]["data"]] == [
[{"count": 1}],
[{"count": 2}],
]
assert response.data["equation|count() * 100"]["order"] == 1
assert [attrs for time, attrs in response.data["equation|count() * 100"]["data"]] == [
[{"count": 100}],
[{"count": 200}],
]
def test_equation_multi_yaxis(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": ["equation|count() / 100", "equation|count() * 100"],
},
)
assert response.status_code == 200, response.content
assert response.data["equation|count() / 100"]["order"] == 0
assert [attrs for time, attrs in response.data["equation|count() / 100"]["data"]] == [
[{"count": 0.01}],
[{"count": 0.02}],
]
assert response.data["equation|count() * 100"]["order"] == 1
assert [attrs for time, attrs in response.data["equation|count() * 100"]["data"]] == [
[{"count": 100}],
[{"count": 200}],
]
def test_large_interval_no_drop_values(self) -> None:
self.store_event(
data={
"event_id": "d" * 32,
"message": "not good",
"timestamp": (self.day_ago - timedelta(minutes=10)).isoformat(),
"fingerprint": ["group3"],
},
project_id=self.project.id,
)
response = self.do_request(
data={
"project": self.project.id,
"end": self.day_ago,
"start": self.day_ago - timedelta(hours=24),
"query": 'message:"not good"',
"interval": "1d",
"yAxis": "count()",
},
)
assert response.status_code == 200
assert [attrs for time, attrs in response.data["data"]] == [[{"count": 0}], [{"count": 1}]]
@mock.patch("sentry.snuba.discover.timeseries_query", return_value={})
def test_multiple_yaxis_only_one_query(self, mock_query: mock.MagicMock) -> None:
self.do_request(
data={
"project": self.project.id,
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"yAxis": ["user_count", "event_count", "epm()", "eps()"],
},
)
assert mock_query.call_count == 1
@mock.patch("sentry.snuba.discover.bulk_snuba_queries", return_value=[{"data": []}])
def test_invalid_interval(self, mock_query: mock.MagicMock) -> None:
self.do_request(
data={
"end": before_now(),
"start": before_now(hours=24),
"query": "",
"interval": "1s",
"yAxis": "count()",
},
)
assert mock_query.call_count == 1
# Should've reset to the default for 24h
assert mock_query.mock_calls[0].args[0][0].query.granularity.granularity == 300
self.do_request(
data={
"end": before_now(),
"start": before_now(hours=24),
"query": "",
"interval": "0d",
"yAxis": "count()",
},
)
assert mock_query.call_count == 2
# Should've reset to the default for 24h
assert mock_query.mock_calls[1].args[0][0].query.granularity.granularity == 300
def test_out_of_retention(self) -> None:
with self.options({"system.event-retention-days": 10}):
response = self.do_request(
data={
"start": before_now(days=20),
"end": before_now(days=15),
"query": "",
"interval": "30m",
"yAxis": "count()",
},
)
assert response.status_code == 400
@mock.patch("sentry.utils.snuba.quantize_time")
def test_quantize_dates(self, mock_quantize: mock.MagicMock) -> None:
mock_quantize.return_value = before_now(days=1)
# Don't quantize short time periods
self.do_request(
data={"statsPeriod": "1h", "query": "", "interval": "30m", "yAxis": "count()"},
)
# Don't quantize absolute date periods
self.do_request(
data={
"start": before_now(days=20),
"end": before_now(days=15),
"query": "",
"interval": "30m",
"yAxis": "count()",
},
)
assert len(mock_quantize.mock_calls) == 0
# Quantize long date periods
self.do_request(
data={"statsPeriod": "90d", "query": "", "interval": "30m", "yAxis": "count()"},
)
assert len(mock_quantize.mock_calls) == 2
def test_with_zerofill(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "30m",
},
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [
[{"count": 1}],
[{"count": 0}],
[{"count": 2}],
[{"count": 0}],
]
def test_comparison_error_dataset(self) -> None:
self.store_event(
data={
"timestamp": (self.day_ago + timedelta(days=-1, minutes=1)).isoformat(),
},
project_id=self.project.id,
)
self.store_event(
data={
"timestamp": (self.day_ago + timedelta(days=-1, minutes=2)).isoformat(),
},
project_id=self.project.id,
)
self.store_event(
data={
"timestamp": (self.day_ago + timedelta(days=-1, hours=1, minutes=1)).isoformat(),
},
project_id=self.project2.id,
)
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"comparisonDelta": int(timedelta(days=1).total_seconds()),
"dataset": "errors",
}
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [
[{"count": 1, "comparisonCount": 2}],
[{"count": 2, "comparisonCount": 1}],
]
def test_comparison(self) -> None:
self.store_event(
data={
"timestamp": (self.day_ago + timedelta(days=-1, minutes=1)).isoformat(),
},
project_id=self.project.id,
)
self.store_event(
data={
"timestamp": (self.day_ago + timedelta(days=-1, minutes=2)).isoformat(),
},
project_id=self.project.id,
)
self.store_event(
data={
"timestamp": (self.day_ago + timedelta(days=-1, hours=1, minutes=1)).isoformat(),
},
project_id=self.project2.id,
)
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"comparisonDelta": int(timedelta(days=1).total_seconds()),
}
)
assert response.status_code == 200, response.content
assert [attrs for time, attrs in response.data["data"]] == [
[{"count": 1, "comparisonCount": 2}],
[{"count": 2, "comparisonCount": 1}],
]
def test_comparison_invalid(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
"comparisonDelta": "17h",
},
)
assert response.status_code == 400, response.content
assert response.data["detail"] == "comparisonDelta must be an integer"
start = before_now(days=85)
end = start + timedelta(days=7)
with self.options({"system.event-retention-days": 90}):
response = self.do_request(
data={
"start": start,
"end": end,
"interval": "1h",
"comparisonDelta": int(timedelta(days=7).total_seconds()),
}
)
assert response.status_code == 400, response.content
assert response.data["detail"] == "Comparison period is outside retention window"
def test_equations_divide_by_zero(self) -> None:
response = self.do_request(
data={
"start": self.day_ago,
"end": self.day_ago + timedelta(hours=2),
"interval": "1h",
# force a 0 in the denominator by doing 1 - 1
# since a 0 literal is illegal as the denominator
"yAxis": ["equation|count() / (1-1)"],
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
assert [attrs for time, attrs in response.data["data"]] == [
[{"count": None}],
[{"count": None}],
]
@mock.patch("sentry.search.events.builder.base.raw_snql_query")
def test_profiles_dataset_simple(self, mock_snql_query: mock.MagicMock) -> None:
mock_snql_query.side_effect = [{"meta": {}, "data": []}]
query = {
"yAxis": [
"count()",
"p75()",
"p95()",
"p99()",
"p75(profile.duration)",
"p95(profile.duration)",
"p99(profile.duration)",
],
"project": [self.project.id],
"dataset": "profiles",
}
response = self.do_request(query, features={"organizations:profiling": True})
assert response.status_code == 200, response.content
def test_tag_with_conflicting_function_alias_simple(self) -> None:
for _ in range(7):
self.store_event(
data={
"timestamp": (self.day_ago + timedelta(minutes=2)).isoformat(),
"tags": {"count": "9001"},
},
project_id=self.project2.id,
)
# Query for count and count()
data = {
"start": self.day_ago.isoformat(),
"end": (self.day_ago + timedelta(minutes=3)).isoformat(),
"interval": "1h",
"yAxis": "count()",
"orderby": ["-count()"],
"field": ["count()", "count"],
"partial": "1",
}
response = self.client.get(self.url, data, format="json")
assert response.status_code == 200
# Expect a count of 8 because one event from setUp
assert response.data["data"][0][1] == [{"count": 8}]
data["query"] = "count:9001"
response = self.client.get(self.url, data, format="json")
assert response.status_code == 200
assert response.data["data"][0][1] == [{"count": 7}]
data["query"] = "count:abc"
response = self.client.get(self.url, data, format="json")
assert response.status_code == 200
assert all([interval[1][0]["count"] == 0 for interval in response.data["data"]])
def test_group_id_tag_simple(self) -> None:
event_data: _EventDataDict = {
"data": {
"message": "poof",
"timestamp": (self.day_ago + timedelta(minutes=2)).isoformat(),
"user": {"email": self.user.email},
"tags": {"group_id": "testing"},
"fingerprint": ["group1"],
},
"project": self.project2,
"count": 7,
}
for i in range(event_data["count"]):
event_data["data"]["event_id"] = f"a{i}" * 16
self.store_event(event_data["data"], project_id=event_data["project"].id)
data = {
"start": self.day_ago.isoformat(),
"end": (self.day_ago + timedelta(hours=2)).isoformat(),
"interval": "1h",
"yAxis": "count()",
"orderby": ["-count()"],
"field": ["count()", "group_id"],
"partial": "1",
}
response = self.client.get(self.url, data, format="json")
assert response.status_code == 200
assert response.data["data"][0][1] == [{"count": 8}]
data["query"] = "group_id:testing"
response = self.client.get(self.url, data, format="json")
assert response.status_code == 200
assert response.data["data"][0][1] == [{"count": 7}]
data["query"] = "group_id:abc"
response = self.client.get(self.url, data, format="json")
assert response.status_code == 200
assert all([interval[1][0]["count"] == 0 for interval in response.data["data"]])
|
OrganizationEventsStatsEndpointTest
|
python
|
huggingface__transformers
|
src/transformers/models/sam2/modeling_sam2.py
|
{
"start": 29581,
"end": 30838
}
|
class ____(nn.Module):
def __init__(self, config: Sam2PromptEncoderConfig):
super().__init__()
self.mask_input_channels = config.mask_input_channels // 4
self.activation = ACT2FN[config.hidden_act]
self.conv1 = nn.Conv2d(1, self.mask_input_channels, kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(self.mask_input_channels, config.mask_input_channels, kernel_size=2, stride=2)
self.conv3 = nn.Conv2d(config.mask_input_channels, config.hidden_size, kernel_size=1)
self.layer_norm1 = Sam2LayerNorm(
self.mask_input_channels, eps=config.layer_norm_eps, data_format="channels_first"
)
self.layer_norm2 = Sam2LayerNorm(
self.mask_input_channels * 4, eps=config.layer_norm_eps, data_format="channels_first"
)
def forward(self, masks):
hidden_states = self.conv1(masks)
hidden_states = self.layer_norm1(hidden_states)
hidden_states = self.activation(hidden_states)
hidden_states = self.conv2(hidden_states)
hidden_states = self.layer_norm2(hidden_states)
hidden_states = self.activation(hidden_states)
dense_embeddings = self.conv3(hidden_states)
return dense_embeddings
|
Sam2MaskEmbedding
|
python
|
huggingface__transformers
|
tests/generation/test_continuous_batching.py
|
{
"start": 1261,
"end": 25562
}
|
class ____(unittest.TestCase):
@parameterized.expand(
[
(None, None, "0"),
(None, 4096, "0"),
("f", None, "0"),
("ffff", None, "0000"),
("sssss", 4096, "00000"),
("fs", 4096, "01"),
("ssfssf", 4096, "001221"),
("ssssf", 4096, "01234"),
("fffsffs", 4096, "0123456"),
]
)
def test_group_layers(
self,
layer_types_str: str | None,
sliding_window: int | None,
expected_groups: str,
) -> None:
# Take a config and change the layer_types attribute to the mix we want
config = AutoConfig.from_pretrained("HuggingFaceTB/SmolLM-1.7B")
if layer_types_str is not None:
layer_types = [{"f": "full_attention", "s": "sliding_window"}[char] for char in layer_types_str]
else:
layer_types = None
config.num_hidden_layers = len(expected_groups)
config.layer_types = layer_types
config.sliding_window = sliding_window
expected_lg = {}
for i, group in enumerate(expected_groups):
group = int(group)
expected_lg[group] = expected_lg.get(group, []) + [i]
expected_layer_groups = [expected_lg[i] for i in sorted(expected_lg.keys())]
# Test layer groups formation
layer_groups, group_types = group_layers_by_attn_type(config)
self.assertEqual(
sorted(expected_layer_groups),
sorted(layer_groups),
f"Test failed for: {layer_types_str = }, {sliding_window = }, {expected_layer_groups = }, {layer_groups = }",
)
# If layer_types is provided, check that group_types matches the type of the all layers in each group
if layer_types is not None:
for layer_group, group_type in zip(layer_groups, group_types):
layer_types = [config.layer_types[i] for i in layer_group]
self.assertEqual(layer_types, [group_type] * len(layer_types))
# If layer_types is None, all groups should be of the same type
else:
for group_type in group_types:
sliding_window = getattr(config, "sliding_window", None)
expected_group_type = "sliding_attention" if sliding_window is not None else "full_attention"
self.assertEqual(
group_type,
expected_group_type,
f"Test failed for: {layer_types_str = }, {sliding_window = }, {group_types = }",
)
@parameterized.expand(
[
([0, 4], [0, 4], 1, ["1000", "1100", "1110", "1111"]),
([0, 4], [0, 4], 2, ["1000", "1100", "0110", "0011"]),
([0, 3], [0, 5], 1, ["11100", "11110", "11111"]),
([0, 3], [0, 5], 3, ["11100", "01110", "00111"]),
([0, 3, 6], [0, 3, 6], 1, ["100000", "110000", "111000", "000100", "000110", "000111"]),
([0, 3, 6], [0, 3, 6], 2, ["100000", "110000", "011000", "000100", "000110", "000011"]),
]
)
def test_attention_mask(
self,
cumulative_seqlens_q: list[int],
cumulative_seqlens_k: list[int],
sliding_window: int, # the sliding window size, 1 means no sliding window
str_expected_mask: list[str], # the attention mask, broken down by line as a string of 0s and 1s
) -> None:
# Build expected mask
minus_inf = torch.finfo(torch.float32).min
expected_mask = torch.empty((cumulative_seqlens_q[-1], cumulative_seqlens_k[-1]), dtype=torch.float32)
for i, line in enumerate(str_expected_mask):
expected_mask[i, :] = torch.tensor([minus_inf if c == "0" else 0 for c in line])
# Build actual mask
actual_mask = torch.full_like(expected_mask, minus_inf) # function modifies in place
build_attention_mask(
actual_mask, torch.tensor(cumulative_seqlens_q), torch.tensor(cumulative_seqlens_k), sliding_window
)
# Check that the actual mask matches the expected mask
matches = (expected_mask == actual_mask).all()
# If it doesn't match, print the masks in a readable form and fail the test
if not matches:
str_mask = [
"".join("1" if x == 0 else "0" for x in token_attn_vector) for token_attn_vector in actual_mask
]
str_mask = "\n".join(str_mask)
str_expected_mask = "\n".join(str_expected_mask)
self.fail(
f"Test failed for: {cumulative_seqlens_q = }, {cumulative_seqlens_k = }, {sliding_window = }\n"
f"Expected mask:\n{str_expected_mask}\n"
f"Actual mask:\n{str_mask}"
)
def _continuous_batching_parity(
self, model_id: str, attn_implementation: str, expected_outputs: dict[str, str]
) -> None:
# Prepare common elements
tokenizer = AutoTokenizer.from_pretrained(model_id, padding_side="left")
prompts = [
"Janet's ducks lay 16 eggs per day. She eats three for breakfast every morning and bakes muffins for her "
"friends every day with four. She sells the remainder at the farmers' market daily for $2 per fresh "
"duck egg. How much in dollars does she make every day at the farmers' market? The answer is:",
"A robe takes 2 bolts of blue fiber and half that much white fiber. How many bolts in total does it take? "
"The answer is:",
"Josh decides to try flipping a house. He buys a house for $80,000 and then puts in $50,000 in repairs. "
"This increased the value of the house by 150%. How much profit did he make? The answer is:",
] # fmt: skip
batched_inputs = [tokenizer.encode(prompt) for prompt in prompts]
# Generation with continuous batching
model = AutoModelForCausalLM.from_pretrained(model_id, attn_implementation=attn_implementation, dtype="auto")
model = model.to(torch_device).eval()
model.generation_config.max_new_tokens = 40
model.generation_config.do_sample = False
model.generation_config.use_cuda_graph = False
cb_outputs = model.generate_batch(inputs=batched_inputs, generation_config=model.generation_config)
# Generation without continuous batching
if attn_implementation == "paged|sdpa":
non_cb_attn_implementation = "sdpa"
elif attn_implementation == "paged|eager":
non_cb_attn_implementation = "eager"
elif attn_implementation == "paged|flash_attention_2":
non_cb_attn_implementation = "eager"
else:
raise ValueError(f"Invalid attention implementation: {attn_implementation}")
# We regenerate the model because just changing the attn_implementation does not work
model = AutoModelForCausalLM.from_pretrained(
model_id, attn_implementation=non_cb_attn_implementation, dtype="auto"
)
model = model.to(torch_device).eval()
model.generation_config.max_new_tokens = 40
model.generation_config.do_sample = False
model.generation_config.use_cuda_graph = False
for request_id, request in cb_outputs.items():
# Generate without continuous batching
input_ids = torch.tensor([request.prompt_ids]).to(torch_device)
attention_mask = torch.ones_like(input_ids)
outputs = model.generate(
input_ids, attention_mask=attention_mask, generation_config=model.generation_config
)
generated_tokens = outputs[0][input_ids.shape[1] :]
non_cb_decoded_output = tokenizer.decode(generated_tokens, skip_special_tokens=True)
input_ids = input_ids.tolist()[0]
# Check that the generated output with and without CB match
cb_decoded_output = tokenizer.decode(request.generated_tokens, skip_special_tokens=True)
outputs_match = non_cb_decoded_output == cb_decoded_output
# If they dont, that might be expected: the outputs can differ slightly due to numerical differences
# If that's the case, there is an expected output ready
if not outputs_match:
expected_output = expected_outputs.get(request_id) if ALLOW_EXPECTED_OUTPUTS else None
if expected_output is None:
self.fail(
f"Test {request_id = } failed, no expected output was provided.\nRef:"
f"{repr(non_cb_decoded_output)}\nOut:{repr(cb_decoded_output)}"
)
else:
self.assertEqual(
expected_output,
cb_decoded_output,
msg=f"Test {request_id = } failed, expected output did not match.\n"
f"Exp:{repr(expected_output)}\nOut:{repr(cb_decoded_output)}",
)
# Eager tests
@require_torch_accelerator
@require_read_token
@slow
def test_continuous_batching_parity_llama_eager(self) -> None:
expected_outputs = Expectations({
("rocm", (9, 4)): {
"req_0": " $16. How did I get that answer? I used the following equation: 16 - 3 - 4 = 9. 9 x $2 = $18. $18 -"
},
("cuda", (9, 0)): {
"req_1": " 3 bolts of blue fiber and 1.5 bolts of white fiber. The total number of bolts is 4.5. The total number of bolts is 4.5. The total",
"req_2": " $50,000. This is because the value of the house increased by 150%, which means that the value of the house increased by $50,000. This is because the value of the"
},
("xpu", None): {
"req_1": " 3 bolts of blue fiber and 1.5 bolts of white fiber. The answer is not 3.5 bolts of blue fiber and 1.5 bolts of white fiber. The answer'",
"req_2": " $50,000. This is because the value of the house increased by 150%, which means that the value of the house increased by $50,000. This is because the value of the"
},
}).get_expectation() # fmt: skip
self._continuous_batching_parity("meta-llama/Llama-3.1-8B", "paged|eager", expected_outputs)
@require_torch_accelerator
@slow
def test_continuous_batching_parity_gemma_eager(self) -> None:
expected_outputs = Expectations({
("rocm", (9, 4)): {
"req_1": " \n\n**Answer:** 3 bolts\n\n**Solution:**\n\n* **White fiber:** The robe needs half as much white fiber as blue fiber, so it needs 2 bolts / 2 ="
},
("cuda", (9, 0)): {
"req_0": "\n\n**$12**\n\n**Here's how to solve it:**\n\n* **Eggs eaten:** 3\n* **Eggs left:** 16 - 3 = 13",
"req_1": " \n \n 2 + 1 = 3 bolts \n \n \n \n \n \n \n \n \n \n \n \n \n "
},
("xpu", None): {
"req_0": "\n\n**$12**\n\n**Here's how to solve it:**\n\n* **Eggs eaten:** 3\n* **Eggs left:** 16 - 3 = 13",
"req_1": " \n \n 2 + 1 = 3 bolts \n \n \n \n \n \n \n \n \n \n \n \n \n ",
"req_2": "\n\n**$100,000**\n\n**Explanation:**\n\nHere's how to calculate the profit:\n\n1. **Calculate the total cost:** $80,00",
},
}).get_expectation() # fmt: skip
self._continuous_batching_parity("google/gemma-2-2b-it", "paged|eager", expected_outputs)
# FIXME: set expected_outputs
# @require_torch_accelerator
# @slow
# def test_continuous_batching_parity_qwen_eager(self) -> None:
# expected_outputs = {}
# self._continuous_batching_parity("Qwen/Qwen3-4B-Instruct-2507", "paged|eager", expected_outputs)
# FIXME: OOMs
# @require_torch_accelerator
# @slow
# def test_continuous_batching_parity_gpt_oss_eager(self) -> None:
# expected_outputs = Expectations({
# ("cuda", (9, 0)): {
# "req_1": " 2.5 bolts. The question: \"What is the name of the puzzle that involves a robe taking 2 bolts of blue fiber and half that much white fiber?\" The answer: \"The",
# "req_2": " 50%.\"\n\nWe need to parse: He buys a house for $80,000. He puts in $50,000 in repairs. This increased the value of the house by 150%."
# },
# ("xpu", None): {
# "req_1": " 2.5 bolts. The question: \"What is the name of the puzzle that involves a robe taking 2 bolts of blue fiber and half that much white fiber?\" The answer: \"The",
# "req_2": " 50%.\"\n\nWe need to parse: He buys a house for $80,000. He puts in $50,000 in repairs. This increased the value of the house by 150%."
# },
# }).get_expectation() # fmt: skip
# self._continuous_batching_parity("openai/gpt-oss-20b", "paged|eager", expected_outputs)
# SDPA tests
@require_read_token
@require_torch_accelerator
@slow
def test_continuous_batching_parity_llama_sdpa(self) -> None:
expected_outputs = Expectations({
("rocm", (9, 4)): {
"req_2": " $50,000. This is because the value of the house increased by 150%, which means that the value of the house increased by $50,000. This is because the value of the"
},
("xpu", None): {
"req_2": " $50,000. This is because the value of the house increased by 150%, which means that the value of the house increased by $50,000. This is because the value of the"
},
}).get_expectation() # fmt: skip
self._continuous_batching_parity("meta-llama/Llama-3.1-8B", "paged|sdpa", expected_outputs)
@require_torch_accelerator
@slow
def test_continuous_batching_parity_gemma_sdpa(self) -> None:
expected_outputs = Expectations({
("cuda", (9, 0)): {
"req_1": " \n\n**Answer:** 3 bolts\n\n**Solution:**\n\n* **White fiber:** The robe needs half as much white fiber as blue fiber, so it needs 2 bolts / 2 =",
},
("xpu", None): {
"req_1": " \n\n**Answer:** 3 bolts\n\n**Solution:**\n\n* **White fiber:** The robe needs half as much white fiber as blue fiber, so it needs 2 bolts / 2 =",
},
}).get_expectation() # fmt: skip
self._continuous_batching_parity("google/gemma-2-2b-it", "paged|sdpa", expected_outputs)
# FIXME: set expected_outputs
# @require_torch_accelerator
# @slow
# def test_continuous_batching_parity_qwen_sdpa(self) -> None:
# expected_outputs = {}
# self._continuous_batching_parity("Qwen/Qwen3-4B-Instruct-2507", "paged|sdpa", expected_outputs)
# GPT-OSS is not compatible with SDPA because it has an attention sink. TODO: is this fixable?
# Flash attention test
@require_torch_gpu
@require_kernels
@slow
def test_continuous_batching_parity_llama_flash(self) -> None:
expected_outputs = Expectations({
("cuda", (9, 0)): {
"req_1": " 3 bolts of blue fiber and 1.5 bolts of white fiber. The total number of bolts is 4.5 bolts. The total number of bolts is 4.5 bolts.",
}
}).get_expectation() # fmt: skip
self._continuous_batching_parity("meta-llama/Llama-3.1-8B", "paged|flash_attention_2", expected_outputs)
@require_torch_gpu
@require_kernels
@slow
def test_continuous_batching_parity_gemma_flash(self) -> None:
expected_outputs = Expectations({
("cuda", (9, 0)): {
"req_1": " \n \n 2 + 1 = 3 bolts \n \n \n \n \n \n \n \n \n \n \n \n \n ",
}
}).get_expectation() # fmt: skip
self._continuous_batching_parity("google/gemma-2-2b-it", "paged|flash_attention_2", expected_outputs)
@require_torch_gpu
@require_kernels
@slow
def test_continuous_batching_parity_qwen_flash(self) -> None:
expected_outputs = {}
self._continuous_batching_parity("Qwen/Qwen3-4B-Instruct-2507", "paged|flash_attention_2", expected_outputs)
@require_torch_gpu
@require_kernels
@slow
def test_continuous_batching_parity_gpt_oss_flash(self) -> None:
expected_outputs = {}
self._continuous_batching_parity("openai/gpt-oss-20b", "paged|flash_attention_2", expected_outputs)
def test_attn_implementation(self) -> None:
model = AutoModelForCausalLM.from_pretrained("gpt2")
manager = model.init_continuous_batching()
assert "paged|sdpa" == manager.model.config._attn_implementation
model = AutoModelForCausalLM.from_pretrained("gpt2", _attn_implementation="eager")
manager = model.init_continuous_batching()
assert "paged|eager" == manager.model.config._attn_implementation
@require_torch_accelerator
def test_streaming_request(self) -> None:
model_id = "Qwen/Qwen2.5-0.5B-Instruct"
max_new_tokens = 3
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
manager = model.init_continuous_batching()
manager.logit_processor = LogitsProcessorList()
manager.start()
messages = [{"content": "What is the Transformers library known for?", "role": "user"}]
inputs = tokenizer.apply_chat_template(
messages, return_tensors="pt", add_generation_prompt=True, return_dict=False
).to(model.device)[0]
request_id = manager.add_request(inputs, max_new_tokens=max_new_tokens, streaming=True)
# In streaming mode, the total number of generated tokens is incremented by 1 on each iteration
chunk_1 = next(manager.request_id_iter(request_id))
self.assertEqual(len(chunk_1.generated_tokens), 1)
chunk_2 = next(manager.request_id_iter(request_id))
self.assertEqual(len(chunk_2.generated_tokens), 2)
chunk_3 = next(manager.request_id_iter(request_id))
self.assertEqual(len(chunk_3.generated_tokens), 3)
manager.stop(block=True)
@require_torch_accelerator
def test_non_streaming_request(self) -> None:
model_id = "Qwen/Qwen2.5-0.5B-Instruct"
max_new_tokens = 3
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
manager = model.init_continuous_batching()
manager.logit_processor = LogitsProcessorList()
manager.start()
messages = [{"content": "What is the Transformers library known for?", "role": "user"}]
inputs = tokenizer.apply_chat_template(
messages, return_tensors="pt", add_generation_prompt=True, return_dict=False
).to(model.device)[0]
request_id = manager.add_request(inputs, max_new_tokens=max_new_tokens, streaming=False)
chunk = next(manager.request_id_iter(request_id))
# In non-streaming mode, the total number of generated tokens is equal to the max new tokens
self.assertEqual(len(chunk.generated_tokens), max_new_tokens)
manager.stop(block=True)
@require_torch_accelerator
def test_streaming_and_non_streaming_requests_can_alternate(self) -> None:
model_id = "Qwen/Qwen2.5-0.5B-Instruct"
max_new_tokens = 3
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
manager = model.init_continuous_batching()
manager.logit_processor = LogitsProcessorList()
manager.start()
messages = [{"content": "What is the Transformers library known for?", "role": "user"}]
inputs = tokenizer.apply_chat_template(
messages, return_tensors="pt", add_generation_prompt=True, return_dict=False
).to(model.device)[0]
# Non-streaming request
request_id = manager.add_request(inputs, max_new_tokens=max_new_tokens, streaming=False)
chunk = next(manager.request_id_iter(request_id))
self.assertEqual(len(chunk.generated_tokens), max_new_tokens)
# Streaming request works afterward
request_id = manager.add_request(inputs, max_new_tokens=max_new_tokens, streaming=True)
chunk_1 = next(manager.request_id_iter(request_id))
self.assertEqual(len(chunk_1.generated_tokens), 1)
chunk_2 = next(manager.request_id_iter(request_id))
self.assertEqual(len(chunk_2.generated_tokens), 2)
chunk_3 = next(manager.request_id_iter(request_id))
self.assertEqual(len(chunk_3.generated_tokens), 3)
manager.stop(block=True)
@require_torch_accelerator
def test_prefix_sharing(self) -> None:
model_id = "Qwen/Qwen2.5-0.5B-Instruct"
max_new_tokens = 32
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto")
generation_config = GenerationConfig(do_sample=False, block_size=32)
with model.continuous_batching_context_manager(generation_config=generation_config) as manager:
manager.logit_processor = LogitsProcessorList()
# Create a request with at least 32 tokens but less than 64 so prefill only generates one complete block
messages = [{"content": "What is the Transformers library known for?", "role": "user"}]
inputs = tokenizer.apply_chat_template(
messages, return_tensors="pt", add_generation_prompt=True, return_dict=False
)
inputs = inputs.to(model.device)[0].tolist()
self.assertGreaterEqual(len(inputs), 32, f"Input length is {len(inputs)} instead of at least 32")
self.assertLess(len(inputs), 64, f"Input length is {len(inputs)} instead of less than 64")
# First request, which populates the cache with a complete block
request_id = manager.add_request(inputs, max_new_tokens=max_new_tokens)
chunk_no_reuse = next(manager.request_id_iter(request_id))
hash_table = manager.batch_processor.cache._block_manager._hash_to_id
self.assertEqual(
len(hash_table),
2,
f"There should be 2 blocks, one for the prefill and one for the decode, but {len(hash_table) = }",
)
total_prefix_length = manager.batch_processor.cache._total_prefix_length
self.assertEqual(
total_prefix_length, 0, f"Expected total prefix length to be 0, got {total_prefix_length}"
)
# Second request, which should reuse the same block
request_id = manager.add_request(inputs, max_new_tokens=max_new_tokens)
chunk_with_reuse = next(manager.request_id_iter(request_id))
# There should only still be two blocks in the hash table because of block reuse
self.assertEqual(
len(hash_table),
2,
f"Because of block reuse, there should still be two blocks in the hash table, but {len(hash_table) = }",
)
# Check that the whole prefill was matched
total_prefix_length = manager.batch_processor.cache._total_prefix_length
self.assertEqual(
total_prefix_length, 32, f"Expected total prefix length to be 32, got {total_prefix_length}"
)
# Check the outputs were the same
self.assertEqual(chunk_no_reuse.generated_tokens, chunk_with_reuse.generated_tokens)
# As an additional sanity check, we also compare to the generated tokens when prefix sharing is disabled
expected_generated_tokens = Expectations({
("rocm", (9, 4)): [785, 80532, 6733, 374, 3881, 369, 1181, 5726, 311, 1855, 323, 36635, 3460, 12934, 4128, 4119, 11, 2670, 1846, 429, 646, 6923, 1467, 11, 14683, 1467, 11, 323, 2736, 1008, 4128, 13904],
}).get_expectation() # fmt: skip
self.assertEqual(chunk_no_reuse.generated_tokens, expected_generated_tokens)
# FIXME: the gemma test seem broken, there is a message about cuda graphs and the sdpa and flash expecteations are
# inverted on CUDA. On AMD they do fine.
|
ContinuousBatchingTest
|
python
|
Unity-Technologies__ml-agents
|
ml-agents/mlagents/trainers/trainer/off_policy_trainer.py
|
{
"start": 881,
"end": 10489
}
|
class ____(RLTrainer):
"""
The SACTrainer is an implementation of the SAC algorithm, with support
for discrete actions and recurrent networks.
"""
def __init__(
self,
behavior_name: str,
reward_buff_cap: int,
trainer_settings: TrainerSettings,
training: bool,
load: bool,
seed: int,
artifact_path: str,
):
"""
Responsible for collecting experiences and training an off-policy model.
:param behavior_name: The name of the behavior associated with trainer config
:param reward_buff_cap: Max reward history to track in the reward buffer
:param trainer_settings: The parameters for the trainer.
:param training: Whether the trainer is set for training.
:param load: Whether the model should be loaded.
:param seed: The seed the model will be initialized with
:param artifact_path: The directory within which to store artifacts from this trainer.
"""
super().__init__(
behavior_name,
trainer_settings,
training,
load,
artifact_path,
reward_buff_cap,
)
self.seed = seed
self.policy: Policy = None # type: ignore
self.optimizer: TorchOptimizer = None # type: ignore
self.hyperparameters: OffPolicyHyperparamSettings = cast(
OffPolicyHyperparamSettings, trainer_settings.hyperparameters
)
self._step = 0
# Don't divide by zero
self.update_steps = 1
self.reward_signal_update_steps = 1
self.steps_per_update = self.hyperparameters.steps_per_update
self.reward_signal_steps_per_update = (
self.hyperparameters.reward_signal_steps_per_update
)
self.checkpoint_replay_buffer = self.hyperparameters.save_replay_buffer
def _checkpoint(self) -> ModelCheckpoint:
"""
Writes a checkpoint model to memory
Overrides the default to save the replay buffer.
"""
ckpt = super()._checkpoint()
if self.checkpoint_replay_buffer:
self.save_replay_buffer()
return ckpt
def save_model(self) -> None:
"""
Saves the final training model to memory
Overrides the default to save the replay buffer.
"""
super().save_model()
if self.checkpoint_replay_buffer:
self.save_replay_buffer()
def save_replay_buffer(self) -> None:
"""
Save the training buffer's update buffer to a pickle file.
"""
filename = os.path.join(self.artifact_path, "last_replay_buffer.hdf5")
logger.info(f"Saving Experience Replay Buffer to {filename}...")
with open(filename, "wb") as file_object:
self.update_buffer.save_to_file(file_object)
logger.info(
f"Saved Experience Replay Buffer ({os.path.getsize(filename)} bytes)."
)
def load_replay_buffer(self) -> None:
"""
Loads the last saved replay buffer from a file.
"""
filename = os.path.join(self.artifact_path, "last_replay_buffer.hdf5")
logger.info(f"Loading Experience Replay Buffer from {filename}...")
with open(filename, "rb+") as file_object:
self.update_buffer.load_from_file(file_object)
logger.debug(
"Experience replay buffer has {} experiences.".format(
self.update_buffer.num_experiences
)
)
def _is_ready_update(self) -> bool:
"""
Returns whether or not the trainer has enough elements to run update model
:return: A boolean corresponding to whether or not _update_policy() can be run
"""
return (
self.update_buffer.num_experiences >= self.hyperparameters.batch_size
and self._step >= self.hyperparameters.buffer_init_steps
)
def maybe_load_replay_buffer(self):
# Load the replay buffer if load
if self.load and self.checkpoint_replay_buffer:
try:
self.load_replay_buffer()
except (AttributeError, FileNotFoundError):
logger.warning(
"Replay buffer was unable to load, starting from scratch."
)
logger.debug(
"Loaded update buffer with {} sequences".format(
self.update_buffer.num_experiences
)
)
def add_policy(
self, parsed_behavior_id: BehaviorIdentifiers, policy: Policy
) -> None:
"""
Adds policy to trainer.
"""
if self.policy:
logger.warning(
"Your environment contains multiple teams, but {} doesn't support adversarial games. Enable self-play to \
train adversarial games.".format(
self.__class__.__name__
)
)
self.policy = policy
self.policies[parsed_behavior_id.behavior_id] = policy
self.optimizer = self.create_optimizer()
for _reward_signal in self.optimizer.reward_signals.keys():
self.collected_rewards[_reward_signal] = defaultdict(lambda: 0)
self.model_saver.register(self.policy)
self.model_saver.register(self.optimizer)
self.model_saver.initialize_or_load()
# Needed to resume loads properly
self._step = policy.get_current_step()
# Assume steps were updated at the correct ratio before
self.update_steps = int(max(1, self._step / self.steps_per_update))
self.reward_signal_update_steps = int(
max(1, self._step / self.reward_signal_steps_per_update)
)
@timed
def _update_policy(self) -> bool:
"""
Uses update_buffer to update the policy. We sample the update_buffer and update
until the steps_per_update ratio is met.
"""
has_updated = False
self.cumulative_returns_since_policy_update.clear()
n_sequences = max(
int(self.hyperparameters.batch_size / self.policy.sequence_length), 1
)
batch_update_stats: Dict[str, list] = defaultdict(list)
while (
self._step - self.hyperparameters.buffer_init_steps
) / self.update_steps > self.steps_per_update:
logger.debug(f"Updating SAC policy at step {self._step}")
buffer = self.update_buffer
if self.update_buffer.num_experiences >= self.hyperparameters.batch_size:
sampled_minibatch = buffer.sample_mini_batch(
self.hyperparameters.batch_size,
sequence_length=self.policy.sequence_length,
)
# Get rewards for each reward
for name, signal in self.optimizer.reward_signals.items():
sampled_minibatch[RewardSignalUtil.rewards_key(name)] = (
signal.evaluate(sampled_minibatch) * signal.strength
)
update_stats = self.optimizer.update(sampled_minibatch, n_sequences)
for stat_name, value in update_stats.items():
batch_update_stats[stat_name].append(value)
self.update_steps += 1
for stat, stat_list in batch_update_stats.items():
self._stats_reporter.add_stat(stat, np.mean(stat_list))
has_updated = True
if self.optimizer.bc_module:
update_stats = self.optimizer.bc_module.update()
for stat, val in update_stats.items():
self._stats_reporter.add_stat(stat, val)
# Truncate update buffer if neccessary. Truncate more than we need to to avoid truncating
# a large buffer at each update.
if self.update_buffer.num_experiences > self.hyperparameters.buffer_size:
self.update_buffer.truncate(
int(self.hyperparameters.buffer_size * BUFFER_TRUNCATE_PERCENT)
)
# TODO: revisit this update
self._update_reward_signals()
return has_updated
def _update_reward_signals(self) -> None:
"""
Iterate through the reward signals and update them. Unlike in PPO,
do it separate from the policy so that it can be done at a different
interval.
This function should only be used to simulate
http://arxiv.org/abs/1809.02925 and similar papers, where the policy is updated
N times, then the reward signals are updated N times. Normally, the reward signal
and policy are updated in parallel.
"""
buffer = self.update_buffer
batch_update_stats: Dict[str, list] = defaultdict(list)
while (
self._step - self.hyperparameters.buffer_init_steps
) / self.reward_signal_update_steps > self.reward_signal_steps_per_update:
# Get minibatches for reward signal update if needed
minibatch = buffer.sample_mini_batch(
self.hyperparameters.batch_size,
sequence_length=self.policy.sequence_length,
)
update_stats = self.optimizer.update_reward_signals(minibatch)
for stat_name, value in update_stats.items():
batch_update_stats[stat_name].append(value)
self.reward_signal_update_steps += 1
for stat, stat_list in batch_update_stats.items():
self._stats_reporter.add_stat(stat, np.mean(stat_list))
|
OffPolicyTrainer
|
python
|
facebook__pyre-check
|
client/command_arguments.py
|
{
"start": 1737,
"end": 1873
}
|
class ____(str, enum.Enum):
_value_: str
JSON = "json"
SHARDED_JSON = "sharded-json"
@dataclass(frozen=True)
|
TaintOutputFormat
|
python
|
PyCQA__pylint
|
tests/functional/c/class_scope.py
|
{
"start": 893,
"end": 1099
}
|
class ____:
"""wrong"""
class Result2:
"""result two"""
OK = 0
def work(self) -> self.Result2: # [undefined-variable]
"""bad type hint"""
return self.Result2.OK
|
Wrong
|
python
|
pandas-dev__pandas
|
pandas/tests/frame/methods/test_get_numeric_data.py
|
{
"start": 209,
"end": 3379
}
|
class ____:
def test_get_numeric_data_preserve_dtype(self):
# get the numeric data
obj = DataFrame({"A": [1, "2", 3.0]}, columns=Index(["A"], dtype="object"))
result = obj._get_numeric_data()
expected = DataFrame(dtype=object, index=pd.RangeIndex(3), columns=[])
tm.assert_frame_equal(result, expected)
def test_get_numeric_data(self, using_infer_string):
datetime64name = np.dtype("M8[s]").name
objectname = np.dtype(np.object_).name
df = DataFrame(
{"a": 1.0, "b": 2, "c": "foo", "f": Timestamp("20010102").as_unit("s")},
index=np.arange(10),
)
result = df.dtypes
expected = Series(
[
np.dtype("float64"),
np.dtype("int64"),
np.dtype(objectname)
if not using_infer_string
else pd.StringDtype(na_value=np.nan),
np.dtype(datetime64name),
],
index=["a", "b", "c", "f"],
)
tm.assert_series_equal(result, expected)
df = DataFrame(
{
"a": 1.0,
"b": 2,
"c": "foo",
"d": np.array([1.0] * 10, dtype="float32"),
"e": np.array([1] * 10, dtype="int32"),
"f": np.array([1] * 10, dtype="int16"),
"g": Timestamp("20010102"),
},
index=np.arange(10),
)
result = df._get_numeric_data()
expected = df.loc[:, ["a", "b", "d", "e", "f"]]
tm.assert_frame_equal(result, expected)
only_obj = df.loc[:, ["c", "g"]]
result = only_obj._get_numeric_data()
expected = df.loc[:, []]
tm.assert_frame_equal(result, expected)
df = DataFrame.from_dict({"a": [1, 2], "b": ["foo", "bar"], "c": [np.pi, np.e]})
result = df._get_numeric_data()
expected = DataFrame.from_dict({"a": [1, 2], "c": [np.pi, np.e]})
tm.assert_frame_equal(result, expected)
df = result.copy()
result = df._get_numeric_data()
expected = df
tm.assert_frame_equal(result, expected)
def test_get_numeric_data_mixed_dtype(self):
# numeric and object columns
df = DataFrame(
{
"a": [1, 2, 3],
"b": [True, False, True],
"c": ["foo", "bar", "baz"],
"d": [None, None, None],
"e": [3.14, 0.577, 2.773],
}
)
result = df._get_numeric_data()
tm.assert_index_equal(result.columns, Index(["a", "b", "e"]))
def test_get_numeric_data_extension_dtype(self):
# GH#22290
df = DataFrame(
{
"A": pd.array([-10, pd.NA, 0, 10, 20, 30], dtype="Int64"),
"B": Categorical(list("abcabc")),
"C": pd.array([0, 1, 2, 3, pd.NA, 5], dtype="UInt8"),
"D": IntervalArray.from_breaks(range(7)),
}
)
result = df._get_numeric_data()
expected = df.loc[:, ["A", "C"]]
tm.assert_frame_equal(result, expected)
|
TestGetNumericData
|
python
|
vyperlang__vyper
|
vyper/ast/nodes.py
|
{
"start": 22759,
"end": 22886
}
|
class ____(Stmt):
__slots__ = ("value",)
@property
def is_terminus(self):
return self.value.is_terminus
|
Expr
|
python
|
walkccc__LeetCode
|
solutions/2589. Minimum Time to Complete All Tasks/2589.py
|
{
"start": 0,
"end": 598
}
|
class ____:
def findMinimumTime(self, tasks: list[list[int]]) -> int:
MAX = 2000
running = [False] * (MAX + 1)
# Sort tasks by end.
for start, end, duration in sorted(tasks, key=lambda x: x[1]):
neededDuration = (duration -
sum(running[i] for i in range(start, end + 1)))
# Greedily run the task as late as possible so that later tasks can run
# simultaneously.
i = end
while neededDuration > 0:
if not running[i]:
running[i] = True
neededDuration -= 1
i -= 1
return sum(running)
|
Solution
|
python
|
wandb__wandb
|
wandb/sdk/launch/inputs/files.py
|
{
"start": 155,
"end": 4685
}
|
class ____:
"""Singleton that read file overrides json from environment variables."""
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = object.__new__(cls)
cls._instance.overrides = {}
cls._instance.load()
return cls._instance
def load(self) -> None:
"""Load overrides from an environment variable."""
overrides = os.environ.get(FILE_OVERRIDE_ENV_VAR)
if overrides is None:
if f"{FILE_OVERRIDE_ENV_VAR}_0" in os.environ:
overrides = ""
idx = 0
while f"{FILE_OVERRIDE_ENV_VAR}_{idx}" in os.environ:
overrides += os.environ[f"{FILE_OVERRIDE_ENV_VAR}_{idx}"]
idx += 1
if overrides:
try:
contents = json.loads(overrides)
if not isinstance(contents, dict):
raise LaunchError(f"Invalid JSON in {FILE_OVERRIDE_ENV_VAR}")
self.overrides = contents
except json.JSONDecodeError:
raise LaunchError(f"Invalid JSON in {FILE_OVERRIDE_ENV_VAR}")
def config_path_is_valid(path: str) -> None:
"""Validate a config file path.
This function checks if a given config file path is valid. A valid path
should meet the following criteria:
- The path must be expressed as a relative path without any upwards path
traversal, e.g. `../config.json`.
- The file specified by the path must exist.
- The file must have a supported extension (`.json`, `.yaml`, or `.yml`).
Args:
path (str): The path to validate.
Raises:
LaunchError: If the path is not valid.
"""
if os.path.isabs(path):
raise LaunchError(
f"Invalid config path: {path}. Please provide a relative path."
)
if ".." in path:
raise LaunchError(
f"Invalid config path: {path}. Please provide a relative path "
"without any upward path traversal, e.g. `../config.json`."
)
path = os.path.normpath(path)
if not os.path.exists(path):
raise LaunchError(f"Invalid config path: {path}. File does not exist.")
if not any(path.endswith(ext) for ext in [".json", ".yaml", ".yml"]):
raise LaunchError(
f"Invalid config path: {path}. Only JSON and YAML files are supported."
)
def override_file(path: str) -> None:
"""Check for file overrides in the environment and apply them if found."""
file_overrides = FileOverrides()
if path in file_overrides.overrides:
overrides = file_overrides.overrides.get(path)
if overrides is not None:
config = _read_config_file(path)
_update_dict(config, overrides)
_write_config_file(path, config)
def _write_config_file(path: str, config: Any) -> None:
"""Write a config file to disk.
Args:
path (str): The path to the config file.
config (Any): The contents of the config file as a Python object.
Raises:
LaunchError: If the file extension is not supported.
"""
_, ext = os.path.splitext(path)
if ext == ".json":
with open(path, "w") as f:
json.dump(config, f, indent=2)
elif ext in [".yaml", ".yml"]:
with open(path, "w") as f:
yaml.safe_dump(config, f)
else:
raise LaunchError(f"Unsupported file extension: {ext}")
def _read_config_file(path: str) -> Any:
"""Read a config file from disk.
Args:
path (str): The path to the config file.
Returns:
Any: The contents of the config file as a Python object.
"""
_, ext = os.path.splitext(path)
if ext == ".json":
with open(
path,
) as f:
return json.load(f)
elif ext in [".yaml", ".yml"]:
with open(
path,
) as f:
return yaml.safe_load(f)
else:
raise LaunchError(f"Unsupported file extension: {ext}")
def _update_dict(target: Dict, source: Dict) -> None:
"""Update a dictionary with the contents of another dictionary.
Args:
target (Dict): The dictionary to update.
source (Dict): The dictionary to update from.
"""
for key, value in source.items():
if isinstance(value, dict):
if key not in target:
target[key] = {}
_update_dict(target[key], value)
else:
target[key] = value
|
FileOverrides
|
python
|
prompt-toolkit__python-prompt-toolkit
|
src/prompt_toolkit/utils.py
|
{
"start": 2782,
"end": 2995
}
|
class ____(ContextManager[None]):
"""
(contextlib.nested is not available on Py3)
"""
def __enter__(self) -> None:
pass
def __exit__(self, *a: object) -> None:
pass
|
DummyContext
|
python
|
allegroai__clearml
|
clearml/backend_api/services/v2_13/tasks.py
|
{
"start": 329823,
"end": 330059
}
|
class ____(Response):
"""
Response of tasks.ping endpoint.
"""
_service = "tasks"
_action = "ping"
_version = "2.13"
_schema = {"additionalProperties": False, "definitions": {}, "type": "object"}
|
PingResponse
|
python
|
aio-libs__aiohttp
|
aiohttp/tracing.py
|
{
"start": 8774,
"end": 8909
}
|
class ____:
"""Parameters sent by the `on_connection_create_end` signal"""
@frozen_dataclass_decorator
|
TraceConnectionCreateEndParams
|
python
|
django__django
|
tests/auth_tests/urls.py
|
{
"start": 2677,
"end": 2797
}
|
class ____(LoginView):
def get_default_redirect_url(self):
return "/custom/"
|
CustomDefaultRedirectURLLoginView
|
python
|
ansible__ansible
|
test/lib/ansible_test/_internal/cli/actions.py
|
{
"start": 3080,
"end": 3367
}
|
class ____(CompositeAction):
"""Composite action parser for a network SSH target."""
def create_parser(self) -> NamespaceParser:
"""Return a namespace parser to parse the argument associated with this action."""
return NetworkSshTargetParser()
|
NetworkSshTargetAction
|
python
|
MongoEngine__mongoengine
|
docs/code/tumblelog.py
|
{
"start": 574,
"end": 626
}
|
class ____(Post):
content = StringField()
|
TextPost
|
python
|
HypothesisWorks__hypothesis
|
hypothesis-python/tests/cover/test_composite.py
|
{
"start": 3284,
"end": 3621
}
|
class ____(list):
pass
@given(st.data(), st.lists(st.integers()).map(MyList))
def test_does_not_change_arguments(data, ls):
# regression test for issue #1017 or other argument mutation
@st.composite
def strat(draw, arg):
draw(st.none())
return arg
ex = data.draw(strat(ls))
assert ex is ls
|
MyList
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-github/source_github/github_schema.py
|
{
"start": 94845,
"end": 95629
}
|
class ____(sgqlc.types.Enum):
"""The bypass mode for a rule or ruleset.
Enumeration Choices:
* `NONE`: Bypassing is disabled
* `ORGANIZATION`: Those with bypass permission at the organization
level can bypass
* `ORGANIZATION_ALWAYS`: Those with bypass permission at the
organization level can always bypass
* `ORGANIZATION_NONE`: Bypassing is disabled
* `ORGANIZATION_PRS_ONLY`: Those with bypass permission at the
organization level can bypass for pull requests only
* `REPOSITORY`: Those with bypass permission at the repository
level can bypass
"""
__schema__ = github_schema
__choices__ = ("NONE", "ORGANIZATION", "ORGANIZATION_ALWAYS", "ORGANIZATION_NONE", "ORGANIZATION_PRS_ONLY", "REPOSITORY")
|
RuleBypassMode
|
python
|
falconry__falcon
|
tests/test_hello.py
|
{
"start": 2894,
"end": 2966
}
|
class ____:
def on_get(self, req, resp):
pass
|
NoStatusResource
|
python
|
PrefectHQ__prefect
|
src/prefect/cli/deploy/_models.py
|
{
"start": 409,
"end": 628
}
|
class ____(BaseModel):
model_config = ConfigDict(extra="ignore")
name: Optional[str] = None
work_queue_name: Optional[str] = None
job_variables: Dict[str, Any] = Field(default_factory=dict)
|
WorkPoolConfig
|
python
|
euske__pdfminer
|
pdfminer/converter.py
|
{
"start": 4658,
"end": 4912
}
|
class ____(PDFLayoutAnalyzer):
def __init__(self, rsrcmgr, outfp, pageno=1, laparams=None):
PDFLayoutAnalyzer.__init__(self, rsrcmgr, pageno=pageno, laparams=laparams)
self.outfp = outfp
return
## TextConverter
##
|
PDFConverter
|
python
|
docker__docker-py
|
docker/errors.py
|
{
"start": 4066,
"end": 4240
}
|
class ____(DockerException):
def __init__(self, reason, build_log):
super().__init__(reason)
self.msg = reason
self.build_log = build_log
|
BuildError
|
python
|
kamyu104__LeetCode-Solutions
|
Python/create-target-array-in-the-given-order.py
|
{
"start": 31,
"end": 536
}
|
class ____(object):
def createTargetArray(self, nums, index):
"""
:type nums: List[int]
:type index: List[int]
:rtype: List[int]
"""
for i in xrange(len(nums)):
for j in xrange(i):
if index[j] >= index[i]:
index[j] += 1
result = [0]*(len(nums))
for i in xrange(len(nums)):
result[index[i]] = nums[i]
return result
# Time: O(n^2)
# Space: O(1)
import itertools
|
Solution
|
python
|
cookiecutter__cookiecutter
|
tests/test_prompt.py
|
{
"start": 14121,
"end": 17409
}
|
class ____:
"""Class to unite choices prompt related tests."""
def test_should_invoke_read_user_choice(self, mocker) -> None:
"""Verify correct function called for select(list) variables."""
prompt_choice = mocker.patch(
'cookiecutter.prompt.prompt_choice_for_config',
wraps=prompt.prompt_choice_for_config,
)
read_user_choice = mocker.patch('cookiecutter.prompt.read_user_choice')
read_user_choice.return_value = 'all'
read_user_variable = mocker.patch('cookiecutter.prompt.read_user_variable')
choices = ['landscape', 'portrait', 'all']
context = {'cookiecutter': {'orientation': choices}}
cookiecutter_dict = prompt.prompt_for_config(context)
assert not read_user_variable.called
assert prompt_choice.called
read_user_choice.assert_called_once_with(
'orientation', choices, {}, DEFAULT_PREFIX
)
assert cookiecutter_dict == {'orientation': 'all'}
def test_should_invoke_read_user_variable(self, mocker) -> None:
"""Verify correct function called for string input variables."""
read_user_variable = mocker.patch('cookiecutter.prompt.read_user_variable')
read_user_variable.return_value = 'Audrey Roy'
prompt_choice = mocker.patch('cookiecutter.prompt.prompt_choice_for_config')
read_user_choice = mocker.patch('cookiecutter.prompt.read_user_choice')
context = {'cookiecutter': {'full_name': 'Your Name'}}
cookiecutter_dict = prompt.prompt_for_config(context)
assert not prompt_choice.called
assert not read_user_choice.called
read_user_variable.assert_called_once_with(
'full_name', 'Your Name', {}, DEFAULT_PREFIX
)
assert cookiecutter_dict == {'full_name': 'Audrey Roy'}
def test_should_render_choices(self, mocker) -> None:
"""Verify Jinja2 templating engine works inside choices variables."""
read_user_choice = mocker.patch('cookiecutter.prompt.read_user_choice')
read_user_choice.return_value = 'anewproject'
read_user_variable = mocker.patch('cookiecutter.prompt.read_user_variable')
read_user_variable.return_value = 'A New Project'
rendered_choices = ['foo', 'anewproject', 'bar']
context = {
'cookiecutter': OrderedDict(
[
('project_name', 'A New Project'),
(
'pkg_name',
[
'foo',
'{{ cookiecutter.project_name|lower|replace(" ", "") }}',
'bar',
],
),
]
)
}
expected = {
'project_name': 'A New Project',
'pkg_name': 'anewproject',
}
cookiecutter_dict = prompt.prompt_for_config(context)
read_user_variable.assert_called_once_with(
'project_name', 'A New Project', {}, ' [dim][1/2][/] '
)
read_user_choice.assert_called_once_with(
'pkg_name', rendered_choices, {}, ' [dim][2/2][/] '
)
assert cookiecutter_dict == expected
|
TestReadUserChoice
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/ext/hybrid.py
|
{
"start": 43854,
"end": 44019
}
|
class ____(Protocol[_T_co]):
def __call__(
s, cls: Any, /
) -> Union[_HasClauseElement[_T_co], SQLColumnExpression[_T_co]]: ...
|
_HybridExprCallableType
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/pylint/duplicate_bases.py
|
{
"start": 88,
"end": 114
}
|
class ____(A, A):
...
|
F1
|
python
|
gevent__gevent
|
src/gevent/tests/test__threading_2.py
|
{
"start": 23515,
"end": 23628
}
|
class ____(lock_tests.SemaphoreTests):
semtype = staticmethod(threading.Semaphore)
@skipDueToHang
|
SemaphoreTests
|
python
|
tensorflow__tensorflow
|
tensorflow/python/ops/math_ops_test.py
|
{
"start": 49102,
"end": 49967
}
|
class ____(test_util.TensorFlowTestCase):
allowed_dtypes = [
dtypes.float16, dtypes.float32, dtypes.float64, dtypes.complex64,
dtypes.complex128
]
def testBasic(self):
for dtype in self.allowed_dtypes:
x = constant_op.constant([1.0, 2.0, 0.0, 4.0], dtype=dtype)
y = math_ops.reciprocal_no_nan(x)
target = constant_op.constant([1.0, 0.5, 0.0, 0.25], dtype=dtype)
self.assertAllEqual(y, target)
self.assertEqual(y.dtype.base_dtype, target.dtype.base_dtype)
def testInverse(self):
for dtype in self.allowed_dtypes:
x = np.random.choice([0, 1, 2, 4, 5], size=(5, 5, 5))
x = constant_op.constant(x, dtype=dtype)
y = math_ops.reciprocal_no_nan(math_ops.reciprocal_no_nan(x))
self.assertAllClose(y, x)
self.assertEqual(y.dtype.base_dtype, x.dtype.base_dtype)
|
ReciprocalNoNanTest
|
python
|
facebookresearch__faiss
|
tests/torch_test_contrib.py
|
{
"start": 13276,
"end": 14082
}
|
class ____(unittest.TestCase):
def test_python_kmeans(self):
""" Test the python implementation of kmeans """
ds = datasets.SyntheticDataset(32, 10000, 0, 0)
x = ds.get_train()
# bad distribution to stress-test split code
xt = x[:10000].copy()
xt[:5000] = x[0]
km_ref = faiss.Kmeans(ds.d, 100, niter=10)
km_ref.train(xt)
err = faiss.knn(xt, km_ref.centroids, 1)[0].sum()
xt_torch = torch.from_numpy(xt)
data = clustering.DatasetAssign(xt_torch)
centroids = clustering.kmeans(100, data, 10)
centroids = centroids.numpy()
err2 = faiss.knn(xt, centroids, 1)[0].sum()
# 33498.332 33380.477
# print(err, err2) 1/0
self.assertLess(err2, err * 1.1)
|
TestClustering
|
python
|
protocolbuffers__protobuf
|
python/google/protobuf/internal/type_checkers.py
|
{
"start": 6355,
"end": 7502
}
|
class ____(object):
"""Checker used for enum fields. Performs type-check and range check."""
def __init__(self, enum_type):
self._enum_type = enum_type
def CheckValue(self, proposed_value):
global _BoolWarningCount
if type(proposed_value) == bool and _BoolWarningCount > 0:
_BoolWarningCount -= 1
message = (
'%.1024r has type %s, but expected one of: %s. This warning '
'will turn into error in 7.34.0, please fix it before that.'
% (
proposed_value,
type(proposed_value),
(int,),
)
)
# TODO: Raise errors in 2026 Q1 release
warnings.warn(message)
if not isinstance(proposed_value, numbers.Integral):
message = ('%.1024r has type %s, but expected one of: %s' %
(proposed_value, type(proposed_value), (int,)))
raise TypeError(message)
if int(proposed_value) not in self._enum_type.values_by_number:
raise ValueError('Unknown enum value: %d' % proposed_value)
return proposed_value
def DefaultValue(self):
return self._enum_type.values[0].number
|
EnumValueChecker
|
python
|
sqlalchemy__sqlalchemy
|
lib/sqlalchemy/sql/roles.py
|
{
"start": 2682,
"end": 2809
}
|
class ____(Generic[_T_co], SQLRole):
"""element-typed form of ColumnsClauseRole"""
__slots__ = ()
|
TypedColumnsClauseRole
|
python
|
PyCQA__pylint
|
tests/functional/i/invalid/invalid_hash_returned.py
|
{
"start": 568,
"end": 696
}
|
class ____:
""" __hash__ returns a dict """
def __hash__(self): # [invalid-hash-returned]
return {}
|
FirstBadHash
|
python
|
openai__openai-python
|
src/openai/types/responses/tool.py
|
{
"start": 5684,
"end": 6031
}
|
class ____(BaseModel):
container: CodeInterpreterContainer
"""The code interpreter container.
Can be a container ID or an object that specifies uploaded file IDs to make
available to your code.
"""
type: Literal["code_interpreter"]
"""The type of the code interpreter tool. Always `code_interpreter`."""
|
CodeInterpreter
|
python
|
dagster-io__dagster
|
python_modules/dagster/dagster/_core/definitions/declarative_automation/operators/dep_operators.py
|
{
"start": 7552,
"end": 8885
}
|
class ____(DepsAutomationCondition[T_EntityKey]):
@property
def base_name(self) -> str:
return "ANY_DEPS_MATCH"
@property
def operator_type(self) -> OperatorType:
return "or"
async def evaluate( # pyright: ignore[reportIncompatibleMethodOverride]
self, context: AutomationContext[T_EntityKey]
) -> AutomationResult[T_EntityKey]:
dep_results = []
true_subset = context.get_empty_subset()
for i, dep_key in enumerate(sorted(self._get_dep_keys(context.key, context.asset_graph))):
dep_result = await context.for_child_condition(
child_condition=EntityMatchesCondition(key=dep_key, operand=self.operand),
child_indices=[ # Prefer a non-indexed ID in case asset keys move around, but fall back to the indexed one for back-compat
None,
i,
],
candidate_subset=context.candidate_subset,
).evaluate_async()
dep_results.append(dep_result)
true_subset = true_subset.compute_union(dep_result.true_subset)
true_subset = context.candidate_subset.compute_intersection(true_subset)
return AutomationResult(context, true_subset=true_subset, child_results=dep_results)
@whitelist_for_serdes
|
AnyDepsCondition
|
python
|
pypa__warehouse
|
tests/unit/admin/views/test_organizations.py
|
{
"start": 52379,
"end": 57463
}
|
class ____:
def test_delete_manual_activation_success(self, db_request, monkeypatch):
organization = OrganizationFactory.create(name="test-org")
OrganizationManualActivationFactory.create(organization=organization)
db_request.matchdict = {"organization_id": str(organization.id)}
db_request.POST = MultiDict({"confirm": "test-org"})
db_request.route_path = pretend.call_recorder(
lambda *a, **kw: "/admin/organizations/"
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
organization.record_event = pretend.call_recorder(lambda *a, **kw: None)
organization_service = pretend.stub(
get_organization=pretend.call_recorder(lambda id: organization)
)
monkeypatch.setattr(
db_request, "find_service", lambda iface, context: organization_service
)
result = views.delete_manual_activation(db_request)
assert isinstance(result, HTTPSeeOther)
# Check that manual activation was deleted
remaining_activations = (
db_request.db.query(OrganizationManualActivation)
.filter(OrganizationManualActivation.organization_id == organization.id)
.count()
)
assert remaining_activations == 0
# Check success flash message
assert len(db_request.session.flash.calls) == 1
call = db_request.session.flash.calls[0]
assert "Manual activation removed from" in call.args[0]
assert call.kwargs == {"queue": "success"}
# Check event was recorded
assert len(organization.record_event.calls) == 1
call = organization.record_event.calls[0]
assert call.kwargs["tag"] == "admin:organization:manual_activation:delete"
def test_delete_manual_activation_no_confirmation(self, db_request, monkeypatch):
organization = OrganizationFactory.create(name="test-org")
OrganizationManualActivationFactory.create(organization=organization)
db_request.matchdict = {"organization_id": str(organization.id)}
db_request.POST = MultiDict({"confirm": "wrong-name"})
db_request.route_path = pretend.call_recorder(
lambda *a, **kw: "/admin/organizations/"
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
organization_service = pretend.stub(
get_organization=pretend.call_recorder(lambda id: organization)
)
monkeypatch.setattr(
db_request, "find_service", lambda iface, context: organization_service
)
result = views.delete_manual_activation(db_request)
assert isinstance(result, HTTPSeeOther)
# Check error flash message
assert len(db_request.session.flash.calls) == 1
call = db_request.session.flash.calls[0]
assert call.args[0] == "Confirm the request"
assert call.kwargs == {"queue": "error"}
# Manual activation should still exist
remaining_activations = (
db_request.db.query(OrganizationManualActivation)
.filter(OrganizationManualActivation.organization_id == organization.id)
.count()
)
assert remaining_activations == 1
def test_delete_manual_activation_not_found(self, db_request, monkeypatch):
organization = OrganizationFactory.create(name="test-org")
db_request.matchdict = {"organization_id": str(organization.id)}
db_request.POST = MultiDict({"confirm": "test-org"})
db_request.route_path = pretend.call_recorder(
lambda *a, **kw: "/admin/organizations/"
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
organization_service = pretend.stub(
get_organization=pretend.call_recorder(lambda id: organization)
)
monkeypatch.setattr(
db_request, "find_service", lambda iface, context: organization_service
)
result = views.delete_manual_activation(db_request)
assert isinstance(result, HTTPSeeOther)
# Check error flash message
assert len(db_request.session.flash.calls) == 1
call = db_request.session.flash.calls[0]
assert "has no manual activation to delete" in call.args[0]
assert call.kwargs == {"queue": "error"}
def test_delete_manual_activation_organization_not_found(
self, db_request, monkeypatch
):
db_request.matchdict = {
"organization_id": "00000000-0000-0000-0000-000000000000"
}
organization_service = pretend.stub(
get_organization=pretend.call_recorder(lambda id: None)
)
monkeypatch.setattr(
db_request, "find_service", lambda iface, context: organization_service
)
with pytest.raises(HTTPNotFound):
views.delete_manual_activation(db_request)
|
TestDeleteManualActivation
|
python
|
apache__airflow
|
providers/google/tests/unit/google/cloud/operators/test_cloud_storage_transfer_service.py
|
{
"start": 20380,
"end": 22787
}
|
class ____:
@mock.patch(
"airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook"
)
def test_job_run(self, mock_hook):
mock_hook.return_value.run_transfer_job.return_value = VALID_OPERATION
op = CloudDataTransferServiceRunJobOperator(
job_name=JOB_NAME,
project_id=GCP_PROJECT_ID,
task_id="task-id",
google_impersonation_chain=IMPERSONATION_CHAIN,
)
result = op.execute(context=mock.MagicMock())
mock_hook.assert_called_once_with(
api_version="v1",
gcp_conn_id="google_cloud_default",
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_hook.return_value.run_transfer_job.assert_called_once_with(
job_name=JOB_NAME, project_id=GCP_PROJECT_ID
)
assert result == VALID_OPERATION
# Setting all the operator's input parameters as templated dag_ids
# (could be anything else) just to test if the templating works for all
# fields
@pytest.mark.db_test
@mock.patch(
"airflow.providers.google.cloud.operators.cloud_storage_transfer_service.CloudDataTransferServiceHook"
)
def test_job_run_with_templates(self, _, create_task_instance_of_operator, session):
dag_id = "test_job_run_with_templates"
ti = create_task_instance_of_operator(
CloudDataTransferServiceRunJobOperator,
dag_id=dag_id,
job_name="{{ dag.dag_id }}",
project_id="{{ dag.dag_id }}",
gcp_conn_id="{{ dag.dag_id }}",
api_version="{{ dag.dag_id }}",
google_impersonation_chain="{{ dag.dag_id }}",
task_id=TASK_ID,
)
session.add(ti)
session.commit()
ti.render_templates()
assert dag_id == ti.task.job_name
assert dag_id == ti.task.project_id
assert dag_id == ti.task.gcp_conn_id
assert dag_id == ti.task.api_version
assert dag_id == ti.task.google_impersonation_chain
def test_job_run_should_throw_ex_when_name_none(self):
op = CloudDataTransferServiceRunJobOperator(job_name="", task_id="task-id")
with pytest.raises(AirflowException, match="The required parameter 'job_name' is empty or None"):
op.execute(context=mock.MagicMock())
|
TestGcpStorageTransferJobRunOperator
|
python
|
pytorch__pytorch
|
benchmarks/operator_benchmark/pt/qobserver_test.py
|
{
"start": 3262,
"end": 4284
}
|
class ____(op_bench.TorchBenchmarkBase):
def init(self, C, M, N, dtype, qscheme, op_func, device):
self.f_input = torch.rand(C, M, N, device=device)
self.q_observer = op_func(dtype=dtype, qscheme=qscheme).to(device)
self.q_observer(self.f_input)
self.inputs = {}
def forward(self):
return self.q_observer.calculate_qparams()
op_bench.generate_pt_tests_from_op_list(
qobserver_per_tensor_list,
qobserver_per_tensor_configs_short + qobserver_per_tensor_configs_long,
QObserverBenchmark,
)
op_bench.generate_pt_tests_from_op_list(
qobserver_per_channel_list,
qobserver_per_channel_configs_short + qobserver_per_channel_configs_long,
QObserverBenchmark,
)
op_bench.generate_pt_tests_from_op_list(
q_hist_observer_list,
q_hist_observer_per_tensor_configs_short + q_hist_observer_per_tensor_configs_long,
QObserverBenchmarkCalculateQparams,
)
if __name__ == "__main__":
op_bench.benchmark_runner.main()
|
QObserverBenchmarkCalculateQparams
|
python
|
ansible__ansible
|
lib/ansible/module_utils/facts/network/aix.py
|
{
"start": 5892,
"end": 5988
}
|
class ____(NetworkCollector):
_fact_class = AIXNetwork
_platform = 'AIX'
|
AIXNetworkCollector
|
python
|
scikit-learn__scikit-learn
|
sklearn/utils/tests/test_deprecation.py
|
{
"start": 528,
"end": 603
}
|
class ____:
@deprecated()
def __init__(self):
pass
|
MockClass3
|
python
|
pypa__pipenv
|
pipenv/exceptions.py
|
{
"start": 3292,
"end": 3834
}
|
class ____(PipenvException):
def __init__(self, contents="", error_text=""):
self.error_text = error_text
self.contents = contents
PipenvException.__init__(self, contents)
def show(self, file=None):
console = Console(stderr=True, file=file, highlight=False)
console.print(
f"[bold][red]Failed parsing JSON results:[/red][/bold]: {self.contents}"
)
if self.error_text:
console.print(f"[bold][red]ERROR TEXT:[/red][/bold]: {self.error_text}")
|
JSONParseError
|
python
|
yandexdataschool__Practical_RL
|
week06_policy_based/atari_wrappers.py
|
{
"start": 10707,
"end": 11227
}
|
class ____(SummariesBase):
"""Writes env summaries using Tensorboard."""
def __init__(self, env, prefix=None, running_mean_size=100, step_var=None):
super().__init__(env, prefix, running_mean_size, step_var)
self.writer = SummaryWriter(f"logs/{self.prefix}")
def add_summary(self, name, value):
if isinstance(value, dict):
self.writer.add_scalars(name, value, self.step_var)
else:
self.writer.add_scalar(name, value, self.step_var)
|
TensorboardSummaries
|
python
|
pypa__pipenv
|
pipenv/vendor/plette/models/hashes.py
|
{
"start": 51,
"end": 1853
}
|
class ____(DataModel):
"""A hash.
"""
item_class = "Hash"
__SCHEMA__ = {
}
__OPTIONAL__ = {
"name": str,
"md5": str,
"sha256": str,
"digest": str,
}
def __init__(self, data):
self.validate(data)
self._data = data
if "name" in data:
self.name = data["name"]
try:
self.digest = data["digest"]
except KeyError:
self.digest = data["value"]
elif "md5" in data:
self.name = "md5"
self.digest = data["md5"]
elif "sha256" in data:
self.name = "sha256"
self.digest = data["sha256"]
@classmethod
def validate(cls, data):
for k, v in cls.__SCHEMA__.items():
if k not in data:
raise DataValidationError(f"Missing required field: {k}")
if not isinstance(data[k], v):
raise DataValidationError(f"Invalid type for field {k}: {type(data[k])}")
@classmethod
def from_hash(cls, ins):
"""Interpolation to the hash result of `hashlib`.
"""
return cls(data={ins.name: ins.hexdigest()})
@classmethod
def from_line(cls, value):
try:
name, value = value.split(":", 1)
except ValueError:
name = "sha256"
return cls(data={"name":name, "value": value})
def __eq__(self, other):
if not isinstance(other, Hash):
raise TypeError("cannot compare Hash with {0!r}".format(
type(other).__name__,
))
return self._data == other._data
@property
def value(self):
return self.digest
def as_line(self):
return "{0[0]}:{0[1]}".format(next(iter(self._data.items())))
|
Hash
|
python
|
spack__spack
|
lib/spack/spack/vendor/macholib/mach_o.py
|
{
"start": 43393,
"end": 43486
}
|
class ____(Structure):
_fields_ = (("magic", p_uint32), ("nfat_arch", p_uint32))
|
fat_header
|
python
|
apache__airflow
|
providers/mysql/tests/unit/mysql/hooks/test_mysql.py
|
{
"start": 19188,
"end": 21686
}
|
class ____:
def setup_method(self):
args = {"owner": "airflow", "start_date": DEFAULT_DATE}
dag = DAG(TEST_DAG_ID, schedule=None, default_args=args)
self.dag = dag
def teardown_method(self):
drop_tables = {"test_mysql_to_mysql", "test_airflow"}
with closing(MySqlHook().get_conn()) as conn:
with closing(conn.cursor()) as cursor:
for table in drop_tables:
cursor.execute(f"DROP TABLE IF EXISTS {table}")
@pytest.mark.parametrize("client", ["mysqlclient", "mysql-connector-python"])
@pytest.mark.parametrize("table", ["test_airflow", "where"])
@mock.patch.dict(
"os.environ",
{
"AIRFLOW_CONN_AIRFLOW_DB": "mysql://root@mysql/airflow?charset=utf8mb4",
},
)
def test_mysql_hook_test_bulk_load(self, client, table, tmp_path):
with MySqlContext(client):
records = ("foo", "bar", "baz")
path = tmp_path / "testfile"
path.write_text("\n".join(records))
hook = MySqlHook("airflow_db", local_infile=True)
with closing(hook.get_conn()) as conn, closing(conn.cursor()) as cursor:
cursor.execute(
f"""
CREATE TABLE IF NOT EXISTS `{table}`(
dummy VARCHAR(50)
)
"""
)
cursor.execute(f"TRUNCATE TABLE `{table}`")
hook.bulk_load(table, os.fspath(path))
cursor.execute(f"SELECT dummy FROM `{table}`")
results = tuple(result[0] for result in cursor.fetchall())
assert sorted(results) == sorted(records)
@pytest.mark.parametrize("client", ["mysqlclient", "mysql-connector-python"])
@mock.patch("airflow.providers.mysql.hooks.mysql.MySqlHook.get_conn")
def test_mysql_hook_test_bulk_dump_mock(self, mock_get_conn, client):
with MySqlContext(client):
mock_execute = mock.MagicMock()
mock_get_conn.return_value.cursor.return_value.execute = mock_execute
hook = MySqlHook("airflow_db")
table = "INFORMATION_SCHEMA.TABLES"
tmp_file = "/path/to/output/file"
hook.bulk_dump(table, tmp_file)
assert mock_execute.call_count == 1
query = f"SELECT * INTO OUTFILE %s FROM `{table}`"
assert_equal_ignore_multiple_spaces(mock_execute.call_args.args[0], query)
|
TestMySql
|
python
|
pytorch__pytorch
|
torch/utils/benchmark/utils/valgrind_wrapper/timer_interface.py
|
{
"start": 950,
"end": 5737
}
|
class ____:
"""Container for manipulating Callgrind results.
It supports:
1) Addition and subtraction to combine or diff results.
2) Tuple-like indexing.
3) A `denoise` function which strips CPython calls which are known to
be non-deterministic and quite noisy.
4) Two higher order methods (`filter` and `transform`) for custom
manipulation.
"""
_data: tuple[FunctionCount, ...]
inclusive: bool
truncate_rows: bool = True
# For normal use, torch._tensor_str.PRINT_OPTS.linewidth determines
# the print settings. This is simply to allow hermetic unit tests.
_linewidth: int | None = None
def __iter__(self) -> Iterator[FunctionCount]:
yield from self._data
def __len__(self) -> int:
return len(self._data)
def __getitem__(self, item: Any) -> Union[FunctionCount, "FunctionCounts"]:
data: FunctionCount | tuple[FunctionCount, ...] = self._data[item]
return (
FunctionCounts(cast(tuple[FunctionCount, ...], data), self.inclusive, truncate_rows=False)
if isinstance(data, tuple) else data
)
def __repr__(self) -> str:
count_len = 0
for c, _ in self:
# Account for sign in string length.
count_len = max(count_len, len(str(c)) + int(c < 0))
lines = []
linewidth = self._linewidth or torch._tensor_str.PRINT_OPTS.linewidth
fn_str_len = max(linewidth - count_len - 4, 40)
for c, fn in self:
if len(fn) > fn_str_len:
left_len = int((fn_str_len - 5) // 2)
fn = fn[:left_len] + " ... " + fn[-(fn_str_len - left_len - 5):]
lines.append(f" {c:>{count_len}} {fn}")
if self.truncate_rows and len(lines) > 18:
lines = lines[:9] + ["...".rjust(count_len + 2)] + lines[-9:]
if not self.inclusive:
lines.extend(["", f"Total: {self.sum()}"])
return "\n".join([super().__repr__()] + lines)
def __add__(
self,
other: "FunctionCounts",
) -> "FunctionCounts":
return self._merge(other, lambda c: c)
def __sub__(
self,
other: "FunctionCounts",
) -> "FunctionCounts":
return self._merge(other, operator.neg)
def __mul__(self, other: int | float) -> "FunctionCounts":
return self._from_dict({
fn: int(c * other) for c, fn in self._data
}, self.inclusive)
def transform(self, map_fn: Callable[[str], str]) -> "FunctionCounts":
"""Apply `map_fn` to all of the function names.
This can be used to regularize function names (e.g. stripping irrelevant
parts of the file path), coalesce entries by mapping multiple functions
to the same name (in which case the counts are added together), etc.
"""
counts: collections.defaultdict[str, int] = collections.defaultdict(int)
for c, fn in self._data:
counts[map_fn(fn)] += c
return self._from_dict(counts, self.inclusive)
def filter(self, filter_fn: Callable[[str], bool]) -> "FunctionCounts":
"""Keep only the elements where `filter_fn` applied to function name returns True."""
return FunctionCounts(tuple(i for i in self if filter_fn(i.function)), self.inclusive)
def sum(self) -> int:
return sum(c for c, _ in self)
def denoise(self) -> "FunctionCounts":
"""Remove known noisy instructions.
Several instructions in the CPython interpreter are rather noisy. These
instructions involve unicode to dictionary lookups which Python uses to
map variable names. FunctionCounts is generally a content agnostic
container, however this is sufficiently important for obtaining
reliable results to warrant an exception."""
return self.filter(lambda fn: "dictobject.c:lookdict_unicode" not in fn)
def _merge(
self,
second: "FunctionCounts",
merge_fn: Callable[[int], int]
) -> "FunctionCounts":
if self.inclusive != second.inclusive:
raise AssertionError("Cannot merge inclusive and exclusive counts.")
counts: collections.defaultdict[str, int] = collections.defaultdict(int)
for c, fn in self:
counts[fn] += c
for c, fn in second:
counts[fn] += merge_fn(c)
return self._from_dict(counts, self.inclusive)
@staticmethod
def _from_dict(counts: dict[str, int], inclusive: bool) -> "FunctionCounts":
flat_counts = (FunctionCount(c, fn) for fn, c in counts.items() if c)
return FunctionCounts(tuple(sorted(flat_counts, reverse=True)), inclusive)
@dataclasses.dataclass(repr=False, eq=False, frozen=True)
|
FunctionCounts
|
python
|
mlflow__mlflow
|
mlflow/telemetry/events.py
|
{
"start": 382,
"end": 638
}
|
class ____(Event):
name: str = "create_experiment"
@classmethod
def parse_result(cls, result: Any) -> dict[str, Any] | None:
# create_experiment API returns the experiment id
return {"experiment_id": result}
|
CreateExperimentEvent
|
python
|
great-expectations__great_expectations
|
tests/metrics/test_metric.py
|
{
"start": 3553,
"end": 4814
}
|
class ____:
@pytest.mark.unit
def test_two_identical_metrics_with_same_batch_id_returns_same_metric_id(self):
metric_1 = ColumnValuesAbove(
column=COLUMN,
min_value=42,
)
metric_2 = ColumnValuesAbove(
column=COLUMN,
min_value=42,
)
assert metric_1.metric_id_for_batch(BATCH_ID) == metric_2.metric_id_for_batch(BATCH_ID)
@pytest.mark.unit
def test_metric_with_different_value_kwargs_return_different_ids(self):
metric_1 = ColumnValuesAbove(
column=COLUMN,
min_value=42,
)
metric_2 = ColumnValuesAbove(
column=COLUMN,
min_value=43,
)
assert metric_1.metric_id_for_batch(BATCH_ID) != metric_2.metric_id_for_batch(BATCH_ID)
@pytest.mark.unit
def test_metric_with_different_batch_ids_return_different_ids(self):
metric_1 = ColumnValuesAbove(
column=COLUMN,
min_value=42,
)
metric_2 = ColumnValuesAbove(
column=COLUMN,
min_value=42,
)
assert metric_1.metric_id_for_batch(BATCH_ID) != metric_2.metric_id_for_batch(
BATCH_ID + "_another"
)
|
TestMetricIdFromBatch
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_chart_format03.py
|
{
"start": 350,
"end": 2750
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_format03.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [46175744, 46319488]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$B$1:$B$5",
"border": {"color": "yellow"},
"fill": {"color": "red"},
}
)
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$C$1:$C$5",
}
)
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
def test_create_file_with_color_type(self):
"""Test the creation of an XlsxWriter file with chart formatting."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [46175744, 46319488]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$B$1:$B$5",
"border": {"color": Color("yellow")},
"fill": {"color": Color("red")},
}
)
chart.add_series(
{
"categories": "=Sheet1!$A$1:$A$5",
"values": "=Sheet1!$C$1:$C$5",
}
)
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
ray-project__ray
|
python/ray/tests/test_memory_pressure.py
|
{
"start": 2760,
"end": 18565
}
|
class ____:
def __init__(self):
self.leaks = []
def allocate(self, allocate_bytes: int, sleep_time_ms: int = 0):
# divide by 8 as each element in the array occupies 8 bytes
new_list = [0] * ceil(allocate_bytes / 8)
self.leaks.append(new_list)
time.sleep(sleep_time_ms / 1000)
def get_worker_id(self):
return ray._private.worker.global_worker.core_worker.get_worker_id().hex()
def get_actor_id(self):
return ray._private.worker.global_worker.core_worker.get_actor_id().hex()
def get_additional_bytes_to_reach_memory_usage_pct(pct: float) -> int:
used = get_used_memory()
total = get_system_memory()
bytes_needed = int(total * pct) - used
assert bytes_needed > 0, "node has less memory than what is requested"
return bytes_needed
def has_metric_tagged_with_value(
addr, tag, value, timeseries: PrometheusTimeseries
) -> bool:
metrics = raw_metric_timeseries(addr, timeseries)
for name, samples in metrics.items():
for sample in samples:
if tag in set(sample.labels.values()) and sample.value == value:
return True
return False
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
@pytest.mark.parametrize("restartable", [False, True])
def test_restartable_actor_throws_oom_error(ray_with_memory_monitor, restartable: bool):
addr = ray_with_memory_monitor
if restartable:
leaker = Leaker.options(max_restarts=1, max_task_retries=1).remote()
else:
leaker = Leaker.options(max_restarts=0, max_task_retries=0).remote()
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(
memory_usage_threshold + 0.1
)
with pytest.raises(ray.exceptions.OutOfMemoryError):
ray.get(leaker.allocate.remote(bytes_to_alloc, memory_monitor_refresh_ms * 3))
timeseries = PrometheusTimeseries()
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="MemoryManager.ActorEviction.Total",
value=2.0 if restartable else 1.0,
timeseries=timeseries,
)
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="Leaker.__init__",
value=2.0 if restartable else 1.0,
timeseries=timeseries,
)
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
def test_restartable_actor_oom_retry_off_throws_oom_error(
ray_with_memory_monitor_no_oom_retry,
):
addr = ray_with_memory_monitor_no_oom_retry
leaker = Leaker.options(max_restarts=1, max_task_retries=1).remote()
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(
memory_usage_threshold + 0.1
)
with pytest.raises(ray.exceptions.OutOfMemoryError) as _:
ray.get(leaker.allocate.remote(bytes_to_alloc, memory_monitor_refresh_ms * 3))
timeseries = PrometheusTimeseries()
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="MemoryManager.ActorEviction.Total",
value=2.0,
timeseries=timeseries,
)
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="Leaker.__init__",
value=2.0,
timeseries=timeseries,
)
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
def test_non_retryable_task_killed_by_memory_monitor_with_oom_error(
ray_with_memory_monitor,
):
addr = ray_with_memory_monitor
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(1.1)
with pytest.raises(ray.exceptions.OutOfMemoryError) as _:
ray.get(allocate_memory.options(max_retries=0).remote(bytes_to_alloc))
timeseries = PrometheusTimeseries()
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="MemoryManager.TaskEviction.Total",
value=1.0,
timeseries=timeseries,
)
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="allocate_memory",
value=1.0,
timeseries=timeseries,
)
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
def test_memory_pressure_kill_newest_worker(ray_with_memory_monitor):
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(
memory_usage_threshold - 0.1
)
actor_ref = Leaker.options(name="actor").remote()
ray.get(actor_ref.allocate.remote(bytes_to_alloc))
with pytest.raises(ray.exceptions.OutOfMemoryError) as _:
ray.get(
allocate_memory.options(max_retries=0).remote(allocate_bytes=bytes_to_alloc)
)
actors = ray.util.list_named_actors()
assert len(actors) == 1
assert "actor" in actors
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
def test_memory_pressure_kill_task_if_actor_submitted_task_first(
ray_with_memory_monitor,
):
actor_ref = Leaker.options(name="leaker1").remote()
ray.get(actor_ref.allocate.remote(10))
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(
memory_usage_threshold - 0.1
)
task_ref = allocate_memory.options(max_retries=0).remote(
allocate_bytes=bytes_to_alloc, allocate_interval_s=0, post_allocate_sleep_s=1000
)
ray.get(actor_ref.allocate.remote(bytes_to_alloc))
with pytest.raises(ray.exceptions.OutOfMemoryError) as _:
ray.get(task_ref)
actors = ray.util.list_named_actors()
assert len(actors) == 1
assert "leaker1" in actors
@pytest.mark.asyncio
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
async def test_actor_oom_logs_error(ray_with_memory_monitor):
first_actor = Leaker.options(name="first_random_actor", max_restarts=0).remote()
ray.get(first_actor.get_worker_id.remote())
oom_actor = Leaker.options(name="the_real_oom_actor", max_restarts=0).remote()
worker_id = ray.get(oom_actor.get_worker_id.remote())
actor_id = ray.get(oom_actor.get_actor_id.remote())
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(1)
with pytest.raises(ray.exceptions.OutOfMemoryError) as _:
ray.get(
oom_actor.allocate.remote(bytes_to_alloc, memory_monitor_refresh_ms * 3)
)
state_api_client = get_local_state_client()
result = await state_api_client.get_all_worker_info(timeout=5, limit=10)
verified = False
for worker in result.worker_table_data:
if worker.worker_address.worker_id.hex() == worker_id:
assert expected_worker_eviction_message in worker.exit_detail
verified = True
assert verified
result = await state_api_client.get_all_actor_info(timeout=5, limit=10)
verified = False
for actor in result.actor_table_data:
if actor.actor_id.hex() == actor_id:
assert actor.death_cause
assert actor.death_cause.oom_context
assert (
expected_worker_eviction_message
in actor.death_cause.oom_context.error_message
)
verified = True
assert verified
# TODO(clarng): verify log info once state api can dump log info
@pytest.mark.asyncio
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
async def test_task_oom_logs_error(ray_with_memory_monitor):
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(1)
with pytest.raises(ray.exceptions.OutOfMemoryError) as _:
ray.get(
allocate_memory.options(max_retries=0, name="allocate_memory").remote(
allocate_bytes=bytes_to_alloc,
allocate_interval_s=0,
post_allocate_sleep_s=1000,
)
)
state_api_client = get_local_state_client()
result = await state_api_client.get_all_worker_info(timeout=5, limit=10)
verified = False
for worker in result.worker_table_data:
if worker.exit_detail:
assert expected_worker_eviction_message in worker.exit_detail
verified = True
assert verified
wait_for_condition(
verify_failed_task,
name="allocate_memory",
error_type="OUT_OF_MEMORY",
error_message="Task was killed due to the node running low on memory",
)
# TODO(clarng): verify log info once state api can dump log info
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
def test_task_oom_no_oom_retry_fails_immediately(
ray_with_memory_monitor_no_oom_retry,
):
addr = ray_with_memory_monitor_no_oom_retry
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(1.1)
with pytest.raises(ray.exceptions.OutOfMemoryError) as _:
ray.get(
allocate_memory.options(max_retries=1).remote(
allocate_bytes=bytes_to_alloc, post_allocate_sleep_s=100
)
)
timeseries = PrometheusTimeseries()
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="MemoryManager.TaskEviction.Total",
value=1.0,
timeseries=timeseries,
)
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="allocate_memory",
value=1.0,
timeseries=timeseries,
)
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
def test_task_oom_only_uses_oom_retry(
ray_with_memory_monitor,
):
addr = ray_with_memory_monitor
leaker = Leaker.options(max_restarts=1, max_task_retries=1).remote()
ray.get(leaker.allocate.remote(1))
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(1.1)
with pytest.raises(ray.exceptions.OutOfMemoryError) as _:
ray.get(
allocate_memory.options(max_retries=-1).remote(
allocate_bytes=bytes_to_alloc, post_allocate_sleep_s=100
)
)
timeseries = PrometheusTimeseries()
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="MemoryManager.TaskEviction.Total",
value=task_oom_retries + 1,
timeseries=timeseries,
)
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="allocate_memory",
value=task_oom_retries + 1,
timeseries=timeseries,
)
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
def test_newer_task_not_retriable_kill_older_retriable_task_first(
ray_with_memory_monitor,
):
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(
memory_usage_threshold - 0.1
)
retriable_task_ref = allocate_memory.options(max_retries=1).remote(
allocate_bytes=bytes_to_alloc, post_allocate_sleep_s=5
)
actor_ref = Leaker.options(name="actor", max_restarts=0).remote()
non_retriable_actor_ref = actor_ref.allocate.remote(bytes_to_alloc)
ray.get(non_retriable_actor_ref)
with pytest.raises(ray.exceptions.OutOfMemoryError) as _:
ray.get(retriable_task_ref)
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
def test_put_object_task_usage_slightly_below_limit_does_not_crash():
with ray.init(
num_cpus=1,
object_store_memory=2 << 30,
_system_config={
"memory_monitor_refresh_ms": 50,
"memory_usage_threshold": 0.98,
},
):
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(0.9)
print(bytes_to_alloc)
ray.get(
allocate_memory.options(max_retries=0).remote(
allocate_bytes=bytes_to_alloc,
),
timeout=90,
)
entries = int((1 << 30) / 8)
obj_ref = ray.put(np.random.rand(entries))
ray.get(obj_ref)
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(0.9)
print(bytes_to_alloc)
ray.get(
allocate_memory.options(max_retries=0).remote(
allocate_bytes=bytes_to_alloc,
),
timeout=90,
)
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
def test_last_task_of_the_group_fail_immediately():
@ray.remote(max_retries=-1)
def infinite_retry_task():
chunks = []
bytes_per_chunk = 1024 * 1024 * 1024
while True:
chunks.append([0] * bytes_per_chunk)
time.sleep(5)
with ray.init() as addr:
timeseries = PrometheusTimeseries()
with pytest.raises(ray.exceptions.OutOfMemoryError) as _:
ray.get(infinite_retry_task.remote())
wait_for_condition(
has_metric_tagged_with_value,
timeout=10,
retry_interval_ms=100,
addr=addr,
tag="MemoryManager.TaskEviction.Total",
value=1.0,
timeseries=timeseries,
)
@pytest.mark.skipif(
sys.platform != "linux" and sys.platform != "linux2",
reason="memory monitor only on linux currently",
)
def test_one_actor_max_lifo_kill_next_actor(shutdown_only):
with ray.init(
_system_config={
"memory_usage_threshold": 0.7,
"memory_monitor_refresh_ms": memory_monitor_refresh_ms,
},
):
bytes_to_alloc = get_additional_bytes_to_reach_memory_usage_pct(0.5)
first_actor = Leaker.options(name="first_actor").remote()
ray.get(first_actor.allocate.remote(bytes_to_alloc))
actors = ray.util.list_named_actors()
assert len(actors) == 1
assert "first_actor" in actors
second_actor = Leaker.options(name="second_actor").remote()
with pytest.raises(ray.exceptions.OutOfMemoryError):
ray.get(
second_actor.allocate.remote(
bytes_to_alloc, memory_monitor_refresh_ms * 3
)
)
actors = ray.util.list_named_actors()
assert len(actors) == 1, actors
assert "first_actor" in actors
assert "second_actor" not in actors
third_actor = Leaker.options(name="third_actor").remote()
with pytest.raises(ray.exceptions.OutOfMemoryError):
ray.get(
third_actor.allocate.remote(
bytes_to_alloc, memory_monitor_refresh_ms * 3
)
)
actors = ray.util.list_named_actors()
assert len(actors) == 1
assert "first_actor" in actors
assert "second_actor" not in actors
assert "third_actor" not in actors
if __name__ == "__main__":
sys.exit(pytest.main(["-sv", __file__]))
|
Leaker
|
python
|
getsentry__sentry
|
tests/sentry/auth/services/test_model.py
|
{
"start": 241,
"end": 898
}
|
class ____(TestCase):
def setUp(self) -> None:
self.user = self.create_user()
self.org = self.create_organization()
def test_serializes_correct_fields(self) -> None:
internal_app = self.create_internal_integration(organization=self.org)
api_token = self.create_internal_integration_token(
user=self.user, internal_integration=internal_app
)
serialized_token = serialize_api_token(api_token)
assert f"{serialized_token} is so skibidi".lower().find("token") == -1
assert f"{serialized_token} is so skibidi".lower().find("hashed_token") == -1
@control_silo_test
|
TestRpcApiToken
|
python
|
tensorflow__tensorflow
|
tensorflow/python/client/session.py
|
{
"start": 9020,
"end": 11808
}
|
class ____(object):
"""Definition of the interface provided by fetch mappers.
Fetch mappers are utility classes used by the _FetchHandler to handle
arbitrary structures for the `fetch` argument to `Session.run()`.
The `fetch` argument can be of various shapes: single tensor or op, list of
fetches, tuple of fetches, namedtuple of fetches, or dict of fetches. The
structures can be arbitrarily nested.
The low level run() API only wants a list of tensor or op names. The various
`_FetchMapper` subclasses below take care of handling the different shapes:
uniquifying the fetches, and constructing results with the original shape.
"""
def unique_fetches(self):
"""Return the list of unique tensors or ops needed by this fetch mapper.
Returns:
A list of tensors or ops.
"""
raise NotImplementedError(
'unique_fetches must be implemented by subclasses')
def build_results(self, values):
"""Build results that match the original shape of the fetch.
Args:
values: List of values returned by run(). The values correspond exactly to
the list tensors or ops returned by unique_fetches().
Returns:
A struct of the same shape as the original fetch object handled by
this fetch mapper. In the returned struct, the original fetches are
replaced by their fetched values.
"""
raise NotImplementedError('build_results must be implemented by subclasses')
@staticmethod
def for_fetch(fetch):
"""Creates fetch mapper that handles the structure of `fetch`.
The default graph must be the one from which we want to fetch values when
this function is called.
Args:
fetch: An arbitrary fetch structure: singleton, list, tuple, namedtuple,
or dict.
Returns:
An instance of a subclass of `_FetchMapper` that handles the shape.
"""
if fetch is None:
raise TypeError(f'Argument `fetch` = {fetch} has invalid type '
f'"{type(fetch).__name__}". Cannot be None')
elif isinstance(fetch, (list, tuple)):
# NOTE(touts): This is also the code path for namedtuples.
return _ListFetchMapper(fetch)
elif isinstance(fetch, collections_abc.Mapping):
return _DictFetchMapper(fetch)
elif _is_attrs_instance(fetch):
return _AttrsFetchMapper(fetch)
else:
# Look for a handler in the registered expansions.
for tensor_type, fetch_fn, _, _ in _REGISTERED_EXPANSIONS:
if isinstance(fetch, tensor_type):
fetches, contraction_fn = fetch_fn(fetch)
return _ElementFetchMapper(fetches, contraction_fn)
# Did not find anything.
raise TypeError(f'Argument `fetch` = {fetch} has invalid type '
f'"{type(fetch).__name__}"')
|
_FetchMapper
|
python
|
django__django
|
tests/many_to_one/models.py
|
{
"start": 769,
"end": 992
}
|
class ____(models.Model):
id = models.BigAutoField(primary_key=True)
country = models.ForeignKey(
Country, models.CASCADE, related_name="cities", null=True
)
name = models.CharField(max_length=50)
|
City
|
python
|
dagster-io__dagster
|
python_modules/dagster/dagster/_core/storage/dagster_run.py
|
{
"start": 4498,
"end": 4812
}
|
class ____(IHaveNew):
"""Utility class to help calculate the immediate impact of launching a run on the op concurrency
slots that will be available for other runs.
"""
root_key_counts: Mapping[str, int]
has_unconstrained_root_nodes: bool
all_pools: Optional[Set[str]] = None
|
RunOpConcurrency
|
python
|
getsentry__sentry
|
src/sentry/web/frontend/js_sdk_loader.py
|
{
"start": 1251,
"end": 1425
}
|
class ____(TypedDict):
isLazy: bool
config: NotRequired[SdkConfig]
jsSdkUrl: NotRequired[str]
publicKey: NotRequired[str | None]
@region_silo_view
|
LoaderContext
|
python
|
walkccc__LeetCode
|
solutions/628. Maximum Product of Three Numbers/628-2.py
|
{
"start": 0,
"end": 613
}
|
class ____:
def maximumProduct(self, nums: list[int]) -> int:
min1 = inf # the minimum
min2 = inf # the second minimum
max1 = -inf # the maximum
max2 = -inf # the second maximum
max3 = -inf # the third maximum
for num in nums:
if num <= min1:
min2 = min1
min1 = num
elif num <= min2:
min2 = num
if num >= max1:
max3 = max2
max2 = max1
max1 = num
elif num >= max2:
max3 = max2
max2 = num
elif num >= max3:
max3 = num
return max(max1 * min1 * min2, max1 * max2 * max3)
|
Solution
|
python
|
numba__numba
|
numba/tests/test_errormodels.py
|
{
"start": 86,
"end": 585
}
|
class ____(unittest.TestCase):
def test_div_by_zero_python(self):
@jit # python model is the default
def model_python(val):
return 1 / val
with self.assertRaises(ZeroDivisionError):
model_python(0)
def test_div_by_zero_numpy(self):
@jit(error_model='numpy')
def model_numpy(val):
return 1 / val
self.assertEqual(model_numpy(0), float('inf'))
if __name__ == '__main__':
unittest.main()
|
TestErrorModel
|
python
|
ansible__ansible
|
lib/ansible/_internal/ansible_collections/ansible/_protomatter/plugins/action/debug.py
|
{
"start": 359,
"end": 1469
}
|
class ____(ActionBase):
TRANSFERS_FILES = False
_requires_connection = False
@classmethod
def finalize_task_arg(cls, name: str, value: t.Any, templar: TemplateEngine, context: t.Any) -> t.Any:
if name == 'expression':
return value
return super().finalize_task_arg(name, value, templar, context)
def run(self, tmp=None, task_vars=None):
# accepts a list of literal expressions (no templating), evaluates with no failure on undefined, returns all results
_vr, args = self.validate_argument_spec(
argument_spec=dict(
expression=dict(type=_check_type_list_strict, elements=_check_type_str_no_conversion, required=True),
),
)
with ReplacingMarkerBehavior.warning_context() as replacing_behavior:
templar = self._templar._engine.extend(marker_behavior=replacing_behavior)
return dict(
_ansible_verbose_always=True,
expression_result=[templar.evaluate_expression(expression) for expression in args['expression']],
)
|
ActionModule
|
python
|
getsentry__sentry
|
tests/sentry/uptime/test_models.py
|
{
"start": 1344,
"end": 2354
}
|
class ____(UptimeTestCase):
def test(self) -> None:
self.create_uptime_subscription(host_provider_name="prov1")
self.create_uptime_subscription(host_provider_name="prov1")
self.create_uptime_subscription(host_provider_name="prov2")
self.create_uptime_subscription(host_provider_name="prov2")
self.create_uptime_subscription(host_provider_name="prov3")
assert get_top_hosting_provider_names(2) == {"prov1", "prov2"}
self.create_uptime_subscription(host_provider_name="prov3")
self.create_uptime_subscription(host_provider_name="prov3")
self.create_uptime_subscription(host_provider_name="prov4")
# Cached, so should remain the same
assert get_top_hosting_provider_names(2) == {"prov1", "prov2"}
# Using a different arg should bust the cache
assert get_top_hosting_provider_names(1) == {"prov3"}
assert get_top_hosting_provider_names(3) == {"prov1", "prov2", "prov3"}
|
GetTopHostingProviderNamesTest
|
python
|
django__django
|
django/db/models/expressions.py
|
{
"start": 63274,
"end": 64351
}
|
class ____(Subquery):
template = "EXISTS(%(subquery)s)"
output_field = fields.BooleanField()
empty_result_set_value = False
def __init__(self, queryset, **kwargs):
super().__init__(queryset, **kwargs)
self.query = self.query.exists()
def select_format(self, compiler, sql, params):
# Wrap EXISTS() with a CASE WHEN expression if a database backend
# (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP
# BY list.
if not compiler.connection.features.supports_boolean_expr_in_select_clause:
sql = "CASE WHEN {} THEN 1 ELSE 0 END".format(sql)
return sql, params
def as_sql(self, compiler, *args, **kwargs):
try:
return super().as_sql(compiler, *args, **kwargs)
except EmptyResultSet:
features = compiler.connection.features
if not features.supports_boolean_expr_in_select_clause:
return "1=0", ()
return compiler.compile(Value(False))
@deconstructible(path="django.db.models.OrderBy")
|
Exists
|
python
|
modin-project__modin
|
modin/core/execution/dispatching/factories/dispatcher.py
|
{
"start": 1205,
"end": 1370
}
|
class ____(AttributeError):
"""
``FactoryNotFound`` exception class.
Raise when no matching factory could be found.
"""
pass
|
FactoryNotFoundError
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-shopify/source_shopify/streams/streams.py
|
{
"start": 8924,
"end": 9044
}
|
class ____(IncrementalShopifyStreamWithDeletedEvents):
data_field = "pages"
deleted_events_api_name = "Page"
|
Pages
|
python
|
pytorch__pytorch
|
torch/utils/data/datapipes/iter/grouping.py
|
{
"start": 4831,
"end": 12441
}
|
class ____(IterDataPipe[DataChunk]):
r"""
Groups data from IterDataPipe by keys from ``group_key_fn``, yielding a ``DataChunk`` with batch size up to ``group_size``.
(functional name: ``groupby``).
The samples are read sequentially from the source ``datapipe``, and a batch of samples belonging to the same group
will be yielded as soon as the size of the batch reaches ``group_size``. When the buffer is full,
the DataPipe will yield the largest batch with the same key, provided that its size is larger
than ``guaranteed_group_size``. If its size is smaller, it will be dropped if ``drop_remaining=True``.
After iterating through the entirety of source ``datapipe``, everything not dropped due to the buffer capacity
will be yielded from the buffer, even if the group sizes are smaller than ``guaranteed_group_size``.
Args:
datapipe: Iterable datapipe to be grouped
group_key_fn: Function used to generate group key from the data of the source datapipe
keep_key: Option to yield the matching key along with the items in a tuple,
resulting in `(key, [items])` otherwise returning [items]
buffer_size: The size of buffer for ungrouped data
group_size: The max size of each group, a batch is yielded as soon as it reaches this size
guaranteed_group_size: The guaranteed minimum group size to be yielded in case the buffer is full
drop_remaining: Specifies if the group smaller than ``guaranteed_group_size`` will be dropped from buffer
when the buffer is full
Example:
>>> import os
>>> # xdoctest: +SKIP
>>> from torchdata.datapipes.iter import IterableWrapper
>>> def group_fn(file):
... return os.path.basename(file).split(".")[0]
>>> source_dp = IterableWrapper(
... ["a.png", "b.png", "a.json", "b.json", "a.jpg", "c.json"]
... )
>>> dp0 = source_dp.groupby(group_key_fn=group_fn)
>>> list(dp0)
[['a.png', 'a.json', 'a.jpg'], ['b.png', 'b.json'], ['c.json']]
>>> # A group is yielded as soon as its size equals to `group_size`
>>> dp1 = source_dp.groupby(group_key_fn=group_fn, group_size=2)
>>> list(dp1)
[['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']]
>>> # Scenario where `buffer` is full, and group 'a' needs to be yielded since its size > `guaranteed_group_size`
>>> dp2 = source_dp.groupby(
... group_key_fn=group_fn,
... buffer_size=3,
... group_size=3,
... guaranteed_group_size=2,
... )
>>> list(dp2)
[['a.png', 'a.json'], ['b.png', 'b.json'], ['a.jpg'], ['c.json']]
"""
def __init__(
self,
datapipe: IterDataPipe[_T_co],
group_key_fn: Callable[[_T_co], Any],
*,
keep_key: bool = False,
buffer_size: int = 10000,
group_size: int | None = None,
guaranteed_group_size: int | None = None,
drop_remaining: bool = False,
) -> None:
_check_unpickable_fn(group_key_fn)
# pyrefly: ignore [invalid-type-var]
self.datapipe = datapipe
# pyrefly: ignore [invalid-type-var]
self.group_key_fn = group_key_fn
self.keep_key = keep_key
self.max_buffer_size = buffer_size
self.buffer_elements: defaultdict[Any, list] = defaultdict(list)
self.curr_buffer_size = 0
self.group_size = group_size
self.guaranteed_group_size = None
if group_size is not None and buffer_size is not None:
if not (0 < group_size <= buffer_size):
raise AssertionError("group_size must be > 0 and <= buffer_size")
# pyrefly: ignore [bad-assignment]
self.guaranteed_group_size = group_size
if guaranteed_group_size is not None:
if group_size is None or not (0 < guaranteed_group_size <= group_size):
raise AssertionError(
"guaranteed_group_size must be > 0 and <= group_size and group_size must be set"
)
# pyrefly: ignore [bad-assignment]
self.guaranteed_group_size = guaranteed_group_size
self.drop_remaining = drop_remaining
self.wrapper_class = DataChunk
def _remove_biggest_key(self):
biggest_key = None
biggest_size = 0
result_to_yield = None
for findkey in self.buffer_elements:
if len(self.buffer_elements[findkey]) > biggest_size:
biggest_size = len(self.buffer_elements[findkey])
biggest_key = findkey
if (
self.guaranteed_group_size is not None
and biggest_size < self.guaranteed_group_size
and not self.drop_remaining
):
raise RuntimeError(
"Failed to group items", str(self.buffer_elements[biggest_key])
)
if (
self.guaranteed_group_size is None
or biggest_size >= self.guaranteed_group_size
):
result_to_yield = self.buffer_elements[biggest_key]
self.curr_buffer_size -= biggest_size
del self.buffer_elements[biggest_key]
return result_to_yield
def __iter__(self):
for x in self.datapipe:
key = self.group_key_fn(x)
self.buffer_elements[key].append(x)
self.curr_buffer_size += 1
if self.group_size is not None and self.group_size == len(
self.buffer_elements[key]
):
result: DataChunk[Any] = self.wrapper_class(self.buffer_elements[key])
yield (key, result) if self.keep_key else result
self.curr_buffer_size -= len(self.buffer_elements[key])
del self.buffer_elements[key]
if self.curr_buffer_size == self.max_buffer_size:
result_to_yield = self._remove_biggest_key()
if result_to_yield is not None:
result = self.wrapper_class(result_to_yield)
yield (key, result) if self.keep_key else result
for key in tuple(self.buffer_elements.keys()):
result = self.wrapper_class(self.buffer_elements.pop(key))
self.curr_buffer_size -= len(result)
yield (key, result) if self.keep_key else result
def reset(self) -> None:
self.curr_buffer_size = 0
self.buffer_elements = defaultdict(list)
def __getstate__(self):
state = (
self.datapipe,
self.group_key_fn,
self.keep_key,
self.max_buffer_size,
self.group_size,
self.guaranteed_group_size,
self.drop_remaining,
self.wrapper_class,
self._valid_iterator_id,
self._number_of_samples_yielded,
)
if IterDataPipe.getstate_hook is not None:
return IterDataPipe.getstate_hook(state)
return state
def __setstate__(self, state):
(
self.datapipe,
self.group_key_fn,
self.keep_key,
self.max_buffer_size,
self.group_size,
self.guaranteed_group_size,
self.drop_remaining,
self.wrapper_class,
self._valid_iterator_id,
self._number_of_samples_yielded,
) = state
self.curr_buffer_size = 0
self.buffer_elements = defaultdict(list)
def __del__(self) -> None:
self.buffer_elements.clear()
|
GrouperIterDataPipe
|
python
|
catalyst-team__catalyst
|
catalyst/contrib/data/sampler_inbatch.py
|
{
"start": 3845,
"end": 5251
}
|
class ____(InBatchTripletsSampler):
"""
This sampler selects all the possible triplets for the given labels
"""
def __init__(self, max_output_triplets: int = maxsize):
"""
Args:
max_output_triplets: with the strategy of choosing all
the triplets, their number in the batch can be very large,
because of it we can sample only random part of them,
determined by this parameter.
"""
self._max_out_triplets = max_output_triplets
def _sample(self, *_: Tensor, labels: List[int]) -> TTripletsIds:
"""
Args:
labels: labels of the samples in the batch
*_: note, that we ignore features argument
Returns:
indices of triplets
"""
num_labels = len(labels)
triplets = []
for label in set(labels):
ids_pos_cur = set(find_value_ids(labels, label))
ids_neg_cur = set(range(num_labels)) - ids_pos_cur
pos_pairs = list(combinations(ids_pos_cur, r=2))
tri = [(a, p, n) for (a, p), n in product(pos_pairs, ids_neg_cur)]
triplets.extend(tri)
triplets = sample(triplets, min(len(triplets), self._max_out_triplets))
ids_anchor, ids_pos, ids_neg = zip(*triplets)
return list(ids_anchor), list(ids_pos), list(ids_neg)
|
AllTripletsSampler
|
python
|
tensorflow__tensorflow
|
tensorflow/tools/ci_build/osx/arm64/tensorflow_metal_plugin_test.py
|
{
"start": 13707,
"end": 16279
}
|
class ____(test.TestCase, parameterized.TestCase):
def _buildParams(self, data, dtype):
data = data.astype(dtype.as_numpy_dtype)
# For complex types, add an index-dependent imaginary component so we can
# tell we got the right value.
if dtype.is_complex:
return data + 10j * data
return data
def testScalar1D(self):
with self.cached_session(use_gpu=True):
data = np.array([0, 1, 2, 3, 7, 5])
for dtype in _TEST_TYPES:
for indices in 4, [1, 2, 2, 4, 5]:
params_np = self._buildParams(data, dtype)
params = constant_op.constant(params_np)
indices_tf = constant_op.constant(indices)
gather_t = array_ops.gather(params, indices_tf)
gather_val = self.evaluate(gather_t)
np_val = params_np[indices]
self.assertAllEqual(np_val, gather_val)
self.assertEqual(np_val.shape, gather_t.get_shape())
def testScalar2D(self):
with self.session(use_gpu=True):
data = np.array(
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]
)
for dtype in _TEST_TYPES:
for axis in range(data.ndim):
params_np = self._buildParams(data, dtype)
params = constant_op.constant(params_np)
indices = constant_op.constant(2)
gather_t = array_ops.gather(params, indices, axis=axis)
gather_val = self.evaluate(gather_t)
print("TF {}".format(gather_val))
print("CPU {}".format(np.take(params_np, 2, axis=axis)))
self.assertAllEqual(np.take(params_np, 2, axis=axis), gather_val)
expected_shape = data.shape[:axis] + data.shape[axis + 1 :]
self.assertEqual(expected_shape, gather_t.get_shape())
def testSimpleTwoD32(self):
with self.session(use_gpu=True):
data = np.array(
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]
)
for dtype in _TEST_TYPES:
for axis in range(data.ndim):
params_np = self._buildParams(data, dtype)
params = constant_op.constant(params_np)
# The indices must be in bounds for any axis.
indices = constant_op.constant([0, 1, 0, 2])
gather_t = array_ops.gather(params, indices, axis=axis)
gather_val = self.evaluate(gather_t)
self.assertAllEqual(
np.take(params_np, [0, 1, 0, 2], axis=axis), gather_val
)
expected_shape = data.shape[:axis] + (4,) + data.shape[axis + 1 :]
self.assertEqual(expected_shape, gather_t.get_shape())
|
GatherTest
|
python
|
django-haystack__django-haystack
|
haystack/generic_views.py
|
{
"start": 3415,
"end": 3865
}
|
class ____(SearchMixin, FormView):
"""A view class for searching a Haystack managed search index"""
def get(self, request, *args, **kwargs):
"""
Handles GET requests and instantiates a blank version of the form.
"""
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
return self.form_invalid(form)
|
SearchView
|
python
|
tornadoweb__tornado
|
tornado/template.py
|
{
"start": 20226,
"end": 20949
}
|
class ____(_Node):
def __init__(self, name: str, body: _Node, template: Template, line: int) -> None:
self.name = name
self.body = body
self.template = template
self.line = line
def each_child(self) -> Iterable["_Node"]:
return (self.body,)
def generate(self, writer: "_CodeWriter") -> None:
block = writer.named_blocks[self.name]
with writer.include(block.template, self.line):
block.body.generate(writer)
def find_named_blocks(
self, loader: Optional[BaseLoader], named_blocks: Dict[str, "_NamedBlock"]
) -> None:
named_blocks[self.name] = self
_Node.find_named_blocks(self, loader, named_blocks)
|
_NamedBlock
|
python
|
kevin1024__vcrpy
|
vcr/stubs/boto3_stubs.py
|
{
"start": 332,
"end": 1203
}
|
class ____(VCRHTTPSConnection, VerifiedHTTPSConnection):
_baseclass = VerifiedHTTPSConnection
def __init__(self, *args, **kwargs):
kwargs.pop("strict", None)
# need to temporarily reset here because the real connection
# inherits from the thing that we are mocking out. Take out
# the reset if you want to see what I mean :)
from vcr.patch import force_reset
with force_reset():
self.real_connection = self._baseclass(*args, **kwargs)
# Make sure to set those attributes as it seems `AWSHTTPConnection` does not
# set them, making the connection to fail !
self.real_connection.assert_hostname = kwargs.get("assert_hostname", False)
self.real_connection.cert_reqs = kwargs.get("cert_reqs", "CERT_NONE")
self._sock = None
|
VCRRequestsHTTPSConnection
|
python
|
great-expectations__great_expectations
|
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_ohio_zip.py
|
{
"start": 727,
"end": 1719
}
|
class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_ohio_zip"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.apply(lambda x: is_valid_ohio_zip(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
|
ColumnValuesToBeValidOhioZip
|
python
|
huggingface__transformers
|
tests/models/owlvit/test_modeling_owlvit.py
|
{
"start": 10591,
"end": 12222
}
|
class ____(ModelTesterMixin, unittest.TestCase):
all_model_classes = (OwlViTTextModel,) if is_torch_available() else ()
def setUp(self):
self.model_tester = OwlViTTextModelTester(self)
self.config_tester = ConfigTester(self, config_class=OwlViTTextConfig, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
@unittest.skip(reason="OWL-ViT does not support training yet")
def test_training(self):
pass
@unittest.skip(reason="OWL-ViT does not support training yet")
def test_training_gradient_checkpointing(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing_use_reentrant(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing_use_reentrant_false(self):
pass
@unittest.skip(reason="OWLVIT does not use inputs_embeds")
def test_inputs_embeds(self):
pass
@slow
def test_model_from_pretrained(self):
model_name = "google/owlvit-base-patch32"
model = OwlViTTextModel.from_pretrained(model_name)
self.assertIsNotNone(model)
|
OwlViTTextModelTest
|
python
|
django__django
|
django/contrib/gis/db/models/functions.py
|
{
"start": 3915,
"end": 4055
}
|
class ____(GeoFunc):
@cached_property
def output_field(self):
return GeometryField(srid=self.geo_field.srid)
|
GeomOutputGeoFunc
|
python
|
microsoft__pyright
|
packages/pyright-internal/src/tests/samples/dataclassReplace1.py
|
{
"start": 510,
"end": 780
}
|
class ____(NamedTuple):
a: int
b: str
c: str = ""
nt1 = NT1(1, "")
nt1_clone = nt1.__replace__(c="")
reveal_type(nt1_clone, expected_text="NT1")
# This should generate an error.
nt1.__replace__(b=2)
# This should generate an error.
nt1.__replace__(d="")
|
NT1
|
python
|
pytorch__pytorch
|
test/dynamo/test_higher_order_ops.py
|
{
"start": 3976,
"end": 12629
}
|
class ____(torch._dynamo.test_case.TestCaseWithNestedGraphBreaks):
def _assert_wrap_fallback(self, func, args, setup=lambda: None):
counters.clear()
backend = EagerAndRecordGraphs()
cnt = CompileCounterWithBackend(backend)
setup()
expected = func(*args)
setup()
result = torch.compile(func, backend=cnt, fullgraph=False)(*args)
num_graph_breaks = len(counters["graph_break"].keys())
self.assertGreater(num_graph_breaks, 0)
for gm in backend.graphs:
for node in gm.graph.nodes:
self.assertFalse(node.target is wrap)
self.assertEqual(result, expected)
def _test_wrap_simple(
self,
func,
args_generator,
expected_num_wrap_args,
expected_opcount=2,
return_graph=False,
):
# Given a `func` that has a single call to `wrap`,
# we check that:
# - there are no graph breaks
# - eager vs torch.compile has the same result (correctness)
# - other compilation metrics, e.g, # of ops in the dynamo captured graph,
# the wrap has the expected number of args, etc
#
# we have one or multiple runs through with each of the args from args_generator,
# and we will check:
# - correctness and no graph breaks for every run
# - other compilation metrics only for the first run, since automatic_dynamic_shapes
# may compile another dynamic version graph for the later runs
graph = None
for i, args in enumerate(args_generator):
backend = EagerAndRecordGraphs()
cnt = CompileCounterWithBackend(backend)
expected = func(*args)
result = torch.compile(func, fullgraph=True, backend=cnt)(*args)
# check correctness and no graph breaks
self.assertEqual(result, expected)
self.assertEqual(cnt.frame_count, 1)
self.assertEqual(len(backend.graphs), 1)
# check other compilation metrics
if i == 0:
self.assertEqual(cnt.op_count, expected_opcount)
graph = backend.graphs[0]
wrap_node = find_first_node(graph, wrap)
self.assertEqual(len(wrap_node.args), expected_num_wrap_args)
# We always return/check the graph from the first run if return_graph = True
if return_graph:
return normalize_gm(graph.print_readable(print_output=False))
def test_error_message_sane(self):
foo = []
def inner(x):
foo.append(x)
return x.clone()
@torch.compile(backend="eager", fullgraph=True)
def f(x):
return wrap(inner, x)
x = torch.randn(3)
with self.assertRaisesRegex(
torch._dynamo.exc.Unsupported,
r"HigherOrderOperator: Mutating a variable not in the current scope \(SideEffects\)",
):
f(x)
def test_no_freevars(self):
def f(x):
return wrap(lambda x: torch.sin(x), x)
x = torch.randn(3)
arg_count = ifdynstaticdefault(2, 3)
self._test_wrap_simple(f, default_args_generator((x,)), arg_count)
def test_enum_arg(self):
class SomeEnum(enum.Enum):
A = 0
B = 1
def g(x, val):
if val == SomeEnum.A:
return torch.sin(x)
return torch.cos(x)
def f(x, val):
return wrap(g, x, val)
x = torch.randn(3)
arg_count = ifdynstaticdefault(2, 3)
self._test_wrap_simple(f, default_args_generator((x, SomeEnum.A)), arg_count)
def test_return_captured_var(self):
freevar = torch.randn(3)
def test(x):
return freevar
def fn(x):
return wrap(test, x)
x = torch.randn(3)
# Since, `x` is unused, we don't lift it to
# be the input.
# when testing with dynamic shape, symbols are lifted as input
arg_count = ifdynstaticdefault(2, 3)
self._test_wrap_simple(fn, default_args_generator((x,)), arg_count, 1)
def test_return_captured_vars(self):
freevar1 = torch.randn(3)
freevar2 = torch.randn(3)
def test(x):
return freevar1, freevar2, freevar1
def fn(x):
return wrap(test, x)
x = torch.randn(3)
# Since, `x` is unused, we don't lift it to
# be the input.
# when testing with dynamic shape, a symbol is lifted as input
arg_count = ifdynstaticdefault(3, 4)
self._test_wrap_simple(fn, default_args_generator((x,)), arg_count, 1)
def test_return_captured_var_used_multiple_times(self):
freevar = torch.randn(3)
def test(x):
y = x + freevar
return y, freevar
def fn(x):
return wrap(test, x)
x = torch.randn(3)
# when testing with dynamic shape, a symbol is lifted as input
arg_count = ifdynstaticdefault(3, 4)
self._test_wrap_simple(fn, default_args_generator((x,)), arg_count, 2)
def test_capture_untracked_global(self):
def f(x):
return wrap(lambda x: x + global_var, x)
x = torch.randn(3)
# when testing with dynamic shape, a symbol is lifted as input
arg_count = ifdynstaticdefault(3, 4)
self._test_wrap_simple(f, default_args_generator((x,)), arg_count)
def test_allow_python_side_effects_utility(self):
from torch._dynamo.utils import (
_disable_side_effect_safety_checks_for_current_subtracer,
)
from torch._higher_order_ops.wrap import dynamo_bypassing_wrapper
def wrapper(fn):
return fn
count = 0
def does_side_effect(x):
nonlocal count
count += 1
return x.sin()
def does_side_effect_wrapped(*args, **kwargs):
return _disable_side_effect_safety_checks_for_current_subtracer(
does_side_effect, *args, **kwargs
)
@torch.compile(backend="eager", fullgraph=True)
def fn(x):
return dynamo_bypassing_wrapper(wrapper, does_side_effect_wrapped, x)
x = torch.tensor(1.0)
fn(x)
def inner_does_side_effect(x):
nonlocal count
count += 1
return x
# Test that any nested HOPs are unaffected
def outer(x):
return dynamo_bypassing_wrapper(wrapper, inner_does_side_effect, x)
def outer_wrapped(*args, **kwargs):
return _disable_side_effect_safety_checks_for_current_subtracer(
outer, *args, **kwargs
)
@torch.compile(backend="eager", fullgraph=True)
def fn_nested(x):
return dynamo_bypassing_wrapper(wrapper, outer_wrapped, x)
x = torch.tensor(1.0)
with self.assertRaisesRegex(
RuntimeError, "Mutating a variable not in the current scope"
):
fn_nested(x)
def test_symint_input(self):
def f(x):
i = x.size(0)
return wrap(lambda x, i: x.view(i), x, i)
x = torch.randn(3, 1)
self._test_wrap_simple(
f,
default_args_generator((x,)),
ifdynstaticdefault(2, 3),
expected_opcount=2,
)
def test_symint_in_slice(self):
def f(x):
i = x.size(0) - 2
j = x.size(1) - 3
k = x.size(2)
return wrap(lambda x: x[:i, :j, k:], x)
x = torch.randn(3, 4, 5)
self._test_wrap_simple(
f,
default_args_generator((x,)),
# 3 basic symbols and 2 compound symbols
ifdynstaticdefault(2, 7),
# 2 more sym expression computation
expected_opcount=ifdynstaticdefault(2, 4),
)
def test_wrap_pytree_args_nested(self):
def f(x, y, z):
def fn(d):
return d["x"].sin() + d["y"][0].cos() - d["y"][1][2].sin()
return wrap(fn, d)
x = torch.tensor(1.5)
y = torch.tensor(2.0)
z = torch.tensor(3.0)
d = {"x": x, "y": (y, [x, y, z])}
def my_args_generator(t):
yield t
yield t[0] + 0.1, t[1], t[2]
yield t[0], t[1] + 0.1, t[2]
actual_graph = self._test_wrap_simple(
f,
my_args_generator((x, y, z)),
4,
return_graph=True,
)
self.assertExpectedInline(
actual_graph,
"""\
|
HigherOrderOpTests
|
python
|
conda__conda
|
conda/models/match_spec.py
|
{
"start": 41446,
"end": 42890
}
|
class ____(GlobStrMatch):
def __init__(self, value):
self._re_match = None
try:
if isinstance(value, str):
if value.startswith("^") and value.endswith("$"):
self._re_match = re.compile(value).match
elif "*" in value:
self._re_match = re.compile(
r"^(?:{})$".format(value.replace("*", r".*"))
).match
else:
value = Channel(value)
except re.error as e:
raise InvalidMatchSpec(
value, f"Contains an invalid regular expression. '{e}'"
)
super(GlobStrMatch, self).__init__(value)
def match(self, other):
try:
_other_val = Channel(other._raw_value)
except AttributeError:
_other_val = Channel(other)
if self._re_match:
return self._re_match(_other_val.canonical_name)
else:
# assert ChannelMatch('pkgs/free').match('defaults') is False
# assert ChannelMatch('defaults').match('pkgs/free') is True
return self._raw_value.name in (_other_val.name, _other_val.canonical_name)
def __str__(self):
try:
return f"{self._raw_value.name}"
except AttributeError:
return f"{self._raw_value}"
def __repr__(self):
return f"'{self.__str__()}'"
|
ChannelMatch
|
python
|
django__django
|
django/template/defaulttags.py
|
{
"start": 17027,
"end": 18090
}
|
class ____(Node):
def __init__(self, val_expr, max_expr, max_width, asvar=None):
self.val_expr = val_expr
self.max_expr = max_expr
self.max_width = max_width
self.asvar = asvar
def render(self, context):
try:
value = self.val_expr.resolve(context)
max_value = self.max_expr.resolve(context)
max_width = int(self.max_width.resolve(context))
except VariableDoesNotExist:
return ""
except (ValueError, TypeError):
raise TemplateSyntaxError("widthratio final argument must be a number")
try:
value = float(value)
max_value = float(max_value)
ratio = (value / max_value) * max_width
result = str(round(ratio))
except ZeroDivisionError:
result = "0"
except (ValueError, TypeError, OverflowError):
result = ""
if self.asvar:
context[self.asvar] = result
return ""
else:
return result
|
WidthRatioNode
|
python
|
tensorflow__tensorflow
|
tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py
|
{
"start": 49950,
"end": 50885
}
|
class ____(test.TestCase):
def testTranspose(self):
if np.__version__ == "1.13.0":
self.skipTest("numpy 1.13.0 bug")
with test_util.force_cpu():
np.random.seed(1618)
shapes = [np.random.randint(1, 10, size=rank) for rank in range(1, 6)]
for shape in shapes:
for dtype in [np.int32, np.int64, np.float32, np.float64]:
dn_input = np.random.randn(*shape).astype(dtype)
rank = self.evaluate(array_ops.rank(dn_input))
perm = np.random.choice(rank, rank, False)
sp_input, unused_a_nnz = _sparsify(dn_input)
sp_trans = sparse_ops.sparse_transpose(sp_input, perm=perm)
dn_trans = sparse_ops.sparse_tensor_to_dense(sp_trans)
expected_trans = array_ops.transpose(dn_input, perm=perm)
self.assertAllEqual(expected_trans.shape, sp_trans.get_shape())
self.assertAllEqual(dn_trans, expected_trans)
|
SparseTransposeTest
|
python
|
pytorch__pytorch
|
test/distributed/checkpoint/e2e/test_e2e_save_and_load.py
|
{
"start": 3025,
"end": 4495
}
|
class ____:
step: int = 0
current_loss: float = -1
losses: list[float] = field(default_factory=list)
def state_dict(self) -> dict[str, Any]:
loss_bytes = BytesIO()
torch.save(self.losses, loss_bytes)
return {
"step": torch.tensor(self.step, dtype=torch.int32),
"current_loss": torch.tensor(self.current_loss, dtype=torch.float32),
"losses": loss_bytes,
}
def load_state_dict(self, state_dict) -> None:
self.step = state_dict["step"].item()
self.current_loss = state_dict["current_loss"].item()
state_dict["losses"].seek(0)
self.losses = torch.load(state_dict["losses"])
def __eq__(self, other):
return (
self.step == other.step
and self.current_loss == other.current_loss
and self.losses == other.losses
)
def _train(model, optim, train_steps=1):
torch.manual_seed(0)
loss = None
train_state = TestTrainState()
for _ in range(train_steps):
loss = model(model.get_input()).sum()
loss.backward()
# We usually sync the loss across dp ranks in real training.
# This is just simulating for testing purpose.
train_state.step += 1
train_state.current_loss = torch.rand(1).item()
train_state.losses.append(train_state.current_loss)
optim.step()
optim.zero_grad()
return loss, train_state
|
TestTrainState
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.