How to use test_append method in Slash

Best Python code snippet using slash

app.py

Source:app.py Github

copy

Full Screen

1from flask import Flask,render_template,request,redirect,url_for,session2from flask_bootstrap import Bootstrap3import MySQLdb4import os5from math import sqrt6from sklearn import neighbors7from os import listdir8from os.path import isdir, join, isfile, splitext9import shutil10import pickle11from PIL import Image, ImageFont, ImageDraw, ImageEnhance12import face_recognition13from face_recognition import face_locations14from face_recognition.face_recognition_cli import image_files_in_folder15from datetime import datetime,timedelta16from pytz import timezone17import xlsxwriter18import pandas as pd19from glob import glob20from flask_mail import Mail, Message21from io import BytesIO22import base6423import lable_image24app = Flask(__name__,static_folder="excel")25# mail settings26app.config.update(27 DEBUG = True,28 #Email settings29 MAIL_SERVER = 'smtp.gmail.com',30 MAIL_PORT = 465,31 MAIL_USE_SSL = True,32 MAIL_USERNAME = 'college1118@gmail.com',33 MAIL_PASSWORD = 'yog12345',34 MAIL_DEFAULT_SENDER = 'college1118@gmail.com'35 )36mail = Mail(app)37# declaring timezone then creating custom date format 38india = timezone('Asia/Kolkata')39date = str(datetime.now(india))[:10] + "@" + str(datetime.now())[11:13] + "hrs"40# getting the location of root directory of the webapp41APP_ROOT = os.path.dirname(os.path.abspath(__file__))42APP_ROOT1 = APP_ROOT.split('teachers_site')43# connection with mysql database using python package MySQLdb44conn = MySQLdb.connect(user='root', passwd='', port=2811, host='localhost',db="login_info")45@app.route('/')46def index():47 return render_template("index.html",title="Faculty Login")48@app.after_request49def set_response_headers(response):50 response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'51 response.headers['Pragma'] = 'no-cache'52 response.headers['Expires'] = '0'53 return response54@app.route('/login',methods=['POST'])55def login():56 print(APP_ROOT)57 print(APP_ROOT1[0])58 user = str(request.form["user"])59 session['user'] = user60 paswd = str(request.form["password"])61 username = user.split(".",1)[0]62 username = str(username)63 print(username)64 print(type(username))65 cursor = conn.cursor()66 result = cursor.execute("SELECT * from teacher_login where binary username=%s and binary password=%s",[user,paswd])67 if(result is 1):68 return render_template("task.html",uname=username)69 else:70 return render_template("index.html",title="Faculty Login",msg="The username or password is incorrect")71@app.after_request72def set_response_headers(response):73 response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'74 response.headers['Pragma'] = 'no-cache'75 response.headers['Expires'] = '0'76 return response77@app.route('/upload_redirect',methods=['POST'])78def upload_redirect():79 if(os.path.isfile(APP_ROOT+"/image.jpeg")):80 os.remove(APP_ROOT + "/image.jpeg")81 return render_template("upload.html")82@app.route("/upload", methods=['POST'])83def upload():84 if not os.path.isfile(APP_ROOT+"/image.jpeg"):85 return render_template("upload.html",msg="spoof detected")86 id_folder = str(request.form['id_folder'])87 session['id_folder']= id_folder88 target = os.path.join(APP_ROOT,"test/")89 if not os.path.isdir(target):90 os.mkdir(target)91 target1 = os.path.join(target,str(request.form["folder_name"])+"/")92 test_append = str(request.form["folder_name"])93 session['test_append']= test_append94 print(target1)95 if not os.path.isdir(target1):96 os.mkdir(target1)97 shutil.copyfile(APP_ROOT+"/"+"image.jpeg",target1+"image.jpeg")98 destination = APP_ROOT + "/" + "test/" + test_append + "/" + "image.jpeg"99 100 session['destination'] = destination101 teacher_name = str(session.get('user'))102 session['teacher_name'] = teacher_name103 #return render_template("upload.html",msg="uploaded successfully")104 return match()105@app.after_request106def set_response_headers(response):107 response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'108 response.headers['Pragma'] = 'no-cache'109 response.headers['Expires'] = '0'110 return response111def match():112 destination = str(session.get('destination'))113 print(destination)114 if os.path.isfile(destination):115 test_append = str(session.get('test_append'))116 session['test_append'] = test_append117 id_folder = str(session.get('id_folder'))118 train_dir = APP_ROOT1[0]+"admin_site/train/"+ test_append119 try:120 model = APP_ROOT1[0]+"admin_site/model/"+test_append+"/" + id_folder + "/" +"model"121 print(model)122 return predict1(model)123 except FileNotFoundError:124 os.remove(APP_ROOT1[0]+"teachers_site/image.jpeg")125 return render_template("upload.html",msg="trained model not present for " + test_append + ": "+id_folder)126 127def predict(X_img_path, knn_clf = None, model_save_path ="", DIST_THRESH = .45):128 if knn_clf is None and model_save_path == "":129 raise Exception("must supply knn classifier either thourgh knn_clf or model_save_path")130 if knn_clf is None:131 with open(model_save_path, 'rb') as f:132 knn_clf = pickle.load(f)133 X_img = face_recognition.load_image_file(X_img_path)134 X_faces_loc = face_locations(X_img)135 if len(X_faces_loc) == 0:136 return []137 faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_faces_loc)138 closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)139 is_recognized = [closest_distances[0][i][0] <= DIST_THRESH for i in range(len(X_faces_loc))]140 141 return [(pred) if rec else ("unknown") for pred, rec in zip(knn_clf.predict(faces_encodings), is_recognized)]142def predict1(model):143 test_append = str(session.get('test_append'))144 test_dir = APP_ROOT1[0]+"teachers_site/test/" + test_append145 f_preds = []146 for img_path in listdir(test_dir):147 preds = predict(join(test_dir, img_path) ,model_save_path=model)148 f_preds.append(preds)149 print(f_preds)150 print(len(preds))151 print(len(f_preds))152 for i in range(len(f_preds)):153 if(f_preds[i]==[]):154 os.remove(APP_ROOT1[0]+"teachers_site/image.jpeg")155 return render_template("upload.html",msg="upload again, face not found")156 else:157 os.remove(APP_ROOT1[0]+"teachers_site/image.jpeg")158 excel = os.path.join(APP_ROOT,"excel/")159 if not os.path.isdir(excel):160 os.mkdir(excel)161 excel1 = os.path.join(excel,test_append)162 if not os.path.isdir(excel1):163 os.mkdir(excel1)164 teacher_name = str(session.get('teacher_name'))165 excel2 = os.path.join(excel1,teacher_name)166 if not os.path.isdir(excel2):167 os.mkdir(excel2)168 session['excel2'] = excel2169 excel3 = excel2+"/"+date+'.xlsx'170 if not os.path.isfile(excel3):171 workbook = xlsxwriter.Workbook(excel2+"/"+date+'.xlsx')172 worksheet = workbook.add_worksheet()173 worksheet.set_column(0,0,20)174 worksheet.write('A1','Roll Id')175 f_preds.sort()176 row = 1177 col = 0178 for i in range(len(f_preds)):179 for j in range(len(f_preds[i])):180 worksheet.write_string(row,col,f_preds[i][j])181 row += 1182 workbook.close()183 return render_template("upload.html",msg= f_preds[0][0] + " present")184 else:185 df = pd.read_excel(excel2+"/"+date+'.xlsx')186 writer = pd.ExcelWriter(excel2 + "/" + date+'.xlsx')187 df.to_excel(writer,sheet_name="Sheet1",index=False)188 workbook = writer.book189 worksheet = writer.sheets['Sheet1']190 rows=df.shape[0]191 worksheet.write_string(rows+1,0,f_preds[0][0])192 writer.save()193 df = pd.read_excel(excel2+"/"+date+'.xlsx')194 df.drop_duplicates(['Roll Id'],keep='first',inplace=True)195 result = df.sort_values("Roll Id")196 writer = pd.ExcelWriter(excel2 + "/" + date+'.xlsx')197 result.to_excel(writer,'Sheet1',index=False)198 workbook = writer.book199 worksheet = writer.sheets['Sheet1']200 worksheet.set_column(0,0,20)201 writer.save()202 return render_template("upload.html",msg= f_preds[0][0] + " present")203@app.route('/view_report',methods=['POST'])204def view_report():205 return render_template("excel.html")206# view route to download excel files 207@app.route('/view',methods=['POST'])208def view():209 test_append = str(request.form['folder_name'])210 session['test_append']=test_append211 teacher_name = str(session.get('user'))212 excel_dir = APP_ROOT+"/excel/"+test_append+"/"+teacher_name+"/"213 excel_date = request.form['fname']214 time = request.form['ftime']215 time = time[:2]216 print(time)217 final_excel=glob(excel_dir + "/" + excel_date+ "@" + time +"*.xlsx")[0]218 print(final_excel)219 df = pd.read_excel(final_excel)220 df.index += 1221 return render_template("files.html",msg=final_excel,df=df,date=excel_date+"@"+time+"hrs")222@app.route('/excel/<path:filename>', methods=['POST'])223def download(filename): 224 return send_from_directory(directory='excel', filename=filename)225# route to send emails to parents and students226@app.route('/send_mail',methods=['POST'])227def send_mail():228 test_append = str(request.form['folder_name'])229 teacher_name = str(session.get('user'))230 excel_dir = APP_ROOT+"/excel/"+test_append+"/"+teacher_name+"/"231 excel_date = request.form['fname']232 time = request.form['ftime']233 time = time[:2]234 final_send = glob(excel_dir + "/" + excel_date+ "@" + time +"*.xlsx")[0]235 print(final_send)236 df = pd.read_excel(final_send)237 roll_id = list(df['Roll Id'])238 print(type(roll_id))239 print(roll_id)240 cursor = conn.cursor()241 for i in range(len(roll_id)):242 cursor.execute("SELECT student_email,parent_email from student_login where binary roll_id=%s",[roll_id[i]])243 email = list(cursor.fetchone())244 print(type(email[1]))245 print(email[0])246 print(email[1])247 msg = Message('Auto Generated',recipients= [email[0],email[1]])248 msg.body = "Hi.. " + roll_id[i] + " is present for the lecture of " + "Prof. " +str(teacher_name.split('.',1)[0]) + ", which is held on " + excel_date + "@" + time + "hrs"249 msg.html = "Hi.. " + roll_id[i] + " is present for the lecture of " + "Prof. " +str(teacher_name .split('.',1)[0])+ ", which is held on " + excel_date + "@" + time + "hrs"250 mail.send(msg)251 return "<h1>mail sent<h1>"252@app.route('/update',methods=['POST'])253def update():254 test_append = str(request.form['excel_folder'])255 print(test_append)256 teacher_name = str(session.get('user'))257 print(teacher_name)258 excel_dir = APP_ROOT + "/excel/" + test_append + "/" + teacher_name + "/"259 print(excel_dir)260 for file in request.files.getlist("updated_excel"):261 print(file)262 filename = file.filename263 print(filename)264 destination = "/".join([excel_dir,filename])265 print(destination)266 file.save(destination)267 return render_template("excel.html",msg="updated successfully")268@app.route('/calculate',methods=['POST'])269def calculate():270 test_append = str(request.form['final_class'])271 print(test_append)272 teacher_name = str(session.get('user'))273 print(teacher_name)274 excel_root = APP_ROOT + "/excel/" + test_append + "/" + teacher_name + "/"275 print(excel_root)276 excel_names = os.listdir(excel_root)277 print(excel_names) 278 for i in range(len(excel_names)):279 if excel_names[i].startswith("."):280 os.remove(excel_root+excel_names[i])281 else:282 if os.path.isdir(excel_root+excel_names[i]):283 shutil.rmtree(excel_root+excel_names[i], ignore_errors=False, onerror=None)284 excel_names = os.listdir(excel_root)285 if(excel_names==[]):286 return render_template("excel.html",msg1="No excel files found")287 for i in range(len(excel_names)):288 excel_names[i] = excel_root + excel_names[i]289 print(type(excel_names))290 # read them in291 excels = [pd.ExcelFile(name) for name in excel_names]292 # turn them into dataframes293 frames = [x.parse(x.sheet_names[0], header=None,index_col=None) for x in excels]294 # delete the first row for all frames except the first295 # i.e. remove the header row -- assumes it's the first296 frames[1:] = [df[1:] for df in frames[1:]]297 # concatenate them..298 combined = pd.concat(frames)299 if not os.path.isdir(excel_root+"final/"):300 os.mkdir(excel_root + "final/")301 final = excel_root + "final/"302 print(final)303 # write it out304 combined.to_excel(final+"final.xlsx", header=False, index=False)305 # below code is to find actual repetative blocks306 workbook = pd.ExcelFile(final+"final.xlsx")307 df = workbook.parse('Sheet1')308 sample_data = df['Roll Id'].tolist()309 print (sample_data)310 #a dict that will store the poll results311 results = {}312 for response in sample_data:313 results[response] = results.setdefault(response, 0) + 1314 finaldf = (pd.DataFrame(list(results.items()), columns=['Roll Id', 'Total presenty']))315 finaldf = finaldf.sort_values("Roll Id")316 print (finaldf)317 writer = pd.ExcelWriter(final+"final.xlsx")318 finaldf.to_excel(writer,'Sheet1',index=False)319 workbook = writer.book320 worksheet = writer.sheets['Sheet1']321 worksheet.set_column(0,1,20)322 writer.save()323 final = final + "final.xlsx"324 session['final']=final325 final = final[91:]326 return viewfinal(final)327def viewfinal(final):328 test_append = str(session.get('test_append'))329 final_path = str(session.get('final'))330 df = pd.read_excel(final_path)331 df.index += 1332 return render_template("files.html",msg=final,course=test_append,df=df)333@app.route('/changetask',methods=['POST'])334def changetask():335 return render_template("task.html")336@app.route('/logout',methods=['POST'])337def logout():338 return render_template("index.html",title="Faculty Login",msg1="Logged out please login again")339@app.route('/hello',methods=['POST'])340def hello():341 data_url = request.values['imageBase64']342 data_url= data_url[22:] 343 im = Image.open(BytesIO(base64.b64decode(data_url)))344 print(type(im))345 im.save('image.jpeg')346 filepath = APP_ROOT + "/" + "image.jpeg"347 var = lable_image.function(filepath)348 print(var)349 for i in range(len(var)):350 if(var[i] > 0.8):351 os.remove(filepath)352 return ''353if(__name__ == '__main__'):354 app.secret_key = 'super secret key'...

