content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
import itertools\n\nimport numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n notna,\n)\n\n\ndef create_series():\n return [\n Series(dtype=np.float64, name="a"),\n Series([np.nan] * 5),\n Series([1.0] * 5),\n Series(range(5, 0, -1)),\n Series(range(5)),\n Series([np.nan, 1.0, np.nan, 1.0, 1.0]),\n Series([np.nan, 1.0, np.nan, 2.0, 3.0]),\n Series([np.nan, 1.0, np.nan, 3.0, 2.0]),\n ]\n\n\ndef create_dataframes():\n return [\n DataFrame(columns=["a", "a"]),\n DataFrame(np.arange(15).reshape((5, 3)), columns=["a", "a", 99]),\n ] + [DataFrame(s) for s in create_series()]\n\n\ndef is_constant(x):\n values = x.values.ravel("K")\n return len(set(values[notna(values)])) == 1\n\n\n@pytest.fixture(\n params=(\n obj\n for obj in itertools.chain(create_series(), create_dataframes())\n if is_constant(obj)\n ),\n)\ndef consistent_data(request):\n return request.param\n\n\n@pytest.fixture(params=create_series())\ndef series_data(request):\n return request.param\n\n\n@pytest.fixture(params=itertools.chain(create_series(), create_dataframes()))\ndef all_data(request):\n """\n Test:\n - Empty Series / DataFrame\n - All NaN\n - All consistent value\n - Monotonically decreasing\n - Monotonically increasing\n - Monotonically consistent with NaNs\n - Monotonically increasing with NaNs\n - Monotonically decreasing with NaNs\n """\n return request.param\n\n\n@pytest.fixture(params=[0, 2])\ndef min_periods(request):\n return request.param\n
.venv\Lib\site-packages\pandas\tests\window\moments\conftest.py
conftest.py
Python
1,595
0.85
0.138889
0
react-lib
264
2024-09-05T06:29:33.094363
Apache-2.0
true
97488b0aa29f315539a083577e7e66ee
import numpy as np\nimport pytest\n\nfrom pandas import (\n DataFrame,\n Series,\n concat,\n)\nimport pandas._testing as tm\n\n\ndef create_mock_weights(obj, com, adjust, ignore_na):\n if isinstance(obj, DataFrame):\n if not len(obj.columns):\n return DataFrame(index=obj.index, columns=obj.columns)\n w = concat(\n [\n create_mock_series_weights(\n obj.iloc[:, i], com=com, adjust=adjust, ignore_na=ignore_na\n )\n for i in range(len(obj.columns))\n ],\n axis=1,\n )\n w.index = obj.index\n w.columns = obj.columns\n return w\n else:\n return create_mock_series_weights(obj, com, adjust, ignore_na)\n\n\ndef create_mock_series_weights(s, com, adjust, ignore_na):\n w = Series(np.nan, index=s.index, name=s.name)\n alpha = 1.0 / (1.0 + com)\n if adjust:\n count = 0\n for i in range(len(s)):\n if s.iat[i] == s.iat[i]:\n w.iat[i] = pow(1.0 / (1.0 - alpha), count)\n count += 1\n elif not ignore_na:\n count += 1\n else:\n sum_wts = 0.0\n prev_i = -1\n count = 0\n for i in range(len(s)):\n if s.iat[i] == s.iat[i]:\n if prev_i == -1:\n w.iat[i] = 1.0\n else:\n w.iat[i] = alpha * sum_wts / pow(1.0 - alpha, count - prev_i)\n sum_wts += w.iat[i]\n prev_i = count\n count += 1\n elif not ignore_na:\n count += 1\n return w\n\n\ndef test_ewm_consistency_mean(all_data, adjust, ignore_na, min_periods):\n com = 3.0\n\n result = all_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).mean()\n weights = create_mock_weights(all_data, com=com, adjust=adjust, ignore_na=ignore_na)\n expected = all_data.multiply(weights).cumsum().divide(weights.cumsum()).ffill()\n expected[\n all_data.expanding().count() < (max(min_periods, 1) if min_periods else 1)\n ] = np.nan\n tm.assert_equal(result, expected.astype("float64"))\n\n\ndef test_ewm_consistency_consistent(consistent_data, adjust, ignore_na, min_periods):\n com = 3.0\n\n count_x = consistent_data.expanding().count()\n mean_x = consistent_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).mean()\n # check that correlation of a series with itself is either 1 or NaN\n corr_x_x = consistent_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).corr(consistent_data)\n exp = (\n consistent_data.max()\n if isinstance(consistent_data, Series)\n else consistent_data.max().max()\n )\n\n # check mean of constant series\n expected = consistent_data * np.nan\n expected[count_x >= max(min_periods, 1)] = exp\n tm.assert_equal(mean_x, expected)\n\n # check correlation of constant series with itself is NaN\n expected[:] = np.nan\n tm.assert_equal(corr_x_x, expected)\n\n\ndef test_ewm_consistency_var_debiasing_factors(\n all_data, adjust, ignore_na, min_periods\n):\n com = 3.0\n\n # check variance debiasing factors\n var_unbiased_x = all_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=False)\n var_biased_x = all_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=True)\n\n weights = create_mock_weights(all_data, com=com, adjust=adjust, ignore_na=ignore_na)\n cum_sum = weights.cumsum().ffill()\n cum_sum_sq = (weights * weights).cumsum().ffill()\n numerator = cum_sum * cum_sum\n denominator = numerator - cum_sum_sq\n denominator[denominator <= 0.0] = np.nan\n var_debiasing_factors_x = numerator / denominator\n\n tm.assert_equal(var_unbiased_x, var_biased_x * var_debiasing_factors_x)\n\n\n@pytest.mark.parametrize("bias", [True, False])\ndef test_moments_consistency_var(all_data, adjust, ignore_na, min_periods, bias):\n com = 3.0\n\n mean_x = all_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).mean()\n var_x = all_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=bias)\n assert not (var_x < 0).any().any()\n\n if bias:\n # check that biased var(x) == mean(x^2) - mean(x)^2\n mean_x2 = (\n (all_data * all_data)\n .ewm(com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na)\n .mean()\n )\n tm.assert_equal(var_x, mean_x2 - (mean_x * mean_x))\n\n\n@pytest.mark.parametrize("bias", [True, False])\ndef test_moments_consistency_var_constant(\n consistent_data, adjust, ignore_na, min_periods, bias\n):\n com = 3.0\n count_x = consistent_data.expanding(min_periods=min_periods).count()\n var_x = consistent_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=bias)\n\n # check that variance of constant series is identically 0\n assert not (var_x > 0).any().any()\n expected = consistent_data * np.nan\n expected[count_x >= max(min_periods, 1)] = 0.0\n if not bias:\n expected[count_x < 2] = np.nan\n tm.assert_equal(var_x, expected)\n\n\n@pytest.mark.parametrize("bias", [True, False])\ndef test_ewm_consistency_std(all_data, adjust, ignore_na, min_periods, bias):\n com = 3.0\n var_x = all_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=bias)\n assert not (var_x < 0).any().any()\n\n std_x = all_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).std(bias=bias)\n assert not (std_x < 0).any().any()\n\n # check that var(x) == std(x)^2\n tm.assert_equal(var_x, std_x * std_x)\n\n cov_x_x = all_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).cov(all_data, bias=bias)\n assert not (cov_x_x < 0).any().any()\n\n # check that var(x) == cov(x, x)\n tm.assert_equal(var_x, cov_x_x)\n\n\n@pytest.mark.parametrize("bias", [True, False])\ndef test_ewm_consistency_series_cov_corr(\n series_data, adjust, ignore_na, min_periods, bias\n):\n com = 3.0\n\n var_x_plus_y = (\n (series_data + series_data)\n .ewm(com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na)\n .var(bias=bias)\n )\n var_x = series_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=bias)\n var_y = series_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=bias)\n cov_x_y = series_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).cov(series_data, bias=bias)\n # check that cov(x, y) == (var(x+y) - var(x) -\n # var(y)) / 2\n tm.assert_equal(cov_x_y, 0.5 * (var_x_plus_y - var_x - var_y))\n\n # check that corr(x, y) == cov(x, y) / (std(x) *\n # std(y))\n corr_x_y = series_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).corr(series_data)\n std_x = series_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).std(bias=bias)\n std_y = series_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).std(bias=bias)\n tm.assert_equal(corr_x_y, cov_x_y / (std_x * std_y))\n\n if bias:\n # check that biased cov(x, y) == mean(x*y) -\n # mean(x)*mean(y)\n mean_x = series_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).mean()\n mean_y = series_data.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).mean()\n mean_x_times_y = (\n (series_data * series_data)\n .ewm(com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na)\n .mean()\n )\n tm.assert_equal(cov_x_y, mean_x_times_y - (mean_x * mean_y))\n
.venv\Lib\site-packages\pandas\tests\window\moments\test_moments_consistency_ewm.py
test_moments_consistency_ewm.py
Python
8,107
0.95
0.09465
0.067633
python-kit
50
2023-07-18T11:14:06.981463
BSD-3-Clause
true
4c3c57b15dec14bcac1e843f79a9e509
import numpy as np\nimport pytest\n\nfrom pandas import Series\nimport pandas._testing as tm\n\n\ndef no_nans(x):\n return x.notna().all().all()\n\n\ndef all_na(x):\n return x.isnull().all().all()\n\n\n@pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum, np.sum])\ndef test_expanding_apply_consistency_sum_nans(request, all_data, min_periods, f):\n if f is np.sum:\n if not no_nans(all_data) and not (\n all_na(all_data) and not all_data.empty and min_periods > 0\n ):\n request.applymarker(\n pytest.mark.xfail(reason="np.sum has different behavior with NaNs")\n )\n expanding_f_result = all_data.expanding(min_periods=min_periods).sum()\n expanding_apply_f_result = all_data.expanding(min_periods=min_periods).apply(\n func=f, raw=True\n )\n tm.assert_equal(expanding_f_result, expanding_apply_f_result)\n\n\n@pytest.mark.parametrize("ddof", [0, 1])\ndef test_moments_consistency_var(all_data, min_periods, ddof):\n var_x = all_data.expanding(min_periods=min_periods).var(ddof=ddof)\n assert not (var_x < 0).any().any()\n\n if ddof == 0:\n # check that biased var(x) == mean(x^2) - mean(x)^2\n mean_x2 = (all_data * all_data).expanding(min_periods=min_periods).mean()\n mean_x = all_data.expanding(min_periods=min_periods).mean()\n tm.assert_equal(var_x, mean_x2 - (mean_x * mean_x))\n\n\n@pytest.mark.parametrize("ddof", [0, 1])\ndef test_moments_consistency_var_constant(consistent_data, min_periods, ddof):\n count_x = consistent_data.expanding(min_periods=min_periods).count()\n var_x = consistent_data.expanding(min_periods=min_periods).var(ddof=ddof)\n\n # check that variance of constant series is identically 0\n assert not (var_x > 0).any().any()\n expected = consistent_data * np.nan\n expected[count_x >= max(min_periods, 1)] = 0.0\n if ddof == 1:\n expected[count_x < 2] = np.nan\n tm.assert_equal(var_x, expected)\n\n\n@pytest.mark.parametrize("ddof", [0, 1])\ndef test_expanding_consistency_var_std_cov(all_data, min_periods, ddof):\n var_x = all_data.expanding(min_periods=min_periods).var(ddof=ddof)\n assert not (var_x < 0).any().any()\n\n std_x = all_data.expanding(min_periods=min_periods).std(ddof=ddof)\n assert not (std_x < 0).any().any()\n\n # check that var(x) == std(x)^2\n tm.assert_equal(var_x, std_x * std_x)\n\n cov_x_x = all_data.expanding(min_periods=min_periods).cov(all_data, ddof=ddof)\n assert not (cov_x_x < 0).any().any()\n\n # check that var(x) == cov(x, x)\n tm.assert_equal(var_x, cov_x_x)\n\n\n@pytest.mark.parametrize("ddof", [0, 1])\ndef test_expanding_consistency_series_cov_corr(series_data, min_periods, ddof):\n var_x_plus_y = (\n (series_data + series_data).expanding(min_periods=min_periods).var(ddof=ddof)\n )\n var_x = series_data.expanding(min_periods=min_periods).var(ddof=ddof)\n var_y = series_data.expanding(min_periods=min_periods).var(ddof=ddof)\n cov_x_y = series_data.expanding(min_periods=min_periods).cov(series_data, ddof=ddof)\n # check that cov(x, y) == (var(x+y) - var(x) -\n # var(y)) / 2\n tm.assert_equal(cov_x_y, 0.5 * (var_x_plus_y - var_x - var_y))\n\n # check that corr(x, y) == cov(x, y) / (std(x) *\n # std(y))\n corr_x_y = series_data.expanding(min_periods=min_periods).corr(series_data)\n std_x = series_data.expanding(min_periods=min_periods).std(ddof=ddof)\n std_y = series_data.expanding(min_periods=min_periods).std(ddof=ddof)\n tm.assert_equal(corr_x_y, cov_x_y / (std_x * std_y))\n\n if ddof == 0:\n # check that biased cov(x, y) == mean(x*y) -\n # mean(x)*mean(y)\n mean_x = series_data.expanding(min_periods=min_periods).mean()\n mean_y = series_data.expanding(min_periods=min_periods).mean()\n mean_x_times_y = (\n (series_data * series_data).expanding(min_periods=min_periods).mean()\n )\n tm.assert_equal(cov_x_y, mean_x_times_y - (mean_x * mean_y))\n\n\ndef test_expanding_consistency_mean(all_data, min_periods):\n result = all_data.expanding(min_periods=min_periods).mean()\n expected = (\n all_data.expanding(min_periods=min_periods).sum()\n / all_data.expanding(min_periods=min_periods).count()\n )\n tm.assert_equal(result, expected.astype("float64"))\n\n\ndef test_expanding_consistency_constant(consistent_data, min_periods):\n count_x = consistent_data.expanding().count()\n mean_x = consistent_data.expanding(min_periods=min_periods).mean()\n # check that correlation of a series with itself is either 1 or NaN\n corr_x_x = consistent_data.expanding(min_periods=min_periods).corr(consistent_data)\n\n exp = (\n consistent_data.max()\n if isinstance(consistent_data, Series)\n else consistent_data.max().max()\n )\n\n # check mean of constant series\n expected = consistent_data * np.nan\n expected[count_x >= max(min_periods, 1)] = exp\n tm.assert_equal(mean_x, expected)\n\n # check correlation of constant series with itself is NaN\n expected[:] = np.nan\n tm.assert_equal(corr_x_x, expected)\n\n\ndef test_expanding_consistency_var_debiasing_factors(all_data, min_periods):\n # check variance debiasing factors\n var_unbiased_x = all_data.expanding(min_periods=min_periods).var()\n var_biased_x = all_data.expanding(min_periods=min_periods).var(ddof=0)\n var_debiasing_factors_x = all_data.expanding().count() / (\n all_data.expanding().count() - 1.0\n ).replace(0.0, np.nan)\n tm.assert_equal(var_unbiased_x, var_biased_x * var_debiasing_factors_x)\n
.venv\Lib\site-packages\pandas\tests\window\moments\test_moments_consistency_expanding.py
test_moments_consistency_expanding.py
Python
5,537
0.95
0.111111
0.125
react-lib
782
2025-03-05T03:56:27.054875
Apache-2.0
true
08bd8d17e05205d9af3dbbf06e2db7f0
import numpy as np\nimport pytest\n\nfrom pandas import Series\nimport pandas._testing as tm\n\n\ndef no_nans(x):\n return x.notna().all().all()\n\n\ndef all_na(x):\n return x.isnull().all().all()\n\n\n@pytest.fixture(params=[(1, 0), (5, 1)])\ndef rolling_consistency_cases(request):\n """window, min_periods"""\n return request.param\n\n\n@pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum, np.sum])\ndef test_rolling_apply_consistency_sum(\n request, all_data, rolling_consistency_cases, center, f\n):\n window, min_periods = rolling_consistency_cases\n\n if f is np.sum:\n if not no_nans(all_data) and not (\n all_na(all_data) and not all_data.empty and min_periods > 0\n ):\n request.applymarker(\n pytest.mark.xfail(reason="np.sum has different behavior with NaNs")\n )\n rolling_f_result = all_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).sum()\n rolling_apply_f_result = all_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).apply(func=f, raw=True)\n tm.assert_equal(rolling_f_result, rolling_apply_f_result)\n\n\n@pytest.mark.parametrize("ddof", [0, 1])\ndef test_moments_consistency_var(all_data, rolling_consistency_cases, center, ddof):\n window, min_periods = rolling_consistency_cases\n\n var_x = all_data.rolling(window=window, min_periods=min_periods, center=center).var(\n ddof=ddof\n )\n assert not (var_x < 0).any().any()\n\n if ddof == 0:\n # check that biased var(x) == mean(x^2) - mean(x)^2\n mean_x = all_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).mean()\n mean_x2 = (\n (all_data * all_data)\n .rolling(window=window, min_periods=min_periods, center=center)\n .mean()\n )\n tm.assert_equal(var_x, mean_x2 - (mean_x * mean_x))\n\n\n@pytest.mark.parametrize("ddof", [0, 1])\ndef test_moments_consistency_var_constant(\n consistent_data, rolling_consistency_cases, center, ddof\n):\n window, min_periods = rolling_consistency_cases\n\n count_x = consistent_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).count()\n var_x = consistent_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).var(ddof=ddof)\n\n # check that variance of constant series is identically 0\n assert not (var_x > 0).any().any()\n expected = consistent_data * np.nan\n expected[count_x >= max(min_periods, 1)] = 0.0\n if ddof == 1:\n expected[count_x < 2] = np.nan\n tm.assert_equal(var_x, expected)\n\n\n@pytest.mark.parametrize("ddof", [0, 1])\ndef test_rolling_consistency_var_std_cov(\n all_data, rolling_consistency_cases, center, ddof\n):\n window, min_periods = rolling_consistency_cases\n\n var_x = all_data.rolling(window=window, min_periods=min_periods, center=center).var(\n ddof=ddof\n )\n assert not (var_x < 0).any().any()\n\n std_x = all_data.rolling(window=window, min_periods=min_periods, center=center).std(\n ddof=ddof\n )\n assert not (std_x < 0).any().any()\n\n # check that var(x) == std(x)^2\n tm.assert_equal(var_x, std_x * std_x)\n\n cov_x_x = all_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).cov(all_data, ddof=ddof)\n assert not (cov_x_x < 0).any().any()\n\n # check that var(x) == cov(x, x)\n tm.assert_equal(var_x, cov_x_x)\n\n\n@pytest.mark.parametrize("ddof", [0, 1])\ndef test_rolling_consistency_series_cov_corr(\n series_data, rolling_consistency_cases, center, ddof\n):\n window, min_periods = rolling_consistency_cases\n\n var_x_plus_y = (\n (series_data + series_data)\n .rolling(window=window, min_periods=min_periods, center=center)\n .var(ddof=ddof)\n )\n var_x = series_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).var(ddof=ddof)\n var_y = series_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).var(ddof=ddof)\n cov_x_y = series_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).cov(series_data, ddof=ddof)\n # check that cov(x, y) == (var(x+y) - var(x) -\n # var(y)) / 2\n tm.assert_equal(cov_x_y, 0.5 * (var_x_plus_y - var_x - var_y))\n\n # check that corr(x, y) == cov(x, y) / (std(x) *\n # std(y))\n corr_x_y = series_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).corr(series_data)\n std_x = series_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).std(ddof=ddof)\n std_y = series_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).std(ddof=ddof)\n tm.assert_equal(corr_x_y, cov_x_y / (std_x * std_y))\n\n if ddof == 0:\n # check that biased cov(x, y) == mean(x*y) -\n # mean(x)*mean(y)\n mean_x = series_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).mean()\n mean_y = series_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).mean()\n mean_x_times_y = (\n (series_data * series_data)\n .rolling(window=window, min_periods=min_periods, center=center)\n .mean()\n )\n tm.assert_equal(cov_x_y, mean_x_times_y - (mean_x * mean_y))\n\n\ndef test_rolling_consistency_mean(all_data, rolling_consistency_cases, center):\n window, min_periods = rolling_consistency_cases\n\n result = all_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).mean()\n expected = (\n all_data.rolling(window=window, min_periods=min_periods, center=center)\n .sum()\n .divide(\n all_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).count()\n )\n )\n tm.assert_equal(result, expected.astype("float64"))\n\n\ndef test_rolling_consistency_constant(\n consistent_data, rolling_consistency_cases, center\n):\n window, min_periods = rolling_consistency_cases\n\n count_x = consistent_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).count()\n mean_x = consistent_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).mean()\n # check that correlation of a series with itself is either 1 or NaN\n corr_x_x = consistent_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).corr(consistent_data)\n\n exp = (\n consistent_data.max()\n if isinstance(consistent_data, Series)\n else consistent_data.max().max()\n )\n\n # check mean of constant series\n expected = consistent_data * np.nan\n expected[count_x >= max(min_periods, 1)] = exp\n tm.assert_equal(mean_x, expected)\n\n # check correlation of constant series with itself is NaN\n expected[:] = np.nan\n tm.assert_equal(corr_x_x, expected)\n\n\ndef test_rolling_consistency_var_debiasing_factors(\n all_data, rolling_consistency_cases, center\n):\n window, min_periods = rolling_consistency_cases\n\n # check variance debiasing factors\n var_unbiased_x = all_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).var()\n var_biased_x = all_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).var(ddof=0)\n var_debiasing_factors_x = (\n all_data.rolling(window=window, min_periods=min_periods, center=center)\n .count()\n .divide(\n (\n all_data.rolling(\n window=window, min_periods=min_periods, center=center\n ).count()\n - 1.0\n ).replace(0.0, np.nan)\n )\n )\n tm.assert_equal(var_unbiased_x, var_biased_x * var_debiasing_factors_x)\n
.venv\Lib\site-packages\pandas\tests\window\moments\test_moments_consistency_rolling.py
test_moments_consistency_rolling.py
Python
7,821
0.95
0.069672
0.069307
python-kit
971
2025-06-30T20:03:27.876804
MIT
true
5cefdfa9ae3ec52bb498e1945a8d92da
\n\n
.venv\Lib\site-packages\pandas\tests\window\moments\__pycache__\conftest.cpython-313.pyc
conftest.cpython-313.pyc
Other
3,465
0.8
0
0
react-lib
827
2023-09-22T14:27:35.268550
MIT
true
0cdb7918dea63a036d91899604d60783
\n\n
.venv\Lib\site-packages\pandas\tests\window\moments\__pycache__\test_moments_consistency_ewm.cpython-313.pyc
test_moments_consistency_ewm.cpython-313.pyc
Other
9,994
0.8
0
0
awesome-app
13
2024-12-24T00:52:14.319775
MIT
true
b239f50a53c34a7697d965c83c22dbb2
\n\n
.venv\Lib\site-packages\pandas\tests\window\moments\__pycache__\test_moments_consistency_expanding.cpython-313.pyc
test_moments_consistency_expanding.cpython-313.pyc
Other
8,727
0.8
0
0
react-lib
289
2023-12-22T15:53:38.012274
BSD-3-Clause
true
d38a4ccc06a0822c13f8e2d629069163
\n\n
.venv\Lib\site-packages\pandas\tests\window\moments\__pycache__\test_moments_consistency_rolling.cpython-313.pyc
test_moments_consistency_rolling.cpython-313.pyc
Other
9,660
0.8
0
0.008772
awesome-app
83
2024-05-18T11:43:16.291900
GPL-3.0
true
83e3051a5a118e434c5800ec34aa3296
\n\n
.venv\Lib\site-packages\pandas\tests\window\moments\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
202
0.7
0
0
python-kit
384
2024-01-02T06:09:52.439466
Apache-2.0
true
7b80aa065513c412ac32f9efad7d5a54
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\conftest.cpython-313.pyc
conftest.cpython-313.pyc
Other
5,375
0.8
0.196078
0
react-lib
682
2025-05-18T03:05:14.712157
BSD-3-Clause
true
56d644539350d22cb4a49fb1ee14dfa5
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_api.cpython-313.pyc
test_api.cpython-313.pyc
Other
21,761
0.8
0.009119
0.00339
react-lib
936
2024-02-11T20:46:01.385959
BSD-3-Clause
true
2e8e4db8845cb1ef08a590f4d397c054
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_apply.cpython-313.pyc
test_apply.cpython-313.pyc
Other
19,978
0.8
0.00722
0.019531
python-kit
470
2025-02-04T09:20:29.665113
GPL-3.0
true
ced9a7ab2442a77cae16609217bff0f1
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_base_indexer.cpython-313.pyc
test_base_indexer.cpython-313.pyc
Other
23,745
0.8
0
0.010753
node-utils
116
2024-08-26T03:21:43.434013
GPL-3.0
true
d21701f389a8f0586fb71526d44a03cd
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_cython_aggregations.cpython-313.pyc
test_cython_aggregations.cpython-313.pyc
Other
5,536
0.95
0.0125
0
python-kit
382
2025-06-01T21:16:12.218036
MIT
true
7240cb58fbed4db94406dbd8157b1c49
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_dtypes.cpython-313.pyc
test_dtypes.cpython-313.pyc
Other
8,461
0.8
0.008621
0
vue-tools
722
2024-07-18T20:58:52.905023
Apache-2.0
true
59dd95d414677f5d71a6a8a3eec6ff29
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_ewm.cpython-313.pyc
test_ewm.cpython-313.pyc
Other
38,128
0.8
0.003774
0.004016
python-kit
575
2023-08-27T08:13:11.312721
GPL-3.0
true
960914d5c81d75dd496a918c0162f459
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_expanding.cpython-313.pyc
test_expanding.cpython-313.pyc
Other
42,964
0.95
0.00202
0.025532
python-kit
701
2024-12-10T11:23:48.968711
GPL-3.0
true
6d0a3850becae7752ba62f38f1ea060c
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_groupby.cpython-313.pyc
test_groupby.cpython-313.pyc
Other
65,885
0.6
0.00128
0.010471
vue-tools
233
2023-12-29T09:37:24.888707
GPL-3.0
true
5325482abcf85aaee008e41a71b15771
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_numba.cpython-313.pyc
test_numba.cpython-313.pyc
Other
24,320
0.95
0.00295
0
node-utils
488
2023-08-22T19:26:10.771286
BSD-3-Clause
true
94cc61af6758ed1f9b7921d9e9a700c5
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_online.cpython-313.pyc
test_online.cpython-313.pyc
Other
6,072
0.95
0
0
node-utils
358
2024-10-22T23:45:35.079499
BSD-3-Clause
true
7c2cc45f7ef054602689714bfe4f799c
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_pairwise.cpython-313.pyc
test_pairwise.cpython-313.pyc
Other
28,454
0.95
0.007491
0
react-lib
327
2025-05-16T23:12:20.357871
BSD-3-Clause
true
8cf52f0821d96a40f8c12558f9d7cc4b
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_rolling.cpython-313.pyc
test_rolling.cpython-313.pyc
Other
86,763
0.75
0.002475
0.020815
awesome-app
816
2023-08-27T01:57:38.862885
Apache-2.0
true
9b764d029ecf91b9299b3b99c2e770d3
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_rolling_functions.cpython-313.pyc
test_rolling_functions.cpython-313.pyc
Other
33,198
0.95
0
0.012
node-utils
1
2023-09-10T12:24:17.881905
Apache-2.0
true
a73aea6a11e96a65818b7d1602cf0184
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_rolling_quantile.cpython-313.pyc
test_rolling_quantile.cpython-313.pyc
Other
11,154
0.8
0
0.030769
node-utils
24
2024-05-09T02:44:57.796381
MIT
true
981be3d40bebf3b99226819c304bc7e6
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_rolling_skew_kurt.cpython-313.pyc
test_rolling_skew_kurt.cpython-313.pyc
Other
14,189
0.95
0
0.019417
vue-tools
628
2025-04-16T09:16:45.921302
GPL-3.0
true
75e28e2e1baa55435da2b1915195a5ac
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_timeseries_window.cpython-313.pyc
test_timeseries_window.cpython-313.pyc
Other
36,641
0.8
0.002342
0.002421
awesome-app
611
2024-07-09T21:55:08.987497
MIT
true
5b58fb92d133834265e3cbebb24fa6d8
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\test_win_type.cpython-313.pyc
test_win_type.cpython-313.pyc
Other
26,703
0.95
0.008451
0.002849
node-utils
715
2023-10-05T12:20:05.093435
GPL-3.0
true
97d8ae9ada5ab9d02fcebcda8b3def0c
\n\n
.venv\Lib\site-packages\pandas\tests\window\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
194
0.7
0
0
vue-tools
546
2024-02-20T04:06:52.038433
Apache-2.0
true
2f1f5c1cefcf085574275baab6d793f0
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_aggregation.cpython-313.pyc
test_aggregation.cpython-313.pyc
Other
4,221
0.8
0
0
react-lib
715
2024-01-24T14:05:41.721494
Apache-2.0
true
1f927abdb079cbb24346e37ace94a921
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_common.cpython-313.pyc
test_common.cpython-313.pyc
Other
14,963
0.95
0.011834
0.006061
vue-tools
407
2025-04-21T00:02:08.690320
GPL-3.0
true
96ae6801d1de1b482407147dc6a70aa2
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_downstream.cpython-313.pyc
test_downstream.cpython-313.pyc
Other
16,432
0.95
0
0.019231
node-utils
114
2025-02-04T12:46:58.870011
MIT
true
07a63957f5fce42c42c1d0045ddb9f6f
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_errors.cpython-313.pyc
test_errors.cpython-313.pyc
Other
4,268
0.95
0.0625
0
vue-tools
731
2023-09-10T08:38:52.031473
Apache-2.0
true
896dd1940c5c740cf75a8bed3bb95111
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_expressions.cpython-313.pyc
test_expressions.cpython-313.pyc
Other
23,389
0.95
0.008929
0
awesome-app
730
2023-08-19T19:55:46.319900
MIT
true
45047852827d01a3484b66497e939736
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_flags.cpython-313.pyc
test_flags.cpython-313.pyc
Other
3,206
0.8
0
0.021739
awesome-app
727
2025-03-07T23:35:55.498110
MIT
true
75d709df2074842e999def9ba107f59c
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_multilevel.cpython-313.pyc
test_multilevel.cpython-313.pyc
Other
19,096
0.8
0
0.01087
vue-tools
846
2024-10-06T11:52:23.731306
GPL-3.0
true
bdd72e3869f37ec5ce30bbc3069e64b2
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_nanops.cpython-313.pyc
test_nanops.cpython-313.pyc
Other
67,131
0.75
0
0.027944
python-kit
325
2025-05-30T11:38:42.681510
Apache-2.0
true
720441de2ae05a81b7f7b18a066ec9a1
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_optional_dependency.cpython-313.pyc
test_optional_dependency.cpython-313.pyc
Other
4,592
0.95
0
0.088235
vue-tools
956
2025-02-17T11:44:10.064555
GPL-3.0
true
8fcb33d38adcbe24280974a71a3c9461
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_register_accessor.cpython-313.pyc
test_register_accessor.cpython-313.pyc
Other
6,994
0.8
0
0.032258
python-kit
830
2024-05-30T03:08:30.713445
MIT
true
271c604093478a6c88c6ba9bec2a233a
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_sorting.cpython-313.pyc
test_sorting.cpython-313.pyc
Other
27,308
0.8
0
0.023529
react-lib
629
2024-08-13T16:37:21.702675
Apache-2.0
true
b5e609f0b7e3c0932e2bfa58c9e8b960
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\test_take.cpython-313.pyc
test_take.cpython-313.pyc
Other
19,789
0.8
0.005263
0
awesome-app
138
2024-07-29T09:16:49.404524
MIT
true
36a0484c040d0b53400e5aaa79189a52
\n\n
.venv\Lib\site-packages\pandas\tests\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
187
0.7
0
0
vue-tools
523
2025-06-24T18:34:58.198063
Apache-2.0
true
68839872fd10af482686404cc95bed9d
"""\nTimeseries API\n"""\n\nfrom pandas._libs.tslibs.parsing import guess_datetime_format\n\nfrom pandas.tseries import offsets\nfrom pandas.tseries.frequencies import infer_freq\n\n__all__ = ["infer_freq", "offsets", "guess_datetime_format"]\n
.venv\Lib\site-packages\pandas\tseries\api.py
api.py
Python
234
0.85
0
0
react-lib
749
2025-05-15T06:09:08.940997
MIT
false
654ccd386a2fd233729b0f68968cdfd8
from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nfrom pandas._libs import lib\nfrom pandas._libs.algos import unique_deltas\nfrom pandas._libs.tslibs import (\n Timestamp,\n get_unit_from_dtype,\n periods_per_day,\n tz_convert_from_utc,\n)\nfrom pandas._libs.tslibs.ccalendar import (\n DAYS,\n MONTH_ALIASES,\n MONTH_NUMBERS,\n MONTHS,\n int_to_weekday,\n)\nfrom pandas._libs.tslibs.dtypes import (\n OFFSET_TO_PERIOD_FREQSTR,\n freq_to_period_freqstr,\n)\nfrom pandas._libs.tslibs.fields import (\n build_field_sarray,\n month_position_check,\n)\nfrom pandas._libs.tslibs.offsets import (\n DateOffset,\n Day,\n to_offset,\n)\nfrom pandas._libs.tslibs.parsing import get_rule_month\nfrom pandas.util._decorators import cache_readonly\n\nfrom pandas.core.dtypes.common import is_numeric_dtype\nfrom pandas.core.dtypes.dtypes import (\n DatetimeTZDtype,\n PeriodDtype,\n)\nfrom pandas.core.dtypes.generic import (\n ABCIndex,\n ABCSeries,\n)\n\nfrom pandas.core.algorithms import unique\n\nif TYPE_CHECKING:\n from pandas._typing import npt\n\n from pandas import (\n DatetimeIndex,\n Series,\n TimedeltaIndex,\n )\n from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin\n# --------------------------------------------------------------------\n# Offset related functions\n\n_need_suffix = ["QS", "BQE", "BQS", "YS", "BYE", "BYS"]\n\nfor _prefix in _need_suffix:\n for _m in MONTHS:\n key = f"{_prefix}-{_m}"\n OFFSET_TO_PERIOD_FREQSTR[key] = OFFSET_TO_PERIOD_FREQSTR[_prefix]\n\nfor _prefix in ["Y", "Q"]:\n for _m in MONTHS:\n _alias = f"{_prefix}-{_m}"\n OFFSET_TO_PERIOD_FREQSTR[_alias] = _alias\n\nfor _d in DAYS:\n OFFSET_TO_PERIOD_FREQSTR[f"W-{_d}"] = f"W-{_d}"\n\n\ndef get_period_alias(offset_str: str) -> str | None:\n """\n Alias to closest period strings BQ->Q etc.\n """\n return OFFSET_TO_PERIOD_FREQSTR.get(offset_str, None)\n\n\n# ---------------------------------------------------------------------\n# Period codes\n\n\ndef infer_freq(\n index: DatetimeIndex | TimedeltaIndex | Series | DatetimeLikeArrayMixin,\n) -> str | None:\n """\n Infer the most likely frequency given the input index.\n\n Parameters\n ----------\n index : DatetimeIndex, TimedeltaIndex, Series or array-like\n If passed a Series will use the values of the series (NOT THE INDEX).\n\n Returns\n -------\n str or None\n None if no discernible frequency.\n\n Raises\n ------\n TypeError\n If the index is not datetime-like.\n ValueError\n If there are fewer than three values.\n\n Examples\n --------\n >>> idx = pd.date_range(start='2020/12/01', end='2020/12/30', periods=30)\n >>> pd.infer_freq(idx)\n 'D'\n """\n from pandas.core.api import DatetimeIndex\n\n if isinstance(index, ABCSeries):\n values = index._values\n if not (\n lib.is_np_dtype(values.dtype, "mM")\n or isinstance(values.dtype, DatetimeTZDtype)\n or values.dtype == object\n ):\n raise TypeError(\n "cannot infer freq from a non-convertible dtype "\n f"on a Series of {index.dtype}"\n )\n index = values\n\n inferer: _FrequencyInferer\n\n if not hasattr(index, "dtype"):\n pass\n elif isinstance(index.dtype, PeriodDtype):\n raise TypeError(\n "PeriodIndex given. Check the `freq` attribute "\n "instead of using infer_freq."\n )\n elif lib.is_np_dtype(index.dtype, "m"):\n # Allow TimedeltaIndex and TimedeltaArray\n inferer = _TimedeltaFrequencyInferer(index)\n return inferer.get_freq()\n\n elif is_numeric_dtype(index.dtype):\n raise TypeError(\n f"cannot infer freq from a non-convertible index of dtype {index.dtype}"\n )\n\n if not isinstance(index, DatetimeIndex):\n index = DatetimeIndex(index)\n\n inferer = _FrequencyInferer(index)\n return inferer.get_freq()\n\n\nclass _FrequencyInferer:\n """\n Not sure if I can avoid the state machine here\n """\n\n def __init__(self, index) -> None:\n self.index = index\n self.i8values = index.asi8\n\n # For get_unit_from_dtype we need the dtype to the underlying ndarray,\n # which for tz-aware is not the same as index.dtype\n if isinstance(index, ABCIndex):\n # error: Item "ndarray[Any, Any]" of "Union[ExtensionArray,\n # ndarray[Any, Any]]" has no attribute "_ndarray"\n self._creso = get_unit_from_dtype(\n index._data._ndarray.dtype # type: ignore[union-attr]\n )\n else:\n # otherwise we have DTA/TDA\n self._creso = get_unit_from_dtype(index._ndarray.dtype)\n\n # This moves the values, which are implicitly in UTC, to the\n # the timezone so they are in local time\n if hasattr(index, "tz"):\n if index.tz is not None:\n self.i8values = tz_convert_from_utc(\n self.i8values, index.tz, reso=self._creso\n )\n\n if len(index) < 3:\n raise ValueError("Need at least 3 dates to infer frequency")\n\n self.is_monotonic = (\n self.index._is_monotonic_increasing or self.index._is_monotonic_decreasing\n )\n\n @cache_readonly\n def deltas(self) -> npt.NDArray[np.int64]:\n return unique_deltas(self.i8values)\n\n @cache_readonly\n def deltas_asi8(self) -> npt.NDArray[np.int64]:\n # NB: we cannot use self.i8values here because we may have converted\n # the tz in __init__\n return unique_deltas(self.index.asi8)\n\n @cache_readonly\n def is_unique(self) -> bool:\n return len(self.deltas) == 1\n\n @cache_readonly\n def is_unique_asi8(self) -> bool:\n return len(self.deltas_asi8) == 1\n\n def get_freq(self) -> str | None:\n """\n Find the appropriate frequency string to describe the inferred\n frequency of self.i8values\n\n Returns\n -------\n str or None\n """\n if not self.is_monotonic or not self.index._is_unique:\n return None\n\n delta = self.deltas[0]\n ppd = periods_per_day(self._creso)\n if delta and _is_multiple(delta, ppd):\n return self._infer_daily_rule()\n\n # Business hourly, maybe. 17: one day / 65: one weekend\n if self.hour_deltas in ([1, 17], [1, 65], [1, 17, 65]):\n return "bh"\n\n # Possibly intraday frequency. Here we use the\n # original .asi8 values as the modified values\n # will not work around DST transitions. See #8772\n if not self.is_unique_asi8:\n return None\n\n delta = self.deltas_asi8[0]\n pph = ppd // 24\n ppm = pph // 60\n pps = ppm // 60\n if _is_multiple(delta, pph):\n # Hours\n return _maybe_add_count("h", delta / pph)\n elif _is_multiple(delta, ppm):\n # Minutes\n return _maybe_add_count("min", delta / ppm)\n elif _is_multiple(delta, pps):\n # Seconds\n return _maybe_add_count("s", delta / pps)\n elif _is_multiple(delta, (pps // 1000)):\n # Milliseconds\n return _maybe_add_count("ms", delta / (pps // 1000))\n elif _is_multiple(delta, (pps // 1_000_000)):\n # Microseconds\n return _maybe_add_count("us", delta / (pps // 1_000_000))\n else:\n # Nanoseconds\n return _maybe_add_count("ns", delta)\n\n @cache_readonly\n def day_deltas(self) -> list[int]:\n ppd = periods_per_day(self._creso)\n return [x / ppd for x in self.deltas]\n\n @cache_readonly\n def hour_deltas(self) -> list[int]:\n pph = periods_per_day(self._creso) // 24\n return [x / pph for x in self.deltas]\n\n @cache_readonly\n def fields(self) -> np.ndarray: # structured array of fields\n return build_field_sarray(self.i8values, reso=self._creso)\n\n @cache_readonly\n def rep_stamp(self) -> Timestamp:\n return Timestamp(self.i8values[0], unit=self.index.unit)\n\n def month_position_check(self) -> str | None:\n return month_position_check(self.fields, self.index.dayofweek)\n\n @cache_readonly\n def mdiffs(self) -> npt.NDArray[np.int64]:\n nmonths = self.fields["Y"] * 12 + self.fields["M"]\n return unique_deltas(nmonths.astype("i8"))\n\n @cache_readonly\n def ydiffs(self) -> npt.NDArray[np.int64]:\n return unique_deltas(self.fields["Y"].astype("i8"))\n\n def _infer_daily_rule(self) -> str | None:\n annual_rule = self._get_annual_rule()\n if annual_rule:\n nyears = self.ydiffs[0]\n month = MONTH_ALIASES[self.rep_stamp.month]\n alias = f"{annual_rule}-{month}"\n return _maybe_add_count(alias, nyears)\n\n quarterly_rule = self._get_quarterly_rule()\n if quarterly_rule:\n nquarters = self.mdiffs[0] / 3\n mod_dict = {0: 12, 2: 11, 1: 10}\n month = MONTH_ALIASES[mod_dict[self.rep_stamp.month % 3]]\n alias = f"{quarterly_rule}-{month}"\n return _maybe_add_count(alias, nquarters)\n\n monthly_rule = self._get_monthly_rule()\n if monthly_rule:\n return _maybe_add_count(monthly_rule, self.mdiffs[0])\n\n if self.is_unique:\n return self._get_daily_rule()\n\n if self._is_business_daily():\n return "B"\n\n wom_rule = self._get_wom_rule()\n if wom_rule:\n return wom_rule\n\n return None\n\n def _get_daily_rule(self) -> str | None:\n ppd = periods_per_day(self._creso)\n days = self.deltas[0] / ppd\n if days % 7 == 0:\n # Weekly\n wd = int_to_weekday[self.rep_stamp.weekday()]\n alias = f"W-{wd}"\n return _maybe_add_count(alias, days / 7)\n else:\n return _maybe_add_count("D", days)\n\n def _get_annual_rule(self) -> str | None:\n if len(self.ydiffs) > 1:\n return None\n\n if len(unique(self.fields["M"])) > 1:\n return None\n\n pos_check = self.month_position_check()\n\n if pos_check is None:\n return None\n else:\n return {"cs": "YS", "bs": "BYS", "ce": "YE", "be": "BYE"}.get(pos_check)\n\n def _get_quarterly_rule(self) -> str | None:\n if len(self.mdiffs) > 1:\n return None\n\n if not self.mdiffs[0] % 3 == 0:\n return None\n\n pos_check = self.month_position_check()\n\n if pos_check is None:\n return None\n else:\n return {"cs": "QS", "bs": "BQS", "ce": "QE", "be": "BQE"}.get(pos_check)\n\n def _get_monthly_rule(self) -> str | None:\n if len(self.mdiffs) > 1:\n return None\n pos_check = self.month_position_check()\n\n if pos_check is None:\n return None\n else:\n return {"cs": "MS", "bs": "BMS", "ce": "ME", "be": "BME"}.get(pos_check)\n\n def _is_business_daily(self) -> bool:\n # quick check: cannot be business daily\n if self.day_deltas != [1, 3]:\n return False\n\n # probably business daily, but need to confirm\n first_weekday = self.index[0].weekday()\n shifts = np.diff(self.i8values)\n ppd = periods_per_day(self._creso)\n shifts = np.floor_divide(shifts, ppd)\n weekdays = np.mod(first_weekday + np.cumsum(shifts), 7)\n\n return bool(\n np.all(\n ((weekdays == 0) & (shifts == 3))\n | ((weekdays > 0) & (weekdays <= 4) & (shifts == 1))\n )\n )\n\n def _get_wom_rule(self) -> str | None:\n weekdays = unique(self.index.weekday)\n if len(weekdays) > 1:\n return None\n\n week_of_months = unique((self.index.day - 1) // 7)\n # Only attempt to infer up to WOM-4. See #9425\n week_of_months = week_of_months[week_of_months < 4]\n if len(week_of_months) == 0 or len(week_of_months) > 1:\n return None\n\n # get which week\n week = week_of_months[0] + 1\n wd = int_to_weekday[weekdays[0]]\n\n return f"WOM-{week}{wd}"\n\n\nclass _TimedeltaFrequencyInferer(_FrequencyInferer):\n def _infer_daily_rule(self):\n if self.is_unique:\n return self._get_daily_rule()\n\n\ndef _is_multiple(us, mult: int) -> bool:\n return us % mult == 0\n\n\ndef _maybe_add_count(base: str, count: float) -> str:\n if count != 1:\n assert count == int(count)\n count = int(count)\n return f"{count}{base}"\n else:\n return base\n\n\n# ----------------------------------------------------------------------\n# Frequency comparison\n\n\ndef is_subperiod(source, target) -> bool:\n """\n Returns True if downsampling is possible between source and target\n frequencies\n\n Parameters\n ----------\n source : str or DateOffset\n Frequency converting from\n target : str or DateOffset\n Frequency converting to\n\n Returns\n -------\n bool\n """\n if target is None or source is None:\n return False\n source = _maybe_coerce_freq(source)\n target = _maybe_coerce_freq(target)\n\n if _is_annual(target):\n if _is_quarterly(source):\n return _quarter_months_conform(\n get_rule_month(source), get_rule_month(target)\n )\n return source in {"D", "C", "B", "M", "h", "min", "s", "ms", "us", "ns"}\n elif _is_quarterly(target):\n return source in {"D", "C", "B", "M", "h", "min", "s", "ms", "us", "ns"}\n elif _is_monthly(target):\n return source in {"D", "C", "B", "h", "min", "s", "ms", "us", "ns"}\n elif _is_weekly(target):\n return source in {target, "D", "C", "B", "h", "min", "s", "ms", "us", "ns"}\n elif target == "B":\n return source in {"B", "h", "min", "s", "ms", "us", "ns"}\n elif target == "C":\n return source in {"C", "h", "min", "s", "ms", "us", "ns"}\n elif target == "D":\n return source in {"D", "h", "min", "s", "ms", "us", "ns"}\n elif target == "h":\n return source in {"h", "min", "s", "ms", "us", "ns"}\n elif target == "min":\n return source in {"min", "s", "ms", "us", "ns"}\n elif target == "s":\n return source in {"s", "ms", "us", "ns"}\n elif target == "ms":\n return source in {"ms", "us", "ns"}\n elif target == "us":\n return source in {"us", "ns"}\n elif target == "ns":\n return source in {"ns"}\n else:\n return False\n\n\ndef is_superperiod(source, target) -> bool:\n """\n Returns True if upsampling is possible between source and target\n frequencies\n\n Parameters\n ----------\n source : str or DateOffset\n Frequency converting from\n target : str or DateOffset\n Frequency converting to\n\n Returns\n -------\n bool\n """\n if target is None or source is None:\n return False\n source = _maybe_coerce_freq(source)\n target = _maybe_coerce_freq(target)\n\n if _is_annual(source):\n if _is_annual(target):\n return get_rule_month(source) == get_rule_month(target)\n\n if _is_quarterly(target):\n smonth = get_rule_month(source)\n tmonth = get_rule_month(target)\n return _quarter_months_conform(smonth, tmonth)\n return target in {"D", "C", "B", "M", "h", "min", "s", "ms", "us", "ns"}\n elif _is_quarterly(source):\n return target in {"D", "C", "B", "M", "h", "min", "s", "ms", "us", "ns"}\n elif _is_monthly(source):\n return target in {"D", "C", "B", "h", "min", "s", "ms", "us", "ns"}\n elif _is_weekly(source):\n return target in {source, "D", "C", "B", "h", "min", "s", "ms", "us", "ns"}\n elif source == "B":\n return target in {"D", "C", "B", "h", "min", "s", "ms", "us", "ns"}\n elif source == "C":\n return target in {"D", "C", "B", "h", "min", "s", "ms", "us", "ns"}\n elif source == "D":\n return target in {"D", "C", "B", "h", "min", "s", "ms", "us", "ns"}\n elif source == "h":\n return target in {"h", "min", "s", "ms", "us", "ns"}\n elif source == "min":\n return target in {"min", "s", "ms", "us", "ns"}\n elif source == "s":\n return target in {"s", "ms", "us", "ns"}\n elif source == "ms":\n return target in {"ms", "us", "ns"}\n elif source == "us":\n return target in {"us", "ns"}\n elif source == "ns":\n return target in {"ns"}\n else:\n return False\n\n\ndef _maybe_coerce_freq(code) -> str:\n """we might need to coerce a code to a rule_code\n and uppercase it\n\n Parameters\n ----------\n source : str or DateOffset\n Frequency converting from\n\n Returns\n -------\n str\n """\n assert code is not None\n if isinstance(code, DateOffset):\n code = freq_to_period_freqstr(1, code.name)\n if code in {"h", "min", "s", "ms", "us", "ns"}:\n return code\n else:\n return code.upper()\n\n\ndef _quarter_months_conform(source: str, target: str) -> bool:\n snum = MONTH_NUMBERS[source]\n tnum = MONTH_NUMBERS[target]\n return snum % 3 == tnum % 3\n\n\ndef _is_annual(rule: str) -> bool:\n rule = rule.upper()\n return rule == "Y" or rule.startswith("Y-")\n\n\ndef _is_quarterly(rule: str) -> bool:\n rule = rule.upper()\n return rule == "Q" or rule.startswith(("Q-", "BQ"))\n\n\ndef _is_monthly(rule: str) -> bool:\n rule = rule.upper()\n return rule in ("M", "BM")\n\n\ndef _is_weekly(rule: str) -> bool:\n rule = rule.upper()\n return rule == "W" or rule.startswith("W-")\n\n\n__all__ = [\n "Day",\n "get_period_alias",\n "infer_freq",\n "is_subperiod",\n "is_superperiod",\n "to_offset",\n]\n
.venv\Lib\site-packages\pandas\tseries\frequencies.py
frequencies.py
Python
17,686
0.95
0.149502
0.063136
python-kit
135
2024-11-13T15:43:56.774406
Apache-2.0
false
01498f8aed6d8db3e0aa0b2856c9a0e9
from __future__ import annotations\n\nfrom datetime import (\n datetime,\n timedelta,\n)\nimport warnings\n\nfrom dateutil.relativedelta import (\n FR,\n MO,\n SA,\n SU,\n TH,\n TU,\n WE,\n)\nimport numpy as np\n\nfrom pandas.errors import PerformanceWarning\n\nfrom pandas import (\n DateOffset,\n DatetimeIndex,\n Series,\n Timestamp,\n concat,\n date_range,\n)\n\nfrom pandas.tseries.offsets import (\n Day,\n Easter,\n)\n\n\ndef next_monday(dt: datetime) -> datetime:\n """\n If holiday falls on Saturday, use following Monday instead;\n if holiday falls on Sunday, use Monday instead\n """\n if dt.weekday() == 5:\n return dt + timedelta(2)\n elif dt.weekday() == 6:\n return dt + timedelta(1)\n return dt\n\n\ndef next_monday_or_tuesday(dt: datetime) -> datetime:\n """\n For second holiday of two adjacent ones!\n If holiday falls on Saturday, use following Monday instead;\n if holiday falls on Sunday or Monday, use following Tuesday instead\n (because Monday is already taken by adjacent holiday on the day before)\n """\n dow = dt.weekday()\n if dow in (5, 6):\n return dt + timedelta(2)\n if dow == 0:\n return dt + timedelta(1)\n return dt\n\n\ndef previous_friday(dt: datetime) -> datetime:\n """\n If holiday falls on Saturday or Sunday, use previous Friday instead.\n """\n if dt.weekday() == 5:\n return dt - timedelta(1)\n elif dt.weekday() == 6:\n return dt - timedelta(2)\n return dt\n\n\ndef sunday_to_monday(dt: datetime) -> datetime:\n """\n If holiday falls on Sunday, use day thereafter (Monday) instead.\n """\n if dt.weekday() == 6:\n return dt + timedelta(1)\n return dt\n\n\ndef weekend_to_monday(dt: datetime) -> datetime:\n """\n If holiday falls on Sunday or Saturday,\n use day thereafter (Monday) instead.\n Needed for holidays such as Christmas observation in Europe\n """\n if dt.weekday() == 6:\n return dt + timedelta(1)\n elif dt.weekday() == 5:\n return dt + timedelta(2)\n return dt\n\n\ndef nearest_workday(dt: datetime) -> datetime:\n """\n If holiday falls on Saturday, use day before (Friday) instead;\n if holiday falls on Sunday, use day thereafter (Monday) instead.\n """\n if dt.weekday() == 5:\n return dt - timedelta(1)\n elif dt.weekday() == 6:\n return dt + timedelta(1)\n return dt\n\n\ndef next_workday(dt: datetime) -> datetime:\n """\n returns next weekday used for observances\n """\n dt += timedelta(days=1)\n while dt.weekday() > 4:\n # Mon-Fri are 0-4\n dt += timedelta(days=1)\n return dt\n\n\ndef previous_workday(dt: datetime) -> datetime:\n """\n returns previous weekday used for observances\n """\n dt -= timedelta(days=1)\n while dt.weekday() > 4:\n # Mon-Fri are 0-4\n dt -= timedelta(days=1)\n return dt\n\n\ndef before_nearest_workday(dt: datetime) -> datetime:\n """\n returns previous workday after nearest workday\n """\n return previous_workday(nearest_workday(dt))\n\n\ndef after_nearest_workday(dt: datetime) -> datetime:\n """\n returns next workday after nearest workday\n needed for Boxing day or multiple holidays in a series\n """\n return next_workday(nearest_workday(dt))\n\n\nclass Holiday:\n """\n Class that defines a holiday with start/end dates and rules\n for observance.\n """\n\n start_date: Timestamp | None\n end_date: Timestamp | None\n days_of_week: tuple[int, ...] | None\n\n def __init__(\n self,\n name: str,\n year=None,\n month=None,\n day=None,\n offset=None,\n observance=None,\n start_date=None,\n end_date=None,\n days_of_week=None,\n ) -> None:\n """\n Parameters\n ----------\n name : str\n Name of the holiday , defaults to class name\n offset : array of pandas.tseries.offsets or\n class from pandas.tseries.offsets\n computes offset from date\n observance: function\n computes when holiday is given a pandas Timestamp\n days_of_week:\n provide a tuple of days e.g (0,1,2,3,) for Monday Through Thursday\n Monday=0,..,Sunday=6\n\n Examples\n --------\n >>> from dateutil.relativedelta import MO\n\n >>> USMemorialDay = pd.tseries.holiday.Holiday(\n ... "Memorial Day", month=5, day=31, offset=pd.DateOffset(weekday=MO(-1))\n ... )\n >>> USMemorialDay\n Holiday: Memorial Day (month=5, day=31, offset=<DateOffset: weekday=MO(-1)>)\n\n >>> USLaborDay = pd.tseries.holiday.Holiday(\n ... "Labor Day", month=9, day=1, offset=pd.DateOffset(weekday=MO(1))\n ... )\n >>> USLaborDay\n Holiday: Labor Day (month=9, day=1, offset=<DateOffset: weekday=MO(+1)>)\n\n >>> July3rd = pd.tseries.holiday.Holiday("July 3rd", month=7, day=3)\n >>> July3rd\n Holiday: July 3rd (month=7, day=3, )\n\n >>> NewYears = pd.tseries.holiday.Holiday(\n ... "New Years Day", month=1, day=1,\n ... observance=pd.tseries.holiday.nearest_workday\n ... )\n >>> NewYears # doctest: +SKIP\n Holiday: New Years Day (\n month=1, day=1, observance=<function nearest_workday at 0x66545e9bc440>\n )\n\n >>> July3rd = pd.tseries.holiday.Holiday(\n ... "July 3rd", month=7, day=3,\n ... days_of_week=(0, 1, 2, 3)\n ... )\n >>> July3rd\n Holiday: July 3rd (month=7, day=3, )\n """\n if offset is not None and observance is not None:\n raise NotImplementedError("Cannot use both offset and observance.")\n\n self.name = name\n self.year = year\n self.month = month\n self.day = day\n self.offset = offset\n self.start_date = (\n Timestamp(start_date) if start_date is not None else start_date\n )\n self.end_date = Timestamp(end_date) if end_date is not None else end_date\n self.observance = observance\n assert days_of_week is None or type(days_of_week) == tuple\n self.days_of_week = days_of_week\n\n def __repr__(self) -> str:\n info = ""\n if self.year is not None:\n info += f"year={self.year}, "\n info += f"month={self.month}, day={self.day}, "\n\n if self.offset is not None:\n info += f"offset={self.offset}"\n\n if self.observance is not None:\n info += f"observance={self.observance}"\n\n repr = f"Holiday: {self.name} ({info})"\n return repr\n\n def dates(\n self, start_date, end_date, return_name: bool = False\n ) -> Series | DatetimeIndex:\n """\n Calculate holidays observed between start date and end date\n\n Parameters\n ----------\n start_date : starting date, datetime-like, optional\n end_date : ending date, datetime-like, optional\n return_name : bool, optional, default=False\n If True, return a series that has dates and holiday names.\n False will only return dates.\n\n Returns\n -------\n Series or DatetimeIndex\n Series if return_name is True\n """\n start_date = Timestamp(start_date)\n end_date = Timestamp(end_date)\n\n filter_start_date = start_date\n filter_end_date = end_date\n\n if self.year is not None:\n dt = Timestamp(datetime(self.year, self.month, self.day))\n dti = DatetimeIndex([dt])\n if return_name:\n return Series(self.name, index=dti)\n else:\n return dti\n\n dates = self._reference_dates(start_date, end_date)\n holiday_dates = self._apply_rule(dates)\n if self.days_of_week is not None:\n holiday_dates = holiday_dates[\n np.isin(\n # error: "DatetimeIndex" has no attribute "dayofweek"\n holiday_dates.dayofweek, # type: ignore[attr-defined]\n self.days_of_week,\n ).ravel()\n ]\n\n if self.start_date is not None:\n filter_start_date = max(\n self.start_date.tz_localize(filter_start_date.tz), filter_start_date\n )\n if self.end_date is not None:\n filter_end_date = min(\n self.end_date.tz_localize(filter_end_date.tz), filter_end_date\n )\n holiday_dates = holiday_dates[\n (holiday_dates >= filter_start_date) & (holiday_dates <= filter_end_date)\n ]\n if return_name:\n return Series(self.name, index=holiday_dates)\n return holiday_dates\n\n def _reference_dates(\n self, start_date: Timestamp, end_date: Timestamp\n ) -> DatetimeIndex:\n """\n Get reference dates for the holiday.\n\n Return reference dates for the holiday also returning the year\n prior to the start_date and year following the end_date. This ensures\n that any offsets to be applied will yield the holidays within\n the passed in dates.\n """\n if self.start_date is not None:\n start_date = self.start_date.tz_localize(start_date.tz)\n\n if self.end_date is not None:\n end_date = self.end_date.tz_localize(start_date.tz)\n\n year_offset = DateOffset(years=1)\n reference_start_date = Timestamp(\n datetime(start_date.year - 1, self.month, self.day)\n )\n\n reference_end_date = Timestamp(\n datetime(end_date.year + 1, self.month, self.day)\n )\n # Don't process unnecessary holidays\n dates = date_range(\n start=reference_start_date,\n end=reference_end_date,\n freq=year_offset,\n tz=start_date.tz,\n )\n\n return dates\n\n def _apply_rule(self, dates: DatetimeIndex) -> DatetimeIndex:\n """\n Apply the given offset/observance to a DatetimeIndex of dates.\n\n Parameters\n ----------\n dates : DatetimeIndex\n Dates to apply the given offset/observance rule\n\n Returns\n -------\n Dates with rules applied\n """\n if dates.empty:\n return dates.copy()\n\n if self.observance is not None:\n return dates.map(lambda d: self.observance(d))\n\n if self.offset is not None:\n if not isinstance(self.offset, list):\n offsets = [self.offset]\n else:\n offsets = self.offset\n for offset in offsets:\n # if we are adding a non-vectorized value\n # ignore the PerformanceWarnings:\n with warnings.catch_warnings():\n warnings.simplefilter("ignore", PerformanceWarning)\n dates += offset\n return dates\n\n\nholiday_calendars = {}\n\n\ndef register(cls) -> None:\n try:\n name = cls.name\n except AttributeError:\n name = cls.__name__\n holiday_calendars[name] = cls\n\n\ndef get_calendar(name: str):\n """\n Return an instance of a calendar based on its name.\n\n Parameters\n ----------\n name : str\n Calendar name to return an instance of\n """\n return holiday_calendars[name]()\n\n\nclass HolidayCalendarMetaClass(type):\n def __new__(cls, clsname: str, bases, attrs):\n calendar_class = super().__new__(cls, clsname, bases, attrs)\n register(calendar_class)\n return calendar_class\n\n\nclass AbstractHolidayCalendar(metaclass=HolidayCalendarMetaClass):\n """\n Abstract interface to create holidays following certain rules.\n """\n\n rules: list[Holiday] = []\n start_date = Timestamp(datetime(1970, 1, 1))\n end_date = Timestamp(datetime(2200, 12, 31))\n _cache = None\n\n def __init__(self, name: str = "", rules=None) -> None:\n """\n Initializes holiday object with a given set a rules. Normally\n classes just have the rules defined within them.\n\n Parameters\n ----------\n name : str\n Name of the holiday calendar, defaults to class name\n rules : array of Holiday objects\n A set of rules used to create the holidays.\n """\n super().__init__()\n if not name:\n name = type(self).__name__\n self.name = name\n\n if rules is not None:\n self.rules = rules\n\n def rule_from_name(self, name: str):\n for rule in self.rules:\n if rule.name == name:\n return rule\n\n return None\n\n def holidays(self, start=None, end=None, return_name: bool = False):\n """\n Returns a curve with holidays between start_date and end_date\n\n Parameters\n ----------\n start : starting date, datetime-like, optional\n end : ending date, datetime-like, optional\n return_name : bool, optional\n If True, return a series that has dates and holiday names.\n False will only return a DatetimeIndex of dates.\n\n Returns\n -------\n DatetimeIndex of holidays\n """\n if self.rules is None:\n raise Exception(\n f"Holiday Calendar {self.name} does not have any rules specified"\n )\n\n if start is None:\n start = AbstractHolidayCalendar.start_date\n\n if end is None:\n end = AbstractHolidayCalendar.end_date\n\n start = Timestamp(start)\n end = Timestamp(end)\n\n # If we don't have a cache or the dates are outside the prior cache, we\n # get them again\n if self._cache is None or start < self._cache[0] or end > self._cache[1]:\n pre_holidays = [\n rule.dates(start, end, return_name=True) for rule in self.rules\n ]\n if pre_holidays:\n # error: Argument 1 to "concat" has incompatible type\n # "List[Union[Series, DatetimeIndex]]"; expected\n # "Union[Iterable[DataFrame], Mapping[<nothing>, DataFrame]]"\n holidays = concat(pre_holidays) # type: ignore[arg-type]\n else:\n # error: Incompatible types in assignment (expression has type\n # "Series", variable has type "DataFrame")\n holidays = Series(\n index=DatetimeIndex([]), dtype=object\n ) # type: ignore[assignment]\n\n self._cache = (start, end, holidays.sort_index())\n\n holidays = self._cache[2]\n holidays = holidays[start:end]\n\n if return_name:\n return holidays\n else:\n return holidays.index\n\n @staticmethod\n def merge_class(base, other):\n """\n Merge holiday calendars together. The base calendar\n will take precedence to other. The merge will be done\n based on each holiday's name.\n\n Parameters\n ----------\n base : AbstractHolidayCalendar\n instance/subclass or array of Holiday objects\n other : AbstractHolidayCalendar\n instance/subclass or array of Holiday objects\n """\n try:\n other = other.rules\n except AttributeError:\n pass\n\n if not isinstance(other, list):\n other = [other]\n other_holidays = {holiday.name: holiday for holiday in other}\n\n try:\n base = base.rules\n except AttributeError:\n pass\n\n if not isinstance(base, list):\n base = [base]\n base_holidays = {holiday.name: holiday for holiday in base}\n\n other_holidays.update(base_holidays)\n return list(other_holidays.values())\n\n def merge(self, other, inplace: bool = False):\n """\n Merge holiday calendars together. The caller's class\n rules take precedence. The merge will be done\n based on each holiday's name.\n\n Parameters\n ----------\n other : holiday calendar\n inplace : bool (default=False)\n If True set rule_table to holidays, else return array of Holidays\n """\n holidays = self.merge_class(self, other)\n if inplace:\n self.rules = holidays\n else:\n return holidays\n\n\nUSMemorialDay = Holiday(\n "Memorial Day", month=5, day=31, offset=DateOffset(weekday=MO(-1))\n)\nUSLaborDay = Holiday("Labor Day", month=9, day=1, offset=DateOffset(weekday=MO(1)))\nUSColumbusDay = Holiday(\n "Columbus Day", month=10, day=1, offset=DateOffset(weekday=MO(2))\n)\nUSThanksgivingDay = Holiday(\n "Thanksgiving Day", month=11, day=1, offset=DateOffset(weekday=TH(4))\n)\nUSMartinLutherKingJr = Holiday(\n "Birthday of Martin Luther King, Jr.",\n start_date=datetime(1986, 1, 1),\n month=1,\n day=1,\n offset=DateOffset(weekday=MO(3)),\n)\nUSPresidentsDay = Holiday(\n "Washington's Birthday", month=2, day=1, offset=DateOffset(weekday=MO(3))\n)\nGoodFriday = Holiday("Good Friday", month=1, day=1, offset=[Easter(), Day(-2)])\n\nEasterMonday = Holiday("Easter Monday", month=1, day=1, offset=[Easter(), Day(1)])\n\n\nclass USFederalHolidayCalendar(AbstractHolidayCalendar):\n """\n US Federal Government Holiday Calendar based on rules specified by:\n https://www.opm.gov/policy-data-oversight/pay-leave/federal-holidays/\n """\n\n rules = [\n Holiday("New Year's Day", month=1, day=1, observance=nearest_workday),\n USMartinLutherKingJr,\n USPresidentsDay,\n USMemorialDay,\n Holiday(\n "Juneteenth National Independence Day",\n month=6,\n day=19,\n start_date="2021-06-18",\n observance=nearest_workday,\n ),\n Holiday("Independence Day", month=7, day=4, observance=nearest_workday),\n USLaborDay,\n USColumbusDay,\n Holiday("Veterans Day", month=11, day=11, observance=nearest_workday),\n USThanksgivingDay,\n Holiday("Christmas Day", month=12, day=25, observance=nearest_workday),\n ]\n\n\ndef HolidayCalendarFactory(name: str, base, other, base_class=AbstractHolidayCalendar):\n rules = AbstractHolidayCalendar.merge_class(base, other)\n calendar_class = type(name, (base_class,), {"rules": rules, "name": name})\n return calendar_class\n\n\n__all__ = [\n "after_nearest_workday",\n "before_nearest_workday",\n "FR",\n "get_calendar",\n "HolidayCalendarFactory",\n "MO",\n "nearest_workday",\n "next_monday",\n "next_monday_or_tuesday",\n "next_workday",\n "previous_friday",\n "previous_workday",\n "register",\n "SA",\n "SU",\n "sunday_to_monday",\n "TH",\n "TU",\n "WE",\n "weekend_to_monday",\n]\n
.venv\Lib\site-packages\pandas\tseries\holiday.py
holiday.py
Python
18,596
0.95
0.148265
0.024482
vue-tools
201
2025-03-10T07:27:04.981502
MIT
false
4be9fc6ee87d160fa3ed71b173559ade
from __future__ import annotations\n\nfrom pandas._libs.tslibs.offsets import (\n FY5253,\n BaseOffset,\n BDay,\n BMonthBegin,\n BMonthEnd,\n BQuarterBegin,\n BQuarterEnd,\n BusinessDay,\n BusinessHour,\n BusinessMonthBegin,\n BusinessMonthEnd,\n BYearBegin,\n BYearEnd,\n CBMonthBegin,\n CBMonthEnd,\n CDay,\n CustomBusinessDay,\n CustomBusinessHour,\n CustomBusinessMonthBegin,\n CustomBusinessMonthEnd,\n DateOffset,\n Day,\n Easter,\n FY5253Quarter,\n Hour,\n LastWeekOfMonth,\n Micro,\n Milli,\n Minute,\n MonthBegin,\n MonthEnd,\n Nano,\n QuarterBegin,\n QuarterEnd,\n Second,\n SemiMonthBegin,\n SemiMonthEnd,\n Tick,\n Week,\n WeekOfMonth,\n YearBegin,\n YearEnd,\n)\n\n__all__ = [\n "Day",\n "BaseOffset",\n "BusinessDay",\n "BusinessMonthBegin",\n "BusinessMonthEnd",\n "BDay",\n "CustomBusinessDay",\n "CustomBusinessMonthBegin",\n "CustomBusinessMonthEnd",\n "CDay",\n "CBMonthEnd",\n "CBMonthBegin",\n "MonthBegin",\n "BMonthBegin",\n "MonthEnd",\n "BMonthEnd",\n "SemiMonthEnd",\n "SemiMonthBegin",\n "BusinessHour",\n "CustomBusinessHour",\n "YearBegin",\n "BYearBegin",\n "YearEnd",\n "BYearEnd",\n "QuarterBegin",\n "BQuarterBegin",\n "QuarterEnd",\n "BQuarterEnd",\n "LastWeekOfMonth",\n "FY5253Quarter",\n "FY5253",\n "Week",\n "WeekOfMonth",\n "Easter",\n "Tick",\n "Hour",\n "Minute",\n "Second",\n "Milli",\n "Micro",\n "Nano",\n "DateOffset",\n]\n
.venv\Lib\site-packages\pandas\tseries\offsets.py
offsets.py
Python
1,531
0.85
0
0
node-utils
270
2023-09-30T10:13:36.633687
MIT
false
96d766d9003c32f92747bdbae7d2ab6a
# ruff: noqa: TCH004\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n # import modules that have public classes/functions:\n from pandas.tseries import (\n frequencies,\n offsets,\n )\n\n # and mark only those modules as public\n __all__ = ["frequencies", "offsets"]\n
.venv\Lib\site-packages\pandas\tseries\__init__.py
__init__.py
Python
293
0.95
0.083333
0.3
node-utils
119
2024-10-29T02:47:14.126385
GPL-3.0
false
53f9a6ed4d731ea6f749e341e6a9de78
\n\n
.venv\Lib\site-packages\pandas\tseries\__pycache__\api.cpython-313.pyc
api.cpython-313.pyc
Other
446
0.7
0
0
awesome-app
332
2023-10-13T17:16:37.552523
GPL-3.0
false
f425e5722cf0ba34674d4a6773c93807
\n\n
.venv\Lib\site-packages\pandas\tseries\__pycache__\frequencies.cpython-313.pyc
frequencies.cpython-313.pyc
Other
21,674
0.8
0.018265
0
awesome-app
845
2023-08-12T03:03:16.156214
BSD-3-Clause
false
5849a70ce4531c3c56a5c3705121295d
\n\n
.venv\Lib\site-packages\pandas\tseries\__pycache__\holiday.cpython-313.pyc
holiday.cpython-313.pyc
Other
20,960
0.95
0.057692
0.010345
python-kit
525
2025-05-26T21:30:10.118736
GPL-3.0
false
1db24277bffb84deefd04b1185b16bc8
\n\n
.venv\Lib\site-packages\pandas\tseries\__pycache__\offsets.cpython-313.pyc
offsets.cpython-313.pyc
Other
1,454
0.8
0
0
vue-tools
271
2024-02-12T02:42:59.798259
BSD-3-Clause
false
def99624059d7b029ae25da971f4fa25
\n\n
.venv\Lib\site-packages\pandas\tseries\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
370
0.7
0
0
awesome-app
529
2024-07-14T08:10:46.135828
GPL-3.0
false
82f72f881001a5ded5d86b40b6ae3315
from __future__ import annotations\n\nfrom functools import wraps\nimport inspect\nfrom textwrap import dedent\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n cast,\n)\nimport warnings\n\nfrom pandas._libs.properties import cache_readonly\nfrom pandas._typing import (\n F,\n T,\n)\nfrom pandas.util._exceptions import find_stack_level\n\nif TYPE_CHECKING:\n from collections.abc import Mapping\n\n\ndef deprecate(\n name: str,\n alternative: Callable[..., Any],\n version: str,\n alt_name: str | None = None,\n klass: type[Warning] | None = None,\n stacklevel: int = 2,\n msg: str | None = None,\n) -> Callable[[F], F]:\n """\n Return a new function that emits a deprecation warning on use.\n\n To use this method for a deprecated function, another function\n `alternative` with the same signature must exist. The deprecated\n function will emit a deprecation warning, and in the docstring\n it will contain the deprecation directive with the provided version\n so it can be detected for future removal.\n\n Parameters\n ----------\n name : str\n Name of function to deprecate.\n alternative : func\n Function to use instead.\n version : str\n Version of pandas in which the method has been deprecated.\n alt_name : str, optional\n Name to use in preference of alternative.__name__.\n klass : Warning, default FutureWarning\n stacklevel : int, default 2\n msg : str\n The message to display in the warning.\n Default is '{name} is deprecated. Use {alt_name} instead.'\n """\n alt_name = alt_name or alternative.__name__\n klass = klass or FutureWarning\n warning_msg = msg or f"{name} is deprecated, use {alt_name} instead."\n\n @wraps(alternative)\n def wrapper(*args, **kwargs) -> Callable[..., Any]:\n warnings.warn(warning_msg, klass, stacklevel=stacklevel)\n return alternative(*args, **kwargs)\n\n # adding deprecated directive to the docstring\n msg = msg or f"Use `{alt_name}` instead."\n doc_error_msg = (\n "deprecate needs a correctly formatted docstring in "\n "the target function (should have a one liner short "\n "summary, and opening quotes should be in their own "\n f"line). Found:\n{alternative.__doc__}"\n )\n\n # when python is running in optimized mode (i.e. `-OO`), docstrings are\n # removed, so we check that a docstring with correct formatting is used\n # but we allow empty docstrings\n if alternative.__doc__:\n if alternative.__doc__.count("\n") < 3:\n raise AssertionError(doc_error_msg)\n empty1, summary, empty2, doc_string = alternative.__doc__.split("\n", 3)\n if empty1 or empty2 and not summary:\n raise AssertionError(doc_error_msg)\n wrapper.__doc__ = dedent(\n f"""\n {summary.strip()}\n\n .. deprecated:: {version}\n {msg}\n\n {dedent(doc_string)}"""\n )\n # error: Incompatible return value type (got "Callable[[VarArg(Any), KwArg(Any)],\n # Callable[...,Any]]", expected "Callable[[F], F]")\n return wrapper # type: ignore[return-value]\n\n\ndef deprecate_kwarg(\n old_arg_name: str,\n new_arg_name: str | None,\n mapping: Mapping[Any, Any] | Callable[[Any], Any] | None = None,\n stacklevel: int = 2,\n) -> Callable[[F], F]:\n """\n Decorator to deprecate a keyword argument of a function.\n\n Parameters\n ----------\n old_arg_name : str\n Name of argument in function to deprecate\n new_arg_name : str or None\n Name of preferred argument in function. Use None to raise warning that\n ``old_arg_name`` keyword is deprecated.\n mapping : dict or callable\n If mapping is present, use it to translate old arguments to\n new arguments. A callable must do its own value checking;\n values not found in a dict will be forwarded unchanged.\n\n Examples\n --------\n The following deprecates 'cols', using 'columns' instead\n\n >>> @deprecate_kwarg(old_arg_name='cols', new_arg_name='columns')\n ... def f(columns=''):\n ... print(columns)\n ...\n >>> f(columns='should work ok')\n should work ok\n\n >>> f(cols='should raise warning') # doctest: +SKIP\n FutureWarning: cols is deprecated, use columns instead\n warnings.warn(msg, FutureWarning)\n should raise warning\n\n >>> f(cols='should error', columns="can\'t pass do both") # doctest: +SKIP\n TypeError: Can only specify 'cols' or 'columns', not both\n\n >>> @deprecate_kwarg('old', 'new', {'yes': True, 'no': False})\n ... def f(new=False):\n ... print('yes!' if new else 'no!')\n ...\n >>> f(old='yes') # doctest: +SKIP\n FutureWarning: old='yes' is deprecated, use new=True instead\n warnings.warn(msg, FutureWarning)\n yes!\n\n To raise a warning that a keyword will be removed entirely in the future\n\n >>> @deprecate_kwarg(old_arg_name='cols', new_arg_name=None)\n ... def f(cols='', another_param=''):\n ... print(cols)\n ...\n >>> f(cols='should raise warning') # doctest: +SKIP\n FutureWarning: the 'cols' keyword is deprecated and will be removed in a\n future version please takes steps to stop use of 'cols'\n should raise warning\n >>> f(another_param='should not raise warning') # doctest: +SKIP\n should not raise warning\n\n >>> f(cols='should raise warning', another_param='') # doctest: +SKIP\n FutureWarning: the 'cols' keyword is deprecated and will be removed in a\n future version please takes steps to stop use of 'cols'\n should raise warning\n """\n if mapping is not None and not hasattr(mapping, "get") and not callable(mapping):\n raise TypeError(\n "mapping from old to new argument values must be dict or callable!"\n )\n\n def _deprecate_kwarg(func: F) -> F:\n @wraps(func)\n def wrapper(*args, **kwargs) -> Callable[..., Any]:\n old_arg_value = kwargs.pop(old_arg_name, None)\n\n if old_arg_value is not None:\n if new_arg_name is None:\n msg = (\n f"the {repr(old_arg_name)} keyword is deprecated and "\n "will be removed in a future version. Please take "\n f"steps to stop the use of {repr(old_arg_name)}"\n )\n warnings.warn(msg, FutureWarning, stacklevel=stacklevel)\n kwargs[old_arg_name] = old_arg_value\n return func(*args, **kwargs)\n\n elif mapping is not None:\n if callable(mapping):\n new_arg_value = mapping(old_arg_value)\n else:\n new_arg_value = mapping.get(old_arg_value, old_arg_value)\n msg = (\n f"the {old_arg_name}={repr(old_arg_value)} keyword is "\n "deprecated, use "\n f"{new_arg_name}={repr(new_arg_value)} instead."\n )\n else:\n new_arg_value = old_arg_value\n msg = (\n f"the {repr(old_arg_name)} keyword is deprecated, "\n f"use {repr(new_arg_name)} instead."\n )\n\n warnings.warn(msg, FutureWarning, stacklevel=stacklevel)\n if kwargs.get(new_arg_name) is not None:\n msg = (\n f"Can only specify {repr(old_arg_name)} "\n f"or {repr(new_arg_name)}, not both."\n )\n raise TypeError(msg)\n kwargs[new_arg_name] = new_arg_value\n return func(*args, **kwargs)\n\n return cast(F, wrapper)\n\n return _deprecate_kwarg\n\n\ndef _format_argument_list(allow_args: list[str]) -> str:\n """\n Convert the allow_args argument (either string or integer) of\n `deprecate_nonkeyword_arguments` function to a string describing\n it to be inserted into warning message.\n\n Parameters\n ----------\n allowed_args : list, tuple or int\n The `allowed_args` argument for `deprecate_nonkeyword_arguments`,\n but None value is not allowed.\n\n Returns\n -------\n str\n The substring describing the argument list in best way to be\n inserted to the warning message.\n\n Examples\n --------\n `format_argument_list([])` -> ''\n `format_argument_list(['a'])` -> "except for the arguments 'a'"\n `format_argument_list(['a', 'b'])` -> "except for the arguments 'a' and 'b'"\n `format_argument_list(['a', 'b', 'c'])` ->\n "except for the arguments 'a', 'b' and 'c'"\n """\n if "self" in allow_args:\n allow_args.remove("self")\n if not allow_args:\n return ""\n elif len(allow_args) == 1:\n return f" except for the argument '{allow_args[0]}'"\n else:\n last = allow_args[-1]\n args = ", ".join(["'" + x + "'" for x in allow_args[:-1]])\n return f" except for the arguments {args} and '{last}'"\n\n\ndef future_version_msg(version: str | None) -> str:\n """Specify which version of pandas the deprecation will take place in."""\n if version is None:\n return "In a future version of pandas"\n else:\n return f"Starting with pandas version {version}"\n\n\ndef deprecate_nonkeyword_arguments(\n version: str | None,\n allowed_args: list[str] | None = None,\n name: str | None = None,\n) -> Callable[[F], F]:\n """\n Decorator to deprecate a use of non-keyword arguments of a function.\n\n Parameters\n ----------\n version : str, optional\n The version in which positional arguments will become\n keyword-only. If None, then the warning message won't\n specify any particular version.\n\n allowed_args : list, optional\n In case of list, it must be the list of names of some\n first arguments of the decorated functions that are\n OK to be given as positional arguments. In case of None value,\n defaults to list of all arguments not having the\n default value.\n\n name : str, optional\n The specific name of the function to show in the warning\n message. If None, then the Qualified name of the function\n is used.\n """\n\n def decorate(func):\n old_sig = inspect.signature(func)\n\n if allowed_args is not None:\n allow_args = allowed_args\n else:\n allow_args = [\n p.name\n for p in old_sig.parameters.values()\n if p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)\n and p.default is p.empty\n ]\n\n new_params = [\n p.replace(kind=p.KEYWORD_ONLY)\n if (\n p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD)\n and p.name not in allow_args\n )\n else p\n for p in old_sig.parameters.values()\n ]\n new_params.sort(key=lambda p: p.kind)\n new_sig = old_sig.replace(parameters=new_params)\n\n num_allow_args = len(allow_args)\n msg = (\n f"{future_version_msg(version)} all arguments of "\n f"{name or func.__qualname__}{{arguments}} will be keyword-only."\n )\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n if len(args) > num_allow_args:\n warnings.warn(\n msg.format(arguments=_format_argument_list(allow_args)),\n FutureWarning,\n stacklevel=find_stack_level(),\n )\n return func(*args, **kwargs)\n\n # error: "Callable[[VarArg(Any), KwArg(Any)], Any]" has no\n # attribute "__signature__"\n wrapper.__signature__ = new_sig # type: ignore[attr-defined]\n return wrapper\n\n return decorate\n\n\ndef doc(*docstrings: None | str | Callable, **params) -> Callable[[F], F]:\n """\n A decorator to take docstring templates, concatenate them and perform string\n substitution on them.\n\n This decorator will add a variable "_docstring_components" to the wrapped\n callable to keep track the original docstring template for potential usage.\n If it should be consider as a template, it will be saved as a string.\n Otherwise, it will be saved as callable, and later user __doc__ and dedent\n to get docstring.\n\n Parameters\n ----------\n *docstrings : None, str, or callable\n The string / docstring / docstring template to be appended in order\n after default docstring under callable.\n **params\n The string which would be used to format docstring template.\n """\n\n def decorator(decorated: F) -> F:\n # collecting docstring and docstring templates\n docstring_components: list[str | Callable] = []\n if decorated.__doc__:\n docstring_components.append(dedent(decorated.__doc__))\n\n for docstring in docstrings:\n if docstring is None:\n continue\n if hasattr(docstring, "_docstring_components"):\n docstring_components.extend(\n docstring._docstring_components # pyright: ignore[reportGeneralTypeIssues]\n )\n elif isinstance(docstring, str) or docstring.__doc__:\n docstring_components.append(docstring)\n\n params_applied = [\n component.format(**params)\n if isinstance(component, str) and len(params) > 0\n else component\n for component in docstring_components\n ]\n\n decorated.__doc__ = "".join(\n [\n component\n if isinstance(component, str)\n else dedent(component.__doc__ or "")\n for component in params_applied\n ]\n )\n\n # error: "F" has no attribute "_docstring_components"\n decorated._docstring_components = ( # type: ignore[attr-defined]\n docstring_components\n )\n return decorated\n\n return decorator\n\n\n# Substitution and Appender are derived from matplotlib.docstring (1.1.0)\n# module https://matplotlib.org/users/license.html\n\n\nclass Substitution:\n """\n A decorator to take a function's docstring and perform string\n substitution on it.\n\n This decorator should be robust even if func.__doc__ is None\n (for example, if -OO was passed to the interpreter)\n\n Usage: construct a docstring.Substitution with a sequence or\n dictionary suitable for performing substitution; then\n decorate a suitable function with the constructed object. e.g.\n\n sub_author_name = Substitution(author='Jason')\n\n @sub_author_name\n def some_function(x):\n "%(author)s wrote this function"\n\n # note that some_function.__doc__ is now "Jason wrote this function"\n\n One can also use positional arguments.\n\n sub_first_last_names = Substitution('Edgar Allen', 'Poe')\n\n @sub_first_last_names\n def some_function(x):\n "%s %s wrote the Raven"\n """\n\n def __init__(self, *args, **kwargs) -> None:\n if args and kwargs:\n raise AssertionError("Only positional or keyword args are allowed")\n\n self.params = args or kwargs\n\n def __call__(self, func: F) -> F:\n func.__doc__ = func.__doc__ and func.__doc__ % self.params\n return func\n\n def update(self, *args, **kwargs) -> None:\n """\n Update self.params with supplied args.\n """\n if isinstance(self.params, dict):\n self.params.update(*args, **kwargs)\n\n\nclass Appender:\n """\n A function decorator that will append an addendum to the docstring\n of the target function.\n\n This decorator should be robust even if func.__doc__ is None\n (for example, if -OO was passed to the interpreter).\n\n Usage: construct a docstring.Appender with a string to be joined to\n the original docstring. An optional 'join' parameter may be supplied\n which will be used to join the docstring and addendum. e.g.\n\n add_copyright = Appender("Copyright (c) 2009", join='\n')\n\n @add_copyright\n def my_dog(has='fleas'):\n "This docstring will have a copyright below"\n pass\n """\n\n addendum: str | None\n\n def __init__(self, addendum: str | None, join: str = "", indents: int = 0) -> None:\n if indents > 0:\n self.addendum = indent(addendum, indents=indents)\n else:\n self.addendum = addendum\n self.join = join\n\n def __call__(self, func: T) -> T:\n func.__doc__ = func.__doc__ if func.__doc__ else ""\n self.addendum = self.addendum if self.addendum else ""\n docitems = [func.__doc__, self.addendum]\n func.__doc__ = dedent(self.join.join(docitems))\n return func\n\n\ndef indent(text: str | None, indents: int = 1) -> str:\n if not text or not isinstance(text, str):\n return ""\n jointext = "".join(["\n"] + [" "] * indents)\n return jointext.join(text.split("\n"))\n\n\n__all__ = [\n "Appender",\n "cache_readonly",\n "deprecate",\n "deprecate_kwarg",\n "deprecate_nonkeyword_arguments",\n "doc",\n "future_version_msg",\n "Substitution",\n]\n
.venv\Lib\site-packages\pandas\util\_decorators.py
_decorators.py
Python
17,106
0.95
0.187008
0.035629
node-utils
941
2024-05-02T06:47:07.280963
Apache-2.0
false
e128cb106f4e792f05c40a15838583f3
from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nimport numpy as np\n\nimport pandas as pd\n\nif TYPE_CHECKING:\n from collections.abc import Iterable\n\n\nclass TablePlotter:\n """\n Layout some DataFrames in vertical/horizontal layout for explanation.\n Used in merging.rst\n """\n\n def __init__(\n self,\n cell_width: float = 0.37,\n cell_height: float = 0.25,\n font_size: float = 7.5,\n ) -> None:\n self.cell_width = cell_width\n self.cell_height = cell_height\n self.font_size = font_size\n\n def _shape(self, df: pd.DataFrame) -> tuple[int, int]:\n """\n Calculate table shape considering index levels.\n """\n row, col = df.shape\n return row + df.columns.nlevels, col + df.index.nlevels\n\n def _get_cells(self, left, right, vertical) -> tuple[int, int]:\n """\n Calculate appropriate figure size based on left and right data.\n """\n if vertical:\n # calculate required number of cells\n vcells = max(sum(self._shape(df)[0] for df in left), self._shape(right)[0])\n hcells = max(self._shape(df)[1] for df in left) + self._shape(right)[1]\n else:\n vcells = max([self._shape(df)[0] for df in left] + [self._shape(right)[0]])\n hcells = sum([self._shape(df)[1] for df in left] + [self._shape(right)[1]])\n return hcells, vcells\n\n def plot(self, left, right, labels: Iterable[str] = (), vertical: bool = True):\n """\n Plot left / right DataFrames in specified layout.\n\n Parameters\n ----------\n left : list of DataFrames before operation is applied\n right : DataFrame of operation result\n labels : list of str to be drawn as titles of left DataFrames\n vertical : bool, default True\n If True, use vertical layout. If False, use horizontal layout.\n """\n from matplotlib import gridspec\n import matplotlib.pyplot as plt\n\n if not isinstance(left, list):\n left = [left]\n left = [self._conv(df) for df in left]\n right = self._conv(right)\n\n hcells, vcells = self._get_cells(left, right, vertical)\n\n if vertical:\n figsize = self.cell_width * hcells, self.cell_height * vcells\n else:\n # include margin for titles\n figsize = self.cell_width * hcells, self.cell_height * vcells\n fig = plt.figure(figsize=figsize)\n\n if vertical:\n gs = gridspec.GridSpec(len(left), hcells)\n # left\n max_left_cols = max(self._shape(df)[1] for df in left)\n max_left_rows = max(self._shape(df)[0] for df in left)\n for i, (_left, _label) in enumerate(zip(left, labels)):\n ax = fig.add_subplot(gs[i, 0:max_left_cols])\n self._make_table(ax, _left, title=_label, height=1.0 / max_left_rows)\n # right\n ax = plt.subplot(gs[:, max_left_cols:])\n self._make_table(ax, right, title="Result", height=1.05 / vcells)\n fig.subplots_adjust(top=0.9, bottom=0.05, left=0.05, right=0.95)\n else:\n max_rows = max(self._shape(df)[0] for df in left + [right])\n height = 1.0 / np.max(max_rows)\n gs = gridspec.GridSpec(1, hcells)\n # left\n i = 0\n for df, _label in zip(left, labels):\n sp = self._shape(df)\n ax = fig.add_subplot(gs[0, i : i + sp[1]])\n self._make_table(ax, df, title=_label, height=height)\n i += sp[1]\n # right\n ax = plt.subplot(gs[0, i:])\n self._make_table(ax, right, title="Result", height=height)\n fig.subplots_adjust(top=0.85, bottom=0.05, left=0.05, right=0.95)\n\n return fig\n\n def _conv(self, data):\n """\n Convert each input to appropriate for table outplot.\n """\n if isinstance(data, pd.Series):\n if data.name is None:\n data = data.to_frame(name="")\n else:\n data = data.to_frame()\n data = data.fillna("NaN")\n return data\n\n def _insert_index(self, data):\n # insert is destructive\n data = data.copy()\n idx_nlevels = data.index.nlevels\n if idx_nlevels == 1:\n data.insert(0, "Index", data.index)\n else:\n for i in range(idx_nlevels):\n data.insert(i, f"Index{i}", data.index._get_level_values(i))\n\n col_nlevels = data.columns.nlevels\n if col_nlevels > 1:\n col = data.columns._get_level_values(0)\n values = [\n data.columns._get_level_values(i)._values for i in range(1, col_nlevels)\n ]\n col_df = pd.DataFrame(values)\n data.columns = col_df.columns\n data = pd.concat([col_df, data])\n data.columns = col\n return data\n\n def _make_table(self, ax, df, title: str, height: float | None = None) -> None:\n if df is None:\n ax.set_visible(False)\n return\n\n from pandas import plotting\n\n idx_nlevels = df.index.nlevels\n col_nlevels = df.columns.nlevels\n # must be convert here to get index levels for colorization\n df = self._insert_index(df)\n tb = plotting.table(ax, df, loc=9)\n tb.set_fontsize(self.font_size)\n\n if height is None:\n height = 1.0 / (len(df) + 1)\n\n props = tb.properties()\n for (r, c), cell in props["celld"].items():\n if c == -1:\n cell.set_visible(False)\n elif r < col_nlevels and c < idx_nlevels:\n cell.set_visible(False)\n elif r < col_nlevels or c < idx_nlevels:\n cell.set_facecolor("#AAAAAA")\n cell.set_height(height)\n\n ax.set_title(title, size=self.font_size)\n ax.axis("off")\n\n\ndef main() -> None:\n import matplotlib.pyplot as plt\n\n p = TablePlotter()\n\n df1 = pd.DataFrame({"A": [10, 11, 12], "B": [20, 21, 22], "C": [30, 31, 32]})\n df2 = pd.DataFrame({"A": [10, 12], "C": [30, 32]})\n\n p.plot([df1, df2], pd.concat([df1, df2]), labels=["df1", "df2"], vertical=True)\n plt.show()\n\n df3 = pd.DataFrame({"X": [10, 12], "Z": [30, 32]})\n\n p.plot(\n [df1, df3], pd.concat([df1, df3], axis=1), labels=["df1", "df2"], vertical=False\n )\n plt.show()\n\n idx = pd.MultiIndex.from_tuples(\n [(1, "A"), (1, "B"), (1, "C"), (2, "A"), (2, "B"), (2, "C")]\n )\n column = pd.MultiIndex.from_tuples([(1, "A"), (1, "B")])\n df3 = pd.DataFrame({"v1": [1, 2, 3, 4, 5, 6], "v2": [5, 6, 7, 8, 9, 10]}, index=idx)\n df3.columns = column\n p.plot(df3, df3, labels=["df3"])\n plt.show()\n\n\nif __name__ == "__main__":\n main()\n
.venv\Lib\site-packages\pandas\util\_doctools.py
_doctools.py
Python
6,819
0.95
0.193069
0.047904
awesome-app
176
2023-07-31T20:55:55.909820
BSD-3-Clause
false
ae41403cf66bc483b3e9c01276e8795c
from __future__ import annotations\n\nimport contextlib\nimport inspect\nimport os\nimport re\nfrom typing import TYPE_CHECKING\nimport warnings\n\nif TYPE_CHECKING:\n from collections.abc import Generator\n from types import FrameType\n\n\n@contextlib.contextmanager\ndef rewrite_exception(old_name: str, new_name: str) -> Generator[None, None, None]:\n """\n Rewrite the message of an exception.\n """\n try:\n yield\n except Exception as err:\n if not err.args:\n raise\n msg = str(err.args[0])\n msg = msg.replace(old_name, new_name)\n args: tuple[str, ...] = (msg,)\n if len(err.args) > 1:\n args = args + err.args[1:]\n err.args = args\n raise\n\n\ndef find_stack_level() -> int:\n """\n Find the first place in the stack that is not inside pandas\n (tests notwithstanding).\n """\n\n import pandas as pd\n\n pkg_dir = os.path.dirname(pd.__file__)\n test_dir = os.path.join(pkg_dir, "tests")\n\n # https://stackoverflow.com/questions/17407119/python-inspect-stack-is-slow\n frame: FrameType | None = inspect.currentframe()\n try:\n n = 0\n while frame:\n filename = inspect.getfile(frame)\n if filename.startswith(pkg_dir) and not filename.startswith(test_dir):\n frame = frame.f_back\n n += 1\n else:\n break\n finally:\n # See note in\n # https://docs.python.org/3/library/inspect.html#inspect.Traceback\n del frame\n return n\n\n\n@contextlib.contextmanager\ndef rewrite_warning(\n target_message: str,\n target_category: type[Warning],\n new_message: str,\n new_category: type[Warning] | None = None,\n) -> Generator[None, None, None]:\n """\n Rewrite the message of a warning.\n\n Parameters\n ----------\n target_message : str\n Warning message to match.\n target_category : Warning\n Warning type to match.\n new_message : str\n New warning message to emit.\n new_category : Warning or None, default None\n New warning type to emit. When None, will be the same as target_category.\n """\n if new_category is None:\n new_category = target_category\n with warnings.catch_warnings(record=True) as record:\n yield\n if len(record) > 0:\n match = re.compile(target_message)\n for warning in record:\n if warning.category is target_category and re.search(\n match, str(warning.message)\n ):\n category = new_category\n message: Warning | str = new_message\n else:\n category, message = warning.category, warning.message\n warnings.warn_explicit(\n message=message,\n category=category,\n filename=warning.filename,\n lineno=warning.lineno,\n )\n
.venv\Lib\site-packages\pandas\util\_exceptions.py
_exceptions.py
Python
2,876
0.95
0.135922
0.032967
awesome-app
41
2024-09-08T04:23:21.233504
Apache-2.0
false
ddb46616dfaceb29de68bdaaed486b32
from __future__ import annotations\n\nimport codecs\nimport json\nimport locale\nimport os\nimport platform\nimport struct\nimport sys\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from pandas._typing import JSONSerializable\n\nfrom pandas.compat._optional import (\n VERSIONS,\n get_version,\n import_optional_dependency,\n)\n\n\ndef _get_commit_hash() -> str | None:\n """\n Use vendored versioneer code to get git hash, which handles\n git worktree correctly.\n """\n try:\n from pandas._version_meson import ( # pyright: ignore [reportMissingImports]\n __git_version__,\n )\n\n return __git_version__\n except ImportError:\n from pandas._version import get_versions\n\n versions = get_versions()\n return versions["full-revisionid"]\n\n\ndef _get_sys_info() -> dict[str, JSONSerializable]:\n """\n Returns system information as a JSON serializable dictionary.\n """\n uname_result = platform.uname()\n language_code, encoding = locale.getlocale()\n return {\n "commit": _get_commit_hash(),\n "python": platform.python_version(),\n "python-bits": struct.calcsize("P") * 8,\n "OS": uname_result.system,\n "OS-release": uname_result.release,\n "Version": uname_result.version,\n "machine": uname_result.machine,\n "processor": uname_result.processor,\n "byteorder": sys.byteorder,\n "LC_ALL": os.environ.get("LC_ALL"),\n "LANG": os.environ.get("LANG"),\n "LOCALE": {"language-code": language_code, "encoding": encoding},\n }\n\n\ndef _get_dependency_info() -> dict[str, JSONSerializable]:\n """\n Returns dependency information as a JSON serializable dictionary.\n """\n deps = [\n "pandas",\n # required\n "numpy",\n "pytz",\n "dateutil",\n # install / build,\n "pip",\n "Cython",\n # docs\n "sphinx",\n # Other, not imported.\n "IPython",\n ]\n # Optional dependencies\n deps.extend(list(VERSIONS))\n\n result: dict[str, JSONSerializable] = {}\n for modname in deps:\n try:\n mod = import_optional_dependency(modname, errors="ignore")\n except Exception:\n # Dependency conflicts may cause a non ImportError\n result[modname] = "N/A"\n else:\n result[modname] = get_version(mod) if mod else None\n return result\n\n\ndef show_versions(as_json: str | bool = False) -> None:\n """\n Provide useful information, important for bug reports.\n\n It comprises info about hosting operation system, pandas version,\n and versions of other installed relative packages.\n\n Parameters\n ----------\n as_json : str or bool, default False\n * If False, outputs info in a human readable form to the console.\n * If str, it will be considered as a path to a file.\n Info will be written to that file in JSON format.\n * If True, outputs info in JSON format to the console.\n\n Examples\n --------\n >>> pd.show_versions() # doctest: +SKIP\n Your output may look something like this:\n INSTALLED VERSIONS\n ------------------\n commit : 37ea63d540fd27274cad6585082c91b1283f963d\n python : 3.10.6.final.0\n python-bits : 64\n OS : Linux\n OS-release : 5.10.102.1-microsoft-standard-WSL2\n Version : #1 SMP Wed Mar 2 00:30:59 UTC 2022\n machine : x86_64\n processor : x86_64\n byteorder : little\n LC_ALL : None\n LANG : en_GB.UTF-8\n LOCALE : en_GB.UTF-8\n pandas : 2.0.1\n numpy : 1.24.3\n ...\n """\n sys_info = _get_sys_info()\n deps = _get_dependency_info()\n\n if as_json:\n j = {"system": sys_info, "dependencies": deps}\n\n if as_json is True:\n sys.stdout.writelines(json.dumps(j, indent=2))\n else:\n assert isinstance(as_json, str) # needed for mypy\n with codecs.open(as_json, "wb", encoding="utf8") as f:\n json.dump(j, f, indent=2)\n\n else:\n assert isinstance(sys_info["LOCALE"], dict) # needed for mypy\n language_code = sys_info["LOCALE"]["language-code"]\n encoding = sys_info["LOCALE"]["encoding"]\n sys_info["LOCALE"] = f"{language_code}.{encoding}"\n\n maxlen = max(len(x) for x in deps)\n print("\nINSTALLED VERSIONS")\n print("------------------")\n for k, v in sys_info.items():\n print(f"{k:<{maxlen}}: {v}")\n print("")\n for k, v in deps.items():\n print(f"{k:<{maxlen}}: {v}")\n
.venv\Lib\site-packages\pandas\util\_print_versions.py
_print_versions.py
Python
4,636
0.95
0.107595
0.065693
node-utils
100
2023-07-22T18:52:03.458622
Apache-2.0
false
add3dd33f173aa2382d0d95d2a4bf229
"""\nEntrypoint for testing from the top-level namespace.\n"""\nfrom __future__ import annotations\n\nimport os\nimport sys\n\nfrom pandas.compat._optional import import_optional_dependency\n\nPKG = os.path.dirname(os.path.dirname(__file__))\n\n\ndef test(extra_args: list[str] | None = None, run_doctests: bool = False) -> None:\n """\n Run the pandas test suite using pytest.\n\n By default, runs with the marks -m "not slow and not network and not db"\n\n Parameters\n ----------\n extra_args : list[str], default None\n Extra marks to run the tests.\n run_doctests : bool, default False\n Whether to only run the Python and Cython doctests. If you would like to run\n both doctests/regular tests, just append "--doctest-modules"/"--doctest-cython"\n to extra_args.\n\n Examples\n --------\n >>> pd.test() # doctest: +SKIP\n running: pytest...\n """\n pytest = import_optional_dependency("pytest")\n import_optional_dependency("hypothesis")\n cmd = ["-m not slow and not network and not db"]\n if extra_args:\n if not isinstance(extra_args, list):\n extra_args = [extra_args]\n cmd = extra_args\n if run_doctests:\n cmd = [\n "--doctest-modules",\n "--doctest-cython",\n f"--ignore={os.path.join(PKG, 'tests')}",\n ]\n cmd += [PKG]\n joined = " ".join(cmd)\n print(f"running: pytest {joined}")\n sys.exit(pytest.main(cmd))\n\n\n__all__ = ["test"]\n
.venv\Lib\site-packages\pandas\util\_tester.py
_tester.py
Python
1,462
0.95
0.09434
0
awesome-app
793
2025-04-30T07:46:31.423220
GPL-3.0
true
97658eaf05300a4eeea5b806158e2750
"""\nThis module provides decorator functions which can be applied to test objects\nin order to skip those objects when certain conditions occur. A sample use case\nis to detect if the platform is missing ``matplotlib``. If so, any test objects\nwhich require ``matplotlib`` and decorated with ``@td.skip_if_no("matplotlib")``\nwill be skipped by ``pytest`` during the execution of the test suite.\n\nTo illustrate, after importing this module:\n\nimport pandas.util._test_decorators as td\n\nThe decorators can be applied to classes:\n\n@td.skip_if_no("package")\nclass Foo:\n ...\n\nOr individual functions:\n\n@td.skip_if_no("package")\ndef test_foo():\n ...\n\nFor more information, refer to the ``pytest`` documentation on ``skipif``.\n"""\nfrom __future__ import annotations\n\nimport locale\nfrom typing import (\n TYPE_CHECKING,\n Callable,\n)\n\nimport pytest\n\nfrom pandas._config import get_option\n\nif TYPE_CHECKING:\n from pandas._typing import F\n\nfrom pandas._config.config import _get_option\n\nfrom pandas.compat import (\n IS64,\n is_platform_windows,\n)\nfrom pandas.compat._optional import import_optional_dependency\n\n\ndef skip_if_installed(package: str) -> pytest.MarkDecorator:\n """\n Skip a test if a package is installed.\n\n Parameters\n ----------\n package : str\n The name of the package.\n\n Returns\n -------\n pytest.MarkDecorator\n a pytest.mark.skipif to use as either a test decorator or a\n parametrization mark.\n """\n return pytest.mark.skipif(\n bool(import_optional_dependency(package, errors="ignore")),\n reason=f"Skipping because {package} is installed.",\n )\n\n\ndef skip_if_no(package: str, min_version: str | None = None) -> pytest.MarkDecorator:\n """\n Generic function to help skip tests when required packages are not\n present on the testing system.\n\n This function returns a pytest mark with a skip condition that will be\n evaluated during test collection. An attempt will be made to import the\n specified ``package`` and optionally ensure it meets the ``min_version``\n\n The mark can be used as either a decorator for a test class or to be\n applied to parameters in pytest.mark.parametrize calls or parametrized\n fixtures. Use pytest.importorskip if an imported moduled is later needed\n or for test functions.\n\n If the import and version check are unsuccessful, then the test function\n (or test case when used in conjunction with parametrization) will be\n skipped.\n\n Parameters\n ----------\n package: str\n The name of the required package.\n min_version: str or None, default None\n Optional minimum version of the package.\n\n Returns\n -------\n pytest.MarkDecorator\n a pytest.mark.skipif to use as either a test decorator or a\n parametrization mark.\n """\n msg = f"Could not import '{package}'"\n if min_version:\n msg += f" satisfying a min_version of {min_version}"\n return pytest.mark.skipif(\n not bool(\n import_optional_dependency(\n package, errors="ignore", min_version=min_version\n )\n ),\n reason=msg,\n )\n\n\nskip_if_32bit = pytest.mark.skipif(not IS64, reason="skipping for 32 bit")\nskip_if_windows = pytest.mark.skipif(is_platform_windows(), reason="Running on Windows")\nskip_if_not_us_locale = pytest.mark.skipif(\n locale.getlocale()[0] != "en_US",\n reason=f"Set local {locale.getlocale()[0]} is not en_US",\n)\n\n\ndef parametrize_fixture_doc(*args) -> Callable[[F], F]:\n """\n Intended for use as a decorator for parametrized fixture,\n this function will wrap the decorated function with a pytest\n ``parametrize_fixture_doc`` mark. That mark will format\n initial fixture docstring by replacing placeholders {0}, {1} etc\n with parameters passed as arguments.\n\n Parameters\n ----------\n args: iterable\n Positional arguments for docstring.\n\n Returns\n -------\n function\n The decorated function wrapped within a pytest\n ``parametrize_fixture_doc`` mark\n """\n\n def documented_fixture(fixture):\n fixture.__doc__ = fixture.__doc__.format(*args)\n return fixture\n\n return documented_fixture\n\n\ndef mark_array_manager_not_yet_implemented(request) -> None:\n mark = pytest.mark.xfail(reason="Not yet implemented for ArrayManager")\n request.applymarker(mark)\n\n\nskip_array_manager_not_yet_implemented = pytest.mark.xfail(\n _get_option("mode.data_manager", silent=True) == "array",\n reason="Not yet implemented for ArrayManager",\n)\n\nskip_array_manager_invalid_test = pytest.mark.skipif(\n _get_option("mode.data_manager", silent=True) == "array",\n reason="Test that relies on BlockManager internals or specific behaviour",\n)\n\nskip_copy_on_write_not_yet_implemented = pytest.mark.xfail(\n get_option("mode.copy_on_write") is True,\n reason="Not yet implemented/adapted for Copy-on-Write mode",\n)\n\nskip_copy_on_write_invalid_test = pytest.mark.skipif(\n get_option("mode.copy_on_write") is True,\n reason="Test not valid for Copy-on-Write mode",\n)\n
.venv\Lib\site-packages\pandas\util\_test_decorators.py
_test_decorators.py
Python
5,079
0.85
0.17341
0
python-kit
224
2025-01-13T21:23:38.045499
Apache-2.0
true
d9ddda8171ad70baa22db718a189c780
"""\nModule that contains many useful utilities\nfor validating data or function arguments\n"""\nfrom __future__ import annotations\n\nfrom collections.abc import (\n Iterable,\n Sequence,\n)\nfrom typing import (\n TypeVar,\n overload,\n)\n\nimport numpy as np\n\nfrom pandas._libs import lib\n\nfrom pandas.core.dtypes.common import (\n is_bool,\n is_integer,\n)\n\nBoolishT = TypeVar("BoolishT", bool, int)\nBoolishNoneT = TypeVar("BoolishNoneT", bool, int, None)\n\n\ndef _check_arg_length(fname, args, max_fname_arg_count, compat_args) -> None:\n """\n Checks whether 'args' has length of at most 'compat_args'. Raises\n a TypeError if that is not the case, similar to in Python when a\n function is called with too many arguments.\n """\n if max_fname_arg_count < 0:\n raise ValueError("'max_fname_arg_count' must be non-negative")\n\n if len(args) > len(compat_args):\n max_arg_count = len(compat_args) + max_fname_arg_count\n actual_arg_count = len(args) + max_fname_arg_count\n argument = "argument" if max_arg_count == 1 else "arguments"\n\n raise TypeError(\n f"{fname}() takes at most {max_arg_count} {argument} "\n f"({actual_arg_count} given)"\n )\n\n\ndef _check_for_default_values(fname, arg_val_dict, compat_args) -> None:\n """\n Check that the keys in `arg_val_dict` are mapped to their\n default values as specified in `compat_args`.\n\n Note that this function is to be called only when it has been\n checked that arg_val_dict.keys() is a subset of compat_args\n """\n for key in arg_val_dict:\n # try checking equality directly with '=' operator,\n # as comparison may have been overridden for the left\n # hand object\n try:\n v1 = arg_val_dict[key]\n v2 = compat_args[key]\n\n # check for None-ness otherwise we could end up\n # comparing a numpy array vs None\n if (v1 is not None and v2 is None) or (v1 is None and v2 is not None):\n match = False\n else:\n match = v1 == v2\n\n if not is_bool(match):\n raise ValueError("'match' is not a boolean")\n\n # could not compare them directly, so try comparison\n # using the 'is' operator\n except ValueError:\n match = arg_val_dict[key] is compat_args[key]\n\n if not match:\n raise ValueError(\n f"the '{key}' parameter is not supported in "\n f"the pandas implementation of {fname}()"\n )\n\n\ndef validate_args(fname, args, max_fname_arg_count, compat_args) -> None:\n """\n Checks whether the length of the `*args` argument passed into a function\n has at most `len(compat_args)` arguments and whether or not all of these\n elements in `args` are set to their default values.\n\n Parameters\n ----------\n fname : str\n The name of the function being passed the `*args` parameter\n args : tuple\n The `*args` parameter passed into a function\n max_fname_arg_count : int\n The maximum number of arguments that the function `fname`\n can accept, excluding those in `args`. Used for displaying\n appropriate error messages. Must be non-negative.\n compat_args : dict\n A dictionary of keys and their associated default values.\n In order to accommodate buggy behaviour in some versions of `numpy`,\n where a signature displayed keyword arguments but then passed those\n arguments **positionally** internally when calling downstream\n implementations, a dict ensures that the original\n order of the keyword arguments is enforced.\n\n Raises\n ------\n TypeError\n If `args` contains more values than there are `compat_args`\n ValueError\n If `args` contains values that do not correspond to those\n of the default values specified in `compat_args`\n """\n _check_arg_length(fname, args, max_fname_arg_count, compat_args)\n\n # We do this so that we can provide a more informative\n # error message about the parameters that we are not\n # supporting in the pandas implementation of 'fname'\n kwargs = dict(zip(compat_args, args))\n _check_for_default_values(fname, kwargs, compat_args)\n\n\ndef _check_for_invalid_keys(fname, kwargs, compat_args) -> None:\n """\n Checks whether 'kwargs' contains any keys that are not\n in 'compat_args' and raises a TypeError if there is one.\n """\n # set(dict) --> set of the dictionary's keys\n diff = set(kwargs) - set(compat_args)\n\n if diff:\n bad_arg = next(iter(diff))\n raise TypeError(f"{fname}() got an unexpected keyword argument '{bad_arg}'")\n\n\ndef validate_kwargs(fname, kwargs, compat_args) -> None:\n """\n Checks whether parameters passed to the **kwargs argument in a\n function `fname` are valid parameters as specified in `*compat_args`\n and whether or not they are set to their default values.\n\n Parameters\n ----------\n fname : str\n The name of the function being passed the `**kwargs` parameter\n kwargs : dict\n The `**kwargs` parameter passed into `fname`\n compat_args: dict\n A dictionary of keys that `kwargs` is allowed to have and their\n associated default values\n\n Raises\n ------\n TypeError if `kwargs` contains keys not in `compat_args`\n ValueError if `kwargs` contains keys in `compat_args` that do not\n map to the default values specified in `compat_args`\n """\n kwds = kwargs.copy()\n _check_for_invalid_keys(fname, kwargs, compat_args)\n _check_for_default_values(fname, kwds, compat_args)\n\n\ndef validate_args_and_kwargs(\n fname, args, kwargs, max_fname_arg_count, compat_args\n) -> None:\n """\n Checks whether parameters passed to the *args and **kwargs argument in a\n function `fname` are valid parameters as specified in `*compat_args`\n and whether or not they are set to their default values.\n\n Parameters\n ----------\n fname: str\n The name of the function being passed the `**kwargs` parameter\n args: tuple\n The `*args` parameter passed into a function\n kwargs: dict\n The `**kwargs` parameter passed into `fname`\n max_fname_arg_count: int\n The minimum number of arguments that the function `fname`\n requires, excluding those in `args`. Used for displaying\n appropriate error messages. Must be non-negative.\n compat_args: dict\n A dictionary of keys that `kwargs` is allowed to\n have and their associated default values.\n\n Raises\n ------\n TypeError if `args` contains more values than there are\n `compat_args` OR `kwargs` contains keys not in `compat_args`\n ValueError if `args` contains values not at the default value (`None`)\n `kwargs` contains keys in `compat_args` that do not map to the default\n value as specified in `compat_args`\n\n See Also\n --------\n validate_args : Purely args validation.\n validate_kwargs : Purely kwargs validation.\n\n """\n # Check that the total number of arguments passed in (i.e.\n # args and kwargs) does not exceed the length of compat_args\n _check_arg_length(\n fname, args + tuple(kwargs.values()), max_fname_arg_count, compat_args\n )\n\n # Check there is no overlap with the positional and keyword\n # arguments, similar to what is done in actual Python functions\n args_dict = dict(zip(compat_args, args))\n\n for key in args_dict:\n if key in kwargs:\n raise TypeError(\n f"{fname}() got multiple values for keyword argument '{key}'"\n )\n\n kwargs.update(args_dict)\n validate_kwargs(fname, kwargs, compat_args)\n\n\ndef validate_bool_kwarg(\n value: BoolishNoneT,\n arg_name: str,\n none_allowed: bool = True,\n int_allowed: bool = False,\n) -> BoolishNoneT:\n """\n Ensure that argument passed in arg_name can be interpreted as boolean.\n\n Parameters\n ----------\n value : bool\n Value to be validated.\n arg_name : str\n Name of the argument. To be reflected in the error message.\n none_allowed : bool, default True\n Whether to consider None to be a valid boolean.\n int_allowed : bool, default False\n Whether to consider integer value to be a valid boolean.\n\n Returns\n -------\n value\n The same value as input.\n\n Raises\n ------\n ValueError\n If the value is not a valid boolean.\n """\n good_value = is_bool(value)\n if none_allowed:\n good_value = good_value or (value is None)\n\n if int_allowed:\n good_value = good_value or isinstance(value, int)\n\n if not good_value:\n raise ValueError(\n f'For argument "{arg_name}" expected type bool, received '\n f"type {type(value).__name__}."\n )\n return value # pyright: ignore[reportGeneralTypeIssues]\n\n\ndef validate_fillna_kwargs(value, method, validate_scalar_dict_value: bool = True):\n """\n Validate the keyword arguments to 'fillna'.\n\n This checks that exactly one of 'value' and 'method' is specified.\n If 'method' is specified, this validates that it's a valid method.\n\n Parameters\n ----------\n value, method : object\n The 'value' and 'method' keyword arguments for 'fillna'.\n validate_scalar_dict_value : bool, default True\n Whether to validate that 'value' is a scalar or dict. Specifically,\n validate that it is not a list or tuple.\n\n Returns\n -------\n value, method : object\n """\n from pandas.core.missing import clean_fill_method\n\n if value is None and method is None:\n raise ValueError("Must specify a fill 'value' or 'method'.")\n if value is None and method is not None:\n method = clean_fill_method(method)\n\n elif value is not None and method is None:\n if validate_scalar_dict_value and isinstance(value, (list, tuple)):\n raise TypeError(\n '"value" parameter must be a scalar or dict, but '\n f'you passed a "{type(value).__name__}"'\n )\n\n elif value is not None and method is not None:\n raise ValueError("Cannot specify both 'value' and 'method'.")\n\n return value, method\n\n\ndef validate_percentile(q: float | Iterable[float]) -> np.ndarray:\n """\n Validate percentiles (used by describe and quantile).\n\n This function checks if the given float or iterable of floats is a valid percentile\n otherwise raises a ValueError.\n\n Parameters\n ----------\n q: float or iterable of floats\n A single percentile or an iterable of percentiles.\n\n Returns\n -------\n ndarray\n An ndarray of the percentiles if valid.\n\n Raises\n ------\n ValueError if percentiles are not in given interval([0, 1]).\n """\n q_arr = np.asarray(q)\n # Don't change this to an f-string. The string formatting\n # is too expensive for cases where we don't need it.\n msg = "percentiles should all be in the interval [0, 1]"\n if q_arr.ndim == 0:\n if not 0 <= q_arr <= 1:\n raise ValueError(msg)\n else:\n if not all(0 <= qs <= 1 for qs in q_arr):\n raise ValueError(msg)\n return q_arr\n\n\n@overload\ndef validate_ascending(ascending: BoolishT) -> BoolishT:\n ...\n\n\n@overload\ndef validate_ascending(ascending: Sequence[BoolishT]) -> list[BoolishT]:\n ...\n\n\ndef validate_ascending(\n ascending: bool | int | Sequence[BoolishT],\n) -> bool | int | list[BoolishT]:\n """Validate ``ascending`` kwargs for ``sort_index`` method."""\n kwargs = {"none_allowed": False, "int_allowed": True}\n if not isinstance(ascending, Sequence):\n return validate_bool_kwarg(ascending, "ascending", **kwargs)\n\n return [validate_bool_kwarg(item, "ascending", **kwargs) for item in ascending]\n\n\ndef validate_endpoints(closed: str | None) -> tuple[bool, bool]:\n """\n Check that the `closed` argument is among [None, "left", "right"]\n\n Parameters\n ----------\n closed : {None, "left", "right"}\n\n Returns\n -------\n left_closed : bool\n right_closed : bool\n\n Raises\n ------\n ValueError : if argument is not among valid values\n """\n left_closed = False\n right_closed = False\n\n if closed is None:\n left_closed = True\n right_closed = True\n elif closed == "left":\n left_closed = True\n elif closed == "right":\n right_closed = True\n else:\n raise ValueError("Closed has to be either 'left', 'right' or None")\n\n return left_closed, right_closed\n\n\ndef validate_inclusive(inclusive: str | None) -> tuple[bool, bool]:\n """\n Check that the `inclusive` argument is among {"both", "neither", "left", "right"}.\n\n Parameters\n ----------\n inclusive : {"both", "neither", "left", "right"}\n\n Returns\n -------\n left_right_inclusive : tuple[bool, bool]\n\n Raises\n ------\n ValueError : if argument is not among valid values\n """\n left_right_inclusive: tuple[bool, bool] | None = None\n\n if isinstance(inclusive, str):\n left_right_inclusive = {\n "both": (True, True),\n "left": (True, False),\n "right": (False, True),\n "neither": (False, False),\n }.get(inclusive)\n\n if left_right_inclusive is None:\n raise ValueError(\n "Inclusive has to be either 'both', 'neither', 'left' or 'right'"\n )\n\n return left_right_inclusive\n\n\ndef validate_insert_loc(loc: int, length: int) -> int:\n """\n Check that we have an integer between -length and length, inclusive.\n\n Standardize negative loc to within [0, length].\n\n The exceptions we raise on failure match np.insert.\n """\n if not is_integer(loc):\n raise TypeError(f"loc must be an integer between -{length} and {length}")\n\n if loc < 0:\n loc += length\n if not 0 <= loc <= length:\n raise IndexError(f"loc must be an integer between -{length} and {length}")\n return loc # pyright: ignore[reportGeneralTypeIssues]\n\n\ndef check_dtype_backend(dtype_backend) -> None:\n if dtype_backend is not lib.no_default:\n if dtype_backend not in ["numpy_nullable", "pyarrow"]:\n raise ValueError(\n f"dtype_backend {dtype_backend} is invalid, only 'numpy_nullable' and "\n f"'pyarrow' are allowed.",\n )\n
.venv\Lib\site-packages\pandas\util\_validators.py
_validators.py
Python
14,300
0.95
0.182018
0.046196
vue-tools
692
2023-10-21T02:01:35.241657
GPL-3.0
false
751ada3d84aa733e11ec340e9f1e0c0d
def __getattr__(key: str):\n # These imports need to be lazy to avoid circular import errors\n if key == "hash_array":\n from pandas.core.util.hashing import hash_array\n\n return hash_array\n if key == "hash_pandas_object":\n from pandas.core.util.hashing import hash_pandas_object\n\n return hash_pandas_object\n if key == "Appender":\n from pandas.util._decorators import Appender\n\n return Appender\n if key == "Substitution":\n from pandas.util._decorators import Substitution\n\n return Substitution\n\n if key == "cache_readonly":\n from pandas.util._decorators import cache_readonly\n\n return cache_readonly\n\n raise AttributeError(f"module 'pandas.util' has no attribute '{key}'")\n\n\ndef capitalize_first_letter(s):\n return s[:1].upper() + s[1:]\n
.venv\Lib\site-packages\pandas\util\__init__.py
__init__.py
Python
827
0.95
0.241379
0.05
node-utils
590
2025-02-20T13:25:10.460558
MIT
false
6f4de7030c804052a362a956bc8e017b
# Vendored from https://github.com/pypa/packaging/blob/main/packaging/_structures.py\n# and https://github.com/pypa/packaging/blob/main/packaging/_structures.py\n# changeset ae891fd74d6dd4c6063bb04f2faeadaac6fc6313\n# 04/30/2021\n\n# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. Licence at LICENSES/PACKAGING_LICENSE\nfrom __future__ import annotations\n\nimport collections\nfrom collections.abc import Iterator\nimport itertools\nimport re\nfrom typing import (\n Callable,\n SupportsInt,\n Tuple,\n Union,\n)\nimport warnings\n\n__all__ = ["parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN"]\n\n\nclass InfinityType:\n def __repr__(self) -> str:\n return "Infinity"\n\n def __hash__(self) -> int:\n return hash(repr(self))\n\n def __lt__(self, other: object) -> bool:\n return False\n\n def __le__(self, other: object) -> bool:\n return False\n\n def __eq__(self, other: object) -> bool:\n return isinstance(other, type(self))\n\n def __ne__(self, other: object) -> bool:\n return not isinstance(other, type(self))\n\n def __gt__(self, other: object) -> bool:\n return True\n\n def __ge__(self, other: object) -> bool:\n return True\n\n def __neg__(self: object) -> NegativeInfinityType:\n return NegativeInfinity\n\n\nInfinity = InfinityType()\n\n\nclass NegativeInfinityType:\n def __repr__(self) -> str:\n return "-Infinity"\n\n def __hash__(self) -> int:\n return hash(repr(self))\n\n def __lt__(self, other: object) -> bool:\n return True\n\n def __le__(self, other: object) -> bool:\n return True\n\n def __eq__(self, other: object) -> bool:\n return isinstance(other, type(self))\n\n def __ne__(self, other: object) -> bool:\n return not isinstance(other, type(self))\n\n def __gt__(self, other: object) -> bool:\n return False\n\n def __ge__(self, other: object) -> bool:\n return False\n\n def __neg__(self: object) -> InfinityType:\n return Infinity\n\n\nNegativeInfinity = NegativeInfinityType()\n\n\nInfiniteTypes = Union[InfinityType, NegativeInfinityType]\nPrePostDevType = Union[InfiniteTypes, tuple[str, int]]\nSubLocalType = Union[InfiniteTypes, int, str]\nLocalType = Union[\n NegativeInfinityType,\n tuple[\n Union[\n SubLocalType,\n tuple[SubLocalType, str],\n tuple[NegativeInfinityType, SubLocalType],\n ],\n ...,\n ],\n]\nCmpKey = tuple[\n int, tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType\n]\nLegacyCmpKey = tuple[int, tuple[str, ...]]\nVersionComparisonMethod = Callable[\n [Union[CmpKey, LegacyCmpKey], Union[CmpKey, LegacyCmpKey]], bool\n]\n\n_Version = collections.namedtuple(\n "_Version", ["epoch", "release", "dev", "pre", "post", "local"]\n)\n\n\ndef parse(version: str) -> LegacyVersion | Version:\n """\n Parse the given version string and return either a :class:`Version` object\n or a :class:`LegacyVersion` object depending on if the given version is\n a valid PEP 440 version or a legacy version.\n """\n try:\n return Version(version)\n except InvalidVersion:\n return LegacyVersion(version)\n\n\nclass InvalidVersion(ValueError):\n """\n An invalid version was found, users should refer to PEP 440.\n\n Examples\n --------\n >>> pd.util.version.Version('1.')\n Traceback (most recent call last):\n InvalidVersion: Invalid version: '1.'\n """\n\n\nclass _BaseVersion:\n _key: CmpKey | LegacyCmpKey\n\n def __hash__(self) -> int:\n return hash(self._key)\n\n # Please keep the duplicated `isinstance` check\n # in the six comparisons hereunder\n # unless you find a way to avoid adding overhead function calls.\n def __lt__(self, other: _BaseVersion) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key < other._key\n\n def __le__(self, other: _BaseVersion) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key <= other._key\n\n def __eq__(self, other: object) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key == other._key\n\n def __ge__(self, other: _BaseVersion) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key >= other._key\n\n def __gt__(self, other: _BaseVersion) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key > other._key\n\n def __ne__(self, other: object) -> bool:\n if not isinstance(other, _BaseVersion):\n return NotImplemented\n\n return self._key != other._key\n\n\nclass LegacyVersion(_BaseVersion):\n def __init__(self, version: str) -> None:\n self._version = str(version)\n self._key = _legacy_cmpkey(self._version)\n\n warnings.warn(\n "Creating a LegacyVersion has been deprecated and will be "\n "removed in the next major release.",\n DeprecationWarning,\n )\n\n def __str__(self) -> str:\n return self._version\n\n def __repr__(self) -> str:\n return f"<LegacyVersion('{self}')>"\n\n @property\n def public(self) -> str:\n return self._version\n\n @property\n def base_version(self) -> str:\n return self._version\n\n @property\n def epoch(self) -> int:\n return -1\n\n @property\n def release(self) -> None:\n return None\n\n @property\n def pre(self) -> None:\n return None\n\n @property\n def post(self) -> None:\n return None\n\n @property\n def dev(self) -> None:\n return None\n\n @property\n def local(self) -> None:\n return None\n\n @property\n def is_prerelease(self) -> bool:\n return False\n\n @property\n def is_postrelease(self) -> bool:\n return False\n\n @property\n def is_devrelease(self) -> bool:\n return False\n\n\n_legacy_version_component_re = re.compile(r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE)\n\n_legacy_version_replacement_map = {\n "pre": "c",\n "preview": "c",\n "-": "final-",\n "rc": "c",\n "dev": "@",\n}\n\n\ndef _parse_version_parts(s: str) -> Iterator[str]:\n for part in _legacy_version_component_re.split(s):\n mapped_part = _legacy_version_replacement_map.get(part, part)\n\n if not mapped_part or mapped_part == ".":\n continue\n\n if mapped_part[:1] in "0123456789":\n # pad for numeric comparison\n yield mapped_part.zfill(8)\n else:\n yield "*" + mapped_part\n\n # ensure that alpha/beta/candidate are before final\n yield "*final"\n\n\ndef _legacy_cmpkey(version: str) -> LegacyCmpKey:\n # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch\n # greater than or equal to 0. This will effectively put the LegacyVersion,\n # which uses the defacto standard originally implemented by setuptools,\n # as before all PEP 440 versions.\n epoch = -1\n\n # This scheme is taken from pkg_resources.parse_version setuptools prior to\n # it's adoption of the packaging library.\n parts: list[str] = []\n for part in _parse_version_parts(version.lower()):\n if part.startswith("*"):\n # remove "-" before a prerelease tag\n if part < "*final":\n while parts and parts[-1] == "*final-":\n parts.pop()\n\n # remove trailing zeros from each series of numeric parts\n while parts and parts[-1] == "00000000":\n parts.pop()\n\n parts.append(part)\n\n return epoch, tuple(parts)\n\n\n# Deliberately not anchored to the start and end of the string, to make it\n# easier for 3rd party code to reuse\nVERSION_PATTERN = r"""\n v?\n (?:\n (?:(?P<epoch>[0-9]+)!)? # epoch\n (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment\n (?P<pre> # pre-release\n [-_\.]?\n (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))\n [-_\.]?\n (?P<pre_n>[0-9]+)?\n )?\n (?P<post> # post release\n (?:-(?P<post_n1>[0-9]+))\n |\n (?:\n [-_\.]?\n (?P<post_l>post|rev|r)\n [-_\.]?\n (?P<post_n2>[0-9]+)?\n )\n )?\n (?P<dev> # dev release\n [-_\.]?\n (?P<dev_l>dev)\n [-_\.]?\n (?P<dev_n>[0-9]+)?\n )?\n )\n (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version\n"""\n\n\nclass Version(_BaseVersion):\n _regex = re.compile(r"^\s*" + VERSION_PATTERN + r"\s*$", re.VERBOSE | re.IGNORECASE)\n\n def __init__(self, version: str) -> None:\n # Validate the version and parse it into pieces\n match = self._regex.search(version)\n if not match:\n raise InvalidVersion(f"Invalid version: '{version}'")\n\n # Store the parsed out pieces of the version\n self._version = _Version(\n epoch=int(match.group("epoch")) if match.group("epoch") else 0,\n release=tuple(int(i) for i in match.group("release").split(".")),\n pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),\n post=_parse_letter_version(\n match.group("post_l"), match.group("post_n1") or match.group("post_n2")\n ),\n dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),\n local=_parse_local_version(match.group("local")),\n )\n\n # Generate a key which will be used for sorting\n self._key = _cmpkey(\n self._version.epoch,\n self._version.release,\n self._version.pre,\n self._version.post,\n self._version.dev,\n self._version.local,\n )\n\n def __repr__(self) -> str:\n return f"<Version('{self}')>"\n\n def __str__(self) -> str:\n parts = []\n\n # Epoch\n if self.epoch != 0:\n parts.append(f"{self.epoch}!")\n\n # Release segment\n parts.append(".".join([str(x) for x in self.release]))\n\n # Pre-release\n if self.pre is not None:\n parts.append("".join([str(x) for x in self.pre]))\n\n # Post-release\n if self.post is not None:\n parts.append(f".post{self.post}")\n\n # Development release\n if self.dev is not None:\n parts.append(f".dev{self.dev}")\n\n # Local version segment\n if self.local is not None:\n parts.append(f"+{self.local}")\n\n return "".join(parts)\n\n @property\n def epoch(self) -> int:\n _epoch: int = self._version.epoch\n return _epoch\n\n @property\n def release(self) -> tuple[int, ...]:\n _release: tuple[int, ...] = self._version.release\n return _release\n\n @property\n def pre(self) -> tuple[str, int] | None:\n _pre: tuple[str, int] | None = self._version.pre\n return _pre\n\n @property\n def post(self) -> int | None:\n return self._version.post[1] if self._version.post else None\n\n @property\n def dev(self) -> int | None:\n return self._version.dev[1] if self._version.dev else None\n\n @property\n def local(self) -> str | None:\n if self._version.local:\n return ".".join([str(x) for x in self._version.local])\n else:\n return None\n\n @property\n def public(self) -> str:\n return str(self).split("+", 1)[0]\n\n @property\n def base_version(self) -> str:\n parts = []\n\n # Epoch\n if self.epoch != 0:\n parts.append(f"{self.epoch}!")\n\n # Release segment\n parts.append(".".join([str(x) for x in self.release]))\n\n return "".join(parts)\n\n @property\n def is_prerelease(self) -> bool:\n return self.dev is not None or self.pre is not None\n\n @property\n def is_postrelease(self) -> bool:\n return self.post is not None\n\n @property\n def is_devrelease(self) -> bool:\n return self.dev is not None\n\n @property\n def major(self) -> int:\n return self.release[0] if len(self.release) >= 1 else 0\n\n @property\n def minor(self) -> int:\n return self.release[1] if len(self.release) >= 2 else 0\n\n @property\n def micro(self) -> int:\n return self.release[2] if len(self.release) >= 3 else 0\n\n\ndef _parse_letter_version(\n letter: str, number: str | bytes | SupportsInt\n) -> tuple[str, int] | None:\n if letter:\n # We consider there to be an implicit 0 in a pre-release if there is\n # not a numeral associated with it.\n if number is None:\n number = 0\n\n # We normalize any letters to their lower case form\n letter = letter.lower()\n\n # We consider some words to be alternate spellings of other words and\n # in those cases we want to normalize the spellings to our preferred\n # spelling.\n if letter == "alpha":\n letter = "a"\n elif letter == "beta":\n letter = "b"\n elif letter in ["c", "pre", "preview"]:\n letter = "rc"\n elif letter in ["rev", "r"]:\n letter = "post"\n\n return letter, int(number)\n if not letter and number:\n # We assume if we are given a number, but we are not given a letter\n # then this is using the implicit post release syntax (e.g. 1.0-1)\n letter = "post"\n\n return letter, int(number)\n\n return None\n\n\n_local_version_separators = re.compile(r"[\._-]")\n\n\ndef _parse_local_version(local: str) -> LocalType | None:\n """\n Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").\n """\n if local is not None:\n return tuple(\n part.lower() if not part.isdigit() else int(part)\n for part in _local_version_separators.split(local)\n )\n return None\n\n\ndef _cmpkey(\n epoch: int,\n release: tuple[int, ...],\n pre: tuple[str, int] | None,\n post: tuple[str, int] | None,\n dev: tuple[str, int] | None,\n local: tuple[SubLocalType] | None,\n) -> CmpKey:\n # When we compare a release version, we want to compare it with all of the\n # trailing zeros removed. So we'll use a reverse the list, drop all the now\n # leading zeros until we come to something non zero, then take the rest\n # re-reverse it back into the correct order and make it a tuple and use\n # that for our sorting key.\n _release = tuple(\n reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))\n )\n\n # We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.\n # We'll do this by abusing the pre segment, but we _only_ want to do this\n # if there is not a pre or a post segment. If we have one of those then\n # the normal sorting rules will handle this case correctly.\n if pre is None and post is None and dev is not None:\n _pre: PrePostDevType = NegativeInfinity\n # Versions without a pre-release (except as noted above) should sort after\n # those with one.\n elif pre is None:\n _pre = Infinity\n else:\n _pre = pre\n\n # Versions without a post segment should sort before those with one.\n if post is None:\n _post: PrePostDevType = NegativeInfinity\n\n else:\n _post = post\n\n # Versions without a development segment should sort after those with one.\n if dev is None:\n _dev: PrePostDevType = Infinity\n\n else:\n _dev = dev\n\n if local is None:\n # Versions without a local segment should sort before those with one.\n _local: LocalType = NegativeInfinity\n else:\n # Versions with a local segment need that segment parsed to implement\n # the sorting rules in PEP440.\n # - Alpha numeric segments sort before numeric segments\n # - Alpha numeric segments sort lexicographically\n # - Numeric segments sort numerically\n # - Shorter versions sort before longer versions when the prefixes\n # match exactly\n _local = tuple(\n (i, "") if isinstance(i, int) else (NegativeInfinity, i) for i in local\n )\n\n return epoch, _release, _pre, _post, _dev, _local\n
.venv\Lib\site-packages\pandas\util\version\__init__.py
__init__.py
Python
16,394
0.95
0.217617
0.136771
react-lib
29
2024-11-02T23:22:37.847978
BSD-3-Clause
false
ce7392eec677af6c2efa4d643deafc50
\n\n
.venv\Lib\site-packages\pandas\util\version\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
22,682
0.8
0.015306
0.005348
python-kit
648
2024-06-19T09:45:44.008073
BSD-3-Clause
false
b11fba396b5e6b69b3f5475a8a598399
\n\n
.venv\Lib\site-packages\pandas\util\__pycache__\_decorators.cpython-313.pyc
_decorators.cpython-313.pyc
Other
19,438
0.95
0.133333
0.014652
python-kit
780
2024-01-11T21:00:20.024501
BSD-3-Clause
false
470d44bda50b3817a7dac463c7670b1d
\n\n
.venv\Lib\site-packages\pandas\util\__pycache__\_doctools.cpython-313.pyc
_doctools.cpython-313.pyc
Other
11,199
0.8
0.018182
0.038462
awesome-app
925
2024-06-16T08:14:37.349267
GPL-3.0
false
7c41cd41f0316e8bfd0a65eaa813061a
\n\n
.venv\Lib\site-packages\pandas\util\__pycache__\_exceptions.cpython-313.pyc
_exceptions.cpython-313.pyc
Other
3,833
0.8
0
0
node-utils
870
2025-07-03T20:53:15.661478
MIT
false
1ed235728ac4e7ac2eb08cd0c75bb419
\n\n
.venv\Lib\site-packages\pandas\util\__pycache__\_print_versions.cpython-313.pyc
_print_versions.cpython-313.pyc
Other
5,751
0.95
0.01087
0.034884
node-utils
543
2025-01-17T01:25:42.961010
Apache-2.0
false
5005441d9f5ae77a52f26986bfa6f656
\n\n
.venv\Lib\site-packages\pandas\util\__pycache__\_tester.cpython-313.pyc
_tester.cpython-313.pyc
Other
2,050
0.95
0.025641
0
awesome-app
543
2025-06-04T18:44:08.464371
Apache-2.0
true
9535092089b8f8d13916678489698441
\n\n
.venv\Lib\site-packages\pandas\util\__pycache__\_test_decorators.cpython-313.pyc
_test_decorators.cpython-313.pyc
Other
6,204
0.95
0.170543
0
awesome-app
260
2024-12-22T12:35:31.241424
GPL-3.0
true
1d403d57af309c897ff6d9ab245bf0f7
\n\n
.venv\Lib\site-packages\pandas\util\__pycache__\_validators.cpython-313.pyc
_validators.cpython-313.pyc
Other
14,501
0.95
0.116105
0.004202
awesome-app
403
2025-03-02T16:53:47.849048
Apache-2.0
false
c4671d16902aa6715a167749a0dd2df5
\n\n
.venv\Lib\site-packages\pandas\util\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
1,068
0.7
0
0
awesome-app
990
2024-07-20T10:26:15.384750
BSD-3-Clause
false
ce13cb405c35e92e0af29375e06c3fb0
"""\nThe config module holds package-wide configurables and provides\na uniform API for working with them.\n\nOverview\n========\n\nThis module supports the following requirements:\n- options are referenced using keys in dot.notation, e.g. "x.y.option - z".\n- keys are case-insensitive.\n- functions should accept partial/regex keys, when unambiguous.\n- options can be registered by modules at import time.\n- options can be registered at init-time (via core.config_init)\n- options have a default value, and (optionally) a description and\n validation function associated with them.\n- options can be deprecated, in which case referencing them\n should produce a warning.\n- deprecated options can optionally be rerouted to a replacement\n so that accessing a deprecated option reroutes to a differently\n named option.\n- options can be reset to their default value.\n- all option can be reset to their default value at once.\n- all options in a certain sub - namespace can be reset at once.\n- the user can set / get / reset or ask for the description of an option.\n- a developer can register and mark an option as deprecated.\n- you can register a callback to be invoked when the option value\n is set or reset. Changing the stored value is considered misuse, but\n is not verboten.\n\nImplementation\n==============\n\n- Data is stored using nested dictionaries, and should be accessed\n through the provided API.\n\n- "Registered options" and "Deprecated options" have metadata associated\n with them, which are stored in auxiliary dictionaries keyed on the\n fully-qualified key, e.g. "x.y.z.option".\n\n- the config_init module is imported by the package's __init__.py file.\n placing any register_option() calls there will ensure those options\n are available as soon as pandas is loaded. If you use register_option\n in a module, it will only be available after that module is imported,\n which you should be aware of.\n\n- `config_prefix` is a context_manager (for use with the `with` keyword)\n which can save developers some typing, see the docstring.\n\n"""\n\nfrom __future__ import annotations\n\nfrom contextlib import (\n ContextDecorator,\n contextmanager,\n)\nimport re\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n Generic,\n NamedTuple,\n cast,\n)\nimport warnings\n\nfrom pandas._typing import (\n F,\n T,\n)\nfrom pandas.util._exceptions import find_stack_level\n\nif TYPE_CHECKING:\n from collections.abc import (\n Generator,\n Iterable,\n )\n\n\nclass DeprecatedOption(NamedTuple):\n key: str\n msg: str | None\n rkey: str | None\n removal_ver: str | None\n\n\nclass RegisteredOption(NamedTuple):\n key: str\n defval: object\n doc: str\n validator: Callable[[object], Any] | None\n cb: Callable[[str], Any] | None\n\n\n# holds deprecated option metadata\n_deprecated_options: dict[str, DeprecatedOption] = {}\n\n# holds registered option metadata\n_registered_options: dict[str, RegisteredOption] = {}\n\n# holds the current values for registered options\n_global_config: dict[str, Any] = {}\n\n# keys which have a special meaning\n_reserved_keys: list[str] = ["all"]\n\n\nclass OptionError(AttributeError, KeyError):\n """\n Exception raised for pandas.options.\n\n Backwards compatible with KeyError checks.\n\n Examples\n --------\n >>> pd.options.context\n Traceback (most recent call last):\n OptionError: No such option\n """\n\n\n#\n# User API\n\n\ndef _get_single_key(pat: str, silent: bool) -> str:\n keys = _select_options(pat)\n if len(keys) == 0:\n if not silent:\n _warn_if_deprecated(pat)\n raise OptionError(f"No such keys(s): {repr(pat)}")\n if len(keys) > 1:\n raise OptionError("Pattern matched multiple keys")\n key = keys[0]\n\n if not silent:\n _warn_if_deprecated(key)\n\n key = _translate_key(key)\n\n return key\n\n\ndef _get_option(pat: str, silent: bool = False) -> Any:\n key = _get_single_key(pat, silent)\n\n # walk the nested dict\n root, k = _get_root(key)\n return root[k]\n\n\ndef _set_option(*args, **kwargs) -> None:\n # must at least 1 arg deal with constraints later\n nargs = len(args)\n if not nargs or nargs % 2 != 0:\n raise ValueError("Must provide an even number of non-keyword arguments")\n\n # default to false\n silent = kwargs.pop("silent", False)\n\n if kwargs:\n kwarg = next(iter(kwargs.keys()))\n raise TypeError(f'_set_option() got an unexpected keyword argument "{kwarg}"')\n\n for k, v in zip(args[::2], args[1::2]):\n key = _get_single_key(k, silent)\n\n o = _get_registered_option(key)\n if o and o.validator:\n o.validator(v)\n\n # walk the nested dict\n root, k_root = _get_root(key)\n root[k_root] = v\n\n if o.cb:\n if silent:\n with warnings.catch_warnings(record=True):\n o.cb(key)\n else:\n o.cb(key)\n\n\ndef _describe_option(pat: str = "", _print_desc: bool = True) -> str | None:\n keys = _select_options(pat)\n if len(keys) == 0:\n raise OptionError("No such keys(s)")\n\n s = "\n".join([_build_option_description(k) for k in keys])\n\n if _print_desc:\n print(s)\n return None\n return s\n\n\ndef _reset_option(pat: str, silent: bool = False) -> None:\n keys = _select_options(pat)\n\n if len(keys) == 0:\n raise OptionError("No such keys(s)")\n\n if len(keys) > 1 and len(pat) < 4 and pat != "all":\n raise ValueError(\n "You must specify at least 4 characters when "\n "resetting multiple keys, use the special keyword "\n '"all" to reset all the options to their default value'\n )\n\n for k in keys:\n _set_option(k, _registered_options[k].defval, silent=silent)\n\n\ndef get_default_val(pat: str):\n key = _get_single_key(pat, silent=True)\n return _get_registered_option(key).defval\n\n\nclass DictWrapper:\n """provide attribute-style access to a nested dict"""\n\n d: dict[str, Any]\n\n def __init__(self, d: dict[str, Any], prefix: str = "") -> None:\n object.__setattr__(self, "d", d)\n object.__setattr__(self, "prefix", prefix)\n\n def __setattr__(self, key: str, val: Any) -> None:\n prefix = object.__getattribute__(self, "prefix")\n if prefix:\n prefix += "."\n prefix += key\n # you can't set new keys\n # can you can't overwrite subtrees\n if key in self.d and not isinstance(self.d[key], dict):\n _set_option(prefix, val)\n else:\n raise OptionError("You can only set the value of existing options")\n\n def __getattr__(self, key: str):\n prefix = object.__getattribute__(self, "prefix")\n if prefix:\n prefix += "."\n prefix += key\n try:\n v = object.__getattribute__(self, "d")[key]\n except KeyError as err:\n raise OptionError("No such option") from err\n if isinstance(v, dict):\n return DictWrapper(v, prefix)\n else:\n return _get_option(prefix)\n\n def __dir__(self) -> list[str]:\n return list(self.d.keys())\n\n\n# For user convenience, we'd like to have the available options described\n# in the docstring. For dev convenience we'd like to generate the docstrings\n# dynamically instead of maintaining them by hand. To this, we use the\n# class below which wraps functions inside a callable, and converts\n# __doc__ into a property function. The doctsrings below are templates\n# using the py2.6+ advanced formatting syntax to plug in a concise list\n# of options, and option descriptions.\n\n\nclass CallableDynamicDoc(Generic[T]):\n def __init__(self, func: Callable[..., T], doc_tmpl: str) -> None:\n self.__doc_tmpl__ = doc_tmpl\n self.__func__ = func\n\n def __call__(self, *args, **kwds) -> T:\n return self.__func__(*args, **kwds)\n\n # error: Signature of "__doc__" incompatible with supertype "object"\n @property\n def __doc__(self) -> str: # type: ignore[override]\n opts_desc = _describe_option("all", _print_desc=False)\n opts_list = pp_options_list(list(_registered_options.keys()))\n return self.__doc_tmpl__.format(opts_desc=opts_desc, opts_list=opts_list)\n\n\n_get_option_tmpl = """\nget_option(pat)\n\nRetrieves the value of the specified option.\n\nAvailable options:\n\n{opts_list}\n\nParameters\n----------\npat : str\n Regexp which should match a single option.\n Note: partial matches are supported for convenience, but unless you use the\n full option name (e.g. x.y.z.option_name), your code may break in future\n versions if new options with similar names are introduced.\n\nReturns\n-------\nresult : the value of the option\n\nRaises\n------\nOptionError : if no such option exists\n\nNotes\n-----\nPlease reference the :ref:`User Guide <options>` for more information.\n\nThe available options with its descriptions:\n\n{opts_desc}\n\nExamples\n--------\n>>> pd.get_option('display.max_columns') # doctest: +SKIP\n4\n"""\n\n_set_option_tmpl = """\nset_option(pat, value)\n\nSets the value of the specified option.\n\nAvailable options:\n\n{opts_list}\n\nParameters\n----------\npat : str\n Regexp which should match a single option.\n Note: partial matches are supported for convenience, but unless you use the\n full option name (e.g. x.y.z.option_name), your code may break in future\n versions if new options with similar names are introduced.\nvalue : object\n New value of option.\n\nReturns\n-------\nNone\n\nRaises\n------\nOptionError if no such option exists\n\nNotes\n-----\nPlease reference the :ref:`User Guide <options>` for more information.\n\nThe available options with its descriptions:\n\n{opts_desc}\n\nExamples\n--------\n>>> pd.set_option('display.max_columns', 4)\n>>> df = pd.DataFrame([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])\n>>> df\n 0 1 ... 3 4\n0 1 2 ... 4 5\n1 6 7 ... 9 10\n[2 rows x 5 columns]\n>>> pd.reset_option('display.max_columns')\n"""\n\n_describe_option_tmpl = """\ndescribe_option(pat, _print_desc=False)\n\nPrints the description for one or more registered options.\n\nCall with no arguments to get a listing for all registered options.\n\nAvailable options:\n\n{opts_list}\n\nParameters\n----------\npat : str\n Regexp pattern. All matching keys will have their description displayed.\n_print_desc : bool, default True\n If True (default) the description(s) will be printed to stdout.\n Otherwise, the description(s) will be returned as a unicode string\n (for testing).\n\nReturns\n-------\nNone by default, the description(s) as a unicode string if _print_desc\nis False\n\nNotes\n-----\nPlease reference the :ref:`User Guide <options>` for more information.\n\nThe available options with its descriptions:\n\n{opts_desc}\n\nExamples\n--------\n>>> pd.describe_option('display.max_columns') # doctest: +SKIP\ndisplay.max_columns : int\n If max_cols is exceeded, switch to truncate view...\n"""\n\n_reset_option_tmpl = """\nreset_option(pat)\n\nReset one or more options to their default value.\n\nPass "all" as argument to reset all options.\n\nAvailable options:\n\n{opts_list}\n\nParameters\n----------\npat : str/regex\n If specified only options matching `prefix*` will be reset.\n Note: partial matches are supported for convenience, but unless you\n use the full option name (e.g. x.y.z.option_name), your code may break\n in future versions if new options with similar names are introduced.\n\nReturns\n-------\nNone\n\nNotes\n-----\nPlease reference the :ref:`User Guide <options>` for more information.\n\nThe available options with its descriptions:\n\n{opts_desc}\n\nExamples\n--------\n>>> pd.reset_option('display.max_columns') # doctest: +SKIP\n"""\n\n# bind the functions with their docstrings into a Callable\n# and use that as the functions exposed in pd.api\nget_option = CallableDynamicDoc(_get_option, _get_option_tmpl)\nset_option = CallableDynamicDoc(_set_option, _set_option_tmpl)\nreset_option = CallableDynamicDoc(_reset_option, _reset_option_tmpl)\ndescribe_option = CallableDynamicDoc(_describe_option, _describe_option_tmpl)\noptions = DictWrapper(_global_config)\n\n#\n# Functions for use by pandas developers, in addition to User - api\n\n\nclass option_context(ContextDecorator):\n """\n Context manager to temporarily set options in the `with` statement context.\n\n You need to invoke as ``option_context(pat, val, [(pat, val), ...])``.\n\n Examples\n --------\n >>> from pandas import option_context\n >>> with option_context('display.max_rows', 10, 'display.max_columns', 5):\n ... pass\n """\n\n def __init__(self, *args) -> None:\n if len(args) % 2 != 0 or len(args) < 2:\n raise ValueError(\n "Need to invoke as option_context(pat, val, [(pat, val), ...])."\n )\n\n self.ops = list(zip(args[::2], args[1::2]))\n\n def __enter__(self) -> None:\n self.undo = [(pat, _get_option(pat)) for pat, val in self.ops]\n\n for pat, val in self.ops:\n _set_option(pat, val, silent=True)\n\n def __exit__(self, *args) -> None:\n if self.undo:\n for pat, val in self.undo:\n _set_option(pat, val, silent=True)\n\n\ndef register_option(\n key: str,\n defval: object,\n doc: str = "",\n validator: Callable[[object], Any] | None = None,\n cb: Callable[[str], Any] | None = None,\n) -> None:\n """\n Register an option in the package-wide pandas config object\n\n Parameters\n ----------\n key : str\n Fully-qualified key, e.g. "x.y.option - z".\n defval : object\n Default value of the option.\n doc : str\n Description of the option.\n validator : Callable, optional\n Function of a single argument, should raise `ValueError` if\n called with a value which is not a legal value for the option.\n cb\n a function of a single argument "key", which is called\n immediately after an option value is set/reset. key is\n the full name of the option.\n\n Raises\n ------\n ValueError if `validator` is specified and `defval` is not a valid value.\n\n """\n import keyword\n import tokenize\n\n key = key.lower()\n\n if key in _registered_options:\n raise OptionError(f"Option '{key}' has already been registered")\n if key in _reserved_keys:\n raise OptionError(f"Option '{key}' is a reserved key")\n\n # the default value should be legal\n if validator:\n validator(defval)\n\n # walk the nested dict, creating dicts as needed along the path\n path = key.split(".")\n\n for k in path:\n if not re.match("^" + tokenize.Name + "$", k):\n raise ValueError(f"{k} is not a valid identifier")\n if keyword.iskeyword(k):\n raise ValueError(f"{k} is a python keyword")\n\n cursor = _global_config\n msg = "Path prefix to option '{option}' is already an option"\n\n for i, p in enumerate(path[:-1]):\n if not isinstance(cursor, dict):\n raise OptionError(msg.format(option=".".join(path[:i])))\n if p not in cursor:\n cursor[p] = {}\n cursor = cursor[p]\n\n if not isinstance(cursor, dict):\n raise OptionError(msg.format(option=".".join(path[:-1])))\n\n cursor[path[-1]] = defval # initialize\n\n # save the option metadata\n _registered_options[key] = RegisteredOption(\n key=key, defval=defval, doc=doc, validator=validator, cb=cb\n )\n\n\ndef deprecate_option(\n key: str,\n msg: str | None = None,\n rkey: str | None = None,\n removal_ver: str | None = None,\n) -> None:\n """\n Mark option `key` as deprecated, if code attempts to access this option,\n a warning will be produced, using `msg` if given, or a default message\n if not.\n if `rkey` is given, any access to the key will be re-routed to `rkey`.\n\n Neither the existence of `key` nor that if `rkey` is checked. If they\n do not exist, any subsequence access will fail as usual, after the\n deprecation warning is given.\n\n Parameters\n ----------\n key : str\n Name of the option to be deprecated.\n must be a fully-qualified option name (e.g "x.y.z.rkey").\n msg : str, optional\n Warning message to output when the key is referenced.\n if no message is given a default message will be emitted.\n rkey : str, optional\n Name of an option to reroute access to.\n If specified, any referenced `key` will be\n re-routed to `rkey` including set/get/reset.\n rkey must be a fully-qualified option name (e.g "x.y.z.rkey").\n used by the default message if no `msg` is specified.\n removal_ver : str, optional\n Specifies the version in which this option will\n be removed. used by the default message if no `msg` is specified.\n\n Raises\n ------\n OptionError\n If the specified key has already been deprecated.\n """\n key = key.lower()\n\n if key in _deprecated_options:\n raise OptionError(f"Option '{key}' has already been defined as deprecated.")\n\n _deprecated_options[key] = DeprecatedOption(key, msg, rkey, removal_ver)\n\n\n#\n# functions internal to the module\n\n\ndef _select_options(pat: str) -> list[str]:\n """\n returns a list of keys matching `pat`\n\n if pat=="all", returns all registered options\n """\n # short-circuit for exact key\n if pat in _registered_options:\n return [pat]\n\n # else look through all of them\n keys = sorted(_registered_options.keys())\n if pat == "all": # reserved key\n return keys\n\n return [k for k in keys if re.search(pat, k, re.I)]\n\n\ndef _get_root(key: str) -> tuple[dict[str, Any], str]:\n path = key.split(".")\n cursor = _global_config\n for p in path[:-1]:\n cursor = cursor[p]\n return cursor, path[-1]\n\n\ndef _is_deprecated(key: str) -> bool:\n """Returns True if the given option has been deprecated"""\n key = key.lower()\n return key in _deprecated_options\n\n\ndef _get_deprecated_option(key: str):\n """\n Retrieves the metadata for a deprecated option, if `key` is deprecated.\n\n Returns\n -------\n DeprecatedOption (namedtuple) if key is deprecated, None otherwise\n """\n try:\n d = _deprecated_options[key]\n except KeyError:\n return None\n else:\n return d\n\n\ndef _get_registered_option(key: str):\n """\n Retrieves the option metadata if `key` is a registered option.\n\n Returns\n -------\n RegisteredOption (namedtuple) if key is deprecated, None otherwise\n """\n return _registered_options.get(key)\n\n\ndef _translate_key(key: str) -> str:\n """\n if key id deprecated and a replacement key defined, will return the\n replacement key, otherwise returns `key` as - is\n """\n d = _get_deprecated_option(key)\n if d:\n return d.rkey or key\n else:\n return key\n\n\ndef _warn_if_deprecated(key: str) -> bool:\n """\n Checks if `key` is a deprecated option and if so, prints a warning.\n\n Returns\n -------\n bool - True if `key` is deprecated, False otherwise.\n """\n d = _get_deprecated_option(key)\n if d:\n if d.msg:\n warnings.warn(\n d.msg,\n FutureWarning,\n stacklevel=find_stack_level(),\n )\n else:\n msg = f"'{key}' is deprecated"\n if d.removal_ver:\n msg += f" and will be removed in {d.removal_ver}"\n if d.rkey:\n msg += f", please use '{d.rkey}' instead."\n else:\n msg += ", please refrain from using it."\n\n warnings.warn(msg, FutureWarning, stacklevel=find_stack_level())\n return True\n return False\n\n\ndef _build_option_description(k: str) -> str:\n """Builds a formatted description of a registered option and prints it"""\n o = _get_registered_option(k)\n d = _get_deprecated_option(k)\n\n s = f"{k} "\n\n if o.doc:\n s += "\n".join(o.doc.strip().split("\n"))\n else:\n s += "No description available."\n\n if o:\n s += f"\n [default: {o.defval}] [currently: {_get_option(k, True)}]"\n\n if d:\n rkey = d.rkey or ""\n s += "\n (Deprecated"\n s += f", use `{rkey}` instead."\n s += ")"\n\n return s\n\n\ndef pp_options_list(keys: Iterable[str], width: int = 80, _print: bool = False):\n """Builds a concise listing of available options, grouped by prefix"""\n from itertools import groupby\n from textwrap import wrap\n\n def pp(name: str, ks: Iterable[str]) -> list[str]:\n pfx = "- " + name + ".[" if name else ""\n ls = wrap(\n ", ".join(ks),\n width,\n initial_indent=pfx,\n subsequent_indent=" ",\n break_long_words=False,\n )\n if ls and ls[-1] and name:\n ls[-1] = ls[-1] + "]"\n return ls\n\n ls: list[str] = []\n singles = [x for x in sorted(keys) if x.find(".") < 0]\n if singles:\n ls += pp("", singles)\n keys = [x for x in keys if x.find(".") >= 0]\n\n for k, g in groupby(sorted(keys), lambda x: x[: x.rfind(".")]):\n ks = [x[len(k) + 1 :] for x in list(g)]\n ls += pp(k, ks)\n s = "\n".join(ls)\n if _print:\n print(s)\n else:\n return s\n\n\n#\n# helpers\n\n\n@contextmanager\ndef config_prefix(prefix: str) -> Generator[None, None, None]:\n """\n contextmanager for multiple invocations of API with a common prefix\n\n supported API functions: (register / get / set )__option\n\n Warning: This is not thread - safe, and won't work properly if you import\n the API functions into your module using the "from x import y" construct.\n\n Example\n -------\n import pandas._config.config as cf\n with cf.config_prefix("display.font"):\n cf.register_option("color", "red")\n cf.register_option("size", " 5 pt")\n cf.set_option(size, " 6 pt")\n cf.get_option(size)\n ...\n\n etc'\n\n will register options "display.font.color", "display.font.size", set the\n value of "display.font.size"... and so on.\n """\n # Note: reset_option relies on set_option, and on key directly\n # it does not fit in to this monkey-patching scheme\n\n global register_option, get_option, set_option\n\n def wrap(func: F) -> F:\n def inner(key: str, *args, **kwds):\n pkey = f"{prefix}.{key}"\n return func(pkey, *args, **kwds)\n\n return cast(F, inner)\n\n _register_option = register_option\n _get_option = get_option\n _set_option = set_option\n set_option = wrap(set_option)\n get_option = wrap(get_option)\n register_option = wrap(register_option)\n try:\n yield\n finally:\n set_option = _set_option\n get_option = _get_option\n register_option = _register_option\n\n\n# These factories and methods are handy for use as the validator\n# arg in register_option\n\n\ndef is_type_factory(_type: type[Any]) -> Callable[[Any], None]:\n """\n\n Parameters\n ----------\n `_type` - a type to be compared against (e.g. type(x) == `_type`)\n\n Returns\n -------\n validator - a function of a single argument x , which raises\n ValueError if type(x) is not equal to `_type`\n\n """\n\n def inner(x) -> None:\n if type(x) != _type:\n raise ValueError(f"Value must have type '{_type}'")\n\n return inner\n\n\ndef is_instance_factory(_type) -> Callable[[Any], None]:\n """\n\n Parameters\n ----------\n `_type` - the type to be checked against\n\n Returns\n -------\n validator - a function of a single argument x , which raises\n ValueError if x is not an instance of `_type`\n\n """\n if isinstance(_type, (tuple, list)):\n _type = tuple(_type)\n type_repr = "|".join(map(str, _type))\n else:\n type_repr = f"'{_type}'"\n\n def inner(x) -> None:\n if not isinstance(x, _type):\n raise ValueError(f"Value must be an instance of {type_repr}")\n\n return inner\n\n\ndef is_one_of_factory(legal_values) -> Callable[[Any], None]:\n callables = [c for c in legal_values if callable(c)]\n legal_values = [c for c in legal_values if not callable(c)]\n\n def inner(x) -> None:\n if x not in legal_values:\n if not any(c(x) for c in callables):\n uvals = [str(lval) for lval in legal_values]\n pp_values = "|".join(uvals)\n msg = f"Value must be one of {pp_values}"\n if len(callables):\n msg += " or a callable"\n raise ValueError(msg)\n\n return inner\n\n\ndef is_nonnegative_int(value: object) -> None:\n """\n Verify that value is None or a positive int.\n\n Parameters\n ----------\n value : None or int\n The `value` to be checked.\n\n Raises\n ------\n ValueError\n When the value is not None or is a negative integer\n """\n if value is None:\n return\n\n elif isinstance(value, int):\n if value >= 0:\n return\n\n msg = "Value must be a nonnegative integer or None"\n raise ValueError(msg)\n\n\n# common type validators, for convenience\n# usage: register_option(... , validator = is_int)\nis_int = is_type_factory(int)\nis_bool = is_type_factory(bool)\nis_float = is_type_factory(float)\nis_str = is_type_factory(str)\nis_text = is_instance_factory((str, bytes))\n\n\ndef is_callable(obj) -> bool:\n """\n\n Parameters\n ----------\n `obj` - the object to be checked\n\n Returns\n -------\n validator - returns True if object is callable\n raises ValueError otherwise.\n\n """\n if not callable(obj):\n raise ValueError("Value must be a callable")\n return True\n
.venv\Lib\site-packages\pandas\_config\config.py
config.py
Python
25,454
0.95
0.191983
0.054017
vue-tools
118
2024-04-13T18:22:00.558167
Apache-2.0
false
e306310d61190dac893e5d91a12ac02e
"""\nconfig for datetime formatting\n"""\nfrom __future__ import annotations\n\nfrom pandas._config import config as cf\n\npc_date_dayfirst_doc = """\n: boolean\n When True, prints and parses dates with the day first, eg 20/01/2005\n"""\n\npc_date_yearfirst_doc = """\n: boolean\n When True, prints and parses dates with the year first, eg 2005/01/20\n"""\n\nwith cf.config_prefix("display"):\n # Needed upstream of `_libs` because these are used in tslibs.parsing\n cf.register_option(\n "date_dayfirst", False, pc_date_dayfirst_doc, validator=cf.is_bool\n )\n cf.register_option(\n "date_yearfirst", False, pc_date_yearfirst_doc, validator=cf.is_bool\n )\n
.venv\Lib\site-packages\pandas\_config\dates.py
dates.py
Python
668
0.95
0.04
0.047619
awesome-app
177
2024-11-03T10:44:27.291772
Apache-2.0
false
23ea8ad7937d46948d970193bf4c8ef8
"""\nUnopinionated display configuration.\n"""\n\nfrom __future__ import annotations\n\nimport locale\nimport sys\n\nfrom pandas._config import config as cf\n\n# -----------------------------------------------------------------------------\n# Global formatting options\n_initial_defencoding: str | None = None\n\n\ndef detect_console_encoding() -> str:\n """\n Try to find the most capable encoding supported by the console.\n slightly modified from the way IPython handles the same issue.\n """\n global _initial_defencoding\n\n encoding = None\n try:\n encoding = sys.stdout.encoding or sys.stdin.encoding\n except (AttributeError, OSError):\n pass\n\n # try again for something better\n if not encoding or "ascii" in encoding.lower():\n try:\n encoding = locale.getpreferredencoding()\n except locale.Error:\n # can be raised by locale.setlocale(), which is\n # called by getpreferredencoding\n # (on some systems, see stdlib locale docs)\n pass\n\n # when all else fails. this will usually be "ascii"\n if not encoding or "ascii" in encoding.lower():\n encoding = sys.getdefaultencoding()\n\n # GH#3360, save the reported defencoding at import time\n # MPL backends may change it. Make available for debugging.\n if not _initial_defencoding:\n _initial_defencoding = sys.getdefaultencoding()\n\n return encoding\n\n\npc_encoding_doc = """\n: str/unicode\n Defaults to the detected encoding of the console.\n Specifies the encoding to be used for strings returned by to_string,\n these are generally strings meant to be displayed on the console.\n"""\n\nwith cf.config_prefix("display"):\n cf.register_option(\n "encoding", detect_console_encoding(), pc_encoding_doc, validator=cf.is_text\n )\n
.venv\Lib\site-packages\pandas\_config\display.py
display.py
Python
1,804
0.95
0.16129
0.1875
python-kit
534
2024-06-23T01:02:10.306599
GPL-3.0
false
140a2894c1059961c7dc525919d4a734
"""\nHelpers for configuring locale settings.\n\nName `localization` is chosen to avoid overlap with builtin `locale` module.\n"""\nfrom __future__ import annotations\n\nfrom contextlib import contextmanager\nimport locale\nimport platform\nimport re\nimport subprocess\nfrom typing import TYPE_CHECKING\n\nfrom pandas._config.config import options\n\nif TYPE_CHECKING:\n from collections.abc import Generator\n\n\n@contextmanager\ndef set_locale(\n new_locale: str | tuple[str, str], lc_var: int = locale.LC_ALL\n) -> Generator[str | tuple[str, str], None, None]:\n """\n Context manager for temporarily setting a locale.\n\n Parameters\n ----------\n new_locale : str or tuple\n A string of the form <language_country>.<encoding>. For example to set\n the current locale to US English with a UTF8 encoding, you would pass\n "en_US.UTF-8".\n lc_var : int, default `locale.LC_ALL`\n The category of the locale being set.\n\n Notes\n -----\n This is useful when you want to run a particular block of code under a\n particular locale, without globally setting the locale. This probably isn't\n thread-safe.\n """\n # getlocale is not always compliant with setlocale, use setlocale. GH#46595\n current_locale = locale.setlocale(lc_var)\n\n try:\n locale.setlocale(lc_var, new_locale)\n normalized_code, normalized_encoding = locale.getlocale()\n if normalized_code is not None and normalized_encoding is not None:\n yield f"{normalized_code}.{normalized_encoding}"\n else:\n yield new_locale\n finally:\n locale.setlocale(lc_var, current_locale)\n\n\ndef can_set_locale(lc: str, lc_var: int = locale.LC_ALL) -> bool:\n """\n Check to see if we can set a locale, and subsequently get the locale,\n without raising an Exception.\n\n Parameters\n ----------\n lc : str\n The locale to attempt to set.\n lc_var : int, default `locale.LC_ALL`\n The category of the locale being set.\n\n Returns\n -------\n bool\n Whether the passed locale can be set\n """\n try:\n with set_locale(lc, lc_var=lc_var):\n pass\n except (ValueError, locale.Error):\n # horrible name for a Exception subclass\n return False\n else:\n return True\n\n\ndef _valid_locales(locales: list[str] | str, normalize: bool) -> list[str]:\n """\n Return a list of normalized locales that do not throw an ``Exception``\n when set.\n\n Parameters\n ----------\n locales : str\n A string where each locale is separated by a newline.\n normalize : bool\n Whether to call ``locale.normalize`` on each locale.\n\n Returns\n -------\n valid_locales : list\n A list of valid locales.\n """\n return [\n loc\n for loc in (\n locale.normalize(loc.strip()) if normalize else loc.strip()\n for loc in locales\n )\n if can_set_locale(loc)\n ]\n\n\ndef get_locales(\n prefix: str | None = None,\n normalize: bool = True,\n) -> list[str]:\n """\n Get all the locales that are available on the system.\n\n Parameters\n ----------\n prefix : str\n If not ``None`` then return only those locales with the prefix\n provided. For example to get all English language locales (those that\n start with ``"en"``), pass ``prefix="en"``.\n normalize : bool\n Call ``locale.normalize`` on the resulting list of available locales.\n If ``True``, only locales that can be set without throwing an\n ``Exception`` are returned.\n\n Returns\n -------\n locales : list of strings\n A list of locale strings that can be set with ``locale.setlocale()``.\n For example::\n\n locale.setlocale(locale.LC_ALL, locale_string)\n\n On error will return an empty list (no locale available, e.g. Windows)\n\n """\n if platform.system() in ("Linux", "Darwin"):\n raw_locales = subprocess.check_output(["locale", "-a"])\n else:\n # Other platforms e.g. windows platforms don't define "locale -a"\n # Note: is_platform_windows causes circular import here\n return []\n\n try:\n # raw_locales is "\n" separated list of locales\n # it may contain non-decodable parts, so split\n # extract what we can and then rejoin.\n split_raw_locales = raw_locales.split(b"\n")\n out_locales = []\n for x in split_raw_locales:\n try:\n out_locales.append(str(x, encoding=options.display.encoding))\n except UnicodeError:\n # 'locale -a' is used to populated 'raw_locales' and on\n # Redhat 7 Linux (and maybe others) prints locale names\n # using windows-1252 encoding. Bug only triggered by\n # a few special characters and when there is an\n # extensive list of installed locales.\n out_locales.append(str(x, encoding="windows-1252"))\n\n except TypeError:\n pass\n\n if prefix is None:\n return _valid_locales(out_locales, normalize)\n\n pattern = re.compile(f"{prefix}.*")\n found = pattern.findall("\n".join(out_locales))\n return _valid_locales(found, normalize)\n
.venv\Lib\site-packages\pandas\_config\localization.py
localization.py
Python
5,190
0.95
0.122093
0.083333
awesome-app
618
2024-03-20T22:50:58.832525
Apache-2.0
false
7d33aef39b48198b984cf351929fa8dd
"""\npandas._config is considered explicitly upstream of everything else in pandas,\nshould have no intra-pandas dependencies.\n\nimporting `dates` and `display` ensures that keys needed by _libs\nare initialized.\n"""\n__all__ = [\n "config",\n "detect_console_encoding",\n "get_option",\n "set_option",\n "reset_option",\n "describe_option",\n "option_context",\n "options",\n "using_copy_on_write",\n "warn_copy_on_write",\n]\nfrom pandas._config import config\nfrom pandas._config import dates # pyright: ignore[reportUnusedImport] # noqa: F401\nfrom pandas._config.config import (\n _global_config,\n describe_option,\n get_option,\n option_context,\n options,\n reset_option,\n set_option,\n)\nfrom pandas._config.display import detect_console_encoding\n\n\ndef using_copy_on_write() -> bool:\n _mode_options = _global_config["mode"]\n return (\n _mode_options["copy_on_write"] is True\n and _mode_options["data_manager"] == "block"\n )\n\n\ndef warn_copy_on_write() -> bool:\n _mode_options = _global_config["mode"]\n return (\n _mode_options["copy_on_write"] == "warn"\n and _mode_options["data_manager"] == "block"\n )\n\n\ndef using_nullable_dtypes() -> bool:\n _mode_options = _global_config["mode"]\n return _mode_options["nullable_dtypes"]\n\n\ndef using_string_dtype() -> bool:\n _mode_options = _global_config["future"]\n return _mode_options["infer_string"]\n
.venv\Lib\site-packages\pandas\_config\__init__.py
__init__.py
Python
1,429
0.95
0.070175
0
python-kit
586
2025-05-02T10:11:43.012681
BSD-3-Clause
false
4e1a06613844393b5f875681d0b6f87a
\n\n
.venv\Lib\site-packages\pandas\_config\__pycache__\config.cpython-313.pyc
config.cpython-313.pyc
Other
32,650
0.95
0.093357
0
vue-tools
747
2024-12-31T03:25:12.430336
MIT
false
3dedcae33dbbb7190b29aeadfb16a4ca
\n\n
.venv\Lib\site-packages\pandas\_config\__pycache__\dates.cpython-313.pyc
dates.cpython-313.pyc
Other
977
0.8
0.052632
0
react-lib
146
2024-11-07T01:34:55.980102
GPL-3.0
false
de3dfc8308defae01167a8a94a5dfb19
\n\n
.venv\Lib\site-packages\pandas\_config\__pycache__\display.cpython-313.pyc
display.cpython-313.pyc
Other
2,102
0.8
0.030303
0
awesome-app
970
2024-10-01T12:24:00.226351
MIT
false
53bb4a7bf464cdf0b2f16ff6e846c42c
\n\n
.venv\Lib\site-packages\pandas\_config\__pycache__\localization.cpython-313.pyc
localization.cpython-313.pyc
Other
5,918
0.8
0.023256
0.017241
vue-tools
305
2024-11-05T11:20:24.920127
GPL-3.0
false
a0fd282193908167eff89a0f944f93fc
\n\n
.venv\Lib\site-packages\pandas\_config\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
1,808
0.85
0
0
react-lib
135
2025-03-26T22:47:55.439702
Apache-2.0
false
9ee6a14073e1e250a016a0dae574ed67
!<arch>\n/ -1 0 162 `\n
.venv\Lib\site-packages\pandas\_libs\algos.cp313-win_amd64.lib
algos.cp313-win_amd64.lib
Other
1,976
0.8
0
0
vue-tools
67
2024-08-08T20:36:26.372112
Apache-2.0
false
31c23f49a473c3fb2adc2df7d528a929
from typing import Any\n\nimport numpy as np\n\nfrom pandas._typing import npt\n\nclass Infinity:\n def __eq__(self, other) -> bool: ...\n def __ne__(self, other) -> bool: ...\n def __lt__(self, other) -> bool: ...\n def __le__(self, other) -> bool: ...\n def __gt__(self, other) -> bool: ...\n def __ge__(self, other) -> bool: ...\n\nclass NegInfinity:\n def __eq__(self, other) -> bool: ...\n def __ne__(self, other) -> bool: ...\n def __lt__(self, other) -> bool: ...\n def __le__(self, other) -> bool: ...\n def __gt__(self, other) -> bool: ...\n def __ge__(self, other) -> bool: ...\n\ndef unique_deltas(\n arr: np.ndarray, # const int64_t[:]\n) -> np.ndarray: ... # np.ndarray[np.int64, ndim=1]\ndef is_lexsorted(list_of_arrays: list[npt.NDArray[np.int64]]) -> bool: ...\ndef groupsort_indexer(\n index: np.ndarray, # const int64_t[:]\n ngroups: int,\n) -> tuple[\n np.ndarray, # ndarray[int64_t, ndim=1]\n np.ndarray, # ndarray[int64_t, ndim=1]\n]: ...\ndef kth_smallest(\n arr: np.ndarray, # numeric[:]\n k: int,\n) -> Any: ... # numeric\n\n# ----------------------------------------------------------------------\n# Pairwise correlation/covariance\n\ndef nancorr(\n mat: npt.NDArray[np.float64], # const float64_t[:, :]\n cov: bool = ...,\n minp: int | None = ...,\n) -> npt.NDArray[np.float64]: ... # ndarray[float64_t, ndim=2]\ndef nancorr_spearman(\n mat: npt.NDArray[np.float64], # ndarray[float64_t, ndim=2]\n minp: int = ...,\n) -> npt.NDArray[np.float64]: ... # ndarray[float64_t, ndim=2]\n\n# ----------------------------------------------------------------------\n\ndef validate_limit(nobs: int | None, limit=...) -> int: ...\ndef get_fill_indexer(\n mask: npt.NDArray[np.bool_],\n limit: int | None = None,\n) -> npt.NDArray[np.intp]: ...\ndef pad(\n old: np.ndarray, # ndarray[numeric_object_t]\n new: np.ndarray, # ndarray[numeric_object_t]\n limit=...,\n) -> npt.NDArray[np.intp]: ... # np.ndarray[np.intp, ndim=1]\ndef pad_inplace(\n values: np.ndarray, # numeric_object_t[:]\n mask: np.ndarray, # uint8_t[:]\n limit=...,\n) -> None: ...\ndef pad_2d_inplace(\n values: np.ndarray, # numeric_object_t[:, :]\n mask: np.ndarray, # const uint8_t[:, :]\n limit=...,\n) -> None: ...\ndef backfill(\n old: np.ndarray, # ndarray[numeric_object_t]\n new: np.ndarray, # ndarray[numeric_object_t]\n limit=...,\n) -> npt.NDArray[np.intp]: ... # np.ndarray[np.intp, ndim=1]\ndef backfill_inplace(\n values: np.ndarray, # numeric_object_t[:]\n mask: np.ndarray, # uint8_t[:]\n limit=...,\n) -> None: ...\ndef backfill_2d_inplace(\n values: np.ndarray, # numeric_object_t[:, :]\n mask: np.ndarray, # const uint8_t[:, :]\n limit=...,\n) -> None: ...\ndef is_monotonic(\n arr: np.ndarray, # ndarray[numeric_object_t, ndim=1]\n timelike: bool,\n) -> tuple[bool, bool, bool]: ...\n\n# ----------------------------------------------------------------------\n# rank_1d, rank_2d\n# ----------------------------------------------------------------------\n\ndef rank_1d(\n values: np.ndarray, # ndarray[numeric_object_t, ndim=1]\n labels: np.ndarray | None = ..., # const int64_t[:]=None\n is_datetimelike: bool = ...,\n ties_method=...,\n ascending: bool = ...,\n pct: bool = ...,\n na_option=...,\n mask: npt.NDArray[np.bool_] | None = ...,\n) -> np.ndarray: ... # np.ndarray[float64_t, ndim=1]\ndef rank_2d(\n in_arr: np.ndarray, # ndarray[numeric_object_t, ndim=2]\n axis: int = ...,\n is_datetimelike: bool = ...,\n ties_method=...,\n ascending: bool = ...,\n na_option=...,\n pct: bool = ...,\n) -> np.ndarray: ... # np.ndarray[float64_t, ndim=1]\ndef diff_2d(\n arr: np.ndarray, # ndarray[diff_t, ndim=2]\n out: np.ndarray, # ndarray[out_t, ndim=2]\n periods: int,\n axis: int,\n datetimelike: bool = ...,\n) -> None: ...\ndef ensure_platform_int(arr: object) -> npt.NDArray[np.intp]: ...\ndef ensure_object(arr: object) -> npt.NDArray[np.object_]: ...\ndef ensure_float64(arr: object) -> npt.NDArray[np.float64]: ...\ndef ensure_int8(arr: object) -> npt.NDArray[np.int8]: ...\ndef ensure_int16(arr: object) -> npt.NDArray[np.int16]: ...\ndef ensure_int32(arr: object) -> npt.NDArray[np.int32]: ...\ndef ensure_int64(arr: object) -> npt.NDArray[np.int64]: ...\ndef ensure_uint64(arr: object) -> npt.NDArray[np.uint64]: ...\ndef take_1d_int8_int8(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int8_int32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int8_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int8_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int16_int16(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int16_int32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int16_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int16_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int32_int32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int32_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int32_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int64_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_int64_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_float32_float32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_float32_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_float64_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_object_object(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_bool_bool(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_1d_bool_object(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int8_int8(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int8_int32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int8_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int8_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int16_int16(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int16_int32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int16_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int16_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int32_int32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int32_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int32_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int64_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_int64_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_float32_float32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_float32_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_float64_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_object_object(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_bool_bool(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis0_bool_object(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int8_int8(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int8_int32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int8_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int8_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int16_int16(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int16_int32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int16_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int16_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int32_int32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int32_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int32_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int64_int64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_int64_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_float32_float32(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_float32_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_float64_float64(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_object_object(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_bool_bool(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_axis1_bool_object(\n values: np.ndarray, indexer: npt.NDArray[np.intp], out: np.ndarray, fill_value=...\n) -> None: ...\ndef take_2d_multi_int8_int8(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int8_int32(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int8_int64(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int8_float64(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int16_int16(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int16_int32(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int16_int64(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int16_float64(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int32_int32(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int32_int64(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int32_float64(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int64_float64(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_float32_float32(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_float32_float64(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_float64_float64(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_object_object(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_bool_bool(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_bool_object(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\ndef take_2d_multi_int64_int64(\n values: np.ndarray,\n indexer: tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]],\n out: np.ndarray,\n fill_value=...,\n) -> None: ...\n
.venv\Lib\site-packages\pandas\_libs\algos.pyi
algos.pyi
Other
15,182
0.95
0.278846
0.014815
node-utils
906
2025-01-16T15:21:07.456523
GPL-3.0
false
6f24b96bbcc4d4fdcee8e819deffc0a3
!<arch>\n/ -1 0 166 `\n
.venv\Lib\site-packages\pandas\_libs\arrays.cp313-win_amd64.lib
arrays.cp313-win_amd64.lib
Other
1,996
0.8
0
0
react-lib
12
2024-02-17T05:03:03.351213
GPL-3.0
false
d58f76819c8a5ddd85d62941cfd44325
MZ
.venv\Lib\site-packages\pandas\_libs\arrays.cp313-win_amd64.pyd
arrays.cp313-win_amd64.pyd
Other
92,672
0.75
0.027481
0.006231
awesome-app
166
2025-02-27T12:11:49.421988
BSD-3-Clause
false
6f992885c9a4a0ac40a17a78404f5e1a
from typing import Sequence\n\nimport numpy as np\n\nfrom pandas._typing import (\n AxisInt,\n DtypeObj,\n Self,\n Shape,\n)\n\nclass NDArrayBacked:\n _dtype: DtypeObj\n _ndarray: np.ndarray\n def __init__(self, values: np.ndarray, dtype: DtypeObj) -> None: ...\n @classmethod\n def _simple_new(cls, values: np.ndarray, dtype: DtypeObj): ...\n def _from_backing_data(self, values: np.ndarray): ...\n def __setstate__(self, state): ...\n def __len__(self) -> int: ...\n @property\n def shape(self) -> Shape: ...\n @property\n def ndim(self) -> int: ...\n @property\n def size(self) -> int: ...\n @property\n def nbytes(self) -> int: ...\n def copy(self, order=...): ...\n def delete(self, loc, axis=...): ...\n def swapaxes(self, axis1, axis2): ...\n def repeat(self, repeats: int | Sequence[int], axis: int | None = ...): ...\n def reshape(self, *args, **kwargs): ...\n def ravel(self, order=...): ...\n @property\n def T(self): ...\n @classmethod\n def _concat_same_type(\n cls, to_concat: Sequence[Self], axis: AxisInt = ...\n ) -> Self: ...\n
.venv\Lib\site-packages\pandas\_libs\arrays.pyi
arrays.pyi
Other
1,105
0.85
0.45
0
node-utils
681
2024-02-05T03:19:46.716918
Apache-2.0
false
a71766a7f29810e1abfbd4681a5bc3a3
!<arch>\n/ -1 0 174 `\n
.venv\Lib\site-packages\pandas\_libs\byteswap.cp313-win_amd64.lib
byteswap.cp313-win_amd64.lib
Other
2,032
0.8
0
0
node-utils
691
2024-04-22T17:30:45.549176
Apache-2.0
false
84c8e82512e64a1cf8bd59164fda3eef
MZ
.venv\Lib\site-packages\pandas\_libs\byteswap.cp313-win_amd64.pyd
byteswap.cp313-win_amd64.pyd
Other
41,984
0.95
0.032609
0.014545
python-kit
347
2023-11-08T00:55:49.529363
Apache-2.0
false
5388012b65eb8db864cfd05d325bdb00
def read_float_with_byteswap(data: bytes, offset: int, byteswap: bool) -> float: ...\ndef read_double_with_byteswap(data: bytes, offset: int, byteswap: bool) -> float: ...\ndef read_uint16_with_byteswap(data: bytes, offset: int, byteswap: bool) -> int: ...\ndef read_uint32_with_byteswap(data: bytes, offset: int, byteswap: bool) -> int: ...\ndef read_uint64_with_byteswap(data: bytes, offset: int, byteswap: bool) -> int: ...\n
.venv\Lib\site-packages\pandas\_libs\byteswap.pyi
byteswap.pyi
Other
423
0.85
1
0
vue-tools
171
2024-07-03T20:29:39.174046
MIT
false
8ae91fcb13255a214d844684748a264c
!<arch>\n/ -1 0 170 `\n
.venv\Lib\site-packages\pandas\_libs\groupby.cp313-win_amd64.lib
groupby.cp313-win_amd64.lib
Other
2,012
0.8
0
0
vue-tools
325
2024-09-17T17:56:39.605902
Apache-2.0
false
c49ee6b84332e52b4be02163fad15eff
from typing import Literal\n\nimport numpy as np\n\nfrom pandas._typing import npt\n\ndef group_median_float64(\n out: np.ndarray, # ndarray[float64_t, ndim=2]\n counts: npt.NDArray[np.int64],\n values: np.ndarray, # ndarray[float64_t, ndim=2]\n labels: npt.NDArray[np.int64],\n min_count: int = ..., # Py_ssize_t\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n) -> None: ...\ndef group_cumprod(\n out: np.ndarray, # float64_t[:, ::1]\n values: np.ndarray, # const float64_t[:, :]\n labels: np.ndarray, # const int64_t[:]\n ngroups: int,\n is_datetimelike: bool,\n skipna: bool = ...,\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n) -> None: ...\ndef group_cumsum(\n out: np.ndarray, # int64float_t[:, ::1]\n values: np.ndarray, # ndarray[int64float_t, ndim=2]\n labels: np.ndarray, # const int64_t[:]\n ngroups: int,\n is_datetimelike: bool,\n skipna: bool = ...,\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n) -> None: ...\ndef group_shift_indexer(\n out: np.ndarray, # int64_t[::1]\n labels: np.ndarray, # const int64_t[:]\n ngroups: int,\n periods: int,\n) -> None: ...\ndef group_fillna_indexer(\n out: np.ndarray, # ndarray[intp_t]\n labels: np.ndarray, # ndarray[int64_t]\n sorted_labels: npt.NDArray[np.intp],\n mask: npt.NDArray[np.uint8],\n limit: int, # int64_t\n dropna: bool,\n) -> None: ...\ndef group_any_all(\n out: np.ndarray, # uint8_t[::1]\n values: np.ndarray, # const uint8_t[::1]\n labels: np.ndarray, # const int64_t[:]\n mask: np.ndarray, # const uint8_t[::1]\n val_test: Literal["any", "all"],\n skipna: bool,\n result_mask: np.ndarray | None,\n) -> None: ...\ndef group_sum(\n out: np.ndarray, # complexfloatingintuint_t[:, ::1]\n counts: np.ndarray, # int64_t[::1]\n values: np.ndarray, # ndarray[complexfloatingintuint_t, ndim=2]\n labels: np.ndarray, # const intp_t[:]\n mask: np.ndarray | None,\n result_mask: np.ndarray | None = ...,\n min_count: int = ...,\n is_datetimelike: bool = ...,\n) -> None: ...\ndef group_prod(\n out: np.ndarray, # int64float_t[:, ::1]\n counts: np.ndarray, # int64_t[::1]\n values: np.ndarray, # ndarray[int64float_t, ndim=2]\n labels: np.ndarray, # const intp_t[:]\n mask: np.ndarray | None,\n result_mask: np.ndarray | None = ...,\n min_count: int = ...,\n) -> None: ...\ndef group_var(\n out: np.ndarray, # floating[:, ::1]\n counts: np.ndarray, # int64_t[::1]\n values: np.ndarray, # ndarray[floating, ndim=2]\n labels: np.ndarray, # const intp_t[:]\n min_count: int = ..., # Py_ssize_t\n ddof: int = ..., # int64_t\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n is_datetimelike: bool = ...,\n name: str = ...,\n) -> None: ...\ndef group_skew(\n out: np.ndarray, # float64_t[:, ::1]\n counts: np.ndarray, # int64_t[::1]\n values: np.ndarray, # ndarray[float64_T, ndim=2]\n labels: np.ndarray, # const intp_t[::1]\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n skipna: bool = ...,\n) -> None: ...\ndef group_mean(\n out: np.ndarray, # floating[:, ::1]\n counts: np.ndarray, # int64_t[::1]\n values: np.ndarray, # ndarray[floating, ndim=2]\n labels: np.ndarray, # const intp_t[:]\n min_count: int = ..., # Py_ssize_t\n is_datetimelike: bool = ..., # bint\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n) -> None: ...\ndef group_ohlc(\n out: np.ndarray, # floatingintuint_t[:, ::1]\n counts: np.ndarray, # int64_t[::1]\n values: np.ndarray, # ndarray[floatingintuint_t, ndim=2]\n labels: np.ndarray, # const intp_t[:]\n min_count: int = ...,\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n) -> None: ...\ndef group_quantile(\n out: npt.NDArray[np.float64],\n values: np.ndarray, # ndarray[numeric, ndim=1]\n labels: npt.NDArray[np.intp],\n mask: npt.NDArray[np.uint8],\n qs: npt.NDArray[np.float64], # const\n starts: npt.NDArray[np.int64],\n ends: npt.NDArray[np.int64],\n interpolation: Literal["linear", "lower", "higher", "nearest", "midpoint"],\n result_mask: np.ndarray | None,\n is_datetimelike: bool,\n) -> None: ...\ndef group_last(\n out: np.ndarray, # rank_t[:, ::1]\n counts: np.ndarray, # int64_t[::1]\n values: np.ndarray, # ndarray[rank_t, ndim=2]\n labels: np.ndarray, # const int64_t[:]\n mask: npt.NDArray[np.bool_] | None,\n result_mask: npt.NDArray[np.bool_] | None = ...,\n min_count: int = ..., # Py_ssize_t\n is_datetimelike: bool = ...,\n skipna: bool = ...,\n) -> None: ...\ndef group_nth(\n out: np.ndarray, # rank_t[:, ::1]\n counts: np.ndarray, # int64_t[::1]\n values: np.ndarray, # ndarray[rank_t, ndim=2]\n labels: np.ndarray, # const int64_t[:]\n mask: npt.NDArray[np.bool_] | None,\n result_mask: npt.NDArray[np.bool_] | None = ...,\n min_count: int = ..., # int64_t\n rank: int = ..., # int64_t\n is_datetimelike: bool = ...,\n skipna: bool = ...,\n) -> None: ...\ndef group_rank(\n out: np.ndarray, # float64_t[:, ::1]\n values: np.ndarray, # ndarray[rank_t, ndim=2]\n labels: np.ndarray, # const int64_t[:]\n ngroups: int,\n is_datetimelike: bool,\n ties_method: Literal["average", "min", "max", "first", "dense"] = ...,\n ascending: bool = ...,\n pct: bool = ...,\n na_option: Literal["keep", "top", "bottom"] = ...,\n mask: npt.NDArray[np.bool_] | None = ...,\n) -> None: ...\ndef group_max(\n out: np.ndarray, # groupby_t[:, ::1]\n counts: np.ndarray, # int64_t[::1]\n values: np.ndarray, # ndarray[groupby_t, ndim=2]\n labels: np.ndarray, # const int64_t[:]\n min_count: int = ...,\n is_datetimelike: bool = ...,\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n) -> None: ...\ndef group_min(\n out: np.ndarray, # groupby_t[:, ::1]\n counts: np.ndarray, # int64_t[::1]\n values: np.ndarray, # ndarray[groupby_t, ndim=2]\n labels: np.ndarray, # const int64_t[:]\n min_count: int = ...,\n is_datetimelike: bool = ...,\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n) -> None: ...\ndef group_idxmin_idxmax(\n out: npt.NDArray[np.intp],\n counts: npt.NDArray[np.int64],\n values: np.ndarray, # ndarray[groupby_t, ndim=2]\n labels: npt.NDArray[np.intp],\n min_count: int = ...,\n is_datetimelike: bool = ...,\n mask: np.ndarray | None = ...,\n name: str = ...,\n skipna: bool = ...,\n result_mask: np.ndarray | None = ...,\n) -> None: ...\ndef group_cummin(\n out: np.ndarray, # groupby_t[:, ::1]\n values: np.ndarray, # ndarray[groupby_t, ndim=2]\n labels: np.ndarray, # const int64_t[:]\n ngroups: int,\n is_datetimelike: bool,\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n skipna: bool = ...,\n) -> None: ...\ndef group_cummax(\n out: np.ndarray, # groupby_t[:, ::1]\n values: np.ndarray, # ndarray[groupby_t, ndim=2]\n labels: np.ndarray, # const int64_t[:]\n ngroups: int,\n is_datetimelike: bool,\n mask: np.ndarray | None = ...,\n result_mask: np.ndarray | None = ...,\n skipna: bool = ...,\n) -> None: ...\n
.venv\Lib\site-packages\pandas\_libs\groupby.pyi
groupby.pyi
Other
7,251
0.95
0.097222
0
react-lib
362
2023-09-19T01:50:31.895712
BSD-3-Clause
false
022a0f3b83ccff25495fbd4628a5e108
!<arch>\n/ -1 0 170 `\n
.venv\Lib\site-packages\pandas\_libs\hashing.cp313-win_amd64.lib
hashing.cp313-win_amd64.lib
Other
2,012
0.8
0
0
vue-tools
164
2023-10-25T05:26:25.824696
MIT
false
6001347f112bf3372160ba0228c6c8f3
import numpy as np\n\nfrom pandas._typing import npt\n\ndef hash_object_array(\n arr: npt.NDArray[np.object_],\n key: str,\n encoding: str = ...,\n) -> npt.NDArray[np.uint64]: ...\n
.venv\Lib\site-packages\pandas\_libs\hashing.pyi
hashing.pyi
Other
181
0.85
0.111111
0
react-lib
563
2024-03-11T10:39:02.056159
Apache-2.0
false
57213d0c1c4afd41d8576fc897a43244
!<arch>\n/ -1 0 178 `\n
.venv\Lib\site-packages\pandas\_libs\hashtable.cp313-win_amd64.lib
hashtable.cp313-win_amd64.lib
Other
2,048
0.8
0
0
node-utils
426
2023-08-18T01:19:56.391947
Apache-2.0
false
8217c33ef5e12ebf7410a810eef708f2
from typing import (\n Any,\n Hashable,\n Literal,\n)\n\nimport numpy as np\n\nfrom pandas._typing import npt\n\ndef unique_label_indices(\n labels: np.ndarray, # const int64_t[:]\n) -> np.ndarray: ...\n\nclass Factorizer:\n count: int\n uniques: Any\n def __init__(self, size_hint: int) -> None: ...\n def get_count(self) -> int: ...\n def factorize(\n self,\n values: np.ndarray,\n na_sentinel=...,\n na_value=...,\n mask=...,\n ) -> npt.NDArray[np.intp]: ...\n\nclass ObjectFactorizer(Factorizer):\n table: PyObjectHashTable\n uniques: ObjectVector\n\nclass Int64Factorizer(Factorizer):\n table: Int64HashTable\n uniques: Int64Vector\n\nclass UInt64Factorizer(Factorizer):\n table: UInt64HashTable\n uniques: UInt64Vector\n\nclass Int32Factorizer(Factorizer):\n table: Int32HashTable\n uniques: Int32Vector\n\nclass UInt32Factorizer(Factorizer):\n table: UInt32HashTable\n uniques: UInt32Vector\n\nclass Int16Factorizer(Factorizer):\n table: Int16HashTable\n uniques: Int16Vector\n\nclass UInt16Factorizer(Factorizer):\n table: UInt16HashTable\n uniques: UInt16Vector\n\nclass Int8Factorizer(Factorizer):\n table: Int8HashTable\n uniques: Int8Vector\n\nclass UInt8Factorizer(Factorizer):\n table: UInt8HashTable\n uniques: UInt8Vector\n\nclass Float64Factorizer(Factorizer):\n table: Float64HashTable\n uniques: Float64Vector\n\nclass Float32Factorizer(Factorizer):\n table: Float32HashTable\n uniques: Float32Vector\n\nclass Complex64Factorizer(Factorizer):\n table: Complex64HashTable\n uniques: Complex64Vector\n\nclass Complex128Factorizer(Factorizer):\n table: Complex128HashTable\n uniques: Complex128Vector\n\nclass Int64Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.int64]: ...\n\nclass Int32Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.int32]: ...\n\nclass Int16Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.int16]: ...\n\nclass Int8Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.int8]: ...\n\nclass UInt64Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.uint64]: ...\n\nclass UInt32Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.uint32]: ...\n\nclass UInt16Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.uint16]: ...\n\nclass UInt8Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.uint8]: ...\n\nclass Float64Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.float64]: ...\n\nclass Float32Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.float32]: ...\n\nclass Complex128Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.complex128]: ...\n\nclass Complex64Vector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.complex64]: ...\n\nclass StringVector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.object_]: ...\n\nclass ObjectVector:\n def __init__(self, *args) -> None: ...\n def __len__(self) -> int: ...\n def to_array(self) -> npt.NDArray[np.object_]: ...\n\nclass HashTable:\n # NB: The base HashTable class does _not_ actually have these methods;\n # we are putting them here for the sake of mypy to avoid\n # reproducing them in each subclass below.\n def __init__(self, size_hint: int = ..., uses_mask: bool = ...) -> None: ...\n def __len__(self) -> int: ...\n def __contains__(self, key: Hashable) -> bool: ...\n def sizeof(self, deep: bool = ...) -> int: ...\n def get_state(self) -> dict[str, int]: ...\n # TODO: `val/key` type is subclass-specific\n def get_item(self, val): ... # TODO: return type?\n def set_item(self, key, val) -> None: ...\n def get_na(self): ... # TODO: return type?\n def set_na(self, val) -> None: ...\n def map_locations(\n self,\n values: np.ndarray, # np.ndarray[subclass-specific]\n mask: npt.NDArray[np.bool_] | None = ...,\n ) -> None: ...\n def lookup(\n self,\n values: np.ndarray, # np.ndarray[subclass-specific]\n mask: npt.NDArray[np.bool_] | None = ...,\n ) -> npt.NDArray[np.intp]: ...\n def get_labels(\n self,\n values: np.ndarray, # np.ndarray[subclass-specific]\n uniques, # SubclassTypeVector\n count_prior: int = ...,\n na_sentinel: int = ...,\n na_value: object = ...,\n mask=...,\n ) -> npt.NDArray[np.intp]: ...\n def unique(\n self,\n values: np.ndarray, # np.ndarray[subclass-specific]\n return_inverse: bool = ...,\n mask=...,\n ) -> (\n tuple[\n np.ndarray, # np.ndarray[subclass-specific]\n npt.NDArray[np.intp],\n ]\n | np.ndarray\n ): ... # np.ndarray[subclass-specific]\n def factorize(\n self,\n values: np.ndarray, # np.ndarray[subclass-specific]\n na_sentinel: int = ...,\n na_value: object = ...,\n mask=...,\n ignore_na: bool = True,\n ) -> tuple[np.ndarray, npt.NDArray[np.intp]]: ... # np.ndarray[subclass-specific]\n\nclass Complex128HashTable(HashTable): ...\nclass Complex64HashTable(HashTable): ...\nclass Float64HashTable(HashTable): ...\nclass Float32HashTable(HashTable): ...\n\nclass Int64HashTable(HashTable):\n # Only Int64HashTable has get_labels_groupby, map_keys_to_values\n def get_labels_groupby(\n self,\n values: npt.NDArray[np.int64], # const int64_t[:]\n ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.int64]]: ...\n def map_keys_to_values(\n self,\n keys: npt.NDArray[np.int64],\n values: npt.NDArray[np.int64], # const int64_t[:]\n ) -> None: ...\n\nclass Int32HashTable(HashTable): ...\nclass Int16HashTable(HashTable): ...\nclass Int8HashTable(HashTable): ...\nclass UInt64HashTable(HashTable): ...\nclass UInt32HashTable(HashTable): ...\nclass UInt16HashTable(HashTable): ...\nclass UInt8HashTable(HashTable): ...\nclass StringHashTable(HashTable): ...\nclass PyObjectHashTable(HashTable): ...\nclass IntpHashTable(HashTable): ...\n\ndef duplicated(\n values: np.ndarray,\n keep: Literal["last", "first", False] = ...,\n mask: npt.NDArray[np.bool_] | None = ...,\n) -> npt.NDArray[np.bool_]: ...\ndef mode(\n values: np.ndarray, dropna: bool, mask: npt.NDArray[np.bool_] | None = ...\n) -> np.ndarray: ...\ndef value_count(\n values: np.ndarray,\n dropna: bool,\n mask: npt.NDArray[np.bool_] | None = ...,\n) -> tuple[np.ndarray, npt.NDArray[np.int64], int]: ... # np.ndarray[same-as-values]\n\n# arr and values should have same dtype\ndef ismember(\n arr: np.ndarray,\n values: np.ndarray,\n) -> npt.NDArray[np.bool_]: ...\ndef object_hash(obj) -> int: ...\ndef objects_are_equal(a, b) -> bool: ...\n
.venv\Lib\site-packages\pandas\_libs\hashtable.pyi
hashtable.pyi
Other
7,424
0.95
0.452381
0.027907
python-kit
71
2025-03-31T02:44:35.339615
BSD-3-Clause
false
62762a847f51707c934c14e48a6d3ea5
!<arch>\n/ -1 0 162 `\n
.venv\Lib\site-packages\pandas\_libs\index.cp313-win_amd64.lib
index.cp313-win_amd64.lib
Other
1,976
0.8
0
0
python-kit
185
2023-08-25T18:50:12.126560
MIT
false
ac212b465f99d326a4b96648163e19cb
import numpy as np\n\nfrom pandas._typing import npt\n\nfrom pandas import MultiIndex\nfrom pandas.core.arrays import ExtensionArray\n\nmultiindex_nulls_shift: int\n\nclass IndexEngine:\n over_size_threshold: bool\n def __init__(self, values: np.ndarray) -> None: ...\n def __contains__(self, val: object) -> bool: ...\n\n # -> int | slice | np.ndarray[bool]\n def get_loc(self, val: object) -> int | slice | np.ndarray: ...\n def sizeof(self, deep: bool = ...) -> int: ...\n def __sizeof__(self) -> int: ...\n @property\n def is_unique(self) -> bool: ...\n @property\n def is_monotonic_increasing(self) -> bool: ...\n @property\n def is_monotonic_decreasing(self) -> bool: ...\n @property\n def is_mapping_populated(self) -> bool: ...\n def clear_mapping(self): ...\n def get_indexer(self, values: np.ndarray) -> npt.NDArray[np.intp]: ...\n def get_indexer_non_unique(\n self,\n targets: np.ndarray,\n ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...\n\nclass MaskedIndexEngine(IndexEngine):\n def __init__(self, values: object) -> None: ...\n def get_indexer_non_unique(\n self, targets: object\n ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...\n\nclass Float64Engine(IndexEngine): ...\nclass Float32Engine(IndexEngine): ...\nclass Complex128Engine(IndexEngine): ...\nclass Complex64Engine(IndexEngine): ...\nclass Int64Engine(IndexEngine): ...\nclass Int32Engine(IndexEngine): ...\nclass Int16Engine(IndexEngine): ...\nclass Int8Engine(IndexEngine): ...\nclass UInt64Engine(IndexEngine): ...\nclass UInt32Engine(IndexEngine): ...\nclass UInt16Engine(IndexEngine): ...\nclass UInt8Engine(IndexEngine): ...\nclass ObjectEngine(IndexEngine): ...\nclass DatetimeEngine(Int64Engine): ...\nclass TimedeltaEngine(DatetimeEngine): ...\nclass PeriodEngine(Int64Engine): ...\nclass BoolEngine(UInt8Engine): ...\nclass MaskedFloat64Engine(MaskedIndexEngine): ...\nclass MaskedFloat32Engine(MaskedIndexEngine): ...\nclass MaskedComplex128Engine(MaskedIndexEngine): ...\nclass MaskedComplex64Engine(MaskedIndexEngine): ...\nclass MaskedInt64Engine(MaskedIndexEngine): ...\nclass MaskedInt32Engine(MaskedIndexEngine): ...\nclass MaskedInt16Engine(MaskedIndexEngine): ...\nclass MaskedInt8Engine(MaskedIndexEngine): ...\nclass MaskedUInt64Engine(MaskedIndexEngine): ...\nclass MaskedUInt32Engine(MaskedIndexEngine): ...\nclass MaskedUInt16Engine(MaskedIndexEngine): ...\nclass MaskedUInt8Engine(MaskedIndexEngine): ...\nclass MaskedBoolEngine(MaskedUInt8Engine): ...\n\nclass StringObjectEngine(ObjectEngine):\n def __init__(self, values: object, na_value) -> None: ...\n\nclass BaseMultiIndexCodesEngine:\n levels: list[np.ndarray]\n offsets: np.ndarray # ndarray[uint64_t, ndim=1]\n\n def __init__(\n self,\n levels: list[np.ndarray], # all entries hashable\n labels: list[np.ndarray], # all entries integer-dtyped\n offsets: np.ndarray, # np.ndarray[np.uint64, ndim=1]\n ) -> None: ...\n def get_indexer(self, target: npt.NDArray[np.object_]) -> npt.NDArray[np.intp]: ...\n def _extract_level_codes(self, target: MultiIndex) -> np.ndarray: ...\n\nclass ExtensionEngine:\n def __init__(self, values: ExtensionArray) -> None: ...\n def __contains__(self, val: object) -> bool: ...\n def get_loc(self, val: object) -> int | slice | np.ndarray: ...\n def get_indexer(self, values: np.ndarray) -> npt.NDArray[np.intp]: ...\n def get_indexer_non_unique(\n self,\n targets: np.ndarray,\n ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...\n @property\n def is_unique(self) -> bool: ...\n @property\n def is_monotonic_increasing(self) -> bool: ...\n @property\n def is_monotonic_decreasing(self) -> bool: ...\n def sizeof(self, deep: bool = ...) -> int: ...\n def clear_mapping(self): ...\n
.venv\Lib\site-packages\pandas\_libs\index.pyi
index.pyi
Other
3,798
0.95
0.61165
0.01087
react-lib
409
2025-05-20T04:36:17.768665
BSD-3-Clause
false
da1cd794433a65a3de21f539f3b96cee
!<arch>\n/ -1 0 174 `\n
.venv\Lib\site-packages\pandas\_libs\indexing.cp313-win_amd64.lib
indexing.cp313-win_amd64.lib
Other
2,032
0.8
0
0
node-utils
42
2023-09-25T22:42:04.984445
MIT
false
984714c2e5de52de1004b28912b0e6b7
MZ
.venv\Lib\site-packages\pandas\_libs\indexing.cp313-win_amd64.pyd
indexing.cp313-win_amd64.pyd
Other
50,688
0.95
0.04321
0.003106
node-utils
312
2023-07-16T12:15:50.120353
Apache-2.0
false
c4144082c68509b7074a7a4a86973228
from typing import (\n Generic,\n TypeVar,\n)\n\nfrom pandas.core.indexing import IndexingMixin\n\n_IndexingMixinT = TypeVar("_IndexingMixinT", bound=IndexingMixin)\n\nclass NDFrameIndexerBase(Generic[_IndexingMixinT]):\n name: str\n # in practice obj is either a DataFrame or a Series\n obj: _IndexingMixinT\n\n def __init__(self, name: str, obj: _IndexingMixinT) -> None: ...\n @property\n def ndim(self) -> int: ...\n
.venv\Lib\site-packages\pandas\_libs\indexing.pyi
indexing.pyi
Other
427
0.95
0.176471
0.076923
react-lib
997
2024-04-13T09:25:11.625493
Apache-2.0
false
fc14bfcfe586a4dd81b7acb70b4dcae6
!<arch>\n/ -1 0 178 `\n
.venv\Lib\site-packages\pandas\_libs\internals.cp313-win_amd64.lib
internals.cp313-win_amd64.lib
Other
2,048
0.8
0
0
react-lib
41
2023-09-15T06:41:36.013174
BSD-3-Clause
false
cf83228c66d870b59f6174dee8dcbb26
from typing import (\n Iterator,\n Sequence,\n final,\n overload,\n)\nimport weakref\n\nimport numpy as np\n\nfrom pandas._typing import (\n ArrayLike,\n Self,\n npt,\n)\n\nfrom pandas import Index\nfrom pandas.core.internals.blocks import Block as B\n\ndef slice_len(slc: slice, objlen: int = ...) -> int: ...\ndef get_concat_blkno_indexers(\n blknos_list: list[npt.NDArray[np.intp]],\n) -> list[tuple[npt.NDArray[np.intp], BlockPlacement]]: ...\ndef get_blkno_indexers(\n blknos: np.ndarray, # int64_t[:]\n group: bool = ...,\n) -> list[tuple[int, slice | np.ndarray]]: ...\ndef get_blkno_placements(\n blknos: np.ndarray,\n group: bool = ...,\n) -> Iterator[tuple[int, BlockPlacement]]: ...\ndef update_blklocs_and_blknos(\n blklocs: npt.NDArray[np.intp],\n blknos: npt.NDArray[np.intp],\n loc: int,\n nblocks: int,\n) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ...\n@final\nclass BlockPlacement:\n def __init__(self, val: int | slice | np.ndarray) -> None: ...\n @property\n def indexer(self) -> np.ndarray | slice: ...\n @property\n def as_array(self) -> np.ndarray: ...\n @property\n def as_slice(self) -> slice: ...\n @property\n def is_slice_like(self) -> bool: ...\n @overload\n def __getitem__(\n self, loc: slice | Sequence[int] | npt.NDArray[np.intp]\n ) -> BlockPlacement: ...\n @overload\n def __getitem__(self, loc: int) -> int: ...\n def __iter__(self) -> Iterator[int]: ...\n def __len__(self) -> int: ...\n def delete(self, loc) -> BlockPlacement: ...\n def add(self, other) -> BlockPlacement: ...\n def append(self, others: list[BlockPlacement]) -> BlockPlacement: ...\n def tile_for_unstack(self, factor: int) -> npt.NDArray[np.intp]: ...\n\nclass Block:\n _mgr_locs: BlockPlacement\n ndim: int\n values: ArrayLike\n refs: BlockValuesRefs\n def __init__(\n self,\n values: ArrayLike,\n placement: BlockPlacement,\n ndim: int,\n refs: BlockValuesRefs | None = ...,\n ) -> None: ...\n def slice_block_rows(self, slicer: slice) -> Self: ...\n\nclass BlockManager:\n blocks: tuple[B, ...]\n axes: list[Index]\n _known_consolidated: bool\n _is_consolidated: bool\n _blknos: np.ndarray\n _blklocs: np.ndarray\n def __init__(\n self, blocks: tuple[B, ...], axes: list[Index], verify_integrity=...\n ) -> None: ...\n def get_slice(self, slobj: slice, axis: int = ...) -> Self: ...\n def _rebuild_blknos_and_blklocs(self) -> None: ...\n\nclass BlockValuesRefs:\n referenced_blocks: list[weakref.ref]\n def __init__(self, blk: Block | None = ...) -> None: ...\n def add_reference(self, blk: Block) -> None: ...\n def add_index_reference(self, index: Index) -> None: ...\n def has_reference(self) -> bool: ...\n
.venv\Lib\site-packages\pandas\_libs\internals.pyi
internals.pyi
Other
2,761
0.95
0.329787
0
vue-tools
786
2024-02-18T08:01:56.968601
MIT
false
925b22601e8eed0a6182839420a3b1b2