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
bea9322aa8aa483aca32c8fc
train
class
class CrossValidationTest(unittest.TestCase): @classmethod def setUpClass(cls): # Setting up data DATA = load_data("air_passengers.csv") DATA.columns = ["time", "y"] cls.TSData = TimeSeriesData(DATA) # Mock model and params cls.model_class = mock.MagicMock() ...
class CrossValidationTest(unittest.TestCase): @classmethod
def setUpClass(cls): # Setting up data DATA = load_data("air_passengers.csv") DATA.columns = ["time", "y"] cls.TSData = TimeSeriesData(DATA) # Mock model and params cls.model_class = mock.MagicMock() cls.model_params = mock.MagicMock() def test_error_val...
_class.assert_called_with(data=self.train_data, params=model_params) # Training local model and getting predictions temp_model = model_class(data=self.train_data, params=model_params) temp_model.fit() temp_fcst = temp_model.predict(steps=TIMESTEPS * 2, freq=FREQUENCY)[TIMESTEPS:] ...
256
256
2,849
12
244
admariner/Kats
kats/tests/test_backtest.py
Python
CrossValidationTest
CrossValidationTest
626
948
626
627
adcc37ea7c1b3c2dbb3e870aefd748bdd369c782
bigcode/the-stack
train
daef527165458809a6b9a994
train
function
def mse(pred, truth): return ((np.abs(truth - pred)) ** 2).mean()
def mse(pred, truth):
return ((np.abs(truth - pred)) ** 2).mean()
decimal places to round low floats to 0 CV_NUM_FOLDS = 3 # Number of folds for cross validation """ Following are ground truth error functions """ def rmse(pred, truth): return np.sqrt(np.mean((pred - truth) ** 2)) def mse(pred, truth):
64
64
22
6
58
admariner/Kats
kats/tests/test_backtest.py
Python
mse
mse
60
61
60
60
f49d0b087b6b176c4e9efa35ed2dfc0e7f636db5
bigcode/the-stack
train
d07b7a694c551e7f19670bd7
train
function
def rmse(pred, truth): return np.sqrt(np.mean((pred - truth) ** 2))
def rmse(pred, truth):
return np.sqrt(np.mean((pred - truth) ** 2))
25 # Fixed window ahead window percentage FLOAT_ROUNDING_PARAM = 3 # Number of decimal places to round low floats to 0 CV_NUM_FOLDS = 3 # Number of folds for cross validation """ Following are ground truth error functions """ def rmse(pred, truth):
64
64
22
7
57
admariner/Kats
kats/tests/test_backtest.py
Python
rmse
rmse
56
57
56
56
0220df4b3b45ea090b2c3ea290272f3369fefd2d
bigcode/the-stack
train
532c5b1ca81bfc7f78cbafd0
train
function
def mape(pred, truth): return np.mean(np.abs((truth - pred) / truth))
def mape(pred, truth):
return np.mean(np.abs((truth - pred) / truth))
for cross validation """ Following are ground truth error functions """ def rmse(pred, truth): return np.sqrt(np.mean((pred - truth) ** 2)) def mse(pred, truth): return ((np.abs(truth - pred)) ** 2).mean() def mape(pred, truth):
64
64
21
7
57
admariner/Kats
kats/tests/test_backtest.py
Python
mape
mape
64
65
64
64
86888e07cf249e8fdf384d224a09320b82604195
bigcode/the-stack
train
af24bb3449f185bf43ad3f90
train
function
def mase(training_inputs, pred, truth): naive_error = np.abs(np.diff(training_inputs)).sum() / ( training_inputs.shape[0] - 1 ) return ((np.abs(truth - pred)).mean()) / naive_error
def mase(training_inputs, pred, truth):
naive_error = np.abs(np.diff(training_inputs)).sum() / ( training_inputs.shape[0] - 1 ) return ((np.abs(truth - pred)).mean()) / naive_error
) / truth)) def smape(pred, truth): return ((abs(truth - pred) / (truth + pred)).sum()) * (2.0 / truth.size) def mae(pred, truth): return (np.abs(truth - pred)).mean() def mase(training_inputs, pred, truth):
64
64
53
9
55
admariner/Kats
kats/tests/test_backtest.py
Python
mase
mase
76
80
76
76
cc83cec30e7bb52fd31d93acd434f1c1da4cd2f6
bigcode/the-stack
train
57a55397ed12c125af3f5d49
train
function
def smape(pred, truth): return ((abs(truth - pred) / (truth + pred)).sum()) * (2.0 / truth.size)
def smape(pred, truth):
return ((abs(truth - pred) / (truth + pred)).sum()) * (2.0 / truth.size)
return np.sqrt(np.mean((pred - truth) ** 2)) def mse(pred, truth): return ((np.abs(truth - pred)) ** 2).mean() def mape(pred, truth): return np.mean(np.abs((truth - pred) / truth)) def smape(pred, truth):
64
64
33
7
57
admariner/Kats
kats/tests/test_backtest.py
Python
smape
smape
68
69
68
68
adb0f3be3203edc92df100852b74b1ed14e2ba43
bigcode/the-stack
train
72dfb02df7fc3db61c309b45
train
class
class ExpandingWindowBackTesterTest(unittest.TestCase): @classmethod def setUpClass(cls): # Setting up data DATA = load_data("air_passengers.csv") DATA.columns = ["time", "y"] cls.TSData = TimeSeriesData(DATA) cls.train_folds, cls.test_folds = cls.create_folds( ...
class ExpandingWindowBackTesterTest(unittest.TestCase): @classmethod
def setUpClass(cls): # Setting up data DATA = load_data("air_passengers.csv") DATA.columns = ["time", "y"] cls.TSData = TimeSeriesData(DATA) cls.train_folds, cls.test_folds = cls.create_folds( cls, data=DATA, start_train_size=EXPANDING_WIN...
/test split model_class.assert_called_with(data=self.train_data, params=model_params) # Training local model and getting predictions temp_model = model_class(data=self.train_data, params=model_params) temp_model.fit() temp_fcst = temp_model.predict(steps=TIMESTEPS, freq=FREQUENC...
256
256
1,460
15
241
admariner/Kats
kats/tests/test_backtest.py
Python
ExpandingWindowBackTesterTest
ExpandingWindowBackTesterTest
177
363
177
178
7bb528c74c30dc314920d9e525180ba1abd7b4a8
bigcode/the-stack
train
0c8c9c0653a9720cd9e01f57
train
class
class FixedWindowBackTesterTest(unittest.TestCase): @classmethod def setUpClass(cls): # Setting up data DATA = load_data("air_passengers.csv") DATA.columns = ["time", "y"] cls.TSData = TimeSeriesData(DATA) # Creating folds cls.train_data = cls.TSData[: len(cls.TS...
class FixedWindowBackTesterTest(unittest.TestCase): @classmethod
def setUpClass(cls): # Setting up data DATA = load_data("air_passengers.csv") DATA.columns = ["time", "y"] cls.TSData = TimeSeriesData(DATA) # Creating folds cls.train_data = cls.TSData[: len(cls.TSData) - (TIMESTEPS * 2)] cls.test_data = TimeSeriesData(DATA....
self.assertEqual(one_step_folds_rolling, folds_simple) def create_folds( self, data: pd.DataFrame, train_size: float, test_size: float, num_folds: int, ) -> Tuple[List[Tuple[int, int]], List[Tuple[int, int]]]: """ Ground truth fold creation """ ...
193
193
645
14
178
admariner/Kats
kats/tests/test_backtest.py
Python
FixedWindowBackTesterTest
FixedWindowBackTesterTest
549
623
549
550
468d9c645642dd8ae94cf338a745aafd0208d099
bigcode/the-stack
train
7de10c8942f6766b25688c79
train
class
class SimpleBackTesterTest(unittest.TestCase): @classmethod def setUpClass(cls): # Setting up data DATA = load_data("air_passengers.csv") DATA.columns = ["time", "y"] cls.TSData = TimeSeriesData(DATA) cls.train_data = cls.TSData[: len(cls.TSData) - TIMESTEPS] cls....
class SimpleBackTesterTest(unittest.TestCase): @classmethod
def setUpClass(cls): # Setting up data DATA = load_data("air_passengers.csv") DATA.columns = ["time", "y"] cls.TSData = TimeSeriesData(DATA) cls.train_data = cls.TSData[: len(cls.TSData) - TIMESTEPS] cls.test_data = TimeSeriesData(DATA.tail(TIMESTEPS)) def prophe...
)).sum() / ( training_inputs.shape[0] - 1 ) return ((np.abs(truth - pred)).mean()) / naive_error error_funcs = { # Maps error name to function that calculates error "mape": mape, "smape": smape, "mae": mae, "mase": mase, "mse": mse, "rmse": rmse, } def load_data(file_name): ...
181
181
604
13
168
admariner/Kats
kats/tests/test_backtest.py
Python
SimpleBackTesterTest
SimpleBackTesterTest
103
174
103
104
9dc222a3e5bb2453218873e2a8732c2001f9a383
bigcode/the-stack
train
2207d14c10976fe800910d0d
train
function
def mae(pred, truth): return (np.abs(truth - pred)).mean()
def mae(pred, truth):
return (np.abs(truth - pred)).mean()
2).mean() def mape(pred, truth): return np.mean(np.abs((truth - pred) / truth)) def smape(pred, truth): return ((abs(truth - pred) / (truth + pred)).sum()) * (2.0 / truth.size) def mae(pred, truth):
64
64
18
6
58
admariner/Kats
kats/tests/test_backtest.py
Python
mae
mae
72
73
72
72
34d9aafec2a6a01b0503675ab51bb8be3e72c309
bigcode/the-stack
train
d819a3d5033ca0685722afa1
train
function
def load_data(file_name): ROOT = "kats" if "kats" in os.getcwd().lower(): path = "data/" else: path = "kats/data/" data_object = pkgutil.get_data(ROOT, path + file_name) return pd.read_csv(io.BytesIO(data_object), encoding="utf8")
def load_data(file_name):
ROOT = "kats" if "kats" in os.getcwd().lower(): path = "data/" else: path = "kats/data/" data_object = pkgutil.get_data(ROOT, path + file_name) return pd.read_csv(io.BytesIO(data_object), encoding="utf8")
{ # Maps error name to function that calculates error "mape": mape, "smape": smape, "mae": mae, "mase": mase, "mse": mse, "rmse": rmse, } def load_data(file_name):
64
64
73
6
58
admariner/Kats
kats/tests/test_backtest.py
Python
load_data
load_data
93
100
93
93
f4d668cad2cb6da6337af676529019496d491b51
bigcode/the-stack
train
089d367cd0cbf096a31f9dc5
train
class
class RollingWindowBackTesterTest(unittest.TestCase): @classmethod def setUpClass(cls): # Setting up data DATA = load_data("air_passengers.csv") DATA.columns = ["time", "y"] cls.TSData = TimeSeriesData(DATA) cls.train_folds, cls.test_folds = cls.create_folds( ...
class RollingWindowBackTesterTest(unittest.TestCase): @classmethod
def setUpClass(cls): # Setting up data DATA = load_data("air_passengers.csv") DATA.columns = ["time", "y"] cls.TSData = TimeSeriesData(DATA) cls.train_folds, cls.test_folds = cls.create_folds( cls, data=DATA, train_size=ROLLING_WINDOW_TRAI...
=self.model_params, train_percentage=PERCENTAGE, test_percentage=(100 - PERCENTAGE), model_class=self.model_class, ) folds_simple = simple_backtester._create_train_test_splits() # Test that folds are equivalent self.assertEqual(one_step_folds_expandin...
256
256
1,413
14
241
admariner/Kats
kats/tests/test_backtest.py
Python
RollingWindowBackTesterTest
RollingWindowBackTesterTest
366
546
366
367
0f2769c10a930a1acd6a797f0246452b3672520b
bigcode/the-stack
train
89b3cf29e7ced0153d8278cc
train
function
@given("a working mesos cluster") def working_mesos_cluster(context): pass
@given("a working mesos cluster") def working_mesos_cluster(context):
pass
either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import itest_utils import requests from behave import given from behave import then from behave import when @given("a working mesos cluster") def working_mesos_cluster(context)...
64
64
18
15
48
Yelp/Tron
cluster_itests/steps/mesos_steps.py
Python
working_mesos_cluster
working_mesos_cluster
23
25
23
24
edfefc3c8e8fcceb50a1c49a933f6444103217d6
bigcode/the-stack
train
460f6d0aa14b3cab2a900e2a
train
function
def list_active_frameworks(): framework_info = fetch_frameworks_endpoint()["frameworks"] return [f["name"] for f in framework_info]
def list_active_frameworks():
framework_info = fetch_frameworks_endpoint()["frameworks"] return [f["name"] for f in framework_info]
{num:d} seconds") def sleep(context, num): time.sleep(num) @then("we should see {num:d} frameworks") def see_num_frameworks(context, num): frameworks = list_active_frameworks() assert len(frameworks) == num, frameworks def list_active_frameworks():
64
64
31
6
57
Yelp/Tron
cluster_itests/steps/mesos_steps.py
Python
list_active_frameworks
list_active_frameworks
55
57
55
55
0d1aadd38625dbd1118a8b8f1af01ac198ffcee9
bigcode/the-stack
train
5cf79942d1f9fec5cc63fb3b
train
function
@when("we run tronctl {command}") def run_tronctl_command(context, command): full_command = f"tronctl --server http://tronmaster:8089 {command}" exit_code, context.output = itest_utils.run(full_command) print(full_command) print(exit_code) print(context.output) assert exit_code == 0, context.out...
@when("we run tronctl {command}") def run_tronctl_command(context, command):
full_command = f"tronctl --server http://tronmaster:8089 {command}" exit_code, context.output = itest_utils.run(full_command) print(full_command) print(exit_code) print(context.output) assert exit_code == 0, context.output
import time import itest_utils import requests from behave import given from behave import then from behave import when @given("a working mesos cluster") def working_mesos_cluster(context): pass @when("we run tronctl {command}") def run_tronctl_command(context, command):
64
64
80
20
43
Yelp/Tron
cluster_itests/steps/mesos_steps.py
Python
run_tronctl_command
run_tronctl_command
28
35
28
29
8311ea5d31eec1ad2d66eb23864612da5a5b57e1
bigcode/the-stack
train
fc0c9c535786e8cb5436c8c0
train
function
def fetch_frameworks_endpoint(): url = "http://mesosmaster:5050/state/frameworks.json" resp = requests.get(url=url) return resp.json()
def fetch_frameworks_endpoint():
url = "http://mesosmaster:5050/state/frameworks.json" resp = requests.get(url=url) return resp.json()
_num_frameworks(context, num): frameworks = list_active_frameworks() assert len(frameworks) == num, frameworks def list_active_frameworks(): framework_info = fetch_frameworks_endpoint()["frameworks"] return [f["name"] for f in framework_info] def fetch_frameworks_endpoint():
64
64
36
6
58
Yelp/Tron
cluster_itests/steps/mesos_steps.py
Python
fetch_frameworks_endpoint
fetch_frameworks_endpoint
60
63
60
60
319da3fa3fbd3ff4b2f63acae0e223dd0a49985e
bigcode/the-stack
train
29a500f6bc378da0faef66a3
train
function
@then("we should see {num:d} frameworks") def see_num_frameworks(context, num): frameworks = list_active_frameworks() assert len(frameworks) == num, frameworks
@then("we should see {num:d} frameworks") def see_num_frameworks(context, num):
frameworks = list_active_frameworks() assert len(frameworks) == num, frameworks
= list_active_frameworks() assert any(framework_string in f for f in frameworks), frameworks @when("we sleep {num:d} seconds") def sleep(context, num): time.sleep(num) @then("we should see {num:d} frameworks") def see_num_frameworks(context, num):
64
64
41
21
43
Yelp/Tron
cluster_itests/steps/mesos_steps.py
Python
see_num_frameworks
see_num_frameworks
49
52
49
50
483f7bcf9d8c4409a01ffbd5405f68b3f4923753
bigcode/the-stack
train
6ae2bf937c01cfb02567ae51
train
function
@then("we should see {framework_string} in the list of frameworks") def see_framework_in_list(context, framework_string): frameworks = list_active_frameworks() assert any(framework_string in f for f in frameworks), frameworks
@then("we should see {framework_string} in the list of frameworks") def see_framework_in_list(context, framework_string):
frameworks = list_active_frameworks() assert any(framework_string in f for f in frameworks), frameworks
_code, context.output = itest_utils.run(full_command) print(full_command) print(exit_code) print(context.output) assert exit_code == 0, context.output @then("we should see {framework_string} in the list of frameworks") def see_framework_in_list(context, framework_string):
64
64
49
26
37
Yelp/Tron
cluster_itests/steps/mesos_steps.py
Python
see_framework_in_list
see_framework_in_list
38
41
38
39
4aeee383bf7b5de6847d39714ec402bb64ffe764
bigcode/the-stack
train
d07792d8a3241363c7edc147
train
function
@when("we sleep {num:d} seconds") def sleep(context, num): time.sleep(num)
@when("we sleep {num:d} seconds") def sleep(context, num):
time.sleep(num)
("we should see {framework_string} in the list of frameworks") def see_framework_in_list(context, framework_string): frameworks = list_active_frameworks() assert any(framework_string in f for f in frameworks), frameworks @when("we sleep {num:d} seconds") def sleep(context, num):
64
64
22
17
46
Yelp/Tron
cluster_itests/steps/mesos_steps.py
Python
sleep
sleep
44
46
44
45
9477088fe0653fb9d3ea43e3499f0e2ec45e913e
bigcode/the-stack
train
82474b32e922d5dfb33de985
train
function
def run(dataset, config): log.info(f"\n**** H2O AutoML [v{h2o.__version__}] ****\n") # Mapping of benchmark metrics to H2O metrics metrics_mapping = dict( acc='mean_per_class_error', auc='AUC', logloss='logloss', mae='mae', mse='mse', r2='r2', rmse='rm...
def run(dataset, config):
log.info(f"\n**** H2O AutoML [v{h2o.__version__}] ****\n") # Mapping of benchmark metrics to H2O metrics metrics_mapping = dict( acc='mean_per_class_error', auc='AUC', logloss='logloss', mae='mae', mse='mse', r2='r2', rmse='rmse', rmsle='rmsle'...
import logging import os import psutil import re from packaging import version import pandas as pd import h2o from h2o.automl import H2OAutoML from frameworks.shared.callee import FrameworkError, call_run, output_subdir, result from frameworks.shared.utils import Monitoring, Namespace as ns, Timer, clean_dir, touch,...
256
256
1,055
6
250
PGijsbers/automlbenchmark
frameworks/H2OAutoML/exec.py
Python
run
run
33
137
33
33
1c98f8df6d51517173b0d4fa8cd92916a7f9b797
bigcode/the-stack
train
3f384b5f30d4763cc4028097
train
class
class BackendMemoryMonitoring(Monitoring): def __init__(self, name=None, interval_seconds=300, check_on_exit=False, verbosity=0, log_level=logging.INFO): super().__init__(name, interval_seconds, check_on_exit, "backend_monitoring_") self._verbosity = verbosity self._log_lev...
class BackendMemoryMonitoring(Monitoring):
def __init__(self, name=None, interval_seconds=300, check_on_exit=False, verbosity=0, log_level=logging.INFO): super().__init__(name, interval_seconds, check_on_exit, "backend_monitoring_") self._verbosity = verbosity self._log_level = log_level def _check_state(self): ...
automl import H2OAutoML from frameworks.shared.callee import FrameworkError, call_run, output_subdir, result from frameworks.shared.utils import Monitoring, Namespace as ns, Timer, clean_dir, touch, zip_path log = logging.getLogger(__name__) class BackendMemoryMonitoring(Monitoring):
64
64
161
8
56
PGijsbers/automlbenchmark
frameworks/H2OAutoML/exec.py
Python
BackendMemoryMonitoring
BackendMemoryMonitoring
19
30
19
20
161a1d0762c675d13b1d7d5f64fe313221d20c74
bigcode/the-stack
train
d4cd56393293ce24fd40c483
train
function
def save_model(model_id, dest_dir='.', mformat='json'): model = h2o.get_model(model_id) if mformat == 'mojo': return model.save_mojo(path=dest_dir) # model.download_mojo(path=dest_dir, get_genmodel_jar=True) elif mformat == 'binary': return h2o.save_model(model, path=dest_dir) ...
def save_model(model_id, dest_dir='.', mformat='json'):
model = h2o.get_model(model_id) if mformat == 'mojo': return model.save_mojo(path=dest_dir) # model.download_mojo(path=dest_dir, get_genmodel_jar=True) elif mformat == 'binary': return h2o.save_model(model, path=dest_dir) # return h2o.download_model(model, path=dest_dir) ...
p: p != logs_zip) write_csv(automl.event_log.as_data_frame(), os.path.join(logs_dir, 'aml_event_log.csv')) except Exception: log.debug("Error when saving artifacts.", exc_info=True) def save_model(model_id, dest_dir='.', mformat='json'):
64
64
115
15
49
PGijsbers/automlbenchmark
frameworks/H2OAutoML/exec.py
Python
save_model
save_model
215
224
215
215
38dc990095fa4df22c0aa8f953384e7bfa122e1a
bigcode/the-stack
train
ef07f5193fd2027548877cb0
train
function
def to_data_frame(arr, columns=None): return pd.DataFrame.from_records(arr, columns=columns)
def to_data_frame(arr, columns=None):
return pd.DataFrame.from_records(arr, columns=columns)
): df = to_data_frame(preds.probabilities, columns=preds.probabilities_labels) df = df.assign(predictions=preds.predictions) df = df.assign(truth=preds.truth) write_csv(df, path) def to_data_frame(arr, columns=None):
64
64
22
9
55
PGijsbers/automlbenchmark
frameworks/H2OAutoML/exec.py
Python
to_data_frame
to_data_frame
258
259
258
258
111e3420f115caf050d44e917e22c6baa0675b02
bigcode/the-stack
train
5ce190f99decb4c736023cda
train
function
def frame_name(fr_type, config): return '_'.join([fr_type, config.name, str(config.fold)])
def frame_name(fr_type, config):
return '_'.join([fr_type, config.name, str(config.fold)])
finally: con = h2o.connection() if con: # h2o.remove_all() con.close() if con.local_server: con.local_server.shutdown() # if h2o.cluster(): # h2o.cluster().shutdown() def frame_name(fr_type, config):
64
64
24
8
56
PGijsbers/automlbenchmark
frameworks/H2OAutoML/exec.py
Python
frame_name
frame_name
142
143
142
142
777c743f932a92863ca151fa982bed5744e9228e
bigcode/the-stack
train
fa7f49edb3201a7a371bc9bb
train
function
def write_preds(preds, path): df = to_data_frame(preds.probabilities, columns=preds.probabilities_labels) df = df.assign(predictions=preds.predictions) df = df.assign(truth=preds.truth) write_csv(df, path)
def write_preds(preds, path):
df = to_data_frame(preds.probabilities, columns=preds.probabilities_labels) df = df.assign(predictions=preds.predictions) df = df.assign(truth=preds.truth) write_csv(df, path)
the labels to avoid mismatch prob_labels = None truth = y_truth.values return ns(predictions=predictions, truth=truth, probabilities=probabilities, probabilities_labels=prob_labels, h2o_labels=h2o_labels) def write_preds(preds, path):
64
64
62
8
56
PGijsbers/automlbenchmark
frameworks/H2OAutoML/exec.py
Python
write_preds
write_preds
251
255
251
251
b4de8697ab723b1adb5fdceda8e04fae07237ddf
bigcode/the-stack
train
631553442007416824538dd8
train
function
def write_csv(df, path): touch(path) df.to_csv(path, header=True, index=False)
def write_csv(df, path):
touch(path) df.to_csv(path, header=True, index=False)
_labels) df = df.assign(predictions=preds.predictions) df = df.assign(truth=preds.truth) write_csv(df, path) def to_data_frame(arr, columns=None): return pd.DataFrame.from_records(arr, columns=columns) def write_csv(df, path):
64
64
23
7
57
PGijsbers/automlbenchmark
frameworks/H2OAutoML/exec.py
Python
write_csv
write_csv
262
264
262
262
27a31c5a8341ecc2dc16dab83583eb535cb127ca
bigcode/the-stack
train
f1951415520b084a871fa00f
train
function
def extract_preds(h2o_preds, test, dataset, ): h2o_preds = h2o_preds.as_data_frame(use_pandas=False) preds = to_data_frame(h2o_preds[1:], columns=h2o_preds[0]) y_pred = preds.iloc[:, 0] h2o_truth = test[:, dataset.target.index].as_data_frame(use_pandas=False, header=False) y_truth = to_data_frame(h...
def extract_preds(h2o_preds, test, dataset, ):
h2o_preds = h2o_preds.as_data_frame(use_pandas=False) preds = to_data_frame(h2o_preds[1:], columns=h2o_preds[0]) y_pred = preds.iloc[:, 0] h2o_truth = test[:, dataset.target.index].as_data_frame(use_pandas=False, header=False) y_truth = to_data_frame(h2o_truth) predictions = y_pred.values ...
, get_genmodel_jar=True) elif mformat == 'binary': return h2o.save_model(model, path=dest_dir) # return h2o.download_model(model, path=dest_dir) else: return model.save_model_details(path=dest_dir) def extract_preds(h2o_preds, test, dataset, ):
72
72
242
13
59
PGijsbers/automlbenchmark
frameworks/H2OAutoML/exec.py
Python
extract_preds
extract_preds
227
248
227
227
619d28c1c1cf131d8a1a73ca6406a985c1188be2
bigcode/the-stack
train
8f61fc26219a4c2d5a0852c9
train
function
def save_artifacts(automl, dataset, config): artifacts = config.framework_params.get('_save_artifacts', ['leaderboard']) try: models_artifacts = [] lb_pat = re.compile(r"leaderboard(?:\[(.*)\])?") lb_match = next((lb_pat.fullmatch(a) for a in artifacts), None) if lb_match: ...
def save_artifacts(automl, dataset, config):
artifacts = config.framework_params.get('_save_artifacts', ['leaderboard']) try: models_artifacts = [] lb_pat = re.compile(r"leaderboard(?:\[(.*)\])?") lb_match = next((lb_pat.fullmatch(a) for a in artifacts), None) if lb_match: lb_ext = list(filter(None, re.split("[,...
_frame=train) if not aml.leader: raise FrameworkError("H2O could not produce any model in the requested time.") with Timer() as predict: preds = aml.predict(test) preds = extract_preds(preds, test, dataset=dataset) save_artifacts(aml, dataset=dataset, config=co...
236
237
793
12
224
PGijsbers/automlbenchmark
frameworks/H2OAutoML/exec.py
Python
save_artifacts
save_artifacts
146
212
146
146
5b37428d666aa4cbd88f86e9162e1561d48950dc
bigcode/the-stack
train
a58a8bbef24fe2492eef8118
train
class
class TestNfsSettingsGlobal(unittest.TestCase): """NfsSettingsGlobal unit test stubs""" def setUp(self): pass def tearDown(self): pass def testNfsSettingsGlobal(self): """Test NfsSettingsGlobal""" # FIXME: construct object with mandatory attributes with example values ...
class TestNfsSettingsGlobal(unittest.TestCase):
"""NfsSettingsGlobal unit test stubs""" def setUp(self): pass def tearDown(self): pass def testNfsSettingsGlobal(self): """Test NfsSettingsGlobal""" # FIXME: construct object with mandatory attributes with example values # model = isi_sdk_8_2_2.models.nfs_setti...
import unittest import isi_sdk_8_2_2 from isi_sdk_8_2_2.models.nfs_settings_global import NfsSettingsGlobal # noqa: E501 from isi_sdk_8_2_2.rest import ApiException class TestNfsSettingsGlobal(unittest.TestCase):
64
64
101
10
53
mohitjain97/isilon_sdk_python
isi_sdk_8_2_2/test/test_nfs_settings_global.py
Python
TestNfsSettingsGlobal
TestNfsSettingsGlobal
23
36
23
23
98578f1edb2ec4829c58c8be72d70cea80aaf974
bigcode/the-stack
train
34c62877d341e0085476ede4
train
function
def osd_prepare(**kwargs): mdl = model.model(**kwargs) update_model(mdl) osdc = osd_ctrl(mdl) return osdc.prepare(**kwargs)
def osd_prepare(**kwargs):
mdl = model.model(**kwargs) update_model(mdl) osdc = osd_ctrl(mdl) return osdc.prepare(**kwargs)
def update_model(mdl): # Utility function to update model for osd_ctrl u = mdl_updater.model_updater(mdl) u.symlinks_refresh() u.defaults_refresh() u.partitions_all_refresh() u.discover_partitions_refresh() def osd_prepare(**kwargs):
64
64
39
7
57
x22x22/python-ceph-cfg
ceph_cfg/osd.py
Python
osd_prepare
osd_prepare
323
327
323
323
a15026334d15e3ab81c6c6ed32179ebb0454ded6
bigcode/the-stack
train
f740758bbb5e66d98632a8db
train
class
class osd_ctrl(object): def __init__(self, mdl): self.model = mdl self.model.init = "systemd" def _get_dev_name(self, path): """ get device name from path. e.g.:: /dev/sda -> sdas, /dev/cciss/c0d1 -> cciss!c0d1 a device "name" is something like:: ...
class osd_ctrl(object):
def __init__(self, mdl): self.model = mdl self.model.init = "systemd" def _get_dev_name(self, path): """ get device name from path. e.g.:: /dev/sda -> sdas, /dev/cciss/c0d1 -> cciss!c0d1 a device "name" is something like:: sdb cci...
# Import Python Libs from __future__ import absolute_import import logging import os import stat # Local imports from . import utils from . import keyring from . import constants from . import model from . import mdl_updater from . import util_which log = logging.getLogger(__name__) class Error(Exception): """...
122
256
2,289
6
116
x22x22/python-ceph-cfg
ceph_cfg/osd.py
Python
osd_ctrl
osd_ctrl
29
311
29
29
da21aa3636e825b5a32b28cab86c9c86c9d53807
bigcode/the-stack
train
f16d86ff00df70532aae9804
train
class
class Error(Exception): """ Error """ def __str__(self): doc = self.__doc__.strip() return ': '.join([doc] + [str(a) for a in self.args])
class Error(Exception):
""" Error """ def __str__(self): doc = self.__doc__.strip() return ': '.join([doc] + [str(a) for a in self.args])
import absolute_import import logging import os import stat # Local imports from . import utils from . import keyring from . import constants from . import model from . import mdl_updater from . import util_which log = logging.getLogger(__name__) class Error(Exception):
64
64
46
4
60
x22x22/python-ceph-cfg
ceph_cfg/osd.py
Python
Error
Error
19
26
19
19
75a2587602ff3a5a32cf13e451ca281933006d1c
bigcode/the-stack
train
00d6be1248fd268fc53e6c4e
train
function
def osd_activate(**kwargs): mdl = model.model(**kwargs) update_model(mdl) osdc = osd_ctrl(mdl) return osdc.activate_targets(**kwargs)
def osd_activate(**kwargs):
mdl = model.model(**kwargs) update_model(mdl) osdc = osd_ctrl(mdl) return osdc.activate_targets(**kwargs)
.defaults_refresh() u.partitions_all_refresh() u.discover_partitions_refresh() def osd_prepare(**kwargs): mdl = model.model(**kwargs) update_model(mdl) osdc = osd_ctrl(mdl) return osdc.prepare(**kwargs) def osd_activate(**kwargs):
64
64
40
7
57
x22x22/python-ceph-cfg
ceph_cfg/osd.py
Python
osd_activate
osd_activate
330
334
330
330
99201898eeca34d04b18eb836884e5a2a467da61
bigcode/the-stack
train
9e8c3063ee82923cc7a8642c
train
function
def update_model(mdl): # Utility function to update model for osd_ctrl u = mdl_updater.model_updater(mdl) u.symlinks_refresh() u.defaults_refresh() u.partitions_all_refresh() u.discover_partitions_refresh()
def update_model(mdl): # Utility function to update model for osd_ctrl
u = mdl_updater.model_updater(mdl) u.symlinks_refresh() u.defaults_refresh() u.partitions_all_refresh() u.discover_partitions_refresh()
executing '%s' Error rc=%s, stdout=%s stderr=%s" % ( " ".join(arguments), output["retcode"], output["stdout"], output["stderr"]) ) return True def update_model(mdl): # Utility function to update model for os...
64
64
57
18
45
x22x22/python-ceph-cfg
ceph_cfg/osd.py
Python
update_model
update_model
314
320
314
315
c149ebc2f5f47b99bb42fa580efe0c16d2fda7f8
bigcode/the-stack
train
4bd7eac2551f06b37a2af5fc
train
class
class PamConv(Structure): ''' Wrapper class for pam_conv structure ''' _fields_ = [ ('conv', CONV_FUNC), ('appdata_ptr', c_void_p) ]
class PamConv(Structure):
''' Wrapper class for pam_conv structure ''' _fields_ = [ ('conv', CONV_FUNC), ('appdata_ptr', c_void_p) ]
): return "<PamResponse %i '%s'>" % (self.resp_retcode, self.resp) CONV_FUNC = CFUNCTYPE(c_int, c_int, POINTER(POINTER(PamMessage)), POINTER(POINTER(PamResponse)), c_void_p) class PamConv(Structure):
64
64
44
6
58
epoelke/salt
salt/auth/pam.py
Python
PamConv
PamConv
82
89
82
82
979a4955d79373af5a49d3d95011b76222075bb5
bigcode/the-stack
train
441810a56a14356a74c60cab
train
class
class PamHandle(Structure): ''' Wrapper class for pam_handle_t ''' _fields_ = [ ('handle', c_void_p) ] def __init__(self): Structure.__init__(self) self.handle = 0
class PamHandle(Structure):
''' Wrapper class for pam_handle_t ''' _fields_ = [ ('handle', c_void_p) ] def __init__(self): Structure.__init__(self) self.handle = 0
UP.restype = POINTER(c_char) # NOT c_char_p !!!! # Various constants PAM_PROMPT_ECHO_OFF = 1 PAM_PROMPT_ECHO_ON = 2 PAM_ERROR_MSG = 3 PAM_TEXT_INFO = 4 class PamHandle(Structure):
64
64
55
6
57
epoelke/salt
salt/auth/pam.py
Python
PamHandle
PamHandle
38
48
38
38
abdbe57041149a0025b9ac121ecdafa42df32b03
bigcode/the-stack
train
e21e78c636767c97e35ee58a
train
function
def authenticate(username, password, service='login'): ''' Returns True if the given username and password authenticate for the given service. Returns False otherwise ``username``: the username to authenticate ``password``: the password in plain text ``service``: the PAM service to authentic...
def authenticate(username, password, service='login'):
''' Returns True if the given username and password authenticate for the given service. Returns False otherwise ``username``: the username to authenticate ``password``: the password in plain text ``service``: the PAM service to authenticate against. Defaults to 'login' '...
_authenticate PAM_AUTHENTICATE.restype = c_int PAM_AUTHENTICATE.argtypes = [PamHandle, c_int] except Exception: HAS_PAM = False else: HAS_PAM = True def __virtual__(): ''' Only load on Linux systems ''' if HAS_PAM: return 'pam' else: return False def authenticate(us...
94
94
314
10
83
epoelke/salt
salt/auth/pam.py
Python
authenticate
authenticate
117
155
117
117
11ae0711c80230810b15ab529b4cd4113d24a339
bigcode/the-stack
train
e57a2a2fc3c46388ea4a0dc0
train
class
class PamResponse(Structure): ''' Wrapper class for pam_response structure ''' _fields_ = [ ('resp', c_char_p), ('resp_retcode', c_int), ] def __repr__(self): return "<PamResponse %i '%s'>" % (self.resp_retcode, self.resp)
class PamResponse(Structure):
''' Wrapper class for pam_response structure ''' _fields_ = [ ('resp', c_char_p), ('resp_retcode', c_int), ] def __repr__(self): return "<PamResponse %i '%s'>" % (self.resp_retcode, self.resp)
class for pam_message structure ''' _fields_ = [ ("msg_style", c_int), ("msg", c_char_p), ] def __repr__(self): return "<PamMessage %i '%s'>" % (self.msg_style, self.msg) class PamResponse(Structure):
64
64
72
6
58
epoelke/salt
salt/auth/pam.py
Python
PamResponse
PamResponse
64
74
64
64
8c319e2141a32e8adad9f911ad0bb54e08c2ef99
bigcode/the-stack
train
94887da8895ac2a4cf0e0004
train
class
class PamMessage(Structure): ''' Wrapper class for pam_message structure ''' _fields_ = [ ("msg_style", c_int), ("msg", c_char_p), ] def __repr__(self): return "<PamMessage %i '%s'>" % (self.msg_style, self.msg)
class PamMessage(Structure):
''' Wrapper class for pam_message structure ''' _fields_ = [ ("msg_style", c_int), ("msg", c_char_p), ] def __repr__(self): return "<PamMessage %i '%s'>" % (self.msg_style, self.msg)
4 class PamHandle(Structure): ''' Wrapper class for pam_handle_t ''' _fields_ = [ ('handle', c_void_p) ] def __init__(self): Structure.__init__(self) self.handle = 0 class PamMessage(Structure):
64
64
68
6
57
epoelke/salt
salt/auth/pam.py
Python
PamMessage
PamMessage
51
61
51
51
1e411188c8dd5178052d36535ec26b51191786fb
bigcode/the-stack
train
583cbcda5d087679c6668585
train
function
def __virtual__(): ''' Only load on Linux systems ''' if HAS_PAM: return 'pam' else: return False
def __virtual__():
''' Only load on Linux systems ''' if HAS_PAM: return 'pam' else: return False
ENTICATE = LIBPAM.pam_authenticate PAM_AUTHENTICATE.restype = c_int PAM_AUTHENTICATE.argtypes = [PamHandle, c_int] except Exception: HAS_PAM = False else: HAS_PAM = True def __virtual__():
64
64
34
5
58
epoelke/salt
salt/auth/pam.py
Python
__virtual__
__virtual__
107
114
107
107
4a4f06b65ddb767caefb17e80ddc549d9140e1e5
bigcode/the-stack
train
8992c360756bf9519229161f
train
function
def auth(username, password, **kwargs): ''' Authenticate via pam ''' return authenticate(username, password, kwargs.get('service', 'login'))
def auth(username, password, **kwargs):
''' Authenticate via pam ''' return authenticate(username, password, kwargs.get('service', 'login'))
(handle)) if retval != 0: # TODO: This is not an authentication error, something # has gone wrong starting up PAM return False retval = PAM_AUTHENTICATE(handle, 0) return retval == 0 def auth(username, password, **kwargs):
64
64
33
9
54
epoelke/salt
salt/auth/pam.py
Python
auth
auth
158
162
158
158
6533af3490acf2056007b31855cbb521dbb683d3
bigcode/the-stack
train
8dab46f89becc97d94a2aef9
train
class
class delPermission(Handler): """Delete permission method class.""" def control(self): """Validate inputs after method setup. :return: None :rtype: None """ self.is_valid(self.admin_username, str) self.is_valid(self.perm_name, str) def setup(self, admin_use...
class delPermission(Handler):
"""Delete permission method class.""" def control(self): """Validate inputs after method setup. :return: None :rtype: None """ self.is_valid(self.admin_username, str) self.is_valid(self.perm_name, str) def setup(self, admin_username, perm_name): """...
"""Delete permission API method.""" from ibsng.handler.handler import Handler class delPermission(Handler):
21
64
129
6
14
ParspooyeshFanavar/pyibsng
ibsng/handler/perm/del_permission.py
Python
delPermission
delPermission
5
27
5
5
1feb8e40a06e9e1661f297e30e8f05bf212c2178
bigcode/the-stack
train
397b97a53c1d2a33340779fc
train
class
@pytest.mark.django_db class TestEventCopy: def assert_dates(self, event, occurrences, volunteers, planners): for shift_date in occurrences: shift = Shift.objects.get(start_time__date=shift_date) assert shift.event.title == event.title assert shift.event.get_start_time() ...
@pytest.mark.django_db class TestEventCopy:
def assert_dates(self, event, occurrences, volunteers, planners): for shift_date in occurrences: shift = Shift.objects.get(start_time__date=shift_date) assert shift.event.title == event.title assert shift.event.get_start_time() == shift.start_time assert shift...
from datetime import datetime, timedelta import pytest import recurrence from django.urls import reverse from guardian.shortcuts import assign_perm from ephios.core.models import Event, Shift from ephios.extra.permissions import get_groups_with_perms @pytest.mark.django_db class TestEventCopy:
59
256
1,347
11
47
garinm90/ephios
tests/core/test_event_copy.py
Python
TestEventCopy
TestEventCopy
12
137
12
13
680c3d2b57b3c28909788957dff88137cfeb6908
bigcode/the-stack
train
9a9434a94ee9ddb9ec8860ca
train
function
def train( model: GraphTaskModel, dataset: GraphDataset, log_fun: Callable[[str], None], run_id: str, max_epochs: int, patience: int, save_dir: str, quiet: bool = False, aml_run=None, ): train_data = dataset.get_tensorflow_dataset(DataFold.TRAIN).prefetch(3) valid_data = data...
def train( model: GraphTaskModel, dataset: GraphDataset, log_fun: Callable[[str], None], run_id: str, max_epochs: int, patience: int, save_dir: str, quiet: bool = False, aml_run=None, ):
train_data = dataset.get_tensorflow_dataset(DataFold.TRAIN).prefetch(3) valid_data = dataset.get_tensorflow_dataset(DataFold.VALIDATION).prefetch(3) save_file = os.path.join(save_dir, f"{run_id}_best.pkl") best_model = model best_valid_avg_loss, _, initial_valid_results = model.run_one_epoch(valid...
from ..data import DataFold, GraphDataset from ..layers import get_known_message_passing_classes from ..models import GraphTaskModel from .model_utils import save_model, load_weights_verbosely, get_model_and_dataset from .task_utils import get_known_tasks def make_run_id(model_name: str, task_name: str, run_name: O...
256
256
1,193
62
194
TrungQuocNguyen/tf2-gnn
tf2_gnn/cli_utils/training_utils.py
Python
train
train
37
159
37
47
02e6d45614305a67b66204d34541941166b40c74
bigcode/the-stack
train
40ae83c3f8915c5acfcf99b6
train
function
def run_train_from_args(args, hyperdrive_hyperparameter_overrides: Dict[str, str] = {}) -> None: # Get the housekeeping going and start logging: os.makedirs(args.save_dir, exist_ok=True) run_id = make_run_id(args.model, args.task) log_file = os.path.join(args.save_dir, f"{run_id}.log") def log(...
def run_train_from_args(args, hyperdrive_hyperparameter_overrides: Dict[str, str] = {}) -> None: # Get the housekeeping going and start logging:
os.makedirs(args.save_dir, exist_ok=True) run_id = make_run_id(args.model, args.task) log_file = os.path.join(args.save_dir, f"{run_id}.log") def log(msg): log_line(log_file, msg) log(f"Setting random seed {args.random_seed}.") random.seed(args.random_seed) np.random.seed(args....
log_fun(f"Saving true target to {valid_target_file}") with open(valid_target_file, 'wb') as handle: pickle.dump(valid_true_targets, handle, protocol=pickle.HIGHEST_PROTOCOL) handle.close() return save_file def unwrap_tf_tracked_data(data: Any) -> Any: if isinstance(data, (tf_data_structures....
173
173
579
35
137
TrungQuocNguyen/tf2-gnn
tf2_gnn/cli_utils/training_utils.py
Python
run_train_from_args
run_train_from_args
171
236
171
172
293285aaa2feaab637f3458c4c41c7de11ada302
bigcode/the-stack
train
92d57f147b5095863a52aa5e
train
function
def log_line(log_file: str, msg: str): with open(log_file, "a") as log_fh: log_fh.write(msg + "\n") print(msg)
def log_line(log_file: str, msg: str):
with open(log_file, "a") as log_fh: log_fh.write(msg + "\n") print(msg)
time.""" if run_name is not None: return run_name else: return "%s_%s__%s" % (model_name, task_name, time.strftime("%Y-%m-%d_%H-%M-%S")) def log_line(log_file: str, msg: str):
63
64
40
12
51
TrungQuocNguyen/tf2-gnn
tf2_gnn/cli_utils/training_utils.py
Python
log_line
log_line
31
34
31
31
bb0dc126f2b0ccda20363777bfb91fa5e1de6bc2
bigcode/the-stack
train
6287fc40be8e2c591b5f9c3f
train
function
def make_run_id(model_name: str, task_name: str, run_name: Optional[str] = None) -> str: """Choose a run ID, based on the --run-name parameter and the current time.""" if run_name is not None: return run_name else: return "%s_%s__%s" % (model_name, task_name, time.strftime("%Y-%m-%d_%H-%M-%S...
def make_run_id(model_name: str, task_name: str, run_name: Optional[str] = None) -> str:
"""Choose a run ID, based on the --run-name parameter and the current time.""" if run_name is not None: return run_name else: return "%s_%s__%s" % (model_name, task_name, time.strftime("%Y-%m-%d_%H-%M-%S"))
from ..models import GraphTaskModel from .model_utils import save_model, load_weights_verbosely, get_model_and_dataset from .task_utils import get_known_tasks def make_run_id(model_name: str, task_name: str, run_name: Optional[str] = None) -> str:
64
64
94
26
37
TrungQuocNguyen/tf2-gnn
tf2_gnn/cli_utils/training_utils.py
Python
make_run_id
make_run_id
23
28
23
23
c4db84e95cd5438c8062a63486b5656830df70d0
bigcode/the-stack
train
a05caaaa5b582d3419e24f45
train
function
def get_train_cli_arg_parser(default_model_type: Optional[str]=None): """ Get an argparse argument parser object with common options for training GNN-based models. Args: default_model_type: If provided, the model type is downgraded from a positional parameter on the command line to ...
def get_train_cli_arg_parser(default_model_type: Optional[str]=None):
""" Get an argparse argument parser object with common options for training GNN-based models. Args: default_model_type: If provided, the model type is downgraded from a positional parameter on the command line to an option with the given default value. """ import...
aml_run = None trained_model_path = train( model, dataset, log_fun=log, run_id=run_id, max_epochs=args.max_epochs, patience=args.patience, save_dir=args.save_dir, quiet=args.quiet, aml_run=aml_run, ) if args.run_test: ...
256
256
925
15
241
TrungQuocNguyen/tf2-gnn
tf2_gnn/cli_utils/training_utils.py
Python
get_train_cli_arg_parser
get_train_cli_arg_parser
239
360
239
239
ca3ef325cec23e8f271894dc1bf0338e0bc315df
bigcode/the-stack
train
2ecbff0fa4367330295d149c
train
function
def unwrap_tf_tracked_data(data: Any) -> Any: if isinstance(data, (tf_data_structures.ListWrapper, list)): return [unwrap_tf_tracked_data(e) for e in data] elif isinstance(data, (tf_data_structures._DictWrapper, dict)): return {k: unwrap_tf_tracked_data(v) for k, v in data.items()} else: ...
def unwrap_tf_tracked_data(data: Any) -> Any:
if isinstance(data, (tf_data_structures.ListWrapper, list)): return [unwrap_tf_tracked_data(e) for e in data] elif isinstance(data, (tf_data_structures._DictWrapper, dict)): return {k: unwrap_tf_tracked_data(v) for k, v in data.items()} else: return data
_fun(f"Saving true target to {valid_target_file}") with open(valid_target_file, 'wb') as handle: pickle.dump(valid_true_targets, handle, protocol=pickle.HIGHEST_PROTOCOL) handle.close() return save_file def unwrap_tf_tracked_data(data: Any) -> Any:
64
64
86
13
50
TrungQuocNguyen/tf2-gnn
tf2_gnn/cli_utils/training_utils.py
Python
unwrap_tf_tracked_data
unwrap_tf_tracked_data
162
168
162
162
eb059004ecc9eb84c50e6eacf330e70090060ea9
bigcode/the-stack
train
033f749fb8933aa7daebc922
train
class
class StandardScaler: def __init__(self, means: np.ndarray = None, stds: np.ndarray = None, replace_nan_token: Any = None): self.means = means self.stds = stds self.replace_nan_token = replace_nan_token def fit(self, X: List[List[float]]) -> 'StandardScaler': X = np.array(X).ast...
class StandardScaler:
def __init__(self, means: np.ndarray = None, stds: np.ndarray = None, replace_nan_token: Any = None): self.means = means self.stds = stds self.replace_nan_token = replace_nan_token def fit(self, X: List[List[float]]) -> 'StandardScaler': X = np.array(X).astype(float) sel...
from typing import Any, List import numpy as np class StandardScaler:
16
98
328
4
11
prokia/DL-Anti-Osteoporosis
finetune_group/cmpnn/data/scaler.py
Python
StandardScaler
StandardScaler
6
34
6
6
d3adab4bcb824ac452331e1f97062cf1f407810b
bigcode/the-stack
train
946738c78fff9b8b9fa2bf1a
train
class
class TestNewUnconfirmedTokensTransactionsRB(unittest.TestCase): """NewUnconfirmedTokensTransactionsRB unit test stubs""" def setUp(self): pass def tearDown(self): pass def testNewUnconfirmedTokensTransactionsRB(self): """Test NewUnconfirmedTokensTransactionsRB""" # FI...
class TestNewUnconfirmedTokensTransactionsRB(unittest.TestCase):
"""NewUnconfirmedTokensTransactionsRB unit test stubs""" def setUp(self): pass def tearDown(self): pass def testNewUnconfirmedTokensTransactionsRB(self): """Test NewUnconfirmedTokensTransactionsRB""" # FIXME: construct object with mandatory attributes with example valu...
_unconfirmed_tokens_transactions_rb_data import NewUnconfirmedTokensTransactionsRBData globals()['NewUnconfirmedTokensTransactionsRBData'] = NewUnconfirmedTokensTransactionsRBData from cryptoapis.model.new_unconfirmed_tokens_transactions_rb import NewUnconfirmedTokensTransactionsRB class TestNewUnconfirmedTokensTransac...
64
64
98
12
51
Crypto-APIs/Crypto_APIs_2.0_SDK_Python
test/test_new_unconfirmed_tokens_transactions_rb.py
Python
TestNewUnconfirmedTokensTransactionsRB
TestNewUnconfirmedTokensTransactionsRB
21
34
21
21
58fdd2c97c9c072f7273716f3017d56483ac4451
bigcode/the-stack
train
76fe7a906fd6260a7188f204
train
class
class ElasticsearchExtractor(BaseExtractor): def __init__(self, *args, **kwargs): super(ElasticsearchExtractor, self).__init__(*args, **kwargs) def run(self): es_index = self.source_definition.get( 'elasticsearch_index', u'%s_%s' % ( settings.DEFAULT_INDEX_PREFIX, ...
class ElasticsearchExtractor(BaseExtractor):
def __init__(self, *args, **kwargs): super(ElasticsearchExtractor, self).__init__(*args, **kwargs) def run(self): es_index = self.source_definition.get( 'elasticsearch_index', u'%s_%s' % ( settings.DEFAULT_INDEX_PREFIX, self.source_definition['index_n...
import json from pprint import pprint from ocd_backend import settings from ocd_backend.extractors import BaseExtractor from ocd_backend.exceptions import ConfigurationError from ocd_backend.es import elasticsearch from elasticsearch.helpers import scan class ElasticsearchExtractor(BaseExtractor):
56
69
230
6
49
ngi-nix/poliscoops
ocd_backend/extractors/es.py
Python
ElasticsearchExtractor
ElasticsearchExtractor
12
34
12
12
a607771fa99fc48235ca22cf7a1974c5f1c7a0bf
bigcode/the-stack
train
fb862b7d3861c7a6b014caa2
train
function
def ripemd160(x): d = hashlib.new('ripemd160') d.update(x) return d
def ripemd160(x):
d = hashlib.new('ripemd160') d.update(x) return d
# pip install base58 / ecdsa # tested in python 3.6.5 import os, binascii, hashlib, base58, ecdsa def ripemd160(x):
42
64
25
6
35
jonprints/econocalypse-source
src/address_gen.py
Python
ripemd160
ripemd160
6
9
6
6
1c075ee9525fc360f5b8507a5caa6305c850a41f
bigcode/the-stack
train
a0fe4481e7aa295cfd560f25
train
class
class LidlCCTColorCluster(CustomCluster, Color): """Lidl CCT Lighting custom cluster.""" # Remove RGB color wheel for CCT Lighting: only expose color temperature # LIDL bulbs do not correctly report this attribute (comes back as None in Home Assistant) _CONSTANT_ATTRIBUTES = {0x400A: 16}
class LidlCCTColorCluster(CustomCluster, Color):
"""Lidl CCT Lighting custom cluster.""" # Remove RGB color wheel for CCT Lighting: only expose color temperature # LIDL bulbs do not correctly report this attribute (comes back as None in Home Assistant) _CONSTANT_ATTRIBUTES = {0x400A: 16}
from zigpy.zcl.clusters.lightlink import LightLink from zhaquirks.const import ( DEVICE_TYPE, ENDPOINTS, INPUT_CLUSTERS, MODELS_INFO, OUTPUT_CLUSTERS, PROFILE_ID, ) class LidlCCTColorCluster(CustomCluster, Color):
64
64
72
11
53
Brazen00/zha-device-handlers
zhaquirks/lidl/cct.py
Python
LidlCCTColorCluster
LidlCCTColorCluster
28
33
28
28
79360620759b4e08d2d2723469601e47826f5c61
bigcode/the-stack
train
e008e58eedf6dc5ced6e59ef
train
class
class CCTLight(CustomDevice): """Lidl CCT Lighting device.""" signature = { MODELS_INFO: [ ("_TZ3000_49qchf10", "TS0502A"), ("_TZ3000_oborybow", "TS0502A"), ("_TZ3000_9evm3otq", "TS0502A"), ("_TZ3000_rylaozuc", "TS0502A"), ("_TZ3000_el5kt5im",...
class CCTLight(CustomDevice):
"""Lidl CCT Lighting device.""" signature = { MODELS_INFO: [ ("_TZ3000_49qchf10", "TS0502A"), ("_TZ3000_oborybow", "TS0502A"), ("_TZ3000_9evm3otq", "TS0502A"), ("_TZ3000_rylaozuc", "TS0502A"), ("_TZ3000_el5kt5im", "TS0502A"), ("_TZ...
Groups, Identify, LevelControl, OnOff, Ota, Scenes, Time, ) from zigpy.zcl.clusters.lighting import Color from zigpy.zcl.clusters.lightlink import LightLink from zhaquirks.const import ( DEVICE_TYPE, ENDPOINTS, INPUT_CLUSTERS, MODELS_INFO, OUTPUT_CLUSTERS, PROFILE_ID...
168
168
563
7
161
Brazen00/zha-device-handlers
zhaquirks/lidl/cct.py
Python
CCTLight
CCTLight
36
106
36
36
4868d0aae85101e1e3bd5bf0e2abb50dd26d28b8
bigcode/the-stack
train
67cd4159bc9731821c6d55da
train
class
class LaplaceNoise(EncodingMechanism): """ The laplace noise mechanisms anonymizes input by perturbing it using the laplace distribution. While this approach is similar to noising results using the laplace mechanism for Differential Privacy, using our laplace noise mechanism itself does not provide any ...
class LaplaceNoise(EncodingMechanism):
""" The laplace noise mechanisms anonymizes input by perturbing it using the laplace distribution. While this approach is similar to noising results using the laplace mechanism for Differential Privacy, using our laplace noise mechanism itself does not provide any Differential Privacy guarantees per se....
import numpy as np from pydantic.types import constr, PositiveFloat from .encoding_mechanism import EncodingMechanism from ..utils.pydantic_base_model import CamelBaseModel class LaplaceNoise(EncodingMechanism):
49
75
252
9
39
openredact/anonymizer
anonymizer/mechanisms/laplace_noise.py
Python
LaplaceNoise
LaplaceNoise
8
33
8
8
fe718ebd26aa424d20cceaff5d6879c146741e4d
bigcode/the-stack
train
78cb68dd662d8c0c2953de55
train
class
class LaplaceNoiseParameters(CamelBaseModel): mechanism: constr(regex="^laplaceNoise$") = "laplaceNoise" config: LaplaceNoise
class LaplaceNoiseParameters(CamelBaseModel):
mechanism: constr(regex="^laplaceNoise$") = "laplaceNoise" config: LaplaceNoise
given input parameter. If the input_value is not a number, it raises a ValueError. """ input_value = float(input_value) noise = np.random.laplace(scale=self.sensitivity / self.epsilon) return input_value + noise class LaplaceNoiseParameters(CamelBaseModel):
64
64
35
10
53
openredact/anonymizer
anonymizer/mechanisms/laplace_noise.py
Python
LaplaceNoiseParameters
LaplaceNoiseParameters
36
38
36
36
23c813870504ee222b90edcacba1f4a3a657b80b
bigcode/the-stack
train
cd4c88c1fd7365b7810d7095
train
class
class DataWriter(): def __init__(self, cfg, opt, save_video=False, video_save_opt=DEFAULT_VIDEO_SAVE_OPT, queueSize=1024): self.cfg = cfg self.opt = opt self.video_save_opt = video_save_opt self.eval_joints = EVAL_JOINTS self.save_video = sa...
class DataWriter():
def __init__(self, cfg, opt, save_video=False, video_save_opt=DEFAULT_VIDEO_SAVE_OPT, queueSize=1024): self.cfg = cfg self.opt = opt self.video_save_opt = video_save_opt self.eval_joints = EVAL_JOINTS self.save_video = save_video sel...
import os import time from threading import Thread from queue import Queue import cv2 import numpy as np import torch import torch.multiprocessing as mp from alphapose.utils.transforms import get_func_heatmap_to_coord from alphapose.utils.pPose_nms import pose_nms, write_json DEFAULT_VIDEO_SAVE_OPT = { 'savepath...
184
256
1,774
4
180
ahmed-nady/AlphaPose
alphapose/utils/writer.py
Python
DataWriter
DataWriter
24
209
24
24
c61b638e5a590be07b0cce54b9f7c9eae8028b89
bigcode/the-stack
train
d62744b4910dbab80b24f710
train
function
def _validate_id(_resource_id): if _resource_id is None: custom_print(ID_IS_NULL, err=True) exit()
def _validate_id(_resource_id):
if _resource_id is None: custom_print(ID_IS_NULL, err=True) exit()
from chargebeecli.constants.constants import ApiOperation from chargebeecli.constants.error_messages import OPERATION_NOT_SUPPORTED, ID_IS_NULL from chargebeecli.printer.printer import custom_print def _validate_id(_resource_id):
47
64
29
8
38
bhaskernitt/chargebee-cli
chargebeecli/processors/processor.py
Python
_validate_id
_validate_id
6
9
6
6
d1b2b215123b06cb28eea3fc85742f4d85274323
bigcode/the-stack
train
49690f655ad7b660b1bf180a
train
class
class Processor(object): def get_api_header(self): raise NotImplementedError("Please Implement this method") def process(self, ctx, operation, payload, resource_id): if operation == ApiOperation.CREATE.value: self.create(ctx=ctx, payload=payload, resource_id=resource_id) el...
class Processor(object):
def get_api_header(self): raise NotImplementedError("Please Implement this method") def process(self, ctx, operation, payload, resource_id): if operation == ApiOperation.CREATE.value: self.create(ctx=ctx, payload=payload, resource_id=resource_id) elif operation == ApiOperati...
from chargebeecli.constants.constants import ApiOperation from chargebeecli.constants.error_messages import OPERATION_NOT_SUPPORTED, ID_IS_NULL from chargebeecli.printer.printer import custom_print def _validate_id(_resource_id): if _resource_id is None: custom_print(ID_IS_NULL, err=True) exit() c...
72
105
352
4
68
bhaskernitt/chargebee-cli
chargebeecli/processors/processor.py
Python
Processor
Processor
12
50
12
13
f6e00af377a163ba55a57bd898932084b9bb7e80
bigcode/the-stack
train
796f05d6b245a1e334e6330c
train
class
@pluginmatcher(re.compile( r'https?://(?:www\.)?huomao\.(?:tv|com)(?P<path>/|/video/v/)(?P<room_id>\d+)' )) class Huomao(Plugin): magic_val = '6FE26D855E1AEAE090E243EB1AF73685' mobile_url = 'https://m.huomao.com/mobile/mob_live/{0}' live_data_url = 'https://m.huomao.com/swf/live_data' vod_url = 'htt...
@pluginmatcher(re.compile( r'https?://(?:www\.)?huomao\.(?:tv|com)(?P<path>/|/video/v/)(?P<room_id>\d+)' )) class Huomao(Plugin):
magic_val = '6FE26D855E1AEAE090E243EB1AF73685' mobile_url = 'https://m.huomao.com/mobile/mob_live/{0}' live_data_url = 'https://m.huomao.com/swf/live_data' vod_url = 'https://www.huomao.com/video/vreplay/{0}' author = None category = None title = None author_re = re.compile( r'...
import hashlib import logging import re import time from streamlink.plugin import Plugin, PluginError, pluginmatcher from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils import parse_json log = logging.getLogger(__name__) @pluginmatcher(re.compile( r'https?://(?...
112
256
1,213
54
58
Erk-/streamlink
src/streamlink/plugins/huomao.py
Python
Huomao
Huomao
14
186
14
17
d70aba0d32d6e8eee93241f8a3e693d391a71b31
bigcode/the-stack
train
75e79316a9300bf076fb7860
train
class
class Migration(migrations.Migration): dependencies = [ ('Bottle_Building', '0001_initial'), ] operations = [ migrations.AddField( model_name='bottle_building', name='title', field=models.CharField(default='', max_length=40), preserve_default...
class Migration(migrations.Migration):
dependencies = [ ('Bottle_Building', '0001_initial'), ] operations = [ migrations.AddField( model_name='bottle_building', name='title', field=models.CharField(default='', max_length=40), preserve_default=False, ), migrations.Ad...
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2017-08-21 01:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
54
64
180
7
46
andrewnyhus/Bottle-Builder
Bottle_Building/migrations/0002_auto_20170821_0125.py
Python
Migration
Migration
8
39
8
9
e82cba46e5190298893874831e7098ac7c848b78
bigcode/the-stack
train
d02e5389ca51d669d4c4bf15
train
class
class TestInput(unittest.TestCase): """Tests for the units package """ def test_input(self): """Testing Input class """ files = ["input.json", "input.yaml"] for fl in files: extsplt = os.path.splitext(fl) filejson = pkg_resou...
class TestInput(unittest.TestCase):
"""Tests for the units package """ def test_input(self): """Testing Input class """ files = ["input.json", "input.yaml"] for fl in files: extsplt = os.path.splitext(fl) filejson = pkg_resources.resource_filename(__package__, ...
# -*- coding: utf-8 -*- import os import pkg_resources import unittest import numpy from quantarhei import Input class TestInput(unittest.TestCase):
35
66
220
7
27
slamavl/quantarhei
tests/unit/wizard/input/test_input.py
Python
TestInput
TestInput
11
44
11
11
53c2ccde95c6bb71618be905db7a6d00b3a27b3a
bigcode/the-stack
train
3a482901edf23441b3d14340
train
function
def usage(argv): """.""" cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [var=value]\n' '(exMample: "%s development.ini")' % (cmd, cmd)) sys.exit(1)
def usage(argv):
""".""" cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [var=value]\n' '(exMample: "%s development.ini")' % (cmd, cmd)) sys.exit(1)
FAKE_USER =[{'username': 'turbo', 'password': context.hash('maple')}, # {'username': 'kitties', 'password': context.hash('fluff')}, # {'username': 'tree', 'password': context.hash('leafy')}] def usage(argv):
64
64
58
4
60
Bonanashelby/MoodBot
mood_bot/mood_bot/scripts/initializedb.py
Python
usage
usage
34
39
34
34
2ad87f2502f7439fe5d562d0c6c35066d7802c8f
bigcode/the-stack
train
f818ecc6beffaf64c9f0ad0f
train
function
def main(argv=sys.argv): """.""" if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) settings["sqlalchemy.url"] = os.environ["DATABASE_URL"] engine = get_engine(settin...
def main(argv=sys.argv):
""".""" if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) settings["sqlalchemy.url"] = os.environ["DATABASE_URL"] engine = get_engine(settings) Base.metadata.dro...
def usage(argv): """.""" cmd = os.path.basename(argv[0]) print('usage: %s <config_uri> [var=value]\n' '(exMample: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv):
64
64
102
6
58
Bonanashelby/MoodBot
mood_bot/mood_bot/scripts/initializedb.py
Python
main
main
42
56
42
42
d43973a3ef36bbc46773bd4a820461531d972399
bigcode/the-stack
train
6acb40f424f29047c5f15e6c
train
class
class DatasetMps(): """ Mps based classification/regression """ def __init__(self, field_n : int, x0 : np.ndarray = None, x1 : np.ndarray = None, max_bond_dim : int = 20, class_n : int = None): """ Intialize a classification/regression model Parameters: ----------- ...
class DatasetMps():
""" Mps based classification/regression """ def __init__(self, field_n : int, x0 : np.ndarray = None, x1 : np.ndarray = None, max_bond_dim : int = 20, class_n : int = None): """ Intialize a classification/regression model Parameters: ----------- field_n : int ...
""" Mps based classification/regression """ import numpy as np from .mps import Mps def data2vector(X : np.ndarray, x0 : np.ndarray, x1 : np.ndarray) -> np.ndarray: """ Convert data points into 2-dim vectors """ theta = (np.pi/2) * (X - x0) / (x1 - x0) if np.any(theta < 0) or np.any(theta > np.p...
132
256
1,193
5
127
lucamarx/pyAutoSpec
pyautospec/dataset_mps.py
Python
DatasetMps
DatasetMps
21
184
21
21
5e6c07997fd9cb31025911790712ef3c3322918a
bigcode/the-stack
train
71e88bb6efa9ae6a495b4f0a
train
function
def data2vector(X : np.ndarray, x0 : np.ndarray, x1 : np.ndarray) -> np.ndarray: """ Convert data points into 2-dim vectors """ theta = (np.pi/2) * (X - x0) / (x1 - x0) if np.any(theta < 0) or np.any(theta > np.pi/2): raise Exception("out of range") return np.dstack((np.cos(theta), np....
def data2vector(X : np.ndarray, x0 : np.ndarray, x1 : np.ndarray) -> np.ndarray:
""" Convert data points into 2-dim vectors """ theta = (np.pi/2) * (X - x0) / (x1 - x0) if np.any(theta < 0) or np.any(theta > np.pi/2): raise Exception("out of range") return np.dstack((np.cos(theta), np.sin(theta)))
""" Mps based classification/regression """ import numpy as np from .mps import Mps def data2vector(X : np.ndarray, x0 : np.ndarray, x1 : np.ndarray) -> np.ndarray:
47
64
105
25
21
lucamarx/pyAutoSpec
pyautospec/dataset_mps.py
Python
data2vector
data2vector
9
18
9
9
30bc9cb225cc8620ad08150078318933c5e2700f
bigcode/the-stack
train
1b841ad47b6166308a931982
train
function
def page_feedback_internal(data, region, language, comment, rating, is_technical): """ Store feedback about single event in database :param data: HTTP request body data :type data: dict :param region: The region of this sitemap's urls :type region: ~integreat_cms.cms.models.regions.region.Regi...
def page_feedback_internal(data, region, language, comment, rating, is_technical):
""" Store feedback about single event in database :param data: HTTP request body data :type data: dict :param region: The region of this sitemap's urls :type region: ~integreat_cms.cms.models.regions.region.Region :param language: The language of this sitemap's urls :type language: ~i...
:param is_technical: is feedback on content or on tech :type is_technical: bool :return: decorated function that saves feedback in database :rtype: ~collections.abc.Callable """ return page_feedback_internal(data, region, language, comment, rating, is_technical) def page_feedback_internal(data, re...
85
85
286
18
67
Carlosbogo/integreat-cms
integreat_cms/api/v3/feedback/page_feedback.py
Python
page_feedback_internal
page_feedback_internal
41
79
41
41
880f2798cf9acf568f30b5a68a849591167c4a1e
bigcode/the-stack
train
a2744242f80e09019741c884
train
function
@feedback_handler @json_response def page_feedback(data, region, language, comment, rating, is_technical): """ Decorate function for storing feedback about single page in database :param data: HTTP request body data :type data: dict :param region: The region of this sitemap's urls :type region...
@feedback_handler @json_response def page_feedback(data, region, language, comment, rating, is_technical):
""" Decorate function for storing feedback about single page in database :param data: HTTP request body data :type data: dict :param region: The region of this sitemap's urls :type region: ~integreat_cms.cms.models.regions.region.Region :param language: The language of this sitemap's urls...
""" from django.http import JsonResponse from django.shortcuts import get_object_or_404 from ....cms.models import PageFeedback, PageTranslation from ...decorators import json_response, feedback_handler @feedback_handler @json_response def page_feedback(data, region, language, comment, rating, is_technical):
66
66
221
25
40
Carlosbogo/integreat-cms
integreat_cms/api/v3/feedback/page_feedback.py
Python
page_feedback
page_feedback
11
38
11
13
63d78a769baa0280b18f1d5377011598ea541b4b
bigcode/the-stack
train
dfffe7a28190e0e2627d84b8
train
function
@mock_ec2_deprecated def test_route_table_get_by_tag(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc('10.0.0.0/16') route_table = conn.create_route_table(vpc.id) route_table.add_tag('Name', 'TestRouteTable') route_tables = conn.get_all_route_tables( filters={'tag...
@mock_ec2_deprecated def test_route_table_get_by_tag():
conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc('10.0.0.0/16') route_table = conn.create_route_table(vpc.id) route_table.add_tag('Name', 'TestRouteTable') route_tables = conn.get_all_route_tables( filters={'tag:Name': 'TestRouteTable'}) route_tables.should.have...
_with_assoc( association_id2, "rtb-1234abcd") cm.exception.code.should.equal('InvalidRouteTableID.NotFound') cm.exception.status.should.equal(400) cm.exception.request_id.should_not.be.none @mock_ec2_deprecated def test_route_table_get_by_tag():
64
64
166
15
48
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_route_table_get_by_tag
test_route_table_get_by_tag
307
323
307
308
2b6c835b59d573bb3b1ad977f445c7ea18d072ee
bigcode/the-stack
train
e670460187d0943e0c9b78b3
train
function
@mock_ec2_deprecated def test_route_tables_additional(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") route_table = conn.create_route_table(vpc.id) all_route_tables = conn.get_all_route_tables(filters={'vpc-id': vpc.id}) all_route_tables.should.have.length_o...
@mock_ec2_deprecated def test_route_tables_additional():
conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") route_table = conn.create_route_table(vpc.id) all_route_tables = conn.get_all_route_tables(filters={'vpc-id': vpc.id}) all_route_tables.should.have.length_of(2) all_route_tables[0].vpc_id.should.equal(vpc.id) ...
routes = main_route_table.routes routes.should.have.length_of(1) local_route = routes[0] local_route.gateway_id.should.equal('local') local_route.state.should.equal('active') local_route.destination_cidr_block.should.equal(vpc.cidr_block) vpc.delete() all_route_tables = conn.get_all_rout...
108
108
363
14
94
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_route_tables_additional
test_route_tables_additional
41
78
41
42
73dee909f14721f6c58e6bb7548f51e1d3c59115
bigcode/the-stack
train
34dfdf7f6a9ace596379cefd
train
function
@requires_boto_gte("2.16.0") @mock_ec2_deprecated def test_route_table_replace_route_table_association(): """ Note: Boto has deprecated replace_route_table_assocation (which returns status) and now uses replace_route_table_assocation_with_assoc (which returns association ID). """ conn = boto.c...
@requires_boto_gte("2.16.0") @mock_ec2_deprecated def test_route_table_replace_route_table_association():
""" Note: Boto has deprecated replace_route_table_assocation (which returns status) and now uses replace_route_table_assocation_with_assoc (which returns association ID). """ conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") subnet = conn.create_subn...
: conn.disassociate_route_table(association_id) cm.exception.code.should.equal('InvalidAssociationID.NotFound') cm.exception.status.should.equal(400) cm.exception.request_id.should_not.be.none # Error: Associate with invalid subnet ID with assert_raises(EC2ResponseError) as cm: conn...
222
222
741
30
191
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_route_table_replace_route_table_association
test_route_table_replace_route_table_association
232
304
232
234
2d38a7ad15732c415375f51937d5c76c15ea8e04
bigcode/the-stack
train
7288a65cc879b31e79e7f369
train
function
@mock_ec2_deprecated def test_route_tables_filters_associations(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") subnet1 = conn.create_subnet(vpc.id, "10.0.0.0/24") subnet2 = conn.create_subnet(vpc.id, "10.0.1.0/24") subnet3 = conn.create_subnet(vpc.id, "10.0...
@mock_ec2_deprecated def test_route_tables_filters_associations():
conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") subnet1 = conn.create_subnet(vpc.id, "10.0.0.0/24") subnet2 = conn.create_subnet(vpc.id, "10.0.1.0/24") subnet3 = conn.create_subnet(vpc.id, "10.0.2.0/24") route_table1 = conn.create_route_table(vpc.id) ro...
.main': 'true', 'vpc-id': vpc2.id}) vpc2_main_route_tables.should.have.length_of(1) vpc2_main_route_table_ids = [ route_table.id for route_table in vpc2_main_route_tables] vpc2_main_route_table_ids.should_not.contain(route_table1.id) vpc2_main_route_table_ids.should_not.contain(route_table2.id) ...
136
136
456
15
121
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_route_tables_filters_associations
test_route_tables_filters_associations
125
162
125
126
821d630bf8826c7e8019485c8cfdefeb7ee7d499
bigcode/the-stack
train
96b2667c7fba9fd9b1b74df0
train
function
@mock_ec2 def test_create_route_with_invalid_destination_cidr_block_parameter(): ec2 = boto3.resource('ec2', region_name='us-west-1') vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16') vpc.reload() vpc.is_default.shouldnt.be.ok route_table = ec2.create_route_table(VpcId=vpc.id) route_table.reload()...
@mock_ec2 def test_create_route_with_invalid_destination_cidr_block_parameter():
ec2 = boto3.resource('ec2', region_name='us-west-1') vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16') vpc.reload() vpc.is_default.shouldnt.be.ok route_table = ec2.create_route_table(VpcId=vpc.id) route_table.reload() internet_gateway = ec2.create_internet_gateway() vpc.attach_internet_ga...
_tables() test_route_table = next(na for na in all_route_tables if na.id == route_table.id) test_route_table.tags.should.have.length_of(1) test_route_table.tags["a key"].should.equal("some value") @mock_ec2 def test_create_route_with_invalid_destination_cidr_block_parameter():
70
70
236
17
53
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_create_route_with_invalid_destination_cidr_block_parameter
test_create_route_with_invalid_destination_cidr_block_parameter
534
554
534
535
ea242881404d0d543f78c25bf670c99bb0f0acf3
bigcode/the-stack
train
8e1d3d2f103a3f624c0f58cf
train
function
@mock_ec2_deprecated def test_routes_replace(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") main_route_table = conn.get_all_route_tables( filters={'association.main': 'true', 'vpc-id': vpc.id})[0] local_route = main_route_table.routes[0] ROUTE_CIDR =...
@mock_ec2_deprecated def test_routes_replace():
conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") main_route_table = conn.get_all_route_tables( filters={'association.main': 'true', 'vpc-id': vpc.id})[0] local_route = main_route_table.routes[0] ROUTE_CIDR = "10.0.0.4/24" # Various route targets ...
vpc-id': vpc.id})[0] # Refresh route table main_route_table.routes.should.have.length_of(1) new_routes = [ route for route in main_route_table.routes if route.destination_cidr_block != vpc.cidr_block] new_routes.should.have.length_of(0) with assert_raises(EC2ResponseError) as cm: conn...
138
138
460
12
125
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_routes_replace
test_routes_replace
388
435
388
389
831973c0da496be57504b27c6f794412a48e7ea9
bigcode/the-stack
train
0d5931ee5f027307821f23c5
train
function
@mock_ec2_deprecated def test_route_table_associations(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") subnet = conn.create_subnet(vpc.id, "10.0.0.0/18") route_table = conn.create_route_table(vpc.id) all_route_tables = conn.get_all_route_tables() all_rou...
@mock_ec2_deprecated def test_route_table_associations():
conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") subnet = conn.create_subnet(vpc.id, "10.0.0.0/18") route_table = conn.create_route_table(vpc.id) all_route_tables = conn.get_all_route_tables() all_route_tables.should.have.length_of(3) # Refresh rout...
_route_tables[0].associations.should.have.length_of(2) # Filter by route table ID route_table2_route_tables = conn.get_all_route_tables( filters={'association.route-table-id': route_table2.id}) route_table2_route_tables.should.have.length_of(1) route_table2_route_tables[0].id.should.equal(route...
183
183
613
14
169
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_route_table_associations
test_route_table_associations
165
229
165
166
53c304e56a1fb3e4ec78ea58ac95ae8e314876c0
bigcode/the-stack
train
510411f4b7d6dbe6946fd273
train
function
@mock_ec2_deprecated def test_network_acl_tagging(): conn = boto.connect_vpc('the_key', 'the secret') vpc = conn.create_vpc("10.0.0.0/16") route_table = conn.create_route_table(vpc.id) route_table.add_tag("a key", "some value") tag = conn.get_all_tags()[0] tag.name.should.equal("a key") t...
@mock_ec2_deprecated def test_network_acl_tagging():
conn = boto.connect_vpc('the_key', 'the secret') vpc = conn.create_vpc("10.0.0.0/16") route_table = conn.create_route_table(vpc.id) route_table.add_tag("a key", "some value") tag = conn.get_all_tags()[0] tag.name.should.equal("a key") tag.value.should.equal("some value") all_route_tab...
.have.length_of(1) new_route = new_routes[0] new_route.gateway_id.should.equal(vpn_gw.id) new_route.instance_id.should.be.none new_route.vpc_peering_connection_id.should.be.none @mock_ec2_deprecated def test_network_acl_tagging():
64
64
163
14
49
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_network_acl_tagging
test_network_acl_tagging
514
531
514
516
d75117fd6f3efccd5eb599e03d7a023fd16c02fd
bigcode/the-stack
train
6724d479c7cfe03255431cee
train
function
@mock_ec2 def test_route_table_get_by_tag_boto3(): ec2 = boto3.resource('ec2', region_name='eu-central-1') vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16') route_table = ec2.create_route_table(VpcId=vpc.id) route_table.create_tags(Tags=[{'Key': 'Name', 'Value': 'TestRouteTable'}]) filters = [{'Name'...
@mock_ec2 def test_route_table_get_by_tag_boto3():
ec2 = boto3.resource('ec2', region_name='eu-central-1') vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16') route_table = ec2.create_route_table(VpcId=vpc.id) route_table.create_tags(Tags=[{'Key': 'Name', 'Value': 'TestRouteTable'}]) filters = [{'Name': 'tag:Name', 'Values': ['TestRouteTable']}] ro...
(vpc.id) route_tables[0].id.should.equal(route_table.id) route_tables[0].tags.should.have.length_of(1) route_tables[0].tags['Name'].should.equal('TestRouteTable') @mock_ec2 def test_route_table_get_by_tag_boto3():
64
64
212
16
48
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_route_table_get_by_tag_boto3
test_route_table_get_by_tag_boto3
326
343
326
327
26c5c7b9c14d84db633ba4026362a38c7a2cae5e
bigcode/the-stack
train
d2cde9493a649c240fe5a3a3
train
function
@requires_boto_gte("2.34.0") @mock_ec2_deprecated def test_routes_vpn_gateway(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") main_route_table = conn.get_all_route_tables( filters={'association.main': 'true', 'vpc-id': vpc.id})[0] ROUTE_CIDR = "10.0.0.4/...
@requires_boto_gte("2.34.0") @mock_ec2_deprecated def test_routes_vpn_gateway():
conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") main_route_table = conn.get_all_route_tables( filters={'association.main': 'true', 'vpc-id': vpc.id})[0] ROUTE_CIDR = "10.0.0.4/24" vpn_gw = conn.create_vpn_gateway(type="ipsec.1") conn.create_route(m...
.should.be.none new_route.vpc_peering_connection_id.should.equal(vpc_pcx.id) new_route.state.should.equal('blackhole') new_route.destination_cidr_block.should.equal(ROUTE_CIDR) @requires_boto_gte("2.34.0") @mock_ec2_deprecated def test_routes_vpn_gateway():
74
74
249
27
47
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_routes_vpn_gateway
test_routes_vpn_gateway
489
511
489
492
4a4b271a249f58e70f94b996a3c76de613f238cf
bigcode/the-stack
train
1a6bb3ed61ef880b44b23cc1
train
function
@mock_ec2_deprecated def test_route_tables_defaults(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") all_route_tables = conn.get_all_route_tables(filters={'vpc-id': vpc.id}) all_route_tables.should.have.length_of(1) main_route_table = all_route_tables[0] ...
@mock_ec2_deprecated def test_route_tables_defaults():
conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") all_route_tables = conn.get_all_route_tables(filters={'vpc-id': vpc.id}) all_route_tables.should.have.length_of(1) main_route_table = all_route_tables[0] main_route_table.vpc_id.should.equal(vpc.id) rout...
import boto3 from boto.exception import EC2ResponseError from botocore.exceptions import ClientError import sure # noqa from moto import mock_ec2, mock_ec2_deprecated from tests.helpers import requires_boto_gte @mock_ec2_deprecated def test_route_tables_defaults():
64
64
197
13
50
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_route_tables_defaults
test_route_tables_defaults
16
38
16
17
c4d4666ff6abf8418c89442ef89f55f809fe1d73
bigcode/the-stack
train
c69b7c0d19c664f34ea8da35
train
function
@mock_ec2_deprecated def test_routes_additional(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") main_route_table = conn.get_all_route_tables(filters={'vpc-id': vpc.id})[0] local_route = main_route_table.routes[0] igw = conn.create_internet_gateway() ROUTE...
@mock_ec2_deprecated def test_routes_additional():
conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") main_route_table = conn.get_all_route_tables(filters={'vpc-id': vpc.id})[0] local_route = main_route_table.routes[0] igw = conn.create_internet_gateway() ROUTE_CIDR = "10.0.0.4/24" conn.create_route(main_r...
[{'Name': 'tag:Name', 'Values': ['TestRouteTable']}] route_tables = list(ec2.route_tables.filter(Filters=filters)) route_tables.should.have.length_of(1) route_tables[0].vpc_id.should.equal(vpc.id) route_tables[0].id.should.equal(route_table.id) route_tables[0].tags.should.have.length_of(1) rou...
125
126
421
13
112
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_routes_additional
test_routes_additional
346
385
346
347
2974c48ea3a77eb4d28d4c30143bebd64a946f7b
bigcode/the-stack
train
a79d6eeefc25546a7bbacf1d
train
function
@mock_ec2_deprecated def test_route_tables_filters_standard(): conn = boto.connect_vpc('the_key', 'the_secret') vpc1 = conn.create_vpc("10.0.0.0/16") route_table1 = conn.create_route_table(vpc1.id) vpc2 = conn.create_vpc("10.0.0.0/16") route_table2 = conn.create_route_table(vpc2.id) all_route...
@mock_ec2_deprecated def test_route_tables_filters_standard():
conn = boto.connect_vpc('the_key', 'the_secret') vpc1 = conn.create_vpc("10.0.0.0/16") route_table1 = conn.create_route_table(vpc1.id) vpc2 = conn.create_vpc("10.0.0.0/16") route_table2 = conn.create_route_table(vpc2.id) all_route_tables = conn.get_all_route_tables() all_route_tables.shou...
Violation') cm.exception.status.should.equal(400) cm.exception.request_id.should_not.be.none conn.delete_route_table(route_table.id) all_route_tables = conn.get_all_route_tables(filters={'vpc-id': vpc.id}) all_route_tables.should.have.length_of(1) with assert_raises(EC2ResponseError) as cm: ...
135
135
452
14
120
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_route_tables_filters_standard
test_route_tables_filters_standard
81
122
81
82
d8a1635011788e42e16487e216dd4d9464fe94fe
bigcode/the-stack
train
75c995a6d416a446580b8eda
train
function
@requires_boto_gte("2.19.0") @mock_ec2_deprecated def test_routes_not_supported(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") main_route_table = conn.get_all_route_tables()[0] local_route = main_route_table.routes[0] igw = conn.create_internet_gateway() ...
@requires_boto_gte("2.19.0") @mock_ec2_deprecated def test_routes_not_supported():
conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") main_route_table = conn.get_all_route_tables()[0] local_route = main_route_table.routes[0] igw = conn.create_internet_gateway() ROUTE_CIDR = "10.0.0.4/24" # Create conn.create_route.when.called_with( ...
gateway_id=igw.id) cm.exception.code.should.equal('InvalidRouteTableID.NotFound') cm.exception.status.should.equal(400) cm.exception.request_id.should_not.be.none @requires_boto_gte("2.19.0") @mock_ec2_deprecated def test_routes_not_supported():
66
66
222
26
39
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_routes_not_supported
test_routes_not_supported
438
456
438
440
756d97149c7a726779c973155a836a26596ec937
bigcode/the-stack
train
268bbd18931b4fa8e6ddfae5
train
function
@requires_boto_gte("2.34.0") @mock_ec2_deprecated def test_routes_vpc_peering_connection(): conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") main_route_table = conn.get_all_route_tables( filters={'association.main': 'true', 'vpc-id': vpc.id})[0] local_route =...
@requires_boto_gte("2.34.0") @mock_ec2_deprecated def test_routes_vpc_peering_connection():
conn = boto.connect_vpc('the_key', 'the_secret') vpc = conn.create_vpc("10.0.0.0/16") main_route_table = conn.get_all_route_tables( filters={'association.main': 'true', 'vpc-id': vpc.id})[0] local_route = main_route_table.routes[0] ROUTE_CIDR = "10.0.0.4/24" peer_vpc = conn.create_vpc("...
igw = conn.create_internet_gateway() conn.create_route(main_route_table.id, ROUTE_CIDR, gateway_id=igw.id) conn.replace_route.when.called_with( main_route_table.id, ROUTE_CIDR, interface_id='eni-1234abcd').should.throw(NotImplementedError) @requires_boto_gte("2.34.0") @mock_ec2_deprecated def test_...
97
97
324
29
68
harveywi/moto
tests/test_ec2/test_route_tables.py
Python
test_routes_vpc_peering_connection
test_routes_vpc_peering_connection
459
486
459
461
89127f1e8127d8553f83f07a6b5e4115a4b0d8a6
bigcode/the-stack
train
7aec347e189e880a57ecb77e
train
class
class ShopeeDatabase(CommerceDatabase): valid_fields: [str] = shopee.get_valid_fields() def create_tables(self) -> None: """Initializes a ShopeeProducts database to store item info of products from Shopee """ with self.conn: # TODO: Find a way to keep the column name...
class ShopeeDatabase(CommerceDatabase):
valid_fields: [str] = shopee.get_valid_fields() def create_tables(self) -> None: """Initializes a ShopeeProducts database to store item info of products from Shopee """ with self.conn: # TODO: Find a way to keep the column names and their data types depend on the con...
import sqlite3 from scrapers import shopee from abc import ABC, abstractmethod class CommerceDatabase(ABC): def __init__(self, db_path=":memory:"): self.conn = sqlite3.connect(db_path) def query(self, query): with self.conn: return self.conn.execute(query) @abstractmethod ...
91
122
407
8
82
AmGthrow/ShopeeScrape
data/database.py
Python
ShopeeDatabase
ShopeeDatabase
19
70
19
19
f2a2ee620f1176371a0aa2004e034738dbe5d038
bigcode/the-stack
train
5b24dac8018d608f18ec8192
train
class
class CommerceDatabase(ABC): def __init__(self, db_path=":memory:"): self.conn = sqlite3.connect(db_path) def query(self, query): with self.conn: return self.conn.execute(query) @abstractmethod def create_tables(self): pass
class CommerceDatabase(ABC):
def __init__(self, db_path=":memory:"): self.conn = sqlite3.connect(db_path) def query(self, query): with self.conn: return self.conn.execute(query) @abstractmethod def create_tables(self): pass
import sqlite3 from scrapers import shopee from abc import ABC, abstractmethod class CommerceDatabase(ABC):
26
64
63
6
19
AmGthrow/ShopeeScrape
data/database.py
Python
CommerceDatabase
CommerceDatabase
6
16
6
6
010f32eb0400c0f6fecc94aa00c1b7d0b2e2b70b
bigcode/the-stack
train
b62a7c08d0a2bcfcf65ab3e1
train
function
def test_lasso_toy(): # Test Lasso on a toy example for various values of alpha. # When validating this against glmnet notice that glmnet divides it # against nobs. X = [[-1], [0], [1]] Y = [-1, 0, 1] # just a straight line T = [[2], [3], [4]] # test sample clf = Lasso(alpha=1e-8) cl...
def test_lasso_toy(): # Test Lasso on a toy example for various values of alpha. # When validating this against glmnet notice that glmnet divides it # against nobs.
X = [[-1], [0], [1]] Y = [-1, 0, 1] # just a straight line T = [[2], [3], [4]] # test sample clf = Lasso(alpha=1e-8) clf.fit(X, Y) pred = clf.predict(T) assert_array_almost_equal(clf.coef_, [1]) assert_array_almost_equal(pred, [2, 3, 4]) assert_almost_equal(clf.dual_gap_, 0) ...
= 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(ValueError, match=msg): clf.fit(X, y) def test_lasso_toy(): # Test Lasso on a toy exa...
116
116
389
43
73
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_lasso_toy
test_lasso_toy
209
244
209
213
d3026dbabaf421fd415cee6c0ceeaf0dbb76571a
bigcode/the-stack
train
faaa9554255dbb6d2f751b1d
train
function
def test_lasso_positive_constraint(): X = [[-1], [0], [1]] y = [1, 0, -1] # just a straight line with negative slope lasso = Lasso(alpha=0.1, positive=True) lasso.fit(X, y) assert min(lasso.coef_) >= 0 lasso = Lasso(alpha=0.1, precompute=True, positive=True) lasso.fit(X, y) assert min...
def test_lasso_positive_constraint():
X = [[-1], [0], [1]] y = [1, 0, -1] # just a straight line with negative slope lasso = Lasso(alpha=0.1, positive=True) lasso.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
_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): clf.fit(X, Y) def test_lasso_positive_constraint():
64
64
116
7
57
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_lasso_positive_constraint
test_lasso_positive_constraint
773
783
773
773
fb682ca4ad02e4d8e906b9e1ffcff139597f117a
bigcode/the-stack
train
d8b44fc6775772680c34aa93
train
function
@pytest.mark.filterwarnings("ignore:'normalize' was deprecated") @pytest.mark.parametrize( "LinearModel, params", [ (Lasso, {"tol": 1e-16, "alpha": 0.1}), (LassoLars, {"alpha": 0.1}), (RidgeClassifier, {"solver": "sparse_cg", "alpha": 0.1}), (ElasticNet, {"tol": 1e-16, "l1_ratio"...
@pytest.mark.filterwarnings("ignore:'normalize' was deprecated") @pytest.mark.parametrize( "LinearModel, params", [ (Lasso, {"tol": 1e-16, "alpha": 0.1}), (LassoLars, {"alpha": 0.1}), (RidgeClassifier, {"solver": "sparse_cg", "alpha": 0.1}), (ElasticNet, {"tol": 1e-16, "l1_ratio"...
model_normalize = LinearModel(normalize=True, fit_intercept=True, **params) pipeline = make_pipeline( StandardScaler(), LinearModel(normalize=False, fit_intercept=True, **params) ) is_multitask = model_normalize._get_tags()["multioutput_only"] # prepare the data n_samples, n_features ...
@pytest.mark.filterwarnings("ignore:'normalize' was deprecated") @pytest.mark.parametrize( "LinearModel, params", [ (Lasso, {"tol": 1e-16, "alpha": 0.1}), (LassoLars, {"alpha": 0.1}), (RidgeClassifier, {"solver": "sparse_cg", "alpha": 0.1}), (ElasticNet, {"tol": 1e-16, "l1_ratio"...
421
235
785
421
0
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_model_pipeline_same_as_normalize_true
test_model_pipeline_same_as_normalize_true
426
493
426
454
4b6bc9f8c02ff9bb9b01cc5fce21b7f23b9221f0
bigcode/the-stack
train
215df14d71ef39f0103b0311
train
function
def test_lasso_dual_gap(): """ Check that Lasso.dual_gap_ matches its objective formulation, with the datafit normalized by n_samples """ X, y, _, _ = build_dataset(n_samples=10, n_features=30) n_samples = len(y) alpha = 0.01 * np.max(np.abs(X.T @ y)) / n_samples clf = Lasso(alpha=alpha,...
def test_lasso_dual_gap():
""" Check that Lasso.dual_gap_ matches its objective formulation, with the datafit normalized by n_samples """ X, y, _, _ = build_dataset(n_samples=10, n_features=30) n_samples = len(y) alpha = 0.01 * np.max(np.abs(X.T @ y)) / n_samples clf = Lasso(alpha=alpha, fit_intercept=False).fit(X...
_array_almost_equal(clf.coef_, [0.45454], 3) assert_array_almost_equal(pred, [0.9090, 1.3636, 1.8181], 3) assert_almost_equal(clf.dual_gap_, 0) def test_lasso_dual_gap():
69
69
230
8
61
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_lasso_dual_gap
test_lasso_dual_gap
294
309
294
294
b915b469d693e10bcc74e3b155eff51b65c21ee1
bigcode/the-stack
train
4cb7416c65f14ee2246bcf42
train
function
def test_random_descent(): # Test that both random and cyclic selection give the same results. # Ensure that the test models fully converge and check a wide # range of conditions. # This uses the coordinate descent algo using the gram trick. X, y, _, _ = build_dataset(n_samples=50, n_features=20) ...
def test_random_descent(): # Test that both random and cyclic selection give the same results. # Ensure that the test models fully converge and check a wide # range of conditions. # This uses the coordinate descent algo using the gram trick.
X, y, _, _ = build_dataset(n_samples=50, n_features=20) clf_cyclic = ElasticNet(selection="cyclic", tol=1e-8) clf_cyclic.fit(X, y) clf_random = ElasticNet(selection="random", tol=1e-8, random_state=42) clf_random.fit(X, y) assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) assert_...
# Fit the solution to the original, less regularized version of the # problem but from the solution of the highly regularized variant of # the problem as a better starting point. This should also converge # faster than the original model that starts from zero. warm_low_reg_model = deepcopy(high_reg_mod...
164
165
552
53
111
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_random_descent
test_random_descent
1,088
1,130
1,088
1,093
c6b3f32f2ca139a33ec53a387c0b2fca274e141e
bigcode/the-stack
train
3e40a377ce8c8cd85f021674
train
function
@pytest.mark.parametrize("check_input", [True, False]) def test_enet_sample_weight_does_not_overwrite_sample_weight(check_input): """Check that ElasticNet does not overwrite sample_weights.""" rng = np.random.RandomState(0) n_samples, n_features = 10, 5 X = rng.rand(n_samples, n_features) y = rng....
@pytest.mark.parametrize("check_input", [True, False]) def test_enet_sample_weight_does_not_overwrite_sample_weight(check_input):
"""Check that ElasticNet does not overwrite sample_weights.""" rng = np.random.RandomState(0) n_samples, n_features = 10, 5 X = rng.rand(n_samples, n_features) y = rng.rand(n_samples) sample_weight_1_25 = 1.25 * np.ones_like(y) sample_weight = sample_weight_1_25.copy() reg = ElasticN...
1e6 # 1 MB with joblib.parallel_backend("loky"): estimator(n_jobs=2, cv=3).fit(X, y) @pytest.mark.parametrize("check_input", [True, False]) def test_enet_sample_weight_does_not_overwrite_sample_weight(check_input):
64
64
151
28
36
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_enet_sample_weight_does_not_overwrite_sample_weight
test_enet_sample_weight_does_not_overwrite_sample_weight
1,702
1,718
1,702
1,703
589a18f2cc82410da9cfd38305f211ef34993320
bigcode/the-stack
train
e586dfddb29ff12d26dde745
train
function
def test_overrided_gram_matrix(): X, y, _, _ = build_dataset(n_samples=20, n_features=10) Gram = X.T.dot(X) clf = ElasticNet(selection="cyclic", tol=1e-8, precompute=Gram) warning_message = ( "Gram matrix was provided but X was centered" " to fit intercept, " "or X was normalized...
def test_overrided_gram_matrix():
X, y, _, _ = build_dataset(n_samples=20, n_features=10) Gram = X.T.dot(X) clf = ElasticNet(selection="cyclic", tol=1e-8, precompute=Gram) warning_message = ( "Gram matrix was provided but X was centered" " to fit intercept, " "or X was normalized : recomputing Gram matrix." )...
.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_overrided_gram_matrix():
64
64
117
9
55
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_overrided_gram_matrix
test_overrided_gram_matrix
1,214
1,224
1,214
1,214
b0770154c3546c2b6aea9058266e8f56ec8c5637
bigcode/the-stack
train
ac6230e299f77bf5aa49a99b
train
function
def test_lasso_cv(): X, y, X_test, y_test = build_dataset() max_iter = 150 clf = LassoCV(n_alphas=10, eps=1e-3, max_iter=max_iter, cv=3).fit(X, y) assert_almost_equal(clf.alpha_, 0.056, 2) clf = LassoCV(n_alphas=10, eps=1e-3, max_iter=max_iter, precompute=True, cv=3) clf.fit(X, y) assert_al...
def test_lasso_cv():
X, y, X_test, y_test = build_dataset() max_iter = 150 clf = LassoCV(n_alphas=10, eps=1e-3, max_iter=max_iter, cv=3).fit(X, y) assert_almost_equal(clf.alpha_, 0.056, 2) clf = LassoCV(n_alphas=10, eps=1e-3, max_iter=max_iter, precompute=True, cv=3) clf.fit(X, y) assert_almost_equal(clf.alpha_...
1: w = random_state.randn(n_features, n_targets) else: w = random_state.randn(n_features) w[n_informative_features:] = 0.0 X = random_state.randn(n_samples, n_features) y = np.dot(X, w) X_test = random_state.randn(n_samples, n_features) y_test = np.dot(X_test, w) return X, y,...
103
103
346
6
96
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_lasso_cv
test_lasso_cv
330
359
330
330
f600957da3700e63646ded2b558c629cc94fc91d
bigcode/the-stack
train
2b1e5952c8adca3f62fda700
train
function
@pytest.mark.parametrize("sample_weight", [False, True]) def test_enet_cv_grid_search(sample_weight): """Test that ElasticNetCV gives same result as GridSearchCV.""" n_samples, n_features = 200, 10 cv = 5 X, y = make_regression( n_samples=n_samples, n_features=n_features, effecti...
@pytest.mark.parametrize("sample_weight", [False, True]) def test_enet_cv_grid_search(sample_weight):
"""Test that ElasticNetCV gives same result as GridSearchCV.""" n_samples, n_features = 200, 10 cv = 5 X, y = make_regression( n_samples=n_samples, n_features=n_features, effective_rank=10, n_informative=n_features - 4, noise=10, random_state=0, ) ...
) # ensure that we chose meaningful alphas, i.e. not boundaries assert alphas[0] < reg.alpha_ < alphas[-1] assert reg_sw.alpha_ == reg.alpha_ assert_allclose(reg_sw.coef_, reg.coef_) assert reg_sw.intercept_ == pytest.approx(reg.intercept_) @pytest.mark.parametrize("sample_weight", [False, True]) d...
94
95
319
22
72
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_enet_cv_grid_search
test_enet_cv_grid_search
1,588
1,620
1,588
1,589
f1f730fc24e8010494be3b8a6cdb34e245f89f75
bigcode/the-stack
train
1fe0412d2098eb9ba63c0a28
train
function
def test_warm_start(): X, y, _, _ = build_dataset() clf = ElasticNet(alpha=0.1, max_iter=5, warm_start=True) ignore_warnings(clf.fit)(X, y) ignore_warnings(clf.fit)(X, y) # do a second round with 5 iterations clf2 = ElasticNet(alpha=0.1, max_iter=10) ignore_warnings(clf2.fit)(X, y) assert_...
def test_warm_start():
X, y, _, _ = build_dataset() clf = ElasticNet(alpha=0.1, max_iter=5, warm_start=True) ignore_warnings(clf.fit)(X, y) ignore_warnings(clf.fit)(X, y) # 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...
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_warm_start():
63
64
118
6
57
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_warm_start
test_warm_start
748
756
748
748
4ddbe7cf541e66562e8fe57759d6f8a1a9889fba
bigcode/the-stack
train
4b48372dbd62e6ed31124abe
train
function
def test_enet_l1_ratio(): # Test that an error message is raised if an estimator that # uses _alpha_grid is called with l1_ratio=0 msg = ( "Automatic alpha grid generation is not supported for l1_ratio=0. " "Please supply a grid by providing your estimator with the " "appropriate `al...
def test_enet_l1_ratio(): # Test that an error message is raised if an estimator that # uses _alpha_grid is called with l1_ratio=0
msg = ( "Automatic alpha grid generation is not supported for l1_ratio=0. " "Please supply a grid by providing your estimator with the " "appropriate `alphas=` argument." ) X = np.array([[1, 2, 4, 5, 8], [3, 5, 7, 7, 8]]).T y = np.array([12, 10, 11, 21, 5]) with pytest.raise...
clf_multioutput.fit(X, multi_y) coef[("multi", dtype)] = clf_multioutput.coef_ intercept[("multi", dtype)] = clf_multioutput.intercept_ assert clf.coef_.dtype == dtype for v in ["simple", "multi"]: assert_array_almost_equal( ...
157
157
524
37
120
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_enet_l1_ratio
test_enet_l1_ratio
1,305
1,347
1,305
1,307
157998cbe88763ccd2872364c81507b0d850f590
bigcode/the-stack
train
d5490511806cf0203957d530
train
function
def test_warm_start_multitask_lasso(): X, y, X_test, y_test = build_dataset() Y = np.c_[y, y] clf = MultiTaskLasso(alpha=0.1, max_iter=5, warm_start=True) ignore_warnings(clf.fit)(X, Y) ignore_warnings(clf.fit)(X, Y) # do a second round with 5 iterations clf2 = MultiTaskLasso(alpha=0.1, max_it...
def test_warm_start_multitask_lasso():
X, y, X_test, y_test = build_dataset() Y = np.c_[y, y] clf = MultiTaskLasso(alpha=0.1, max_iter=5, warm_start=True) ignore_warnings(clf.fit)(X, Y) ignore_warnings(clf.fit)(X, Y) # do a second round with 5 iterations clf2 = MultiTaskLasso(alpha=0.1, max_iter=10) ignore_warnings(clf2.fit)(X,...
_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_warm_start_multitask_lasso():
63
64
140
11
52
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_warm_start_multitask_lasso
test_warm_start_multitask_lasso
1,356
1,365
1,356
1,356
f2ed4e017545d20086eb19baef93592afedcab29
bigcode/the-stack
train
3e7cbcd8b0cedf33cdac1e31
train
function
@pytest.mark.filterwarnings("ignore:'normalize' was deprecated") @pytest.mark.parametrize( "LinearModel, params", [ (Lasso, {"tol": 1e-16, "alpha": 0.1}), (LassoCV, {"tol": 1e-16}), (ElasticNetCV, {}), (RidgeClassifier, {"solver": "sparse_cg", "alpha": 0.1}), (ElasticNet,...
@pytest.mark.filterwarnings("ignore:'normalize' was deprecated") @pytest.mark.parametrize( "LinearModel, params", [ (Lasso, {"tol": 1e-16, "alpha": 0.1}), (LassoCV, {"tol": 1e-16}), (ElasticNetCV, {}), (RidgeClassifier, {"solver": "sparse_cg", "alpha": 0.1}), (ElasticNet,...
model_dense = make_pipeline( StandardScaler(with_mean=False), LinearModel(normalize=False, **params) ) model_sparse = make_pipeline( StandardScaler(with_mean=False), LinearModel(normalize=False, **params) ) # prepare the data rng = np.random.RandomState(0) n_samples = 200 ...
@pytest.mark.filterwarnings("ignore:'normalize' was deprecated") @pytest.mark.parametrize( "LinearModel, params", [ (Lasso, {"tol": 1e-16, "alpha": 0.1}), (LassoCV, {"tol": 1e-16}), (ElasticNetCV, {}), (RidgeClassifier, {"solver": "sparse_cg", "alpha": 0.1}), (ElasticNet,...
262
146
488
262
0
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_model_pipeline_same_dense_and_sparse
test_model_pipeline_same_dense_and_sparse
595
645
595
615
fbdde4e8bc044a7a63e5b7481eda74cf0bdfc995
bigcode/the-stack
train
ca141972faa66a4137534313
train
function
def test_enet_path(): # We use a large number of samples and of informative features so that # the l1_ratio selected is more toward ridge than lasso X, y, X_test, y_test = build_dataset( n_samples=200, n_features=100, n_informative_features=100 ) max_iter = 150 # Here we have a small nu...
def test_enet_path(): # We use a large number of samples and of informative features so that # the l1_ratio selected is more toward ridge than lasso
X, y, X_test, y_test = build_dataset( n_samples=200, n_features=100, n_informative_features=100 ) max_iter = 150 # Here we have a small number of iterations, and thus the # ElasticNet might not converge. This is to speed up tests clf = ElasticNetCV( alphas=[0.01, 0.05, 0.1], eps...
, 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 = interpolate.interp1d( alphas_lars[::-1], coef_path_lars[:, ::-1] ) alphas_lasso2, coef_pa...
224
224
748
37
187
AnkitKumar2698/scikit-learn
sklearn/linear_model/tests/test_coordinate_descent.py
Python
test_enet_path
test_enet_path
673
734
673
675
b8a010a9f0badbf5e589311ef8f4ca6e6739ca62
bigcode/the-stack
train