Full Screen

Full Screen

second.py

Source:second.py Github

copy

Full Screen

1import warnings2warnings.filterwarnings('ignore')3import pandas as pd4import numpy as np5import gc6import pickle7import time8import xgboost as xgb9from sklearn.preprocessing import LabelEncoder10from lightgbm import LGBMClassifier11from sklearn.linear_model import LinearRegression,Ridge,Lasso12from sklearn.metrics import mean_squared_error13from mlxtend.regressor import StackingRegressor,StackingCVRegressor14from sklearn.model_selection import cross_val_score,GridSearchCV15from sklearn import metrics16save_path = './data_final/'17def fun(x):18 if x >= 0.5:19 return 120 else:21 return 022with open(save_path + 'invite_info.pkl','rb') as file:23 invite_info = pickle.load(file)24member_feat = pd.read_hdf(save_path + 'member_feat.h5',key='data')25question_feat = pd.read_hdf(save_path + 'question_feat.h5',key='data')26member_question_feat = pd.read_hdf(save_path + 'member_question_feat.h5',key='data')27invite_info_evaluate = invite_info.ix[:1000]28invite_info_test = invite_info.ix[1000:2000]29invite_info = invite_info.ix[2000:]30tt = invite_info_evaluate['label']31ttt = invite_info_test['label']32del invite_info_evaluate['label'],invite_info_test['label']33invite_info['author_question_id'] = invite_info['author_id'] + invite_info['question_id']34invite_info_evaluate['author_question_id'] = invite_info_evaluate['author_id'] + invite_info_evaluate['question_id']35invite_info_test['author_question_id'] = invite_info_test['author_id'] + invite_info_test['question_id']36train = invite_info.merge(member_feat, 'left', 'author_id')37test = invite_info_evaluate.merge(member_feat, 'left', 'author_id')38pre = invite_info_test.merge(member_feat,'left','author_id')39train = train.merge(question_feat, 'left', 'question_id')40test = test.merge(question_feat, 'left', 'question_id')41pre = pre.merge(question_feat,'left','question_id')42train = train.merge(member_question_feat, 'left', 'author_question_id')43test = test.merge(member_question_feat, 'left', 'author_question_id')44pre = pre.merge(member_question_feat,'left','author_question_id')45del member_feat, question_feat, member_question_feat46gc.collect()47drop_feats = ['question_id', 'author_id', 'author_question_id', 'invite_time', 'label', 'invite_day']48used_feats = [f for f in train.columns if f not in drop_feats]49train_x = train[used_feats].reset_index(drop=True)50train_y = train['label'].reset_index(drop=True)51test_x = test[used_feats].reset_index(drop=True)52pre_x = pre[used_feats].reset_index(drop=True)53# LGBMClassifier54'''55model_lgb = LGBMClassifier(boostiong_type='gdbt',num_leaves=64,learning_rate=0.01,n_estimators=2500,max_bin=425,subsample_for_bin=50000,objective='binary',min_split_gain=0,min_child_weight=5,min_child_samples=10,subsample=0.8,subsample_freq=1,colsample_bytree=1,req_alpha=3,reg_lambda=5,seed=1000,n_jobs=-1,silent=True)56model_lgb.fit(train_x,train_y,eval_names=['train'],eval_metric=['logloss','auc'],eval_set=[(train_x,train_y)],early_stopping_rounds=10)57test_y = model_lgb.predict_proba(test_x)[:,1]58print("test auc: ",metrics.roc_auc_score(tt,test_y))59test_append = invite_info_evaluate[['question_id', 'author_id', 'invite_time']]60test_append['answer'] = test_y61test_append['answer'] = test_append['answer'].apply(lambda x: fun(x))62test_append['true'] = tt63test_append.to_csv('result_test_LGBM.txt',index=False,header=False,sep='\t')64pre_y = model_lgb.predict_proba(pre_x)[:,1]65print("pre auc: ",metrics.roc_auc_score(ttt,pre_y))66pre_append = invite_info_test[['question_id', 'author_id', 'invite_time']]67pre_append['answer'] = pre_y68pre_append['answer'] = pre_append['answer'].apply(lambda x: fun(x))69pre_append['true'] = ttt70pre_append.to_csv('result_pre_LGBM.txt',index=False,header=False,sep='\t')71'''72'''73# Stacking One74print("Let's Begin Stacking Model One")75lr = LinearRegression()76ridge = Ridge(random_state = 2019,)77models = [lr,ridge]78for model in models:79 model.fit(train_x,train_y)80 pred = model.predict(test_x)81 print("loss is {}".format(mean_squared_error(tt,pred)))82sclf = StackingRegressor(regressors = models,meta_regressor = ridge)83sclf.fit(train_x,train_y)84test_y= sclf.predict(test_x)85print("test auc: ",metrics.roc_auc_score(tt,test_y))86test_append = invite_info_evaluate[['question_id', 'author_id', 'invite_time']]87test_append['answer'] = test_y88test_append['answer'] = test_append['answer'].apply(lambda x: fun(x))89test_append['true'] = tt90test_append.to_csv('result_test_S1.txt',index=False,header=False,sep='\t')91pre_y= sclf.predict(pre_x)92print("pre auc: ",metrics.roc_auc_score(ttt,pre_y))93pre_append = invite_info_test[['question_id', 'author_id', 'invite_time']]94pre_append['answer'] = pre_y95pre_append['answer'] = pre_append['answer'].apply(lambda x: fun(x))96pre_append['true'] = ttt97pre_append.to_csv('result_pre_S1.txt',index=False,header=False,sep='\t')98'''99# Xgboost100'''101params = {'n_estimators': 10, 'seed': 0, 'n_estimators': 600, 'max_depth': 6, 'min_child_weight' :1, 'gamma': 0.2, 'subsample': 0.8, 'colsample_bytree': 0.9, 'reg_alpha':0.1, 'reg_lambda':0.05, 'learning_rate':0.01}102model = xgb.XGBRegressor(params=params, booster='dart')103model.fit(train_x, train_y)104test_y = model.predict(test_x)105print("test auc: ",metrics.roc_auc_score(tt,test_y))106test_append = invite_info_evaluate[['question_id', 'author_id', 'invite_time']]107test_append['answer'] = test_y108test_append['answer'] = test_append['answer'].apply(lambda x: fun(x))109test_append['true'] = tt110test_append.to_csv('result_test_Xgboost.txt',index=False,header=False,sep='\t')111pre_y= model.predict(pre_x)112print("pre auc: ",metrics.roc_auc_score(ttt,pre_y))113pre_append = invite_info_test[['question_id', 'author_id', 'invite_time']]114pre_append['answer'] = pre_y115pre_append['answer'] = pre_append['answer'].apply(lambda x: fun(x))116pre_append['true'] = ttt117pre_append.to_csv('result_pre_Xgboost.txt',index=False,header=False,sep='\t')118'''119# Stacking_Two120print("Let's Begin Stacking Model Two!")121lr = LinearRegression()122ridge = Ridge(random_state=2019,)123lasso =Lasso()124models = [lr,ridge, lasso]125params = {'lasso__alpha': [0.1, 1.0, 10.0],'ridge__alpha': [0.1, 1.0, 10.0]}126sclf = StackingCVRegressor(regressors=models, meta_regressor=ridge)127sclf = StackingCVRegressor(regressors=models, meta_regressor=ridge)128grid = GridSearchCV(estimator=sclf, param_grid=params, cv=5, refit=True)129grid.fit(train_x, train_y)130test_y = grid.predict(test_x)131print("test auc: ",metrics.roc_auc_score(tt,test_y))132test_append = invite_info_evaluate[['question_id', 'author_id', 'invite_time']]133test_append['answer'] = test_y134test_append['answer'] = test_append['answer'].apply(lambda x: fun(x))135test_append['true'] = tt136test_append.to_csv('result_test_S2.txt',index=False,header=False,sep='\t')137pre_y= grid.predict(pre_x)138print("pre auc: ",metrics.roc_auc_score(ttt,pre_y))139pre_append = invite_info_test[['question_id', 'author_id', 'invite_time']]140pre_append['answer'] = pre_y141pre_append['answer'] = pre_append['answer'].apply(lambda x: fun(x))142pre_append['true'] = ttt...

