uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
153cba7cec7f80f88f0f56cf | train | function | def build_dataset(n_samples=50, n_features=200, n_informative_features=10, n_targets=1):
"""
build an ill-posed linear regression problem with many noisy features and
comparatively few samples
"""
random_state = np.random.RandomState(0)
if n_targets > 1:
w = random_state.randn(n_features... | def build_dataset(n_samples=50, n_features=200, n_informative_features=10, n_targets=1):
| """
build an ill-posed linear regression problem with many noisy features and
comparatively few samples
"""
random_state = np.random.RandomState(0)
if n_targets > 1:
w = random_state.randn(n_features, n_targets)
else:
w = random_state.randn(n_features)
w[n_informative_fea... | 0.5 * (np.mean(y ** 2) - np.mean((y - R) ** 2))
assert_allclose(clf.dual_gap_, primal - dual)
def build_dataset(n_samples=50, n_features=200, n_informative_features=10, n_targets=1):
| 64 | 64 | 164 | 26 | 38 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | build_dataset | build_dataset | 312 | 327 | 312 | 312 | c72245b11f1bc84da0a913d400ea6d6f6a4c2df6 | bigcode/the-stack | train |
9a78abd79e4b97da99159027 | train | function | @filterwarnings_normalize
def test_enet_float_precision():
# Generate dataset
X, y, X_test, y_test = build_dataset(n_samples=20, n_features=10)
# Here we have a small number of iterations, and thus the
# ElasticNet might not converge. This is to speed up tests
for normalize in [True, False]:
... | @filterwarnings_normalize
def test_enet_float_precision():
# Generate dataset
| X, y, X_test, y_test = build_dataset(n_samples=20, n_features=10)
# Here we have a small number of iterations, and thus the
# ElasticNet might not converge. This is to speed up tests
for normalize in [True, False]:
for fit_intercept in [True, False]:
coef = {}
intercept ... | ElasticNet, Lasso])
def test_lasso_non_float_y(model):
X = [[0, 0], [1, 1], [-1, -1]]
y = [0, 1, 2]
y_float = [0.0, 1.0, 2.0]
clf = model(fit_intercept=False)
clf.fit(X, y)
clf_float = model(fit_intercept=False)
clf_float.fit(X, y_float)
assert_array_equal(clf.coef_, clf_float.coef_)
... | 152 | 152 | 507 | 18 | 133 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_float_precision | test_enet_float_precision | 1,241 | 1,302 | 1,241 | 1,243 | 4223c884abc7337c6858eeec3f5173233b7a3ea9 | bigcode/the-stack | train |
c2f54fff57025b4652a755f9 | train | function | @pytest.mark.parametrize("fit_intercept", [True, False])
def test_enet_cv_sample_weight_correctness(fit_intercept):
"""Test that ElasticNetCV with sample weights gives correct results."""
rng = np.random.RandomState(42)
n_splits, n_samples, n_features = 3, 10, 5
X = rng.rand(n_splits * n_samples, n_feat... | @pytest.mark.parametrize("fit_intercept", [True, False])
def test_enet_cv_sample_weight_correctness(fit_intercept):
| """Test that ElasticNetCV with sample weights gives correct results."""
rng = np.random.RandomState(42)
n_splits, n_samples, n_features = 3, 10, 5
X = rng.rand(n_splits * n_samples, n_features)
beta = rng.rand(n_features)
beta[0:2] = 0
y = X @ beta + rng.rand(n_splits * n_samples)
sw = n... | )
assert_allclose(reg1.coef_, reg2.coef_)
@pytest.mark.parametrize("estimator", (Lasso, ElasticNet))
def test_enet_sample_weight_sparse(estimator):
reg = estimator()
X = sparse.csc_matrix(np.zeros((3, 2)))
y = np.array([-1, 0, 1])
sw = np.array([1, 2, 3])
with pytest.raises(
ValueError... | 153 | 153 | 512 | 27 | 126 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_cv_sample_weight_correctness | test_enet_cv_sample_weight_correctness | 1,541 | 1,585 | 1,541 | 1,542 | 99f87c41ac0a756b4c8920203b4909712b1ac31f | bigcode/the-stack | train |
6772785f2da53ba4df42e500 | train | function | def test_sparse_input_dtype_enet_and_lassocv():
X, y, _, _ = build_dataset(n_features=10)
clf = ElasticNetCV(n_alphas=5)
clf.fit(sparse.csr_matrix(X), y)
clf1 = ElasticNetCV(n_alphas=5)
clf1.fit(sparse.csr_matrix(X, dtype=np.float32), y)
assert_almost_equal(clf.alpha_, clf1.alpha_, decimal=6)
... | def test_sparse_input_dtype_enet_and_lassocv():
| X, y, _, _ = build_dataset(n_features=10)
clf = ElasticNetCV(n_alphas=5)
clf.fit(sparse.csr_matrix(X), y)
clf1 = ElasticNetCV(n_alphas=5)
clf1.fit(sparse.csr_matrix(X, dtype=np.float32), y)
assert_almost_equal(clf.alpha_, clf1.alpha_, decimal=6)
assert_almost_equal(clf.coef_, clf1.coef_, dec... | .fit(X, y)
assert_almost_equal(clf.alpha_, clf1.alpha_)
assert_almost_equal(clf.coef_, clf1.coef_[0])
assert_almost_equal(clf.intercept_, clf1.intercept_[0])
def test_sparse_input_dtype_enet_and_lassocv():
| 64 | 64 | 209 | 12 | 52 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_sparse_input_dtype_enet_and_lassocv | test_sparse_input_dtype_enet_and_lassocv | 970 | 984 | 970 | 970 | 47afa1b1d1f25e0d85b5bde378296bc49d21ce5e | bigcode/the-stack | train |
635cb4a8c0002387551c13e1 | train | function | def test_multioutput_enetcv_error():
rng = np.random.RandomState(0)
X = rng.randn(10, 2)
y = rng.randn(10, 2)
clf = ElasticNetCV()
with pytest.raises(ValueError):
clf.fit(X, y)
| def test_multioutput_enetcv_error():
| rng = np.random.RandomState(0)
X = rng.randn(10, 2)
y = rng.randn(10, 2)
clf = ElasticNetCV()
with pytest.raises(ValueError):
clf.fit(X, y)
| estimator.fit(X, y[:, k])
assert_array_almost_equal(coef[k, :], estimator.coef_)
assert_array_almost_equal(intercept[k], estimator.intercept_)
assert_array_almost_equal(dual_gap[k], estimator.dual_gap_)
def test_multioutput_enetcv_error():
| 63 | 64 | 62 | 9 | 54 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_multioutput_enetcv_error | test_multioutput_enetcv_error | 909 | 915 | 909 | 909 | 0739508e00733e09d971b63422107c5c3d2637e9 | bigcode/the-stack | train |
5361d280f89b299bcce03beb | train | function | @pytest.mark.parametrize(
"CoordinateDescentModel",
[
ElasticNet,
Lasso,
LassoCV,
ElasticNetCV,
MultiTaskElasticNet,
MultiTaskLasso,
MultiTaskElasticNetCV,
MultiTaskLassoCV,
],
)
@pytest.mark.parametrize(
"normalize, n_warnings", [(True, 1)... | @pytest.mark.parametrize(
"CoordinateDescentModel",
[
ElasticNet,
Lasso,
LassoCV,
ElasticNetCV,
MultiTaskElasticNet,
MultiTaskLasso,
MultiTaskElasticNetCV,
MultiTaskLassoCV,
],
)
@pytest.mark.parametrize(
"normalize, n_warnings", [(True, 1)... | rng = check_random_state(0)
n_samples = 200
n_features = 2
X = rng.randn(n_samples, n_features)
X[X < 0.1] = 0.0
y = rng.rand(n_samples)
if "MultiTask" in CoordinateDescentModel.__name__:
y = np.stack((y, y), axis=1)
model = CoordinateDescentModel(normalize=normalize)
with ... | @pytest.mark.parametrize(
"CoordinateDescentModel",
[
ElasticNet,
Lasso,
LassoCV,
ElasticNetCV,
MultiTaskElasticNet,
MultiTaskLasso,
MultiTaskElasticNetCV,
MultiTaskLassoCV,
],
)
@pytest.mark.parametrize(
"normalize, n_warnings", [(True, 1)... | 125 | 79 | 266 | 125 | 0 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_assure_warning_when_normalize | test_assure_warning_when_normalize | 73 | 106 | 73 | 90 | 3d5c93670118ff4ae67e93de0ee5a35165637ecb | bigcode/the-stack | train |
242f592c76df439a835d3451 | train | function | def test_sparse_input_convergence_warning():
X, y, _, _ = build_dataset(n_samples=1000, n_features=500)
with pytest.warns(ConvergenceWarning):
ElasticNet(max_iter=1, tol=0).fit(sparse.csr_matrix(X, dtype=np.float32), y)
# check that the model converges w/o warnings
with pytest.warns(None) as r... | def test_sparse_input_convergence_warning():
| X, y, _, _ = build_dataset(n_samples=1000, n_features=500)
with pytest.warns(ConvergenceWarning):
ElasticNet(max_iter=1, tol=0).fit(sparse.csr_matrix(X, dtype=np.float32), y)
# check that the model converges w/o warnings
with pytest.warns(None) as record:
Lasso().fit(sparse.csr_matrix(... | =1, tol=-1).fit(X, y)
# check that the model converges w/o warnings
with pytest.warns(None) as record:
MultiTaskElasticNet().fit(X, y)
assert not [w.message for w in record]
def test_sparse_input_convergence_warning():
| 64 | 64 | 118 | 8 | 56 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_sparse_input_convergence_warning | test_sparse_input_convergence_warning | 1,410 | 1,420 | 1,410 | 1,410 | 2ad2d46acfb7deafe2c22f4b6b2b03125c3f86ac | bigcode/the-stack | train |
248cd3618dd7454f8b4e74c7 | train | function | @pytest.mark.parametrize(
"estimator",
[
Lasso(alpha=1.0),
ElasticNet(alpha=1.0, l1_ratio=0.1),
],
)
@filterwarnings_normalize
def test_sample_weight_invariance(estimator):
rng = np.random.RandomState(42)
X, y = make_regression(
n_samples=100,
n_features=300,
... | @pytest.mark.parametrize(
"estimator",
[
Lasso(alpha=1.0),
ElasticNet(alpha=1.0, l1_ratio=0.1),
],
)
@filterwarnings_normalize
def test_sample_weight_invariance(estimator):
| rng = np.random.RandomState(42)
X, y = make_regression(
n_samples=100,
n_features=300,
effective_rank=10,
n_informative=50,
random_state=rng,
)
normalize = False # These tests don't work for normalize=True.
sw = rng.uniform(low=0.01, high=2, size=X.shape[0])
... | _weight=sw)
if normalize:
alpha_enet = alpha / n_samples
else:
alpha_enet = alpha / sw.sum()
enet = ElasticNet(alpha=alpha_enet, l1_ratio=0, **common_params).fit(
X, y, sample_weight=sw
)
assert_allclose(ridge.coef_, enet.coef_)
assert_allclose(ridge.intercept_, enet.inte... | 150 | 151 | 504 | 55 | 95 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_sample_weight_invariance | test_sample_weight_invariance | 1,761 | 1,813 | 1,761 | 1,769 | b31200446d5676c077f5dc8e4111a33798c7e961 | bigcode/the-stack | train |
37cf6e8e4f71b85b3c8877ae | train | function | def test_lasso_readonly_data():
X = np.array([[-1], [0], [1]])
Y = np.array([-1, 0, 1]) # just a straight line
T = np.array([[2], [3], [4]]) # test sample
with TempMemmap((X, Y)) as (X, Y):
clf = Lasso(alpha=0.5)
clf.fit(X, Y)
pred = clf.predict(T)
assert_array_almost_e... | def test_lasso_readonly_data():
| X = np.array([[-1], [0], [1]])
Y = np.array([-1, 0, 1]) # just a straight line
T = np.array([[2], [3], [4]]) # test sample
with TempMemmap((X, Y)) as (X, Y):
clf = Lasso(alpha=0.5)
clf.fit(X, Y)
pred = clf.predict(T)
assert_array_almost_equal(clf.coef_, [0.25])
... | 8, max_iter=1)
warning_message = (
"Objective did not converge. You might want to "
"increase the number of iterations."
)
with pytest.warns(ConvergenceWarning, match=warning_message):
clf.fit(X, Y)
def test_lasso_readonly_data():
| 64 | 64 | 157 | 8 | 56 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_lasso_readonly_data | test_lasso_readonly_data | 866 | 876 | 866 | 866 | 58d82d2ded934a35bbbd5d4b3455fc774969d308 | bigcode/the-stack | train |
11863f933c58150ecb7e6645 | train | function | def test_multitask_enet_and_lasso_cv():
X, y, _, _ = build_dataset(n_features=50, n_targets=3)
clf = MultiTaskElasticNetCV(cv=3).fit(X, y)
assert_almost_equal(clf.alpha_, 0.00556, 3)
clf = MultiTaskLassoCV(cv=3).fit(X, y)
assert_almost_equal(clf.alpha_, 0.00278, 3)
X, y, _, _ = build_dataset(n_... | def test_multitask_enet_and_lasso_cv():
| X, y, _, _ = build_dataset(n_features=50, n_targets=3)
clf = MultiTaskElasticNetCV(cv=3).fit(X, y)
assert_almost_equal(clf.alpha_, 0.00556, 3)
clf = MultiTaskLassoCV(cv=3).fit(X, y)
assert_almost_equal(clf.alpha_, 0.00278, 3)
X, y, _, _ = build_dataset(n_targets=3)
clf = MultiTaskElasticNet... | ], estimator.coef_)
assert_array_almost_equal(intercept[k], estimator.intercept_)
assert_array_almost_equal(dual_gap[k], estimator.dual_gap_)
def test_multioutput_enetcv_error():
rng = np.random.RandomState(0)
X = rng.randn(10, 2)
y = rng.randn(10, 2)
clf = ElasticNetCV()
with pyte... | 110 | 110 | 368 | 12 | 98 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_multitask_enet_and_lasso_cv | test_multitask_enet_and_lasso_cv | 918 | 942 | 918 | 918 | 01e7ffb16cba4988d8ae5968232793538b7dae38 | bigcode/the-stack | train |
76d50aa8e799b37044ec562a | train | function | @pytest.mark.parametrize("fit_intercept", [True, False])
@pytest.mark.parametrize("l1_ratio", [0, 0.5, 1])
@pytest.mark.parametrize("precompute", [False, True])
def test_enet_cv_sample_weight_consistency(fit_intercept, l1_ratio, precompute):
"""Test that the impact of sample_weight is consistent."""
rng = np.ra... | @pytest.mark.parametrize("fit_intercept", [True, False])
@pytest.mark.parametrize("l1_ratio", [0, 0.5, 1])
@pytest.mark.parametrize("precompute", [False, True])
def test_enet_cv_sample_weight_consistency(fit_intercept, l1_ratio, precompute):
| """Test that the impact of sample_weight is consistent."""
rng = np.random.RandomState(0)
n_samples, n_features = 10, 5
X = rng.rand(n_samples, n_features)
y = X.sum(axis=1) + rng.rand(n_samples)
params = dict(
l1_ratio=l1_ratio,
fit_intercept=fit_intercept,
precompute=p... | =ElasticNet(),
param_grid=param,
cv=cv,
scoring="neg_mean_squared_error",
).fit(X, y, sample_weight=sample_weight)
assert reg.l1_ratio_ == pytest.approx(gs.best_params_["l1_ratio"])
assert reg.alpha_ == pytest.approx(gs.best_params_["alpha"])
@pytest.mark.parametrize("fit_intercept"... | 136 | 137 | 459 | 65 | 71 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_cv_sample_weight_consistency | test_enet_cv_sample_weight_consistency | 1,623 | 1,669 | 1,623 | 1,626 | b20cd939b362df4bd3005bb7b13a78dce9b494b9 | bigcode/the-stack | train |
a80d1d732c37afb4ea8d28dd | train | function | def test_lasso_zero():
# Check that the lasso can handle zero data without crashing
X = [[0], [0], [0]]
y = [0, 0, 0]
clf = Lasso(alpha=0.1).fit(X, y)
pred = clf.predict([[1], [2], [3]])
assert_array_almost_equal(clf.coef_, [0])
assert_array_almost_equal(pred, [0, 0, 0])
assert_almost_eq... | def test_lasso_zero():
# Check that the lasso can handle zero data without crashing
| X = [[0], [0], [0]]
y = [0, 0, 0]
clf = Lasso(alpha=0.1).fit(X, y)
pred = clf.predict([[1], [2], [3]])
assert_array_almost_equal(clf.coef_, [0])
assert_array_almost_equal(pred, [0, 0, 0])
assert_almost_equal(clf.dual_gap_, 0)
| )
assert sparse.isspmatrix_csr(y2)
elif order == "F":
assert sparse.isspmatrix_csc(X2)
assert sparse.isspmatrix_csc(y2)
def test_lasso_zero():
# Check that the lasso can handle zero data without crashing
| 64 | 64 | 119 | 20 | 44 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_lasso_zero | test_lasso_zero | 183 | 191 | 183 | 184 | 4ccf9f91d2009208e7e45c15931b3f399c5a87a7 | bigcode/the-stack | train |
c201a27c4865ef4bdb06f25d | train | function | def test_multi_task_lasso_cv_dtype():
n_samples, n_features = 10, 3
rng = np.random.RandomState(42)
X = rng.binomial(1, 0.5, size=(n_samples, n_features))
X = X.astype(int) # make it explicit that X is int
y = X[:, [0, 0]].copy()
est = MultiTaskLassoCV(n_alphas=5, fit_intercept=True).fit(X, y)
... | def test_multi_task_lasso_cv_dtype():
| n_samples, n_features = 10, 3
rng = np.random.RandomState(42)
X = rng.binomial(1, 0.5, size=(n_samples, n_features))
X = X.astype(int) # make it explicit that X is int
y = X[:, [0, 0]].copy()
est = MultiTaskLassoCV(n_alphas=5, fit_intercept=True).fit(X, y)
assert_array_almost_equal(est.coef... | self.precompute == inner_precompute
monkeypatch.setattr("sklearn.linear_model._coordinate_descent.Lasso", LassoMock)
clf = LassoCV(precompute=precompute)
clf.fit(X, y)
assert calls > 0
def test_multi_task_lasso_cv_dtype():
| 64 | 64 | 135 | 9 | 54 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_multi_task_lasso_cv_dtype | test_multi_task_lasso_cv_dtype | 1,448 | 1,455 | 1,448 | 1,448 | 6f8a3a0f6da8af963516768fb26a38479a5d6b43 | bigcode/the-stack | train |
4a185bb808fdfa0f1750382c | train | function | @pytest.mark.parametrize("model", [ElasticNet, Lasso])
def test_lasso_non_float_y(model):
X = [[0, 0], [1, 1], [-1, -1]]
y = [0, 1, 2]
y_float = [0.0, 1.0, 2.0]
clf = model(fit_intercept=False)
clf.fit(X, y)
clf_float = model(fit_intercept=False)
clf_float.fit(X, y_float)
assert_array_e... | @pytest.mark.parametrize("model", [ElasticNet, Lasso])
def test_lasso_non_float_y(model):
| X = [[0, 0], [1, 1], [-1, -1]]
y = [0, 1, 2]
y_float = [0.0, 1.0, 2.0]
clf = model(fit_intercept=False)
clf.fit(X, y)
clf_float = model(fit_intercept=False)
clf_float.fit(X, y_float)
assert_array_equal(clf.coef_, clf_float.coef_)
| " to fit intercept, "
"or X was normalized : recomputing Gram matrix."
)
with pytest.warns(UserWarning, match=warning_message):
clf.fit(X, y)
@pytest.mark.parametrize("model", [ElasticNet, Lasso])
def test_lasso_non_float_y(model):
| 64 | 64 | 125 | 22 | 42 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_lasso_non_float_y | test_lasso_non_float_y | 1,227 | 1,237 | 1,227 | 1,228 | fbdf37bcec016edddedffbac9247ed4858c49ea4 | bigcode/the-stack | train |
1ead41b896b3cb9dff1d510e | train | function | def test_enet_positive_constraint():
X = [[-1], [0], [1]]
y = [1, 0, -1] # just a straight line with negative slope
enet = ElasticNet(alpha=0.1, positive=True)
enet.fit(X, y)
assert min(enet.coef_) >= 0
| def test_enet_positive_constraint():
| X = [[-1], [0], [1]]
y = [1, 0, -1] # just a straight line with negative slope
enet = ElasticNet(alpha=0.1, positive=True)
enet.fit(X, y)
assert min(enet.coef_) >= 0
| asso.fit(X, y)
assert min(lasso.coef_) >= 0
lasso = Lasso(alpha=0.1, precompute=True, positive=True)
lasso.fit(X, y)
assert min(lasso.coef_) >= 0
def test_enet_positive_constraint():
| 64 | 64 | 77 | 7 | 56 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_positive_constraint | test_enet_positive_constraint | 786 | 792 | 786 | 786 | 6d611a940c1bee983f19ffcb8fd2544e5b9bb1f0 | bigcode/the-stack | train |
095704289b299cf5eeb87069 | train | function | def test_lasso_cv_with_some_model_selection():
from sklearn.model_selection import ShuffleSplit
from sklearn import datasets
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target
pipe = make_pipeline(StandardScaler(), LassoCV(cv=ShuffleSplit(random_state=0)))
pipe.fit(X... | def test_lasso_cv_with_some_model_selection():
| from sklearn.model_selection import ShuffleSplit
from sklearn import datasets
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target
pipe = make_pipeline(StandardScaler(), LassoCV(cv=ShuffleSplit(random_state=0)))
pipe.fit(X, y)
| .assert_approx_equal(
mse_lars(clf.alphas_[5]).mean(), clf.mse_path_[5].mean(), significant=2
)
# test set
assert clf.score(X_test, y_test) > 0.99
def test_lasso_cv_with_some_model_selection():
| 64 | 64 | 72 | 10 | 53 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_lasso_cv_with_some_model_selection | test_lasso_cv_with_some_model_selection | 362 | 371 | 362 | 362 | c0cc0b7a4604828101867aea1056ead8505e13b7 | bigcode/the-stack | train |
95327fc3dea15967334ee824 | train | function | @pytest.mark.parametrize("estimator", [ElasticNetCV, LassoCV])
def test_linear_models_cv_fit_with_loky(estimator):
# LinearModelsCV.fit performs inplace operations on fancy-indexed memmapped
# data when using the loky backend, causing an error due to unexpected
# behavior of fancy indexing of read-only memm... | @pytest.mark.parametrize("estimator", [ElasticNetCV, LassoCV])
def test_linear_models_cv_fit_with_loky(estimator):
# LinearModelsCV.fit performs inplace operations on fancy-indexed memmapped
# data when using the loky backend, causing an error due to unexpected
# behavior of fancy indexing of read-only memm... | if parse_version(joblib.__version__) < parse_version("0.12"):
pytest.skip("loky backend does not exist in joblib <0.12")
# Create a problem sufficiently large to cause memmapping (1MB).
# Unfortunately the scikit-learn and joblib APIs do not make it possible to
# change the max_nbyte of the inn... | @pytest.mark.parametrize("estimator", [ElasticNetCV, LassoCV])
def test_linear_models_cv_fit_with_loky(estimator):
# LinearModelsCV.fit performs inplace operations on fancy-indexed memmapped
# data when using the loky backend, causing an error due to unexpected
# behavior of fancy indexing of read-only memm... | 81 | 68 | 229 | 81 | 0 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_linear_models_cv_fit_with_loky | test_linear_models_cv_fit_with_loky | 1,684 | 1,699 | 1,684 | 1,689 | 7547849846d66db11d8ad16d750953d15dd2bd6f | bigcode/the-stack | train |
344b0d1f74bd5b76590ba8ee | train | function | @pytest.mark.parametrize("estimator", (LassoCV, ElasticNetCV))
def test_enet_cv_sample_weight_sparse(estimator):
reg = estimator()
X = sparse.csc_matrix(np.zeros((3, 2)))
y = np.array([-1, 0, 1])
sw = np.array([1, 2, 3])
with pytest.raises(
ValueError, match="Sample weights do not.*support s... | @pytest.mark.parametrize("estimator", (LassoCV, ElasticNetCV))
def test_enet_cv_sample_weight_sparse(estimator):
| reg = estimator()
X = sparse.csc_matrix(np.zeros((3, 2)))
y = np.array([-1, 0, 1])
sw = np.array([1, 2, 3])
with pytest.raises(
ValueError, match="Sample weights do not.*support sparse matrices"
):
reg.fit(X, y, sample_weight=sw)
| sample_weight)
assert_allclose(reg.coef_, coef, rtol=1e-6)
if fit_intercept:
assert_allclose(reg.intercept_, intercept)
@pytest.mark.parametrize("estimator", (LassoCV, ElasticNetCV))
def test_enet_cv_sample_weight_sparse(estimator):
| 64 | 64 | 109 | 27 | 37 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_cv_sample_weight_sparse | test_enet_cv_sample_weight_sparse | 1,672 | 1,681 | 1,672 | 1,673 | 0231ee7f69e1c6f29505cb73d8dbd21990ab3ca5 | bigcode/the-stack | train |
f1ea88c0543112c43d955b66 | train | function | @pytest.mark.parametrize("check_input", [True, False])
def test_enet_copy_X_True(check_input):
X, y, _, _ = build_dataset()
X = X.copy(order="F")
original_X = X.copy()
enet = ElasticNet(copy_X=True)
enet.fit(X, y, check_input=check_input)
assert_array_equal(original_X, X)
| @pytest.mark.parametrize("check_input", [True, False])
def test_enet_copy_X_True(check_input):
| X, y, _, _ = build_dataset()
X = X.copy(order="F")
original_X = X.copy()
enet = ElasticNet(copy_X=True)
enet.fit(X, y, check_input=check_input)
assert_array_equal(original_X, X)
| in false
# computation
X = check_array(X, order="C", dtype="float64")
with pytest.raises(ValueError):
clf.fit(X, y, check_input=False)
@pytest.mark.parametrize("check_input", [True, False])
def test_enet_copy_X_True(check_input):
| 64 | 64 | 83 | 23 | 41 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_copy_X_True | test_enet_copy_X_True | 1,190 | 1,199 | 1,190 | 1,191 | 1463a61957e4805dfe4864af22994b37bc72f1eb | bigcode/the-stack | train |
d43507ea6a5a44f46691d34b | train | function | def _scale_alpha_inplace(estimator, n_samples):
"""Rescale the parameter alpha from when the estimator is evoked with
normalize set to True as if it were evoked in a Pipeline with normalize set
to False and with a StandardScaler.
"""
if ("alpha" not in estimator.get_params()) and (
"alphas" ... | def _scale_alpha_inplace(estimator, n_samples):
| """Rescale the parameter alpha from when the estimator is evoked with
normalize set to True as if it were evoked in a Pipeline with normalize set
to False and with a StandardScaler.
"""
if ("alpha" not in estimator.get_params()) and (
"alphas" not in estimator.get_params()
):
ret... | # On same data, constrained fit has non-negative coefficients
clf_constrained = LassoCV(
n_alphas=3, eps=1e-1, max_iter=max_iter, positive=True, cv=2, n_jobs=1
)
clf_constrained.fit(X, y)
assert min(clf_constrained.coef_) >= 0
def _scale_alpha_inplace(estimator, n_samples):
| 89 | 89 | 299 | 12 | 76 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | _scale_alpha_inplace | _scale_alpha_inplace | 391 | 420 | 391 | 391 | 405f743cd7dd27358c39317620ebc8b32e11227e | bigcode/the-stack | train |
3b6da2d767144b91f6089402 | train | function | def test_enet_path_positive():
# Test positive parameter
X, Y, _, _ = build_dataset(n_samples=50, n_features=50, n_targets=2)
# For mono output
# Test that the coefs returned by positive=True in enet_path are positive
for path in [enet_path, lasso_path]:
pos_path_coef = path(X, Y[:, 0], po... | def test_enet_path_positive():
# Test positive parameter
| X, Y, _, _ = build_dataset(n_samples=50, n_features=50, n_targets=2)
# For mono output
# Test that the coefs returned by positive=True in enet_path are positive
for path in [enet_path, lasso_path]:
pos_path_coef = path(X, Y[:, 0], positive=True)[1]
assert np.all(pos_path_coef >= 0)
... | (clf_cyclic.intercept_, clf_random.intercept_)
# Raise error when selection is not in cyclic or random.
clf_random = ElasticNet(selection="invalid")
with pytest.raises(ValueError):
clf_random.fit(X, y)
def test_enet_path_positive():
# Test positive parameter
| 64 | 64 | 152 | 13 | 51 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_path_positive | test_enet_path_positive | 1,133 | 1,148 | 1,133 | 1,135 | 29eebd0b9c1692b9dc541c5061ed705b24313217 | bigcode/the-stack | train |
1c76986d19f60eee8a455702 | train | function | def test_convergence_warnings():
random_state = np.random.RandomState(0)
X = random_state.standard_normal((1000, 500))
y = random_state.standard_normal((1000, 3))
# check that the model fails to converge (a negative dual gap cannot occur)
with pytest.warns(ConvergenceWarning):
MultiTaskElas... | def test_convergence_warnings():
| random_state = np.random.RandomState(0)
X = random_state.standard_normal((1000, 500))
y = random_state.standard_normal((1000, 3))
# check that the model fails to converge (a negative dual gap cannot occur)
with pytest.warns(ConvergenceWarning):
MultiTaskElasticNet(max_iter=1, tol=-1).fit(X,... | :
y = y.ravel()
warning_message = (
"Objective did not converge. You might want to"
" increase the number of iterations."
)
with pytest.warns(ConvergenceWarning, match=warning_message):
clf.fit(X, y)
def test_convergence_warnings():
| 64 | 64 | 136 | 7 | 57 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_convergence_warnings | test_convergence_warnings | 1,394 | 1,407 | 1,394 | 1,394 | a22bd405b39ea7bef31bd7c4aac0d7a633798092 | bigcode/the-stack | train |
2340741ef1bf4aea21b432f8 | train | function | def test_elasticnet_precompute_incorrect_gram():
# check that passing an invalid precomputed Gram matrix will raise an
# error.
X, y, _, _ = build_dataset()
rng = np.random.RandomState(0)
X_centered = X - np.average(X, axis=0)
garbage = rng.standard_normal(X.shape)
precompute = np.dot(garb... | def test_elasticnet_precompute_incorrect_gram():
# check that passing an invalid precomputed Gram matrix will raise an
# error.
| X, y, _, _ = build_dataset()
rng = np.random.RandomState(0)
X_centered = X - np.average(X, axis=0)
garbage = rng.standard_normal(X.shape)
precompute = np.dot(garbage.T, garbage)
clf = ElasticNet(alpha=0.01, precompute=precompute)
msg = "Gram matrix.*did not pass validation.*"
with pyt... | .*array-like.*Got 'auto'"
with pytest.raises(ValueError, match=err_msg):
Lasso(precompute="auto").fit(X, y)
def test_elasticnet_precompute_incorrect_gram():
# check that passing an invalid precomputed Gram matrix will raise an
# error.
| 64 | 64 | 139 | 31 | 33 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_elasticnet_precompute_incorrect_gram | test_elasticnet_precompute_incorrect_gram | 1,004 | 1,018 | 1,004 | 1,006 | 13d2f2b30b62145190f53f2470427148aae6e7fc | bigcode/the-stack | train |
ecc4b4781782c7453f8d44f2 | train | function | def test_uniform_targets():
enet = ElasticNetCV(n_alphas=3)
m_enet = MultiTaskElasticNetCV(n_alphas=3)
lasso = LassoCV(n_alphas=3)
m_lasso = MultiTaskLassoCV(n_alphas=3)
models_single_task = (enet, lasso)
models_multi_task = (m_enet, m_lasso)
rng = np.random.RandomState(0)
X_train = r... | def test_uniform_targets():
| enet = ElasticNetCV(n_alphas=3)
m_enet = MultiTaskElasticNetCV(n_alphas=3)
lasso = LassoCV(n_alphas=3)
m_lasso = MultiTaskLassoCV(n_alphas=3)
models_single_task = (enet, lasso)
models_multi_task = (m_enet, m_lasso)
rng = np.random.RandomState(0)
X_train = rng.random_sample(size=(10, 3... | # On same data, constrained fit has non-negative coefficients
enetcv_constrained = ElasticNetCV(
n_alphas=3, eps=1e-1, max_iter=max_iter, cv=2, positive=True, n_jobs=1
)
enetcv_constrained.fit(X, y)
assert min(enetcv_constrained.coef_) >= 0
def test_uniform_targets():
| 88 | 88 | 295 | 5 | 82 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_uniform_targets | test_uniform_targets | 814 | 842 | 814 | 814 | f0826d867e3dc3f324d38681243faf3a9c8896e5 | bigcode/the-stack | train |
06dba222221ee0fdc872b5ac | train | function | def test_elasticnet_precompute_gram_weighted_samples():
# check the equivalence between passing a precomputed Gram matrix and
# internal computation using sample weights.
X, y, _, _ = build_dataset()
rng = np.random.RandomState(0)
sample_weight = rng.lognormal(size=y.shape)
w_norm = sample_wei... | def test_elasticnet_precompute_gram_weighted_samples():
# check the equivalence between passing a precomputed Gram matrix and
# internal computation using sample weights.
| X, y, _, _ = build_dataset()
rng = np.random.RandomState(0)
sample_weight = rng.lognormal(size=y.shape)
w_norm = sample_weight * (y.shape / np.sum(sample_weight))
X_c = X - np.average(X, axis=0, weights=w_norm)
X_r = X_c * np.sqrt(w_norm)[:, np.newaxis]
gram = np.dot(X_r.T, X_r)
clf1 ... | matrix.*did not pass validation.*"
with pytest.raises(ValueError, match=msg):
clf.fit(X_centered, y)
def test_elasticnet_precompute_gram_weighted_samples():
# check the equivalence between passing a precomputed Gram matrix and
# internal computation using sample weights.
| 64 | 64 | 208 | 36 | 28 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_elasticnet_precompute_gram_weighted_samples | test_elasticnet_precompute_gram_weighted_samples | 1,021 | 1,040 | 1,021 | 1,023 | 1f67cedb2a0ace91531507a0541f412c321a534f | bigcode/the-stack | train |
4b2d31a72d126acf121b5541 | train | function | @pytest.mark.parametrize("order", ["C", "F"])
@pytest.mark.parametrize("input_order", ["C", "F"])
def test_set_order_dense(order, input_order):
"""Check that _set_order returns arrays with promised order."""
X = np.array([[0], [0], [0]], order=input_order)
y = np.array([0, 0, 0], order=input_order)
X2, ... | @pytest.mark.parametrize("order", ["C", "F"])
@pytest.mark.parametrize("input_order", ["C", "F"])
def test_set_order_dense(order, input_order):
| """Check that _set_order returns arrays with promised order."""
X = np.array([[0], [0], [0]], order=input_order)
y = np.array([0, 0, 0], order=input_order)
X2, y2 = _set_order(X, y, order=order)
if order == "C":
assert X2.flags["C_CONTIGUOUS"]
assert y2.flags["C_CONTIGUOUS"]
elif... | enet = ElasticNet(**params)
with pytest.raises(err_type, match=err_msg):
enet.fit(X, y)
@pytest.mark.parametrize("order", ["C", "F"])
@pytest.mark.parametrize("input_order", ["C", "F"])
def test_set_order_dense(order, input_order):
| 64 | 64 | 185 | 35 | 29 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_set_order_dense | test_set_order_dense | 146 | 162 | 146 | 148 | 29366c409283ac1912b42a115a79df7c09c9e73e | bigcode/the-stack | train |
24e4ecc4ebd58c939fe055ea | train | function | def test_sparse_dense_descent_paths():
# Test that dense and sparse input give the same input for descent paths.
X, y, _, _ = build_dataset(n_samples=50, n_features=20)
csr = sparse.csr_matrix(X)
for path in [enet_path, lasso_path]:
_, coefs, _ = path(X, y)
_, sparse_coefs, _ = path(csr,... | def test_sparse_dense_descent_paths():
# Test that dense and sparse input give the same input for descent paths.
| X, y, _, _ = build_dataset(n_samples=50, n_features=20)
csr = sparse.csr_matrix(X)
for path in [enet_path, lasso_path]:
_, coefs, _ = path(X, y)
_, sparse_coefs, _ = path(csr, y)
assert_array_almost_equal(coefs, sparse_coefs)
| not allowed
# Test that an error is raised
for path in [enet_path, lasso_path]:
with pytest.raises(ValueError):
path(X, Y, positive=True)
def test_sparse_dense_descent_paths():
# Test that dense and sparse input give the same input for descent paths.
| 64 | 64 | 104 | 24 | 40 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_sparse_dense_descent_paths | test_sparse_dense_descent_paths | 1,151 | 1,158 | 1,151 | 1,152 | bac8c0600bd2d884491cfa071f5181dfd816e80d | bigcode/the-stack | train |
c4bf23cda20015ea64cf84b8 | train | function | def test_check_input_false():
X, y, _, _ = build_dataset(n_samples=20, n_features=10)
X = check_array(X, order="F", dtype="float64")
y = check_array(X, order="F", dtype="float64")
clf = ElasticNet(selection="cyclic", tol=1e-8)
# Check that no error is raised if data is provided in the right format
... | def test_check_input_false():
| X, y, _, _ = build_dataset(n_samples=20, n_features=10)
X = check_array(X, order="F", dtype="float64")
y = check_array(X, order="F", dtype="float64")
clf = ElasticNet(selection="cyclic", tol=1e-8)
# Check that no error is raised if data is provided in the right format
clf.fit(X, y, check_input=F... | will raise an error."""
X, y, _, _ = build_dataset(n_samples=50, n_features=20)
err_msg = "Unexpected parameters in params"
with pytest.raises(ValueError, match=err_msg):
path_func(X, y, normalize=True, fit_intercept=True)
def test_check_input_false():
| 68 | 68 | 229 | 6 | 62 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_check_input_false | test_check_input_false | 1,171 | 1,187 | 1,171 | 1,171 | f19c1f221e3abef510423287e478fc96fb5e51c2 | bigcode/the-stack | train |
7172b9710b023f777fa000a4 | train | function | @pytest.mark.parametrize(
"klass, n_classes, kwargs",
[
(Lasso, 1, dict(precompute=True)),
(Lasso, 1, dict(precompute=False)),
(MultiTaskLasso, 2, dict()),
(MultiTaskLasso, 2, dict()),
],
)
def test_enet_coordinate_descent(klass, n_classes, kwargs):
"""Test that a warning... | @pytest.mark.parametrize(
"klass, n_classes, kwargs",
[
(Lasso, 1, dict(precompute=True)),
(Lasso, 1, dict(precompute=False)),
(MultiTaskLasso, 2, dict()),
(MultiTaskLasso, 2, dict()),
],
)
def test_enet_coordinate_descent(klass, n_classes, kwargs):
| """Test that a warning is issued if model does not converge"""
clf = klass(max_iter=2, **kwargs)
n_samples = 5
n_features = 2
X = np.ones((n_samples, n_features)) * 1e50
y = np.ones((n_samples, n_classes))
if klass == Lasso:
y = y.ravel()
warning_message = (
"Objective di... | @pytest.mark.parametrize(
"klass, n_classes, kwargs",
[
(Lasso, 1, dict(precompute=True)),
(Lasso, 1, dict(precompute=False)),
(MultiTaskLasso, 2, dict()),
(MultiTaskLasso, 2, dict()),
],
)
def test_enet_coordinate_descent(klass, n_classes, kwargs):
| 83 | 64 | 216 | 83 | 0 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_coordinate_descent | test_enet_coordinate_descent | 1,368 | 1,391 | 1,368 | 1,377 | 20a2907e2cf8b1538e263ca4c777164d477a393f | bigcode/the-stack | train |
eb0867c902d1c09aefb321c2 | train | function | def test_enet_toy():
# Test ElasticNet for various parameters of alpha and l1_ratio.
# Actually, the parameters alpha = 0 should not be allowed. However,
# we test it as a border case.
# ElasticNet is tested with and without precomputed Gram matrix
X = np.array([[-1.0], [0.0], [1.0]])
Y = [-1, ... | def test_enet_toy():
# Test ElasticNet for various parameters of alpha and l1_ratio.
# Actually, the parameters alpha = 0 should not be allowed. However,
# we test it as a border case.
# ElasticNet is tested with and without precomputed Gram matrix
| X = np.array([[-1.0], [0.0], [1.0]])
Y = [-1, 0, 1] # just a straight line
T = [[2.0], [3.0], [4.0]] # test sample
# this should be the same as lasso
clf = ElasticNet(alpha=1e-8, l1_ratio=1.0)
clf.fit(X, Y)
pred = clf.predict(T)
assert_array_almost_equal(clf.coef_, [1])
assert_arr... | assert_array_almost_equal(clf.coef_, [0.25])
assert_array_almost_equal(pred, [0.5, 0.75, 1.0])
assert_almost_equal(clf.dual_gap_, 0)
clf = Lasso(alpha=1)
clf.fit(X, Y)
pred = clf.predict(T)
assert_array_almost_equal(clf.coef_, [0.0])
assert_array_almost_equal(pred, [0, 0, 0])
assert_al... | 185 | 185 | 618 | 63 | 122 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_toy | test_enet_toy | 247 | 291 | 247 | 252 | 1b7d6d5a20f6c5fc44d32fe98b3a8bad7a057c9e | bigcode/the-stack | train |
ae070f4dbc0d1fd1758f8dc9 | train | function | @pytest.mark.parametrize("path_func", [enet_path, lasso_path])
def test_path_unknown_parameter(path_func):
"""Check that passing parameter not used by the coordinate descent solver
will raise an error."""
X, y, _, _ = build_dataset(n_samples=50, n_features=20)
err_msg = "Unexpected parameters in params"... | @pytest.mark.parametrize("path_func", [enet_path, lasso_path])
def test_path_unknown_parameter(path_func):
| """Check that passing parameter not used by the coordinate descent solver
will raise an error."""
X, y, _, _ = build_dataset(n_samples=50, n_features=20)
err_msg = "Unexpected parameters in params"
with pytest.raises(ValueError, match=err_msg):
path_func(X, y, normalize=True, fit_intercept=T... | _path]:
_, coefs, _ = path(X, y)
_, sparse_coefs, _ = path(csr, y)
assert_array_almost_equal(coefs, sparse_coefs)
@pytest.mark.parametrize("path_func", [enet_path, lasso_path])
def test_path_unknown_parameter(path_func):
| 64 | 64 | 100 | 23 | 41 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_path_unknown_parameter | test_path_unknown_parameter | 1,161 | 1,168 | 1,161 | 1,162 | 6b36c15c94823d16c041c49b89b75d38d9afa658 | bigcode/the-stack | train |
b1ccab61e1f30b42389b275a | train | function | def test_lasso_cv_positive_constraint():
X, y, X_test, y_test = build_dataset()
max_iter = 500
# Ensure the unconstrained fit has a negative coefficient
clf_unconstrained = LassoCV(n_alphas=3, eps=1e-1, max_iter=max_iter, cv=2, n_jobs=1)
clf_unconstrained.fit(X, y)
assert min(clf_unconstrained.... | def test_lasso_cv_positive_constraint():
| X, y, X_test, y_test = build_dataset()
max_iter = 500
# Ensure the unconstrained fit has a negative coefficient
clf_unconstrained = LassoCV(n_alphas=3, eps=1e-1, max_iter=max_iter, cv=2, n_jobs=1)
clf_unconstrained.fit(X, y)
assert min(clf_unconstrained.coef_) < 0
# On same data, constrain... | ShuffleSplit
from sklearn import datasets
diabetes = datasets.load_diabetes()
X = diabetes.data
y = diabetes.target
pipe = make_pipeline(StandardScaler(), LassoCV(cv=ShuffleSplit(random_state=0)))
pipe.fit(X, y)
def test_lasso_cv_positive_constraint():
| 64 | 64 | 180 | 8 | 56 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_lasso_cv_positive_constraint | test_lasso_cv_positive_constraint | 374 | 388 | 374 | 374 | 31b4c5f57fb7f1f50dc365dbd34a0f77b884a65c | bigcode/the-stack | train |
2f838a9b16ef00da0acb6c10 | train | function | def test_1d_multioutput_enet_and_multitask_enet_cv():
X, y, _, _ = build_dataset(n_features=10)
y = y[:, np.newaxis]
clf = ElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7])
clf.fit(X, y[:, 0])
clf1 = MultiTaskElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7])
clf1.fit(X, y)
assert... | def test_1d_multioutput_enet_and_multitask_enet_cv():
| X, y, _, _ = build_dataset(n_features=10)
y = y[:, np.newaxis]
clf = ElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7])
clf.fit(X, y[:, 0])
clf1 = MultiTaskElasticNetCV(n_alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7])
clf1.fit(X, y)
assert_almost_equal(clf.l1_ratio_, clf1.l1_ratio_)
asser... | == clf.coef_.shape
assert (3,) == clf.intercept_.shape
assert (10, 3) == clf.mse_path_.shape
assert 10 == len(clf.alphas_)
def test_1d_multioutput_enet_and_multitask_enet_cv():
| 63 | 64 | 190 | 17 | 46 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_1d_multioutput_enet_and_multitask_enet_cv | test_1d_multioutput_enet_and_multitask_enet_cv | 945 | 955 | 945 | 945 | f3ac13cd01342e223b939c685053a0037aed412f | bigcode/the-stack | train |
1330cea89bc64b854b6aa150 | train | function | @pytest.mark.parametrize("fit_intercept", [True, False])
@pytest.mark.parametrize("alpha", [0.01])
@pytest.mark.parametrize("normalize", [False, True])
@pytest.mark.parametrize("precompute", [False, True])
def test_enet_sample_weight_consistency(fit_intercept, alpha, normalize, precompute):
"""Test that the impact ... | @pytest.mark.parametrize("fit_intercept", [True, False])
@pytest.mark.parametrize("alpha", [0.01])
@pytest.mark.parametrize("normalize", [False, True])
@pytest.mark.parametrize("precompute", [False, True])
def test_enet_sample_weight_consistency(fit_intercept, alpha, normalize, precompute):
| """Test that the impact of sample_weight is consistent."""
rng = np.random.RandomState(0)
n_samples, n_features = 10, 5
X = rng.rand(n_samples, n_features)
y = rng.rand(n_samples)
params = dict(
alpha=alpha,
fit_intercept=fit_intercept,
precompute=precompute,
tol... | 0
def test_multi_task_lasso_cv_dtype():
n_samples, n_features = 10, 3
rng = np.random.RandomState(42)
X = rng.binomial(1, 0.5, size=(n_samples, n_features))
X = X.astype(int) # make it explicit that X is int
y = X[:, [0, 0]].copy()
est = MultiTaskLassoCV(n_alphas=5, fit_intercept=True).fit(X... | 205 | 205 | 685 | 67 | 138 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_sample_weight_consistency | test_enet_sample_weight_consistency | 1,458 | 1,526 | 1,458 | 1,462 | 0d07f4867dda4f39ccef8ed04c1fadcbe5331b96 | bigcode/the-stack | train |
ecfe788200f0d690edda8cd8 | train | function | def test_enet_cv_positive_constraint():
X, y, X_test, y_test = build_dataset()
max_iter = 500
# Ensure the unconstrained fit has a negative coefficient
enetcv_unconstrained = ElasticNetCV(
n_alphas=3, eps=1e-1, max_iter=max_iter, cv=2, n_jobs=1
)
enetcv_unconstrained.fit(X, y)
asser... | def test_enet_cv_positive_constraint():
| X, y, X_test, y_test = build_dataset()
max_iter = 500
# Ensure the unconstrained fit has a negative coefficient
enetcv_unconstrained = ElasticNetCV(
n_alphas=3, eps=1e-1, max_iter=max_iter, cv=2, n_jobs=1
)
enetcv_unconstrained.fit(X, y)
assert min(enetcv_unconstrained.coef_) < 0
... | y = [1, 0, -1] # just a straight line with negative slope
enet = ElasticNet(alpha=0.1, positive=True)
enet.fit(X, y)
assert min(enet.coef_) >= 0
def test_enet_cv_positive_constraint():
| 64 | 64 | 194 | 8 | 55 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_cv_positive_constraint | test_enet_cv_positive_constraint | 795 | 811 | 795 | 795 | 13d69a1c1ce1e31ecb806c8c8b81244ef9298fc3 | bigcode/the-stack | train |
30c6aebf665dbb9a36e4e95e | train | function | def test_warm_start_convergence():
X, y, _, _ = build_dataset()
model = ElasticNet(alpha=1e-3, tol=1e-3).fit(X, y)
n_iter_reference = model.n_iter_
# This dataset is not trivial enough for the model to converge in one pass.
assert n_iter_reference > 2
# Check that n_iter_ is invariant to multi... | def test_warm_start_convergence():
| X, y, _, _ = build_dataset()
model = ElasticNet(alpha=1e-3, tol=1e-3).fit(X, y)
n_iter_reference = model.n_iter_
# This dataset is not trivial enough for the model to converge in one pass.
assert n_iter_reference > 2
# Check that n_iter_ is invariant to multiple calls to fit
# when warm_st... | _c, y, sample_weight=sample_weight)
clf2 = ElasticNet(alpha=0.01, precompute=False)
clf2.fit(X, y, sample_weight=sample_weight)
assert_allclose(clf1.coef_, clf2.coef_)
def test_warm_start_convergence():
| 63 | 64 | 205 | 8 | 55 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_warm_start_convergence | test_warm_start_convergence | 1,043 | 1,062 | 1,043 | 1,043 | 0b19081aa10997db7b3b8fa338f44e364b63221f | bigcode/the-stack | train |
09f47e307d47cf0458b27c33 | train | function | def test_enet_multitarget():
n_targets = 3
X, y, _, _ = build_dataset(
n_samples=10, n_features=8, n_informative_features=10, n_targets=n_targets
)
estimator = ElasticNet(alpha=0.01)
estimator.fit(X, y)
coef, intercept, dual_gap = (
estimator.coef_,
estimator.intercept_,
... | def test_enet_multitarget():
| n_targets = 3
X, y, _, _ = build_dataset(
n_samples=10, n_features=8, n_informative_features=10, n_targets=n_targets
)
estimator = ElasticNet(alpha=0.01)
estimator.fit(X, y)
coef, intercept, dual_gap = (
estimator.coef_,
estimator.intercept_,
estimator.dual_gap_,
... | MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y)
assert 0 < clf.dual_gap_ < 1e-5
assert_array_almost_equal(clf.coef_[0], clf.coef_[1])
def test_enet_multitarget():
| 64 | 64 | 160 | 8 | 56 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_multitarget | test_enet_multitarget | 889 | 906 | 889 | 889 | eafdafad6d6f11fef1be312bc2a5194193ab185b | bigcode/the-stack | train |
1424b6ec1e3d3e5c75fe1e84 | train | function | def test_multi_task_lasso_readonly_data():
X, y, X_test, y_test = build_dataset()
Y = np.c_[y, y]
with TempMemmap((X, Y)) as (X, Y):
Y = np.c_[y, y]
clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y)
assert 0 < clf.dual_gap_ < 1e-5
assert_array_almost_equal(clf.coef_[0], clf.c... | def test_multi_task_lasso_readonly_data():
| X, y, X_test, y_test = build_dataset()
Y = np.c_[y, y]
with TempMemmap((X, Y)) as (X, Y):
Y = np.c_[y, y]
clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y)
assert 0 < clf.dual_gap_ < 1e-5
assert_array_almost_equal(clf.coef_[0], clf.coef_[1])
| )
assert_array_almost_equal(clf.coef_, [0.25])
assert_array_almost_equal(pred, [0.5, 0.75, 1.0])
assert_almost_equal(clf.dual_gap_, 0)
def test_multi_task_lasso_readonly_data():
| 64 | 64 | 119 | 10 | 54 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_multi_task_lasso_readonly_data | test_multi_task_lasso_readonly_data | 879 | 886 | 879 | 879 | 227bff0f96314d1d002a6b6446d159c7473fd541 | bigcode/the-stack | train |
65e310d61cb393924ab3f1f3 | train | function | @pytest.mark.filterwarnings("ignore:'normalize' was deprecated")
@pytest.mark.parametrize(
"estimator, params",
[
(Lasso, {"tol": 1e-16, "alpha": 0.1}),
(RidgeClassifier, {"solver": "sparse_cg", "alpha": 0.1}),
(ElasticNet, {"tol": 1e-16, "l1_ratio": 1, "alpha": 0.1}),
(ElasticNe... | @pytest.mark.filterwarnings("ignore:'normalize' was deprecated")
@pytest.mark.parametrize(
"estimator, params",
[
(Lasso, {"tol": 1e-16, "alpha": 0.1}),
(RidgeClassifier, {"solver": "sparse_cg", "alpha": 0.1}),
(ElasticNet, {"tol": 1e-16, "l1_ratio": 1, "alpha": 0.1}),
(ElasticNe... | model_name = estimator.__name__
if model_name in ["Lasso", "ElasticNet"] and is_sparse:
pytest.skip(f"{model_name} does not support sample_weight with sparse")
rng = np.random.RandomState(0)
X, y = make_regression(n_samples=20, n_features=5, noise=1e-2, random_state=rng)
if is_classifier(... | @pytest.mark.filterwarnings("ignore:'normalize' was deprecated")
@pytest.mark.parametrize(
"estimator, params",
[
(Lasso, {"tol": 1e-16, "alpha": 0.1}),
(RidgeClassifier, {"solver": "sparse_cg", "alpha": 0.1}),
(ElasticNet, {"tol": 1e-16, "l1_ratio": 1, "alpha": 0.1}),
(ElasticNe... | 335 | 256 | 953 | 335 | 0 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_linear_model_sample_weights_normalize_in_pipeline | test_linear_model_sample_weights_normalize_in_pipeline | 497 | 591 | 497 | 526 | c8bef2f639819441a39cfaba557d16dc39935895 | bigcode/the-stack | train |
acd71930284c90572f1513aa | train | function | @pytest.mark.filterwarnings("ignore:'normalize' was deprecated")
@pytest.mark.parametrize("ridge_alpha", [1e-1, 1.0, 1e6])
@pytest.mark.parametrize("normalize", [True, False])
def test_enet_ridge_consistency(normalize, ridge_alpha):
# Check that ElasticNet(l1_ratio=0) converges to the same solution as Ridge
# p... | @pytest.mark.filterwarnings("ignore:'normalize' was deprecated")
@pytest.mark.parametrize("ridge_alpha", [1e-1, 1.0, 1e6])
@pytest.mark.parametrize("normalize", [True, False])
def test_enet_ridge_consistency(normalize, ridge_alpha):
# Check that ElasticNet(l1_ratio=0) converges to the same solution as Ridge
# p... | rng = np.random.RandomState(42)
n_samples = 300
X, y = make_regression(
n_samples=n_samples,
n_features=100,
effective_rank=10,
n_informative=50,
random_state=rng,
)
sw = rng.uniform(low=0.01, high=10, size=X.shape[0])
alpha = 1.0
common_params = dict(... | @pytest.mark.filterwarnings("ignore:'normalize' was deprecated")
@pytest.mark.parametrize("ridge_alpha", [1e-1, 1.0, 1e6])
@pytest.mark.parametrize("normalize", [True, False])
def test_enet_ridge_consistency(normalize, ridge_alpha):
# Check that ElasticNet(l1_ratio=0) converges to the same solution as Ridge
# p... | 156 | 113 | 379 | 156 | 0 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_ridge_consistency | test_enet_ridge_consistency | 1,722 | 1,758 | 1,722 | 1,733 | 9a8e4959aead503e8d35eeb8bb3069ee8db6e20f | bigcode/the-stack | train |
21cf7a6bccc6b409720db06f | train | function | @pytest.mark.parametrize(
"params, err_type, err_msg",
[
({"alpha": -1}, ValueError, "alpha == -1, must be >= 0.0"),
({"l1_ratio": -1}, ValueError, "l1_ratio == -1, must be >= 0.0"),
({"l1_ratio": 2}, ValueError, "l1_ratio == 2, must be <= 1.0"),
(
{"l1_ratio": "1"},
... | @pytest.mark.parametrize(
"params, err_type, err_msg",
[
({"alpha": -1}, ValueError, "alpha == -1, must be >= 0.0"),
({"l1_ratio": -1}, ValueError, "l1_ratio == -1, must be >= 0.0"),
({"l1_ratio": 2}, ValueError, "l1_ratio == 2, must be <= 1.0"),
(
{"l1_ratio": "1"},
... | X = np.array([[-1.0], [0.0], [1.0]])
y = [-1, 0, 1] # just a straight line
enet = ElasticNet(**params)
with pytest.raises(err_type, match=err_msg):
enet.fit(X, y)
| @pytest.mark.parametrize(
"params, err_type, err_msg",
[
({"alpha": -1}, ValueError, "alpha == -1, must be >= 0.0"),
({"l1_ratio": -1}, ValueError, "l1_ratio == -1, must be >= 0.0"),
({"l1_ratio": 2}, ValueError, "l1_ratio == 2, must be <= 1.0"),
(
{"l1_ratio": "1"},
... | 312 | 114 | 381 | 312 | 0 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_param_invalid | test_param_invalid | 109 | 143 | 109 | 137 | cc4285fa7eea9c3a0b69cf5acc6cb94ae6c26e2b | bigcode/the-stack | train |
46db0fca0ba53ccfe551278c | train | function | def test_precompute_invalid_argument():
X, y, _, _ = build_dataset()
for clf in [ElasticNetCV(precompute="invalid"), LassoCV(precompute="invalid")]:
err_msg = ".*should be.*True.*False.*auto.* array-like.*Got 'invalid'"
with pytest.raises(ValueError, match=err_msg):
clf.fit(X, y)
... | def test_precompute_invalid_argument():
| X, y, _, _ = build_dataset()
for clf in [ElasticNetCV(precompute="invalid"), LassoCV(precompute="invalid")]:
err_msg = ".*should be.*True.*False.*auto.* array-like.*Got 'invalid'"
with pytest.raises(ValueError, match=err_msg):
clf.fit(X, y)
# Precompute = 'auto' is not supported... | =5)
clf1.fit(sparse.csr_matrix(X, dtype=np.float32), y)
assert_almost_equal(clf.alpha_, clf1.alpha_, decimal=6)
assert_almost_equal(clf.coef_, clf1.coef_, decimal=6)
def test_precompute_invalid_argument():
| 64 | 64 | 189 | 7 | 57 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_precompute_invalid_argument | test_precompute_invalid_argument | 987 | 1,001 | 987 | 987 | 9190e1259ed1b7a8f290d89d53c714b1af8de102 | bigcode/the-stack | train |
b50f0aaf683ba267ea446802 | train | function | @pytest.mark.parametrize("estimator", (Lasso, ElasticNet))
def test_enet_sample_weight_sparse(estimator):
reg = estimator()
X = sparse.csc_matrix(np.zeros((3, 2)))
y = np.array([-1, 0, 1])
sw = np.array([1, 2, 3])
with pytest.raises(
ValueError, match="Sample weights do not.*support sparse m... | @pytest.mark.parametrize("estimator", (Lasso, ElasticNet))
def test_enet_sample_weight_sparse(estimator):
| reg = estimator()
X = sparse.csc_matrix(np.zeros((3, 2)))
y = np.array([-1, 0, 1])
sw = np.array([1, 2, 3])
with pytest.raises(
ValueError, match="Sample weights do not.*support sparse matrices"
):
reg.fit(X, y, sample_weight=sw, check_input=True)
| sample_weight_1)
reg2 = ElasticNet(**params).fit(X2, y2, sample_weight=None)
assert_allclose(reg1.coef_, reg2.coef_)
@pytest.mark.parametrize("estimator", (Lasso, ElasticNet))
def test_enet_sample_weight_sparse(estimator):
| 63 | 64 | 110 | 24 | 39 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_sample_weight_sparse | test_enet_sample_weight_sparse | 1,529 | 1,538 | 1,529 | 1,530 | 80b51935e522f2dfe03b0f816df30bf878192862 | bigcode/the-stack | train |
ac22231158a6a73150e2e61f | train | function | def test_path_parameters():
X, y, _, _ = build_dataset()
max_iter = 100
clf = ElasticNetCV(n_alphas=50, eps=1e-3, max_iter=max_iter, l1_ratio=0.5, tol=1e-3)
clf.fit(X, y) # new params
assert_almost_equal(0.5, clf.l1_ratio)
assert 50 == clf.n_alphas
assert 50 == len(clf.alphas_)
| def test_path_parameters():
| X, y, _, _ = build_dataset()
max_iter = 100
clf = ElasticNetCV(n_alphas=50, eps=1e-3, max_iter=max_iter, l1_ratio=0.5, tol=1e-3)
clf.fit(X, y) # new params
assert_almost_equal(0.5, clf.l1_ratio)
assert 50 == clf.n_alphas
assert 50 == len(clf.alphas_)
| , l1_ratio=[0.5, 0.7])
clf2.fit(X, y[:, np.newaxis])
assert_almost_equal(clf1.l1_ratio_, clf2.l1_ratio_)
assert_almost_equal(clf1.alpha_, clf2.alpha_)
def test_path_parameters():
| 63 | 64 | 110 | 5 | 58 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_path_parameters | test_path_parameters | 737 | 745 | 737 | 737 | 23dc37e63aea67d2af51519adc17654f122c5ad8 | bigcode/the-stack | train |
76225f74c0d4ba774ae6ba79 | train | function | @pytest.mark.parametrize("order", ["C", "F"])
@pytest.mark.parametrize("input_order", ["C", "F"])
def test_set_order_sparse(order, input_order):
"""Check that _set_order returns sparse matrices in promised format."""
X = sparse.coo_matrix(np.array([[0], [0], [0]]))
y = sparse.coo_matrix(np.array([0, 0, 0]))... | @pytest.mark.parametrize("order", ["C", "F"])
@pytest.mark.parametrize("input_order", ["C", "F"])
def test_set_order_sparse(order, input_order):
| """Check that _set_order returns sparse matrices in promised format."""
X = sparse.coo_matrix(np.array([[0], [0], [0]]))
y = sparse.coo_matrix(np.array([0, 0, 0]))
sparse_format = "csc" if input_order == "F" else "csr"
X = X.asformat(sparse_format)
y = X.asformat(sparse_format)
X2, y2 = _set... | .flags["F_CONTIGUOUS"]
if order == input_order:
assert X is X2
assert y is y2
@pytest.mark.parametrize("order", ["C", "F"])
@pytest.mark.parametrize("input_order", ["C", "F"])
def test_set_order_sparse(order, input_order):
| 64 | 64 | 205 | 35 | 28 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_set_order_sparse | test_set_order_sparse | 165 | 180 | 165 | 167 | 1c3d80c8ab2d7081d3dc36862fc1c3363f315c89 | bigcode/the-stack | train |
094139251674eee214e1cdad | train | function | def test_enet_nonfinite_params():
# Check ElasticNet throws ValueError when dealing with non-finite parameter
# values
rng = np.random.RandomState(0)
n_samples = 10
fmax = np.finfo(np.float64).max
X = fmax * rng.uniform(size=(n_samples, 2))
y = rng.randint(0, 2, size=n_samples)
clf = El... | def test_enet_nonfinite_params():
# Check ElasticNet throws ValueError when dealing with non-finite parameter
# values
| rng = np.random.RandomState(0)
n_samples = 10
fmax = np.finfo(np.float64).max
X = fmax * rng.uniform(size=(n_samples, 2))
y = rng.randint(0, 2, size=n_samples)
clf = ElasticNet(alpha=0.1)
msg = "Coordinate descent iterations resulted in non-finite parameter values"
with pytest.raises(Va... | ef_, [0])
assert_array_almost_equal(pred, [0, 0, 0])
assert_almost_equal(clf.dual_gap_, 0)
def test_enet_nonfinite_params():
# Check ElasticNet throws ValueError when dealing with non-finite parameter
# values
| 64 | 64 | 133 | 28 | 36 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_nonfinite_params | test_enet_nonfinite_params | 194 | 206 | 194 | 196 | d75bbabcdba01ad310a9cb19ccc86870673d53f4 | bigcode/the-stack | train |
df9d9b89c50da53b33e6c81c | train | function | def test_lasso_alpha_warning():
X = [[-1], [0], [1]]
Y = [-1, 0, 1] # just a straight line
clf = Lasso(alpha=0)
warning_message = (
"With alpha=0, this algorithm does not "
"converge well. You are advised to use the "
"LinearRegression estimator"
)
with pytest.warns(Use... | def test_lasso_alpha_warning():
| X = [[-1], [0], [1]]
Y = [-1, 0, 1] # just a straight line
clf = Lasso(alpha=0)
warning_message = (
"With alpha=0, this algorithm does not "
"converge well. You are advised to use the "
"LinearRegression estimator"
)
with pytest.warns(UserWarning, match=warning_message)... | # do a second round with 5 iterations
clf2 = ElasticNet(alpha=0.1, max_iter=10)
ignore_warnings(clf2.fit)(X, y)
assert_array_almost_equal(clf2.coef_, clf.coef_)
def test_lasso_alpha_warning():
| 63 | 64 | 107 | 7 | 56 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_lasso_alpha_warning | test_lasso_alpha_warning | 759 | 770 | 759 | 759 | a5855a0707938ed3a578542490a62688f3f92194 | bigcode/the-stack | train |
d7412a7799a26a83dfc192b5 | train | function | def test_multi_task_lasso_and_enet():
X, y, X_test, y_test = build_dataset()
Y = np.c_[y, y]
# Y_test = np.c_[y_test, y_test]
clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y)
assert 0 < clf.dual_gap_ < 1e-5
assert_array_almost_equal(clf.coef_[0], clf.coef_[1])
clf = MultiTaskElasticNet(alp... | def test_multi_task_lasso_and_enet():
| X, y, X_test, y_test = build_dataset()
Y = np.c_[y, y]
# Y_test = np.c_[y_test, y_test]
clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y)
assert 0 < clf.dual_gap_ < 1e-5
assert_array_almost_equal(clf.coef_[0], clf.coef_[1])
clf = MultiTaskElasticNet(alpha=1, tol=1e-8).fit(X, Y)
assert 0... | 2[:, 0].fill(y_values)
y2[:, 1].fill(2 * y_values)
assert_array_equal(model.fit(X_train, y2).predict(X_test), y2)
assert_array_equal(model.alphas_, [np.finfo(float).resolution] * 3)
def test_multi_task_lasso_and_enet():
| 72 | 72 | 240 | 10 | 62 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_multi_task_lasso_and_enet | test_multi_task_lasso_and_enet | 845 | 863 | 845 | 845 | 1706e77f204246724d5613aaba31b73c076ec07a | bigcode/the-stack | train |
99135dd6d59e1047bc17e76c | train | function | def test_1d_multioutput_lasso_and_multitask_lasso_cv():
X, y, _, _ = build_dataset(n_features=10)
y = y[:, np.newaxis]
clf = LassoCV(n_alphas=5, eps=2e-3)
clf.fit(X, y[:, 0])
clf1 = MultiTaskLassoCV(n_alphas=5, eps=2e-3)
clf1.fit(X, y)
assert_almost_equal(clf.alpha_, clf1.alpha_)
assert_... | def test_1d_multioutput_lasso_and_multitask_lasso_cv():
| X, y, _, _ = build_dataset(n_features=10)
y = y[:, np.newaxis]
clf = LassoCV(n_alphas=5, eps=2e-3)
clf.fit(X, y[:, 0])
clf1 = MultiTaskLassoCV(n_alphas=5, eps=2e-3)
clf1.fit(X, y)
assert_almost_equal(clf.alpha_, clf1.alpha_)
assert_almost_equal(clf.coef_, clf1.coef_[0])
assert_almost... | assert_almost_equal(clf.alpha_, clf1.alpha_)
assert_almost_equal(clf.coef_, clf1.coef_[0])
assert_almost_equal(clf.intercept_, clf1.intercept_[0])
def test_1d_multioutput_lasso_and_multitask_lasso_cv():
| 64 | 64 | 147 | 17 | 47 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_1d_multioutput_lasso_and_multitask_lasso_cv | test_1d_multioutput_lasso_and_multitask_lasso_cv | 958 | 967 | 958 | 958 | c881a72d00077cbda35a3275302b8def6d1aaa47 | bigcode/the-stack | train |
102e38501d8ab97d1b88f056 | train | function | def test_warm_start_convergence_with_regularizer_decrement():
X, y = load_diabetes(return_X_y=True)
# Train a model to converge on a lightly regularized problem
final_alpha = 1e-5
low_reg_model = ElasticNet(alpha=final_alpha).fit(X, y)
# Fitting a new model on a more regularized version of the sam... | def test_warm_start_convergence_with_regularizer_decrement():
| X, y = load_diabetes(return_X_y=True)
# Train a model to converge on a lightly regularized problem
final_alpha = 1e-5
low_reg_model = ElasticNet(alpha=final_alpha).fit(X, y)
# Fitting a new model on a more regularized version of the same problem.
# Fitting with high regularization is easier it... | using a warm start: the optimizer just performs
# a single pass before checking that it has already converged
model.set_params(warm_start=True)
model.fit(X, y)
n_iter_warm_start = model.n_iter_
assert n_iter_warm_start == 1
def test_warm_start_convergence_with_regularizer_decrement():
| 75 | 75 | 252 | 13 | 61 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_warm_start_convergence_with_regularizer_decrement | test_warm_start_convergence_with_regularizer_decrement | 1,065 | 1,085 | 1,065 | 1,065 | 43e6b23107623b75b6aaf1f890555ba1bc3fd79f | bigcode/the-stack | train |
fca0dbff79206269af35bb75 | train | function | @pytest.mark.parametrize(
"precompute, inner_precompute",
[
(True, True),
("auto", False),
(False, False),
],
)
def test_lassoCV_does_not_set_precompute(monkeypatch, precompute, inner_precompute):
X, y, _, _ = build_dataset()
calls = 0
class LassoMock(Lasso):
def... | @pytest.mark.parametrize(
"precompute, inner_precompute",
[
(True, True),
("auto", False),
(False, False),
],
)
def test_lassoCV_does_not_set_precompute(monkeypatch, precompute, inner_precompute):
| X, y, _, _ = build_dataset()
calls = 0
class LassoMock(Lasso):
def fit(self, X, y):
super().fit(X, y)
nonlocal calls
calls += 1
assert self.precompute == inner_precompute
monkeypatch.setattr("sklearn.linear_model._coordinate_descent.Lasso", Lasso... | .message for w in record]
@pytest.mark.parametrize(
"precompute, inner_precompute",
[
(True, True),
("auto", False),
(False, False),
],
)
def test_lassoCV_does_not_set_precompute(monkeypatch, precompute, inner_precompute):
| 64 | 64 | 168 | 58 | 6 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_lassoCV_does_not_set_precompute | test_lassoCV_does_not_set_precompute | 1,423 | 1,445 | 1,423 | 1,431 | b24e5e98dddc54ba5388e869671ee895cd5c6de9 | bigcode/the-stack | train |
cec1d628d4eef4df808bf6d5 | train | function | def test_coef_shape_not_zero():
est_no_intercept = Lasso(fit_intercept=False)
est_no_intercept.fit(np.c_[np.ones(3)], np.ones(3))
assert est_no_intercept.coef_.shape == (1,)
| def test_coef_shape_not_zero():
| est_no_intercept = Lasso(fit_intercept=False)
est_no_intercept.fit(np.c_[np.ones(3)], np.ones(3))
assert est_no_intercept.coef_.shape == (1,)
| (l1_ratio=0, **estkwds)
with ignore_warnings():
est.fit(X, y[:, None])
est_desired.fit(X, y[:, None])
assert_array_almost_equal(est.coef_, est_desired.coef_, decimal=5)
def test_coef_shape_not_zero():
| 64 | 64 | 54 | 7 | 57 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_coef_shape_not_zero | test_coef_shape_not_zero | 1,350 | 1,353 | 1,350 | 1,350 | 99a094a7e61384518987ec39ff8507b323de83a6 | bigcode/the-stack | train |
4f91d22076d3a27a435796e9 | train | function | def test_enet_copy_X_False_check_input_False():
X, y, _, _ = build_dataset()
X = X.copy(order="F")
original_X = X.copy()
enet = ElasticNet(copy_X=False)
enet.fit(X, y, check_input=False)
# No copying, X is overwritten
assert np.any(np.not_equal(original_X, X))
| def test_enet_copy_X_False_check_input_False():
| X, y, _, _ = build_dataset()
X = X.copy(order="F")
original_X = X.copy()
enet = ElasticNet(copy_X=False)
enet.fit(X, y, check_input=False)
# No copying, X is overwritten
assert np.any(np.not_equal(original_X, X))
| _dataset()
X = X.copy(order="F")
original_X = X.copy()
enet = ElasticNet(copy_X=True)
enet.fit(X, y, check_input=check_input)
assert_array_equal(original_X, X)
def test_enet_copy_X_False_check_input_False():
| 64 | 64 | 83 | 13 | 51 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_enet_copy_X_False_check_input_False | test_enet_copy_X_False_check_input_False | 1,202 | 1,211 | 1,202 | 1,202 | 0b254382afcd14498ab5e4ef88664be744e6c0d9 | bigcode/the-stack | train |
ef1c530ff1f7a36fa21025b5 | train | function | def test_lasso_path_return_models_vs_new_return_gives_same_coefficients():
# Test that lasso_path with lars_path style output gives the
# same result
# Some toy data
X = np.array([[1, 2, 3.1], [2.3, 5.4, 4.3]]).T
y = np.array([1, 2, 3.1])
alphas = [5.0, 1.0, 0.5]
# Use lars_path and lasso_... | def test_lasso_path_return_models_vs_new_return_gives_same_coefficients():
# Test that lasso_path with lars_path style output gives the
# same result
# Some toy data
| X = np.array([[1, 2, 3.1], [2.3, 5.4, 4.3]]).T
y = np.array([1, 2, 3.1])
alphas = [5.0, 1.0, 0.5]
# Use lars_path and lasso_path(new output) with 1D linear interpolation
# to compute the same path
alphas_lars, _, coef_path_lars = lars_path(X, y, method="lasso")
coef_path_cont_lars = interpo... | y_pred_sparse = model_sparse.predict(X_sparse)
assert_allclose(y_pred_dense, y_pred_sparse)
assert_allclose(model_dense[1].intercept_, model_sparse[1].intercept_)
def test_lasso_path_return_models_vs_new_return_gives_same_coefficients():
# Test that lasso_path with lars_path style output gives the
# s... | 85 | 86 | 288 | 43 | 42 | AnkitKumar2698/scikit-learn | sklearn/linear_model/tests/test_coordinate_descent.py | Python | test_lasso_path_return_models_vs_new_return_gives_same_coefficients | test_lasso_path_return_models_vs_new_return_gives_same_coefficients | 648 | 670 | 648 | 652 | 773753ccc3cac76ab270670b538d1a29feb9916c | bigcode/the-stack | train |
4cef9cb58def47b658b60f67 | train | function | @rule
async def terraform_check(
request: TerraformCheckRequest, subsystem: TerraformValidateSubsystem
) -> CheckResults:
if subsystem.options.skip:
return CheckResults([], checker_name="terraform validate")
setup = await Get(StyleSetup, StyleSetupRequest(request, ("validate",)))
results = awai... | @rule
async def terraform_check(
request: TerraformCheckRequest, subsystem: TerraformValidateSubsystem
) -> CheckResults:
| if subsystem.options.skip:
return CheckResults([], checker_name="terraform validate")
setup = await Get(StyleSetup, StyleSetupRequest(request, ("validate",)))
results = await MultiGet(
Get(FallibleProcessResult, TerraformProcess, process)
for _, (process, _) in setup.directory_to_pr... | )
@property
def skip(self) -> bool:
return cast(bool, self.options.skip)
class TerraformCheckRequest(CheckRequest):
field_set_type = TerraformFieldSet
@rule
async def terraform_check(
request: TerraformCheckRequest, subsystem: TerraformValidateSubsystem
) -> CheckResults:
| 64 | 64 | 165 | 26 | 37 | yoav-orca/pants | src/python/pants/backend/terraform/goals/check.py | Python | terraform_check | terraform_check | 42 | 63 | 42 | 45 | 46d353f891416d6dffe2a49b71ea910b21d7e547 | bigcode/the-stack | train |
d95c3d814748357a73a65cb3 | train | class | class TerraformCheckRequest(CheckRequest):
field_set_type = TerraformFieldSet
| class TerraformCheckRequest(CheckRequest):
| field_set_type = TerraformFieldSet
| bool,
default=False,
help=(
f"Don't run `terraform validate` when running `{register.bootstrap.pants_bin_name} check`."
),
)
@property
def skip(self) -> bool:
return cast(bool, self.options.skip)
class TerraformCheckRequest(CheckRequest):
| 64 | 64 | 16 | 7 | 57 | yoav-orca/pants | src/python/pants/backend/terraform/goals/check.py | Python | TerraformCheckRequest | TerraformCheckRequest | 38 | 39 | 38 | 38 | 1fa407486be8b53c2283e88ee4c6251ca06951b9 | bigcode/the-stack | train |
b815dc178ff7abf2fa2a1ce1 | train | function | def rules():
return (
*collect_rules(),
UnionRule(CheckRequest, TerraformCheckRequest),
)
| def rules():
| return (
*collect_rules(),
UnionRule(CheckRequest, TerraformCheckRequest),
)
| directory, result in zip(setup.directory_to_process.keys(), results):
check_results.append(
CheckResult.from_fallible_process_result(
result, partition_description=f"`terraform validate` on `{directory}`"
)
)
return CheckResults(check_results, checker_name="... | 64 | 64 | 23 | 3 | 61 | yoav-orca/pants | src/python/pants/backend/terraform/goals/check.py | Python | rules | rules | 66 | 70 | 66 | 66 | 3cc5ded3534c3dd7cfc30b8da68aff3a59b88c00 | bigcode/the-stack | train |
8bc6ebb0639efa7749aa63dd | train | class | class TerraformValidateSubsystem(Subsystem):
options_scope = "terraform-validate"
help = """Terraform validate options."""
@classmethod
def register_options(cls, register):
super().register_options(register)
register(
"--skip",
type=bool,
default=Fals... | class TerraformValidateSubsystem(Subsystem):
| options_scope = "terraform-validate"
help = """Terraform validate options."""
@classmethod
def register_options(cls, register):
super().register_options(register)
register(
"--skip",
type=bool,
default=False,
help=(
f"Don't... | CheckResult, CheckResults
from pants.engine.internals.selectors import Get, MultiGet
from pants.engine.process import FallibleProcessResult
from pants.engine.rules import collect_rules, rule
from pants.engine.unions import UnionRule
from pants.option.subsystem import Subsystem
class TerraformValidateSubsystem(Subsyste... | 64 | 64 | 110 | 7 | 56 | yoav-orca/pants | src/python/pants/backend/terraform/goals/check.py | Python | TerraformValidateSubsystem | TerraformValidateSubsystem | 17 | 35 | 17 | 17 | ab354d0ca37abc06b2861a15626a060f4ba0ab9c | bigcode/the-stack | train |
0d5ebdb866260805af343849 | train | class | class DbTranData:
@staticmethod
def getFileName(cardHolderName,cardNo):
return DbTranDataFile%(cardHolderName,cardNo)
@staticmethod
def addToTran(valueTran):
#print(valueTran)
fname=DbTranData.getFileName(valueTran.cardHolderName,valueTran.cardNo)
#print(fname)
with open(fname, 'ab') as output:
pickle.... | class DbTranData:
@staticmethod
| def getFileName(cardHolderName,cardNo):
return DbTranDataFile%(cardHolderName,cardNo)
@staticmethod
def addToTran(valueTran):
#print(valueTran)
fname=DbTranData.getFileName(valueTran.cardHolderName,valueTran.cardNo)
#print(fname)
with open(fname, 'ab') as output:
pickle.dump(valueTran, output, pickle.HI... | =cardHolderName;
self.tranDate=tranDate;self.itemId=itemId;self.price=price;self.tranItem=None;self.isTranItem=False;
def __repr__(self):
return "%s- %s-%s-%s-%s-%s- %s"%(str(self.tranId),
str(self.cardId),str(self.cardNo),self.cardHolderName, str(self.tranDate),str(self.itemId),
str(self.price))
def Cate... | 197 | 197 | 658 | 9 | 188 | PacktPublishing/Python-Programming | expenseManager/app/TranData.py | Python | DbTranData | DbTranData | 18 | 91 | 18 | 19 | 1ad88a15930fe545512fdec1b292d5e57ae258fa | bigcode/the-stack | train |
b20605475ee03a1dfed6b051 | train | class | class TranData:
def __init__(self, tranId, cardId, cardNo,cardHolderName, tranDate, itemId, price):
self.tranId=tranId;self.cardId=cardId;self.cardNo=cardNo;self.cardHolderName=cardHolderName;
self.tranDate=tranDate;self.itemId=itemId;self.price=price;self.tranItem=None;self.isTranItem=False;
def __repr__(self):
... | class TranData:
| def __init__(self, tranId, cardId, cardNo,cardHolderName, tranDate, itemId, price):
self.tranId=tranId;self.cardId=cardId;self.cardNo=cardNo;self.cardHolderName=cardHolderName;
self.tranDate=tranDate;self.itemId=itemId;self.price=price;self.tranItem=None;self.isTranItem=False;
def __repr__(self):
return "%s- %s... | import pickle
class TranData:
| 7 | 70 | 235 | 4 | 2 | PacktPublishing/Python-Programming | expenseManager/app/TranData.py | Python | TranData | TranData | 2 | 15 | 2 | 2 | 1ee78a75828528eee4d960c670b1e0c43bb35f63 | bigcode/the-stack | train |
7ef59ade699d15184e19b0a4 | train | class | class DescribeMetricRuleCountRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Cms', '2019-01-01', 'DescribeMetricRuleCount','cms')
def get_Namespace(self):
return self.get_query_params().get('Namespace')
def set_Namespace(self,Namespace):
self.add_query_param('Namespace',Namespace)
... | class DescribeMetricRuleCountRequest(RpcRequest):
| def __init__(self):
RpcRequest.__init__(self, 'Cms', '2019-01-01', 'DescribeMetricRuleCount','cms')
def get_Namespace(self):
return self.get_query_params().get('Namespace')
def set_Namespace(self,Namespace):
self.add_query_param('Namespace',Namespace)
def get_MetricName(self):
return self.get_qu... | an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
class DescribeMetricRuleCountRequest(RpcRequest):
| 64 | 64 | 120 | 10 | 53 | sdk-team/aliyun-openapi-python-sdk | aliyun-python-sdk-cms/aliyunsdkcms/request/v20190101/DescribeMetricRuleCountRequest.py | Python | DescribeMetricRuleCountRequest | DescribeMetricRuleCountRequest | 21 | 36 | 21 | 22 | bfdb36c69ea5412abe94495bef22966af2746dcb | bigcode/the-stack | train |
50655271857e2869bb1398ae | train | function | def commit_notice_destination(path, changelist):
dirs = path.split('/')
if len(dirs) >= 4 and dirs[3] not in ("*", "..."):
directory = dirs[3]
else:
# No subdirectory, so just use "depot"
directory = dirs[2]
if directory not in ["evil-master-plan", "my-super-secret-repository"]:... | def commit_notice_destination(path, changelist):
| dirs = path.split('/')
if len(dirs) >= 4 and dirs[3] not in ("*", "..."):
directory = dirs[3]
else:
# No subdirectory, so just use "depot"
directory = dirs[2]
if directory not in ["evil-master-plan", "my-super-secret-repository"]:
return dict(stream = "%s-commits" % (di... | notification).
#
# The default code below will send every commit except for ones in the
# "master-plan" and "secret" subdirectories of //depot/ to:
# * stream "depot_subdirectory-commits"
# * subject "change_root"
def commit_notice_destination(path, changelist):
| 64 | 64 | 121 | 9 | 55 | enterstudio/zulip | api/integrations/perforce/zulip_perforce_config.py | Python | commit_notice_destination | commit_notice_destination | 43 | 56 | 43 | 43 | 7c355af83b25ba9c94c2ffa7fe772f262ba3701c | bigcode/the-stack | train |
543f2afb23ef8f1be7b786be | train | function | @udy.cod_cmd(
pattern="img(?: |$)(\d*)? ?([\s\S]*)",
command=("img", plugin_category),
info={
"header": "Google image search.",
"description": "To search images in google. By default will send 3 images.you can get more images(upto 10 only by changing limit value as shown in usage and example... | @udy.cod_cmd(
pattern="img(?: |$)(\d*)? ?([\s\S]*)",
command=("img", plugin_category),
info={
"header": "Google image search.",
"description": "To search images in google. By default will send 3 images.you can get more images(upto 10 only by changing limit value as shown in usage and example... | "Google image search."
reply_to_id = await reply_id(event)
if event.is_reply and not event.pattern_match.group(2):
query = await event.get_reply_message()
query = str(query.message)
else:
query = str(event.pattern_match.group(2))
if not query:
return await edit_or_rep... | @udy.cod_cmd(
pattern="img(?: |$)(\d*)? ?([\s\S]*)",
command=("img", plugin_category),
info={
"header": "Google image search.",
"description": "To search images in google. By default will send 3 images.you can get more images(upto 10 only by changing limit value as shown in usage and example... | 157 | 136 | 456 | 157 | 0 | brut69/AudyNesia | audynesia/plugins/images.py | Python | img_sampler | img_sampler | 14 | 65 | 14 | 28 | 02bca14d8eba057226094e27b162ee586dc2ac20 | bigcode/the-stack | train |
8cb0daa417479eb3be988336 | train | class | class AdminSiteTests(TestCase):
def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email="admin@yash.com",
password='password123'
)
self.client.force_login(self.admin_user)
self.user = get_user_model()... | class AdminSiteTests(TestCase):
| def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email="admin@yash.com",
password='password123'
)
self.client.force_login(self.admin_user)
self.user = get_user_model().objects.create_user(
... | from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import Client
class AdminSiteTests(TestCase):
| 35 | 75 | 252 | 7 | 27 | yashmehta001/recipe-app-api | app/core/tests/test_admin.py | Python | AdminSiteTests | AdminSiteTests | 7 | 42 | 7 | 8 | b5d3b7278b48224eeb66658c189c5856d6baf6be | bigcode/the-stack | train |
bebd657b2dbc0d1afc77e8e4 | train | function | def custom_ts_project(name, deps = [], **kwargs):
"""
Helper wrapper around ts_project adding default attributes and dependencies
Args:
name: The name that should be given the this rule
deps: A list of dependencies for this rule
kwargs: All other attrs are passed to ts_project
"... | def custom_ts_project(name, deps = [], **kwargs):
| """
Helper wrapper around ts_project adding default attributes and dependencies
Args:
name: The name that should be given the this rule
deps: A list of dependencies for this rule
kwargs: All other attrs are passed to ts_project
"""
ts_project(
name = name,
t... | """Example package for generating stardoc from rules_nodejs at source"""
load("@build_bazel_rules_nodejs//packages/typescript:index.bzl", "ts_project")
def custom_ts_project(name, deps = [], **kwargs):
| 47 | 64 | 119 | 12 | 35 | kriswuollett/rules_nodejs | examples/from_source/index.bzl | Python | custom_ts_project | custom_ts_project | 5 | 24 | 5 | 5 | 4e525859f0c1c0d9f5e30a48d0d03a506473867c | bigcode/the-stack | train |
eb9b84ad6f293ac8da089bda | train | class | class TestProblem2(unittest.TestCase):
def tests(self):
self.assertEqual(numSubarrayBoundedMax([2, 1, 4, 3], 2, 3), 3)
self.assertEqual(numSubarrayBoundedMax([2, 9, 2, 5, 6], 2, 8), 7)
self.assertEqual(numSubarrayBoundedMax([2, 2, 2, 2], 1, 3), 16)
self.assertEqual(numSubarrayBo... | class TestProblem2(unittest.TestCase):
| def tests(self):
self.assertEqual(numSubarrayBoundedMax([2, 1, 4, 3], 2, 3), 3)
self.assertEqual(numSubarrayBoundedMax([2, 9, 2, 5, 6], 2, 8), 7)
self.assertEqual(numSubarrayBoundedMax([2, 2, 2, 2], 1, 3), 16)
self.assertEqual(numSubarrayBoundedMax([1, 1, 1, 1, 1], 2, 3), 0)
| import unittest
from problem2 import numSubarrayBoundedMax
class TestProblem2(unittest.TestCase):
| 23 | 64 | 144 | 9 | 13 | jeffreycshelton/ghp-challenges | daily-problems/Day3/problem2_tests.py | Python | TestProblem2 | TestProblem2 | 5 | 11 | 5 | 6 | 7ab35cee709fd2ead6c199e58412526c6ce9970a | bigcode/the-stack | train |
c56ad0a66c91cfa911726a2e | train | function | def load_weights():
fff = h5py.File('Mybase/mask_rcnn_coco.h5','r') #打开h5文件
#print(list(f.keys()))
mydict = {}
mydict['global_step:0'] = 1000
########res1########
dset = fff['conv1']
a = dset['conv1']
b = np.array(a['kernel:0'], dtype=np.float32)
c = np.array(a['bias:0' ], dtype... | def load_weights():
| fff = h5py.File('Mybase/mask_rcnn_coco.h5','r') #打开h5文件
#print(list(f.keys()))
mydict = {}
mydict['global_step:0'] = 1000
########res1########
dset = fff['conv1']
a = dset['conv1']
b = np.array(a['kernel:0'], dtype=np.float32)
c = np.array(a['bias:0' ], dtype=np.float32)
dse... | import h5py
import pickle
import numpy as np
def load_weights():
| 17 | 256 | 33,886 | 4 | 12 | lior1990/semantic-instance-segmentation | Mybase/load_weights.py | Python | load_weights | load_weights | 5 | 1,570 | 5 | 5 | a1643de2d26854f3b3c55c284d85b102be0d7853 | bigcode/the-stack | train |
77d2e8148f1108d58f49261b | train | class | @attr.s(auto_attribs=True, kw_only=True)
class LayerGroup(Layer):
"""Layer Group.
A LayerGroup can be thought of as a layer that contains layers
(potentially including other LayerGroups).
Offset and opacity recursively affect child layers.
See: https://doc.mapeditor.org/en/stable/reference/tm... | @attr.s(auto_attribs=True, kw_only=True)
class LayerGroup(Layer):
| """Layer Group.
A LayerGroup can be thought of as a layer that contains layers
(potentially including other LayerGroups).
Offset and opacity recursively affect child layers.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#group
Attributes:
Layers (Optional[List... | /objects/#changing-stacking-order \
for more info.
"""
tiled_objects: List[TiledObject]
color: Optional[str] = None
draw_order: Optional[str] = "topdown"
@attr.s(auto_attribs=True, kw_only=True)
class LayerGroup(Layer):
| 64 | 64 | 121 | 19 | 45 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | LayerGroup | LayerGroup | 401 | 417 | 401 | 402 | a36ec2506088a6071adbc6cd423897d326be3f10 | bigcode/the-stack | train |
2db554a13130f6b672151a91 | train | class | class Color(NamedTuple):
"""
Color object.
Attributes:
red (int): Red, between 1 and 255.
green (int): Green, between 1 and 255.
blue (int): Blue, between 1 and 255.
alpha (int): Alpha, between 1 and 255.
"""
red: int
green: int
blue: int
alpha: int
| class Color(NamedTuple):
| """
Color object.
Attributes:
red (int): Red, between 1 and 255.
green (int): Green, between 1 and 255.
blue (int): Blue, between 1 and 255.
alpha (int): Alpha, between 1 and 255.
"""
red: int
green: int
blue: int
alpha: int
| """pytiled_parser objects for Tiled maps.
"""
# pylint: disable=too-few-public-methods
from pathlib import Path
from typing import Dict, List, NamedTuple, Optional, Union
import attr
class Color(NamedTuple):
| 52 | 64 | 93 | 6 | 45 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Color | Color | 12 | 26 | 12 | 12 | c29068a4acdc79c40ff2589f700fbdeb7137ab60 | bigcode/the-stack | train |
ffff2ee434c1a9979030f5b5 | train | class | @attr.s()
class RectangleObject(TiledObject):
"""Rectangle shape defined by a point, width, and height.
See: https://doc.mapeditor.org/en/stable/manual/objects/#insert-rectangle
(objects in tiled are rectangles by default, so there is no specific
documentation on the tmx-map-format page for it.... | @attr.s()
class RectangleObject(TiledObject):
| """Rectangle shape defined by a point, width, and height.
See: https://doc.mapeditor.org/en/stable/manual/objects/#insert-rectangle
(objects in tiled are rectangles by default, so there is no specific
documentation on the tmx-map-format page for it.)
"""
| rotation: int = 0
opacity: float = 1
name: Optional[str] = None
type: Optional[str] = None
properties: Optional[Properties] = None
template: Optional[Template] = None
@attr.s()
class RectangleObject(TiledObject):
| 64 | 64 | 75 | 11 | 52 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | RectangleObject | RectangleObject | 268 | 275 | 268 | 269 | ae1225bb7e29e955e8c9cdc68c4fd422fa43e73c | bigcode/the-stack | train |
8e70b6f0f3b749535e573665 | train | class | @attr.s(auto_attribs=True)
class Chunk:
"""
Chunk object for infinite maps.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#chunk
Attributes:
location (OrderedPair): Location of chunk in tiles.
width (int): The width of the chunk in tiles.
height (int): The h... | @attr.s(auto_attribs=True)
class Chunk:
| """
Chunk object for infinite maps.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#chunk
Attributes:
location (OrderedPair): Location of chunk in tiles.
width (int): The width of the chunk in tiles.
height (int): The height of the chunk in tiles.
lay... | object.
size (Union[int, float]): The height of the object.
"""
width: Union[int, float]
height: Union[int, float]
@attr.s(auto_attribs=True)
class Template:
"""FIXME TODO"""
@attr.s(auto_attribs=True)
class Chunk:
| 64 | 64 | 127 | 12 | 52 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Chunk | Chunk | 70 | 87 | 70 | 71 | d723d4853fbe45a93625088c71cc3db316667509 | bigcode/the-stack | train |
5d462c1e3b34071d144f1bdb | train | class | class Property(NamedTuple):
"""OrderedPair NamedTuple.
Attributes:
name str: Name of property
value str: Value of property
"""
name: str
value: str
| class Property(NamedTuple):
| """OrderedPair NamedTuple.
Attributes:
name str: Name of property
value str: Value of property
"""
name: str
value: str
|
class OrderedPair(NamedTuple):
"""OrderedPair NamedTuple.
Attributes:
x (Union[int, float]): X coordinate.
y (Union[int, float]): Y coordinate.
"""
x: Union[int, float]
y: Union[int, float]
class Property(NamedTuple):
| 64 | 64 | 44 | 6 | 58 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Property | Property | 41 | 50 | 41 | 41 | a08f549bbe6e4534fb176ee3123e86911ba8029f | bigcode/the-stack | train |
380c11376cbaa1ff695d893a | train | class | @attr.s(auto_attribs=True, kw_only=True)
class PolylineObject(TiledObject):
"""Polyline defined by a set of connections between points.
See:
https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#polyline
Attributes:
points (List[Tuple[int, int]]): List of coordinates relative to \
... | @attr.s(auto_attribs=True, kw_only=True)
class PolylineObject(TiledObject):
| """Polyline defined by a set of connections between points.
See:
https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#polyline
Attributes:
points (List[Tuple[int, int]]): List of coordinates relative to \
the location of the object.
"""
points: List[OrderedPair]
| See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#polygon
Attributes:
points (List[OrderedPair]): FIXME
"""
points: List[OrderedPair]
@attr.s(auto_attribs=True, kw_only=True)
class PolylineObject(TiledObject):
| 64 | 64 | 92 | 21 | 43 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | PolylineObject | PolylineObject | 320 | 332 | 320 | 321 | 29790ed2d54a1a79f5617cb5490e92da19be19a3 | bigcode/the-stack | train |
3d327e377ebb2c27456c128d | train | class | @attr.s(auto_attribs=True)
class TileSet:
"""Object for storing a TSX with all associated collision data.
Args:
name (str): The name of this tileset.
max_tile_size (Size): The maximum size of a tile in this tile set in pixels.
spacing (int): The spacing in pixels between the tiles in th... | @attr.s(auto_attribs=True)
class TileSet:
| """Object for storing a TSX with all associated collision data.
Args:
name (str): The name of this tileset.
max_tile_size (Size): The maximum size of a tile in this tile set in pixels.
spacing (int): The spacing in pixels between the tiles in this \
tileset (applies to the t... | ] = None
draw_order: Optional[str] = "topdown"
@attr.s(auto_attribs=True, kw_only=True)
class LayerGroup(Layer):
"""Layer Group.
A LayerGroup can be thought of as a layer that contains layers
(potentially including other LayerGroups).
Offset and opacity recursively affect child layers.
... | 150 | 150 | 503 | 13 | 136 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | TileSet | TileSet | 420 | 467 | 420 | 421 | 4a3768e9a74408c7a382213ea5b68c636d824034 | bigcode/the-stack | train |
6fd683b900780b8202dd0485 | train | class | @attr.s()
class ElipseObject(TiledObject):
"""Elipse shape defined by a point, width, and height.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#ellipse
"""
| @attr.s()
class ElipseObject(TiledObject):
| """Elipse shape defined by a point, width, and height.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#ellipse
"""
| .
See: https://doc.mapeditor.org/en/stable/manual/objects/#insert-rectangle
(objects in tiled are rectangles by default, so there is no specific
documentation on the tmx-map-format page for it.)
"""
@attr.s()
class ElipseObject(TiledObject):
| 63 | 64 | 49 | 12 | 51 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | ElipseObject | ElipseObject | 278 | 283 | 278 | 279 | 7a7509ce09ab0e2f549c0eaffc85f55d9e936024 | bigcode/the-stack | train |
c22bd0da25ae917c07434ddf | train | class | @attr.s(auto_attribs=True)
class Template:
"""FIXME TODO"""
| @attr.s(auto_attribs=True)
class Template:
| """FIXME TODO"""
| NamedTuple.
Attributes:
width (Union[int, float]): The width of the object.
size (Union[int, float]): The height of the object.
"""
width: Union[int, float]
height: Union[int, float]
@attr.s(auto_attribs=True)
class Template:
| 64 | 64 | 18 | 12 | 52 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Template | Template | 65 | 67 | 65 | 66 | 0364d4ca398f5648d509cad190a272daf729bd80 | bigcode/the-stack | train |
a362341383bc84819cff4331 | train | class | class OrderedPair(NamedTuple):
"""OrderedPair NamedTuple.
Attributes:
x (Union[int, float]): X coordinate.
y (Union[int, float]): Y coordinate.
"""
x: Union[int, float]
y: Union[int, float]
| class OrderedPair(NamedTuple):
| """OrderedPair NamedTuple.
Attributes:
x (Union[int, float]): X coordinate.
y (Union[int, float]): Y coordinate.
"""
x: Union[int, float]
y: Union[int, float]
| between 1 and 255.
blue (int): Blue, between 1 and 255.
alpha (int): Alpha, between 1 and 255.
"""
red: int
green: int
blue: int
alpha: int
class OrderedPair(NamedTuple):
| 64 | 64 | 57 | 7 | 56 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | OrderedPair | OrderedPair | 29 | 38 | 29 | 29 | d710e9e7e98e6ffb8a6e27c93de41d6e03599a5e | bigcode/the-stack | train |
be2c00dc1617a76e772d2ae0 | train | class | class Terrain(NamedTuple):
"""Terrain object.
Args:
name (str): The name of the terrain type.
tile (int): The local tile-id of the tile that represents the terrain visually.
"""
name: str
tile: int
| class Terrain(NamedTuple):
| """Terrain object.
Args:
name (str): The name of the terrain type.
tile (int): The local tile-id of the tile that represents the terrain visually.
"""
name: str
tile: int
| Tuple):
"""Contains info for isometric maps.
This element is only used in case of isometric orientation, and
determines how tile overlays for terrain and collision information
are rendered.
"""
orientation: str
width: int
height: int
class Terrain(NamedTuple):
| 64 | 64 | 56 | 6 | 57 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Terrain | Terrain | 125 | 134 | 125 | 125 | c6de4e29865432679487eca111ea71d8d1e3b3e2 | bigcode/the-stack | train |
95585da4fbc0c8ce6c4afe5c | train | class | class Frame(NamedTuple):
"""Animation Frame object.
This is only used as a part of an animation for Tile objects.
Args:
tile_id (int): The local ID of a tile within the parent tile set
object.
duration (int): How long in milliseconds this frame should be
displayed b... | class Frame(NamedTuple):
| """Animation Frame object.
This is only used as a part of an animation for Tile objects.
Args:
tile_id (int): The local ID of a tile within the parent tile set
object.
duration (int): How long in milliseconds this frame should be
displayed before advancing to the ne... | int
class Terrain(NamedTuple):
"""Terrain object.
Args:
name (str): The name of the terrain type.
tile (int): The local tile-id of the tile that represents the terrain visually.
"""
name: str
tile: int
class Frame(NamedTuple):
| 64 | 64 | 87 | 6 | 57 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Frame | Frame | 137 | 150 | 137 | 137 | 35af0d38706a0a80fe34bc818b9f2a9f531a0a56 | bigcode/the-stack | train |
5bda25d4490d0b26b6e92a8f | train | class | @attr.s(auto_attribs=True, kw_only=True)
class TextObject(TiledObject):
"""Text object with associated settings.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#text
and https://doc.mapeditor.org/en/stable/manual/objects/#insert-text
Attributes:
font_family (str): The fo... | @attr.s(auto_attribs=True, kw_only=True)
class TextObject(TiledObject):
| """Text object with associated settings.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#text
and https://doc.mapeditor.org/en/stable/manual/objects/#insert-text
Attributes:
font_family (str): The font family used (default: "sans-serif")
font_size (int): The size... | (auto_attribs=True, kw_only=True)
class PolylineObject(TiledObject):
"""Polyline defined by a set of connections between points.
See:
https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#polyline
Attributes:
points (List[Tuple[int, int]]): List of coordinates relative to \
... | 109 | 109 | 365 | 20 | 89 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | TextObject | TextObject | 335 | 369 | 335 | 336 | d3f0bae8b5c43ecb926e682bd79b5f869afbdbc9 | bigcode/the-stack | train |
fcd537b5fcf95fe78135235b | train | class | @attr.s(auto_attribs=True, kw_only=True)
class Tile:
"""Individual tile object.
Args:
:id (int): The local tile ID within its tileset.
:type (str): The type of the tile. Refers to an object type and is
used by tile objects.
:terrain (int): Defines the terrain type of each co... | @attr.s(auto_attribs=True, kw_only=True)
class Tile:
| """Individual tile object.
Args:
:id (int): The local tile ID within its tileset.
:type (str): The type of the tile. Refers to an object type and is
used by tile objects.
:terrain (int): Defines the terrain type of each corner of the tile.
:animation (List[Frame]): E... | Optional[List[Terrain]] = None
tiles: Optional[Dict[int, "Tile"]] = None
tsx_file: Path = None
parent_dir: Path = None
TileSetDict = Dict[int, TileSet]
@attr.s(auto_attribs=True, kw_only=True)
class Tile:
| 65 | 65 | 219 | 16 | 49 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Tile | Tile | 473 | 496 | 473 | 474 | 7fc278f4630013b56d781a7b2f823699dc918d31 | bigcode/the-stack | train |
6170cc998c6eb7b9d691759c | train | class | class Grid(NamedTuple):
"""Contains info for isometric maps.
This element is only used in case of isometric orientation, and
determines how tile overlays for terrain and collision information
are rendered.
"""
orientation: str
width: int
height: int
| class Grid(NamedTuple):
| """Contains info for isometric maps.
This element is only used in case of isometric orientation, and
determines how tile overlays for terrain and collision information
are rendered.
"""
orientation: str
width: int
height: int
| ).
height (Optional[str]): The image height in pixels (optional).
"""
source: str
size: Optional[Size] = None
trans: Optional[str] = None
Properties = Dict[str, Union[int, float, Color, Path, str]]
class Grid(NamedTuple):
| 63 | 64 | 62 | 6 | 57 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Grid | Grid | 112 | 122 | 112 | 112 | f953e8608d6fe00804d6600e37c45690441320a4 | bigcode/the-stack | train |
dff8a5ec9f726a314088cb98 | train | class | @attr.s(auto_attribs=True)
class TileMap:
"""Object for storing a TMX with all associated layers and properties.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#map
Attributes:
:parent_dir (Path): The directory the TMX file is in. Used for finding
relative paths to T... | @attr.s(auto_attribs=True)
class TileMap:
| """Object for storing a TMX with all associated layers and properties.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#map
Attributes:
:parent_dir (Path): The directory the TMX file is in. Used for finding
relative paths to TSX files and other assets.
:versio... | type of the tile. Refers to an object type and is
used by tile objects.
:terrain (int): Defines the terrain type of each corner of the tile.
:animation (List[Frame]): Each tile can have exactly one animation
associated with it.
"""
id_: int
type_: Optional[str] = No... | 185 | 185 | 618 | 13 | 171 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | TileMap | TileMap | 499 | 558 | 499 | 500 | ff0d7bb15bf28c184adef756f6f51de024548890 | bigcode/the-stack | train |
16fbd8f24fff912323fe364b | train | class | @attr.s(auto_attribs=True)
class Image:
"""
Image object.
This module does not support embedded data in image elements.
Attributes:
source (Optional[str]): The reference to the tileset image file. Note that this is a relative path compared to FIXME
trans (Optional[Color]): Defines a sp... | @attr.s(auto_attribs=True)
class Image:
| """
Image object.
This module does not support embedded data in image elements.
Attributes:
source (Optional[str]): The reference to the tileset image file. Note that this is a relative path compared to FIXME
trans (Optional[Color]): Defines a specific color that is treated as transpar... | of the chunk in tiles.
layer_data (List[List(int)]): The global tile IDs in chunky according to row.
"""
location: OrderedPair
width: int
height: int
chunk_data: List[List[int]]
@attr.s(auto_attribs=True)
class Image:
| 63 | 64 | 140 | 12 | 51 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Image | Image | 90 | 106 | 90 | 91 | c7d63c8b1111cd6022fed4239e6a9d6036d7b7bb | bigcode/the-stack | train |
9eb61a8a0684eca4261729e9 | train | class | @attr.s(auto_attribs=True, kw_only=True)
class TiledObject:
"""TiledObject object.
See:
https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#object
Args:
id (int): Unique ID of the object. Each object that is placed on a \
map gets a unique id. Even if an object was del... | @attr.s(auto_attribs=True, kw_only=True)
class TiledObject:
| """TiledObject object.
See:
https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#object
Args:
id (int): Unique ID of the object. Each object that is placed on a \
map gets a unique id. Even if an object was deleted, no object \
gets the same ID.
gid (... | :
size: The width of the layer in tiles. The same as the map width
unless map is infitite.
data: Either an 2 dimensional array of integers representing the
global tile IDs for the map layer, or a list of chunks for an
infinite map.
"""
size: Size
data: La... | 93 | 93 | 312 | 18 | 74 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | TiledObject | TiledObject | 231 | 265 | 231 | 232 | bb43b09223706ce6b68975340c4b6fe370a4a036 | bigcode/the-stack | train |
ca3b350241e912e7a0c22de1 | train | class | @attr.s(auto_attribs=True, kw_only=True)
class Layer:
"""
Class that all layers inherit from.
Args:
id: Unique ID of the layer. Each layer that added to a map gets a \
unique id. Even if a layer is deleted, no layer ever gets the same \
ID.
name: The name of the laye... | @attr.s(auto_attribs=True, kw_only=True)
class Layer:
| """
Class that all layers inherit from.
Args:
id: Unique ID of the layer. Each layer that added to a map gets a \
unique id. Even if a layer is deleted, no layer ever gets the same \
ID.
name: The name of the layer object.
tiled_objects: List of tiled_objects... | Optional[int]): Bottom left terrain type.
bottom_right (Optional[int]): Bottom right terrain type.
"""
top_left: Optional[int] = None
top_right: Optional[int] = None
bottom_left: Optional[int] = None
bottom_right: Optional[int] = None
@attr.s(auto_attribs=True, kw_only=True)
class Layer:
| 78 | 78 | 260 | 16 | 61 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Layer | Layer | 173 | 202 | 173 | 174 | ab9923f18762ed8f7b7b524597200e9d3f4b1cfd | bigcode/the-stack | train |
72866b34f0bbe37f0bad5c16 | train | class | @attr.s(auto_attribs=True, kw_only=True)
class TileLayer(Layer):
"""Tile map layer containing tiles.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#layer
Args:
size: The width of the layer in tiles. The same as the map width
unless map is infitite.
data: Eit... | @attr.s(auto_attribs=True, kw_only=True)
class TileLayer(Layer):
| """Tile map layer containing tiles.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#layer
Args:
size: The width of the layer in tiles. The same as the map width
unless map is infitite.
data: Either an 2 dimensional array of integers representing the
... | ]], List[Chunk]]
"""The tile data for one layer.
Either a 2 dimensional array of integers representing the global tile IDs
for a map layer, or a lists of chunks for an infinite map layer.
"""
@attr.s(auto_attribs=True, kw_only=True)
class TileLayer(Layer):
| 64 | 64 | 124 | 19 | 45 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | TileLayer | TileLayer | 213 | 228 | 213 | 214 | 77d2768f1089c4e791be422966441e2aa7f78f6b | bigcode/the-stack | train |
b87d0eee123c85f53a4740b8 | train | class | @attr.s()
class PointObject(TiledObject):
"""Point defined by a point (x,y).
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#point
"""
| @attr.s()
class PointObject(TiledObject):
| """Point defined by a point (x,y).
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#point
"""
| """
@attr.s()
class ElipseObject(TiledObject):
"""Elipse shape defined by a point, width, and height.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#ellipse
"""
@attr.s()
class PointObject(TiledObject):
| 63 | 64 | 44 | 11 | 52 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | PointObject | PointObject | 286 | 291 | 286 | 287 | b5042d6c2d3d321b8c0d8a062b3b3ac3ae64a199 | bigcode/the-stack | train |
26a3c4dbf5080613beec99ea | train | class | @attr.s(auto_attribs=True)
class TileTerrain:
"""Defines each corner of a tile by Terrain index in
'TileSet.terrain_types'.
Defaults to 'None'. 'None' means that corner has no terrain.
Attributes:
top_left (Optional[int]): Top left terrain type.
top_right (Optional[int]): Top right... | @attr.s(auto_attribs=True)
class TileTerrain:
| """Defines each corner of a tile by Terrain index in
'TileSet.terrain_types'.
Defaults to 'None'. 'None' means that corner has no terrain.
Attributes:
top_left (Optional[int]): Top left terrain type.
top_right (Optional[int]): Top right terrain type.
bottom_left (Optional[i... | The local ID of a tile within the parent tile set
object.
duration (int): How long in milliseconds this frame should be
displayed before advancing to the next frame.
"""
tile_id: int
duration: int
@attr.s(auto_attribs=True)
class TileTerrain:
| 64 | 64 | 143 | 13 | 50 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | TileTerrain | TileTerrain | 153 | 170 | 153 | 154 | d83bfac74110784b21e3f9c14c687a52f4099a58 | bigcode/the-stack | train |
a8fbfdbc644d31792fd211b6 | train | class | @attr.s(auto_attribs=True, kw_only=True)
class PolygonObject(TiledObject):
"""Polygon shape defined by a set of connections between points.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#polygon
Attributes:
points (List[OrderedPair]): FIXME
"""
points: List[OrderedPair... | @attr.s(auto_attribs=True, kw_only=True)
class PolygonObject(TiledObject):
| """Polygon shape defined by a set of connections between points.
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#polygon
Attributes:
points (List[OrderedPair]): FIXME
"""
points: List[OrderedPair]
| See: https://doc.mapeditor.org/en/stable/manual/objects/#insert-tile
Attributes:
gid (int): Refference to a global tile id.
"""
gid: int
@attr.s(auto_attribs=True, kw_only=True)
class PolygonObject(TiledObject):
| 64 | 64 | 76 | 20 | 43 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | PolygonObject | PolygonObject | 307 | 317 | 307 | 308 | 65f3d3ecd7292480a38fad86107e23edc875a144 | bigcode/the-stack | train |
93006a1573115d740f7604e0 | train | class | @attr.s(auto_attribs=True, kw_only=True)
class TileImageObject(TiledObject):
"""Polygon shape defined by a set of connections between points.
See: https://doc.mapeditor.org/en/stable/manual/objects/#insert-tile
Attributes:
gid (int): Refference to a global tile id.
"""
gid: int
| @attr.s(auto_attribs=True, kw_only=True)
class TileImageObject(TiledObject):
| """Polygon shape defined by a set of connections between points.
See: https://doc.mapeditor.org/en/stable/manual/objects/#insert-tile
Attributes:
gid (int): Refference to a global tile id.
"""
gid: int
| .s()
class PointObject(TiledObject):
"""Point defined by a point (x,y).
See: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#point
"""
@attr.s(auto_attribs=True, kw_only=True)
class TileImageObject(TiledObject):
| 63 | 64 | 78 | 21 | 42 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | TileImageObject | TileImageObject | 294 | 304 | 294 | 295 | 792e6bb10200432e65f0685e3945ab66122cec1f | bigcode/the-stack | train |
449813e5032ca7e67f30d76d | train | class | class Size(NamedTuple):
"""Size NamedTuple.
Attributes:
width (Union[int, float]): The width of the object.
size (Union[int, float]): The height of the object.
"""
width: Union[int, float]
height: Union[int, float]
| class Size(NamedTuple):
| """Size NamedTuple.
Attributes:
width (Union[int, float]): The width of the object.
size (Union[int, float]): The height of the object.
"""
width: Union[int, float]
height: Union[int, float]
| : Union[int, float]
y: Union[int, float]
class Property(NamedTuple):
"""OrderedPair NamedTuple.
Attributes:
name str: Name of property
value str: Value of property
"""
name: str
value: str
class Size(NamedTuple):
| 64 | 64 | 61 | 6 | 57 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | Size | Size | 53 | 62 | 53 | 53 | 044cb76374f1714436a8787d108ed49ad35bf285 | bigcode/the-stack | train |
1c99bf2e088ede7db316fc7e | train | class | @attr.s(auto_attribs=True, kw_only=True)
class ObjectLayer(Layer):
"""
TiledObject Group Object.
The object group is in fact a map layer, and is hence called \
"object layer" in Tiled.
See:
https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#objectgroup
Args:
tiled_objec... | @attr.s(auto_attribs=True, kw_only=True)
class ObjectLayer(Layer):
| """
TiledObject Group Object.
The object group is in fact a map layer, and is hence called \
"object layer" in Tiled.
See:
https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#objectgroup
Args:
tiled_objects: List of tiled_objects in the layer.
offset: Rendering o... | italic: bool = False
underline: bool = False
strike_out: bool = False
kerning: bool = False
horizontal_align: str = "left"
vertical_align: str = "top"
@attr.s(auto_attribs=True, kw_only=True)
class ObjectLayer(Layer):
| 67 | 67 | 225 | 19 | 48 | AberDerBart/pytiled_parser | pytiled_parser/objects.py | Python | ObjectLayer | ObjectLayer | 372 | 398 | 372 | 373 | 6912a0f4fcc71dccbe972b33da69658a69d6daab | bigcode/the-stack | train |
1b3b09a21a2c8b481006e72c | train | class | class FunctionFilter(ColumnElement):
"""Represent a function FILTER clause.
This is a special operator against aggregate and window functions,
which controls which rows are passed to it.
It's supported only by certain database backends.
Invocation of :class:`.FunctionFilter` is via
:meth:`.Fun... | class FunctionFilter(ColumnElement):
| """Represent a function FILTER clause.
This is a special operator against aggregate and window functions,
which controls which rows are passed to it.
It's supported only by certain database backends.
Invocation of :class:`.FunctionFilter` is via
:meth:`.FunctionElement.filter`::
func.... | """
return Over(
self, partition_by=partition_by, order_by=order_by,
range_=range_, rows=rows)
@util.memoized_property
def type(self):
wgt = self.element.within_group_type(self)
if wgt is not None:
return wgt
else:
return self.ele... | 209 | 210 | 700 | 6 | 203 | gujun4990/sqlalchemy | lib/sqlalchemy/sql/elements.py | Python | FunctionFilter | FunctionFilter | 3,427 | 3,540 | 3,427 | 3,427 | 4713df0caa13aadd565f3c3a79f67c12aaa2164a | bigcode/the-stack | train |
3337c58fe8fd26e2bbfd28b2 | train | class | class UnaryExpression(ColumnElement):
"""Define a 'unary' expression.
A unary expression has a single column expression
and an operator. The operator can be placed on the left
(where it is called the 'operator') or right (where it is called the
'modifier') of the column expression.
:class:`.U... | class UnaryExpression(ColumnElement):
| """Define a 'unary' expression.
A unary expression has a single column expression
and an operator. The operator can be placed on the left
(where it is called the 'operator') or right (where it is called the
'modifier') of the column expression.
:class:`.UnaryExpression` is the basis for sever... | _from_objects(self):
return self.expr._from_objects
class _label_reference(ColumnElement):
"""Wrap a column expression as it appears in a 'reference' context.
This expression is any that includes an _order_by_label_element,
which is a Label, or a DESC / ASC construct wrapping a Label.
The p... | 256 | 256 | 1,903 | 6 | 250 | gujun4990/sqlalchemy | lib/sqlalchemy/sql/elements.py | Python | UnaryExpression | UnaryExpression | 2,570 | 2,851 | 2,570 | 2,570 | 1a842e80b89986a6f0f95c94885fd41363b1f284 | bigcode/the-stack | train |
03395cb03a0ade90c7b267eb | train | class | @inspection._self_inspects
class ClauseElement(Visitable):
"""Base class for elements of a programmatically constructed SQL
expression.
"""
__visit_name__ = 'clause'
_annotations = {}
supports_execution = False
_from_objects = []
bind = None
_is_clone_of = None
is_selectable = ... | @inspection._self_inspects
class ClauseElement(Visitable):
| """Base class for elements of a programmatically constructed SQL
expression.
"""
__visit_name__ = 'clause'
_annotations = {}
supports_execution = False
_from_objects = []
bind = None
_is_clone_of = None
is_selectable = False
is_clause_element = True
description = None
... | API, or is translatable via the given type argument.
:param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` which
will provide bind-parameter translation for this literal.
"""
return BindParameter(None, value, type_=type_, unique=True)
def outparam(key, type_=None):
"""Create an ... | 256 | 256 | 2,505 | 14 | 242 | gujun4990/sqlalchemy | lib/sqlalchemy/sql/elements.py | Python | ClauseElement | ClauseElement | 160 | 497 | 160 | 161 | dc888da3d66dd5de0badc484e4b3de14c9e47b4c | bigcode/the-stack | train |
e8356d388d1f40d67122ba04 | train | class | class RollbackToSavepointClause(_IdentifiedClause):
__visit_name__ = 'rollback_to_savepoint'
| class RollbackToSavepointClause(_IdentifiedClause):
| __visit_name__ = 'rollback_to_savepoint'
| execution_options = \
Executable._execution_options.union({'autocommit': False})
def __init__(self, ident):
self.ident = ident
class SavepointClause(_IdentifiedClause):
__visit_name__ = 'savepoint'
class RollbackToSavepointClause(_IdentifiedClause):
| 64 | 64 | 24 | 12 | 52 | gujun4990/sqlalchemy | lib/sqlalchemy/sql/elements.py | Python | RollbackToSavepointClause | RollbackToSavepointClause | 3,939 | 3,940 | 3,939 | 3,939 | f9874f059601028c53c951fbe2f04389edeb2ae5 | bigcode/the-stack | train |
8db128a0403b1a941575a2fa | train | class | class False_(ColumnElement):
"""Represent the ``false`` keyword, or equivalent, in a SQL statement.
:class:`.False_` is accessed as a constant via the
:func:`.false` function.
"""
__visit_name__ = 'false'
@util.memoized_property
def type(self):
return type_api.BOOLEANTYPE
de... | class False_(ColumnElement):
| """Represent the ``false`` keyword, or equivalent, in a SQL statement.
:class:`.False_` is accessed as a constant via the
:func:`.false` function.
"""
__visit_name__ = 'false'
@util.memoized_property
def type(self):
return type_api.BOOLEANTYPE
def _negate(self):
retu... | ):
"""Represent the NULL keyword in a SQL statement.
:class:`.Null` is accessed as a constant via the
:func:`.null` function.
"""
__visit_name__ = 'null'
@util.memoized_property
def type(self):
return type_api.NULLTYPE
@classmethod
def _instance(cls):
"""Return a... | 113 | 113 | 378 | 6 | 107 | gujun4990/sqlalchemy | lib/sqlalchemy/sql/elements.py | Python | False_ | False_ | 1,688 | 1,744 | 1,688 | 1,688 | 963ad90d76268edd96af6716ca9c640e16de0cc4 | bigcode/the-stack | train |
571e7e17a01779a1df6d14e1 | train | function | def outparam(key, type_=None):
"""Create an 'OUT' parameter for usage in functions (stored procedures),
for databases which support them.
The ``outparam`` can be used like a regular function parameter.
The "output" value will be available from the
:class:`~sqlalchemy.engine.ResultProxy` object via ... | def outparam(key, type_=None):
| """Create an 'OUT' parameter for usage in functions (stored procedures),
for databases which support them.
The ``outparam`` can be used like a regular function parameter.
The "output" value will be available from the
:class:`~sqlalchemy.engine.ResultProxy` object via its ``out_parameters``
attr... | latable via the given type argument.
:param type\_: an optional :class:`~sqlalchemy.types.TypeEngine` which
will provide bind-parameter translation for this literal.
"""
return BindParameter(None, value, type_=type_, unique=True)
def outparam(key, type_=None):
| 64 | 64 | 113 | 9 | 55 | gujun4990/sqlalchemy | lib/sqlalchemy/sql/elements.py | Python | outparam | outparam | 135 | 146 | 135 | 135 | e8d0bddcf2fd5aed881d4f5749a87aab42f0cd2d | bigcode/the-stack | train |
9089efdc8d61f2ce30013941 | train | function | def _type_from_args(args):
for a in args:
if not a.type._isnull:
return a.type
else:
return type_api.NULLTYPE
| def _type_from_args(args):
| for a in args:
if not a.type._isnull:
return a.type
else:
return type_api.NULLTYPE
| return element
elif element is None:
return Null()
elif element is False:
return False_()
elif element is True:
return True_()
else:
raise exc.ArgumentError(
"Expected None, False, or True"
)
def _type_from_args(args):
| 64 | 64 | 37 | 7 | 57 | gujun4990/sqlalchemy | lib/sqlalchemy/sql/elements.py | Python | _type_from_args | _type_from_args | 4,424 | 4,429 | 4,424 | 4,424 | e8d7dd69857ea08e30cfd2ec08ed6822be523ac5 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.