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
pydata__xarray
xarray/tests/test_groupby.py
{ "start": 84542, "end": 118057 }
class ____: @pytest.mark.parametrize( "resample_freq", [ "24h", "123456s", "1234567890us", pd.Timedelta(hours=2), pd.offsets.MonthBegin(), pd.offsets.Second(123456), datetime.timedelta(days=1, hours=6), ], ) def test_resample( self, use_cftime: bool, resample_freq: ResampleCompatible ) -> None: if use_cftime and not has_cftime: pytest.skip() times = xr.date_range( "2000-01-01", freq="6h", periods=10, use_cftime=use_cftime ) def resample_as_pandas(ds, *args, **kwargs): ds_ = ds.copy(deep=True) if use_cftime: ds_["time"] = times.to_datetimeindex(time_unit="ns") result = Dataset.from_dataframe( ds_.to_dataframe().resample(*args, **kwargs).mean() ) if use_cftime: result = result.convert_calendar( calendar="standard", use_cftime=use_cftime ) return result ds = Dataset( { "foo": ("time", np.random.randint(1, 1000, 10)), "bar": ("time", np.random.randint(1, 1000, 10)), "time": times, } ) actual = ds.resample(time=resample_freq).mean() expected = resample_as_pandas(ds, resample_freq) assert_identical(expected, actual) actual = ds.resample(time=resample_freq).reduce(np.mean) assert_identical(expected, actual) actual = ds.resample(time=resample_freq, closed="right").mean() expected = resample_as_pandas(ds, resample_freq, closed="right") assert_identical(expected, actual) with pytest.raises(ValueError, match=r"Index must be monotonic"): ds.isel(time=[2, 0, 1]).resample(time=resample_freq) reverse = ds.isel(time=slice(-1, None, -1)) with pytest.raises(ValueError): reverse.resample(time=resample_freq).mean() def test_resample_and_first(self) -> None: times = pd.date_range("2000-01-01", freq="6h", periods=10) ds = Dataset( { "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)), "bar": ("time", np.random.randn(10), {"meta": "data"}), "time": times, } ) actual = ds.resample(time="1D").first(keep_attrs=True) expected = ds.isel(time=[0, 4, 8]) assert_identical(expected, actual) # upsampling expected_time = pd.date_range("2000-01-01", freq="3h", periods=19) expected = ds.reindex(time=expected_time) rs = ds.resample(time="3h") for how in ["mean", "sum", "first", "last"]: method = getattr(rs, how) result = method() assert_equal(expected, result) for method in [np.mean]: result = rs.reduce(method) assert_equal(expected, result) def test_resample_min_count(self) -> None: times = pd.date_range("2000-01-01", freq="6h", periods=10) ds = Dataset( { "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)), "bar": ("time", np.random.randn(10), {"meta": "data"}), "time": times, } ) # inject nan ds["foo"] = xr.where(ds["foo"] > 2.0, np.nan, ds["foo"]) actual = ds.resample(time="1D").sum(min_count=1) expected = xr.concat( [ ds.isel(time=slice(i * 4, (i + 1) * 4)).sum("time", min_count=1) for i in range(3) ], dim=actual["time"], data_vars="all", ) assert_allclose(expected, actual) def test_resample_by_mean_with_keep_attrs(self) -> None: times = pd.date_range("2000-01-01", freq="6h", periods=10) ds = Dataset( { "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)), "bar": ("time", np.random.randn(10), {"meta": "data"}), "time": times, } ) ds.attrs["dsmeta"] = "dsdata" resampled_ds = ds.resample(time="1D").mean(keep_attrs=True) actual = resampled_ds["bar"].attrs expected = ds["bar"].attrs assert expected == actual actual = resampled_ds.attrs expected = ds.attrs assert expected == actual def test_resample_by_mean_discarding_attrs(self) -> None: times = pd.date_range("2000-01-01", freq="6h", periods=10) ds = Dataset( { "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)), "bar": ("time", np.random.randn(10), {"meta": "data"}), "time": times, } ) ds.attrs["dsmeta"] = "dsdata" resampled_ds = ds.resample(time="1D").mean(keep_attrs=False) assert resampled_ds["bar"].attrs == {} assert resampled_ds.attrs == {} def test_resample_by_last_discarding_attrs(self) -> None: times = pd.date_range("2000-01-01", freq="6h", periods=10) ds = Dataset( { "foo": (["time", "x", "y"], np.random.randn(10, 5, 3)), "bar": ("time", np.random.randn(10), {"meta": "data"}), "time": times, } ) ds.attrs["dsmeta"] = "dsdata" resampled_ds = ds.resample(time="1D").last(keep_attrs=False) assert resampled_ds["bar"].attrs == {} assert resampled_ds.attrs == {} @requires_scipy def test_resample_drop_nondim_coords(self) -> None: xs = np.arange(6) ys = np.arange(3) times = pd.date_range("2000-01-01", freq="6h", periods=5) data = np.tile(np.arange(5), (6, 3, 1)) xx, yy = np.meshgrid(xs * 5, ys * 2.5) tt = np.arange(len(times), dtype=int) array = DataArray(data, {"time": times, "x": xs, "y": ys}, ("x", "y", "time")) xcoord = DataArray(xx.T, {"x": xs, "y": ys}, ("x", "y")) ycoord = DataArray(yy.T, {"x": xs, "y": ys}, ("x", "y")) tcoord = DataArray(tt, {"time": times}, ("time",)) ds = Dataset({"data": array, "xc": xcoord, "yc": ycoord, "tc": tcoord}) ds = ds.set_coords(["xc", "yc", "tc"]) # Re-sample actual = ds.resample(time="12h").mean("time") assert "tc" not in actual.coords # Up-sample - filling actual = ds.resample(time="1h").ffill() assert "tc" not in actual.coords # Up-sample - interpolation actual = ds.resample(time="1h").interpolate("linear") assert "tc" not in actual.coords def test_resample_ds_da_are_the_same(self) -> None: time = pd.date_range("2000-01-01", freq="6h", periods=365 * 4) ds = xr.Dataset( { "foo": (("time", "x"), np.random.randn(365 * 4, 5)), "time": time, "x": np.arange(5), } ) assert_allclose( ds.resample(time="ME").mean()["foo"], ds.foo.resample(time="ME").mean() ) def test_ds_resample_apply_func_args(self) -> None: def func(arg1, arg2, arg3=0.0): return arg1.mean("time") + arg2 + arg3 times = pd.date_range("2000", freq="D", periods=3) ds = xr.Dataset({"foo": ("time", [1.0, 1.0, 1.0]), "time": times}) expected = xr.Dataset({"foo": ("time", [3.0, 3.0, 3.0]), "time": times}) actual = ds.resample(time="D").map(func, args=(1.0,), arg3=1.0) assert_identical(expected, actual) def test_groupby_cumsum() -> None: ds = xr.Dataset( {"foo": (("x",), [7, 3, 1, 1, 1, 1, 1])}, coords={"x": [0, 1, 2, 3, 4, 5, 6], "group_id": ("x", [0, 0, 1, 1, 2, 2, 2])}, ) actual = ds.groupby("group_id").cumsum(dim="x") expected = xr.Dataset( { "foo": (("x",), [7, 10, 1, 2, 1, 2, 3]), }, coords={ "x": [0, 1, 2, 3, 4, 5, 6], "group_id": ds.group_id, }, ) # TODO: Remove drop_vars when GH6528 is fixed # when Dataset.cumsum propagates indexes, and the group variable? assert_identical(expected.drop_vars(["x", "group_id"]), actual) actual = ds.foo.groupby("group_id").cumsum(dim="x") expected.coords["group_id"] = ds.group_id expected.coords["x"] = np.arange(7) assert_identical(expected.foo, actual) def test_groupby_cumprod() -> None: ds = xr.Dataset( {"foo": (("x",), [7, 3, 0, 1, 1, 2, 1])}, coords={"x": [0, 1, 2, 3, 4, 5, 6], "group_id": ("x", [0, 0, 1, 1, 2, 2, 2])}, ) actual = ds.groupby("group_id").cumprod(dim="x") expected = xr.Dataset( { "foo": (("x",), [7, 21, 0, 0, 1, 2, 2]), }, coords={ "x": [0, 1, 2, 3, 4, 5, 6], "group_id": ds.group_id, }, ) # TODO: Remove drop_vars when GH6528 is fixed # when Dataset.cumsum propagates indexes, and the group variable? assert_identical(expected.drop_vars(["x", "group_id"]), actual) actual = ds.foo.groupby("group_id").cumprod(dim="x") expected.coords["group_id"] = ds.group_id expected.coords["x"] = np.arange(7) assert_identical(expected.foo, actual) @pytest.mark.parametrize( "method, expected_array", [ ("cumsum", [1.0, 2.0, 5.0, 6.0, 2.0, 2.0]), ("cumprod", [1.0, 2.0, 6.0, 6.0, 2.0, 2.0]), ], ) def test_resample_cumsum(method: str, expected_array: list[float]) -> None: ds = xr.Dataset( {"foo": ("time", [1, 2, 3, 1, 2, np.nan])}, coords={ "time": xr.date_range("01-01-2001", freq="ME", periods=6, use_cftime=False), }, ) actual = getattr(ds.resample(time="3ME"), method)(dim="time") expected = xr.Dataset( {"foo": (("time",), expected_array)}, coords={ "time": xr.date_range("01-01-2001", freq="ME", periods=6, use_cftime=False), }, ) # TODO: Remove drop_vars when GH6528 is fixed # when Dataset.cumsum propagates indexes, and the group variable? assert_identical(expected.drop_vars(["time"]), actual) actual = getattr(ds.foo.resample(time="3ME"), method)(dim="time") expected.coords["time"] = ds.time assert_identical(expected.drop_vars(["time"]).foo, actual) def test_groupby_binary_op_regression() -> None: # regression test for #7797 # monthly timeseries that should return "zero anomalies" everywhere time = xr.date_range("2023-01-01", "2023-12-31", freq="MS") data = np.linspace(-1, 1, 12) x = xr.DataArray(data, coords={"time": time}) clim = xr.DataArray(data, coords={"month": np.arange(1, 13, 1)}) # seems to give the correct result if we use the full x, but not with a slice x_slice = x.sel(time=["2023-04-01"]) # two typical ways of computing anomalies anom_gb = x_slice.groupby("time.month") - clim assert_identical(xr.zeros_like(anom_gb), anom_gb) def test_groupby_multiindex_level() -> None: # GH6836 midx = pd.MultiIndex.from_product([list("abc"), [0, 1]], names=("one", "two")) mda = xr.DataArray(np.random.rand(6, 3), [("x", midx), ("y", range(3))]) groups = mda.groupby("one").groups assert groups == {"a": [0, 1], "b": [2, 3], "c": [4, 5]} @requires_flox @pytest.mark.parametrize("func", ["sum", "prod"]) @pytest.mark.parametrize("skipna", [True, False]) @pytest.mark.parametrize("min_count", [None, 1]) def test_min_count_vs_flox(func: str, min_count: int | None, skipna: bool) -> None: da = DataArray( data=np.array([np.nan, 1, 1, np.nan, 1, 1]), dims="x", coords={"labels": ("x", np.array([1, 2, 3, 1, 2, 3]))}, ) gb = da.groupby("labels") method = operator.methodcaller(func, min_count=min_count, skipna=skipna) with xr.set_options(use_flox=True): actual = method(gb) with xr.set_options(use_flox=False): expected = method(gb) assert_identical(actual, expected) @pytest.mark.parametrize("use_flox", [True, False]) def test_min_count_error(use_flox: bool) -> None: if use_flox and not has_flox: pytest.skip() da = DataArray( data=np.array([np.nan, 1, 1, np.nan, 1, 1]), dims="x", coords={"labels": ("x", np.array([1, 2, 3, 1, 2, 3]))}, ) with xr.set_options(use_flox=use_flox): with pytest.raises(TypeError): da.groupby("labels").mean(min_count=1) @requires_dask def test_groupby_math_auto_chunk() -> None: da = xr.DataArray( [[1, 2, 3], [1, 2, 3], [1, 2, 3]], dims=("y", "x"), coords={"label": ("x", [2, 2, 1])}, ) sub = xr.DataArray( InaccessibleArray(np.array([1, 2])), dims="label", coords={"label": [1, 2]} ) chunked = da.chunk(x=1, y=2) chunked.label.load() actual = chunked.groupby("label") - sub assert actual.chunksizes == {"x": (1, 1, 1), "y": (2, 1)} @pytest.mark.parametrize("use_flox", [True, False]) def test_groupby_dim_no_dim_equal(use_flox: bool) -> None: # https://github.com/pydata/xarray/issues/8263 da = DataArray( data=[1, 2, 3, 4], dims="lat", coords={"lat": np.linspace(0, 1.01, 4)} ) with xr.set_options(use_flox=use_flox): actual1 = da.drop_vars("lat").groupby("lat").sum() actual2 = da.groupby("lat").sum() assert_identical(actual1, actual2.drop_vars("lat")) @requires_flox def test_default_flox_method() -> None: import flox.xarray da = xr.DataArray([1, 2, 3], dims="x", coords={"label": ("x", [2, 2, 1])}) result = xr.DataArray([3, 3], dims="label", coords={"label": [1, 2]}) with mock.patch("flox.xarray.xarray_reduce", return_value=result) as mocked_reduce: da.groupby("label").sum() kwargs = mocked_reduce.call_args.kwargs if Version(flox.__version__) < Version("0.9.0"): assert kwargs["method"] == "cohorts" else: assert "method" not in kwargs @requires_cftime @pytest.mark.filterwarnings("ignore") def test_cftime_resample_gh_9108() -> None: import cftime ds = Dataset( {"pr": ("time", np.random.random((10,)))}, coords={"time": xr.date_range("0001-01-01", periods=10, freq="D")}, ) actual = ds.resample(time="ME").mean() expected = ds.mean("time").expand_dims( time=[cftime.DatetimeGregorian(1, 1, 31, 0, 0, 0, 0, has_year_zero=False)] ) assert actual.time.data[0].has_year_zero == ds.time.data[0].has_year_zero assert_equal(actual, expected) def test_custom_grouper() -> None: class YearGrouper(Grouper): """ An example re-implementation of ``.groupby("time.year")``. """ def factorize(self, group) -> EncodedGroups: assert np.issubdtype(group.dtype, np.datetime64) year = group.dt.year.data codes_, uniques = pd.factorize(year) codes = group.copy(data=codes_).rename("year") return EncodedGroups(codes=codes, full_index=pd.Index(uniques)) def reset(self): return type(self)() da = xr.DataArray( dims="time", data=np.arange(20), coords={"time": ("time", pd.date_range("2000-01-01", freq="3MS", periods=20))}, name="foo", ) ds = da.to_dataset() expected = ds.groupby("time.year").mean() actual = ds.groupby(time=YearGrouper()).mean() assert_identical(expected, actual) actual = ds.groupby({"time": YearGrouper()}).mean() assert_identical(expected, actual) expected = ds.foo.groupby("time.year").mean() actual = ds.foo.groupby(time=YearGrouper()).mean() assert_identical(expected, actual) actual = ds.foo.groupby({"time": YearGrouper()}).mean() assert_identical(expected, actual) for obj in [ds, ds.foo]: with pytest.raises(ValueError): obj.groupby("time.year", time=YearGrouper()) with pytest.raises(ValueError): obj.groupby() @pytest.mark.parametrize("use_flox", [True, False]) def test_weather_data_resample(use_flox): # from the docs times = pd.date_range("2000-01-01", "2001-12-31", name="time") annual_cycle = np.sin(2 * np.pi * (times.dayofyear.values / 365.25 - 0.28)) base = 10 + 15 * annual_cycle.reshape(-1, 1) tmin_values = base + 3 * np.random.randn(annual_cycle.size, 3) tmax_values = base + 10 + 3 * np.random.randn(annual_cycle.size, 3) ds = xr.Dataset( { "tmin": (("time", "location"), tmin_values), "tmax": (("time", "location"), tmax_values), }, { "time": ("time", times, {"time_key": "time_values"}), "location": ("location", ["IA", "IN", "IL"], {"loc_key": "loc_value"}), }, ) with xr.set_options(use_flox=use_flox): actual = ds.resample(time="1MS").mean() assert "location" in actual._indexes gb = ds.groupby(time=TimeResampler(freq="1MS"), location=UniqueGrouper()) with xr.set_options(use_flox=use_flox): actual = gb.mean() expected = ds.resample(time="1MS").mean().sortby("location") assert_allclose(actual, expected) assert actual.time.attrs == ds.time.attrs assert actual.location.attrs == ds.location.attrs assert expected.time.attrs == ds.time.attrs assert expected.location.attrs == ds.location.attrs @pytest.mark.parametrize("as_dataset", [True, False]) def test_multiple_groupers_string(as_dataset) -> None: obj = DataArray( np.array([1, 2, 3, 0, 2, np.nan]), dims="d", coords=dict( labels1=("d", np.array(["a", "b", "c", "c", "b", "a"])), labels2=("d", np.array(["x", "y", "z", "z", "y", "x"])), ), name="foo", ) if as_dataset: obj = obj.to_dataset() # type: ignore[assignment] expected = obj.groupby(labels1=UniqueGrouper(), labels2=UniqueGrouper()).mean() actual = obj.groupby(("labels1", "labels2")).mean() assert_identical(expected, actual) # Passes `"labels2"` to squeeze; will raise an error around kwargs rather than the # warning & type error in the future with pytest.warns(FutureWarning): with pytest.raises(TypeError): obj.groupby("labels1", "labels2") # type: ignore[arg-type, misc] with pytest.raises(ValueError): obj.groupby("labels1", foo="bar") # type: ignore[arg-type] with pytest.raises(ValueError): obj.groupby("labels1", foo=UniqueGrouper()) @pytest.mark.parametrize("shuffle", [True, False]) @pytest.mark.parametrize("use_flox", [True, False]) def test_multiple_groupers(use_flox: bool, shuffle: bool) -> None: da = DataArray( np.array([1, 2, 3, 0, 2, np.nan]), dims="d", coords=dict( labels1=("d", np.array(["a", "b", "c", "c", "b", "a"])), labels2=("d", np.array(["x", "y", "z", "z", "y", "x"])), ), name="foo", ) groupers: dict[str, Grouper] groupers = dict(labels1=UniqueGrouper(), labels2=UniqueGrouper()) gb = da.groupby(groupers) if shuffle: gb = gb.shuffle_to_chunks().groupby(groupers) repr(gb) expected = DataArray( np.array([[1.0, np.nan, np.nan], [np.nan, 2.0, np.nan], [np.nan, np.nan, 1.5]]), dims=("labels1", "labels2"), coords={ "labels1": np.array(["a", "b", "c"], dtype=object), "labels2": np.array(["x", "y", "z"], dtype=object), }, name="foo", ) with xr.set_options(use_flox=use_flox): actual = gb.mean() assert_identical(actual, expected) # ------- coords = {"a": ("x", [0, 0, 1, 1]), "b": ("y", [0, 0, 1, 1])} square = DataArray(np.arange(16).reshape(4, 4), coords=coords, dims=["x", "y"]) groupers = dict(a=UniqueGrouper(), b=UniqueGrouper()) gb = square.groupby(groupers) if shuffle: gb = gb.shuffle_to_chunks().groupby(groupers) repr(gb) with xr.set_options(use_flox=use_flox): actual = gb.mean() expected = DataArray( np.array([[2.5, 4.5], [10.5, 12.5]]), dims=("a", "b"), coords={"a": [0, 1], "b": [0, 1]}, ) assert_identical(actual, expected) expected = square.astype(np.float64) expected["a"], expected["b"] = broadcast(square.a, square.b) with xr.set_options(use_flox=use_flox): assert_identical( square.groupby(x=UniqueGrouper(), y=UniqueGrouper()).mean(), expected ) b = xr.DataArray( np.random.default_rng(0).random((2, 3, 4)), coords={"xy": (("x", "y"), [["a", "b", "c"], ["b", "c", "c"]], {"foo": "bar"})}, dims=["x", "y", "z"], ) groupers = dict(x=UniqueGrouper(), y=UniqueGrouper()) gb = b.groupby(groupers) if shuffle: gb = gb.shuffle_to_chunks().groupby(groupers) repr(gb) with xr.set_options(use_flox=use_flox): assert_identical(gb.mean("z"), b.mean("z")) groupers = dict(x=UniqueGrouper(), xy=UniqueGrouper()) gb = b.groupby(groupers) if shuffle: gb = gb.shuffle_to_chunks().groupby(groupers) repr(gb) with xr.set_options(use_flox=use_flox): actual = gb.mean() expected = b.drop_vars("xy").rename({"y": "xy"}).copy(deep=True) newval = b.isel(x=1, y=slice(1, None)).mean("y").data expected.loc[dict(x=1, xy=1)] = expected.sel(x=1, xy=0).data expected.loc[dict(x=1, xy=0)] = np.nan expected.loc[dict(x=1, xy=2)] = newval expected["xy"] = ("xy", ["a", "b", "c"], {"foo": "bar"}) # TODO: is order of dims correct? assert_identical(actual, expected.transpose("z", "x", "xy")) if has_dask: b["xy"] = b["xy"].chunk() expected = xr.DataArray( [[[1, 1, 1], [np.nan, 1, 2]]] * 4, dims=("z", "x", "xy"), coords={"xy": ("xy", ["a", "b", "c"], {"foo": "bar"})}, ) with raise_if_dask_computes(max_computes=0): gb = b.groupby(x=UniqueGrouper(), xy=UniqueGrouper(labels=["a", "b", "c"])) assert is_chunked_array(gb.encoded.codes.data) assert not gb.encoded.group_indices if has_flox: with raise_if_dask_computes(max_computes=1): assert_identical(gb.count(), expected) else: with pytest.raises(ValueError, match="when lazily grouping"): gb.count() @pytest.mark.parametrize("use_flox", [True, False]) @pytest.mark.parametrize("shuffle", [True, False]) def test_multiple_groupers_mixed(use_flox: bool, shuffle: bool) -> None: # This groupby has missing groups ds = xr.Dataset( {"foo": (("x", "y"), np.arange(12).reshape((4, 3)))}, coords={"x": [10, 20, 30, 40], "letters": ("x", list("abba"))}, ) groupers: dict[str, Grouper] = dict( x=BinGrouper(bins=[5, 15, 25]), letters=UniqueGrouper() ) gb = ds.groupby(groupers) if shuffle: gb = gb.shuffle_to_chunks().groupby(groupers) expected_data = np.array( [ [[0.0, np.nan], [np.nan, 3.0]], [[1.0, np.nan], [np.nan, 4.0]], [[2.0, np.nan], [np.nan, 5.0]], ] ) expected = xr.Dataset( {"foo": (("y", "x_bins", "letters"), expected_data)}, coords={ "x_bins": ( "x_bins", np.array( [ pd.Interval(5, 15, closed="right"), pd.Interval(15, 25, closed="right"), ], dtype=object, ), ), "letters": ("letters", np.array(["a", "b"], dtype=object)), }, ) with xr.set_options(use_flox=use_flox): actual = gb.sum() assert_identical(actual, expected) # assert_identical( # b.groupby(['x', 'y']).apply(lambda x: x - x.mean()), # b - b.mean("z"), # ) # gb = square.groupby(x=UniqueGrouper(), y=UniqueGrouper()) # gb - gb.mean() # ------ @requires_flox_0_9_12 @pytest.mark.parametrize( "reduction", ["max", "min", "nanmax", "nanmin", "sum", "nansum", "prod", "nanprod"] ) def test_groupby_preserve_dtype(reduction): # all groups are present, we should follow numpy exactly ds = xr.Dataset( { "test": ( ["x", "y"], np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype="int16"), ) }, coords={"idx": ("x", [1, 2, 1])}, ) kwargs = {} if "nan" in reduction: kwargs["skipna"] = True # TODO: fix dtype with numbagg/bottleneck and use_flox=False with xr.set_options(use_numbagg=False, use_bottleneck=False): actual = getattr(ds.groupby("idx"), reduction.removeprefix("nan"))( **kwargs ).test.dtype expected = getattr(np, reduction)(ds.test.data, axis=0).dtype assert actual == expected @requires_dask @requires_flox_0_9_12 @pytest.mark.parametrize("reduction", ["any", "all", "count"]) def test_gappy_resample_reductions(reduction): # GH8090 dates = (("1988-12-01", "1990-11-30"), ("2000-12-01", "2001-11-30")) times = [xr.date_range(*d, freq="D") for d in dates] da = xr.concat( [ xr.DataArray(np.random.rand(len(t)), coords={"time": t}, dims="time") for t in times ], dim="time", ).chunk(time=100) rs = (da > 0.5).resample(time="YS-DEC") method = getattr(rs, reduction) with xr.set_options(use_flox=True): actual = method(dim="time") with xr.set_options(use_flox=False): expected = method(dim="time") assert_identical(expected, actual) def test_groupby_transpose() -> None: # GH5361 data = xr.DataArray( np.random.randn(4, 2), dims=["x", "z"], coords={"x": ["a", "b", "a", "c"], "y": ("x", [0, 1, 0, 2])}, ) first = data.T.groupby("x").sum() second = data.groupby("x").sum() assert_identical(first, second.transpose(*first.dims)) @requires_dask @pytest.mark.parametrize( "grouper, expect_index", [ [UniqueGrouper(labels=np.arange(1, 5)), pd.Index(np.arange(1, 5))], [UniqueGrouper(labels=np.arange(1, 5)[::-1]), pd.Index(np.arange(1, 5)[::-1])], [ BinGrouper(bins=np.arange(1, 5)), pd.IntervalIndex.from_breaks(np.arange(1, 5)), ], ], ) def test_lazy_grouping(grouper, expect_index): import dask.array data = DataArray( dims=("x", "y"), data=dask.array.arange(20, chunks=3).reshape((4, 5)), name="zoo", ) with raise_if_dask_computes(): encoded = grouper.factorize(data) assert encoded.codes.ndim == data.ndim pd.testing.assert_index_equal(encoded.full_index, expect_index) np.testing.assert_array_equal(encoded.unique_coord.values, np.array(expect_index)) eager = ( xr.Dataset({"foo": data}, coords={"zoo": data.compute()}) .groupby(zoo=grouper) .count() ) expected = Dataset( {"foo": (encoded.codes.name, np.ones(encoded.full_index.size))}, coords={encoded.codes.name: expect_index}, ) assert_identical(eager, expected) if has_flox: lazy = ( xr.Dataset({"foo": data}, coords={"zoo": data}).groupby(zoo=grouper).count() ) assert_identical(eager, lazy) @requires_dask def test_lazy_grouping_errors() -> None: import dask.array data = DataArray( dims=("x",), data=dask.array.arange(20, chunks=3), name="foo", coords={"y": ("x", dask.array.arange(20, chunks=3))}, ) gb = data.groupby(y=UniqueGrouper(labels=np.arange(5, 10))) message = "not supported when lazily grouping by" with pytest.raises(ValueError, match=message): gb.map(lambda x: x) with pytest.raises(ValueError, match=message): gb.reduce(np.mean) with pytest.raises(ValueError, match=message): for _, _ in gb: pass @requires_dask def test_lazy_int_bins_error() -> None: import dask.array with pytest.raises(ValueError, match="Bin edges must be provided"): with raise_if_dask_computes(): _ = BinGrouper(bins=4).factorize(DataArray(dask.array.arange(3))) def test_time_grouping_seasons_specified() -> None: time = xr.date_range("2001-01-01", "2002-01-01", freq="D") ds = xr.Dataset({"foo": np.arange(time.size)}, coords={"time": ("time", time)}) labels = ["DJF", "MAM", "JJA", "SON"] actual = ds.groupby({"time.season": UniqueGrouper(labels=labels)}).sum() expected = ds.groupby("time.season").sum() assert_identical(actual, expected.reindex(season=labels)) def test_multiple_grouper_unsorted_order() -> None: time = xr.date_range("2001-01-01", "2003-01-01", freq="MS") ds = xr.Dataset({"foo": np.arange(time.size)}, coords={"time": ("time", time)}) labels = ["DJF", "MAM", "JJA", "SON"] actual = ds.groupby( { "time.season": UniqueGrouper(labels=labels), "time.year": UniqueGrouper(labels=[2002, 2001]), } ).sum() expected = ( ds.groupby({"time.season": UniqueGrouper(), "time.year": UniqueGrouper()}) .sum() .reindex(season=labels, year=[2002, 2001]) ) assert_identical(actual, expected.reindex(season=labels)) b = xr.DataArray( np.random.default_rng(0).random((2, 3, 4)), coords={"x": [0, 1], "y": [0, 1, 2]}, dims=["x", "y", "z"], ) actual2 = b.groupby( x=UniqueGrouper(labels=[1, 0]), y=UniqueGrouper(labels=[2, 0, 1]) ).sum() expected2 = b.reindex(x=[1, 0], y=[2, 0, 1]).transpose("z", ...) assert_identical(actual2, expected2) def test_multiple_grouper_empty_groups() -> None: ds = xr.Dataset( {"foo": (("x", "y"), np.random.rand(4, 3))}, coords={"x": [10, 20, 30, 40], "letters": ("x", list("abba"))}, ) groups = ds.groupby(x=BinGrouper(bins=[5, 15, 25]), letters=UniqueGrouper()) assert len(groups.groups) == 2 def test_groupby_multiple_bin_grouper_missing_groups() -> None: from numpy import nan ds = xr.Dataset( {"foo": (("z"), np.arange(12))}, coords={"x": ("z", np.arange(12)), "y": ("z", np.arange(12))}, ) actual = ds.groupby( x=BinGrouper(np.arange(0, 13, 4)), y=BinGrouper(bins=np.arange(0, 16, 2)) ).count() expected = Dataset( { "foo": ( ("x_bins", "y_bins"), np.array( [ [2.0, 2.0, nan, nan, nan, nan, nan], [nan, nan, 2.0, 2.0, nan, nan, nan], [nan, nan, nan, nan, 2.0, 1.0, nan], ] ), ) }, coords={ "x_bins": ("x_bins", pd.IntervalIndex.from_breaks(np.arange(0, 13, 4))), "y_bins": ("y_bins", pd.IntervalIndex.from_breaks(np.arange(0, 16, 2))), }, ) assert_identical(actual, expected) @requires_dask_ge_2024_08_1 def test_shuffle_simple() -> None: import dask da = xr.DataArray( dims="x", data=dask.array.from_array([1, 2, 3, 4, 5, 6], chunks=2), coords={"label": ("x", ["a", "b", "c", "a", "b", "c"])}, ) actual = da.groupby(label=UniqueGrouper()).shuffle_to_chunks() expected = da.isel(x=[0, 3, 1, 4, 2, 5]) assert_identical(actual, expected) with pytest.raises(ValueError): da.chunk(x=2, eagerly_load_group=False).groupby("label").shuffle_to_chunks() @requires_dask_ge_2024_08_1 @pytest.mark.parametrize( "chunks, expected_chunks", [ ((1,), (1, 3, 3, 3)), ((10,), (10,)), ], ) def test_shuffle_by(chunks, expected_chunks): import dask.array da = xr.DataArray( dims="x", data=dask.array.arange(10, chunks=chunks), coords={"x": [1, 2, 3, 1, 2, 3, 1, 2, 3, 0]}, name="a", ) ds = da.to_dataset() for obj in [ds, da]: actual = obj.groupby(x=UniqueGrouper()).shuffle_to_chunks() assert_identical(actual, obj.sortby("x")) assert actual.chunksizes["x"] == expected_chunks @requires_dask def test_groupby_dask_eager_load_warnings() -> None: ds = xr.Dataset( {"foo": (("z"), np.arange(12))}, coords={"x": ("z", np.arange(12)), "y": ("z", np.arange(12))}, ).chunk(z=6) with pytest.raises(ValueError, match="Please pass"): with pytest.warns(DeprecationWarning): ds.groupby("x", eagerly_compute_group=False) with pytest.raises(ValueError, match="Eagerly computing"): ds.groupby("x", eagerly_compute_group=True) # type: ignore[arg-type] # This is technically fine but anyone iterating over the groupby object # will see an error, so let's warn and have them opt-in. ds.groupby(x=UniqueGrouper(labels=[1, 2, 3])) with pytest.warns(DeprecationWarning): ds.groupby(x=UniqueGrouper(labels=[1, 2, 3]), eagerly_compute_group=False) with pytest.raises(ValueError, match="Please pass"): with pytest.warns(DeprecationWarning): ds.groupby_bins("x", bins=3, eagerly_compute_group=False) with pytest.raises(ValueError, match="Eagerly computing"): ds.groupby_bins("x", bins=3, eagerly_compute_group=True) # type: ignore[arg-type] ds.groupby_bins("x", bins=[1, 2, 3]) with pytest.warns(DeprecationWarning): ds.groupby_bins("x", bins=[1, 2, 3], eagerly_compute_group=False)
TestDatasetResample
python
great-expectations__great_expectations
great_expectations/render/components.py
{ "start": 13763, "end": 15779 }
class ____(RenderedComponentContent): def __init__( # noqa: PLR0913 # FIXME CoP self, table_data, table_columns, title_row=None, table_options=None, header=None, subheader=None, styling=None, content_block_type="bootstrap_table", ) -> None: super().__init__(content_block_type=content_block_type, styling=styling) self.table_data = table_data self.table_columns = table_columns self.title_row = title_row self.table_options = table_options self.header = header self.subheader = subheader @override def to_json_dict(self) -> dict[str, JSONValues]: """Returns a JSON-serializable dict representation of this RenderedBootstrapTableContent. Returns: A JSON-serializable dict representation of this RenderedBootstrapTableContent. """ d = super().to_json_dict() d["table_data"] = RenderedContent.rendered_content_list_to_json( self.table_data, check_dicts=True ) d["table_columns"] = RenderedContent.rendered_content_list_to_json( self.table_columns, check_dicts=True ) if self.table_options is not None: d["table_options"] = self.table_options if self.title_row is not None: if isinstance(self.title_row, RenderedContent): d["title_row"] = self.title_row.to_json_dict() else: d["title_row"] = self.title_row if self.header is not None: if isinstance(self.header, RenderedContent): d["header"] = self.header.to_json_dict() else: d["header"] = self.header if self.subheader is not None: if isinstance(self.subheader, RenderedContent): d["subheader"] = self.subheader.to_json_dict() else: d["subheader"] = self.subheader return d
RenderedBootstrapTableContent
python
davidhalter__parso
parso/pgen2/generator.py
{ "start": 1854, "end": 2256 }
class ____: """ Plans are used for the parser to create stack nodes and do the proper DFA state transitions. """ def __init__(self, next_dfa: 'DFAState', dfa_pushes: Sequence['DFAState'] = []): self.next_dfa = next_dfa self.dfa_pushes = dfa_pushes def __repr__(self): return '%s(%s, %s)' % (self.__class__.__name__, self.next_dfa, self.dfa_pushes)
DFAPlan
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess19.py
{ "start": 161, "end": 1516 }
class ____: @overload def __getattr__(self, key: Literal["a"]) -> Literal["x"]: ... @overload def __getattr__(self, key: Literal["b"]) -> Literal[4]: ... @overload def __getattr__(self, key: Literal["c"]) -> Literal["y"]: ... @overload def __getattr__(self: T, key: Literal["d"]) -> T: ... def __getattr__(self, key: Literal["a", "b", "c", "d"]) -> Any: ... @overload def __setattr__(self, key: Literal["e"], val: str): ... @overload def __setattr__(self, key: Literal["f"], val: int): ... def __setattr__(self, key: str, val: str | int): pass @overload def __delattr__(self, key: Literal["g"]): ... @overload def __delattr__(self, key: Literal["h"]): ... def __delattr__(self, key: str): pass a = A() reveal_type(a.a, expected_text="Literal['x']") reveal_type(a.b, expected_text="Literal[4]") reveal_type(a.c, expected_text="Literal['y']") reveal_type(a.d, expected_text="A") # This should generate an error. reveal_type(a.e) # This should generate an error. a.a = 4 a.e = "4" # This should generate an error. a.e = 4 # This should generate an error. a.f = "4" a.f = 4 # This should generate an error. del a.e del a.g del a.h # Test asymmetric __getattr__ and __setattr__ methods. We should not # narrow the type on assignment in this case.
A
python
getsentry__sentry
src/sentry/issues/endpoints/project_ownership.py
{ "start": 7013, "end": 11800 }
class ____(ProjectEndpoint): owner = ApiOwner.ISSUES publish_status = { "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } permission_classes = (ProjectOwnershipPermission,) def get_ownership(self, project: Project) -> ProjectOwnership: try: return ProjectOwnership.objects.get(project=project) except ProjectOwnership.DoesNotExist: # XXX: the values for last_updated / date_created aren't valid but # this is the "simplest" way to show an empty state in the api return ProjectOwnership(project=project, last_updated=None, date_created=None) # type: ignore[misc] def refresh_ownership_schema(self, ownership: ProjectOwnership, project: Project) -> None: if hasattr(ownership, "schema") and ( ownership.schema is None or ownership.schema.get("rules") is None ): return ownership.schema = create_schema_from_issue_owners( project_id=project.id, issue_owners=ownership.raw, remove_deleted_owners=True, ) ownership.save() def rename_schema_identifier_for_parsing(self, ownership: ProjectOwnership) -> None: """ Rename the attribute "identifier" to "name" in the schema response so that it can be parsed in the frontend `ownership`: The ownership containing the schema with the rules that will be renamed """ if hasattr(ownership, "schema") and ownership.schema and ownership.schema.get("rules"): for rule in ownership.schema["rules"]: for rule_owner in rule["owners"]: rule_owner["name"] = rule_owner.pop("identifier") @extend_schema( operation_id="Retrieve Ownership Configuration for a Project", parameters=[ GlobalParams.ORG_ID_OR_SLUG, GlobalParams.PROJECT_ID_OR_SLUG, ], request=None, responses={200: ProjectOwnershipSerializer}, examples=ownership_examples.GET_PROJECT_OWNERSHIP, ) def get(self, request: Request, project) -> Response: """ Returns details on a project's ownership configuration. """ ownership = self.get_ownership(project) if ownership: self.refresh_ownership_schema(ownership, project) self.rename_schema_identifier_for_parsing(ownership) return Response(serialize(ownership, request.user)) @extend_schema( operation_id="Update Ownership Configuration for a Project", parameters=[ GlobalParams.ORG_ID_OR_SLUG, GlobalParams.PROJECT_ID_OR_SLUG, ], request=ProjectOwnershipRequestSerializer, responses={ 202: ProjectOwnershipSerializer, 400: RESPONSE_BAD_REQUEST, }, examples=ownership_examples.UPDATE_PROJECT_OWNERSHIP, ) def put(self, request: Request, project) -> Response: """ Updates ownership configurations for a project. Note that only the attributes submitted are modified. """ # Ownership settings others than "raw" ownership rules can only be updated by # users with the organization-level owner, manager, or team-level admin roles has_project_write = request.access and ( request.access.has_scope("project:write") or request.access.has_project_scope(project, "project:write") ) if list(request.data) != ["raw"] and not has_project_write: raise PermissionDenied serializer = ProjectOwnershipRequestSerializer( data=request.data, partial=True, context={"ownership": self.get_ownership(project)} ) if serializer.is_valid(): ownership = serializer.save() change_data = {**serializer.validated_data} # Ownership rules can be large (3 MB) and we don't want to store them in the audit log if "raw" in change_data and "schema" in change_data: del change_data["schema"] del change_data["raw"] change_data["ownership_rules"] = "modified" create_audit_entry( request=self.request, actor=request.user, organization=project.organization, target_object=project.id, event=audit_log.get_event_id("PROJECT_OWNERSHIPRULE_EDIT"), data={**change_data, **project.get_audit_log_data()}, ) ownership_rule_created.send_robust(project=project, sender=self.__class__) return Response(serialize(ownership, request.user)) return Response(serializer.errors, status=400)
ProjectOwnershipEndpoint
python
sqlalchemy__sqlalchemy
test/sql/test_query.py
{ "start": 26291, "end": 28255 }
class ____(fixtures.TablesTest): run_create_tables = None run_deletes = None @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column("id", Integer, primary_key=True), Column("data", String(50)), Column("x", Integer), ) def _assert_raises(self, stmt, params): with testing.db.connect() as conn: assert_raises_message( exc.StatementError, "A value is required for bind parameter 'x'", conn.execute, stmt, params, ) def test_insert(self): stmt = self.tables.foo.insert().values( x=bindparam("x"), data=bindparam("data") ) self._assert_raises(stmt, {"data": "data"}) def test_select_where(self): stmt = ( select(self.tables.foo) .where(self.tables.foo.c.data == bindparam("data")) .where(self.tables.foo.c.x == bindparam("x")) ) self._assert_raises(stmt, {"data": "data"}) @testing.requires.standalone_binds def test_select_columns(self): stmt = select(bindparam("data"), bindparam("x")) self._assert_raises(stmt, {"data": "data"}) def test_text(self): stmt = text("select * from foo where x=:x and data=:data1") self._assert_raises(stmt, {"data1": "data"}) def test_required_flag(self): is_(bindparam("foo").required, True) is_(bindparam("foo", required=False).required, False) is_(bindparam("foo", "bar").required, False) is_(bindparam("foo", "bar", required=True).required, True) def c(): return None is_(bindparam("foo", callable_=c, required=True).required, True) is_(bindparam("foo", callable_=c).required, False) is_(bindparam("foo", callable_=c, required=False).required, False)
RequiredBindTest
python
aimacode__aima-python
nlp.py
{ "start": 19046, "end": 20882 }
class ____(object): """If the hub and authority values of the pages are no longer changing, we have reached a convergence and further iterations will have no effect. This detects convergence so that we can stop the HITS algorithm as early as possible.""" def __init__(self): self.hub_history = None self.auth_history = None def __call__(self): return self.detect() def detect(self): curr_hubs = [page.hub for addr, page in pagesIndex.items()] curr_auths = [page.authority for addr, page in pagesIndex.items()] if self.hub_history is None: self.hub_history, self.auth_history = [], [] else: diffsHub = [abs(x - y) for x, y in zip(curr_hubs, self.hub_history[-1])] diffsAuth = [abs(x - y) for x, y in zip(curr_auths, self.auth_history[-1])] aveDeltaHub = sum(diffsHub) / float(len(pagesIndex)) aveDeltaAuth = sum(diffsAuth) / float(len(pagesIndex)) if aveDeltaHub < 0.01 and aveDeltaAuth < 0.01: # may need tweaking return True if len(self.hub_history) > 2: # prevent list from getting long del self.hub_history[0] del self.auth_history[0] self.hub_history.append([x for x in curr_hubs]) self.auth_history.append([x for x in curr_auths]) return False def getInLinks(page): if not page.inlinks: page.inlinks = determineInlinks(page) return [addr for addr, p in pagesIndex.items() if addr in page.inlinks] def getOutLinks(page): if not page.outlinks: page.outlinks = findOutlinks(page) return [addr for addr, p in pagesIndex.items() if addr in page.outlinks] # ______________________________________________________________________________ # HITS Algorithm
ConvergenceDetector
python
optuna__optuna
optuna/visualization/_param_importances.py
{ "start": 664, "end": 7379 }
class ____(NamedTuple): importance_values: list[float] param_names: list[str] importance_labels: list[str] target_name: str def _get_importances_info( study: Study, evaluator: BaseImportanceEvaluator | None, params: list[str] | None, target: Callable[[FrozenTrial], float] | None, target_name: str, ) -> _ImportancesInfo: _check_plot_args(study, target, target_name) trials = _filter_nonfinite( study.get_trials(deepcopy=False, states=(TrialState.COMPLETE,)), target=target ) if len(trials) == 0: logger.warning("Study instance does not contain completed trials.") return _ImportancesInfo( importance_values=[], param_names=[], importance_labels=[], target_name=target_name, ) importances = optuna.importance.get_param_importances( study, evaluator=evaluator, params=params, target=target ) importances = dict(reversed(list(importances.items()))) importance_values = list(importances.values()) param_names = list(importances.keys()) importance_labels = [f"{val:.2f}" if val >= 0.01 else "<0.01" for val in importance_values] return _ImportancesInfo( importance_values=importance_values, param_names=param_names, importance_labels=importance_labels, target_name=target_name, ) def _get_importances_infos( study: Study, evaluator: BaseImportanceEvaluator | None, params: list[str] | None, target: Callable[[FrozenTrial], float] | None, target_name: str, ) -> tuple[_ImportancesInfo, ...]: metric_names = study.metric_names if target or not study._is_multi_objective(): target_name = metric_names[0] if metric_names is not None and not target else target_name importances_infos: tuple[_ImportancesInfo, ...] = ( _get_importances_info( study, evaluator, params, target=target, target_name=target_name, ), ) else: n_objectives = len(study.directions) target_names = ( metric_names if metric_names is not None else (f"{target_name} {objective_id}" for objective_id in range(n_objectives)) ) importances_infos = tuple( _get_importances_info( study, evaluator, params, target=lambda t: t.values[objective_id], target_name=target_name, ) for objective_id, target_name in enumerate(target_names) ) return importances_infos def plot_param_importances( study: Study, evaluator: BaseImportanceEvaluator | None = None, params: list[str] | None = None, *, target: Callable[[FrozenTrial], float] | None = None, target_name: str = "Objective Value", ) -> "go.Figure": """Plot hyperparameter importances. .. seealso:: This function visualizes the results of :func:`optuna.importance.get_param_importances`. Args: study: An optimized study. evaluator: An importance evaluator object that specifies which algorithm to base the importance assessment on. Defaults to :class:`~optuna.importance.FanovaImportanceEvaluator`. .. note:: Although the default importance evaluator in Optuna is :class:`~optuna.importance.FanovaImportanceEvaluator`, Optuna Dashboard uses a light-weight evaluator, i.e., :class:`~optuna.importance.PedAnovaImportanceEvaluator`, for runtime performance purposes, yielding a different result. params: A list of names of parameters to assess. If :obj:`None`, all parameters that are present in all of the completed trials are assessed. target: A function to specify the value to display. If it is :obj:`None` and ``study`` is being used for single-objective optimization, the objective values are plotted. For multi-objective optimization, all objectives will be plotted if ``target`` is :obj:`None`. .. note:: This argument can be used to specify which objective to plot if ``study`` is being used for multi-objective optimization. For example, to get only the hyperparameter importance of the first objective, use ``target=lambda t: t.values[0]`` for the target parameter. target_name: Target's name to display on the legend. Names set via :meth:`~optuna.study.Study.set_metric_names` will be used if ``target`` is :obj:`None`, overriding this argument. Returns: A :class:`plotly.graph_objects.Figure` object. """ _imports.check() importances_infos = _get_importances_infos(study, evaluator, params, target, target_name) return _get_importances_plot(importances_infos, study) def _get_importances_plot(infos: tuple[_ImportancesInfo, ...], study: Study) -> "go.Figure": layout = go.Layout( title="Hyperparameter Importances", xaxis={"title": "Hyperparameter Importance"}, yaxis={"title": "Hyperparameter"}, ) data: list[go.Bar] = [] for info in infos: if not info.importance_values: continue data.append( go.Bar( x=info.importance_values, y=info.param_names, name=info.target_name, text=info.importance_labels, textposition="outside", cliponaxis=False, # Ensure text is not clipped. hovertemplate=_get_hover_template(info, study), orientation="h", ) ) return go.Figure(data, layout) def _get_distribution(param_name: str, study: Study) -> BaseDistribution: for trial in study.trials: if param_name in trial.distributions: return trial.distributions[param_name] assert False def _make_hovertext(param_name: str, importance: float, study: Study) -> str: class_name = _get_distribution(param_name, study).__class__.__name__ return f"{param_name} ({class_name}): {importance}<extra></extra>" def _get_hover_template(importances_info: _ImportancesInfo, study: Study) -> list[str]: return [ _make_hovertext(param_name, importance, study) for param_name, importance in zip( importances_info.param_names, importances_info.importance_values ) ]
_ImportancesInfo
python
kamyu104__LeetCode-Solutions
Python/edit-distance.py
{ "start": 816, "end": 1441 }
class ____(object): # @return an integer def minDistance(self, word1, word2): distance = [[i] for i in xrange(len(word1) + 1)] distance[0] = [j for j in xrange(len(word2) + 1)] for i in xrange(1, len(word1) + 1): for j in xrange(1, len(word2) + 1): insert = distance[i][j - 1] + 1 delete = distance[i - 1][j] + 1 replace = distance[i - 1][j - 1] if word1[i - 1] != word2[j - 1]: replace += 1 distance[i].append(min(insert, delete, replace)) return distance[-1][-1]
Solution2
python
MongoEngine__mongoengine
tests/queryset/test_transform.py
{ "start": 171, "end": 14221 }
class ____(MongoDBTestCase): def test_transform_str_datetime(self): data = {"date": {"$ne": "2015-12-01T00:00:00"}} assert transform.query(**data) == {"date": {"$ne": "2015-12-01T00:00:00"}} assert transform.query(date__ne="2015-12-01T00:00:00") == { "date": {"$ne": "2015-12-01T00:00:00"} } def test_transform_query(self): """Ensure that the _transform_query function operates correctly.""" assert transform.query(name="test", age=30) == {"name": "test", "age": 30} assert transform.query(age__lt=30) == {"age": {"$lt": 30}} assert transform.query(age__gt=20, age__lt=50) == { "age": {"$gt": 20, "$lt": 50} } assert transform.query(age=20, age__gt=50) == { "$and": [{"age": {"$gt": 50}}, {"age": 20}] } assert transform.query(friend__age__gte=30) == {"friend.age": {"$gte": 30}} assert transform.query(name__exists=True) == {"name": {"$exists": True}} assert transform.query(name=["Mark"], __raw__={"name": {"$in": "Tom"}}) == { "$and": [{"name": ["Mark"]}, {"name": {"$in": "Tom"}}] } assert transform.query(name__in=["Tom"], __raw__={"name": "Mark"}) == { "$and": [{"name": {"$in": ["Tom"]}}, {"name": "Mark"}] } def test_transform_update(self): class LisDoc(Document): foo = ListField(StringField()) class DicDoc(Document): dictField = DictField() class Doc(Document): pass LisDoc.drop_collection() DicDoc.drop_collection() Doc.drop_collection() DicDoc().save() doc = Doc().save() for k, v in ( ("set", "$set"), ("set_on_insert", "$setOnInsert"), ("push", "$push"), ): update = transform.update(DicDoc, **{"%s__dictField__test" % k: doc}) assert isinstance(update[v]["dictField.test"], dict) # Update special cases update = transform.update(DicDoc, unset__dictField__test=doc) assert update["$unset"]["dictField.test"] == 1 update = transform.update(DicDoc, pull__dictField__test=doc) assert isinstance(update["$pull"]["dictField"]["test"], dict) update = transform.update(LisDoc, pull__foo__in=["a"]) assert update == {"$pull": {"foo": {"$in": ["a"]}}} def test_transform_update_push(self): """Ensure the differences in behvaior between 'push' and 'push_all'""" class BlogPost(Document): tags = ListField(StringField()) update = transform.update(BlogPost, push__tags=["mongo", "db"]) assert update == {"$push": {"tags": ["mongo", "db"]}} update = transform.update(BlogPost, push_all__tags=["mongo", "db"]) assert update == {"$push": {"tags": {"$each": ["mongo", "db"]}}} def test_transform_update_no_operator_default_to_set(self): """Ensure the differences in behvaior between 'push' and 'push_all'""" class BlogPost(Document): tags = ListField(StringField()) update = transform.update(BlogPost, tags=["mongo", "db"]) assert update == {"$set": {"tags": ["mongo", "db"]}} def test_query_field_name(self): """Ensure that the correct field name is used when querying.""" class Comment(EmbeddedDocument): content = StringField(db_field="commentContent") class BlogPost(Document): title = StringField(db_field="postTitle") comments = ListField( EmbeddedDocumentField(Comment), db_field="postComments" ) BlogPost.drop_collection() data = {"title": "Post 1", "comments": [Comment(content="test")]} post = BlogPost(**data) post.save() qs = BlogPost.objects(title=data["title"]) assert qs._query == {"postTitle": data["title"]} assert qs.count() == 1 qs = BlogPost.objects(pk=post.id) assert qs._query == {"_id": post.id} assert qs.count() == 1 qs = BlogPost.objects(comments__content="test") assert qs._query == {"postComments.commentContent": "test"} assert qs.count() == 1 BlogPost.drop_collection() def test_query_pk_field_name(self): """Ensure that the correct "primary key" field name is used when querying """ class BlogPost(Document): title = StringField(primary_key=True, db_field="postTitle") BlogPost.drop_collection() data = {"title": "Post 1"} post = BlogPost(**data) post.save() assert "_id" in BlogPost.objects(pk=data["title"])._query assert "_id" in BlogPost.objects(title=data["title"])._query assert BlogPost.objects(pk=data["title"]).count() == 1 BlogPost.drop_collection() def test_chaining(self): class A(Document): pass class B(Document): a = ReferenceField(A) A.drop_collection() B.drop_collection() a1 = A().save() a2 = A().save() B(a=a1).save() # Works q1 = B.objects.filter(a__in=[a1, a2], a=a1)._query # Doesn't work q2 = B.objects.filter(a__in=[a1, a2]) q2 = q2.filter(a=a1)._query assert q1 == q2 def test_raw_query_and_Q_objects(self): """ Test raw plays nicely """ class Foo(Document): name = StringField() a = StringField() b = StringField() c = StringField() meta = {"allow_inheritance": False} query = Foo.objects(__raw__={"$nor": [{"name": "bar"}]})._query assert query == {"$nor": [{"name": "bar"}]} q1 = {"$or": [{"a": 1}, {"b": 1}]} query = Foo.objects(Q(__raw__=q1) & Q(c=1))._query assert query == {"$or": [{"a": 1}, {"b": 1}], "c": 1} def test_raw_and_merging(self): class Doc(Document): meta = {"allow_inheritance": False} raw_query = Doc.objects( __raw__={ "deleted": False, "scraped": "yes", "$nor": [ {"views.extracted": "no"}, {"attachments.views.extracted": "no"}, ], } )._query assert raw_query == { "deleted": False, "scraped": "yes", "$nor": [{"views.extracted": "no"}, {"attachments.views.extracted": "no"}], } def test_geojson_PointField(self): class Location(Document): loc = PointField() update = transform.update(Location, set__loc=[1, 2]) assert update == {"$set": {"loc": {"type": "Point", "coordinates": [1, 2]}}} update = transform.update( Location, set__loc={"type": "Point", "coordinates": [1, 2]} ) assert update == {"$set": {"loc": {"type": "Point", "coordinates": [1, 2]}}} def test_geojson_LineStringField(self): class Location(Document): line = LineStringField() update = transform.update(Location, set__line=[[1, 2], [2, 2]]) assert update == { "$set": {"line": {"type": "LineString", "coordinates": [[1, 2], [2, 2]]}} } update = transform.update( Location, set__line={"type": "LineString", "coordinates": [[1, 2], [2, 2]]} ) assert update == { "$set": {"line": {"type": "LineString", "coordinates": [[1, 2], [2, 2]]}} } def test_geojson_PolygonField(self): class Location(Document): poly = PolygonField() update = transform.update( Location, set__poly=[[[40, 5], [40, 6], [41, 6], [40, 5]]] ) assert update == { "$set": { "poly": { "type": "Polygon", "coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]], } } } update = transform.update( Location, set__poly={ "type": "Polygon", "coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]], }, ) assert update == { "$set": { "poly": { "type": "Polygon", "coordinates": [[[40, 5], [40, 6], [41, 6], [40, 5]]], } } } def test_type(self): class Doc(Document): df = DynamicField() Doc(df=True).save() Doc(df=7).save() Doc(df="df").save() assert Doc.objects(df__type=1).count() == 0 # double assert Doc.objects(df__type=8).count() == 1 # bool assert Doc.objects(df__type=2).count() == 1 # str assert Doc.objects(df__type=16).count() == 1 # int def test_embedded_field_name_like_operator(self): class EmbeddedItem(EmbeddedDocument): type = StringField() name = StringField() class Doc(Document): item = EmbeddedDocumentField(EmbeddedItem) Doc.drop_collection() doc = Doc(item=EmbeddedItem(type="axe", name="Heroic axe")) doc.save() assert 1 == Doc.objects(item__type__="axe").count() assert 1 == Doc.objects(item__name__="Heroic axe").count() Doc.objects(id=doc.id).update(set__item__type__="sword") assert 1 == Doc.objects(item__type__="sword").count() assert 0 == Doc.objects(item__type__="axe").count() def test_regular_field_named_like_operator(self): class SimpleDoc(Document): size = StringField() type = StringField() SimpleDoc.drop_collection() SimpleDoc(type="ok", size="ok").save() qry = transform.query(SimpleDoc, type="testtype") assert qry == {"type": "testtype"} assert SimpleDoc.objects(type="ok").count() == 1 assert SimpleDoc.objects(size="ok").count() == 1 update = transform.update(SimpleDoc, set__type="testtype") assert update == {"$set": {"type": "testtype"}} SimpleDoc.objects.update(set__type="testtype") SimpleDoc.objects.update(set__size="testsize") s = SimpleDoc.objects.first() assert s.type == "testtype" assert s.size == "testsize" def test_understandable_error_raised(self): class Event(Document): title = StringField() location = GeoPointField() box = [(35.0, -125.0), (40.0, -100.0)] # I *meant* to execute location__within_box=box events = Event.objects(location__within=box) with pytest.raises(InvalidQueryError): events.count() def test_update_pull_for_list_fields(self): """ Test added to check pull operation in update for EmbeddedDocumentListField which is inside a EmbeddedDocumentField """ class Word(EmbeddedDocument): word = StringField() index = IntField() class SubDoc(EmbeddedDocument): heading = ListField(StringField()) text = EmbeddedDocumentListField(Word) class MainDoc(Document): title = StringField() content = EmbeddedDocumentField(SubDoc) word = Word(word="abc", index=1) update = transform.update(MainDoc, pull__content__text=word) assert update == { "$pull": {"content.text": SON([("word", "abc"), ("index", 1)])} } update = transform.update(MainDoc, pull__content__heading="xyz") assert update == {"$pull": {"content.heading": "xyz"}} update = transform.update(MainDoc, pull__content__text__word__in=["foo", "bar"]) assert update == {"$pull": {"content.text": {"word": {"$in": ["foo", "bar"]}}}} update = transform.update( MainDoc, pull__content__text__word__nin=["foo", "bar"] ) assert update == {"$pull": {"content.text": {"word": {"$nin": ["foo", "bar"]}}}} def test_transform_embedded_document_list_fields(self): """ Test added to check filtering EmbeddedDocumentListField which is inside a EmbeddedDocumentField """ class Drink(EmbeddedDocument): id = StringField() meta = {"strict": False} class Shop(Document): drinks = EmbeddedDocumentListField(Drink) Shop.drop_collection() drinks = [Drink(id="drink_1"), Drink(id="drink_2")] Shop.objects.create(drinks=drinks) q_obj = transform.query( Shop, drinks__all=[{"$elemMatch": {"_id": x.id}} for x in drinks] ) assert q_obj == { "drinks": {"$all": [{"$elemMatch": {"_id": x.id}} for x in drinks]} } Shop.drop_collection() def test_transform_generic_reference_field(self): class Object(Document): field = GenericReferenceField() Object.drop_collection() objects = Object.objects.insert([Object() for _ in range(8)]) # singular queries assert transform.query(Object, field=objects[0].pk) == { "field._ref.$id": objects[0].pk } assert transform.query(Object, field=objects[1].to_dbref()) == { "field._ref": objects[1].to_dbref() } # iterable queries assert transform.query(Object, field__in=[objects[2].pk, objects[3].pk]) == { "field._ref.$id": {"$in": [objects[2].pk, objects[3].pk]} } assert transform.query( Object, field__in=[objects[4].to_dbref(), objects[5].to_dbref()] ) == {"field._ref": {"$in": [objects[4].to_dbref(), objects[5].to_dbref()]}} # invalid query with pytest.raises(match="cannot be applied to mixed queries"): transform.query(Object, field__in=[objects[6].pk, objects[7].to_dbref()]) Object.drop_collection() if __name__ == "__main__": unittest.main()
TestTransform
python
django__django
tests/prefetch_related/models.py
{ "start": 1669, "end": 1901 }
class ____(Book): book = models.OneToOneField(Book, models.CASCADE, parent_link=True) published_year = models.IntegerField() aged_authors = models.ManyToManyField(AuthorWithAge, related_name="books_with_year")
BookWithYear
python
google__pytype
pytype/abstract/_pytd_function.py
{ "start": 3584, "end": 22990 }
class ____(_function_base.Function): """A PyTD function (name + list of signatures). This represents (potentially overloaded) functions. """ @classmethod def make( cls, name: str, ctx: "context.Context", module: str, pyval_name: str | None = None, ) -> "PyTDFunction": """Create a PyTDFunction. Args: name: The function name. ctx: The abstract context. module: The module that the function is in. pyval_name: Optionally, the name of the pytd.Function object to look up, if it is different from the function name. Returns: A new PyTDFunction. """ pyval = ctx.loader.lookup_pytd(module, pyval_name or name) if isinstance(pyval, pytd.Alias) and isinstance(pyval.type, pytd.Function): pyval = pyval.type pyval = pyval.Replace(name=f"{module}.{name}") f = ctx.convert.constant_to_value(pyval, {}, ctx.root_node) self = cls( name, f.signatures, # pytype: disable=attribute-error pyval.kind, pyval.decorators, ctx, ) self.module = module return self def __init__( self, name: str, signatures: "list[PyTDSignature]", kind: pytd.MethodKind, decorators, ctx: "context.Context", ) -> None: super().__init__(name, ctx) assert signatures self.kind = kind self.bound_class = _function_base.BoundPyTDFunction self.signatures = signatures self._signature_cache = {} self._return_types = {sig.pytd_sig.return_type for sig in signatures} self._mutated_type_parameters = set() for sig in signatures: for param in sig.pytd_sig.params: for params in sig.mutated_type_parameters[param]: for template, value in params: if template.type_param != value: self._mutated_type_parameters.add(template.type_param.full_name) for sig in signatures: sig.function = self sig.name = self.name self.decorators: list[str] = [d.type.name for d in decorators] def property_get( self, callself: cfg.Variable, is_class=False ) -> ( # TODO: b/353979649 - See whether we need this big union _function_base.BoundFunction | _function_base.ClassMethod | _function_base.Function | _function_base.Property | _function_base.StaticMethod ): if self.kind == pytd.MethodKind.STATICMETHOD: if is_class: # Binding the function to None rather than not binding it tells # output.py to infer the type as a Callable rather than reproducing the # signature, including the @staticmethod decorator, which is # undesirable for module-level aliases. callself = None return _function_base.StaticMethod(self.name, self, callself, self.ctx) elif self.kind == pytd.MethodKind.CLASSMETHOD: if not is_class: callself = abstract_utils.get_atomic_value( callself, default=self.ctx.convert.unsolvable ) if isinstance(callself, _typing.TypeParameterInstance): callself = abstract_utils.get_atomic_value( callself.instance.get_instance_type_parameter(callself.name), default=self.ctx.convert.unsolvable, ) # callself is the instance, and we want to bind to its class. callself = callself.cls.to_variable(self.ctx.root_node) return _function_base.ClassMethod(self.name, self, callself, self.ctx) elif self.kind == pytd.MethodKind.PROPERTY and not is_class: return _function_base.Property(self.name, self, callself, self.ctx) else: return super().property_get(callself, is_class) def argcount(self, _): return min(sig.signature.mandatory_param_count() for sig in self.signatures) def _log_args( self, arg_values_list: Iterator[list[cfg.Binding]], level: int = 0, logged: set[Any] | None = None, ) -> None: """Log the argument values.""" if log.isEnabledFor(logging.DEBUG): if logged is None: logged = set() for i, arg_values in enumerate(arg_values_list): arg_values = list(arg_values) if level: if arg_values and any(v.data not in logged for v in arg_values): log.debug("%s%s:", " " * level, arg_values[0].variable.id) else: log.debug("Arg %d", i) for value in arg_values: if value.data not in logged: log.debug( "%s%s [var %d]", " " * (level + 1), value.data, value.variable.id, ) self._log_args( value.data.unique_parameter_values(), level + 2, logged | {value.data}, ) def call( self, node: cfg.CFGNode, func: cfg.Binding, args: function.Args, alias_map: datatypes.UnionFind | None = None, ) -> tuple[cfg.CFGNode, cfg.Variable]: # TODO(b/159052609): We should be passing function signatures to simplify. if len(self.signatures) == 1: args = args.simplify(node, self.ctx, self.signatures[0].signature) else: args = args.simplify(node, self.ctx) self._log_args(arg.bindings for arg in args.posargs) ret_map = {} retvar = self.ctx.program.NewVariable() all_mutations = {} # The following line may raise error_types.FailedFunctionCall possible_calls = self.match_args(node, args, alias_map) # It's possible for the substitution dictionary computed for a particular # view of 'args' to contain references to variables not in the view because # of optimizations that copy bindings directly into subst without going # through the normal matching process. Thus, we create a combined view that # is guaranteed to contain an entry for every variable in every view for use # by the match_var_against_type() call in 'compatible_with' below. combined_view = datatypes.AccessTrackingDict() for signatures in possible_calls: view = datatypes.AccessTrackingDict() for _, _, match in signatures: view.update(match.view) if len(signatures) > 1: ret = self._call_with_signatures(node, func, args, view, signatures) else: ((sig, arg_dict, match),) = signatures ret = sig.call_with_args(node, func, arg_dict, match, ret_map) node, result, mutations = ret retvar.PasteVariable(result, node) for mutation in mutations: # This may overwrite a previous view, which is fine: we just want any # valid view to pass to match_var_against_type() later. all_mutations[mutation] = view combined_view.update(view) # Don't check container types if the function has multiple bindings. # This is a hack to prevent false positives when we call a method on a # variable with multiple bindings, since we don't always filter rigorously # enough in get_views. # See tests/test_annotations:test_list for an example that would break # if we removed the len(bindings) check. if all_mutations and len(func.variable.Bindings(node)) == 1: # Raise an error if: # - An annotation has a type param that is not ambiguous or empty # - The mutation adds a type that is not ambiguous or empty def should_check(value): return not isinstance(value, _abstract.AMBIGUOUS_OR_EMPTY) def compatible_with(new, existing, view): """Check whether a new type can be added to a container.""" new_key = view[new].data.get_type_key() for data in existing: k = (new_key, data.get_type_key()) if k not in compatible_with_cache: # This caching lets us skip duplicate matching work. Very # unfortunately, it is also needed for correctness because # cfg_utils.deep_variable_product() ignores bindings to values with # duplicate type keys when generating views. compatible_with_cache[k] = self.ctx.matcher( node ).match_var_against_type(new, data.cls, {}, view) if compatible_with_cache[k] is not None: return True return False compatible_with_cache = {} filtered_mutations = [] errors = collections.defaultdict(dict) for mutation, view in all_mutations.items(): obj = mutation.instance name = mutation.name values = mutation.value if not obj.from_annotation: filtered_mutations.append(function.Mutation(obj, name, values)) continue params = obj.get_instance_type_parameter(name) ps = {v for v in params.data if should_check(v)} if not ps: # By updating filtered_mutations only when ps is non-empty, we # filter out mutations to parameters with type Any. continue # We should check for parameter mismatches only if the class is generic. # Consider: # class A(tuple[int, int]): ... # class B(tuple): ... # Although pytype computes mutations for tuple.__new__ for both classes, # the second implicitly inherits from tuple[Any, ...], so there are no # restrictions on the container contents. check_params = False for cls in obj.cls.mro: if isinstance(cls, _classes.ParameterizedClass): check_params = True break elif cls.template: break filtered_values = self.ctx.program.NewVariable() # check if the container type is being broadened. new = [] short_name = name.rsplit(".", 1)[-1] for b in values.bindings: if not check_params or not should_check(b.data) or b.data in ps: filtered_values.PasteBinding(b) continue new_view = datatypes.AccessTrackingDict.merge( combined_view, view, {values: b} ) if not compatible_with(values, ps, new_view): combination = [b] bad_param = b.data.get_instance_type_parameter(short_name) if bad_param in new_view: combination.append(new_view[bad_param]) if not node.HasCombination(combination): # Since HasCombination is expensive, we don't use it to # pre-filter bindings, but once we think we have an error, we # should double-check that the binding is actually visible. We # also drop non-visible bindings from filtered_values. continue filtered_values.PasteBinding(b) new.append(b.data) filtered_mutations.append(function.Mutation(obj, name, filtered_values)) if new: errors[obj][short_name] = (params, values, obj.from_annotation) all_mutations = filtered_mutations for obj, errs in errors.items(): names = {name for _, _, name in errs.values()} name = list(names)[0] if len(names) == 1 else None # Find the container class for base in obj.cls.mro: if isinstance(base, _abstract.ParameterizedClass): cls = base break else: assert False, f"{obj.cls.full_name} is not a container" self.ctx.errorlog.container_type_mismatch( self.ctx.vm.frames, cls, errs, name ) node = abstract_utils.apply_mutations(node, all_mutations.__iter__) return node, retvar def _get_mutation_to_unknown( self, node: cfg.CFGNode, values: list[_base.BaseValue] ) -> list[function.Mutation]: """Mutation for making all type parameters in a list of instances "unknown". This is used if we call a function that has mutable parameters and multiple signatures with unknown parameters. Args: node: The current CFG node. values: A list of instances of BaseValue. Returns: A list of function.Mutation instances. """ mutations = [] for v in values: if isinstance(v, _instance_base.SimpleValue): for name in v.instance_type_parameters: if name in self._mutated_type_parameters: mutations.append( function.Mutation( v, name, self.ctx.convert.create_new_unknown( node, action="type_param_" + name ), ) ) return mutations def _can_match_multiple(self, args): # If we're calling an overloaded pytd function with an unknown as a # parameter, we can't tell whether it matched or not. Hence, if multiple # signatures are possible matches, we don't know which got called. Check # if this is the case. if len(self.signatures) <= 1: return False for var in args.get_variables(): if any(isinstance(v, _abstract.AMBIGUOUS_OR_EMPTY) for v in var.data): return True # An opaque *args or **kwargs behaves like an unknown. return args.has_opaque_starargs_or_starstarargs() def _call_with_signatures( self, node: cfg.CFGNode, func: cfg.Binding, args: function.Args, view: datatypes.AccessTrackingDict, signatures: "list[tuple[PyTDSignature, dict[str, cfg.Variable], matcher.GoodMatch]]", ) -> tuple[cfg.CFGNode, cfg.Variable, list[function.Mutation]]: """Perform a function call that involves multiple signatures.""" ret_type = self._combine_multiple_returns(signatures) if self.ctx.options.protocols and isinstance(ret_type, pytd.AnythingType): # We can infer a more specific type. log.debug("Creating unknown return") result = self.ctx.convert.create_new_unknown(node, action="pytd_call") else: log.debug("Unknown args. But return is %s", pytd_utils.Print(ret_type)) result = self.ctx.convert.constant_to_var( abstract_utils.AsReturnValue(ret_type), {}, node ) for i, arg in enumerate(args.posargs): if arg in view and isinstance(view[arg].data, _singletons.Unknown): for sig, _, _ in signatures: if len(sig.param_types) > i and isinstance( sig.param_types[i], _typing.TypeParameter ): # Change this parameter from unknown to unsolvable to prevent the # unknown from being solved to a type in another signature. For # instance, with the following definitions: # def f(x: T) -> T # def f(x: int) -> T # the type of x should be Any, not int. view[arg] = arg.AddBinding(self.ctx.convert.unsolvable, [], node) break if self._mutated_type_parameters: mutations = ( self._get_mutation_to_unknown( # pytype: disable=wrong-arg-types node, ( view[p].data if p in view else self.ctx.convert.unsolvable for p in itertools.chain( args.posargs, args.namedargs.values() ) ), ) ) else: mutations = [] self.ctx.vm.trace_call( node, func, tuple(sig[0] for sig in signatures), args.posargs, args.namedargs, result, ) return node, result, mutations def _combine_multiple_returns( self, signatures: "list[tuple[PyTDSignature, dict[str, cfg.Variable], matcher.GoodMatch]]", ): """Combines multiple return types. Args: signatures: The candidate signatures. Returns: The combined return type. """ options = [] for sig, _, _ in signatures: t = sig.pytd_sig.return_type params = pytd_utils.GetTypeParameters(t) if params: replacement = {} for param_type in params: replacement[param_type] = pytd.AnythingType() replace_visitor = visitors.ReplaceTypeParameters(replacement) t = t.Visit(replace_visitor) options.append(t) if len(set(options)) == 1: return options[0] # Optimizing and then removing unions allows us to preserve as much # precision as possible while avoiding false positives. ret_type = optimize.Optimize(pytd_utils.JoinTypes(options)) return ret_type.Visit(visitors.ReplaceUnionsWithAny()) def _match_args_sequentially( self, node: cfg.CFGNode, args: function.Args, alias_map: datatypes.UnionFind | None, match_all_views: bool, ) -> "list[list[tuple[PyTDSignature, dict[str, cfg.Variable], matcher.GoodMatch]]]": error = None matched_signatures = _MatchedSignatures( args, self._can_match_multiple(args) ) # Once a constant has matched a literal type, it should no longer be able to # match non-literal types. For example, with: # @overload # def f(x: Literal['r']): ... # @overload # def f(x: str): ... # f('r') should match only the first signature. literal_matches = set() for sig in self.signatures: if any( not _is_literal(sig.signature.annotations.get(name)) for name in literal_matches ): continue try: arg_dict, matches = sig.substitute_formal_args( node, args, match_all_views, keep_all_views=sig is not self.signatures[-1], ) except error_types.FailedFunctionCall as e: if e > error: # Add the name of the caller if possible. if hasattr(self, "parent"): e.name = f"{self.parent.name}.{e.name}" error = e else: with matched_signatures.with_signature(sig): for match in matches: matched_signatures.add(arg_dict, match) for name, var in arg_dict.items(): if any( isinstance(v, mixin.PythonConstant) for v in var.data ) and _is_literal(sig.signature.annotations.get(name)): literal_matches.add(name) if not matched_signatures: raise error return matched_signatures.get() def set_function_defaults( self, node: cfg.CFGNode, defaults_var: cfg.Variable ) -> None: """Attempts to set default arguments for a function's signatures. If defaults_var is not an unambiguous tuple (i.e. one that can be processed by abstract_utils.get_atomic_python_constant), every argument is made optional and a warning is issued. This function emulates __defaults__. If this function is part of a class (or has a parent), that parent is updated so the change is stored. Args: node: the node that defaults are being set at. defaults_var: a Variable with a single binding to a tuple of default values. """ defaults = self._extract_defaults(defaults_var) new_sigs = [] for sig in self.signatures: if defaults: new_sigs.append(sig.set_defaults(defaults)) else: d = sig.param_types # If we have a parent, we have a "self" or "cls" parameter. Do NOT make # that one optional! if hasattr(self, "parent"): d = d[1:] new_sigs.append(sig.set_defaults(d)) self.signatures = new_sigs # Update our parent's AST too, if we have a parent. # 'parent' is set by PyTDClass._convert_member if hasattr(self, "parent"): self.parent._member_map[self.name] = self.to_pytd_def(node, self.name) # pylint: disable=protected-access
PyTDFunction
python
google__jax
jax/_src/lax/lax.py
{ "start": 14144, "end": 16551 }
class ____(enum.IntEnum): """Rounding strategies for handling halfway values (e.g., 0.5) in :func:`jax.lax.round`. """ AWAY_FROM_ZERO = 0 """Rounds halfway values away from zero (e.g., 0.5 -> 1, -0.5 -> -1).""" TO_NEAREST_EVEN = 1 """Rounds halfway values to the nearest even integer. This is also known as “banker’s rounding” (e.g., 0.5 -> 0, 1.5 -> 2). """ @export def round(x: ArrayLike, rounding_method: RoundingMethod = RoundingMethod.AWAY_FROM_ZERO ) -> Array: r"""Elementwise round. Rounds values to the nearest integer. This function lowers directly to the `stablehlo.round`_ operation. Args: x: an array or scalar value to round. Must have floating-point type. rounding_method: the method to use when rounding halfway values (e.g., ``0.5``). See :class:`jax.lax.RoundingMethod` for possible values. Returns: An array of the same shape and dtype as ``x``, containing the elementwise rounding of ``x``. See also: - :func:`jax.lax.floor`: round to the next integer toward negative infinity - :func:`jax.lax.ceil`: round to the next integer toward positive infinity Examples: >>> import jax.numpy as jnp >>> from jax import lax >>> x = jnp.array([-1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5]) >>> jax.lax.round(x) # defaults method is AWAY_FROM_ZERO Array([-2., -1., -1., 0., 1., 1., 2.], dtype=float32) >>> jax.lax.round(x, rounding_method=jax.lax.RoundingMethod.TO_NEAREST_EVEN) Array([-2., -1., -0., 0., 0., 1., 2.], dtype=float32) .. _stablehlo.round: https://openxla.org/stablehlo/spec#round """ rounding_method = RoundingMethod(rounding_method) return round_p.bind(x, rounding_method=rounding_method) @export def is_finite(x: ArrayLike) -> Array: r"""Elementwise :math:`\mathrm{isfinite}`. This function lowers directly to the `stablehlo.is_finite`_ operation. Args: x: input array. Must have floating-point type. Returns: Array of boolean dtype with the same shape as ``x``, containing ``False`` where ``x`` is :math:`\pm\infty` or :math:`\mathit{NaN}`, and ``True`` otherwise. See also: - :func:`jax.numpy.isinf`: return True where array is infinite. - :func:`jax.numpy.isnan`: return True where array is NaN. .. _stablehlo.is_finite: https://openxla.org/stablehlo/spec#is_finite """ return is_finite_p.bind(x)
RoundingMethod
python
numba__numba
numba/cuda/tests/cudapy/test_compiler.py
{ "start": 565, "end": 9049 }
class ____(unittest.TestCase): def test_global_kernel(self): def f(r, x, y): i = cuda.grid(1) if i < len(r): r[i] = x[i] + y[i] args = (float32[:], float32[:], float32[:]) ptx, resty = compile_ptx(f, args) # Kernels should not have a func_retval parameter self.assertNotIn('func_retval', ptx) # .visible .func is used to denote a device function self.assertNotIn('.visible .func', ptx) # .visible .entry would denote the presence of a global function self.assertIn('.visible .entry', ptx) # Return type for kernels should always be void self.assertEqual(resty, void) def test_device_function(self): def add(x, y): return x + y args = (float32, float32) ptx, resty = compile_ptx(add, args, device=True) # Device functions take a func_retval parameter for storing the # returned value in by reference self.assertIn('func_retval', ptx) # .visible .func is used to denote a device function self.assertIn('.visible .func', ptx) # .visible .entry would denote the presence of a global function self.assertNotIn('.visible .entry', ptx) # Inferred return type as expected? self.assertEqual(resty, float32) # Check that function's output matches signature sig_int32 = int32(int32, int32) ptx, resty = compile_ptx(add, sig_int32, device=True) self.assertEqual(resty, int32) sig_int16 = int16(int16, int16) ptx, resty = compile_ptx(add, sig_int16, device=True) self.assertEqual(resty, int16) # Using string as signature sig_string = "uint32(uint32, uint32)" ptx, resty = compile_ptx(add, sig_string, device=True) self.assertEqual(resty, uint32) def test_fastmath(self): def f(x, y, z, d): return sqrt((x * y + z) / d) args = (float32, float32, float32, float32) ptx, resty = compile_ptx(f, args, device=True) # Without fastmath, fma contraction is enabled by default, but ftz and # approximate div / sqrt is not. self.assertIn('fma.rn.f32', ptx) self.assertIn('div.rn.f32', ptx) self.assertIn('sqrt.rn.f32', ptx) ptx, resty = compile_ptx(f, args, device=True, fastmath=True) # With fastmath, ftz and approximate div / sqrt are enabled self.assertIn('fma.rn.ftz.f32', ptx) self.assertIn('div.approx.ftz.f32', ptx) self.assertIn('sqrt.approx.ftz.f32', ptx) def check_debug_info(self, ptx): # A debug_info section should exist in the PTX. Whitespace varies # between CUDA toolkit versions. self.assertRegex(ptx, '\\.section\\s+\\.debug_info') # A .file directive should be produced and include the name of the # source. The path and whitespace may vary, so we accept anything # ending in the filename of this module. self.assertRegex(ptx, '\\.file.*test_compiler.py"') def test_device_function_with_debug(self): # See Issue #6719 - this ensures that compilation with debug succeeds # with CUDA 11.2 / NVVM 7.0 onwards. Previously it failed because NVVM # IR version metadata was not added when compiling device functions, # and NVVM assumed DBG version 1.0 if not specified, which is # incompatible with the 3.0 IR we use. This was specified only for # kernels. def f(): pass ptx, resty = compile_ptx(f, (), device=True, debug=True) self.check_debug_info(ptx) def test_kernel_with_debug(self): # Inspired by (but not originally affected by) Issue #6719 def f(): pass ptx, resty = compile_ptx(f, (), debug=True) self.check_debug_info(ptx) def check_line_info(self, ptx): # A .file directive should be produced and include the name of the # source. The path and whitespace may vary, so we accept anything # ending in the filename of this module. self.assertRegex(ptx, '\\.file.*test_compiler.py"') def test_device_function_with_line_info(self): def f(): pass ptx, resty = compile_ptx(f, (), device=True, lineinfo=True) self.check_line_info(ptx) def test_kernel_with_line_info(self): def f(): pass ptx, resty = compile_ptx(f, (), lineinfo=True) self.check_line_info(ptx) def test_non_void_return_type(self): def f(x, y): return x[0] + y[0] with self.assertRaisesRegex(TypeError, 'must have void return type'): compile_ptx(f, (uint32[::1], uint32[::1])) def test_c_abi_disallowed_for_kernel(self): def f(x, y): return x + y with self.assertRaisesRegex(NotImplementedError, "The C ABI is not supported for kernels"): compile_ptx(f, (int32, int32), abi="c") def test_unsupported_abi(self): def f(x, y): return x + y with self.assertRaisesRegex(NotImplementedError, "Unsupported ABI: fastcall"): compile_ptx(f, (int32, int32), abi="fastcall") def test_c_abi_device_function(self): def f(x, y): return x + y ptx, resty = compile_ptx(f, int32(int32, int32), device=True, abi="c") # There should be no more than two parameters self.assertNotIn(ptx, "param_2") # The function name should match the Python function name (not the # qualname, which includes additional info), and its return value # should be 32 bits self.assertRegex(ptx, r"\.visible\s+\.func\s+\(\.param\s+\.b32\s+" r"func_retval0\)\s+f\(") # If we compile for 64-bit integers, the return type should be 64 bits # wide ptx, resty = compile_ptx(f, int64(int64, int64), device=True, abi="c") self.assertRegex(ptx, r"\.visible\s+\.func\s+\(\.param\s+\.b64") def test_c_abi_device_function_module_scope(self): ptx, resty = compile_ptx(f_module, int32(int32, int32), device=True, abi="c") # The function name should match the Python function name, and its # return value should be 32 bits self.assertRegex(ptx, r"\.visible\s+\.func\s+\(\.param\s+\.b32\s+" r"func_retval0\)\s+f_module\(") def test_c_abi_with_abi_name(self): abi_info = {'abi_name': '_Z4funcii'} ptx, resty = compile_ptx(f_module, int32(int32, int32), device=True, abi="c", abi_info=abi_info) # The function name should match the one given in the ABI info, and its # return value should be 32 bits self.assertRegex(ptx, r"\.visible\s+\.func\s+\(\.param\s+\.b32\s+" r"func_retval0\)\s+_Z4funcii\(") def test_compile_defaults_to_c_abi(self): ptx, resty = compile(f_module, int32(int32, int32), device=True) # The function name should match the Python function name, and its # return value should be 32 bits self.assertRegex(ptx, r"\.visible\s+\.func\s+\(\.param\s+\.b32\s+" r"func_retval0\)\s+f_module\(") def test_compile_to_ltoir(self): if runtime.get_version() < (11, 5): self.skipTest("-gen-lto unavailable in this toolkit version") ltoir, resty = compile(f_module, int32(int32, int32), device=True, output="ltoir") # There are no tools to interpret the LTOIR output, but we can check # that we appear to have obtained an LTOIR file. This magic number is # not documented, but is expected to remain consistent. LTOIR_MAGIC = 0x7F4E43ED header = int.from_bytes(ltoir[:4], byteorder='little') self.assertEqual(header, LTOIR_MAGIC) self.assertEqual(resty, int32) def test_compile_to_invalid_error(self): illegal_output = "illegal" msg = f"Unsupported output type: {illegal_output}" with self.assertRaisesRegex(NotImplementedError, msg): compile(f_module, int32(int32, int32), device=True, output=illegal_output) @skip_on_cudasim('Compilation unsupported in the simulator')
TestCompile
python
sqlalchemy__sqlalchemy
test/perf/compiled_extensions/collections_.py
{ "start": 177, "end": 3269 }
class ____(Case): @staticmethod def python(): from sqlalchemy.util import _immutabledict_cy py_immutabledict = load_uncompiled_module(_immutabledict_cy) assert not py_immutabledict._is_compiled() return py_immutabledict.immutabledict @staticmethod def cython(): from sqlalchemy.util import _immutabledict_cy assert _immutabledict_cy._is_compiled() return _immutabledict_cy.immutabledict IMPLEMENTATIONS = { "python": python.__func__, "cython": cython.__func__, } def init_objects(self): self.small = {"a": 5, "b": 4} self.large = {f"k{i}": f"v{i}" for i in range(50)} self.d1 = self.impl({"x": 5, "y": 4}) self.d2 = self.impl({f"key{i}": f"value{i}" for i in range(50)}) @classmethod def update_results(cls, results): cls._divide_results(results, "c", "python", "c / py") cls._divide_results(results, "cython", "python", "cy / py") cls._divide_results(results, "cython", "c", "cy / c") @test_case def init_empty(self): self.impl() @test_case def init(self): self.impl(self.small) @test_case def init_large(self): self.impl(self.large) @test_case def len(self): len(self.d1) + len(self.d2) @test_case def getitem(self): self.d1["x"] self.d2["key42"] @test_case def union(self): self.d1.union(self.small) self.d1.union(self.small.items()) @test_case def union_large(self): self.d2.union(self.large) @test_case def merge_with(self): self.d1.merge_with(self.small) self.d1.merge_with(self.small.items()) @test_case def merge_with_large(self): self.d2.merge_with(self.large) @test_case def get(self): self.d1.get("x") self.d2.get("key42") @test_case def get_miss(self): self.d1.get("xxx") self.d2.get("xxx") @test_case def keys(self): self.d1.keys() self.d2.keys() @test_case def items(self): self.d1.items() self.d2.items() @test_case def values(self): self.d1.values() self.d2.values() @test_case def iter(self): list(self.d1) list(self.d2) @test_case def in_case(self): "x" in self.d1 "key42" in self.d1 @test_case def in_miss(self): "xx" in self.d1 "xx" in self.d1 @test_case def eq(self): self.d1 == self.d1 self.d2 == self.d2 @test_case def eq_dict(self): self.d1 == dict(self.d1) self.d2 == dict(self.d2) @test_case def eq_other(self): self.d1 == self.d2 self.d1 == "foo" @test_case def ne(self): self.d1 != self.d1 self.d2 != self.d2 @test_case def ne_dict(self): self.d1 != dict(self.d1) self.d2 != dict(self.d2) @test_case def ne_other(self): self.d1 != self.d2 self.d1 != "foo"
ImmutableDict
python
pydantic__pydantic
pydantic/_internal/_decorators.py
{ "start": 8323, "end": 14910 }
class ____(Generic[DecoratorInfoType]): """A generic container class to join together the decorator metadata (metadata from decorator itself, which we have when the decorator is called but not when we are building the core-schema) and the bound function (which we have after the class itself is created). Attributes: cls_ref: The class ref. cls_var_name: The decorated function name. func: The decorated function. shim: A wrapper function to wrap V1 style function. info: The decorator info. """ cls_ref: str cls_var_name: str func: Callable[..., Any] shim: Callable[[Any], Any] | None info: DecoratorInfoType @staticmethod def build( cls_: Any, *, cls_var_name: str, shim: Callable[[Any], Any] | None, info: DecoratorInfoType, ) -> Decorator[DecoratorInfoType]: """Build a new decorator. Args: cls_: The class. cls_var_name: The decorated function name. shim: A wrapper function to wrap V1 style function. info: The decorator info. Returns: The new decorator instance. """ func = get_attribute_from_bases(cls_, cls_var_name) if shim is not None: func = shim(func) func = unwrap_wrapped_function(func, unwrap_partial=False) if not callable(func): # TODO most likely this branch can be removed when we drop support for Python 3.12: # This branch will get hit for classmethod properties attribute = get_attribute_from_base_dicts(cls_, cls_var_name) # prevents the binding call to `__get__` if isinstance(attribute, PydanticDescriptorProxy): func = unwrap_wrapped_function(attribute.wrapped) return Decorator( cls_ref=get_type_ref(cls_), cls_var_name=cls_var_name, func=func, shim=shim, info=info, ) def bind_to_cls(self, cls: Any) -> Decorator[DecoratorInfoType]: """Bind the decorator to a class. Args: cls: the class. Returns: The new decorator instance. """ return self.build( cls, cls_var_name=self.cls_var_name, shim=self.shim, info=copy(self.info), ) def get_bases(tp: type[Any]) -> tuple[type[Any], ...]: """Get the base classes of a class or typeddict. Args: tp: The type or class to get the bases. Returns: The base classes. """ if is_typeddict(tp): return tp.__orig_bases__ # type: ignore try: return tp.__bases__ except AttributeError: return () def mro(tp: type[Any]) -> tuple[type[Any], ...]: """Calculate the Method Resolution Order of bases using the C3 algorithm. See https://www.python.org/download/releases/2.3/mro/ """ # try to use the existing mro, for performance mainly # but also because it helps verify the implementation below if not is_typeddict(tp): try: return tp.__mro__ except AttributeError: # GenericAlias and some other cases pass bases = get_bases(tp) return (tp,) + mro_for_bases(bases) def mro_for_bases(bases: tuple[type[Any], ...]) -> tuple[type[Any], ...]: def merge_seqs(seqs: list[deque[type[Any]]]) -> Iterable[type[Any]]: while True: non_empty = [seq for seq in seqs if seq] if not non_empty: # Nothing left to process, we're done. return candidate: type[Any] | None = None for seq in non_empty: # Find merge candidates among seq heads. candidate = seq[0] not_head = [s for s in non_empty if candidate in islice(s, 1, None)] if not_head: # Reject the candidate. candidate = None else: break if not candidate: raise TypeError('Inconsistent hierarchy, no C3 MRO is possible') yield candidate for seq in non_empty: # Remove candidate. if seq[0] == candidate: seq.popleft() seqs = [deque(mro(base)) for base in bases] + [deque(bases)] return tuple(merge_seqs(seqs)) _sentinel = object() def get_attribute_from_bases(tp: type[Any] | tuple[type[Any], ...], name: str) -> Any: """Get the attribute from the next class in the MRO that has it, aiming to simulate calling the method on the actual class. The reason for iterating over the mro instead of just getting the attribute (which would do that for us) is to support TypedDict, which lacks a real __mro__, but can have a virtual one constructed from its bases (as done here). Args: tp: The type or class to search for the attribute. If a tuple, this is treated as a set of base classes. name: The name of the attribute to retrieve. Returns: Any: The attribute value, if found. Raises: AttributeError: If the attribute is not found in any class in the MRO. """ if isinstance(tp, tuple): for base in mro_for_bases(tp): attribute = base.__dict__.get(name, _sentinel) if attribute is not _sentinel: attribute_get = getattr(attribute, '__get__', None) if attribute_get is not None: return attribute_get(None, tp) return attribute raise AttributeError(f'{name} not found in {tp}') else: try: return getattr(tp, name) except AttributeError: return get_attribute_from_bases(mro(tp), name) def get_attribute_from_base_dicts(tp: type[Any], name: str) -> Any: """Get an attribute out of the `__dict__` following the MRO. This prevents the call to `__get__` on the descriptor, and allows us to get the original function for classmethod properties. Args: tp: The type or class to search for the attribute. name: The name of the attribute to retrieve. Returns: Any: The attribute value, if found. Raises: KeyError: If the attribute is not found in any class's `__dict__` in the MRO. """ for base in reversed(mro(tp)): if name in base.__dict__: return base.__dict__[name] return tp.__dict__[name] # raise the error @dataclass(**slots_true)
Decorator
python
gevent__gevent
src/greentest/3.10/test_socket.py
{ "start": 87090, "end": 88201 }
class ____(unittest.TestCase): def testCrucialConstants(self): socket.AF_QIPCRTR def testCreateSocket(self): with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s: pass def testUnbound(self): with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s: self.assertEqual(s.getsockname()[1], 0) def testBindSock(self): with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s: socket_helper.bind_port(s, host=s.getsockname()[0]) self.assertNotEqual(s.getsockname()[1], 0) def testInvalidBindSock(self): with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s: self.assertRaises(OSError, socket_helper.bind_port, s, host=-2) def testAutoBindSock(self): with socket.socket(socket.AF_QIPCRTR, socket.SOCK_DGRAM) as s: s.connect((123, 123)) self.assertNotEqual(s.getsockname()[1], 0) @unittest.skipIf(fcntl is None, "need fcntl") @unittest.skipUnless(HAVE_SOCKET_VSOCK, 'VSOCK sockets required for this test.')
BasicQIPCRTRTest
python
numba__numba
numba/cuda/tests/cudapy/test_montecarlo.py
{ "start": 91, "end": 603 }
class ____(CUDATestCase): def test_montecarlo(self): """Just make sure we can compile this """ @cuda.jit( 'void(double[:], double[:], double, double, double, double[:])') def step(last, paths, dt, c0, c1, normdist): i = cuda.grid(1) if i >= paths.shape[0]: return noise = normdist[i] paths[i] = last[i] * math.exp(c0 * dt + c1 * noise) if __name__ == '__main__': unittest.main()
TestCudaMonteCarlo
python
realpython__materials
build-a-rest-api-frontend/source_code_final_before/models.py
{ "start": 593, "end": 1066 }
class ____(db.Model): __tablename__ = "person" id = db.Column(db.Integer, primary_key=True) lname = db.Column(db.String(32)) fname = db.Column(db.String(32)) timestamp = db.Column( db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow ) notes = db.relationship( Note, backref="person", cascade="all, delete, delete-orphan", single_parent=True, order_by="desc(Note.timestamp)", )
Person
python
openai__openai-python
src/openai/types/responses/response_input_item_param.py
{ "start": 3068, "end": 4001 }
class ____(TypedDict, total=False): call_id: Required[str] """The ID of the computer tool call that produced the output.""" output: Required[ResponseComputerToolCallOutputScreenshotParam] """A computer screenshot image used with the computer use tool.""" type: Required[Literal["computer_call_output"]] """The type of the computer tool call output. Always `computer_call_output`.""" id: Optional[str] """The ID of the computer tool call output.""" acknowledged_safety_checks: Optional[Iterable[ComputerCallOutputAcknowledgedSafetyCheck]] """ The safety checks reported by the API that have been acknowledged by the developer. """ status: Optional[Literal["in_progress", "completed", "incomplete"]] """The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API. """
ComputerCallOutput
python
pyca__cryptography
tests/doubles.py
{ "start": 621, "end": 789 }
class ____(DummyCipherAlgorithm, BlockCipherAlgorithm): def __init__(self, _: object) -> None: pass name = "dummy-block-cipher"
DummyBlockCipherAlgorithm
python
python-poetry__poetry
src/poetry/utils/env/python/exceptions.py
{ "start": 265, "end": 1007 }
class ____(PythonVersionError): def __init__(self, expected: str, given: str | None = None) -> None: if given: message = ( f"The specified Python version ({given}) " f"is not supported by the project ({expected}).\n" "Please choose a compatible version " "or loosen the python constraint specified " "in the pyproject.toml file." ) else: message = ( "Poetry was unable to find a compatible version. " "If you have one, you can explicitly use it " 'via the "env use" command.' ) super().__init__(message)
NoCompatiblePythonVersionFoundError
python
google__pytype
pytype/overlays/typing_overlay.py
{ "start": 5743, "end": 6326 }
class ____(overlay_utils.TypingContainer): """Implementation of typing.Tuple.""" def _get_value_info(self, inner, ellipses, allowed_ellipses=frozenset()): if ellipses: # An ellipsis may appear at the end of the parameter list as long as it is # not the only parameter. return super()._get_value_info( inner, ellipses, allowed_ellipses={len(inner) - 1} - {0} ) else: template = list(range(len(inner))) + [abstract_utils.T] inner += (self.ctx.convert.merge_values(inner),) return template, inner, abstract.TupleClass
Tuple
python
jd__tenacity
tenacity/retry.py
{ "start": 5396, "end": 5929 }
class ____(retry_base): """Retries if the result verifies a predicate.""" def __init__(self, predicate: typing.Callable[[typing.Any], bool]) -> None: self.predicate = predicate def __call__(self, retry_state: "RetryCallState") -> bool: if retry_state.outcome is None: raise RuntimeError("__call__() called before outcome was set") if not retry_state.outcome.failed: return self.predicate(retry_state.outcome.result()) else: return False
retry_if_result
python
scrapy__scrapy
scrapy/pipelines/files.py
{ "start": 4350, "end": 9355 }
class ____: AWS_ACCESS_KEY_ID = None AWS_SECRET_ACCESS_KEY = None AWS_SESSION_TOKEN = None AWS_ENDPOINT_URL = None AWS_REGION_NAME = None AWS_USE_SSL = None AWS_VERIFY = None POLICY = "private" # Overridden from settings.FILES_STORE_S3_ACL in FilesPipeline.from_crawler() HEADERS = { "Cache-Control": "max-age=172800", } def __init__(self, uri: str): if not is_botocore_available(): raise NotConfigured("missing botocore library") import botocore.session # noqa: PLC0415 session = botocore.session.get_session() self.s3_client = session.create_client( "s3", aws_access_key_id=self.AWS_ACCESS_KEY_ID, aws_secret_access_key=self.AWS_SECRET_ACCESS_KEY, aws_session_token=self.AWS_SESSION_TOKEN, endpoint_url=self.AWS_ENDPOINT_URL, region_name=self.AWS_REGION_NAME, use_ssl=self.AWS_USE_SSL, verify=self.AWS_VERIFY, ) if not uri.startswith("s3://"): raise ValueError(f"Incorrect URI scheme in {uri}, expected 's3'") self.bucket, self.prefix = uri[5:].split("/", 1) def stat_file( self, path: str, info: MediaPipeline.SpiderInfo ) -> Deferred[StatInfo]: def _onsuccess(boto_key: dict[str, Any]) -> StatInfo: checksum = boto_key["ETag"].strip('"') last_modified = boto_key["LastModified"] modified_stamp = time.mktime(last_modified.timetuple()) return {"checksum": checksum, "last_modified": modified_stamp} return self._get_boto_key(path).addCallback(_onsuccess) def _get_boto_key(self, path: str) -> Deferred[dict[str, Any]]: key_name = f"{self.prefix}{path}" return cast( "Deferred[dict[str, Any]]", deferToThread( self.s3_client.head_object, # type: ignore[attr-defined] Bucket=self.bucket, Key=key_name, ), ) def persist_file( self, path: str, buf: BytesIO, info: MediaPipeline.SpiderInfo, meta: dict[str, Any] | None = None, headers: dict[str, str] | None = None, ) -> Deferred[Any]: """Upload file to S3 storage""" key_name = f"{self.prefix}{path}" buf.seek(0) extra = self._headers_to_botocore_kwargs(self.HEADERS) if headers: extra.update(self._headers_to_botocore_kwargs(headers)) return deferToThread( self.s3_client.put_object, # type: ignore[attr-defined] Bucket=self.bucket, Key=key_name, Body=buf, Metadata={k: str(v) for k, v in (meta or {}).items()}, ACL=self.POLICY, **extra, ) def _headers_to_botocore_kwargs(self, headers: dict[str, Any]) -> dict[str, Any]: """Convert headers to botocore keyword arguments.""" # This is required while we need to support both boto and botocore. mapping = CaseInsensitiveDict( { "Content-Type": "ContentType", "Cache-Control": "CacheControl", "Content-Disposition": "ContentDisposition", "Content-Encoding": "ContentEncoding", "Content-Language": "ContentLanguage", "Content-Length": "ContentLength", "Content-MD5": "ContentMD5", "Expires": "Expires", "X-Amz-Grant-Full-Control": "GrantFullControl", "X-Amz-Grant-Read": "GrantRead", "X-Amz-Grant-Read-ACP": "GrantReadACP", "X-Amz-Grant-Write-ACP": "GrantWriteACP", "X-Amz-Object-Lock-Legal-Hold": "ObjectLockLegalHoldStatus", "X-Amz-Object-Lock-Mode": "ObjectLockMode", "X-Amz-Object-Lock-Retain-Until-Date": "ObjectLockRetainUntilDate", "X-Amz-Request-Payer": "RequestPayer", "X-Amz-Server-Side-Encryption": "ServerSideEncryption", "X-Amz-Server-Side-Encryption-Aws-Kms-Key-Id": "SSEKMSKeyId", "X-Amz-Server-Side-Encryption-Context": "SSEKMSEncryptionContext", "X-Amz-Server-Side-Encryption-Customer-Algorithm": "SSECustomerAlgorithm", "X-Amz-Server-Side-Encryption-Customer-Key": "SSECustomerKey", "X-Amz-Server-Side-Encryption-Customer-Key-Md5": "SSECustomerKeyMD5", "X-Amz-Storage-Class": "StorageClass", "X-Amz-Tagging": "Tagging", "X-Amz-Website-Redirect-Location": "WebsiteRedirectLocation", } ) extra: dict[str, Any] = {} for key, value in headers.items(): try: kwarg = mapping[key] except KeyError: raise TypeError(f'Header "{key}" is not supported by botocore') extra[kwarg] = value return extra
S3FilesStore
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events_vitals.py
{ "start": 9513, "end": 15513 }
class ____(MetricsEnhancedPerformanceTestCase): METRIC_STRINGS = ["measurement_rating"] def setUp(self) -> None: super().setUp() self.start = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0) self.end = self.start + timedelta(hours=6) self.query: dict[str, str | list[str]] = { "start": self.start.isoformat(), "end": self.end.isoformat(), } self.features = {"organizations:performance-use-metrics": True} def do_request(self, query=None, features=None): if features is None: features = {"organizations:discover-basic": True} features.update(self.features) if query is None: query = self.query query["dataset"] = "metricsEnhanced" self.login_as(user=self.user) with self.feature(features): url = reverse( "sentry-api-0-organization-events-vitals", kwargs={"organization_id_or_slug": self.organization.slug}, ) with self.feature(features): return self.client.get(url, query, format="json") def test_no_projects(self) -> None: response = self.do_request() assert response.status_code == 200, response.content assert len(response.data) == 0 def test_no_vitals(self) -> None: self.query.update({"vital": [], "project": self.project.id}) response = self.do_request() assert response.status_code == 400, response.content assert "Need to pass at least one vital" == response.data["detail"] def test_simple(self) -> None: for rating, lcp in [("good", 2000), ("meh", 3000), ("poor", 5000)]: self.store_transaction_metric( lcp, metric="measurements.lcp", tags={"transaction": "foo_transaction", "measurement_rating": rating}, timestamp=self.start + timedelta(minutes=5), ) self.query.update({"vital": ["measurements.lcp"]}) response = self.do_request() assert response.status_code == 200, response.content assert response.data["meta"]["isMetricsData"] assert response.data["measurements.lcp"] == { "good": 1, "meh": 1, "poor": 1, "total": 3, "p75": 4000, } def test_grouping(self) -> None: counts = [ ("good", 100, 2), ("meh", 3000, 3), ("poor", 4500, 1), ] for rating, duration, count in counts: for _ in range(count): self.store_transaction_metric( duration, metric="measurements.lcp", tags={"transaction": "foo_transaction", "measurement_rating": rating}, timestamp=self.start + timedelta(minutes=5), ) self.query.update({"vital": ["measurements.lcp"]}) response = self.do_request() assert response.status_code == 200 assert response.data["meta"]["isMetricsData"] assert response.data["measurements.lcp"] == { "good": 2, "meh": 3, "poor": 1, "total": 6, "p75": 3000, } def test_multiple_vitals(self) -> None: vitals = [ ("measurements.lcp", 3000, "meh"), ("measurements.fid", 50, "good"), ("measurements.cls", 0.15, "meh"), ("measurements.fcp", 5000, "poor"), ("measurements.fp", 4000, "poor"), ] for vital, duration, rating in vitals: self.store_transaction_metric( duration, metric=vital, tags={"transaction": "foo_transaction", "measurement_rating": rating}, timestamp=self.start + timedelta(minutes=5), ) self.query.update( { "vital": [ "measurements.lcp", "measurements.fid", "measurements.cls", "measurements.fcp", "measurements.fp", ] } ) response = self.do_request() assert response.status_code == 200 assert response.data["meta"]["isMetricsData"] assert response.data["measurements.lcp"] == { "good": 0, "meh": 1, "poor": 0, "total": 1, "p75": 3000, } assert response.data["measurements.fid"] == { "good": 1, "meh": 0, "poor": 0, "total": 1, "p75": 50, } assert response.data["measurements.cls"] == { "good": 0, "meh": 1, "poor": 0, "total": 1, "p75": 0.15, } assert response.data["measurements.fcp"] == { "good": 0, "meh": 0, "poor": 1, "total": 1, "p75": 5000, } assert response.data["measurements.fp"] == { "good": 0, "meh": 0, "poor": 1, "total": 1, "p75": 4000, } def test_transactions_without_vitals(self) -> None: self.query.update( {"vital": ["measurements.lcp", "measurements.fcp"], "project": self.project.id} ) response = self.do_request() assert response.status_code == 200, response.data assert response.data["meta"]["isMetricsData"] assert response.data["measurements.lcp"] == { "good": 0, "meh": 0, "poor": 0, "total": 0, "p75": 0, } assert response.data["measurements.fcp"] == { "good": 0, "meh": 0, "poor": 0, "total": 0, "p75": 0, }
OrganizationEventsMetricsEnhancedPerformanceEndpointTest
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/directory_tree_reload.py
{ "start": 113, "end": 1603 }
class ____(App[None]): BINDINGS = [ ("r", "reload"), ("e", "expand"), ("d", "delete"), ] async def setup(self, path_root: Path) -> None: self.path_root = path_root structure = [ "f1.txt", "f2.txt", "b1/f1.txt", "b1/f2.txt", "b2/f1.txt", "b2/f2.txt", "b1/c1/f1.txt", "b1/c1/f2.txt", "b1/c2/f1.txt", "b1/c2/f2.txt", "b1/c1/d1/f1.txt", "b1/c1/d1/f2.txt", "b1/c1/d2/f1.txt", "b1/c1/d2/f2.txt", ] for file in structure: path = path_root / Path(file) path.parent.mkdir(parents=True, exist_ok=True) path.touch(exist_ok=True) await self.mount(DirectoryTree(self.path_root)) async def action_reload(self) -> None: dt = self.query_one(DirectoryTree) await dt.reload() def action_expand(self) -> None: self.query_one(DirectoryTree).root.expand_all() def action_delete(self) -> None: self.rmdir(self.path_root / Path("b1/c1/d2")) self.rmdir(self.path_root / Path("b1/c2")) self.rmdir(self.path_root / Path("b2")) def rmdir(self, path: Path) -> None: for file in path.iterdir(): if file.is_file(): file.unlink() elif file.is_dir(): self.rmdir(file) path.rmdir()
DirectoryTreeReloadApp
python
coleifer__peewee
tests/regressions.py
{ "start": 48696, "end": 48799 }
class ____(TestModel): fk_a_1 = ForeignKeyField(FKF_A, field='key') fk_a_2 = IntegerField()
FKF_B
python
apache__airflow
providers/alibaba/src/airflow/providers/alibaba/cloud/operators/oss.py
{ "start": 2682, "end": 3679 }
class ____(BaseOperator): """ This operator to upload an file-like object. :param key: the OSS path of the object :param file: local file to upload. :param region: OSS region you want to create bucket :param bucket_name: This is bucket name you want to create :param oss_conn_id: The Airflow connection used for OSS credentials. """ def __init__( self, key: str, file: str, region: str, bucket_name: str | None = None, oss_conn_id: str = "oss_default", **kwargs, ) -> None: super().__init__(**kwargs) self.key = key self.file = file self.oss_conn_id = oss_conn_id self.region = region self.bucket_name = bucket_name def execute(self, context: Context): oss_hook = OSSHook(oss_conn_id=self.oss_conn_id, region=self.region) oss_hook.upload_local_file(bucket_name=self.bucket_name, key=self.key, file=self.file)
OSSUploadObjectOperator
python
django-haystack__django-haystack
haystack/backends/elasticsearch5_backend.py
{ "start": 16880, "end": 17157 }
class ____(ElasticsearchSearchQuery): def add_field_facet(self, field, **options): """Adds a regular facet on a field.""" # to be renamed to the facet fieldname by build_search_kwargs later self.facets[field] = options.copy()
Elasticsearch5SearchQuery
python
tensorflow__tensorflow
tensorflow/python/keras/optimizer_v2/adam.py
{ "start": 10709, "end": 20383 }
class ____(optimizer_v2.OptimizerV2): r"""Optimizer that implements the Adam algorithm without fused kernels. Adam optimization is a stochastic gradient descent method that is based on adaptive estimation of first-order and second-order moments. According to the paper [Adam: A Method for Stochastic Optimization. Kingma et al., 2014](http://arxiv.org/abs/1412.6980), the method is "*computationally efficient, has little memory requirement, invariant to diagonal rescaling of gradients, and is well suited for problems that are large in terms of data/parameters*". For AMSGrad see [On The Convergence Of Adam And Beyond. Reddi et al., 5-8](https://openreview.net/pdf?id=ryQu7f-RZ). **If amsgrad = False**: initialize $m_0$ as 1st moment vector initialize $v_0$ as 2nd moment vector The update rule for $\theta$ with gradient $g$ uses an optimization described at the end of section 2 of the paper: $$lr_t = \mathrm{learning\_rate} * \sqrt{1 - \beta_2^t} / (1 - \beta_1^t)$$ $$m_t = \beta_1 * m_{t-1} + (1 - \beta_1) * g$$ $$v_t = \beta_2 * v_{t-1} + (1 - \beta_2) * g^2$$ $$\theta_t = \theta_{t-1} - lr_t * m_t / (\sqrt{v_t} + \epsilon)$$ **If amsgrad = True**: initialize $m_0$ as 1st moment vector initialize $v_0$ as 2nd moment vector initialize $\hat{v}_0$ as 2nd moment vector The update rule for $\theta$ with gradient $g$ uses an optimization described at the end of section 2 of the paper: $$lr_t = \mathrm{learning\_rate} * \sqrt{1 - \beta_2^t} / (1 - \beta_1^t)$$ $$m_t = \beta_1 * m_{t-1} + (1 - \beta_1) * g$$ $$v_t = \beta_2 * v_{t-1} + (1 - \beta_2) * g^2$$ $$\hat{v}_t = \max(\hat{v}_{t-1}, v_t)$$ $$\theta_t = \theta_{t-1} - lr_t * m_t / (\sqrt{\hat{v}_t} + \epsilon)$$ The default value of 1e-7 for epsilon might not be a good default in general. For example, when training an Inception network on ImageNet a current good choice is 1.0 or 0.1. Note that since Adam uses the formulation just before Section 2.1 of the Kingma and Ba paper rather than the formulation in Algorithm 1, the "epsilon" referred to here is "epsilon hat" in the paper. The sparse implementation of this algorithm (used when the gradient is an IndexedSlices object, typically because of `tf.gather` or an embedding lookup in the forward pass) does apply momentum to variable slices even if they were not used in the forward pass (meaning they have a gradient equal to zero). Momentum decay (beta1) is also applied to the entire momentum accumulator. This means that the sparse behavior is equivalent to the dense behavior (in contrast to some momentum implementations which ignore momentum unless a variable slice was actually used). Usage: >>> opt = tf.keras.optimizers.Adam(learning_rate=0.1) >>> var1 = tf.Variable(10.0) >>> loss = lambda: (var1 ** 2)/2.0 # d(loss)/d(var1) == var1 >>> step_count = opt.minimize(loss, [var1]).numpy() >>> # The first step is `-learning_rate*sign(grad)` >>> var1.numpy() 9.9 """ _HAS_AGGREGATE_GRAD = True def __init__(self, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-7, amsgrad=False, name='Adam', **kwargs): """Construct a new Adam optimizer. Args: learning_rate: A `Tensor`, floating point value, or a schedule that is a `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable that takes no arguments and returns the actual value to use, The learning rate. Defaults to 0.001. beta_1: A float value or a constant float tensor, or a callable that takes no arguments and returns the actual value to use. The exponential decay rate for the 1st moment estimates. Defaults to 0.9. beta_2: A float value or a constant float tensor, or a callable that takes no arguments and returns the actual value to use, The exponential decay rate for the 2nd moment estimates. Defaults to 0.999. epsilon: A small constant for numerical stability. This epsilon is "epsilon hat" in the Kingma and Ba paper (in the formula just before Section 2.1), not the epsilon in Algorithm 1 of the paper. Defaults to 1e-7. amsgrad: Boolean. Whether to apply AMSGrad variant of this algorithm from the paper "On the Convergence of Adam and beyond". Defaults to `False`. name: Optional name for the operations created when applying gradients. Defaults to "Adam". **kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`, `lr`, `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is clip gradients by value, `decay` is included for backward compatibility to allow time inverse decay of learning rate. `lr` is included for backward compatibility, recommended to use `learning_rate` instead. """ super(NonFusedAdam, self).__init__(name, **kwargs) self._set_hyper('learning_rate', kwargs.get('lr', learning_rate)) self._set_hyper('decay', self._initial_decay) self._set_hyper('beta_1', beta_1) self._set_hyper('beta_2', beta_2) self.epsilon = epsilon or backend_config.epsilon() self.amsgrad = amsgrad def _create_slots(self, var_list): # Create slots for the first and second moments. # Separate for-loops to respect the ordering of slot variables from v1. for var in var_list: self.add_slot(var, 'm') for var in var_list: self.add_slot(var, 'v') if self.amsgrad: for var in var_list: self.add_slot(var, 'vhat') def _prepare_local(self, var_device, var_dtype, apply_state): super(NonFusedAdam, self)._prepare_local(var_device, var_dtype, apply_state) local_step = math_ops.cast(self.iterations + 1, var_dtype) beta_1_t = array_ops.identity(self._get_hyper('beta_1', var_dtype)) beta_2_t = array_ops.identity(self._get_hyper('beta_2', var_dtype)) beta_1_power = math_ops.pow(beta_1_t, local_step) beta_2_power = math_ops.pow(beta_2_t, local_step) lr = ( apply_state[(var_device, var_dtype)]['lr_t'] * (math_ops.sqrt(1 - beta_2_power) / (1 - beta_1_power))) apply_state[(var_device, var_dtype)].update( dict( lr=lr, epsilon=tensor_conversion.convert_to_tensor_v2_with_dispatch( self.epsilon, var_dtype ), beta_1_t=beta_1_t, beta_1_power=beta_1_power, one_minus_beta_1_t=1 - beta_1_t, beta_2_t=beta_2_t, beta_2_power=beta_2_power, one_minus_beta_2_t=1 - beta_2_t, ) ) def set_weights(self, weights): params = self.weights # If the weights are generated by Keras V1 optimizer, it includes vhats # even without amsgrad, i.e, V1 optimizer has 3x + 1 variables, while V2 # optimizer has 2x + 1 variables. Filter vhats out for compatibility. num_vars = int((len(params) - 1) / 2) if len(weights) == 3 * num_vars + 1: weights = weights[:len(params)] super(NonFusedAdam, self).set_weights(weights) @def_function.function(jit_compile=True) def _resource_apply_dense(self, grad, var, apply_state=None): var_device, var_dtype = var.device, var.dtype.base_dtype coefficients = ((apply_state or {}).get((var_device, var_dtype)) or self._fallback_apply_state(var_device, var_dtype)) m = self.get_slot(var, 'm') v = self.get_slot(var, 'v') alpha = ( coefficients['lr_t'] * math_ops.sqrt(1 - coefficients['beta_2_power']) / (1 - coefficients['beta_1_power'])) m.assign_add((grad - m) * (1 - coefficients['beta_1_t'])) v.assign_add((math_ops.square(grad) - v) * (1 - coefficients['beta_2_t'])) if self.amsgrad: vhat = self.get_slot(var, 'vhat') vhat.assign(math_ops.maximum(vhat, v)) v = vhat var.assign_sub( (m * alpha) / (math_ops.sqrt(v) - coefficients['epsilon'])) @def_function.function(jit_compile=True) def _resource_apply_sparse(self, grad, var, indices, apply_state=None): var_device, var_dtype = var.device, var.dtype.base_dtype coefficients = ((apply_state or {}).get((var_device, var_dtype)) or self._fallback_apply_state(var_device, var_dtype)) # m_t = beta1 * m + (1 - beta1) * g_t m = self.get_slot(var, 'm') m_scaled_g_values = grad * coefficients['one_minus_beta_1_t'] m.assign(m * coefficients['beta_1_t']) m.scatter_add(indexed_slices.IndexedSlices(m_scaled_g_values, indices)) # v_t = beta2 * v + (1 - beta2) * (g_t * g_t) v = self.get_slot(var, 'v') v_scaled_g_values = (grad * grad) * coefficients['one_minus_beta_2_t'] v.assign(v * coefficients['beta_2_t']) v.scatter_add(indexed_slices.IndexedSlices(v_scaled_g_values, indices)) if not self.amsgrad: var.assign_sub(coefficients['lr'] * m / (math_ops.sqrt(v) + coefficients['epsilon'])) else: v_hat = self.get_slot(var, 'vhat') v_hat.assign(math_ops.maximum(v_hat, v)) var.assign_sub(coefficients['lr'] * m / (math_ops.sqrt(v_hat) + coefficients['epsilon'])) def get_config(self): config = super(NonFusedAdam, self).get_config() config.update({ 'learning_rate': self._serialize_hyperparameter('learning_rate'), 'decay': self._initial_decay, 'beta_1': self._serialize_hyperparameter('beta_1'), 'beta_2': self._serialize_hyperparameter('beta_2'), 'epsilon': self.epsilon, 'amsgrad': self.amsgrad, }) return config
NonFusedAdam
python
wandb__wandb
wandb/sdk/artifacts/_generated/fragments.py
{ "start": 8645, "end": 8862 }
class ____(GQLResult): name: Optional[str] fields: Optional[List[TypeInfoFragmentFields]] input_fields: Optional[List[TypeInfoFragmentInputFields]] = Field( alias="inputFields" )
TypeInfoFragment
python
python__mypy
mypyc/ir/ops.py
{ "start": 17410, "end": 17915 }
class ____(RegisterOp): """Increase reference count (inc_ref src).""" error_kind = ERR_NEVER def __init__(self, src: Value, line: int = -1) -> None: assert src.type.is_refcounted super().__init__(line) self.src = src def sources(self) -> list[Value]: return [self.src] def set_sources(self, new: list[Value]) -> None: (self.src,) = new def accept(self, visitor: OpVisitor[T]) -> T: return visitor.visit_inc_ref(self) @final
IncRef
python
ansible__ansible
lib/ansible/plugins/lookup/ini.py
{ "start": 4333, "end": 8171 }
class ____(LookupBase): def get_value(self, key, section, dflt, is_regexp): # Retrieve all values from a section using a regexp if is_regexp: return [v for k, v in self.cp.items(section) if re.match(key, k)] value = None # Retrieve a single value try: value = self.cp.get(section, key) except configparser.NoOptionError: return dflt return value def run(self, terms, variables=None, **kwargs): self.set_options(var_options=variables, direct=kwargs) paramvals = self.get_options() self.cp = configparser.ConfigParser( allow_no_value=paramvals.get('allow_no_value', paramvals.get('allow_none')), interpolation=configparser.BasicInterpolation() if paramvals.get('interpolation') else None, ) if paramvals['case_sensitive']: self.cp.optionxform = to_native ret = [] for term in terms: key = term # parameters specified? if '=' in term or ' ' in term.strip(): self._deprecate_inline_kv() params = _parse_params(term, paramvals) param = None try: updated_key = False updated_options = False for param in params: if '=' in param: name, value = param.split('=') if name not in paramvals: raise AnsibleError(f"{name!r} is not a valid option.") self.set_option(name, value) updated_options = True elif key == term: # only take first, this format never supported multiple keys inline key = param updated_key = True if updated_options: paramvals = self.get_options() except ValueError as ex: # bad params passed raise ValueError(f"Could not use {param!r} from {params!r}.") from ex if not updated_key: raise ValueError(f"No key to look up was provided as first term within string inline options: {term}") # only passed options in inline string # TODO: look to use cache to avoid redoing this for every term if they use same file # Retrieve file path path = self.find_file_in_search_path(variables, 'files', paramvals['file']) # Create StringIO later used to parse ini config = StringIO() # Special case for java properties if paramvals['type'] == "properties": config.write(u'[java_properties]\n') paramvals['section'] = 'java_properties' contents = self._loader.get_text_file_contents(path, encoding=paramvals['encoding']) config.write(contents) config.seek(0, os.SEEK_SET) try: self.cp.read_file(config) except configparser.DuplicateOptionError as ex: raise ValueError(f"Duplicate option in {paramvals['file']!r}.") from ex try: var = self.get_value(key, paramvals['section'], paramvals['default'], paramvals['re']) except configparser.NoSectionError: raise ValueError(f"No section {paramvals['section']!r} in {paramvals['file']!r}.") from None if var is not None: if isinstance(var, MutableSequence): for v in var: ret.append(v) else: ret.append(var) return ret
LookupModule
python
huggingface__transformers
src/transformers/models/diffllama/modeling_diffllama.py
{ "start": 14005, "end": 21041 }
class ____(DiffLlamaAttention): """ DiffLlama flash attention module. This module inherits from `DiffLlamaAttention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding tokens in case the input contains any of them. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignment, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). self._flash_attn_uses_top_left_mask = flash_attn_supports_top_left_mask() def forward( self, hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor, torch.Tensor], attention_mask: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, use_cache: bool = False, cache_position: Optional[torch.LongTensor] = None, ) -> tuple[torch.Tensor, None]: if isinstance(past_key_values, StaticCache): raise ValueError( "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` " "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers" ) bsz, q_len, _ = hidden_states.size() query_states = self.q_proj(hidden_states) key_states = self.k_proj(hidden_states) value_states = self.v_proj(hidden_states) # Flash attention requires the input to have the shape # batch_size x seq_length x head_dim x hidden_dim # therefore we just need to keep the original shape query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) cos, sin = position_embeddings query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin) if past_key_values is not None: # sin and cos are specific to RoPE models; cache_position needed for the static cache cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position} key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs) # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache # to be able to avoid many of these transpose/reshape/view. query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) dropout_rate = self.attention_dropout if self.training else 0.0 # In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in the correct dtype just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (DiffLlamaRMSNorm handles it correctly) input_dtype = query_states.dtype device_type = query_states.device.type if query_states.device.type != "mps" else "cpu" if input_dtype == torch.float32: if torch.is_autocast_enabled(): # NOTE: `torch.get_autocast_dtype` is there starting from PyTorch 2.4 target_dtype = ( torch.get_autocast_dtype(device_type) if hasattr(torch, "get_autocast_dtype") else torch.get_autocast_gpu_dtype() ) # Handle the case where the model is quantized elif hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype else: target_dtype = self.q_proj.weight.dtype logger.warning_once( f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." ) query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype) value_states1, value_states2 = torch.chunk(value_states, 2, dim=2) value_states1 = value_states1.repeat(1, 1, 2, 1) value_states2 = value_states2.repeat(1, 1, 2, 1) attn_output1 = _flash_attention_forward( query_states, key_states, value_states1, attention_mask, q_len, position_ids=position_ids, dropout=dropout_rate, sliding_window=getattr(self, "sliding_window", None), use_top_left_mask=self._flash_attn_uses_top_left_mask, is_causal=self.is_causal, ) attn_output2 = _flash_attention_forward( query_states, key_states, value_states2, attention_mask, q_len, position_ids=position_ids, dropout=dropout_rate, sliding_window=getattr(self, "sliding_window", None), use_top_left_mask=self._flash_attn_uses_top_left_mask, is_causal=self.is_causal, ) attn_output = torch.cat([attn_output1, attn_output2], dim=-1) attn_output1, attn_output2 = torch.chunk(attn_output, 2, dim=2) lambda_1 = torch.exp(torch.sum(self.lambda_q1 * self.lambda_k1, dim=-1, dtype=torch.float32)).to( query_states.dtype ) lambda_2 = torch.exp(torch.sum(self.lambda_q2 * self.lambda_k2, dim=-1, dtype=torch.float32)).to( query_states.dtype ) lambda_full = lambda_1 - lambda_2 + self.lambda_init attn_output = attn_output1 - lambda_full * attn_output2 attn_output = (1 - self.lambda_init) * self.groupnorm(attn_output) attn_output = attn_output.reshape(bsz, q_len, -1).contiguous() attn_output = self.o_proj(attn_output) return attn_output, None
DiffLlamaFlashAttention2
python
pypa__pip
src/pip/_internal/network/lazy_wheel.py
{ "start": 1542, "end": 7646 }
class ____: """File-like object mapped to a ZIP file over HTTP. This uses HTTP range requests to lazily fetch the file's content, which is supposed to be fed to ZipFile. If such requests are not supported by the server, raise HTTPRangeRequestUnsupported during initialization. """ def __init__( self, url: str, session: PipSession, chunk_size: int = CONTENT_CHUNK_SIZE ) -> None: head = session.head(url, headers=HEADERS) raise_for_status(head) assert head.status_code == 200 self._session, self._url, self._chunk_size = session, url, chunk_size self._length = int(head.headers["Content-Length"]) self._file = NamedTemporaryFile() self.truncate(self._length) self._left: list[int] = [] self._right: list[int] = [] if "bytes" not in head.headers.get("Accept-Ranges", "none"): raise HTTPRangeRequestUnsupported("range request is not supported") self._check_zip() @property def mode(self) -> str: """Opening mode, which is always rb.""" return "rb" @property def name(self) -> str: """Path to the underlying file.""" return self._file.name def seekable(self) -> bool: """Return whether random access is supported, which is True.""" return True def close(self) -> None: """Close the file.""" self._file.close() @property def closed(self) -> bool: """Whether the file is closed.""" return self._file.closed def read(self, size: int = -1) -> bytes: """Read up to size bytes from the object and return them. As a convenience, if size is unspecified or -1, all bytes until EOF are returned. Fewer than size bytes may be returned if EOF is reached. """ download_size = max(size, self._chunk_size) start, length = self.tell(), self._length stop = length if size < 0 else min(start + download_size, length) start = max(0, stop - download_size) self._download(start, stop - 1) return self._file.read(size) def readable(self) -> bool: """Return whether the file is readable, which is True.""" return True def seek(self, offset: int, whence: int = 0) -> int: """Change stream position and return the new absolute position. Seek to offset relative position indicated by whence: * 0: Start of stream (the default). pos should be >= 0; * 1: Current position - pos may be negative; * 2: End of stream - pos usually negative. """ return self._file.seek(offset, whence) def tell(self) -> int: """Return the current position.""" return self._file.tell() def truncate(self, size: int | None = None) -> int: """Resize the stream to the given size in bytes. If size is unspecified resize to the current position. The current stream position isn't changed. Return the new file size. """ return self._file.truncate(size) def writable(self) -> bool: """Return False.""" return False def __enter__(self) -> LazyZipOverHTTP: self._file.__enter__() return self def __exit__(self, *exc: Any) -> None: self._file.__exit__(*exc) @contextmanager def _stay(self) -> Generator[None, None, None]: """Return a context manager keeping the position. At the end of the block, seek back to original position. """ pos = self.tell() try: yield finally: self.seek(pos) def _check_zip(self) -> None: """Check and download until the file is a valid ZIP.""" end = self._length - 1 for start in reversed(range(0, end, self._chunk_size)): self._download(start, end) with self._stay(): try: # For read-only ZIP files, ZipFile only needs # methods read, seek, seekable and tell. ZipFile(self) except BadZipFile: pass else: break def _stream_response( self, start: int, end: int, base_headers: dict[str, str] = HEADERS ) -> Response: """Return HTTP response to a range request from start to end.""" headers = base_headers.copy() headers["Range"] = f"bytes={start}-{end}" # TODO: Get range requests to be correctly cached headers["Cache-Control"] = "no-cache" return self._session.get(self._url, headers=headers, stream=True) def _merge( self, start: int, end: int, left: int, right: int ) -> Generator[tuple[int, int], None, None]: """Return a generator of intervals to be fetched. Args: start (int): Start of needed interval end (int): End of needed interval left (int): Index of first overlapping downloaded data right (int): Index after last overlapping downloaded data """ lslice, rslice = self._left[left:right], self._right[left:right] i = start = min([start] + lslice[:1]) end = max([end] + rslice[-1:]) for j, k in zip(lslice, rslice): if j > i: yield i, j - 1 i = k + 1 if i <= end: yield i, end self._left[left:right], self._right[left:right] = [start], [end] def _download(self, start: int, end: int) -> None: """Download bytes from start to end inclusively.""" with self._stay(): left = bisect_left(self._right, start) right = bisect_right(self._left, end) for start, end in self._merge(start, end, left, right): response = self._stream_response(start, end) response.raise_for_status() self.seek(start) for chunk in response_chunks(response, self._chunk_size): self._file.write(chunk)
LazyZipOverHTTP
python
google__jax
jax/_src/source_info_util.py
{ "start": 2359, "end": 2462 }
class ____(NamedTuple): name: str def wrap(self, stack: list[str]): stack.append(self.name)
Scope
python
PrefectHQ__prefect
tests/cli/test_work_queues.py
{ "start": 18186, "end": 19509 }
class ____: def test_preview(self, work_queue): invoke_and_assert( command=f"work-queue preview {work_queue.name}", expected_code=0, ) def test_preview_by_id(self, work_queue): invoke_and_assert( command=f"work-queue preview {work_queue.id}", expected_code=0, ) def test_preview_with_pool( self, work_queue_1, ): cmd = f"work-queue preview {work_queue_1.name} -p {work_queue_1.work_pool.name}" invoke_and_assert( command=cmd, expected_code=0, ) # Tests all of the above, but with bad input def test_preview_bad_queue(self, work_queue): invoke_and_assert( command=f"work-queue preview {work_queue.name}-bad", expected_code=1, ) def test_preview_bad_id(self, work_queue): invoke_and_assert( command=f"work-queue preview {work_queue.id}-bad", expected_code=1, ) def test_preview_bad_pool( self, work_queue_1, ): cmd = ( f"work-queue preview {work_queue_1.name} " f"-p {work_queue_1.work_pool.name}-bad" ) invoke_and_assert( command=cmd, expected_code=1, )
TestPreview
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/batchtospace_op_test.py
{ "start": 1454, "end": 1594 }
class ____(object): @staticmethod def batch_to_space(*args, **kwargs): return gen_array_ops.batch_to_space(*args, **kwargs)
CppOpImpl
python
facebook__pyre-check
scripts/tests/compare_pysa_models_to_json_test.py
{ "start": 498, "end": 785 }
class ____(unittest.TestCase): EMPTY_CALLABLE_MODEL: TargetModel = make_default_target_model() def test_defaultdict(self) -> None: self.assertEqual( self.EMPTY_CALLABLE_MODEL["parameters"]["foo"], make_default_taint_model() )
MakeDefaultTargetModelTest
python
run-llama__llama_index
llama-index-core/llama_index/core/storage/docstore/keyval_docstore.py
{ "start": 1046, "end": 26601 }
class ____(BaseDocumentStore): """ Document (Node) store. NOTE: at the moment, this store is primarily used to store Node objects. Each node will be assigned an ID. The same docstore can be reused across index structures. This allows you to reuse the same storage for multiple index structures; otherwise, each index would create a docstore under the hood. .. code-block:: python nodes = SentenceSplitter().get_nodes_from_documents() docstore = SimpleDocumentStore() docstore.add_documents(nodes) storage_context = StorageContext.from_defaults(docstore=docstore) summary_index = SummaryIndex(nodes, storage_context=storage_context) vector_index = VectorStoreIndex(nodes, storage_context=storage_context) keyword_table_index = SimpleKeywordTableIndex(nodes, storage_context=storage_context) This will use the same docstore for multiple index structures. Args: kvstore (BaseKVStore): key-value store namespace (str): namespace for the docstore """ def __init__( self, kvstore: BaseKVStore, namespace: Optional[str] = None, batch_size: int = DEFAULT_BATCH_SIZE, node_collection_suffix: Optional[str] = None, ref_doc_collection_suffix: Optional[str] = None, metadata_collection_suffix: Optional[str] = None, ) -> None: """Init a KVDocumentStore.""" self._kvstore = kvstore self._namespace = namespace or DEFAULT_NAMESPACE self._node_collection_suffix = ( node_collection_suffix or DEFAULT_COLLECTION_DATA_SUFFIX ) self._ref_doc_collection_suffix = ( ref_doc_collection_suffix or DEFAULT_REF_DOC_COLLECTION_SUFFIX ) self._metadata_collection_suffix = ( metadata_collection_suffix or DEFAULT_METADATA_COLLECTION_SUFFIX ) self._node_collection = f"{self._namespace}{self._node_collection_suffix}" self._ref_doc_collection = f"{self._namespace}{self._ref_doc_collection_suffix}" self._metadata_collection = ( f"{self._namespace}{self._metadata_collection_suffix}" ) self._batch_size = batch_size @property def docs(self) -> Dict[str, BaseNode]: """ Get all documents. Returns: Dict[str, BaseDocument]: documents """ json_dict = self._kvstore.get_all(collection=self._node_collection) return {key: json_to_doc(json) for key, json in json_dict.items()} def _get_kv_pairs_for_insert( self, node: BaseNode, ref_doc_info: Optional[RefDocInfo], store_text: bool ) -> Tuple[ Optional[Tuple[str, dict]], Optional[Tuple[str, dict]], Optional[Tuple[str, dict]], ]: node_kv_pair = None metadata_kv_pair = None ref_doc_kv_pair = None node_key = node.node_id data = doc_to_json(node) if store_text: node_kv_pair = (node_key, data) # update doc_collection if needed metadata = {"doc_hash": node.hash} if ref_doc_info is not None and node.ref_doc_id: if node.node_id not in ref_doc_info.node_ids: ref_doc_info.node_ids.append(node.node_id) if not ref_doc_info.metadata: ref_doc_info.metadata = node.metadata or {} # update metadata with map metadata["ref_doc_id"] = node.ref_doc_id metadata_kv_pair = (node_key, metadata) ref_doc_kv_pair = (node.ref_doc_id, ref_doc_info.to_dict()) else: metadata_kv_pair = (node_key, metadata) return node_kv_pair, metadata_kv_pair, ref_doc_kv_pair def _merge_ref_doc_kv_pairs(self, ref_doc_kv_pairs: dict) -> List[Tuple[str, dict]]: merged_ref_doc_kv_pairs: List[Tuple[str, dict]] = [] for key, kv_pairs in ref_doc_kv_pairs.items(): merged_node_ids: List[str] = [] metadata: Dict[str, Any] = {} for kv_pair in kv_pairs: nodes = kv_pair[1].get("node_ids", []) new_nodes = set(nodes).difference(set(merged_node_ids)) merged_node_ids.extend([node for node in nodes if node in new_nodes]) metadata.update(kv_pair[1].get("metadata", {})) merged_ref_doc_kv_pairs.append( (key, {"node_ids": merged_node_ids, "metadata": metadata}) ) return merged_ref_doc_kv_pairs def _prepare_kv_pairs( self, nodes: Sequence[BaseNode], allow_update: bool, store_text: bool ) -> Tuple[List[Tuple[str, dict]], List[Tuple[str, dict]], List[Tuple[str, dict]]]: """ This method processes a sequence of document nodes and prepares key-value pairs for nodes, their metadata, and reference documents. The key-value pairs are structured for subsequent insertion into the key-value store. This method does not insert the key-value pairs into the store; it only prepares them. The reference document key-value pairs are merged to ensure each `ref_doc_id` has a consolidated entry. Args: nodes (Sequence[BaseNode]): A sequence of document nodes to be processed. allow_update (bool): A flag indicating whether existing nodes should be updated. store_text (bool): A flag indicating whether the text content of the nodes should be stored. Returns: Tuple[ list, # List of key-value pairs for nodes list, # List of key-value pairs for metadata List[Tuple[str, dict]] # Dictionary of key-value pairs for reference documents, keyed by ref_doc_id ] Raises: ValueError: If a node already exists in the store and `allow_update` is False. """ node_kv_pairs = [] metadata_kv_pairs = [] ref_doc_kv_pairs: Dict[str, List[Tuple[str, dict]]] = {} for node in nodes: # NOTE: doc could already exist in the store, but we overwrite it if not allow_update and self.document_exists(node.node_id): raise ValueError( f"node_id {node.node_id} already exists. " "Set allow_update to True to overwrite." ) ref_doc_info = None if node.source_node is not None: ref_doc_info = ( self.get_ref_doc_info(node.source_node.node_id) or RefDocInfo() ) ( node_kv_pair, metadata_kv_pair, ref_doc_kv_pair, ) = self._get_kv_pairs_for_insert(node, ref_doc_info, store_text) if node_kv_pair is not None: node_kv_pairs.append(node_kv_pair) if metadata_kv_pair is not None: metadata_kv_pairs.append(metadata_kv_pair) if ref_doc_kv_pair is not None: key = ref_doc_kv_pair[0] if key not in ref_doc_kv_pairs: ref_doc_kv_pairs[key] = [] ref_doc_kv_pairs[key].append(ref_doc_kv_pair) # multiple nodes can point to the same ref_doc_id merged_ref_doc_kv_pairs = self._merge_ref_doc_kv_pairs(ref_doc_kv_pairs) return node_kv_pairs, metadata_kv_pairs, merged_ref_doc_kv_pairs def add_documents( self, docs: Sequence[BaseNode], allow_update: bool = True, batch_size: Optional[int] = None, store_text: bool = True, ) -> None: """ Add a document to the store. Args: docs (List[BaseDocument]): documents allow_update (bool): allow update of docstore from document """ batch_size = batch_size or self._batch_size node_kv_pairs, metadata_kv_pairs, ref_doc_kv_pairs = self._prepare_kv_pairs( docs, allow_update, store_text ) self._kvstore.put_all( node_kv_pairs, collection=self._node_collection, batch_size=batch_size, ) self._kvstore.put_all( metadata_kv_pairs, collection=self._metadata_collection, batch_size=batch_size, ) self._kvstore.put_all( ref_doc_kv_pairs, collection=self._ref_doc_collection, batch_size=batch_size, ) async def _async_prepare_kv_pairs( self, nodes: Sequence[BaseNode], allow_update: bool, store_text: bool ) -> Tuple[List[Tuple[str, dict]], List[Tuple[str, dict]], List[Tuple[str, dict]]]: """ This method processes a sequence of document nodes asynchronously and prepares key-value pairs for nodes, their metadata, and reference documents. The key-value pairs are structured for subsequent insertion into the key-value store. This method does not insert the key-value pairs into the store; it only prepares them. The reference document key-value pairs are merged to ensure each `ref_doc_id` has a consolidated entry. Args: nodes (Sequence[BaseNode]): A sequence of document nodes to be processed. allow_update (bool): A flag indicating whether existing nodes should be updated. store_text (bool): A flag indicating whether the text content of the nodes should be stored. Returns: Tuple[ list, # List of key-value pairs for nodes list, # List of key-value pairs for metadata List[Tuple[str, dict]] # List of key-value pairs for reference documents, keyed by ref_doc_id ] Raises: ValueError: If a node already exists in the store and `allow_update` is False. """ node_kv_pairs = [] metadata_kv_pairs = [] ref_doc_kv_pairs: Dict[str, List[Tuple[str, dict]]] = {} for node in nodes: # NOTE: doc could already exist in the store, but we overwrite it if not allow_update and await self.adocument_exists(node.node_id): raise ValueError( f"node_id {node.node_id} already exists. " "Set allow_update to True to overwrite." ) ref_doc_info = None if node.source_node is not None: ref_doc_info = ( await self.aget_ref_doc_info(node.source_node.node_id) or RefDocInfo() ) ( node_kv_pair, metadata_kv_pair, ref_doc_kv_pair, ) = self._get_kv_pairs_for_insert(node, ref_doc_info, store_text) if node_kv_pair is not None: node_kv_pairs.append(node_kv_pair) if metadata_kv_pair is not None: metadata_kv_pairs.append(metadata_kv_pair) if ref_doc_kv_pair is not None: key = ref_doc_kv_pair[0] if key not in ref_doc_kv_pairs: ref_doc_kv_pairs[key] = [] ref_doc_kv_pairs[key].append(ref_doc_kv_pair) # multiple nodes can point to the same ref_doc_id merged_ref_doc_kv_pairs = self._merge_ref_doc_kv_pairs(ref_doc_kv_pairs) return node_kv_pairs, metadata_kv_pairs, merged_ref_doc_kv_pairs async def async_add_documents( self, docs: Sequence[BaseNode], allow_update: bool = True, batch_size: Optional[int] = None, store_text: bool = True, ) -> None: """ Add a document to the store. Args: docs (List[BaseDocument]): documents allow_update (bool): allow update of docstore from document """ batch_size = batch_size or self._batch_size ( node_kv_pairs, metadata_kv_pairs, ref_doc_kv_pairs, ) = await self._async_prepare_kv_pairs(docs, allow_update, store_text) await asyncio.gather( self._kvstore.aput_all( node_kv_pairs, collection=self._node_collection, batch_size=batch_size, ), self._kvstore.aput_all( metadata_kv_pairs, collection=self._metadata_collection, batch_size=batch_size, ), self._kvstore.aput_all( ref_doc_kv_pairs, collection=self._ref_doc_collection, batch_size=batch_size, ), ) def get_document(self, doc_id: str, raise_error: bool = True) -> Optional[BaseNode]: """ Get a document from the store. Args: doc_id (str): document id raise_error (bool): raise error if doc_id not found """ json = self._kvstore.get(doc_id, collection=self._node_collection) if json is None: if raise_error: raise ValueError(f"doc_id {doc_id} not found.") else: return None return json_to_doc(json) async def aget_document( self, doc_id: str, raise_error: bool = True ) -> Optional[BaseNode]: """ Get a document from the store. Args: doc_id (str): document id raise_error (bool): raise error if doc_id not found """ json = await self._kvstore.aget(doc_id, collection=self._node_collection) if json is None: if raise_error: raise ValueError(f"doc_id {doc_id} not found.") else: return None return json_to_doc(json) def _remove_legacy_info(self, ref_doc_info_dict: dict) -> RefDocInfo: if "doc_ids" in ref_doc_info_dict: ref_doc_info_dict["node_ids"] = ref_doc_info_dict.get("doc_ids", []) ref_doc_info_dict.pop("doc_ids") ref_doc_info_dict["metadata"] = ref_doc_info_dict.get("extra_info", {}) ref_doc_info_dict.pop("extra_info") return RefDocInfo( metadata=ref_doc_info_dict.get("metadata", {}), node_ids=ref_doc_info_dict.get("node_ids", []), ) def get_ref_doc_info(self, ref_doc_id: str) -> Optional[RefDocInfo]: """Get the RefDocInfo for a given ref_doc_id.""" ref_doc_info = self._kvstore.get( ref_doc_id, collection=self._ref_doc_collection ) if not ref_doc_info: return None # TODO: deprecated legacy support return self._remove_legacy_info(ref_doc_info) async def aget_ref_doc_info(self, ref_doc_id: str) -> Optional[RefDocInfo]: """Get the RefDocInfo for a given ref_doc_id.""" ref_doc_info = await self._kvstore.aget( ref_doc_id, collection=self._ref_doc_collection ) if not ref_doc_info: return None # TODO: deprecated legacy support return self._remove_legacy_info(ref_doc_info) def get_all_ref_doc_info(self) -> Optional[Dict[str, RefDocInfo]]: """Get a mapping of ref_doc_id -> RefDocInfo for all ingested documents.""" ref_doc_infos = self._kvstore.get_all(collection=self._ref_doc_collection) if ref_doc_infos is None: return None # TODO: deprecated legacy support all_ref_doc_infos = {} for doc_id, ref_doc_info in ref_doc_infos.items(): all_ref_doc_infos[doc_id] = self._remove_legacy_info(ref_doc_info) return all_ref_doc_infos async def aget_all_ref_doc_info(self) -> Optional[Dict[str, RefDocInfo]]: """Get a mapping of ref_doc_id -> RefDocInfo for all ingested documents.""" ref_doc_infos = await self._kvstore.aget_all( collection=self._ref_doc_collection ) if ref_doc_infos is None: return None # TODO: deprecated legacy support all_ref_doc_infos = {} for doc_id, ref_doc_info in ref_doc_infos.items(): all_ref_doc_infos[doc_id] = self._remove_legacy_info(ref_doc_info) return all_ref_doc_infos def ref_doc_exists(self, ref_doc_id: str) -> bool: """Check if a ref_doc_id has been ingested.""" return self.get_ref_doc_info(ref_doc_id) is not None async def aref_doc_exists(self, ref_doc_id: str) -> bool: """Check if a ref_doc_id has been ingested.""" return await self.aget_ref_doc_info(ref_doc_id) is not None def document_exists(self, doc_id: str) -> bool: """Check if document exists.""" return self._kvstore.get(doc_id, self._node_collection) is not None async def adocument_exists(self, doc_id: str) -> bool: """Check if document exists.""" return await self._kvstore.aget(doc_id, self._node_collection) is not None def _get_ref_doc_id(self, doc_id: str) -> Optional[str]: """Helper function to get ref_doc_info for a given doc_id.""" metadata = self._kvstore.get(doc_id, collection=self._metadata_collection) if metadata is None: return None return metadata.get("ref_doc_id", None) async def _aget_ref_doc_id(self, doc_id: str) -> Optional[str]: """Helper function to get ref_doc_info for a given doc_id.""" metadata = await self._kvstore.aget( doc_id, collection=self._metadata_collection ) if metadata is None: return None return metadata.get("ref_doc_id", None) def _remove_from_ref_doc_node(self, doc_id: str) -> None: """ Helper function to remove node doc_id from ref_doc_collection. If ref_doc has no more doc_ids, delete it from the collection. """ ref_doc_id = self._get_ref_doc_id(doc_id) if ref_doc_id is None: return ref_doc_info = self.get_ref_doc_info(ref_doc_id) if ref_doc_info is None: return if doc_id in ref_doc_info.node_ids: # sanity check ref_doc_info.node_ids.remove(doc_id) # delete ref_doc from collection if it has no more doc_ids if len(ref_doc_info.node_ids) > 0: self._kvstore.put( ref_doc_id, ref_doc_info.to_dict(), collection=self._ref_doc_collection, ) else: self._kvstore.delete(ref_doc_id, collection=self._metadata_collection) self._kvstore.delete(ref_doc_id, collection=self._node_collection) self._kvstore.delete(ref_doc_id, collection=self._ref_doc_collection) async def _aremove_from_ref_doc_node(self, doc_id: str) -> None: """ Helper function to remove node doc_id from ref_doc_collection. If ref_doc has no more doc_ids, delete it from the collection. """ ref_doc_id, ref_doc_info = await asyncio.gather( self._aget_ref_doc_id(doc_id), self.aget_ref_doc_info(doc_id), ) if ref_doc_id is None or ref_doc_info is None: return if doc_id in ref_doc_info.node_ids: # sanity check ref_doc_info.node_ids.remove(doc_id) # delete ref_doc from collection if it has no more doc_ids if len(ref_doc_info.node_ids) > 0: await self._kvstore.aput( ref_doc_id, ref_doc_info.to_dict(), collection=self._ref_doc_collection, ) else: await asyncio.gather( self._kvstore.adelete(ref_doc_id, collection=self._metadata_collection), self._kvstore.adelete(ref_doc_id, collection=self._node_collection), self._kvstore.adelete(ref_doc_id, collection=self._ref_doc_collection), ) def delete_document(self, doc_id: str, raise_error: bool = True) -> None: """Delete a document from the store.""" self._remove_from_ref_doc_node(doc_id) delete_success = self._kvstore.delete(doc_id, collection=self._node_collection) self._kvstore.delete(doc_id, collection=self._metadata_collection) if not delete_success and raise_error: raise ValueError(f"doc_id {doc_id} not found.") async def adelete_document(self, doc_id: str, raise_error: bool = True) -> None: """Delete a document from the store.""" _, delete_success, _ = await asyncio.gather( self._aremove_from_ref_doc_node(doc_id), self._kvstore.adelete(doc_id, collection=self._node_collection), self._kvstore.adelete(doc_id, collection=self._metadata_collection), ) if not delete_success and raise_error: raise ValueError(f"doc_id {doc_id} not found.") def delete_ref_doc(self, ref_doc_id: str, raise_error: bool = True) -> None: """Delete a ref_doc and all it's associated nodes.""" ref_doc_info = self.get_ref_doc_info(ref_doc_id) if ref_doc_info is None: if raise_error: raise ValueError(f"ref_doc_id {ref_doc_id} not found.") else: return original_node_ids = ( ref_doc_info.node_ids.copy() ) # copy to avoid mutation during iteration for doc_id in original_node_ids: self.delete_document(doc_id, raise_error=False) # Deleting all the nodes should already delete the ref_doc, but just to be sure self._kvstore.delete(ref_doc_id, collection=self._ref_doc_collection) self._kvstore.delete(ref_doc_id, collection=self._metadata_collection) self._kvstore.delete(ref_doc_id, collection=self._node_collection) async def adelete_ref_doc(self, ref_doc_id: str, raise_error: bool = True) -> None: """Delete a ref_doc and all it's associated nodes.""" ref_doc_info = await self.aget_ref_doc_info(ref_doc_id) if ref_doc_info is None: if raise_error: raise ValueError(f"ref_doc_id {ref_doc_id} not found.") else: return original_node_ids = ( ref_doc_info.node_ids.copy() ) # copy to avoid mutation during iteration for doc_id in original_node_ids: await self.adelete_document(doc_id, raise_error=False) # Deleting all the nodes should already delete the ref_doc, but just to be sure await asyncio.gather( self._kvstore.adelete(ref_doc_id, collection=self._ref_doc_collection), self._kvstore.adelete(ref_doc_id, collection=self._metadata_collection), self._kvstore.adelete(ref_doc_id, collection=self._node_collection), ) def set_document_hash(self, doc_id: str, doc_hash: str) -> None: """Set the hash for a given doc_id.""" metadata = {"doc_hash": doc_hash} self._kvstore.put(doc_id, metadata, collection=self._metadata_collection) def set_document_hashes(self, doc_hashes: Dict[str, str]) -> None: """Set the hash for a given doc_id.""" metadata_kv_pairs = [] for doc_id, doc_hash in doc_hashes.items(): metadata_kv_pairs.append((doc_id, {"doc_hash": doc_hash})) self._kvstore.put_all( metadata_kv_pairs, collection=self._metadata_collection, batch_size=self._batch_size, ) async def aset_document_hash(self, doc_id: str, doc_hash: str) -> None: """Set the hash for a given doc_id.""" metadata = {"doc_hash": doc_hash} await self._kvstore.aput(doc_id, metadata, collection=self._metadata_collection) async def aset_document_hashes(self, doc_hashes: Dict[str, str]) -> None: """Set the hash for a given doc_id.""" metadata_kv_pairs = [] for doc_id, doc_hash in doc_hashes.items(): metadata_kv_pairs.append((doc_id, {"doc_hash": doc_hash})) await self._kvstore.aput_all( metadata_kv_pairs, collection=self._metadata_collection, batch_size=self._batch_size, ) def get_document_hash(self, doc_id: str) -> Optional[str]: """Get the stored hash for a document, if it exists.""" metadata = self._kvstore.get(doc_id, collection=self._metadata_collection) if metadata is not None: return metadata.get("doc_hash", None) else: return None async def aget_document_hash(self, doc_id: str) -> Optional[str]: """Get the stored hash for a document, if it exists.""" metadata = await self._kvstore.aget( doc_id, collection=self._metadata_collection ) if metadata is not None: return metadata.get("doc_hash", None) else: return None def get_all_document_hashes(self) -> Dict[str, str]: """Get the stored hash for all documents.""" return { doc_hash: doc_id for doc_id, doc in ( self._kvstore.get_all(collection=self._metadata_collection) ).items() if (doc_hash := doc.get("doc_hash")) } async def aget_all_document_hashes(self) -> Dict[str, str]: """Get the stored hash for all documents.""" return { doc_hash: doc_id for doc_id, doc in ( await self._kvstore.aget_all(collection=self._metadata_collection) ).items() if (doc_hash := doc.get("doc_hash")) }
KVDocumentStore
python
pennersr__django-allauth
allauth/socialaccount/providers/patreon/provider.py
{ "start": 299, "end": 583 }
class ____(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get("attributes").get("thumb_url") def to_str(self): email = self.account.extra_data.get("attributes", {}).get("email") return email or super().to_str()
PatreonAccount
python
mlflow__mlflow
mlflow/types/llm.py
{ "start": 22656, "end": 23016 }
class ____(_BaseDataclass): """ Log probability information for the choice. Args: content: A list of message content tokens with log probability information. """ content: list[TokenLogProb] | None = None def __post_init__(self): self._convert_dataclass_list("content", TokenLogProb, False) @dataclass
ChatChoiceLogProbs
python
getsentry__sentry
src/sentry/tasks/summaries/metrics.py
{ "start": 225, "end": 471 }
class ____(StrEnum): """ The reason for a halt in the weekly reporting pipeline. """ EMPTY_REPORT = "empty_report" DRY_RUN = "dry_run" DUPLICATE_DELIVERY = "duplicate_delivery" TIMEOUT = "timeout"
WeeklyReportHaltReason
python
google__pytype
pytype/directors/parser.py
{ "start": 2789, "end": 2991 }
class ____: """Tracks branches of match statements.""" def __init__(self): self.matches = [] def add_match(self, start, end, cases): self.matches.append(_Match(start, end, cases))
_Matches
python
falconry__falcon
falcon/routing/compiled.py
{ "start": 42404, "end": 42707 }
class ____(_CxChild): def __init__(self, segment_idx: int) -> None: self._segment_idx = segment_idx def src(self, indentation: int) -> str: return '{0}fragment = path[{1}]'.format( _TAB_STR * indentation, self._segment_idx, )
_CxSetFragmentFromPath
python
pypa__hatch
backend/src/hatchling/metadata/core.py
{ "start": 52679, "end": 55048 }
class ____(Generic[PluginManagerBound]): def __init__(self, root: str, config: dict[str, dict[str, Any]], plugin_manager: PluginManagerBound) -> None: self.root = root self.config = config self.plugin_manager = plugin_manager self._metadata: HatchMetadataSettings | None = None self._build_config: dict[str, Any] | None = None self._build_targets: dict[str, Any] | None = None self._version: HatchVersionConfig | None = None @property def metadata(self) -> HatchMetadataSettings: if self._metadata is None: metadata_config = self.config.get("metadata", {}) if not isinstance(metadata_config, dict): message = "Field `tool.hatch.metadata` must be a table" raise TypeError(message) self._metadata = HatchMetadataSettings(self.root, metadata_config, self.plugin_manager) return self._metadata @property def build_config(self) -> dict[str, Any]: if self._build_config is None: build_config = self.config.get("build", {}) if not isinstance(build_config, dict): message = "Field `tool.hatch.build` must be a table" raise TypeError(message) self._build_config = build_config return self._build_config @property def build_targets(self) -> dict[str, Any]: if self._build_targets is None: build_targets: dict = self.build_config.get("targets", {}) if not isinstance(build_targets, dict): message = "Field `tool.hatch.build.targets` must be a table" raise TypeError(message) self._build_targets = build_targets return self._build_targets @property def version(self) -> HatchVersionConfig: if self._version is None: if "version" not in self.config: message = "Missing `tool.hatch.version` configuration" raise ValueError(message) options = self.config["version"] if not isinstance(options, dict): message = "Field `tool.hatch.version` must be a table" raise TypeError(message) self._version = HatchVersionConfig(self.root, deepcopy(options), self.plugin_manager) return self._version
HatchMetadata
python
sympy__sympy
sympy/geometry/line.py
{ "start": 32118, "end": 38759 }
class ____(LinearEntity): """An infinite line in space. A 2D line is declared with two distinct points, point and slope, or an equation. A 3D line may be defined with a point and a direction ratio. Parameters ========== p1 : Point p2 : Point slope : SymPy expression direction_ratio : list equation : equation of a line Notes ===== `Line` will automatically subclass to `Line2D` or `Line3D` based on the dimension of `p1`. The `slope` argument is only relevant for `Line2D` and the `direction_ratio` argument is only relevant for `Line3D`. The order of the points will define the direction of the line which is used when calculating the angle between lines. See Also ======== sympy.geometry.point.Point sympy.geometry.line.Line2D sympy.geometry.line.Line3D Examples ======== >>> from sympy import Line, Segment, Point, Eq >>> from sympy.abc import x, y, a, b >>> L = Line(Point(2,3), Point(3,5)) >>> L Line2D(Point2D(2, 3), Point2D(3, 5)) >>> L.points (Point2D(2, 3), Point2D(3, 5)) >>> L.equation() -2*x + y + 1 >>> L.coefficients (-2, 1, 1) Instantiate with keyword ``slope``: >>> Line(Point(0, 0), slope=0) Line2D(Point2D(0, 0), Point2D(1, 0)) Instantiate with another linear object >>> s = Segment((0, 0), (0, 1)) >>> Line(s).equation() x The line corresponding to an equation in the for `ax + by + c = 0`, can be entered: >>> Line(3*x + y + 18) Line2D(Point2D(0, -18), Point2D(1, -21)) If `x` or `y` has a different name, then they can be specified, too, as a string (to match the name) or symbol: >>> Line(Eq(3*a + b, -18), x='a', y=b) Line2D(Point2D(0, -18), Point2D(1, -21)) """ def __new__(cls, *args, **kwargs): if len(args) == 1 and isinstance(args[0], (Expr, Eq)): missing = uniquely_named_symbol('?', args) if not kwargs: x = 'x' y = 'y' else: x = kwargs.pop('x', missing) y = kwargs.pop('y', missing) if kwargs: raise ValueError('expecting only x and y as keywords') equation = args[0] if isinstance(equation, Eq): equation = equation.lhs - equation.rhs def find_or_missing(x): try: return find(x, equation) except ValueError: return missing x = find_or_missing(x) y = find_or_missing(y) a, b, c = linear_coeffs(equation, x, y) if b: return Line((0, -c/b), slope=-a/b) if a: return Line((-c/a, 0), slope=oo) raise ValueError('not found in equation: %s' % (set('xy') - {x, y})) else: if len(args) > 0: p1 = args[0] if len(args) > 1: p2 = args[1] else: p2 = None if isinstance(p1, LinearEntity): if p2: raise ValueError('If p1 is a LinearEntity, p2 must be None.') dim = len(p1.p1) else: p1 = Point(p1) dim = len(p1) if p2 is not None or isinstance(p2, Point) and p2.ambient_dimension != dim: p2 = Point(p2) if dim == 2: return Line2D(p1, p2, **kwargs) elif dim == 3: return Line3D(p1, p2, **kwargs) return LinearEntity.__new__(cls, p1, p2, **kwargs) def contains(self, other): """ Return True if `other` is on this Line, or False otherwise. Examples ======== >>> from sympy import Line,Point >>> p1, p2 = Point(0, 1), Point(3, 4) >>> l = Line(p1, p2) >>> l.contains(p1) True >>> l.contains((0, 1)) True >>> l.contains((0, 0)) False >>> a = (0, 0, 0) >>> b = (1, 1, 1) >>> c = (2, 2, 2) >>> l1 = Line(a, b) >>> l2 = Line(b, a) >>> l1 == l2 False >>> l1 in l2 True """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if isinstance(other, Point): return Point.is_collinear(other, self.p1, self.p2) if isinstance(other, LinearEntity): return Point.is_collinear(self.p1, self.p2, other.p1, other.p2) return False def distance(self, other): """ Finds the shortest distance between a line and a point. Raises ====== NotImplementedError is raised if `other` is not a Point Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(1, 1) >>> s = Line(p1, p2) >>> s.distance(Point(-1, 1)) sqrt(2) >>> s.distance((-1, 2)) 3*sqrt(2)/2 >>> p1, p2 = Point(0, 0, 0), Point(1, 1, 1) >>> s = Line(p1, p2) >>> s.distance(Point(-1, 1, 1)) 2*sqrt(6)/3 >>> s.distance((-1, 1, 1)) 2*sqrt(6)/3 """ if not isinstance(other, GeometryEntity): other = Point(other, dim=self.ambient_dimension) if self.contains(other): return S.Zero return self.perpendicular_segment(other).length def equals(self, other): """Returns True if self and other are the same mathematical entities""" if not isinstance(other, Line): return False return Point.is_collinear(self.p1, other.p1, self.p2, other.p2) def plot_interval(self, parameter='t'): """The plot interval for the default geometric plot of line. Gives values that will produce a line that is +/- 5 units long (where a unit is the distance between the two points that define the line). Parameters ========== parameter : str, optional Default value is 't'. Returns ======= plot_interval : list (plot interval) [parameter, lower_bound, upper_bound] Examples ======== >>> from sympy import Point, Line >>> p1, p2 = Point(0, 0), Point(5, 3) >>> l1 = Line(p1, p2) >>> l1.plot_interval() [t, -5, 5] """ t = _symbol(parameter, real=True) return [t, -5, 5]
Line
python
django__django
tests/migrations/test_commands.py
{ "start": 121064, "end": 139055 }
class ____(MigrationTestBase): """ Tests running the squashmigrations command. """ def test_squashmigrations_squashes(self): """ squashmigrations squashes migrations. """ out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "squashmigrations", "migrations", "0002", interactive=False, stdout=out, no_color=True, ) squashed_migration_file = os.path.join( migration_dir, "0001_squashed_0002_second.py" ) self.assertTrue(os.path.exists(squashed_migration_file)) self.assertEqual( out.getvalue(), "Will squash the following migrations:\n" " - 0001_initial\n" " - 0002_second\n" "Optimizing...\n" " Optimized from 8 operations to 2 operations.\n" "Created new squashed migration %s\n" " You should commit this migration but leave the old ones in place;\n" " the new migration will be used for new installs. Once you are sure\n" " all instances of the codebase have applied the migrations you " "squashed,\n" " you can delete them.\n" % squashed_migration_file, ) def test_squashmigrations_replacement_cycle(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_squashed_loop" ): # Hits a squash replacement cycle check error, but the actual # failure is dependent on the order in which the files are read on # disk. with self.assertRaisesRegex( CommandError, r"Cyclical squash replacement found, starting at" r" \('migrations', '2_(squashed|auto)'\)", ): call_command( "migrate", "migrations", "--plan", interactive=False, stdout=out ) def test_squashmigrations_squashes_already_squashed(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_squashed_complex" ): call_command( "squashmigrations", "migrations", "3_squashed_5", "--squashed-name", "double_squash", stdout=out, interactive=False, ) loader = MigrationLoader(connection) migration = loader.disk_migrations[("migrations", "0001_double_squash")] # Confirm the replaces mechanism holds the squashed migration # (and not what it squashes, as the squash operations are what # end up being used). self.assertEqual( migration.replaces, [ ("migrations", "1_auto"), ("migrations", "2_auto"), ("migrations", "3_squashed_5"), ], ) out = io.StringIO() call_command( "migrate", "migrations", "--plan", interactive=False, stdout=out ) migration_plan = re.findall("migrations.(.+)\n", out.getvalue()) self.assertEqual(migration_plan, ["0001_double_squash", "6_auto", "7_auto"]) def test_squash_partially_applied(self): """ Replacement migrations are partially applied. Then we squash again and verify that only unapplied migrations will be applied by "migrate". """ out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_squashed_partially_applied" ): # Apply first 2 migrations. call_command("migrate", "migrations", "0002", interactive=False, stdout=out) # Squash the 2 migrations, that we just applied + 1 more. call_command( "squashmigrations", "migrations", "0001", "0003", "--squashed-name", "squashed_0001_0003", stdout=out, interactive=False, ) # Update the 4th migration to depend on the squash(replacement) # migration. loader = MigrationLoader(connection) migration = loader.disk_migrations[ ("migrations", "0004_remove_mymodel1_field_1_mymodel1_field_3_and_more") ] migration.dependencies = [("migrations", "0001_squashed_0001_0003")] writer = MigrationWriter(migration) with open(writer.path, "w", encoding="utf-8") as fh: fh.write(writer.as_string()) # Squash the squash(replacement) migration with the 4th migration. call_command( "squashmigrations", "migrations", "0001_squashed_0001_0003", "0004", "--squashed-name", "squashed_0001_0004", stdout=out, interactive=False, ) loader = MigrationLoader(connection) migration = loader.disk_migrations[ ("migrations", "0001_squashed_0001_0004") ] self.assertEqual( migration.replaces, [ ("migrations", "0001_squashed_0001_0003"), ( "migrations", "0004_remove_mymodel1_field_1_mymodel1_field_3_and_more", ), ], ) # Verify that only unapplied migrations will be applied. out = io.StringIO() call_command( "migrate", "migrations", "--plan", interactive=False, stdout=out ) migration_plan = re.findall("migrations.(.+)\n", out.getvalue()) self.assertEqual( migration_plan, [ "0003_alter_mymodel2_unique_together", "0004_remove_mymodel1_field_1_mymodel1_field_3_and_more", ], ) def test_double_replaced_migrations_are_recorded(self): """ All recursively replaced migrations should be recorded/unrecorded, when migrating an app with double squashed migrations. """ out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_squashed_double" ): recorder = MigrationRecorder(connection) applied_app_labels = [ app_label for app_label, _ in recorder.applied_migrations() ] self.assertNotIn("migrations", applied_app_labels) call_command( "migrate", "migrations", "--plan", interactive=False, stdout=out ) migration_plan = re.findall("migrations.(.+)\n", out.getvalue()) # Only the top-level replacement migration should be applied. self.assertEqual(migration_plan, ["0005_squashed_0003_and_0004"]) call_command("migrate", "migrations", interactive=False, verbosity=0) applied_migrations = recorder.applied_migrations() # Make sure all replaced migrations are recorded. self.assertIn(("migrations", "0001_initial"), applied_migrations) self.assertIn(("migrations", "0002_auto"), applied_migrations) self.assertIn( ("migrations", "0003_squashed_0001_and_0002"), applied_migrations ) self.assertIn(("migrations", "0004_auto"), applied_migrations) self.assertIn( ("migrations", "0005_squashed_0003_and_0004"), applied_migrations ) # Unapply all migrations from this app. call_command( "migrate", "migrations", "zero", interactive=False, verbosity=0 ) applied_app_labels = [ app_label for app_label, _ in recorder.applied_migrations() ] self.assertNotIn("migrations", applied_app_labels) def test_double_replaced_migrations_are_checked_correctly(self): """ If replaced migrations are already applied and replacing migrations are not, then migrate should not fail with InconsistentMigrationHistory. """ with self.temporary_migration_module(): call_command( "makemigrations", "migrations", "--empty", interactive=False, verbosity=0, ) call_command( "makemigrations", "migrations", "--empty", interactive=False, verbosity=0, ) call_command( "makemigrations", "migrations", "--empty", interactive=False, verbosity=0, ) call_command( "makemigrations", "migrations", "--empty", interactive=False, verbosity=0, ) call_command("migrate", "migrations", interactive=False, verbosity=0) call_command( "squashmigrations", "migrations", "0001", "0002", interactive=False, verbosity=0, ) call_command( "squashmigrations", "migrations", "0001_initial_squashed", "0003", interactive=False, verbosity=0, ) call_command("migrate", "migrations", interactive=False, verbosity=0) def test_squashmigrations_initial_attribute(self): with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "squashmigrations", "migrations", "0002", interactive=False, verbosity=0 ) squashed_migration_file = os.path.join( migration_dir, "0001_squashed_0002_second.py" ) with open(squashed_migration_file, encoding="utf-8") as fp: content = fp.read() self.assertIn("initial = True", content) def test_squashmigrations_optimizes(self): """ squashmigrations optimizes operations. """ out = io.StringIO() with self.temporary_migration_module(module="migrations.test_migrations"): call_command( "squashmigrations", "migrations", "0002", interactive=False, verbosity=1, stdout=out, ) self.assertIn("Optimized from 8 operations to 2 operations.", out.getvalue()) def test_ticket_23799_squashmigrations_no_optimize(self): """ squashmigrations --no-optimize doesn't optimize operations. """ out = io.StringIO() with self.temporary_migration_module(module="migrations.test_migrations"): call_command( "squashmigrations", "migrations", "0002", interactive=False, verbosity=1, no_optimize=True, stdout=out, ) self.assertIn("Skipping optimization", out.getvalue()) def test_squashmigrations_valid_start(self): """ squashmigrations accepts a starting migration. """ out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_no_changes" ) as migration_dir: call_command( "squashmigrations", "migrations", "0002", "0003", interactive=False, verbosity=1, stdout=out, ) squashed_migration_file = os.path.join( migration_dir, "0002_second_squashed_0003_third.py" ) with open(squashed_migration_file, encoding="utf-8") as fp: content = fp.read() if HAS_BLACK: test_str = ' ("migrations", "0001_initial")' else: test_str = " ('migrations', '0001_initial')" self.assertIn(test_str, content) self.assertNotIn("initial = True", content) out = out.getvalue() self.assertNotIn(" - 0001_initial", out) self.assertIn(" - 0002_second", out) self.assertIn(" - 0003_third", out) def test_squashmigrations_invalid_start(self): """ squashmigrations doesn't accept a starting migration after the ending migration. """ with self.temporary_migration_module( module="migrations.test_migrations_no_changes" ): msg = ( "The migration 'migrations.0003_third' cannot be found. Maybe " "it comes after the migration 'migrations.0002_second'" ) with self.assertRaisesMessage(CommandError, msg): call_command( "squashmigrations", "migrations", "0003", "0002", interactive=False, verbosity=0, ) def test_squashed_name_with_start_migration_name(self): """--squashed-name specifies the new migration's name.""" squashed_name = "squashed_name" with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "squashmigrations", "migrations", "0001", "0002", squashed_name=squashed_name, interactive=False, verbosity=0, ) squashed_migration_file = os.path.join( migration_dir, "0001_%s.py" % squashed_name ) self.assertTrue(os.path.exists(squashed_migration_file)) def test_squashed_name_without_start_migration_name(self): """--squashed-name also works if a start migration is omitted.""" squashed_name = "squashed_name" with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: call_command( "squashmigrations", "migrations", "0001", squashed_name=squashed_name, interactive=False, verbosity=0, ) squashed_migration_file = os.path.join( migration_dir, "0001_%s.py" % squashed_name ) self.assertTrue(os.path.exists(squashed_migration_file)) def test_squashed_name_exists(self): msg = "Migration 0001_initial already exists. Use a different name." with self.temporary_migration_module(module="migrations.test_migrations"): with self.assertRaisesMessage(CommandError, msg): call_command( "squashmigrations", "migrations", "0001", "0002", squashed_name="initial", interactive=False, verbosity=0, ) def test_squashmigrations_manual_porting(self): out = io.StringIO() with self.temporary_migration_module( module="migrations.test_migrations_manual_porting", ) as migration_dir: call_command( "squashmigrations", "migrations", "0002", interactive=False, stdout=out, no_color=True, ) squashed_migration_file = os.path.join( migration_dir, "0001_squashed_0002_second.py", ) self.assertTrue(os.path.exists(squashed_migration_file)) black_warning = "" if HAS_BLACK: black_warning = ( "Squashed migration couldn't be formatted using the " '"black" command. You can call it manually.\n' ) self.assertEqual( out.getvalue(), f"Will squash the following migrations:\n" f" - 0001_initial\n" f" - 0002_second\n" f"Optimizing...\n" f" No optimizations possible.\n" f"Created new squashed migration {squashed_migration_file}\n" f" You should commit this migration but leave the old ones in place;\n" f" the new migration will be used for new installs. Once you are sure\n" f" all instances of the codebase have applied the migrations you " f"squashed,\n" f" you can delete them.\n" f"Manual porting required\n" f" Your migrations contained functions that must be manually copied " f"over,\n" f" as we could not safely copy their implementation.\n" f" See the comment at the top of the squashed migration for details.\n" + black_warning, ) def test_failure_to_format_code(self): self.assertFormatterFailureCaught( "squashmigrations", "migrations", "0002", interactive=False )
SquashMigrationsTests
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_format28.py
{ "start": 315, "end": 1748 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_format28.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": "line"}) chart.axis_ids = [108645376, 108655360] 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", "trendline": { "type": "linear", "display_equation": True, "display_r_squared": True, }, } ) chart.add_series( { "categories": "=Sheet1!$A$1:$A$5", "values": "=Sheet1!$C$1:$C$5", } ) chart.set_legend({"delete_series": [0, 2]}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol41.py
{ "start": 1165, "end": 1237 }
class ____: def write(self, __b: Buffer) -> None: pass
BytesIO
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_page_view03.py
{ "start": 315, "end": 1011 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("page_view03.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with print options.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_pagebreak_view() worksheet.set_zoom(75) # Options to match automatic page setup. worksheet.set_paper(9) worksheet.vertical_dpi = 200 worksheet.write("A1", "Foo") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
vyperlang__vyper
vyper/venom/analysis/mem_ssa.py
{ "start": 16480, "end": 16577 }
class ____(MemSSAAbstract): addr_space = MEMORY mem_alias_type = MemoryAliasAnalysis
MemSSA
python
google__pytype
pytype/blocks/blocks.py
{ "start": 7611, "end": 19924 }
class ____: """CFG made up of ordered code blocks.""" def __init__(self): self.graph: dict[opcodes.Opcode, OrderedCode] = {} def add(self, ordered_code: OrderedCode): self.graph[ordered_code.get_first_opcode()] = ordered_code def pretty_print(self): return str(self.graph) def add_pop_block_targets(bytecode: list[opcodes.Opcode]) -> None: """Modifies bytecode so that each POP_BLOCK has a block_target. This is to achieve better initial ordering of try/except and try/finally code. try: i = 1 a[i] except IndexError: return i By connecting a CFG edge from the end of the block (after the "a[i]") to the except handler, our basic block ordering algorithm knows that the except block needs to be scheduled last, whereas if there only was an edge before the "i = 1", it would be able to schedule it too early and thus encounter an undefined variable. This is only for ordering. The actual analysis of the code happens later, in vm.py. Args: bytecode: An array of bytecodes. """ if not bytecode: return for op in bytecode: op.block_target = None setup_except_op = (opcodes.SETUP_FINALLY, opcodes.SETUP_EXCEPT_311) todo = [(bytecode[0], ())] # unordered queue of (position, block_stack) seen = set() while todo: op, block_stack = todo.pop() if op in seen: continue else: seen.add(op) # Compute the block stack if isinstance(op, opcodes.POP_BLOCK): assert block_stack, "POP_BLOCK without block." op.block_target = block_stack[-1].target block_stack = block_stack[0:-1] elif isinstance(op, opcodes.RAISE_VARARGS): # Make "raise" statements jump to the innermost exception handler. # (If there's no exception handler, do nothing.) for b in reversed(block_stack): if isinstance(b, setup_except_op): op.block_target = b.target break elif isinstance(op, opcodes.BREAK_LOOP): # Breaks jump to after the loop for i in reversed(range(len(block_stack))): b = block_stack[i] if isinstance(b, opcodes.SETUP_LOOP): op.block_target = b.target assert b.target != op todo.append((op.block_target, block_stack[0:i])) break elif isinstance(op, setup_except_op): # Exceptions pop the block, so store the previous block stack. todo.append((op.target, block_stack)) block_stack += (op,) elif op.pushes_block(): assert op.target, f"{op.name} without target" # We push the entire opcode onto the block stack, for better debugging. block_stack += (op,) elif op.does_jump() and op.target: if op.push_exc_block: # We're jumping into an exception range, so push onto the block stack. setup_op = op.target while not isinstance(setup_op, setup_except_op): setup_op = setup_op.prev block_stack += (setup_op,) todo.append((op.target, block_stack)) if not op.no_next(): assert op.next, f"Bad instruction at end of bytecode: {op!r}." todo.append((op.next, block_stack)) def _split_bytecode( bytecode: list[opcodes.Opcode], processed_blocks: set[Block], python_version ) -> list[Block]: """Given a sequence of bytecodes, return basic blocks. This will split the code at "basic block boundaries". These occur at every instruction that is jumped to, and after every instruction that jumps somewhere else (or returns / aborts). Args: bytecode: A list of instances of opcodes.Opcode. (E.g. returned from opcodes.dis()) Returns: A list of _Block instances. """ targets = {op.target for op in bytecode if op.target} blocks = [] code = [] prev_block: Block = None i = 0 while i < len(bytecode): op = bytecode[i] # SEND is only used in the context of async for and `yield from`. # These instructions are not used in other context, so it's safe to process # it assuming that these are the only constructs they're being used. if python_version >= (3, 12) and isinstance(op, opcodes.SEND): if code: prev_block = Block(code) blocks.append(prev_block) code = [] new_blocks, i = _preprocess_async_for_and_yield( i, bytecode, prev_block, processed_blocks ) blocks.extend(new_blocks) prev_block = blocks[-1] continue code.append(op) if ( op.no_next() or op.does_jump() or op.pops_block() or op.next is None or (op.next in targets) and ( not isinstance(op.next, opcodes.GET_ANEXT) or python_version < (3, 12) ) ): prev_block = Block(code) blocks.append(prev_block) code = [] i += 1 return blocks def _preprocess_async_for_and_yield( idx: int, bytecode: Sequence[opcodes.Opcode], prev_block: Block, processed_blocks: set[Block], ) -> tuple[list[Block], int]: """Process bytecode instructions for yield and async for in a way that pytype can iterate correctly. 'Async for' and yield statements, contains instructions that starts with SEND and ends with END_SEND. The reason why we need to pre process async for is because the control flow of async for is drastically different from regular control flows also due to the fact that the termination of the loop happens by STOP_ASYNC_ITERATION exception, not a regular control flow. So we need to split (or merge) the basic blocks in a way that pytype executes in the order that what'd happen in the runtime, so that it doesn't fail with wrong order of execution, which can result in a stack underrun. Args: idx: The index of the SEND instruction. bytecode: A list of instances of opcodes.Opcode prev_block: The previous block that we want to connect the new blocks to. processed_blocks: Blocks that has been processed so that it doesn't get processed again by compute_order. Returns: A tuple of (list[Block], int), where the Block is the block containing the iteration part of the async for construct, and the int is the index of the END_SEND instruction. """ assert isinstance(bytecode[idx], opcodes.SEND) i = next( i for i in range(idx + 1, len(bytecode)) if isinstance(bytecode[i], opcodes.JUMP_BACKWARD_NO_INTERRUPT) ) end_block_idx = i + 1 # In CLEANUP_THROW can be present after JUMP_BACKWARD_NO_INTERRUPT # depending on how the control flow graph is constructed. # Usually, CLEANUP_THROW comes way after if isinstance(bytecode[end_block_idx], opcodes.CLEANUP_THROW): end_block_idx += 1 # Somehow pytype expects the SEND and YIELD_VALUE to be in different # blocks, so we need to split. send_block = Block(bytecode[idx : idx + 1]) yield_value_block = Block(bytecode[idx + 1 : end_block_idx]) prev_block.connect_outgoing(send_block) send_block.connect_outgoing(yield_value_block) processed_blocks.update(send_block, yield_value_block) return [send_block, yield_value_block], end_block_idx def _remove_jmp_to_get_anext_and_merge( blocks: list[Block], processed_blocks: set[Block] ) -> list[Block]: """Remove JUMP_BACKWARD instructions to GET_ANEXT instructions. And also merge the block that contains the END_ASYNC_FOR which is part of the same loop of the GET_ANEXT and JUMP_BACKWARD construct, to the JUMP_BACKWARD instruction. This is to ignore the JUMP_BACKWARD because in pytype's eyes it's useless (as it'll jump back to block that it already executed), and also this is the way to make pytype run the code of END_ASYNC_FOR and whatever comes afterwards. Args: blocks: A list of Block instances. Returns: A list of Block instances after the removal and merge. """ op_to_block = {} merge_list = [] for block_idx, block in enumerate(blocks): for code in block.code: op_to_block[code] = block_idx for block_idx, block in enumerate(blocks): for code in block.code: if code.end_async_for_target: merge_list.append((block_idx, op_to_block[code.end_async_for_target])) map_target = {} for block_idx, block_idx_to_merge in merge_list: # Remove JUMP_BACKWARD instruction as we don't want to execute it. jump_back_op = blocks[block_idx].code.pop() blocks[block_idx].code.extend(blocks[block_idx_to_merge].code) map_target[jump_back_op] = blocks[block_idx_to_merge].code[0] if block_idx_to_merge < len(blocks) - 1: blocks[block_idx].connect_outgoing(blocks[block_idx_to_merge + 1]) processed_blocks.add(blocks[block_idx]) to_delete = sorted({to_idx for _, to_idx in merge_list}, reverse=True) for block_idx in to_delete: del blocks[block_idx] for block in blocks: replace_op = map_target.get(block.code[-1].target, None) if replace_op: block.code[-1].target = replace_op return blocks def _remove_jump_back_block(blocks: list[Block]): """Remove JUMP_BACKWARD instructions which are exception handling for async for. These are not used during the regular pytype control flow analysis. """ new_blocks = [] for block in blocks: last_op = block.code[-1] if ( isinstance(last_op, opcodes.JUMP_BACKWARD) and isinstance(last_op.target, opcodes.END_SEND) and len(block.code) >= 2 and isinstance(block.code[-2], opcodes.CLEANUP_THROW) ): continue new_blocks.append(block) return new_blocks def compute_order( bytecode: list[opcodes.Opcode], python_version ) -> list[Block]: """Split bytecode into blocks and order the blocks. This builds an "ancestor first" ordering of the basic blocks of the bytecode. Args: bytecode: A list of instances of opcodes.Opcode. (E.g. returned from opcodes.dis()) Returns: A list of Block instances. """ processed_blocks = set() blocks = _split_bytecode(bytecode, processed_blocks, python_version) if python_version >= (3, 12): blocks = _remove_jump_back_block(blocks) blocks = _remove_jmp_to_get_anext_and_merge(blocks, processed_blocks) first_op_to_block = {block.code[0]: block for block in blocks} for i, block in enumerate(blocks): next_block = blocks[i + 1] if i < len(blocks) - 1 else None if block in processed_blocks: continue first_op, last_op = block.code[0], block.code[-1] if next_block and not last_op.no_next(): block.connect_outgoing(next_block) if first_op.target: # Handles SETUP_EXCEPT -> except block block.connect_outgoing(first_op_to_block[first_op.target]) if last_op.target: block.connect_outgoing(first_op_to_block[last_op.target]) if last_op.block_target: block.connect_outgoing(first_op_to_block[last_op.block_target]) return cfg_utils.order_nodes(blocks) def _order_code(dis_code: pycnite.types.DisassembledCode) -> OrderedCode: """Split a CodeType object into ordered blocks. This takes a CodeType object (i.e., a piece of compiled Python code) and splits it into ordered basic blocks. Args: dis_code: A pycnite.types.DisassembledCode object. Returns: An OrderedCode instance. """ ops = opcodes.build_opcodes(dis_code) add_pop_block_targets(ops) blocks = compute_order(ops, dis_code.python_version) return OrderedCode(dis_code.code, ops, blocks) def _process( dis_code: pycnite.types.DisassembledCode, block_graph: BlockGraph ) -> OrderedCode: """Recursively convert code -> OrderedCode, while collecting a blockgraph.""" ordered_code = _order_code(dis_code) if dis_code.children: # dis_code.children is an ordered list of DisassembledCode for every code # object in dis_code.code.co_consts children = iter(dis_code.children) new_consts = list(dis_code.code.co_consts) for i, c in enumerate(new_consts): if hasattr(c, "co_consts"): # This is a CodeType object (because it has co_consts). new_consts[i] = _process(next(children), block_graph) ordered_code.consts = tuple(new_consts) block_graph.add(ordered_code) return ordered_code def process_code( code: pycnite.types.CodeTypeBase, ) -> tuple[OrderedCode, BlockGraph]: dis_code = pyc_bytecode.dis_all(code) block_graph = BlockGraph() ordered = _process(dis_code, block_graph) return ordered, block_graph
BlockGraph
python
pytorch__pytorch
test/dynamo/test_misc.py
{ "start": 3796, "end": 4631 }
class ____(torch.nn.Module): def __init__(self, z): super().__init__() self.z = z def forward(self, x, y): return x * x * x + y + self.z # These are used for test_{cond/map}_with_quantization default_symmetric_fake_quant = FakeQuantize.with_args( observer=MinMaxObserver, qscheme=torch.per_tensor_symmetric, dtype=torch.quint8 ) default_weight_symmetric_fake_quant = FakeQuantize.with_args( observer=MinMaxObserver, qscheme=torch.per_tensor_symmetric, dtype=torch.qint8 ) uniform_qconfig_8bit = QConfig( activation=default_symmetric_fake_quant, weight=default_weight_symmetric_fake_quant.with_args, ) qconfig_dict = {"object_type": [(torch.nn.Linear, uniform_qconfig_8bit)]} def closure_adder(val): def inner(x): return torch.sin(x + val) return inner
MyPickledModule
python
pyparsing__pyparsing
examples/statemachine/video_demo.py
{ "start": 150, "end": 1192 }
class ____(videostate.VideoStateMixin): def __init__(self, title): self.initialize_state(videostate.Stopped) self.title = title # ==== main loop - a REPL ==== v = Video("Die Hard.mp4") while True: print(v.state) cmd = ( input("Command ({})> ".format("/".join(videostate.VideoState.transition_names))) .lower() .strip() ) if not cmd: continue if cmd in ("?", "h", "help"): print("enter a transition {!r}".format(videostate.VideoState.transition_names)) print(" q - quit") print(" ?, h, help - this message") continue # quitting out if cmd.startswith("q"): break # get transition function for given command state_transition_fn = getattr(v, cmd, None) if state_transition_fn is None: print("???") continue # invoke the input transition, handle invalid commands try: state_transition_fn() except videostate.VideoState.InvalidTransitionException as e: print(e)
Video
python
pytorch__pytorch
test/mobile/test_lite_script_type.py
{ "start": 298, "end": 6133 }
class ____(TestCase): def test_typing_namedtuple(self): myNamedTuple = NamedTuple( # noqa: UP014 "myNamedTuple", [("a", list[torch.Tensor])] ) class MyTestModule(torch.nn.Module): def forward(self, a: torch.Tensor): p = myNamedTuple([a]) return p sample_input = torch.tensor(5) script_module = torch.jit.script(MyTestModule()) script_module_result = script_module(sample_input).a buffer = io.BytesIO( script_module._save_to_buffer_for_lite_interpreter( _save_mobile_debug_info=True ) ) buffer.seek(0) mobile_module = _load_for_lite_interpreter(buffer) # Error here mobile_module_result = mobile_module(sample_input).a torch.testing.assert_close(script_module_result, mobile_module_result) @unittest.skip("T137512434") def test_typing_dict_with_namedtuple(self): class Foo(NamedTuple): id: torch.Tensor class Bar(torch.nn.Module): def __init__(self) -> None: super().__init__() self.foo = Foo(torch.tensor(1)) def forward(self, a: torch.Tensor): self.foo = Foo(a) re: dict[str, Foo] = {} re["test"] = Foo(a) return self.foo, re["test"] # The corresponding bytecode is # (8, # ('__torch__.___torch_mangle_2.Bar.forward', # (('instructions', # (('STOREN', 1, 2), # ('DROPR', 1, 0), # ('DICT_CONSTRUCT', 0, 0), # ('STORE', 3, 0), # ('LOAD', 3, 0), # ('LOADC', 1, 0), # ('MOVE', 2, 0), # ('NAMED_TUPLE_CONSTRUCT', 1, 1), # ('OP', 0, 0), # ('MOVE', 3, 0), # ('LOADC', 1, 0), # ('DICT_INDEX', 0, 0), # ('LOADC', 0, 0), # ('TUPLE_INDEX', 0, 0), # ('RET', 0, 0))), # ('operators', (('aten::_set_item', 'str', 3),)), # ('constants', (0, 'test')), # ('types', # ('Dict[str,__torch__.Foo[NamedTuple, [[id, Tensor]]]]', # '__torch__.Foo[NamedTuple, [[id, Tensor]]]')), # ('register_size', 3)), # (('arguments', # ((('name', 'self'), # ('type', '__torch__.___torch_mangle_2.Bar'), # ('default_value', None)), # (('name', 'a'), ('type', 'Tensor'), ('default_value', None)))), # ('returns', # ((('name', ''), ('type', 'Tensor'), ('default_value', None)),))))) sample_input = torch.tensor(5) script_module = torch.jit.script(Bar()) script_module_result = script_module(sample_input) buffer_mobile = io.BytesIO(script_module._save_to_buffer_for_lite_interpreter()) buffer_mobile.seek(0) mobile_module = _load_for_lite_interpreter(buffer_mobile) mobile_module_result = mobile_module(sample_input) torch.testing.assert_close(script_module_result, mobile_module_result) def test_typing_namedtuple_custom_classtype(self): class Foo(NamedTuple): id: torch.Tensor class Bar(torch.nn.Module): def __init__(self) -> None: super().__init__() self.foo = Foo(torch.tensor(1)) def forward(self, a: torch.Tensor): self.foo = Foo(a) return self.foo sample_input = torch.tensor(5) script_module = torch.jit.script(Bar()) script_module_result = script_module(sample_input) buffer_mobile = io.BytesIO(script_module._save_to_buffer_for_lite_interpreter()) buffer_mobile.seek(0) mobile_module = _load_for_lite_interpreter(buffer_mobile) mobile_module_result = mobile_module(sample_input) torch.testing.assert_close(script_module_result, mobile_module_result) def test_return_collections_namedtuple(self): myNamedTuple = namedtuple("myNamedTuple", [("a")]) class MyTestModule(torch.nn.Module): def forward(self, a: torch.Tensor): return myNamedTuple(a) sample_input = torch.Tensor(1) script_module = torch.jit.script(MyTestModule()) script_module_result = script_module(sample_input) buffer_mobile = io.BytesIO(script_module._save_to_buffer_for_lite_interpreter()) buffer_mobile.seek(0) mobile_module = _load_for_lite_interpreter(buffer_mobile) mobile_module_result = mobile_module(sample_input) torch.testing.assert_close(script_module_result, mobile_module_result) def test_nest_typing_namedtuple_custom_classtype(self): class Baz(NamedTuple): di: torch.Tensor class Foo(NamedTuple): id: torch.Tensor baz: Baz class Bar(torch.nn.Module): def __init__(self) -> None: super().__init__() self.foo = Foo(torch.tensor(1), Baz(torch.tensor(1))) def forward(self, a: torch.Tensor): self.foo = Foo(a, Baz(torch.tensor(1))) return self.foo sample_input = torch.tensor(5) script_module = torch.jit.script(Bar()) script_module_result = script_module(sample_input) buffer_mobile = io.BytesIO(script_module._save_to_buffer_for_lite_interpreter()) buffer_mobile.seek(0) mobile_module = _load_for_lite_interpreter(buffer_mobile) mobile_module_result = mobile_module(sample_input) torch.testing.assert_close( script_module_result.baz.di, mobile_module_result.baz.di ) if __name__ == "__main__": run_tests()
TestLiteScriptModule
python
facebook__pyre-check
tools/generate_taint_models/tests/get_class_sources_test.py
{ "start": 356, "end": 743 }
class ____(unittest.TestCase): def test_gather_functions_to_model(self) -> None: self.assertEqual( set( ClassSourceGenerator( classes_to_taint=[f"{qualifier}.TestClass"] ).gather_functions_to_model() ), {TestChildClassB.__init__, TestGrandChildClassA.__init__}, )
GetClassSourcesTest
python
readthedocs__readthedocs.org
readthedocs/core/migrations/0008_add_extra_history_fields.py
{ "start": 149, "end": 826 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("core", "0007_historicaluser"), ] operations = [ migrations.AddField( model_name="historicaluser", name="extra_history_browser", field=models.CharField( blank=True, max_length=250, null=True, verbose_name="Browser user-agent" ), ), migrations.AddField( model_name="historicaluser", name="extra_history_ip", field=models.CharField( blank=True, max_length=250, null=True, verbose_name="IP address" ), ), ]
Migration
python
pytorch__pytorch
test/torch_np/numpy_tests/core/test_multiarray.py
{ "start": 248946, "end": 250704 }
class ____(TestCase): # Test various array sizes that hit different code paths in quicksort-avx512 @parametrize( "N", [8, 16, 24, 32, 48, 64, 96, 128, 151, 191, 256, 383, 512, 1023, 2047] ) def test_sort_float(self, N): # Regular data with nan sprinkled np.random.seed(42) arr = -0.5 + np.random.sample(N).astype("f") arr[np.random.choice(arr.shape[0], 3)] = np.nan assert_equal(np.sort(arr, kind="quick"), np.sort(arr, kind="heap")) # (2) with +INF infarr = np.inf * np.ones(N, dtype="f") infarr[np.random.choice(infarr.shape[0], 5)] = -1.0 assert_equal(np.sort(infarr, kind="quick"), np.sort(infarr, kind="heap")) # (3) with -INF neginfarr = -np.inf * np.ones(N, dtype="f") neginfarr[np.random.choice(neginfarr.shape[0], 5)] = 1.0 assert_equal(np.sort(neginfarr, kind="quick"), np.sort(neginfarr, kind="heap")) # (4) with +/-INF infarr = np.inf * np.ones(N, dtype="f") infarr[np.random.choice(infarr.shape[0], (int)(N / 2))] = -np.inf assert_equal(np.sort(infarr, kind="quick"), np.sort(infarr, kind="heap")) def test_sort_int(self): # Random data with NPY_MAX_INT32 and NPY_MIN_INT32 sprinkled # rng = np.random.default_rng(42) np.random.seed(1234) N = 2047 minv = np.iinfo(np.int32).min maxv = np.iinfo(np.int32).max arr = np.random.randint(low=minv, high=maxv, size=N).astype("int32") arr[np.random.choice(arr.shape[0], 10)] = minv arr[np.random.choice(arr.shape[0], 10)] = maxv assert_equal(np.sort(arr, kind="quick"), np.sort(arr, kind="heap")) if __name__ == "__main__": run_tests()
TestSortFloatMisc
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 37751, "end": 37852 }
class ____: tensors: list[VariableTracker] = dataclasses.field(default_factory=list)
SavedTensorBox
python
kamyu104__LeetCode-Solutions
Python/time-based-key-value-store.py
{ "start": 91, "end": 941 }
class ____(object): def __init__(self): """ Initialize your data structure here. """ self.lookup = collections.defaultdict(list) def set(self, key, value, timestamp): """ :type key: str :type value: str :type timestamp: int :rtype: None """ self.lookup[key].append((timestamp, value)) def get(self, key, timestamp): """ :type key: str :type timestamp: int :rtype: str """ A = self.lookup.get(key, None) if A is None: return "" i = bisect.bisect_right(A, (timestamp+1, 0)) return A[i-1][1] if i else "" # Your TimeMap object will be instantiated and called as such: # obj = TimeMap() # obj.set(key,value,timestamp) # param_2 = obj.get(key,timestamp)
TimeMap
python
lxml__lxml
src/lxml/html/diff.py
{ "start": 11704, "end": 19479 }
class ____: pass def merge_delete(del_chunks, doc: list): """ Adds the text chunks in del_chunks to the document doc (another list of text chunks) with marker to show it is a delete. cleanup_delete later resolves these markers into <del> tags.""" doc.append(DEL_START) doc.extend(del_chunks) doc.append(DEL_END) def cleanup_delete(chunks: list): """ Cleans up any DEL_START/DEL_END markers in the document, replacing them with <del></del>. To do this while keeping the document valid, it may need to drop some tags (either start or end tags). It may also move the del into adjacent tags to try to move it to a similar location where it was originally located (e.g., moving a delete into preceding <div> tag, if the del looks like (DEL_START, 'Text</div>', DEL_END) """ chunk_count = len(chunks) i: cython.Py_ssize_t del_start: cython.Py_ssize_t del_end: cython.Py_ssize_t shift_start_right: cython.Py_ssize_t shift_end_left: cython.Py_ssize_t unbalanced_start: cython.Py_ssize_t unbalanced_end: cython.Py_ssize_t pos: cython.Py_ssize_t start_pos: cython.Py_ssize_t chunk: str start_pos = 0 while 1: # Find a pending DEL_START/DEL_END, splitting the document # into stuff-preceding-DEL_START, stuff-inside, and # stuff-following-DEL_END try: del_start = chunks.index(DEL_START, start_pos) except ValueError: # Nothing found, we've cleaned up the entire doc break else: del_end = chunks.index(DEL_END, del_start + 1) shift_end_left = shift_start_right = 0 unbalanced_start = unbalanced_end = 0 deleted_chunks = mark_unbalanced(chunks[del_start+1:del_end]) # For unbalanced start tags at the beginning, find matching (non-deleted) # end tags after the current DEL_END and move the start tag outside. for balanced, del_chunk in deleted_chunks: if balanced != 'us': break unbalanced_start += 1 unbalanced_start_name = tag_name_of_chunk(del_chunk) for i in range(del_end+1, chunk_count): if chunks[i] is DEL_START: break chunk = chunks[i] if chunk[0] != '<' or chunk[1] == '/': # Reached a word or closing tag. break name = tag_name_of_chunk(chunk) if name == 'ins': # Cannot move into an insert. break assert name != 'del', f"Unexpected delete tag: {chunk!r}" if name != unbalanced_start_name: # Avoid mixing in other start tags. break # Exclude start tag to balance the end tag. shift_start_right += 1 # For unbalanced end tags at the end, find matching (non-deleted) # start tags before the currend DEL_START and move the end tag outside. for balanced, del_chunk in reversed(deleted_chunks): if balanced != 'ue': break unbalanced_end += 1 unbalanced_end_name = tag_name_of_chunk(del_chunk) for i in range(del_start - 1, -1, -1): if chunks[i] is DEL_END: break chunk = chunks[i] if chunk[0] == '<' and chunk[1] != '/': # Reached an opening tag, can we go further? Maybe not... break name = tag_name_of_chunk(chunk) if name == 'ins' or name == 'del': # Cannot move into an insert or delete. break if name != unbalanced_end_name: # Avoid mixing in other start tags. break # Exclude end tag to balance the start tag. shift_end_left += 1 """ # This is what we do below in loops, spelled out using slicing and list copying: chunks[del_start - shift_end_left : del_end + shift_start_right + 1] = [ *chunks[del_start + 1: del_start + shift_start_right + 1], '<del>', *chunks[del_start + unbalanced_start + 1 : del_end - unbalanced_end], '</del> ', *chunks[del_end - shift_end_left: del_end], ] new_del_end = del_end - 2 * shift_end_left assert chunks[new_del_end] == '</del> ' del_end = new_del_end if new_del_start > 0 and not chunks[new_del_start - 1].endswith(' '): # Fix up case where the word before us didn't have a trailing space. chunks[new_del_start - 1] += ' ' if new_del_end > 0 and chunks[new_del_end - 1].endswith(' '): # Move space outside of </del>. chunks[new_del_end - 1] = chunks[new_del_end - 1][:-1] """ pos = del_start - shift_end_left # Move re-balanced start tags before the '<del>'. for i in range(del_start + 1, del_start + shift_start_right + 1): chunks[pos] = chunks[i] pos += 1 if pos and not chunks[pos - 1].endswith(' '): # Fix up the case where the word before '<del>' didn't have a trailing space. chunks[pos - 1] += ' ' chunks[pos] = '<del>' pos += 1 # Copy only the balanced deleted content between '<del>' and '</del>'. for i in range(del_start + unbalanced_start + 1, del_end - unbalanced_end): chunks[pos] = chunks[i] pos += 1 if chunks[pos - 1].endswith(' '): # Move trailing space outside of </del>. chunks[pos - 1] = chunks[pos - 1][:-1] chunks[pos] = '</del> ' pos += 1 # Move re-balanced end tags after the '</del>'. for i in range(del_end - shift_end_left, del_end): chunks[pos] = chunks[i] pos += 1 # Adjust the length of the processed part in 'chunks'. del chunks[pos : del_end + shift_start_right + 1] start_pos = pos @cython.cfunc def mark_unbalanced(chunks) -> list: tag_stack = [] marked = [] chunk: str parents: list for chunk in chunks: if not chunk.startswith('<'): marked.append(('b', chunk)) continue name = tag_name_of_chunk(chunk) if name in empty_tags: marked.append(('b', chunk)) continue if chunk[1] == '/': # closing tag found, unwind tag stack while tag_stack: start_name, start_chunk, parents = tag_stack.pop() if start_name == name: # balanced tag closing, keep rest of stack intact parents.append(('b', start_chunk)) parents.extend(marked) parents.append(('b', chunk)) marked = parents chunk = None break else: # unmatched start tag parents.append(('us', start_chunk)) parents.extend(marked) marked = parents if chunk is not None: # unmatched end tag left after clearing the stack marked.append(('ue', chunk)) else: # new start tag found tag_stack.append((name, chunk, marked)) marked = [] # add any unbalanced start tags while tag_stack: _, start_chunk, parents = tag_stack.pop() parents.append(('us', start_chunk)) parents.extend(marked) marked = parents return marked
DEL_END
python
huggingface__transformers
src/transformers/models/beit/image_processing_beit.py
{ "start": 2077, "end": 24306 }
class ____(BaseImageProcessor): r""" Constructs a BEiT image processor. Args: do_resize (`bool`, *optional*, defaults to `True`): Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the `do_resize` parameter in the `preprocess` method. size (`dict[str, int]` *optional*, defaults to `{"height": 256, "width": 256}`): Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess` method. resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`): Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the `preprocess` method. do_center_crop (`bool`, *optional*, defaults to `True`): Whether to center crop the image. If the input size is smaller than `crop_size` along any edge, the image is padded with 0's and then center cropped. Can be overridden by the `do_center_crop` parameter in the `preprocess` method. crop_size (`dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`): Desired output size when applying center-cropping. Only has an effect if `do_center_crop` is set to `True`. Can be overridden by the `crop_size` parameter in the `preprocess` method. rescale_factor (`int` or `float`, *optional*, defaults to `1/255`): Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the `preprocess` method. do_rescale (`bool`, *optional*, defaults to `True`): Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale` parameter in the `preprocess` method. do_normalize (`bool`, *optional*, defaults to `True`): Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess` method. image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`): The mean to use if normalizing the image. This is a float or list of floats of length of the number of channels of the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`): The standard deviation to use if normalizing the image. This is a float or list of floats of length of the number of channels of the image. Can be overridden by the `image_std` parameter in the `preprocess` method. do_reduce_labels (`bool`, *optional*, defaults to `False`): Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background, and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255. Can be overridden by the `do_reduce_labels` parameter in the `preprocess` method. """ model_input_names = ["pixel_values"] valid_kwargs = BeitImageProcessorKwargs @filter_out_non_signature_kwargs(extra=INIT_SERVICE_KWARGS) def __init__( self, do_resize: bool = True, size: Optional[dict[str, int]] = None, resample: PILImageResampling = PILImageResampling.BICUBIC, do_center_crop: bool = True, crop_size: Optional[dict[str, int]] = None, rescale_factor: Union[int, float] = 1 / 255, do_rescale: bool = True, do_normalize: bool = True, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, do_reduce_labels: bool = False, **kwargs, ) -> None: super().__init__(**kwargs) size = size if size is not None else {"height": 256, "width": 256} size = get_size_dict(size) crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224} crop_size = get_size_dict(crop_size, param_name="crop_size") self.do_resize = do_resize self.size = size self.resample = resample self.do_center_crop = do_center_crop self.crop_size = crop_size self.do_rescale = do_rescale self.rescale_factor = rescale_factor self.do_normalize = do_normalize self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD self.do_reduce_labels = do_reduce_labels def resize( self, image: np.ndarray, size: dict[str, int], resample: PILImageResampling = PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, **kwargs, ) -> np.ndarray: """ Resize an image to (size["height"], size["width"]). Args: image (`np.ndarray`): Image to resize. size (`dict[str, int]`): Size of the output image. resample (`PILImageResampling`, *optional*, defaults to `PIL.Image.BICUBIC`): Resampling filter to use when resiizing the image. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. input_data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format of the input image. If not provided, it will be inferred. """ size = get_size_dict(size, default_to_square=True, param_name="size") if "height" not in size or "width" not in size: raise ValueError(f"The `size` argument must contain `height` and `width` keys. Got {size.keys()}") return resize( image, size=(size["height"], size["width"]), resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs, ) def reduce_label(self, label: ImageInput) -> np.ndarray: label = to_numpy_array(label) # Avoid using underflow conversion label[label == 0] = 255 label = label - 1 label[label == 254] = 255 return label def _preprocess( self, image: ImageInput, do_reduce_labels: Optional[bool] = None, do_resize: Optional[bool] = None, size: Optional[dict[str, int]] = None, resample: Optional[PILImageResampling] = None, do_center_crop: Optional[bool] = None, crop_size: Optional[dict[str, int]] = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ): if do_reduce_labels: image = self.reduce_label(image) if do_resize: image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format) if do_center_crop: image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) if do_rescale: image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format) if do_normalize: image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format) return image def _preprocess_image( self, image: ImageInput, do_resize: Optional[bool] = None, size: Optional[dict[str, int]] = None, resample: Optional[PILImageResampling] = None, do_center_crop: Optional[bool] = None, crop_size: Optional[dict[str, int]] = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, data_format: Optional[Union[str, ChannelDimension]] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> np.ndarray: """Preprocesses a single image.""" # All transformations expect numpy arrays. image = to_numpy_array(image) if do_rescale and is_scaled_image(image): logger.warning_once( "It looks like you are trying to rescale already rescaled images. If the input" " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again." ) if input_data_format is None: input_data_format = infer_channel_dimension_format(image) image = self._preprocess( image, do_reduce_labels=False, do_resize=do_resize, size=size, resample=resample, do_center_crop=do_center_crop, crop_size=crop_size, do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, input_data_format=input_data_format, ) if data_format is not None: image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) return image def _preprocess_segmentation_map( self, segmentation_map: ImageInput, do_resize: Optional[bool] = None, size: Optional[dict[str, int]] = None, resample: Optional[PILImageResampling] = None, do_center_crop: Optional[bool] = None, crop_size: Optional[dict[str, int]] = None, do_reduce_labels: Optional[bool] = None, input_data_format: Optional[Union[str, ChannelDimension]] = None, ): """Preprocesses a single segmentation map.""" # All transformations expect numpy arrays. segmentation_map = to_numpy_array(segmentation_map) # Add an axis to the segmentation maps for transformations. if segmentation_map.ndim == 2: segmentation_map = segmentation_map[None, ...] added_dimension = True input_data_format = ChannelDimension.FIRST else: added_dimension = False if input_data_format is None: input_data_format = infer_channel_dimension_format(segmentation_map, num_channels=1) segmentation_map = self._preprocess( image=segmentation_map, do_reduce_labels=do_reduce_labels, do_resize=do_resize, resample=resample, size=size, do_center_crop=do_center_crop, crop_size=crop_size, do_normalize=False, do_rescale=False, input_data_format=ChannelDimension.FIRST, ) # Remove extra axis if added if added_dimension: segmentation_map = np.squeeze(segmentation_map, axis=0) segmentation_map = segmentation_map.astype(np.int64) return segmentation_map def __call__(self, images, segmentation_maps=None, **kwargs): # Overrides the `__call__` method of the `Preprocessor` class such that the images and segmentation maps can both # be passed in as positional arguments. return super().__call__(images, segmentation_maps=segmentation_maps, **kwargs) @filter_out_non_signature_kwargs() def preprocess( self, images: ImageInput, segmentation_maps: Optional[ImageInput] = None, do_resize: Optional[bool] = None, size: Optional[dict[str, int]] = None, resample: Optional[PILImageResampling] = None, do_center_crop: Optional[bool] = None, crop_size: Optional[dict[str, int]] = None, do_rescale: Optional[bool] = None, rescale_factor: Optional[float] = None, do_normalize: Optional[bool] = None, image_mean: Optional[Union[float, list[float]]] = None, image_std: Optional[Union[float, list[float]]] = None, do_reduce_labels: Optional[bool] = None, return_tensors: Optional[Union[str, TensorType]] = None, data_format: ChannelDimension = ChannelDimension.FIRST, input_data_format: Optional[Union[str, ChannelDimension]] = None, ) -> PIL.Image.Image: """ Preprocess an image or batch of images. Args: images (`ImageInput`): Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`. segmentation_maps (`ImageInput`, *optional*) Segmentation maps to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`. do_resize (`bool`, *optional*, defaults to `self.do_resize`): Whether to resize the image. size (`dict[str, int]`, *optional*, defaults to `self.size`): Size of the image after resizing. resample (`int`, *optional*, defaults to `self.resample`): Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only has an effect if `do_resize` is set to `True`. do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`): Whether to center crop the image. crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`): Size of the image after center crop. If one edge the image is smaller than `crop_size`, it will be padded with zeros and then cropped do_rescale (`bool`, *optional*, defaults to `self.do_rescale`): Whether to rescale the image values between [0 - 1]. rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`): Rescale factor to rescale the image by if `do_rescale` is set to `True`. do_normalize (`bool`, *optional*, defaults to `self.do_normalize`): Whether to normalize the image. image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`): Image mean. image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`): Image standard deviation. do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`): Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background, and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255. return_tensors (`str` or `TensorType`, *optional*): The type of tensors to return. Can be one of: - Unset: Return a list of `np.ndarray`. - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`. data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`): The channel dimension format for the output image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - Unset: Use the channel dimension format of the input image. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of: - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format. - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format. - `"none"` or `ChannelDimension.NONE`: image in (height, width) format. """ do_resize = do_resize if do_resize is not None else self.do_resize size = size if size is not None else self.size size = get_size_dict(size, default_to_square=True, param_name="size") resample = resample if resample is not None else self.resample do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop crop_size = crop_size if crop_size is not None else self.crop_size crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size") do_rescale = do_rescale if do_rescale is not None else self.do_rescale rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor do_normalize = do_normalize if do_normalize is not None else self.do_normalize image_mean = image_mean if image_mean is not None else self.image_mean image_std = image_std if image_std is not None else self.image_std do_reduce_labels = do_reduce_labels if do_reduce_labels is not None else self.do_reduce_labels images = make_flat_list_of_images(images) if segmentation_maps is not None: segmentation_maps = make_flat_list_of_images(segmentation_maps, expected_ndims=2) if segmentation_maps is not None and not valid_images(segmentation_maps): raise ValueError( "Invalid segmentation_maps type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor" ) if not valid_images(images): raise ValueError("Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, or torch.Tensor") validate_preprocess_arguments( do_rescale=do_rescale, rescale_factor=rescale_factor, do_normalize=do_normalize, image_mean=image_mean, image_std=image_std, do_center_crop=do_center_crop, crop_size=crop_size, do_resize=do_resize, size=size, resample=resample, ) images = [ self._preprocess_image( image=img, do_resize=do_resize, do_center_crop=do_center_crop, do_rescale=do_rescale, do_normalize=do_normalize, resample=resample, size=size, rescale_factor=rescale_factor, crop_size=crop_size, image_mean=image_mean, image_std=image_std, data_format=data_format, input_data_format=input_data_format, ) for img in images ] data = {"pixel_values": images} if segmentation_maps is not None: segmentation_maps = [ self._preprocess_segmentation_map( segmentation_map=segmentation_map, do_reduce_labels=do_reduce_labels, do_resize=do_resize, resample=resample, size=size, do_center_crop=do_center_crop, crop_size=crop_size, ) for segmentation_map in segmentation_maps ] data["labels"] = segmentation_maps return BatchFeature(data=data, tensor_type=return_tensors) def post_process_semantic_segmentation(self, outputs, target_sizes: Optional[list[tuple]] = None): """ Converts the output of [`BeitForSemanticSegmentation`] into semantic segmentation maps. Args: outputs ([`BeitForSemanticSegmentation`]): Raw outputs of the model. target_sizes (`list[Tuple]` of length `batch_size`, *optional*): List of tuples corresponding to the requested final size (height, width) of each prediction. If unset, predictions will not be resized. Returns: semantic_segmentation: `list[torch.Tensor]` of length `batch_size`, where each item is a semantic segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each `torch.Tensor` correspond to a semantic class id. """ logits = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(logits) != len(target_sizes): raise ValueError( "Make sure that you pass in as many target sizes as the batch dimension of the logits" ) if is_torch_tensor(target_sizes): target_sizes = target_sizes.numpy() semantic_segmentation = [] for idx in range(len(logits)): resized_logits = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False ) semantic_map = resized_logits[0].argmax(dim=0) semantic_segmentation.append(semantic_map) else: semantic_segmentation = logits.argmax(dim=1) semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])] return semantic_segmentation __all__ = ["BeitImageProcessor"]
BeitImageProcessor
python
django-extensions__django-extensions
tests/testapp/management/commands/test_email_notification_command.py
{ "start": 88, "end": 253 }
class ____(EmailNotificationCommand): help = "Just for email_notifications testing purpose" def handle(self, *args, **kwargs): raise Exception()
Command
python
run-llama__llama_index
llama-index-core/llama_index/core/evaluation/retrieval/metrics.py
{ "start": 6010, "end": 7920 }
class ____(BaseRetrievalMetric): """ Precision metric. The `K`-value in `Precision@K` usually corresponds to `top_k` of the retriever. Attributes: metric_name (str): The name of the metric. """ metric_name: ClassVar[str] = "precision" def compute( self, query: Optional[str] = None, expected_ids: Optional[List[str]] = None, retrieved_ids: Optional[List[str]] = None, expected_texts: Optional[List[str]] = None, retrieved_texts: Optional[List[str]] = None, **kwargs: Any, ) -> RetrievalMetricResult: """ Compute precision based on the provided inputs and selected method. Parameters ---------- query (Optional[str]): The query string (not used in the current implementation). expected_ids (Optional[List[str]]): Expected document IDs. retrieved_ids (Optional[List[str]]): Retrieved document IDs. expected_texts (Optional[List[str]]): Expected texts (not used in the current implementation). retrieved_texts (Optional[List[str]]): Retrieved texts (not used in the current implementation). Raises ------ ValueError: If the necessary IDs are not provided. Returns ------- RetrievalMetricResult: The result with the computed precision score. """ # Checking for the required arguments if ( retrieved_ids is None or expected_ids is None or not retrieved_ids or not expected_ids ): raise ValueError("Retrieved ids and expected ids must be provided") retrieved_set = set(retrieved_ids) expected_set = set(expected_ids) precision = len(retrieved_set & expected_set) / len(retrieved_set) return RetrievalMetricResult(score=precision)
Precision
python
wandb__wandb
wandb/sdk/launch/sweeps/scheduler.py
{ "start": 1084, "end": 1249 }
class ____(Enum): PENDING = 0 STARTING = 1 RUNNING = 2 FLUSH_RUNS = 3 COMPLETED = 4 FAILED = 5 STOPPED = 6 CANCELLED = 7
SchedulerState
python
wandb__wandb
tests/unit_tests/test_file_stats.py
{ "start": 1910, "end": 3011 }
class ____: def test_init_file(self): s = stats.Stats() s.init_file("foo", 10) assert s.summary() == stats.Summary( uploaded_bytes=0, total_bytes=10, deduped_bytes=0 ) def test_update_uploaded_file_updates_uploaded_bytes(self): s = stats.Stats() s.init_file("foo", 10) s.update_uploaded_file("foo", 7) assert s.summary() == stats.Summary( uploaded_bytes=7, total_bytes=10, deduped_bytes=0 ) def test_set_file_deduped_updates_deduped_bytes(self): s = stats.Stats() s.init_file("foo", 10) s.set_file_deduped("foo") assert s.summary() == stats.Summary( uploaded_bytes=10, total_bytes=10, deduped_bytes=10 ) def test_failed_file_resets_summary_uploaded_bytes(): s = stats.Stats() s.init_file("foo", 10) s.init_file("bar", 10) s.update_uploaded_file("foo", 7) s.update_uploaded_file("bar", 8) assert s.summary().uploaded_bytes == 15 s.update_failed_file("foo") assert s.summary().uploaded_bytes == 8
TestSummary
python
matplotlib__matplotlib
lib/matplotlib/ticker.py
{ "start": 12158, "end": 12644 }
class ____(string.Formatter): """ A specialized string formatter so that `.StrMethodFormatter` respects :rc:`axes.unicode_minus`. This implementation relies on the fact that the format string is only ever called with kwargs *x* and *pos*, so it blindly replaces dashes by unicode minuses without further checking. """ def format_field(self, value, format_spec): return Formatter.fix_minus(super().format_field(value, format_spec))
_UnicodeMinusFormat
python
django-guardian__django-guardian
guardian/admin.py
{ "start": 3723, "end": 4142 }
class ____(GroupObjectPermissionsForm): """Admin form for group object permissions. Extends the `GroupObjectPermissionsForm` and overrides the `get_obj_perms_field_widget` method so it returns the `django.contrib.admin.widgets.FilteredSelectMultiple` widget. """ def get_obj_perms_field_widget(self): return FilteredSelectMultiple(_("Permissions"), False)
AdminGroupObjectPermissionsForm
python
redis__redis-py
tests/test_cluster.py
{ "start": 136149, "end": 138320 }
class ____: def test_wait_command_not_found(self, r): "Make sure the wait_for_command func works when command is not found" key = "foo" node = r.get_node_from_key(key) with r.monitor(target_node=node) as m: response = wait_for_command(r, m, "nothing", key=key) assert response is None def test_response_values(self, r): db = 0 key = "foo" node = r.get_node_from_key(key) with r.monitor(target_node=node) as m: r.ping(target_nodes=node) response = wait_for_command(r, m, "PING", key=key) assert isinstance(response["time"], float) assert response["db"] == db assert response["client_type"] in ("tcp", "unix") assert isinstance(response["client_address"], str) assert isinstance(response["client_port"], str) assert response["command"] == "PING" def test_command_with_quoted_key(self, r): key = "{foo}1" node = r.get_node_from_key(key) with r.monitor(node) as m: r.get('{foo}"bar') response = wait_for_command(r, m, 'GET {foo}"bar', key=key) assert response["command"] == 'GET {foo}"bar' def test_command_with_binary_data(self, r): key = "{foo}1" node = r.get_node_from_key(key) with r.monitor(target_node=node) as m: byte_string = b"{foo}bar\x92" r.get(byte_string) response = wait_for_command(r, m, "GET {foo}bar\\x92", key=key) assert response["command"] == "GET {foo}bar\\x92" def test_command_with_escaped_data(self, r): key = "{foo}1" node = r.get_node_from_key(key) with r.monitor(target_node=node) as m: byte_string = b"{foo}bar\\x92" r.get(byte_string) response = wait_for_command(r, m, "GET {foo}bar\\\\x92", key=key) assert response["command"] == "GET {foo}bar\\\\x92" def test_flush(self, r): r.set("x", "1") r.set("z", "1") r.flushall() assert r.get("x") is None assert r.get("y") is None
TestClusterMonitor
python
langchain-ai__langchain
libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py
{ "start": 38984, "end": 67241 }
class ____(BaseRetriever): documents: list[Document] @override def _get_relevant_documents( self, query: str, *, run_manager: CallbackManagerForRetrieverRun ) -> list[Document]: return self.documents async def test_event_stream_with_retriever() -> None: """Test the event stream with a retriever.""" retriever = HardCodedRetriever( documents=[ Document( page_content="hello world!", metadata={"foo": "bar"}, ), Document( page_content="goodbye world!", metadata={"food": "spare"}, ), ] ) events = await _collect_events( retriever.astream_events({"query": "hello"}, version="v2") ) _assert_events_equal_allow_superset_metadata( events, [ { "data": { "input": {"query": "hello"}, }, "event": "on_retriever_start", "metadata": {}, "name": "HardCodedRetriever", "run_id": "", "parent_ids": [], "tags": [], }, { "data": { "output": [ Document(page_content="hello world!", metadata={"foo": "bar"}), Document( page_content="goodbye world!", metadata={"food": "spare"} ), ] }, "event": "on_retriever_end", "metadata": {}, "name": "HardCodedRetriever", "run_id": "", "parent_ids": [], "tags": [], }, ], ) async def test_event_stream_with_retriever_and_formatter() -> None: """Test the event stream with a retriever.""" retriever = HardCodedRetriever( documents=[ Document( page_content="hello world!", metadata={"foo": "bar"}, ), Document( page_content="goodbye world!", metadata={"food": "spare"}, ), ] ) def format_docs(docs: list[Document]) -> str: """Format the docs.""" return ", ".join([doc.page_content for doc in docs]) chain = retriever | format_docs events = await _collect_events(chain.astream_events("hello", version="v2")) _assert_events_equal_allow_superset_metadata( events, [ { "data": {"input": "hello"}, "event": "on_chain_start", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"input": {"query": "hello"}}, "event": "on_retriever_start", "metadata": {}, "name": "HardCodedRetriever", "run_id": "", "parent_ids": [], "tags": ["seq:step:1"], }, { "data": { "input": {"query": "hello"}, "output": [ Document(page_content="hello world!", metadata={"foo": "bar"}), Document( page_content="goodbye world!", metadata={"food": "spare"} ), ], }, "event": "on_retriever_end", "metadata": {}, "name": "HardCodedRetriever", "run_id": "", "parent_ids": [], "tags": ["seq:step:1"], }, { "data": {}, "event": "on_chain_start", "metadata": {}, "name": "format_docs", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"chunk": "hello world!, goodbye world!"}, "event": "on_chain_stream", "metadata": {}, "name": "format_docs", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"chunk": "hello world!, goodbye world!"}, "event": "on_chain_stream", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": { "input": [ Document(page_content="hello world!", metadata={"foo": "bar"}), Document( page_content="goodbye world!", metadata={"food": "spare"} ), ], "output": "hello world!, goodbye world!", }, "event": "on_chain_end", "metadata": {}, "name": "format_docs", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"output": "hello world!, goodbye world!"}, "event": "on_chain_end", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, ], ) async def test_event_stream_on_chain_with_tool() -> None: """Test the event stream with a tool.""" @tool def concat(a: str, b: str) -> str: """A tool that does nothing.""" return a + b def reverse(s: str) -> str: """Reverse a string.""" return s[::-1] # For whatever reason type annotations fail here because reverse # does not appear to be a runnable chain = concat | reverse events = await _collect_events( chain.astream_events({"a": "hello", "b": "world"}, version="v2") ) _assert_events_equal_allow_superset_metadata( events, [ { "data": {"input": {"a": "hello", "b": "world"}}, "event": "on_chain_start", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"input": {"a": "hello", "b": "world"}}, "event": "on_tool_start", "metadata": {}, "name": "concat", "run_id": "", "parent_ids": [], "tags": ["seq:step:1"], }, { "data": {"input": {"a": "hello", "b": "world"}, "output": "helloworld"}, "event": "on_tool_end", "metadata": {}, "name": "concat", "run_id": "", "parent_ids": [], "tags": ["seq:step:1"], }, { "data": {}, "event": "on_chain_start", "metadata": {}, "name": "reverse", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"chunk": "dlrowolleh"}, "event": "on_chain_stream", "metadata": {}, "name": "reverse", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"chunk": "dlrowolleh"}, "event": "on_chain_stream", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"input": "helloworld", "output": "dlrowolleh"}, "event": "on_chain_end", "metadata": {}, "name": "reverse", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"output": "dlrowolleh"}, "event": "on_chain_end", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, ], ) @pytest.mark.xfail(reason="Fix order of callback invocations in RunnableSequence") async def test_chain_ordering() -> None: """Test the event stream with a tool.""" def foo(a: str) -> str: return a def bar(a: str) -> str: return a chain = RunnableLambda(foo) | RunnableLambda(bar) iterable = chain.astream_events("q", version="v2") events = [] try: for _ in range(10): next_chunk = await iterable.__anext__() events.append(next_chunk) except Exception: pass events = _with_nulled_run_id(events) for event in events: event["tags"] = sorted(event["tags"]) _assert_events_equal_allow_superset_metadata( events, [ { "data": {"input": "q"}, "event": "on_chain_start", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {}, "event": "on_chain_start", "metadata": {}, "name": "foo", "run_id": "", "parent_ids": [], "tags": ["seq:step:1"], }, { "data": {"chunk": "q"}, "event": "on_chain_stream", "metadata": {}, "name": "foo", "run_id": "", "parent_ids": [], "tags": ["seq:step:1"], }, { "data": {"input": "q", "output": "q"}, "event": "on_chain_end", "metadata": {}, "name": "foo", "run_id": "", "parent_ids": [], "tags": ["seq:step:1"], }, { "data": {}, "event": "on_chain_start", "metadata": {}, "name": "bar", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"chunk": "q"}, "event": "on_chain_stream", "metadata": {}, "name": "bar", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"chunk": "q"}, "event": "on_chain_stream", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"input": "q", "output": "q"}, "event": "on_chain_end", "metadata": {}, "name": "bar", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"output": "q"}, "event": "on_chain_end", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, ], ) async def test_event_stream_with_retry() -> None: """Test the event stream with a tool.""" def success(_: str) -> str: return "success" def fail(_: str) -> None: """Simple func.""" msg = "fail" raise ValueError(msg) chain = RunnableLambda(success) | RunnableLambda(fail).with_retry( stop_after_attempt=1, ) iterable = chain.astream_events("q", version="v2") events = [] try: for _ in range(10): next_chunk = await iterable.__anext__() events.append(next_chunk) except Exception: pass events = _with_nulled_run_id(events) for event in events: event["tags"] = sorted(event["tags"]) _assert_events_equal_allow_superset_metadata( events, [ { "data": {"input": "q"}, "event": "on_chain_start", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {}, "event": "on_chain_start", "metadata": {}, "name": "success", "run_id": "", "parent_ids": [], "tags": ["seq:step:1"], }, { "data": {"chunk": "success"}, "event": "on_chain_stream", "metadata": {}, "name": "success", "run_id": "", "parent_ids": [], "tags": ["seq:step:1"], }, { "data": {}, "event": "on_chain_start", "metadata": {}, "name": "fail", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"input": "q", "output": "success"}, "event": "on_chain_end", "metadata": {}, "name": "success", "run_id": "", "parent_ids": [], "tags": ["seq:step:1"], }, ], ) async def test_with_llm() -> None: """Test with regular llm.""" prompt = ChatPromptTemplate.from_messages( [ ("system", "You are Cat Agent 007"), ("human", "{question}"), ] ).with_config({"run_name": "my_template", "tags": ["my_template"]}) llm = FakeStreamingListLLM(responses=["abc"]) chain = prompt | llm events = await _collect_events( chain.astream_events({"question": "hello"}, version="v2") ) _assert_events_equal_allow_superset_metadata( events, [ { "data": {"input": {"question": "hello"}}, "event": "on_chain_start", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"input": {"question": "hello"}}, "event": "on_prompt_start", "metadata": {}, "name": "my_template", "run_id": "", "parent_ids": [], "tags": ["my_template", "seq:step:1"], }, { "data": { "input": {"question": "hello"}, "output": ChatPromptValue( messages=[ SystemMessage(content="You are Cat Agent 007"), HumanMessage(content="hello"), ] ), }, "event": "on_prompt_end", "metadata": {}, "name": "my_template", "run_id": "", "parent_ids": [], "tags": ["my_template", "seq:step:1"], }, { "data": { "input": { "prompts": ["System: You are Cat Agent 007\nHuman: hello"] } }, "event": "on_llm_start", "metadata": {}, "name": "FakeStreamingListLLM", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": { "input": { "prompts": ["System: You are Cat Agent 007\nHuman: hello"] }, "output": { "generations": [ [ { "generation_info": None, "text": "abc", "type": "Generation", } ] ], "llm_output": None, }, }, "event": "on_llm_end", "metadata": {}, "name": "FakeStreamingListLLM", "run_id": "", "parent_ids": [], "tags": ["seq:step:2"], }, { "data": {"chunk": "a"}, "event": "on_chain_stream", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"chunk": "b"}, "event": "on_chain_stream", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"chunk": "c"}, "event": "on_chain_stream", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"output": "abc"}, "event": "on_chain_end", "metadata": {}, "name": "RunnableSequence", "run_id": "", "parent_ids": [], "tags": [], }, ], ) async def test_runnable_each() -> None: """Test runnable each astream_events.""" async def add_one(x: int) -> int: return x + 1 add_one_map = RunnableLambda(add_one).map() # type: ignore[arg-type,var-annotated] assert await add_one_map.ainvoke([1, 2, 3]) == [2, 3, 4] with pytest.raises(NotImplementedError): _ = [_ async for _ in add_one_map.astream_events([1, 2, 3], version="v2")] async def test_events_astream_config() -> None: """Test that astream events support accepting config.""" infinite_cycle = cycle([AIMessage(content="hello world!", id="ai1")]) good_world_on_repeat = cycle([AIMessage(content="Goodbye world", id="ai2")]) model = GenericFakeChatModel(messages=infinite_cycle).configurable_fields( messages=ConfigurableField( id="messages", name="Messages", description="Messages return by the LLM", ) ) model_02 = model.with_config({"configurable": {"messages": good_world_on_repeat}}) assert model_02.invoke("hello") == AIMessage(content="Goodbye world", id="ai2") events = await _collect_events(model_02.astream_events("hello", version="v2")) _assert_events_equal_allow_superset_metadata( events, [ { "data": {"input": "hello"}, "event": "on_chat_model_start", "metadata": {"ls_model_type": "chat"}, "name": "GenericFakeChatModel", "run_id": "", "parent_ids": [], "tags": [], }, { "data": { "chunk": AIMessageChunk( content="Goodbye", id="ai2", ) }, "event": "on_chat_model_stream", "metadata": {"ls_model_type": "chat"}, "name": "GenericFakeChatModel", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"chunk": AIMessageChunk(content=" ", id="ai2")}, "event": "on_chat_model_stream", "metadata": {"ls_model_type": "chat"}, "name": "GenericFakeChatModel", "run_id": "", "parent_ids": [], "tags": [], }, { "data": { "chunk": AIMessageChunk( content="world", id="ai2", chunk_position="last" ) }, "event": "on_chat_model_stream", "metadata": {"ls_model_type": "chat"}, "name": "GenericFakeChatModel", "run_id": "", "parent_ids": [], "tags": [], }, { "data": { "output": AIMessageChunk( content="Goodbye world", id="ai2", chunk_position="last" ), }, "event": "on_chat_model_end", "metadata": {"ls_model_type": "chat"}, "name": "GenericFakeChatModel", "run_id": "", "parent_ids": [], "tags": [], }, ], ) async def test_runnable_with_message_history() -> None: class InMemoryHistory(BaseChatMessageHistory, BaseModel): """In memory implementation of chat message history.""" # Attention: for the tests use an Any type to work-around a pydantic issue # where it re-instantiates a list, so mutating the list doesn't end up mutating # the content in the store! # Using Any type here rather than list[BaseMessage] due to pydantic issue! messages: Any def add_message(self, message: BaseMessage) -> None: """Add a self-created message to the store.""" self.messages.append(message) def clear(self) -> None: self.messages = [] # Here we use a global variable to store the chat message history. # This will make it easier to inspect it to see the underlying results. store: dict = {} def get_by_session_id(session_id: str) -> BaseChatMessageHistory: """Get a chat message history.""" if session_id not in store: store[session_id] = [] return InMemoryHistory(messages=store[session_id]) infinite_cycle = cycle( [ AIMessage(content="hello", id="ai3"), AIMessage(content="world", id="ai4"), ] ) prompt = ChatPromptTemplate.from_messages( [ ("system", "You are a cat"), MessagesPlaceholder(variable_name="history"), ("human", "{question}"), ] ) model = GenericFakeChatModel(messages=infinite_cycle) chain = prompt | model with_message_history = RunnableWithMessageHistory( chain, get_session_history=get_by_session_id, input_messages_key="question", history_messages_key="history", ) # patch with_message_history._get_output_messages to listen for errors # so we can raise them in this main thread raised_errors = [] def collect_errors(fn: Callable[..., Any]) -> Callable[..., Any]: nonlocal raised_errors def _get_output_messages(*args: Any, **kwargs: Any) -> Any: try: return fn(*args, **kwargs) except Exception as e: raised_errors.append(e) raise return _get_output_messages old_ref = with_message_history._get_output_messages with_message_history.__dict__["_get_output_messages"] = collect_errors(old_ref) await with_message_history.with_config( {"configurable": {"session_id": "session-123"}} ).ainvoke({"question": "hello"}) assert store == { "session-123": [ HumanMessage(content="hello"), AIMessage(content="hello", id="ai3"), ] } await asyncio.to_thread( with_message_history.with_config( {"configurable": {"session_id": "session-123"}} ).invoke, {"question": "meow"}, ) assert store == { "session-123": [ HumanMessage(content="hello"), AIMessage(content="hello", id="ai3"), HumanMessage(content="meow"), AIMessage(content="world", id="ai4"), ] } assert not raised_errors EXPECTED_EVENTS = [ { "data": {"input": 1}, "event": "on_chain_start", "metadata": {}, "name": "add_one_proxy", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {}, "event": "on_chain_start", "metadata": {}, "name": "add_one", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"chunk": 2}, "event": "on_chain_stream", "metadata": {}, "name": "add_one", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"input": 1, "output": 2}, "event": "on_chain_end", "metadata": {}, "name": "add_one", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"chunk": 2}, "event": "on_chain_stream", "metadata": {}, "name": "add_one_proxy", "run_id": "", "parent_ids": [], "tags": [], }, { "data": {"output": 2}, "event": "on_chain_end", "metadata": {}, "name": "add_one_proxy", "run_id": "", "parent_ids": [], "tags": [], }, ] async def test_sync_in_async_stream_lambdas(blockbuster: BlockBuster) -> None: """Test invoking nested runnable lambda.""" blockbuster.deactivate() def add_one(x: int) -> int: return x + 1 add_one_ = RunnableLambda(add_one) async def add_one_proxy(x: int, config: RunnableConfig) -> int: streaming = add_one_.stream(x, config) results = list(streaming) return results[0] add_one_proxy_ = RunnableLambda(add_one_proxy) # type: ignore[arg-type,var-annotated] events = await _collect_events(add_one_proxy_.astream_events(1, version="v2")) _assert_events_equal_allow_superset_metadata(events, EXPECTED_EVENTS) async def test_async_in_async_stream_lambdas() -> None: """Test invoking nested runnable lambda.""" async def add_one(x: int) -> int: return x + 1 add_one_ = RunnableLambda(add_one) # type: ignore[arg-type,var-annotated] async def add_one_proxy(x: int, config: RunnableConfig) -> int: # Use sync streaming streaming = add_one_.astream(x, config) results = [result async for result in streaming] return results[0] add_one_proxy_ = RunnableLambda(add_one_proxy) # type: ignore[arg-type,var-annotated] events = await _collect_events(add_one_proxy_.astream_events(1, version="v2")) _assert_events_equal_allow_superset_metadata(events, EXPECTED_EVENTS) async def test_sync_in_sync_lambdas() -> None: """Test invoking nested runnable lambda.""" def add_one(x: int) -> int: return x + 1 add_one_ = RunnableLambda(add_one) def add_one_proxy(x: int, config: RunnableConfig) -> int: # Use sync streaming streaming = add_one_.stream(x, config) results = list(streaming) return results[0] add_one_proxy_ = RunnableLambda(add_one_proxy) events = await _collect_events(add_one_proxy_.astream_events(1, version="v2")) _assert_events_equal_allow_superset_metadata(events, EXPECTED_EVENTS)
HardCodedRetriever
python
jamielennox__requests-mock
requests_mock/exceptions.py
{ "start": 619, "end": 914 }
class ____(MockException): """The requested URL was not mocked""" def __init__(self, request): self.request = request def __str__(self): return "No mock address: %s %s" % (self.request.method, self.request.url)
NoMockAddress
python
gevent__gevent
src/gevent/greenlet.py
{ "start": 3227, "end": 3541 }
class ____(SpawnedLink): """A wrapper around link that calls it in another greenlet only if source succeed. Can be called only from main loop. """ __slots__ = [] def __call__(self, source): if source.successful(): return SpawnedLink.__call__(self, source)
SuccessSpawnedLink
python
astropy__astropy
astropy/io/votable/tree.py
{ "start": 73250, "end": 116476 }
class ____( Element, _IDProperty, _NameProperty, _UcdProperty, _DescriptionProperty ): """ TABLE_ element: optionally contains data. It contains the following publicly-accessible and mutable attribute: *array*: A Numpy masked array of the data itself, where each row is a row of votable data, and columns are named and typed based on the <FIELD> elements of the table. The mask is parallel to the data array, except for variable-length fields. For those fields, the numpy array's column type is "object" (``"O"``), and another masked array is stored there. If the TableElement contains no data, (for example, its enclosing :class:`Resource` has :attr:`~Resource.type` == 'meta') *array* will have zero-length. The keyword arguments correspond to setting members of the same name, documented below. """ def __init__( self, votable, ID=None, name=None, ref=None, ucd=None, utype=None, nrows=None, id=None, config=None, pos=None, **extra, ): self._config = _attach_default_config(votable, config) self._pos = pos self._empty = False Element.__init__(self) self._votable = votable self.ID = resolve_id(ID, id, self._config, pos) or xmlutil.fix_id( name, self._config, pos ) self.name = name xmlutil.check_id(ref, "ref", self._config, pos) self._ref = ref self.ucd = ucd self.utype = utype if nrows is not None: nrows = int(nrows) if nrows < 0: raise ValueError("'nrows' cannot be negative.") self._nrows = nrows self.description = None self.format = "tabledata" self._fields = HomogeneousList(Field) self._all_fields = HomogeneousList(Field) self._params = HomogeneousList(Param) self._groups = HomogeneousList(Group) self._links = HomogeneousList(Link) self._infos = HomogeneousList(Info) self.array = ma.array([]) warn_unknown_attrs("TABLE", extra.keys(), self._config, pos) def __repr__(self): s = repr(self.to_table()) if s.startswith("<Table"): s = "<VO" + s[1:] return s def __bytes__(self): return bytes(self.to_table()) def __str__(self): return str(self.to_table()) @property def ref(self): return self._ref @ref.setter def ref(self, ref): """ Refer to another TABLE, previously defined, by the *ref* ID_ for all metadata (FIELD_, PARAM_ etc.) information. """ # When the ref changes, we want to verify that it will work # by actually going and looking for the referenced table. # If found, set a bunch of properties in this table based # on the other one. xmlutil.check_id(ref, "ref", self._config, self._pos) if ref is not None: try: table = self._votable.get_table_by_id(ref, before=self) except KeyError: warn_or_raise(W43, W43, ("TABLE", self.ref), self._config, self._pos) ref = None else: self._fields = table.fields self._all_fields = table.all_fields self._params = table.params self._groups = table.groups self._links = table.links else: del self._fields[:] del self._all_fields[:] del self._params[:] del self._groups[:] del self._links[:] self._ref = ref @ref.deleter def ref(self): self._ref = None @property def format(self): """The serialization format of the table [*required*]. Must be one of: 'tabledata' (TABLEDATA_), 'binary' (BINARY_), 'binary2' (BINARY2_) 'fits' (FITS_). Note that the 'fits' format, since it requires an external file, can not be written out. Any file read in with 'fits' format will be read out, by default, in 'tabledata' format. See :ref:`astropy:votable-serialization`. """ return self._format @format.setter def format(self, format): format = format.lower() if format == "fits": vo_raise( NotImplementedError, "fits format can not be written out, only read.", self._config, self._pos, ) if format == "binary2": if not self._config.get("version_1_3_or_later"): vo_raise( W37, "binary2 only supported in votable 1.3 or later", self._config, self._pos, ) elif format not in ("tabledata", "binary"): vo_raise(W37, f"Invalid format '{format}'", self._config, self._pos) self._format = format @property def nrows(self): """ [*immutable*] The number of rows in the table, as specified in the XML file. """ return self._nrows @property def fields(self): """ A list of :class:`Field` objects describing the types of each of the data columns. """ return self._fields @property def all_fields(self): """ A list of :class:`Field` objects describing the types of each of the data columns. Contrary to ``fields``, this property should list every field that's available on disk, including deselected columns. """ # since we support extending self.fields directly via list.extend # and list.append, self._all_fields may go out of sync. # To remedy this issue, we sync back the public property upon access. for field in self._fields: if field not in self._all_fields: self._all_fields.append(field) return self._all_fields @property def params(self): """ A list of parameters (constant-valued columns) for the table. Must contain only :class:`Param` objects. """ return self._params @property def groups(self): """ A list of :class:`Group` objects describing how the columns and parameters are grouped. Currently this information is only kept around for round-tripping and informational purposes. """ return self._groups @property def links(self): """ A list of :class:`Link` objects (pointers to other documents or servers through a URI) for the table. """ return self._links @property def infos(self): """ A list of :class:`Info` objects for the table. Allows for post-operational diagnostics. """ return self._infos def is_empty(self): """ Returns True if this table doesn't contain any real data because it was skipped over by the parser (through use of the ``table_number`` kwarg). """ return self._empty def create_arrays( self, nrows=0, config=None, *, colnumbers=None, ): """ Create a new array to hold the data based on the current set of fields, and store them in the *array* and member variable. Any data in the existing array will be lost. *nrows*, if provided, is the number of rows to allocate. *colnumbers*, if provided, is the list of column indices to select. By default, all columns are selected. """ if nrows is None: nrows = 0 if colnumbers is None: colnumbers = list(range(len(self.all_fields))) new_fields = HomogeneousList( Field, values=[f for i, f in enumerate(self.all_fields) if i in colnumbers], ) if new_fields != self._fields: self._fields = new_fields fields = self.all_fields if len(fields) == 0: array = np.recarray((nrows,), dtype="O") mask = np.zeros((nrows,), dtype="b") else: # for field in fields: field._setup(config) Field.uniqify_names(fields) dtype = [] for i, x in enumerate(fields): if i not in colnumbers: continue if x._unique_name == x.ID: id = x.ID else: id = (x._unique_name, x.ID) dtype.append((id, x.converter.format)) array = np.recarray((nrows,), dtype=np.dtype(dtype)) descr_mask = [] for d in array.dtype.descr: new_type = (d[1][1] == "O" and "O") or "bool" if len(d) == 2: descr_mask.append((d[0], new_type)) elif len(d) == 3: descr_mask.append((d[0], new_type, d[2])) mask = np.zeros((nrows,), dtype=descr_mask) self.array = ma.array(array, mask=mask) def _resize_strategy(self, size): """ Return a new (larger) size based on size, used for reallocating an array when it fills up. This is in its own function so the resizing strategy can be easily replaced. """ # Once we go beyond 0, make a big step -- after that use a # factor of 1.5 to help keep memory usage compact if size == 0: return 512 return int(np.ceil(size * RESIZE_AMOUNT)) def add_field(self, field: Field) -> None: self.fields.append(field) self.all_fields.append(field) def _register_field(self, iterator, tag, data, config, pos) -> None: field = Field(self._votable, config=config, pos=pos, **data) field.parse(iterator, config) self._all_fields.append(field) def _add_param(self, iterator, tag, data, config, pos): param = Param(self._votable, config=config, pos=pos, **data) self.params.append(param) param.parse(iterator, config) def _add_group(self, iterator, tag, data, config, pos): group = Group(self, config=config, pos=pos, **data) self.groups.append(group) group.parse(iterator, config) def _add_link(self, iterator, tag, data, config, pos): link = Link(config=config, pos=pos, **data) self.links.append(link) link.parse(iterator, config) def _add_info(self, iterator, tag, data, config, pos): if not config.get("version_1_2_or_later"): warn_or_raise(W26, W26, ("INFO", "TABLE", "1.2"), config, pos) info = Info(config=config, pos=pos, **data) self.infos.append(info) info.parse(iterator, config) def parse(self, iterator, config): columns = config.get("columns") # If we've requested to read in only a specific table, skip # all others table_number = config.get("table_number") current_table_number = config.get("_current_table_number") skip_table = False if current_table_number is not None: config["_current_table_number"] += 1 if table_number is not None and table_number != current_table_number: skip_table = True self._empty = True table_id = config.get("table_id") if table_id is not None: if table_id != self.ID: skip_table = True self._empty = True if self.ref is not None: # This table doesn't have its own datatype descriptors, it # just references those from another table. # This is to call the property setter to go and get the # referenced information self.ref = self.ref for start, tag, data, pos in iterator: if start: if tag == "DATA": warn_unknown_attrs("DATA", data.keys(), config, pos) break else: if tag == "TABLE": return self elif tag == "DESCRIPTION": if self.description is not None: warn_or_raise(W17, W17, "RESOURCE", config, pos) self.description = data or None else: tag_mapping = { "FIELD": self._register_field, "PARAM": self._add_param, "GROUP": self._add_group, "LINK": self._add_link, "INFO": self._add_info, "DESCRIPTION": self._ignore_add, } for start, tag, data, pos in iterator: if start: if tag == "DATA": if len(self.all_fields) == 0: warn_or_raise(E25, E25, None, config, pos) warn_unknown_attrs("DATA", data.keys(), config, pos) break tag_mapping.get(tag, self._add_unknown_tag)( iterator, tag, data, config, pos ) else: if tag == "DESCRIPTION": if self.description is not None: warn_or_raise(W17, W17, "RESOURCE", config, pos) self.description = data or None elif tag == "TABLE": # For error checking purposes Field.uniqify_names(self.all_fields) # We still need to create arrays, even if the file # contains no DATA section self.create_arrays(nrows=0, config=config) return self fields = self.all_fields Field.uniqify_names(fields) names = [x.ID for x in fields] # Deal with a subset of the columns, if requested. if not columns: colnumbers = list(range(len(fields))) else: if isinstance(columns, str): columns = [columns] columns = np.asarray(columns) if issubclass(columns.dtype.type, np.integer): if np.any(columns < 0) or np.any(columns > len(fields)): raise ValueError("Some specified column numbers out of range") colnumbers = columns elif issubclass(columns.dtype.type, np.character): try: colnumbers = [names.index(x) for x in columns] except ValueError: # convert to builtin str because representation of numpy strings # differ in numpy 2 and may be confusing to users missing_columns = [ str(name) for name in columns if name not in names ] raise ValueError( f"Columns {missing_columns} were not found in fields list" ) from None else: raise TypeError("Invalid columns list") self.create_arrays(nrows=self._nrows, config=config, colnumbers=colnumbers) if (not skip_table) and (len(fields) > 0): for start, tag, data, pos in iterator: if not start: continue if tag == "TABLEDATA": warn_unknown_attrs("TABLEDATA", data.keys(), config, pos) self.array = self._parse_tabledata(iterator, colnumbers, config) elif tag == "BINARY": warn_unknown_attrs("BINARY", data.keys(), config, pos) self.array = self._parse_binary( 1, iterator, colnumbers, config, pos ) elif tag == "BINARY2": if not config.get("version_1_3_or_later"): warn_or_raise(W52, W52, config["version"], config, pos) self.array = self._parse_binary( 2, iterator, colnumbers, config, pos ) elif tag == "FITS": if config.get("columns") is not None: raise NotImplementedError warn_unknown_attrs("FITS", data.keys(), config, pos, ["extnum"]) try: extnum = int(data.get("extnum", 0)) if extnum < 0: raise ValueError("'extnum' cannot be negative.") except ValueError: vo_raise(E17, (), config, pos) self.array = self._parse_fits(iterator, extnum, config) elif tag == "PARQUET": if (data["type"] == "VOTable-remote-file") | ( data["type"] == "VOTable-remote-partition" ): warn_unknown_attrs("PARQUET", data.keys(), config, pos) self.array = self._parse_parquet(iterator, config) else: warn_or_raise(W37, W37, tag, config, pos) break for start, tag, data, pos in iterator: if not start and tag == "DATA": break for start, tag, data, pos in iterator: if start and tag == "INFO": if not config.get("version_1_2_or_later"): warn_or_raise(W26, W26, ("INFO", "TABLE", "1.2"), config, pos) info = Info(config=config, pos=pos, **data) self.infos.append(info) info.parse(iterator, config) elif not start and tag == "TABLE": break return self def _parse_tabledata(self, iterator, colnumbers, config): # Since we don't know the number of rows up front, we'll # reallocate the record array to make room as we go. This # prevents the need to scan through the XML twice. The # allocation is by factors of 1.5. invalid = config.get("invalid", "exception") # Need to have only one reference so that we can resize the # array array = self.array del self.array fields = self.all_fields parsers = [field.converter.parse for field in fields] binparsers = [field.converter.binparse for field in fields] numrows = 0 alloc_rows = len(array) colnumbers_bits = [i in colnumbers for i in range(len(fields))] row_default = [field.converter.default for field in self.fields] mask_default = [True] * len(self.fields) array_chunk = [] mask_chunk = [] chunk_size = config.get("chunk_size", DEFAULT_CHUNK_SIZE) for start, tag, data, pos in iterator: if tag == "TR": # Now parse one row row = row_default[:] row_mask = mask_default[:] i = 0 # index of the column being read from disk j = 0 # index of the column being written in array (not necessarily == i) for start, tag, data, pos in iterator: if start: binary = data.get("encoding", None) == "base64" warn_unknown_attrs(tag, data.keys(), config, pos, ["encoding"]) else: if tag == "TD": if i >= len(fields): vo_raise(E20, len(fields), config, pos) if colnumbers_bits[i]: try: if binary: rawdata = base64.b64decode(data.encode("ascii")) buf = io.BytesIO(rawdata) buf.seek(0) try: value, mask_value = binparsers[i](buf.read) except Exception as e: vo_reraise( e, config, pos, ( f"(in row {len(array_chunk):d}, " f"col '{fields[i].ID}')" ), ) else: try: value, mask_value = parsers[i]( data, config, pos ) except Exception as e: vo_reraise( e, config, pos, ( f"(in row {len(array_chunk):d}, " f"col '{fields[i].ID}')" ), ) except Exception as e: if invalid == "exception": vo_reraise(e, config, pos) else: row[j] = value row_mask[j] = mask_value j += 1 elif tag == "TR": break else: self._add_unknown_tag(iterator, tag, data, config, pos) i += 1 if i < len(fields): vo_raise(E21, (i, len(fields)), config, pos) array_chunk.append(tuple(row)) mask_chunk.append(tuple(row_mask)) if len(array_chunk) == chunk_size: while numrows + chunk_size > alloc_rows: alloc_rows = self._resize_strategy(alloc_rows) if alloc_rows != len(array): array = _resize(array, alloc_rows) array[numrows : numrows + chunk_size] = array_chunk array.mask[numrows : numrows + chunk_size] = mask_chunk numrows += chunk_size array_chunk = [] mask_chunk = [] elif not start and tag == "TABLEDATA": break # Now, resize the array to the exact number of rows we need and # put the last chunk values in there. alloc_rows = numrows + len(array_chunk) array = _resize(array, alloc_rows) array[numrows:] = array_chunk if alloc_rows != 0: array.mask[numrows:] = mask_chunk numrows += len(array_chunk) if self.nrows is not None and self.nrows >= 0 and self.nrows != numrows: warn_or_raise(W18, W18, (self.nrows, numrows), config, pos) self._nrows = numrows return array def _get_binary_data_stream(self, iterator, config): have_local_stream = False for start, tag, data, pos in iterator: if tag == "STREAM": if start: warn_unknown_attrs( "STREAM", data.keys(), config, pos, ["type", "href", "actuate", "encoding", "expires", "rights"], ) if "href" not in data: have_local_stream = True if data.get("encoding", None) != "base64": warn_or_raise( W38, W38, data.get("encoding", None), config, pos ) else: href = data["href"] xmlutil.check_anyuri(href, config, pos) encoding = data.get("encoding", None) else: buffer = data break if have_local_stream: buffer = base64.b64decode(buffer.encode("ascii")) string_io = io.BytesIO(buffer) string_io.seek(0) read = string_io.read else: vo_prot = ("http", "https", "ftp", "file") if not href.startswith(vo_prot): vo_raise( NotImplementedError, f"The vo package only supports remote data through {vo_prot}", self._config, self._pos, ) fd = urllib.request.urlopen(href) if encoding is not None: if encoding == "gzip": fd = gzip.GzipFile(href, "rb", fileobj=fd) elif encoding == "base64": fd = codecs.EncodedFile(fd, "base64") else: vo_raise( NotImplementedError, f"Unknown encoding type '{encoding}'", self._config, self._pos, ) read = fd.read def careful_read(length): result = read(length) if len(result) != length: raise EOFError return result return careful_read def _parse_binary(self, mode, iterator, colnumbers, config, pos): careful_read = self._get_binary_data_stream(iterator, config) # Need to have only one reference so that we can resize the # array array = self.array del self.array fields = self.all_fields binparsers = [field.converter.binparse for field in fields] numrows = 0 alloc_rows = len(array) while True: # Resize result arrays if necessary if numrows >= alloc_rows: alloc_rows = self._resize_strategy(alloc_rows) array = _resize(array, alloc_rows) row_data = [] row_mask_data = [] try: if mode == 2: mask_bits = careful_read(int((len(fields) + 7) / 8)) row_mask_data = list( converters.bitarray_to_bool(mask_bits, len(fields)) ) # Ignore the mask for string columns (see issue 8995) for i, f in enumerate(fields): if row_mask_data[i] and ( f.datatype == "char" or f.datatype == "unicodeChar" ): row_mask_data[i] = False for i, binparse in enumerate(binparsers): try: value, value_mask = binparse(careful_read) except EOFError: raise except Exception as e: vo_reraise( e, config, pos, f"(in row {numrows:d}, col '{fields[i].ID}')", ) row_data.append(value) if mode == 1: row_mask_data.append(value_mask) else: row_mask_data[i] = row_mask_data[i] or value_mask except EOFError: break row = [x.converter.default for x in self.fields] row_mask = [False] * len(self.fields) for j, i in enumerate(colnumbers): row[j] = row_data[i] row_mask[j] = row_mask_data[i] array[numrows] = tuple(row) array.mask[numrows] = tuple(row_mask) numrows += 1 return _resize(array, numrows) def _parse_fits(self, iterator, extnum, config): for start, tag, data, pos in iterator: if tag == "STREAM": if start: warn_unknown_attrs( "STREAM", data.keys(), config, pos, ["type", "href", "actuate", "encoding", "expires", "rights"], ) href = data["href"] encoding = data.get("encoding", None) else: break if not href.startswith(("http", "ftp", "file")): vo_raise( NotImplementedError, "The vo package only supports remote data through http, ftp or file", self._config, self._pos, ) fd = urllib.request.urlopen(href) if encoding is not None: if encoding == "gzip": fd = gzip.GzipFile(href, "r", fileobj=fd) elif encoding == "base64": fd = codecs.EncodedFile(fd, "base64") else: vo_raise( NotImplementedError, f"Unknown encoding type '{encoding}'", self._config, self._pos, ) hdulist = fits.open(fd) array = hdulist[int(extnum)].data if array.dtype != self.array.dtype: warn_or_raise(W19, W19, (), self._config, self._pos) return array def _parse_parquet(self, iterator, config): """ Functionality to parse parquet files that are embedded in VOTables. """ from astropy.table import Table for start, tag, data, pos in iterator: if tag == "STREAM": if start: warn_unknown_attrs( "STREAM", data.keys(), config, pos, ["type", "href", "actuate", "encoding", "expires", "rights"], ) href = data["href"] encoding = data.get("encoding", None) else: break else: # in this case, there is no STREAM, hence no file linked. href = "" if not href.startswith(("http", "ftp", "file")): vo_raise( NotImplementedError, "The vo package only supports remote data through http, ftp or file", self._config, self._pos, ) try: # Hack to keep windows working try: fd = urllib.request.urlopen(href) except urllib.error.URLError: # Hack to keep windows working if href.startswith("file://"): fd = urllib.request.urlopen(f"file:{href[7:]}") # Relative path to parquet part should be relative from the votable elif href.startswith("file:"): parquet = os.path.join( os.path.dirname(config["filename"]), href[5:] ) fd = urllib.request.urlopen(f"file:{parquet}") if encoding is not None: if encoding == "gzip": fd = gzip.GzipFile(href, "r", fileobj=fd) elif encoding == "base64": fd = codecs.EncodedFile(fd, "base64") else: vo_raise( NotImplementedError, f"Unknown encoding type '{encoding}'", self._config, self._pos, ) array = Table.read(fd, format="parquet") finally: if hasattr(fd, "close"): fd.close() if array.dtype != self.array.dtype: warn_or_raise(W56, W56, (), self._config, self._pos) return array def to_xml(self, w, **kwargs): specified_format = kwargs.get("tabledata_format") if specified_format is not None: format = specified_format else: format = self.format if format == "fits": format = "tabledata" with w.tag( "TABLE", attrib=w.object_attrs(self, ("ID", "name", "ref", "ucd", "utype", "nrows")), ): if self.description is not None: w.element("DESCRIPTION", self.description, wrap=True) for element_set in (self.fields, self.params): for element in element_set: element._setup({}, None) if self.ref is None: for element_set in (self.fields, self.params, self.groups, self.links): for element in element_set: element.to_xml(w, **kwargs) elif kwargs["version_1_2_or_later"]: index = list(self._votable.iter_tables()).index(self) group = Group(self, ID=f"_g{index}") group.to_xml(w, **kwargs) if len(self.array): with w.tag("DATA"): if format == "tabledata": self._write_tabledata(w, **kwargs) elif format == "binary": self._write_binary(1, w, **kwargs) elif format == "binary2": self._write_binary(2, w, **kwargs) if kwargs["version_1_2_or_later"]: for element in self._infos: element.to_xml(w, **kwargs) def _write_tabledata(self, w, **kwargs): fields = self.fields array = self.array with w.tag("TABLEDATA"): w._flush() if _has_c_tabledata_writer and not kwargs.get("_debug_python_based_parser"): supports_empty_values = [ field.converter.supports_empty_values(kwargs) for field in fields ] fields = [field.converter.output for field in fields] indent = len(w._tags) - 1 tablewriter.write_tabledata( w.write, array.data, array.mask, fields, supports_empty_values, indent, 1 << 8, ) else: write = w.write indent_spaces = w.get_indentation_spaces() tr_start = indent_spaces + "<TR>\n" tr_end = indent_spaces + "</TR>\n" td = indent_spaces + " <TD>{}</TD>\n" td_empty = indent_spaces + " <TD/>\n" fields = [ ( i, field.converter.output, field.converter.supports_empty_values(kwargs), ) for i, field in enumerate(fields) ] for row in range(len(array)): write(tr_start) array_row = array.data[row] mask_row = array.mask[row] for i, output, supports_empty_values in fields: data = array_row[i] masked = mask_row[i] if supports_empty_values and np.all(masked): write(td_empty) else: try: val = output(data, masked) except Exception as e: vo_reraise( e, additional=( f"(in row {row:d}, col '{self.fields[i].ID}')" ), ) if len(val): write(td.format(val)) else: write(td_empty) write(tr_end) def _write_binary(self, mode, w, **kwargs): fields = self.fields array = self.array if mode == 1: tag_name = "BINARY" else: tag_name = "BINARY2" with w.tag(tag_name): with w.tag("STREAM", encoding="base64"): fields_basic = [ (i, field.converter.binoutput) for (i, field) in enumerate(fields) ] data = io.BytesIO() for row in range(len(array)): array_row = array.data[row] array_mask = array.mask[row] if mode == 2: flattened = np.array([np.all(x) for x in array_mask]) data.write(converters.bool_to_bitarray(flattened)) for i, converter in fields_basic: try: # BINARY2 cannot handle individual array element masks converter_type = converter.__self__.__class__ # Delegate converter to handle the mask delegate_condition = issubclass( converter_type, converters.Array ) if mode == 1 or delegate_condition: chunk = converter(array_row[i], array_mask[i]) else: # Mask is already handled by BINARY2 behaviour chunk = converter(array_row[i], None) assert type(chunk) == bytes except Exception as e: vo_reraise( e, additional=f"(in row {row:d}, col '{fields[i].ID}')" ) data.write(chunk) w._flush() w.write(base64.b64encode(data.getvalue()).decode("ascii")) def to_table(self, use_names_over_ids=False): """ Convert this VO Table to an `astropy.table.Table` instance. Parameters ---------- use_names_over_ids : bool, optional When `True` use the ``name`` attributes of columns as the names of columns in the `astropy.table.Table` instance. Since names are not guaranteed to be unique, this may cause some columns to be renamed by appending numbers to the end. Otherwise (default), use the ID attributes as the column names. .. warning:: Variable-length array fields may not be restored identically when round-tripping through the `astropy.table.Table` instance. """ from astropy.table import Table meta = {} for key in ["ID", "name", "ref", "ucd", "utype", "description"]: val = getattr(self, key, None) if val is not None: meta[key] = val if use_names_over_ids: names = [field.name for field in self.fields] unique_names = [] for i, name in enumerate(names): new_name = name i = 2 while new_name in unique_names: new_name = f"{name}{i}" i += 1 unique_names.append(new_name) names = unique_names else: names = [field.ID for field in self.fields] table = Table(self.array, names=names, meta=meta) for name, field in zip(names, self.fields): column = table[name] field.to_table_column(column) return table @classmethod def from_table(cls, votable, table): """ Create a `TableElement` instance from a given `astropy.table.Table` instance. """ kwargs = {} for key in ["ID", "name", "ref", "ucd", "utype"]: val = table.meta.get(key) if val is not None: kwargs[key] = val new_table = cls(votable, **kwargs) if "description" in table.meta: new_table.description = table.meta["description"] for colname in table.colnames: column = table[colname] new_table.add_field(Field.from_table_column(votable, column)) if table.mask is None: new_table.array = ma.array(np.asarray(table)) else: new_table.array = ma.array(np.asarray(table), mask=np.asarray(table.mask)) return new_table def iter_fields_and_params(self): """ Recursively iterate over all FIELD and PARAM elements in the TABLE. """ yield from self.params yield from self.all_fields for group in self.groups: yield from group.iter_fields_and_params() get_field_by_id = _lookup_by_attr_factory( "ID", True, "iter_fields_and_params", "FIELD or PARAM", """ Looks up a FIELD or PARAM element by the given ID. """, ) get_field_by_id_or_name = _lookup_by_id_or_name_factory( "iter_fields_and_params", "FIELD or PARAM", """ Looks up a FIELD or PARAM element by the given ID or name. """, ) get_fields_by_utype = _lookup_by_attr_factory( "utype", False, "iter_fields_and_params", "FIELD or PARAM", """ Looks up a FIELD or PARAM element by the given utype and returns an iterator emitting all matches. """, ) def iter_groups(self): """ Recursively iterate over all GROUP elements in the TABLE. """ for group in self.groups: yield group yield from group.iter_groups() get_group_by_id = _lookup_by_attr_factory( "ID", True, "iter_groups", "GROUP", """ Looks up a GROUP element by the given ID. Used by the group's "ref" attribute """, ) get_groups_by_utype = _lookup_by_attr_factory( "utype", False, "iter_groups", "GROUP", """ Looks up a GROUP element by the given utype and returns an iterator emitting all matches. """, ) def iter_info(self): yield from self.infos
TableElement
python
huggingface__transformers
src/transformers/models/pop2piano/modeling_pop2piano.py
{ "start": 3497, "end": 4462 }
class ____(nn.Module): def __init__(self, config: Pop2PianoConfig): super().__init__() self.wi = nn.Linear(config.d_model, config.d_ff, bias=False) self.wo = nn.Linear(config.d_ff, config.d_model, bias=False) self.dropout = nn.Dropout(config.dropout_rate) self.act = ACT2FN[config.dense_act_fn] def forward(self, hidden_states): hidden_states = self.wi(hidden_states) hidden_states = self.act(hidden_states) hidden_states = self.dropout(hidden_states) if ( isinstance(self.wo.weight, torch.Tensor) and hidden_states.dtype != self.wo.weight.dtype and self.wo.weight.dtype != torch.int8 ): hidden_states = hidden_states.to(self.wo.weight.dtype) hidden_states = self.wo(hidden_states) return hidden_states # Copied from transformers.models.t5.modeling_t5.T5DenseGatedActDense with T5->Pop2Piano
Pop2PianoDenseActDense
python
pypa__virtualenv
src/virtualenv/app_data/via_disk_folder.py
{ "start": 1292, "end": 3378 }
class ____(AppData): """Store the application data on the disk within a folder layout.""" transient = False can_update = True def __init__(self, folder) -> None: self.lock = ReentrantFileLock(folder) def __repr__(self) -> str: return f"{type(self).__name__}({self.lock.path})" def __str__(self) -> str: return str(self.lock.path) def reset(self): LOGGER.debug("reset app data folder %s", self.lock.path) safe_delete(self.lock.path) def close(self): """Do nothing.""" @contextmanager def locked(self, path): path_lock = self.lock / path with path_lock: yield path_lock.path @contextmanager def extract(self, path, to_folder): root = ReentrantFileLock(to_folder()) if to_folder is not None else self.lock / "unzip" / __version__ with root.lock_for_key(path.name): dest = root.path / path.name if not dest.exists(): extract(path, dest) yield dest @property def py_info_at(self): return self.lock / "py_info" / "2" def py_info(self, path): return PyInfoStoreDisk(self.py_info_at, path) def py_info_clear(self): """clear py info.""" py_info_folder = self.py_info_at with py_info_folder: for filename in py_info_folder.path.iterdir(): if filename.suffix == ".json": with py_info_folder.lock_for_key(filename.stem): if filename.exists(): filename.unlink() def embed_update_log(self, distribution, for_py_version): return EmbedDistributionUpdateStoreDisk(self.lock / "wheel" / for_py_version / "embed" / "3", distribution) @property def house(self): path = self.lock.path / "wheel" / "house" path.mkdir(parents=True, exist_ok=True) return path def wheel_image(self, for_py_version, name): return self.lock.path / "wheel" / for_py_version / "image" / "1" / name
AppDataDiskFolder
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B024.py
{ "start": 2049, "end": 2172 }
class ____(metaclass=abc.ABC): # incorrect but outside scope of this check def method(self): foo()
keyword_abc_2
python
huggingface__transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
{ "start": 58881, "end": 64497 }
class ____(PreTrainedModel): config: SeamlessM4TConfig base_model_prefix = "seamless_m4t" supports_gradient_checkpointing = True _no_split_modules = ["SeamlessM4TEncoderLayer", "SeamlessM4TDecoderLayer", "SeamlessM4TConformerEncoderLayer"] @torch.no_grad() def _init_weights(self, module: nn.Module): """Initialize the weights""" std = self.config.initializer_range if isinstance(module, nn.Linear): init.normal_(module.weight, mean=0.0, std=std) if module.bias is not None: init.zeros_(module.bias) elif isinstance(module, nn.Embedding): init.normal_(module.weight, mean=0.0, std=std) # Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False): init.zeros_(module.weight[module.padding_idx]) elif isinstance(module, SeamlessM4TConformerSelfAttention): if hasattr(module, "pos_bias_u"): init.xavier_uniform_(module.pos_bias_u) if hasattr(module, "pos_bias_v"): init.xavier_uniform_(module.pos_bias_v) elif isinstance(module, SeamlessM4TConformerPositionalConvEmbedding): init.normal_( module.conv.weight, mean=0, std=2 * math.sqrt(1 / (module.conv.kernel_size[0] * module.conv.in_channels)), ) init.constant_(module.conv.bias, 0) elif isinstance(module, SeamlessM4TConformerFeatureProjection): k = math.sqrt(1 / module.projection.in_features) init.uniform_(module.projection.weight, a=-k, b=k) init.uniform_(module.projection.bias, a=-k, b=k) elif isinstance(module, (nn.LayerNorm, nn.BatchNorm1d)): init.zeros_(module.bias) init.ones_(module.weight) elif isinstance(module, nn.Conv1d): init.kaiming_normal_(module.weight) if module.bias is not None: k = math.sqrt(module.groups / (module.in_channels * module.kernel_size[0])) init.uniform_(module.bias, a=-k, b=k) def _compute_sub_sample_lengths_from_attention_mask(self, attention_mask): kernel_size, stride = self.config.adaptor_kernel_size, self.config.adaptor_stride pad = kernel_size // 2 seq_lens = attention_mask.size(1) - (1 - attention_mask.int()).sum(1) seq_lens = ((seq_lens + 2 * pad - kernel_size) / stride) + 1 return seq_lens.floor() def compute_last_hidden_states_per_sample( self, hidden_states: tuple[tuple[torch.Tensor]], beam_indices: Optional[torch.Tensor] = None, ) -> torch.Tensor: """ Computes the last hidden states. Parameters: hidden_states (`tuple[tuple[torch.Tensor]]`): The generated hidden states. Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of torch.FloatTensor of shape (batch_size*num_beams*num_return_sequences, generated_length, hidden_size). beam_indices (`torch.LongTensor`, *optional*): Beam indices of generated token id at each generation step. `torch.LongTensor` of shape `(batch_size*num_return_sequences, sequence_length)`. Only required if a `num_beams>1` at generate-time. Return: `torch.Tensor`: A `torch.Tensor` of shape `(batch_size*num_return_sequences, sequence_length, hidden_size)` containing the last hidden states. ```""" # 1. First, let's compute last_hidden_states from hidden_states. # For each generation step, takes the hidden state from the last layer. # shape: (batch_size*vocab_size*num_return_sequences, # generation_steps, hidden_dim) last_hidden_states = torch.concat([hidden_states[-1] for hidden_states in hidden_states], dim=1) # 2. In absence of `beam_indices`, we can assume that we come from e.g. greedy search, which is equivalent # to a beam search approach were the first (and only) beam is always selected # in that case, return directly last_hidden_states if beam_indices is None: return last_hidden_states # 3. cut beam_indices to longest beam length beam_indices_mask = beam_indices < 0 max_beam_length = (1 - beam_indices_mask.long()).sum(-1).max() beam_indices = beam_indices.clone()[:, :max_beam_length] beam_indices_mask = beam_indices_mask[:, :max_beam_length] # 4. Set indices of beams that finished early to 0; such indices will be masked correctly afterwards anyways beam_indices[beam_indices_mask] = 0 # 5. expand beam_indices to last_hidden_states dim beam_indices = beam_indices.unsqueeze(-1) beam_indices = beam_indices.expand(-1, -1, last_hidden_states.shape[-1]) # 6. select the right candidate for each beam # in other words, new_last_hidden_states[i,j,k] = last_hidden_states[beam_indices[i,j,k], j, k] for all i, j, k last_hidden_states = torch.gather(last_hidden_states, 0, beam_indices) return last_hidden_states @auto_docstring( custom_intro=""" Transformer speech encoder consisting of *config.speech_encoder_layers* conformer self attention layers. Each layer is a [`SeamlessM4TConformerEncoderLayer`]. """ )
SeamlessM4TPreTrainedModel
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 1874, "end": 2034 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("ALL", "LATEST")
CheckRunType
python
pexpect__pexpect
tests/test_destructor.py
{ "start": 1061, "end": 3176 }
class ____(PexpectTestCase.PexpectTestCase): def test_destructor (self): if platform.python_implementation() != 'CPython': # Details of garbage collection are different on other implementations return 'SKIP' gc.collect() time.sleep(3) p1 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) p2 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) p3 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) p4 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) fd_t1 = (p1.child_fd,p2.child_fd,p3.child_fd,p4.child_fd) p1.expect(pexpect.EOF) p2.expect(pexpect.EOF) p3.expect(pexpect.EOF) p4.expect(pexpect.EOF) p1.kill(9) p2.kill(9) p3.kill(9) p4.kill(9) p1 = None p2 = None p3 = None p4 = None gc.collect() time.sleep(3) # Some platforms are slow at gc... Solaris! p1 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) p2 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) p3 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) p4 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) fd_t2 = (p1.child_fd,p2.child_fd,p3.child_fd,p4.child_fd) p1.kill(9) p2.kill(9) p3.kill(9) p4.kill(9) del (p1) del (p2) del (p3) del (p4) gc.collect() time.sleep(3) p1 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) p2 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) p3 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) p4 = pexpect.spawn('%s hello_world.py' % self.PYTHONBIN) fd_t3 = (p1.child_fd,p2.child_fd,p3.child_fd,p4.child_fd) assert (fd_t1 == fd_t2 == fd_t3), "pty file descriptors not properly garbage collected (fd_t1,fd_t2,fd_t3)=(%s,%s,%s)" % (str(fd_t1),str(fd_t2),str(fd_t3)) if __name__ == '__main__': unittest.main() suite = unittest.TestLoader().loadTestsFromTestCase(TestCaseDestructor)
TestCaseDestructor
python
kamyu104__LeetCode-Solutions
Python/divide-chocolate.py
{ "start": 33, "end": 722 }
class ____(object): def maximizeSweetness(self, sweetness, K): """ :type sweetness: List[int] :type K: int :rtype: int """ def check(sweetness, K, x): curr, cuts = 0, 0 for s in sweetness: curr += s if curr >= x: cuts += 1 curr = 0 return cuts >= K+1 left, right = min(sweetness), sum(sweetness)//(K+1) while left <= right: mid = left + (right-left)//2 if not check(sweetness, K, mid): right = mid-1 else: left = mid+1 return right
Solution
python
ray-project__ray
release/k8s_tests/run_gcs_ft_on_k8s.py
{ "start": 328, "end": 12275 }
class ____(enum.Enum): KILL_WORKER_NODE = "kill_worker_node" KILL_HEAD_NODE = "kill_head_node" if os.environ.get("RAY_IMAGE") is not None: ray_image = os.environ.get("RAY_IMAGE") elif ray.__version__ != "3.0.0.dev0": ray_image = f"rayproject/ray:{ray.__version__}" elif ray.__commit__ == "{{RAY_COMMIT_SHA}}": ray_image = "rayproject/ray:nightly" else: ray_image = f"rayproject/ray:{ray.__commit__[:6]}" config.load_kube_config() cli = client.CoreV1Api() yaml_path = pathlib.Path("/tmp/ray_v1alpha1_rayservice.yaml") def generate_cluster_variable(): global CLUSTER_ID global RAY_CLUSTER_NAME global RAY_SERVICE_NAME global LOCUST_ID CLUSTER_ID = str(uuid.uuid4()).split("-")[0] RAY_CLUSTER_NAME = "cluster-" + CLUSTER_ID RAY_SERVICE_NAME = "service-" + CLUSTER_ID LOCUST_ID = "ray-locust-" + CLUSTER_ID def check_kuberay_installed(): # Make sure the ray namespace exists KUBERAY_VERSION = "v1.5.1" uri = ( "github.com/ray-project/kuberay/manifests" f"/base?ref={KUBERAY_VERSION}&timeout=90s" ) print( subprocess.check_output( [ "kubectl", "apply", "-k", uri, ] ).decode() ) pods = subprocess.check_output( ["kubectl", "get", "pods", "--namespace", "ray-system", "--no-headers"] ).decode() assert pods.split("\n") != 0 def start_rayservice(): # step-1: generate the yaml file print(f"Using ray image: {ray_image}") solution = "\n".join( [ f" {line}" for line in pathlib.Path("./solution.py").read_text().splitlines() ] ) locustfile = "\n".join( [ f" {line}" for line in pathlib.Path("./locustfile.py").read_text().splitlines() ] ) template = ( pathlib.Path("ray_v1alpha1_rayservice_template.yaml") .read_text() .format( cluster_id=CLUSTER_ID, ray_image=ray_image, solution=solution, locustfile=locustfile, ) ) print("=== YamlFile ===") print(template) tmp_yaml = pathlib.Path("/tmp/ray_v1alpha1_rayservice.yaml") tmp_yaml.write_text(template) print("=== Get Pods from ray-system ===") print( subprocess.check_output( ["kubectl", "get", "pods", "--namespace", "ray-system", "--no-headers"] ).decode() ) # step-2: create the cluter print(f"Creating cluster with id: {CLUSTER_ID}") print(subprocess.check_output(["kubectl", "create", "-f", str(tmp_yaml)]).decode()) # step-3: make sure the ray cluster is up w = watch.Watch() start_time = time.time() head_pod_name = None for event in w.stream( func=cli.list_namespaced_pod, namespace="default", label_selector=f"rayCluster={RAY_CLUSTER_NAME},ray.io/node-type=head", timeout_seconds=60, ): if event["object"].status.phase == "Running": assert event["object"].kind == "Pod" head_pod_name = event["object"].metadata.name end_time = time.time() print(f"{CLUSTER_ID} started in {end_time-start_time} sec") print(f"head pod {head_pod_name}") break assert head_pod_name is not None # step-4: e2e check it's alive cmd = """ import requests print(requests.get('http://localhost:8000/?val=123').text) """ while True: try: resp = ( subprocess.check_output( f'kubectl exec {head_pod_name} -- python -c "{cmd}"', shell=True ) .decode() .strip() ) if resp == "375": print("Service is up now!") break else: print(f"Failed with msg {resp}") except Exception as e: print("Error", e) time.sleep(2) def start_port_forward(): proc = None proc = subprocess.Popen( [ "kubectl", "port-forward", f"svc/{RAY_SERVICE_NAME}-serve-svc", "8000:8000", "--address=0.0.0.0", ] ) while True: try: resp = requests.get( "http://localhost:8000/", timeout=1, params={ "val": 10, }, ) if resp.status_code == 200: print("The ray service is ready!!!") break except requests.exceptions.Timeout: pass except requests.exceptions.ConnectionError: pass print("Waiting for the proxy to be alive") time.sleep(1) return proc def warmup_cluster(num_reqs): for _ in range(num_reqs): resp = requests.get( "http://localhost:8000/", timeout=1, params={ "val": 10, }, ) assert resp.status_code == 200 def start_sending_traffics(duration, users): print("=== Install locust by helm ===") yaml_config = ( pathlib.Path("locust-run.yaml") .read_text() .format(users=users, cluster_id=CLUSTER_ID, duration=int(duration)) ) print("=== Locust YAML ===") print(yaml_config) pathlib.Path("/tmp/locust-run-config.yaml").write_text(yaml_config) helm_install_logs = subprocess.check_output( [ "helm", "install", LOCUST_ID, "deliveryhero/locust", "-f", "/tmp/locust-run-config.yaml", ] ) print(helm_install_logs) timeout_wait_for_locust_s = 300 while timeout_wait_for_locust_s > 0: labels = [ f"app.kubernetes.io/instance=ray-locust-{CLUSTER_ID}", "app.kubernetes.io/name=locust,component=master", ] pods = cli.list_namespaced_pod("default", label_selector=",".join(labels)) assert len(pods.items) == 1 if pods.items[0].status.phase == "Pending": print("Waiting for the locust pod to be ready...") time.sleep(30) timeout_wait_for_locust_s -= 30 else: break proc = subprocess.Popen( [ "kubectl", "port-forward", f"svc/ray-locust-{CLUSTER_ID}", "8080:8089", "--address=0.0.0.0", ] ) return proc def dump_pods_actors(pod_name): print( subprocess.run( f"kubectl exec {pod_name} -- ps -ef | grep ::", shell=True, capture_output=True, ).stdout.decode() ) def kill_head(): pods = cli.list_namespaced_pod( "default", label_selector=f"rayCluster={RAY_CLUSTER_NAME},ray.io/node-type=head", ) if pods.items[0].status.phase == "Running": print(f"Killing header {pods.items[0].metadata.name}") dump_pods_actors(pods.items[0].metadata.name) cli.delete_namespaced_pod(pods.items[0].metadata.name, "default") def kill_worker(): pods = cli.list_namespaced_pod( "default", label_selector=f"rayCluster={RAY_CLUSTER_NAME},ray.io/node-type=worker", ) alive_pods = [ (p.status.start_time, p.metadata.name) for p in pods.items if p.status.phase == "Running" ] # sorted(alive_pods) # We kill the oldest nodes for now given the memory leak in serve. # to_be_killed = alive_pods[-1][1] to_be_killed = random.choice(alive_pods)[1] print(f"Killing worker {to_be_killed}") dump_pods_actors(pods.items[0].metadata.name) cli.delete_namespaced_pod(to_be_killed, "default") def start_killing_nodes(duration, kill_interval, kill_node_type): """Kill the nodes in ray cluster. duration: How long does we run the test (seconds) kill_interval: The interval between two kills (seconds) kill_head_every_n: For every n kills, we kill a head node kill_node_type: kill either worker node or head node """ for kill_idx in range(1, int(duration / kill_interval)): while True: try: # kill if kill_node_type == TestScenario.KILL_HEAD_NODE: kill_head() elif kill_node_type == TestScenario.KILL_WORKER_NODE: kill_worker() break except Exception as e: from time import sleep print(f"Fail to kill node, retry in 5 seconds: {e}") sleep(5) time.sleep(kill_interval) def get_stats(): labels = [ f"app.kubernetes.io/instance=ray-locust-{CLUSTER_ID}", "app.kubernetes.io/name=locust,component=master", ] pods = cli.list_namespaced_pod("default", label_selector=",".join(labels)) assert len(pods.items) == 1 pod_name = pods.items[0].metadata.name subprocess.check_output( [ "kubectl", "cp", f"{pod_name}:/home/locust/test_result_{CLUSTER_ID}_stats_history.csv", "./stats_history.csv", ] ) data = [] with open("stats_history.csv") as f: import csv reader = csv.reader(f) for d in reader: data.append(d) # The first 5mins is for warming up offset = 300 start_time = int(data[offset][0]) end_time = int(data[-1][0]) # 17 is the index for total requests # 18 is the index for total failed requests total = float(data[-1][17]) - float(data[offset][17]) failures = float(data[-1][18]) - float(data[offset][18]) # Available, through put return (total - failures) / total, total / (end_time - start_time), data def main(): result = { TestScenario.KILL_WORKER_NODE.value: {"rate": None}, TestScenario.KILL_HEAD_NODE.value: {"rate": None}, } expected_result = { TestScenario.KILL_HEAD_NODE: 0.99, TestScenario.KILL_HEAD_NODE: 0.99, } check_kuberay_installed() users = 60 exception = None for kill_node_type, kill_interval, test_duration in [ (TestScenario.KILL_WORKER_NODE, 60, 600), (TestScenario.KILL_HEAD_NODE, 300, 1200), ]: try: generate_cluster_variable() procs = [] start_rayservice() procs.append(start_port_forward()) warmup_cluster(200) procs.append(start_sending_traffics(test_duration * 1.1, users)) start_killing_nodes(test_duration, kill_interval, kill_node_type) rate, qps, data = get_stats() print("Raw Data", data, qps) result[kill_node_type.value]["rate"] = rate assert expected_result[kill_node_type] <= rate assert qps > users * 10 * 0.8 except Exception as e: print(f"{kill_node_type} HA test failed, {e}") exception = e finally: print("=== Cleanup ===") subprocess.run( ["kubectl", "delete", "-f", str(yaml_path)], capture_output=True, ) subprocess.run( ["helm", "uninstall", LOCUST_ID], capture_output=True, ) for p in procs: p.kill() print("==== Cleanup done ===") if exception: raise exception print("Result:", result) test_output_json_path = os.environ.get( "TEST_OUTPUT_JSON", "/tmp/release_test_output.json" ) with open(test_output_json_path, "wt") as f: json.dump(result, f) if __name__ == "__main__": try: # Connect to ray so that the auto suspense # will not start. ray.init("auto") except Exception: # It doesnt' matter if it failed. pass main()
TestScenario
python
mlflow__mlflow
mlflow/store/tracking/dbmodels/models.py
{ "start": 2230, "end": 4452 }
class ____(Base): """ DB model for :py:class:`mlflow.entities.Experiment`. These are recorded in ``experiment`` table. """ __tablename__ = "experiments" experiment_id = Column(Integer, autoincrement=True) """ Experiment ID: `Integer`. *Primary Key* for ``experiment`` table. """ name = Column(String(256), unique=True, nullable=False) """ Experiment name: `String` (limit 256 characters). Defined as *Unique* and *Non null* in table schema. """ artifact_location = Column(String(256), nullable=True) """ Default artifact location for this experiment: `String` (limit 256 characters). Defined as *Non null* in table schema. """ lifecycle_stage = Column(String(32), default=LifecycleStage.ACTIVE) """ Lifecycle Stage of experiment: `String` (limit 32 characters). Can be either ``active`` (default) or ``deleted``. """ creation_time = Column(BigInteger(), default=get_current_time_millis) """ Creation time of experiment: `BigInteger`. """ last_update_time = Column(BigInteger(), default=get_current_time_millis) """ Last Update time of experiment: `BigInteger`. """ __table_args__ = ( CheckConstraint( lifecycle_stage.in_(LifecycleStage.view_type_to_stages(ViewType.ALL)), name="experiments_lifecycle_stage", ), PrimaryKeyConstraint("experiment_id", name="experiment_pk"), ) def __repr__(self): return f"<SqlExperiment ({self.experiment_id}, {self.name})>" def to_mlflow_entity(self): """ Convert DB model to corresponding MLflow entity. Returns: :py:class:`mlflow.entities.Experiment`. """ return Experiment( experiment_id=str(self.experiment_id), name=self.name, artifact_location=self.artifact_location, lifecycle_stage=self.lifecycle_stage, tags=[t.to_mlflow_entity() for t in self.tags], creation_time=self.creation_time, last_update_time=self.last_update_time, )
SqlExperiment
python
ansible__ansible
lib/ansible/modules/group.py
{ "start": 9661, "end": 10654 }
class ____(Group): """ This is a SunOS Group manipulation class. Solaris doesn't have the 'system' group concept. This overrides the following methods from the generic class:- - group_add() """ platform = 'SunOS' distribution = None GROUPFILE = '/etc/group' def group_add(self, **kwargs): cmd = [self.module.get_bin_path('groupadd', True)] for key in kwargs: if key == 'gid' and kwargs[key] is not None: cmd.append('-g') cmd.append(str(kwargs[key])) if self.non_unique: cmd.append('-o') if self.gid_min is not None: cmd.append('-K') cmd.append('GID_MIN=' + str(self.gid_min)) if self.gid_max is not None: cmd.append('-K') cmd.append('GID_MAX=' + str(self.gid_max)) cmd.append(self.name) return self.execute_command(cmd) # ===========================================
SunOS
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/enums.py
{ "start": 4534, "end": 4687 }
class ____(MemberType): @property def name(self): """inherited""" return super().name # type: ignore[misc]
_NamePropertyInDataType
python
pytorch__pytorch
torch/_inductor/codegen/rocm/rocm_template.py
{ "start": 722, "end": 765 }
class ____: name: str ty: str
ArgInfo
python
redis__redis-py
tests/test_asyncio/test_encoding.py
{ "start": 3368, "end": 3693 }
class ____: @pytest_asyncio.fixture() async def r(self, create_redis): redis = await create_redis(encoding="utf-16") yield redis await redis.flushall() @pytest.mark.xfail async def test_basic_command(self, r: redis.Redis): await r.set("hello", "world")
TestCommandsAreNotEncoded
python
coleifer__peewee
playhouse/sqlite_ext.py
{ "start": 11578, "end": 11875 }
class ____(Model): class Meta: arguments = None extension_module = None prefix_arguments = None primary_key = False schema_manager_class = VirtualTableSchemaManager @classmethod def clean_options(cls, options): return options
VirtualModel
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 32735, "end": 33270 }
class ____(Stmt): """An overlay scope for extensions. This is a largely unoptimized scope that however can be used to introduce completely arbitrary variables into a sub scope from a dictionary or dictionary like object. The `context` field has to evaluate to a dictionary object. Example usage:: OverlayScope(context=self.call_method('get_context'), body=[...]) .. versionadded:: 2.10 """ fields = ("context", "body") context: Expr body: list[Node]
OverlayScope
python
numba__numba
numba/tests/test_findlib.py
{ "start": 84, "end": 324 }
class ____(TestCase): def test_find_file_nonexistent_path(self): candidates = findlib.find_file('libirrelevant.so', 'NONEXISTENT') self.assertEqual(candidates, []) if __name__ == '__main__': unittest.main()
TestFindlib
python
django__django
django/contrib/auth/hashers.py
{ "start": 19378, "end": 19957 }
class ____(BCryptSHA256PasswordHasher): """ Secure password hashing using the bcrypt algorithm This is considered by many to be the most secure algorithm but you must first install the bcrypt library. Please be warned that this library depends on native C code and might cause portability issues. This hasher does not first hash the password which means it is subject to bcrypt's 72 bytes password truncation. Most use cases should prefer the BCryptSHA256PasswordHasher. """ algorithm = "bcrypt" digest = None
BCryptPasswordHasher
python
pytorch__pytorch
torch/ao/nn/quantized/modules/batchnorm.py
{ "start": 121, "end": 1769 }
class ____(torch.nn.modules.batchnorm._BatchNorm): def __init__( self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None ) -> None: factory_kwargs = {"device": device, "dtype": dtype} super().__init__(num_features, eps, momentum, True, True, **factory_kwargs) # pyrefly: ignore [bad-argument-type] self.register_buffer("scale", torch.tensor(1.0, **factory_kwargs)) # pyrefly: ignore [bad-argument-type] self.register_buffer("zero_point", torch.tensor(0, **factory_kwargs)) @staticmethod def from_float(cls, mod, use_precomputed_fake_quant=False): activation_post_process = mod.activation_post_process if type(mod) is cls._NNI_BN_RELU_MODULE: mod = mod[0] scale, zero_point = activation_post_process.calculate_qparams() new_mod = cls(mod.num_features, mod.eps) new_mod.weight = mod.weight new_mod.bias = mod.bias new_mod.running_mean = mod.running_mean new_mod.running_var = mod.running_var new_mod.scale = scale new_mod.zero_point = zero_point return new_mod @classmethod def from_reference(cls, bn, output_scale, output_zero_point): qbn = cls( bn.num_features, bn.eps, bn.momentum, device=bn.weight.device, dtype=bn.weight.dtype, ) qbn.weight = bn.weight qbn.bias = bn.bias qbn.running_mean = bn.running_mean qbn.running_var = bn.running_var qbn.scale = output_scale qbn.zero_point = output_zero_point return qbn
_BatchNorm
python
fsspec__filesystem_spec
fsspec/callbacks.py
{ "start": 30, "end": 5697 }
class ____: """ Base class and interface for callback mechanism This class can be used directly for monitoring file transfers by providing ``callback=Callback(hooks=...)`` (see the ``hooks`` argument, below), or subclassed for more specialised behaviour. Parameters ---------- size: int (optional) Nominal quantity for the value that corresponds to a complete transfer, e.g., total number of tiles or total number of bytes value: int (0) Starting internal counter value hooks: dict or None A dict of named functions to be called on each update. The signature of these must be ``f(size, value, **kwargs)`` """ def __init__(self, size=None, value=0, hooks=None, **kwargs): self.size = size self.value = value self.hooks = hooks or {} self.kw = kwargs def __enter__(self): return self def __exit__(self, *exc_args): self.close() def close(self): """Close callback.""" def branched(self, path_1, path_2, **kwargs): """ Return callback for child transfers If this callback is operating at a higher level, e.g., put, which may trigger transfers that can also be monitored. The function returns a callback that has to be passed to the child method, e.g., put_file, as `callback=` argument. The implementation uses `callback.branch` for compatibility. When implementing callbacks, it is recommended to override this function instead of `branch` and avoid calling `super().branched(...)`. Prefer using this function over `branch`. Parameters ---------- path_1: str Child's source path path_2: str Child's destination path **kwargs: Arbitrary keyword arguments Returns ------- callback: Callback A callback instance to be passed to the child method """ self.branch(path_1, path_2, kwargs) # mutate kwargs so that we can force the caller to pass "callback=" explicitly return kwargs.pop("callback", DEFAULT_CALLBACK) def branch_coro(self, fn): """ Wraps a coroutine, and pass a new child callback to it. """ @wraps(fn) async def func(path1, path2: str, **kwargs): with self.branched(path1, path2, **kwargs) as child: return await fn(path1, path2, callback=child, **kwargs) return func def set_size(self, size): """ Set the internal maximum size attribute Usually called if not initially set at instantiation. Note that this triggers a ``call()``. Parameters ---------- size: int """ self.size = size self.call() def absolute_update(self, value): """ Set the internal value state Triggers ``call()`` Parameters ---------- value: int """ self.value = value self.call() def relative_update(self, inc=1): """ Delta increment the internal counter Triggers ``call()`` Parameters ---------- inc: int """ self.value += inc self.call() def call(self, hook_name=None, **kwargs): """ Execute hook(s) with current state Each function is passed the internal size and current value Parameters ---------- hook_name: str or None If given, execute on this hook kwargs: passed on to (all) hook(s) """ if not self.hooks: return kw = self.kw.copy() kw.update(kwargs) if hook_name: if hook_name not in self.hooks: return return self.hooks[hook_name](self.size, self.value, **kw) for hook in self.hooks.values() or []: hook(self.size, self.value, **kw) def wrap(self, iterable): """ Wrap an iterable to call ``relative_update`` on each iterations Parameters ---------- iterable: Iterable The iterable that is being wrapped """ for item in iterable: self.relative_update() yield item def branch(self, path_1, path_2, kwargs): """ Set callbacks for child transfers If this callback is operating at a higher level, e.g., put, which may trigger transfers that can also be monitored. The passed kwargs are to be *mutated* to add ``callback=``, if this class supports branching to children. Parameters ---------- path_1: str Child's source path path_2: str Child's destination path kwargs: dict arguments passed to child method, e.g., put_file. Returns ------- """ return None def no_op(self, *_, **__): pass def __getattr__(self, item): """ If undefined methods are called on this class, nothing happens """ return self.no_op @classmethod def as_callback(cls, maybe_callback=None): """Transform callback=... into Callback instance For the special value of ``None``, return the global instance of ``NoOpCallback``. This is an alternative to including ``callback=DEFAULT_CALLBACK`` directly in a method signature. """ if maybe_callback is None: return DEFAULT_CALLBACK return maybe_callback
Callback
python
PrefectHQ__prefect
tests/deployment/test_steps.py
{ "start": 39916, "end": 44233 }
class ____: async def test_run_shell_script_single_command(self, capsys): result = await run_shell_script("echo Hello World", stream_output=True) assert result["stdout"] == "Hello World" assert result["stderr"] == "" # Validate the output was streamed to the console out, err = capsys.readouterr() assert out.strip() == "Hello World" assert err == "" async def test_run_shell_script_multiple_commands(self, capsys): script = """ echo First Line echo Second Line """ result = await run_shell_script(script, stream_output=True) assert result["stdout"] == "First Line\nSecond Line" assert result["stderr"] == "" # Validate the output was streamed to the console out, err = capsys.readouterr() assert out.strip() == "First Line\nSecond Line" assert err == "" @pytest.mark.skipif( sys.platform == "win32", reason="stderr redirect does not work on Windows" ) async def test_run_shell_script_stderr(self, capsys): script = "bash -c '>&2 echo Error Message'" result = await run_shell_script(script, stream_output=True) assert result["stdout"] == "" assert result["stderr"] == "Error Message" # Validate the error was streamed to the console out, err = capsys.readouterr() assert out == "" assert err.strip() == "Error Message" @pytest.mark.parametrize( "script,expected", [ ("bash -c 'echo $TEST_ENV_VAR'", "Test Value"), ("echo $TEST_ENV_VAR", "$TEST_ENV_VAR"), ], ) async def test_run_shell_script_with_env(self, script, expected, capsys): result = await run_shell_script( script, env={"TEST_ENV_VAR": "Test Value"}, stream_output=True ) assert result["stdout"] == expected assert result["stderr"] == "" # Validate the output was streamed to the console out, err = capsys.readouterr() assert out.strip() == expected assert err == "" @pytest.mark.parametrize( "script", [ "echo $DUMMY_ENV_VAR", "bash -c 'echo $DUMMY_ENV_VAR'", ], ) async def test_run_shell_script_expand_env(self, script, capsys, set_dummy_env_var): result = await run_shell_script( script, expand_env_vars=True, stream_output=True, ) assert result["stdout"] == "dummy" assert result["stderr"] == "" async def test_run_shell_script_no_expand_env(self, capsys, set_dummy_env_var): result = await run_shell_script( "echo $DUMMY_ENV_VAR", stream_output=True, ) assert result["stdout"] == "$DUMMY_ENV_VAR" assert result["stderr"] == "" async def test_run_shell_script_no_output(self, capsys): result = await run_shell_script("echo Hello World", stream_output=False) assert result["stdout"] == "Hello World" assert result["stderr"] == "" # Validate nothing was streamed to the console out, err = capsys.readouterr() assert out == "" assert err == "" async def test_run_shell_script_in_directory(self): parent_dir = str(Path.cwd().parent) result = await run_shell_script( "pwd", directory=parent_dir, stream_output=False ) assert result["stdout"] == parent_dir assert result["stderr"] == "" @pytest.mark.skipif( sys.platform != "win32", reason="_open_anyio_process errors when mocking OS in test context", ) async def test_run_shell_script_split_on_windows(self, monkeypatch): # return type needs to be mocked to avoid TypeError shex_split_mock = MagicMock(return_value=["echo", "Hello", "World"]) monkeypatch.setattr( "prefect.deployments.steps.utility.shlex.split", shex_split_mock, ) result = await run_shell_script("echo Hello World") # validates that command is parsed as non-posix shex_split_mock.assert_called_once_with("echo Hello World", posix=False) assert result["stdout"] == "Hello World" assert result["stderr"] == ""
TestRunShellScript
python
ray-project__ray
python/ray/data/_internal/logical/interfaces/logical_operator.py
{ "start": 3729, "end": 4443 }
class ____(LogicalOperator): """Mixin for reading operators supporting predicate pushdown""" def supports_predicate_pushdown(self) -> bool: return False def get_current_predicate(self) -> Optional[Expr]: return None def apply_predicate( self, predicate_expr: Expr, ) -> LogicalOperator: return self def get_column_renames(self) -> Optional[Dict[str, str]]: """Return the column renames applied by projection pushdown, if any. Returns: A dictionary mapping old column names to new column names, or None if no renaming has been applied. """ return None
LogicalOperatorSupportsPredicatePushdown
python
apache__airflow
helm-tests/tests/helm_tests/airflow_core/test_triggerer.py
{ "start": 969, "end": 27911 }
class ____: """Tests triggerer.""" @pytest.mark.parametrize( ("airflow_version", "num_docs"), [ ("2.1.0", 0), ("2.2.0", 1), ], ) def test_only_exists_on_new_airflow_versions(self, airflow_version, num_docs): """Trigger was only added from Airflow 2.2 onwards.""" docs = render_chart( values={"airflowVersion": airflow_version}, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert num_docs == len(docs) def test_can_be_disabled(self): """ Triggerer should be able to be disabled if the users desires. For example, user may be disabled when using Python 3.6 or doesn't want to use async tasks. """ docs = render_chart( values={"triggerer": {"enabled": False}}, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert len(docs) == 0 @pytest.mark.parametrize( ("revision_history_limit", "global_revision_history_limit"), [(8, 10), (10, 8), (8, None), (None, 10), (None, None)], ) def test_revision_history_limit(self, revision_history_limit, global_revision_history_limit): values = { "triggerer": { "enabled": True, } } if revision_history_limit: values["triggerer"]["revisionHistoryLimit"] = revision_history_limit if global_revision_history_limit: values["revisionHistoryLimit"] = global_revision_history_limit docs = render_chart( values=values, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) expected_result = revision_history_limit or global_revision_history_limit assert jmespath.search("spec.revisionHistoryLimit", docs[0]) == expected_result def test_disable_wait_for_migration(self): docs = render_chart( values={ "triggerer": { "waitForMigrations": {"enabled": False}, }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) actual = jmespath.search( "spec.template.spec.initContainers[?name=='wait-for-airflow-migrations']", docs[0] ) assert actual is None def test_should_add_extra_containers(self): docs = render_chart( values={ "triggerer": { "extraContainers": [ {"name": "{{ .Chart.Name }}", "image": "test-registry/test-repo:test-tag"} ], }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.containers[-1]", docs[0]) == { "name": "airflow", "image": "test-registry/test-repo:test-tag", } def test_should_template_extra_containers(self): docs = render_chart( values={ "triggerer": { "extraContainers": [{"name": "{{ .Release.Name }}-test-container"}], }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.containers[-1]", docs[0]) == { "name": "release-name-test-container" } def test_should_add_extra_init_containers(self): docs = render_chart( values={ "triggerer": { "extraInitContainers": [ {"name": "test-init-container", "image": "test-registry/test-repo:test-tag"} ], }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.initContainers[-1]", docs[0]) == { "name": "test-init-container", "image": "test-registry/test-repo:test-tag", } def test_should_template_extra_init_containers(self): docs = render_chart( values={ "triggerer": { "extraInitContainers": [{"name": "{{ .Release.Name }}-test-init-container"}], }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.initContainers[-1]", docs[0]) == { "name": "release-name-test-init-container" } def test_should_add_extra_volume_and_extra_volume_mount(self): docs = render_chart( values={ "triggerer": { "extraVolumes": [{"name": "test-volume-{{ .Chart.Name }}", "emptyDir": {}}], "extraVolumeMounts": [ {"name": "test-volume-{{ .Chart.Name }}", "mountPath": "/opt/test"} ], }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.volumes[1].name", docs[0]) == "test-volume-airflow" assert ( jmespath.search("spec.template.spec.containers[0].volumeMounts[0].name", docs[0]) == "test-volume-airflow" ) assert ( jmespath.search("spec.template.spec.initContainers[0].volumeMounts[-1].name", docs[0]) == "test-volume-airflow" ) def test_should_add_global_volume_and_global_volume_mount(self): docs = render_chart( values={ "volumes": [{"name": "test-volume", "emptyDir": {}}], "volumeMounts": [{"name": "test-volume", "mountPath": "/opt/test"}], }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.volumes[1].name", docs[0]) == "test-volume" assert ( jmespath.search("spec.template.spec.containers[0].volumeMounts[0].name", docs[0]) == "test-volume" ) def test_should_add_extraEnvs(self): docs = render_chart( values={ "triggerer": { "env": [ {"name": "TEST_ENV_1", "value": "test_env_1"}, { "name": "TEST_ENV_2", "valueFrom": {"secretKeyRef": {"name": "my-secret", "key": "my-key"}}, }, { "name": "TEST_ENV_3", "valueFrom": {"configMapKeyRef": {"name": "my-config-map", "key": "my-key"}}, }, ], } }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert {"name": "TEST_ENV_1", "value": "test_env_1"} in jmespath.search( "spec.template.spec.containers[0].env", docs[0] ) assert { "name": "TEST_ENV_2", "valueFrom": {"secretKeyRef": {"name": "my-secret", "key": "my-key"}}, } in jmespath.search("spec.template.spec.containers[0].env", docs[0]) assert { "name": "TEST_ENV_3", "valueFrom": {"configMapKeyRef": {"name": "my-config-map", "key": "my-key"}}, } in jmespath.search("spec.template.spec.containers[0].env", docs[0]) def test_should_add_extraEnvs_to_wait_for_migration_container(self): docs = render_chart( values={ "triggerer": { "waitForMigrations": { "env": [{"name": "TEST_ENV_1", "value": "test_env_1"}], }, } }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert {"name": "TEST_ENV_1", "value": "test_env_1"} in jmespath.search( "spec.template.spec.initContainers[0].env", docs[0] ) def test_should_add_component_specific_labels(self): docs = render_chart( values={ "triggerer": { "labels": {"test_label": "test_label_value"}, }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert "test_label" in jmespath.search("spec.template.metadata.labels", docs[0]) assert jmespath.search("spec.template.metadata.labels", docs[0])["test_label"] == "test_label_value" def test_scheduler_name(self): docs = render_chart( values={"schedulerName": "airflow-scheduler"}, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert ( jmespath.search( "spec.template.spec.schedulerName", docs[0], ) == "airflow-scheduler" ) def test_should_create_valid_affinity_tolerations_and_node_selector(self): docs = render_chart( values={ "triggerer": { "affinity": { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ { "matchExpressions": [ {"key": "foo", "operator": "In", "values": ["true"]}, ] } ] } } }, "tolerations": [ {"key": "dynamic-pods", "operator": "Equal", "value": "true", "effect": "NoSchedule"} ], "nodeSelector": {"diskType": "ssd"}, }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("kind", docs[0]) == "StatefulSet" assert ( jmespath.search( "spec.template.spec.affinity.nodeAffinity." "requiredDuringSchedulingIgnoredDuringExecution." "nodeSelectorTerms[0]." "matchExpressions[0]." "key", docs[0], ) == "foo" ) assert ( jmespath.search( "spec.template.spec.nodeSelector.diskType", docs[0], ) == "ssd" ) assert ( jmespath.search( "spec.template.spec.tolerations[0].key", docs[0], ) == "dynamic-pods" ) def test_affinity_tolerations_topology_spread_constraints_and_node_selector_precedence(self): """When given both global and triggerer affinity etc, triggerer affinity etc is used.""" expected_affinity = { "nodeAffinity": { "requiredDuringSchedulingIgnoredDuringExecution": { "nodeSelectorTerms": [ { "matchExpressions": [ {"key": "foo", "operator": "In", "values": ["true"]}, ] } ] } } } expected_topology_spread_constraints = { "maxSkew": 1, "topologyKey": "foo", "whenUnsatisfiable": "ScheduleAnyway", "labelSelector": {"matchLabels": {"tier": "airflow"}}, } docs = render_chart( values={ "triggerer": { "affinity": expected_affinity, "tolerations": [ {"key": "dynamic-pods", "operator": "Equal", "value": "true", "effect": "NoSchedule"} ], "topologySpreadConstraints": [expected_topology_spread_constraints], "nodeSelector": {"type": "ssd"}, }, "affinity": { "nodeAffinity": { "preferredDuringSchedulingIgnoredDuringExecution": [ { "weight": 1, "preference": { "matchExpressions": [ {"key": "not-me", "operator": "In", "values": ["true"]}, ] }, } ] } }, "tolerations": [ {"key": "not-me", "operator": "Equal", "value": "true", "effect": "NoSchedule"} ], "topologySpreadConstraints": [ { "maxSkew": 1, "topologyKey": "not-me", "whenUnsatisfiable": "ScheduleAnyway", "labelSelector": {"matchLabels": {"tier": "airflow"}}, } ], "nodeSelector": {"type": "not-me"}, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert expected_affinity == jmespath.search("spec.template.spec.affinity", docs[0]) assert ( jmespath.search( "spec.template.spec.nodeSelector.type", docs[0], ) == "ssd" ) tolerations = jmespath.search("spec.template.spec.tolerations", docs[0]) assert len(tolerations) == 1 assert tolerations[0]["key"] == "dynamic-pods" assert expected_topology_spread_constraints == jmespath.search( "spec.template.spec.topologySpreadConstraints[0]", docs[0] ) def test_should_create_default_affinity(self): docs = render_chart(show_only=["templates/scheduler/scheduler-deployment.yaml"]) assert jmespath.search( "spec.template.spec.affinity.podAntiAffinity." "preferredDuringSchedulingIgnoredDuringExecution[0]." "podAffinityTerm.labelSelector.matchLabels", docs[0], ) == {"component": "scheduler"} def test_livenessprobe_values_are_configurable(self): docs = render_chart( values={ "triggerer": { "livenessProbe": { "initialDelaySeconds": 111, "timeoutSeconds": 222, "failureThreshold": 333, "periodSeconds": 444, "command": ["sh", "-c", "echo", "wow such test"], } }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert ( jmespath.search("spec.template.spec.containers[0].livenessProbe.initialDelaySeconds", docs[0]) == 111 ) assert ( jmespath.search("spec.template.spec.containers[0].livenessProbe.timeoutSeconds", docs[0]) == 222 ) assert ( jmespath.search("spec.template.spec.containers[0].livenessProbe.failureThreshold", docs[0]) == 333 ) assert jmespath.search("spec.template.spec.containers[0].livenessProbe.periodSeconds", docs[0]) == 444 assert jmespath.search("spec.template.spec.containers[0].livenessProbe.exec.command", docs[0]) == [ "sh", "-c", "echo", "wow such test", ] @pytest.mark.parametrize( ("airflow_version", "probe_command"), [ ("2.4.9", "airflow jobs check --job-type TriggererJob --hostname $(hostname)"), ("2.5.0", "airflow jobs check --job-type TriggererJob --local"), ], ) def test_livenessprobe_command_depends_on_airflow_version(self, airflow_version, probe_command): docs = render_chart( values={"airflowVersion": f"{airflow_version}"}, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert ( probe_command in jmespath.search("spec.template.spec.containers[0].livenessProbe.exec.command", docs[0])[-1] ) @pytest.mark.parametrize( ("log_values", "expected_volume"), [ ({"persistence": {"enabled": False}}, {"emptyDir": {}}), ( {"persistence": {"enabled": False}, "emptyDirConfig": {"sizeLimit": "10Gi"}}, {"emptyDir": {"sizeLimit": "10Gi"}}, ), ( {"persistence": {"enabled": True}}, {"persistentVolumeClaim": {"claimName": "release-name-logs"}}, ), ( {"persistence": {"enabled": True, "existingClaim": "test-claim"}}, {"persistentVolumeClaim": {"claimName": "test-claim"}}, ), ], ) def test_logs_persistence_changes_volume(self, log_values, expected_volume): docs = render_chart( values={ "triggerer": {"persistence": {"enabled": False}}, "logs": log_values, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.volumes[1]", docs[0]) == { "name": "logs", **expected_volume, } def test_resources_are_configurable(self): docs = render_chart( values={ "triggerer": { "resources": { "limits": {"cpu": "200m", "memory": "128Mi"}, "requests": {"cpu": "300m", "memory": "169Mi"}, } }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.containers[0].resources.limits.memory", docs[0]) == "128Mi" assert jmespath.search("spec.template.spec.containers[0].resources.limits.cpu", docs[0]) == "200m" assert ( jmespath.search("spec.template.spec.containers[0].resources.requests.memory", docs[0]) == "169Mi" ) assert jmespath.search("spec.template.spec.containers[0].resources.requests.cpu", docs[0]) == "300m" assert ( jmespath.search("spec.template.spec.initContainers[0].resources.limits.memory", docs[0]) == "128Mi" ) assert jmespath.search("spec.template.spec.initContainers[0].resources.limits.cpu", docs[0]) == "200m" assert ( jmespath.search("spec.template.spec.initContainers[0].resources.requests.memory", docs[0]) == "169Mi" ) assert ( jmespath.search("spec.template.spec.initContainers[0].resources.requests.cpu", docs[0]) == "300m" ) def test_resources_are_not_added_by_default(self): docs = render_chart( show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.containers[0].resources", docs[0]) == {} @pytest.mark.parametrize( ("persistence", "update_strategy", "expected_update_strategy"), [ (False, None, None), (True, {"rollingUpdate": {"partition": 0}}, {"rollingUpdate": {"partition": 0}}), (True, None, None), ], ) def test_update_strategy(self, persistence, update_strategy, expected_update_strategy): docs = render_chart( values={ "airflowVersion": "2.6.0", "executor": "CeleryExecutor", "triggerer": { "persistence": {"enabled": persistence}, "updateStrategy": update_strategy, }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert expected_update_strategy == jmespath.search("spec.updateStrategy", docs[0]) @pytest.mark.parametrize( ("persistence", "strategy", "expected_strategy"), [ (True, None, None), ( False, {"rollingUpdate": {"maxSurge": "100%", "maxUnavailable": "50%"}}, {"rollingUpdate": {"maxSurge": "100%", "maxUnavailable": "50%"}}, ), (False, None, None), ], ) def test_strategy(self, persistence, strategy, expected_strategy): docs = render_chart( values={ "triggerer": {"persistence": {"enabled": persistence}, "strategy": strategy}, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert expected_strategy == jmespath.search("spec.strategy", docs[0]) def test_default_command_and_args(self): docs = render_chart( show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.containers[0].command", docs[0]) is None assert jmespath.search("spec.template.spec.containers[0].args", docs[0]) == [ "bash", "-c", "exec airflow triggerer", ] @pytest.mark.parametrize("command", [None, ["custom", "command"]]) @pytest.mark.parametrize("args", [None, ["custom", "args"]]) def test_command_and_args_overrides(self, command, args): docs = render_chart( values={"triggerer": {"command": command, "args": args}}, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert command == jmespath.search("spec.template.spec.containers[0].command", docs[0]) assert args == jmespath.search("spec.template.spec.containers[0].args", docs[0]) def test_command_and_args_overrides_are_templated(self): docs = render_chart( values={ "triggerer": {"command": ["{{ .Release.Name }}"], "args": ["{{ .Release.Service }}"]}, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.containers[0].command", docs[0]) == ["release-name"] assert jmespath.search("spec.template.spec.containers[0].args", docs[0]) == ["Helm"] def test_dags_gitsync_sidecar_and_init_container(self): docs = render_chart( values={"dags": {"gitSync": {"enabled": True}}}, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert "git-sync" in [c["name"] for c in jmespath.search("spec.template.spec.containers", docs[0])] assert "git-sync-init" in [ c["name"] for c in jmespath.search("spec.template.spec.initContainers", docs[0]) ] def test_dags_gitsync_with_persistence_no_sidecar_or_init_container(self): docs = render_chart( values={"dags": {"gitSync": {"enabled": True}, "persistence": {"enabled": True}}}, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) # No gitsync sidecar or init container assert "git-sync" not in [ c["name"] for c in jmespath.search("spec.template.spec.containers", docs[0]) ] assert "git-sync-init" not in [ c["name"] for c in jmespath.search("spec.template.spec.initContainers", docs[0]) ] def test_no_airflow_local_settings(self): docs = render_chart( values={"airflowLocalSettings": None}, show_only=["templates/triggerer/triggerer-deployment.yaml"] ) volume_mounts = jmespath.search("spec.template.spec.containers[0].volumeMounts", docs[0]) assert "airflow_local_settings.py" not in str(volume_mounts) volume_mounts_init = jmespath.search("spec.template.spec.containers[0].volumeMounts", docs[0]) assert "airflow_local_settings.py" not in str(volume_mounts_init) def test_airflow_local_settings(self): docs = render_chart( values={"airflowLocalSettings": "# Well hello!"}, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) volume_mount = { "name": "config", "mountPath": "/opt/airflow/config/airflow_local_settings.py", "subPath": "airflow_local_settings.py", "readOnly": True, } assert volume_mount in jmespath.search("spec.template.spec.containers[0].volumeMounts", docs[0]) assert volume_mount in jmespath.search("spec.template.spec.initContainers[0].volumeMounts", docs[0]) def test_should_add_component_specific_annotations(self): docs = render_chart( values={ "triggerer": { "annotations": {"test_annotation": "test_annotation_value"}, }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert "annotations" in jmespath.search("metadata", docs[0]) assert jmespath.search("metadata.annotations", docs[0])["test_annotation"] == "test_annotation_value" def test_triggerer_pod_hostaliases(self): docs = render_chart( values={ "triggerer": { "hostAliases": [{"ip": "127.0.0.1", "hostnames": ["foo.local"]}], }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.template.spec.hostAliases[0].ip", docs[0]) == "127.0.0.1" assert jmespath.search("spec.template.spec.hostAliases[0].hostnames[0]", docs[0]) == "foo.local" def test_triggerer_template_storage_class_name(self): docs = render_chart( values={"triggerer": {"persistence": {"storageClassName": "{{ .Release.Name }}-storage-class"}}}, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert ( jmespath.search("spec.volumeClaimTemplates[0].spec.storageClassName", docs[0]) == "release-name-storage-class" ) def test_persistent_volume_claim_retention_policy(self): docs = render_chart( values={ "executor": "CeleryExecutor", "triggerer": { "persistence": { "enabled": True, "persistentVolumeClaimRetentionPolicy": {"whenDeleted": "Delete"}, } }, }, show_only=["templates/triggerer/triggerer-deployment.yaml"], ) assert jmespath.search("spec.persistentVolumeClaimRetentionPolicy", docs[0]) == { "whenDeleted": "Delete", }
TestTriggerer
python
django__django
django/contrib/gis/geos/prototypes/threadsafe.py
{ "start": 152, "end": 598 }
class ____(GEOSBase): """Represent a GEOS context handle.""" ptr_type = CONTEXT_PTR destructor = lgeos.finishGEOS_r def __init__(self): # Initializing the context handler for this thread with # the notice and error handler. self.ptr = lgeos.initGEOS_r(notice_h, error_h) # Defining a thread-local object and creating an instance # to hold a reference to GEOSContextHandle for this thread.
GEOSContextHandle
python
ray-project__ray
python/ray/train/_internal/state/schema.py
{ "start": 4615, "end": 5011 }
class ____(TrainRunInfo): """Metadata for a Ray Train run and information about its workers.""" workers: List[TrainWorkerInfoWithDetails] = Field( description="A List of Train workers sorted by global ranks." ) job_details: Optional[JobDetails] = Field( None, description="Details of the job that started this Train run." ) @DeveloperAPI
TrainRunInfoWithDetails
python
pypa__hatch
tests/cli/test/test_test.py
{ "start": 36380, "end": 41421 }
class ____: def test_default_compact(self, hatch, temp_dir, config_file, helpers): config_file.model.template.plugins["default"]["tests"] = False config_file.save() project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new", project_name) assert result.exit_code == 0, result.output project_path = temp_dir / "my-app" data_path = temp_dir / "data" data_path.mkdir() project = Project(project_path) config = dict(project.raw_config) config["tool"]["hatch"]["envs"] = { "hatch-test": { "matrix": [{"python": ["3.12", "3.10", "3.8"]}], "dependencies": ["foo", "bar"], "scripts": { "run": "test {env_name}", "run-cov": "test with coverage", "cov-combine": "combine coverage", "cov-report": "show coverage", }, } } project.save_config(config) with project_path.as_cwd(env_vars={ConfigEnvVars.DATA: str(data_path)}): result = hatch("test", "--show") assert result.exit_code == 0, result.output assert helpers.remove_trailing_spaces(result.output) == helpers.dedent( """ +------------+---------+-------------------+--------------+-------------+ | Name | Type | Envs | Dependencies | Scripts | +============+=========+===================+==============+=============+ | hatch-test | virtual | hatch-test.py3.12 | bar | cov-combine | | | | hatch-test.py3.10 | foo | cov-report | | | | hatch-test.py3.8 | | run | | | | | | run-cov | +------------+---------+-------------------+--------------+-------------+ """ ) def test_verbose(self, hatch, temp_dir, config_file, helpers): config_file.model.template.plugins["default"]["tests"] = False config_file.save() project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new", project_name) assert result.exit_code == 0, result.output project_path = temp_dir / "my-app" data_path = temp_dir / "data" data_path.mkdir() project = Project(project_path) config = dict(project.raw_config) config["tool"]["hatch"]["envs"] = { "hatch-test": { "matrix": [{"python": ["3.12", "3.10", "3.8"]}], "dependencies": ["foo", "bar"], "scripts": { "run": "test {env_name}", "run-cov": "test with coverage", "cov-combine": "combine coverage", "cov-report": "show coverage", }, "overrides": {"matrix": {"python": {"description": {"value": "test 3.10", "if": ["3.10"]}}}}, } } project.save_config(config) with project_path.as_cwd(env_vars={ConfigEnvVars.DATA: str(data_path)}): result = hatch("-v", "test", "--show") assert result.exit_code == 0, result.output assert helpers.remove_trailing_spaces(result.output) == helpers.dedent( """ +-------------------+---------+--------------+-------------+-------------+ | Name | Type | Dependencies | Scripts | Description | +===================+=========+==============+=============+=============+ | hatch-test.py3.12 | virtual | bar | cov-combine | | | | | foo | cov-report | | | | | | run | | | | | | run-cov | | +-------------------+---------+--------------+-------------+-------------+ | hatch-test.py3.10 | virtual | bar | cov-combine | test 3.10 | | | | foo | cov-report | | | | | | run | | | | | | run-cov | | +-------------------+---------+--------------+-------------+-------------+ | hatch-test.py3.8 | virtual | bar | cov-combine | | | | | foo | cov-report | | | | | | run | | | | | | run-cov | | +-------------------+---------+--------------+-------------+-------------+ """ )
TestShow