Full Screen

Full Screen

test_storage.py

Source:test_storage.py Github

copy

Full Screen

...8 def setUp(self):9 self.space = RNNSpace(20, 5)10 self.storage = Storage()11 self.arch = Architect(self.space)12 def test_append(self, na_points=0):13 c = 014 starting_len = len(self.storage)15 while c < 10 + na_points:16 description, logps, values, entropies = self.arch.sample()17 desc = self.space.preprocess(description, (-1, 128))18 if desc is not None:19 param_count = sum(self.space.parameter_count(desc)[:2]) / 1e620 self.storage.append(description, logps, values, entropies,21 uniform(.6, 1) if c < 10 else None,22 param_count)23 c += 124 self.assertEqual(len(self.storage), starting_len+10+na_points)25 def test_reward(self):26 chosen_description = None27 while chosen_description is None:28 description, logps, values, entropies = self.arch.sample()29 desc = self.space.preprocess(description, (-1, 128))30 if desc is not None:31 if uniform(0, 1) < .5:32 chosen_description = description33 param_count = sum(self.space.parameter_count(desc)[:2]) / 1e6 # Million parameters34 self.storage.append(description, logps, values, entropies, None, param_count)35 self.storage.reward(chosen_description, 1.)36 index = self.storage.find(chosen_description)37 self.assertIsNotNone(index)38 self.assertTrue(torch.eq(self.storage[index][-3], 1.).all())39 def test__update_advantages(self):40 chosen_description = None41 while chosen_description is None:42 description, logps, values, entropies = self.arch.sample()43 desc = self.space.preprocess(description, (-1, 128))44 if desc is not None:45 if uniform(0, 1) < .5:46 chosen_description = description47 param_count = sum(self.space.parameter_count(desc)[:2]) / 1e6 # Million parameters48 self.storage.append(description, logps, values, entropies, None, param_count)49 for adv in self.storage.advantages:50 self.assertEqual(torch.sum(adv != adv), adv.numel())51 self.storage.reward(chosen_description, 1.)52 index = self.storage.find(chosen_description)53 self.assertIsNotNone(index)54 self.assertFalse(np.isnan(self.storage[index][-3].mean().item()))55 def test_update(self):56 desc = None57 while desc is None:58 description, logps, values, entropies = self.arch.sample()59 desc = self.space.preprocess(description, (-1, 128))60 if desc is not None:61 param_count = sum(self.space.parameter_count(desc)[:2]) / 1e6 # Million parameters62 self.storage.append(description, logps, values, entropies, None, param_count)63 self.arch.reset()64 _, logps_, values_, entropies_ = self.arch.evaluate_description(description)65 self.storage.update(description, logps_, values_, entropies_)66 index = self.storage.find(description)67 self.assertIsNotNone(index)68 _, logps, values, entropies, _, _, _ = self.storage[index]69 self.assertTrue(torch.eq(logps, logps_).all())70 self.assertTrue(torch.eq(values, values_).all())71 self.assertTrue(torch.eq(entropies, entropies_).all())72 def test___get_item__(self):73 self.test_append()74 self.storage[5]75 self.storage[1:4]76 self.storage[1:4:-1]77 self.storage[np.arange(5)]78 def test___del_item__(self):79 self.test_append()80 item = self.storage[5]81 del self.storage[5]82 self.assertNotEqual(item, self.storage[5])83 def test___len__(self):84 self.test_append()85 self.assertIs(len(self.storage), 10)86 def test_filterna(self):87 self.test_append(5)88 self.assertEqual(len(self.storage), 15)89 self.storage.filter_na()90 self.assertEqual(len(self.storage), 10)91class TestCurriculumStorage(TestStorage):92 def setUp(self):93 super().setUp()94 self.storage = CurriculumStorage(20)95 def test_append(self):96 super().test_append()97 self.assertIs(len(self.storage), 10)98 self.storage.set_complexity(2)99 super().test_append()100 super().test_append()101 self.assertIs(len(self.storage), 20)102 self.storage.set_complexity(1)...

Full Screen

Full Screen

test_linked_list.py

Source:test_linked_list.py Github

copy

Full Screen

1from linked_list import __version__2from linked_list.linked_list import (LinkedList,Node)3def test_empty_linked_list():4 test_1=LinkedList()5 test_1.insert()6 actual=test_1.__str__()7 expected='(null) -> none'8 assert actual==expected9def test_insert_into_the_linked_list():10 test_2=LinkedList()11 test_2.insert(332)12 actual=test_2.head.value13 expected=33214 assert actual==expected15def test_first_node_in_the_linked_list():16 test_3=LinkedList()17 test_3.insert(332)18 test_3.insert(26)19 test_3.insert(778)20 test_3.insert(1000)21 actual=test_3.head.value22 expected=100023 assert actual==expected24def test_multiple_nodes_into_the_linked_list():25 test_4=LinkedList()26 test_4.insert(4)27 test_4.insert(5)28 actual=test_4.__str__()29 expected='(5) -> (4) -> none'30 assert actual==expected31def test_return_true_when_finding_a_value():32 test_5=LinkedList()33 test_5.insert('ahmad')34 test_5.insert('abudames')35 actual=test_5.includes('ahmad')36 expected=True37 assert actual==expected38def test_return_false_when_does_not_exist():39 test_5=LinkedList()40 test_5.insert('ahmad')41 test_5.insert('abudames')42 actual=test_5.includes('mais')43 expected=False44 assert actual==expected45def test_all_collection_values_in_in_the_linedlist():46 test_6=LinkedList()47 test_6.insert("abudames")48 test_6.insert("ameen")49 test_6.insert("shahar")50 test_6.insert("ahmad")51 actual=test_6.__str__()52 expected='(ahmad) -> (shahar) -> (ameen) -> (abudames) -> none'53 assert actual==expected54def test_end_of_the_linked_list():55 test_append=LinkedList()56 test_append.insert(22)57 test_append.insert(4)58 test_append.append(2)59 actual=test_append.__str__()60 expected='(4) -> (22) -> (2) -> none'61 assert actual==expected62def test_multiple_nodes_to_the_end_of_a_linked_list():63 test_append=LinkedList()64 test_append.append(2)65 test_append.append(1)66 actual=test_append.__str__()67 expected='(2) -> (1) -> none'68 assert actual==expected69def test_before_middle_of_the_linked_list():70 test_before=LinkedList()71 test_before.append("ahmad")72 test_before.append("shaher")73 test_before.append("abudames")74 test_before.insertBefore("abudames","ameen")75 actual=test_before.__str__()76 expected='(ahmad) -> (shaher) -> (ameen) -> (abudames) -> none'77 assert actual==expected78def test_before_the_first_node_of_a_linked_list():79 test_before_first=LinkedList()80 test_before_first.append(2)81 test_before_first.append(3)82 test_before_first.insertBefore(2,1)83 actual=test_before_first.__str__()84 expected='(1) -> (2) -> (3) -> none'85 assert actual==expected86def test_insert_after():87 test_after=LinkedList()88 test_after.append(1)89 test_after.append(3)90 test_after.insertAfter(1,2)91 actual=test_after.__str__()92 expected='(1) -> (2) -> (3) -> none'93 assert actual==expected94def test_insert_after_the_last_node():95 test_after_last_node=LinkedList()96 test_after_last_node.append(1)97 test_after_last_node.append(2)98 test_after_last_node.insertAfter(2,3)99 actual=test_after_last_node.__str__()100 expected='(1) -> (2) -> (3) -> none'101 assert actual==expected102def test_k_is_greater_than_the_length():103 test_k=LinkedList()104 test_k.insert(1)105 test_k.insert(3)106 test_k.insert(8)107 test_k.insert(2)108 test_k.NthFromLast(4)109 actual=test_k.__str__()110 expected="exception"111 assert actual==expected112def test_ths_same_of_length():113 test_k=LinkedList()114 test_k.insert(1)115 test_k.insert(3)116 test_k.insert(8)117 test_k.insert(2)118 test_k.NthFromLast(3)119 actual=test_k.__str__()120 expected='(2) -> (8) -> (3) -> (1) -> none'121 assert actual==expected122def test_not_a_positive_integer():123 test_k=LinkedList()124 test_k.insert(1)125 test_k.insert(3)126 test_k.insert(8)127 test_k.insert(2)128 test_k.NthFromLast(-1)129 actual=test_k.__str__()130 expected='(2) -> (8) -> (3) -> (1) -> none'131 assert actual==expected132def test_linked_list_is_of_a_size_1():133 test_k=LinkedList()134 test_k.insert(1)135 test_k.insert(3)136 test_k.insert(8)137 test_k.insert(2)138 test_k.NthFromLast(1)139 actual=test_k.__str__()140 expected='(2) -> (8) -> (3) -> (1) -> none'141 assert actual==expected142def test_k_in_the_middle():143 test_k=LinkedList()144 test_k.insert(1)145 test_k.insert(3)146 test_k.insert(8)147 test_k.insert(2)148 test_k.insert(5)149 test_k.NthFromLast(2)150 actual=test_k.__str__()151 expected='(5) -> (2) -> (8) -> (3) -> (1) -> none'...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Slash automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful