Best Python code snippet using avocado_python
data_collection.py
Source:data_collection.py  
1import streamlit as st2import math3import re4#import sqlite35import mysql.connector as mysql6#import pandas as pd7import csv8from tkinter import *9from tkinter import ttk10from tkinter import messagebox11#from calculations import *12#import matplotlib13#matplotlib.use('Agg')14status=""1516#------------------------------------------------ reading input file -----------------------------------------------------------1718#read date, write into date_break192021#cnx = mysql.connector.connect(user='PBTK', password='akstr!admin2',22#                              host='131.220.66.200',23#                              database='coffee_list')24#cnx.close()2526#--------------------------- main function to call from different script27def write_break(coffee_break,breaklen):28    id_ext=""29    db = mysql.connect(user='PBTK', password='akstr!admin2', #connecting to mysql30                              host='127.0.0.1',31                              database='coffee_list')32    cursor=db.cursor(buffered=True)33    34    cursor.execute("use coffee_list")3536    cursor.execute("create table if not exists breaks (id int auto_increment, id_ext char(10), day int, month int, year int,  primary key(id), unique key(id_ext))")                 #creatingbreaks table37    cursor.execute("create table if not exists drinkers (id int auto_increment, id_ext char(10), persons varchar(30), coffees varchar(30), primary key(id), CONSTRAINT fk_drinkers_break_ID_ext FOREIGN KEY(id_ext) REFERENCES breaks(id_ext) ON DELETE CASCADE)")   #creating drinkers table38    cursor.execute("create table if not exists members (id int auto_increment, name varchar(3), password varchar(20), primary key(id))")39    cursor.execute("create table if not exists update_status (id int auto_increment, object varchar(5), id_ext int, content varchar(1000), primary key(id))")40    41       #---------------------- creating the extended id -----------------------42    id_ext=""43    date_break=coffee_break[0]44    day_break=str(date_break[0])45    month_break=str(date_break[1])46    if(len(month_break)==1):          #adding "0" if month has 1 digit47        month_break="0"+str(date_break[1])48    if(len(day_break)==1):            #adding "0" if day has 1 digit49        day_break="0"+str(date_break[0])50    id_ext=str(date_break[2])+month_break+day_break51    52    total=053    cursor.execute("SELECT id_ext FROM breaks WHERE id_ext like '"+id_ext+"%'")    #searching for breaks of the same day as enterd break54    ids=cursor.fetchall()55    ids=list(ids)56    for i in range(len(ids)):57        ids[i]=int(ids[i][0])58    if len(ids)==0:59        id_ext=id_ext+"01"60    else:61        id_ext=str(max(ids)+1)6263    temp1=""                                    #converting coffee_break into a list of strings for instertion into database64    temp2=""65    coffee_break_str=[]66    coffee_break_str.append(date_break)6768    for i in range(len(coffee_break[1])):69        temp1=temp1+str(coffee_break[1][i])70        temp2=temp2+str(coffee_break[2][i])71        if i<(len(coffee_break[1])-1):72            temp1=temp1+"-"73            temp2=temp2+"-"74    coffee_break_str.append(temp1)75    coffee_break_str.append(temp2)76    77    cursor.execute("INSERT INTO breaks (id_ext, day, month, year) VALUES ("+id_ext+","+str(date_break[0])+","+str(date_break[1])+","+str(date_break[2])+")")78    cursor.execute("INSERT INTO drinkers (id_ext, persons, coffees) VALUES ("+id_ext+",'"+str(coffee_break_str[1])+"','"+str(coffee_break_str[2])+"')")79    #cursor.execute("select * from drinkers")80    #temp=cursor.fetchall()81    #for row in temp:82    #    print(row)83    print("Coffee break saved!")84    print(id_ext+", "+str(coffee_break_str[1])+", "+str(coffee_break_str[2]))8586    #--------------------- writing into each person's list -------------------87    persons=coffee_break[1]88    coffees=coffee_break[2]8990    for i in range(len(persons)):91        cursor.execute("create table if not exists mbr_"+persons[i]+" (id_ext char(10), n_coffees int, primary key(id_ext), CONSTRAINT fk_member_"+persons[i]+"_break_ID_ext FOREIGN KEY(id_ext) REFERENCES breaks(id_ext) ON DELETE CASCADE)")     #creating a table for each individual person92        cursor.execute("insert into mbr_"+persons[i]+" (id_ext, n_coffees) values (%s, %s)", (id_ext, coffees[i]))              #writes break id and coffees into personal table93        cursor.execute("select count(*) from members where name='"+persons[i]+"'")                                                #checks if person is already written in members table94        temp=cursor.fetchone()95        temp=int(temp[0])96        if temp==0:97            cursor.execute("insert into members (name) values ('"+str(persons[i])+"')")                                           #writes person into members table98                           99100    #---------------------- writing break length table ------------------------101    cursor.execute("create table if not exists break_lengths (id int auto_increment, id_ext char(10), length time(6), primary key(id), CONSTRAINT fk_breaklen_break_ID_ext FOREIGN KEY(id_ext) REFERENCES breaks(id_ext) ON DELETE CASCADE)")102    cursor.execute("insert into break_lengths (id_ext, length) values (%s, %s)",(id_ext,breaklen))103104    #writing update_status table105    cursor.execute("select max(id_ext) from breaks")106    tmp = cursor.fetchall()107    cursor.execute("update update_status set id_ext = "+str(tmp[0][0])+" where object = 'database'")108    109    110    db.commit()111    #cursor.execute("select * from drinkers")112    #databases=cursor.fetchall()113    #for row in databases:114    #    print(row)115    #print("--------------------")116    db.close()117118119    #---------------------- checking for user and password --------------------120121def safety_check(command):122    status=command123    sfycheck_fld = Tk()124    sfycheck_fld.geometry("400x100")125    sfycheck_fld.title("Safety Check")126    frame_sfycheck = LabelFrame(sfycheck_fld, width= 400, height=200, bd = 0)127    frame_sfycheck.place (x=0, y= 10)128    header_sfycheck=Label(frame_sfycheck, text="Please enter your user name and password:", fg="red", font=("Helvetica", 14))129    header_sfycheck.place(x=20, y = 0)130    user_inp=ttk.Entry(frame_sfycheck, text="", width=4)131    user_inp.place(x=120, y = 30)132    pw_inp=ttk.Entry(frame_sfycheck, show="*", text="", width=8)133    pw_inp.place(x=161, y = 30)134    conf_sfycheck=ttk.Button(frame_sfycheck, text="Delete this break", command=lambda: user_pw_database_search(sfycheck_fld,user_inp,pw_inp,status) )135    conf_sfycheck.place(x=119, y= 60)136    sfycheck_fld.bind('<Return>', (lambda event: user_pw_database_search(sfycheck_fld,user_inp,pw_inp,status)))137138def user_pw_database_search(sfycheck_fld,user_inp,pw_inp,status):139    user_inp=str(user_inp.get()).upper()140    pw_inp=str(pw_inp.get())141    142    #print(user_inp, pw_inp)143144    db = mysql.connect(user='PBTK', password='akstr!admin2', #connecting to mysql145                              host='127.0.0.1',146                              database='coffee_list')147    cursor=db.cursor(buffered=True)148    149    cursor.execute("use coffee_list")150    cursor.execute("SELECT * FROM members WHERE name='"+user_inp+"'")151    user_data=""152    user_data=cursor.fetchall()153    #print(user_data)154    if user_data==[]:155        sfycheck_fld.destroy()156        messagebox.showinfo("Log-In status", "No such User!")157        158    else:159        user_data_check=list(user_data[0])160    161        #print(user_data)162        #print(pw_inp)     163        164        if user_data_check[2]==pw_inp:165            sfycheck_fld.destroy()166167            if status=="delete_one":                            # to delete one break168                clear_ONE_break()169            elif status=="delete_db":                           # to clear the whole database170                if user_data_check[3]==1:171                    answer = messagebox.askokcancel("Confirmation", "Are you REALLY sure to clear the database?",icon="warning")172                    if answer:173                        answer = messagebox.askokcancel("Confirmation", "Final warning!",icon="warning")174                        if answer:175                            #clear_database()176                            messagebox.showinfo("Deletion status", "The database has successfully been cleared.")177                else:178                    messagebox.showerror("Access denied", "You do not have admin rights. Please contact your system administrator.")179        else:180            sfycheck_fld.destroy()181            messagebox.showinfo("Log-In status", "Wrong Password!")182183        return184            185    #---------------------- deleting a break by knowing id_ext ----------------186def clear_ONE_break():187    input_fld = Tk()188    input_fld.geometry("600x100")189    input_fld.title("Deleting a break from the databank")190    frame_ifld = LabelFrame(input_fld, width= 600, height=100, bd = 0)191    frame_ifld.place (x=0, y= 30)192    header_ifld=Label(input_fld, text="Please enter the coffee break ID you want to delete:", fg="red", font=("Helvetica", 14))193    header_ifld.place(x=70, y = 10)194    id_inp=ttk.Entry(frame_ifld, text="", width=20)195    id_inp.place(x=220, y = 30)196    conf_delete_break=ttk.Button(frame_ifld, text="Delete this break", command=lambda: conf_break_delete(input_fld,id_inp) )197    conf_delete_break.place(x=350, y=28)198    input_fld.bind('<Return>', (lambda event: conf_break_delete(input_fld,id_inp)))199        200def conf_break_delete(input_fld,id_inp):201    #print(str(id_inp.get()).upper())202    del_ID=[]203    del_ID.append(str(id_inp.get()).upper())204    del_ID=str(del_ID[0])205    print("Coffee break deleted: "+del_ID)206207    db = mysql.connect(user='PBTK', password='akstr!admin2', #connecting to mysql208                              host='127.0.0.1',209                              database='coffee_list')210    cursor=db.cursor(buffered=True)211    212    cursor.execute("use coffee_list")213    cursor.execute("SELECT * FROM breaks WHERE id_ext='"+del_ID+"'")214    del_break=""215    del_break=cursor.fetchall()216    #print(del_break)217    218    if del_break != []:219        cursor.execute("DELETE FROM breaks WHERE id_ext='"+del_ID+"'")220221        #writing update_status table222        cursor.execute("select max(id_ext) from breaks")223        tmp = cursor.fetchall()224        cursor.execute("update update_status set id_ext = "+str(tmp[0][0])+" where object = 'database'")225226        input_fld.destroy()227        messagebox.showinfo("Deletion status", "This break has successfully been deleted.")228             229    else:230        input_fld.destroy()231        messagebox.showinfo("Deletion status", "This break does not exist, therefore nothing was deleted.")232233        234        235    236    db.commit()237    db.close    238239    #------------------- deleting the whole database --------------------------------------240def clear_database():241    db = mysql.connect(user='PBTK', password='akstr!admin2',242                              host='127.0.0.1',243                              database='coffee_list')244    cursor=db.cursor()245246    cursor.execute("use coffee_list")247    cursor.execute("SHOW tables")248    databases=cursor.fetchall()249    #print(databases)250    #print("yes")251    cursor.execute("select name from members")252    mbrs=cursor.fetchall()253    mbrs=list(mbrs)254    for i in range(len(mbrs)):255        cursor.execute("drop table if exists mbr_"+mbrs[i][0])256    257    cursor.execute("drop table if exists break_ID,breaks, drinkers, members, total_coffees, break_lengths")258    cursor.execute("SHOW tables")259    databases=cursor.fetchall()260    #print(databases)261    db.commit()262    db.close()263264   265    #------------------------- reading breaks from 2021 into database ---------------------266def breaks_2021():267    db = mysql.connect(user='PBTK', password='akstr!admin2',268                              host='127.0.0.1',269                              database='coffee_list')270    cursor=db.cursor()271272    cursor.execute("use coffee_list")273274    inp = []275    file = open("breaks_2021.txt","r")276    lines = file.readlines()277    file.close()278    persons=['TK','PB','NV','DB','FLG','SHK','TB']279    for line in lines:280        #print(line)281        #inp.append(list(map(int,line.split())))282        inp=list(map(int,line.split()))                     #getting lines from input file283        284        cursor.execute("SELECT * FROM breaks WHERE id_ext='"+str(inp[0])+"'")   #check if break is already in database285        exists=""286        exists=cursor.fetchall()287        if exists==[]:288            #print(str(inp[0])+","+str(inp[0])[0:4]+","+str(inp[0])[4:6]+","+str(inp[0])[6:8])289            290            temp1=""291            temp2=""292            temp3=0293            temp4=0294            for j in range(7):                              #checking how many persons took part in break295                if inp[j+1]!=0:296                    temp3+=1297298            cursor.execute("insert into breaks (id_ext, year, month, day) VALUES ("+str(inp[0])+","+str(inp[0])[0:4]+","+str(inp[0])[4:6]+","+str(inp[0])[6:8]+")")299            300            for j in range(7):                              #creating string for input into drinkers table301                if inp[j+1]!=0:302                    temp1+=persons[j]303                    temp2+=str(inp[j+1])304                    temp4+=1305                    if temp4 < temp3:306                        temp1+="-"307                        temp2+="-"308                    print(inp)309                    cursor.execute("create table if not exists mbr_"+persons[j]+" (id_ext char(10), n_coffees int, primary key(id_ext), CONSTRAINT fk_member_"+persons[j]+"_break_ID_ext FOREIGN KEY(id_ext) REFERENCES breaks(id_ext) ON DELETE CASCADE)")310                    cursor.execute("insert into mbr_"+persons[j]+" (id_ext, n_coffees) values (%s, %s)", (inp[0], inp[j+1]))311            312            cursor.execute("INSERT INTO drinkers (id_ext, persons, coffees) VALUES ("+str(inp[0])+",'"+temp1+"','"+temp2+"')")313314    db.commit()
...preprocessing.py
Source:preprocessing.py  
...20# Ne pas oublier de dl toutes les libs21#nltk.download()22path = "./tmp/"23##### PREPROCESSING ######24def del_break(file):25    '''26     Remove breaks from a text27    '''28    f = open(file, encoding = "utf8")29    raw = f.read()30    raw = raw.replace('\n','')31    f.close()32    #output= open(path + file, "w", encoding="utf8")33    #print(raw, file=output)34    #output.close()35def sentence_tokenize(file, language):36    '''37        Separate texte into indexed sentences.38    '''39    # ATTENTION AU FORMAT DES FICHIERS sinon erreurs possibles -> pour twitter uft840    # Il faudra adapter le path pour les fichiers des CGUs41    if isinstance(file, str) and file.endswith(".txt"):42        del_break(file)43        f = open(file, encoding="utf8")44        raw = f.read()45        raw = raw.replace('\n\n', '. ').replace('\n', ' ')46        f.close()47    48    elif isinstance(file, str): 49        raw = file.replace("\n\n", '. ').replace('\n', " ")50    else :51        return " ERROR TYPE"52    # l'objet JSON53    data_stopwords = {}54    data = {}55    # segmentation par phrase56    stop_words = set(stopwords.words(language))...03_❌_Delete_coffee_or_break.py
Source:03_❌_Delete_coffee_or_break.py  
1import streamlit as st2from common_functions import *3import pandas as pd4st.set_page_config(page_title="Coffee list",page_icon="coffee",layout="wide")5    #---------------------- deleting a break by knowing id_ext ----------------6def clear_one_break(del_id, test):7    db = init_connection()8    cursor = db.cursor(buffered=True)9    10    if del_id == "":11         st.warning("Please enter a break ID")12    else:13        cursor.execute("SELECT * FROM breaks WHERE id_ext='"+del_id+"'")14        del_break=cursor.fetchall()15        if del_break != []:16            cursor.execute("DELETE FROM breaks WHERE id_ext='"+del_id+"'")17            cursor.execute("delete from break_sizes where id_ext ='"+del_id+"'")18            cursor.execute("update update_status set last_break = timestamp(subdate(current_date, 1))")19            st.success("Break "+del_id+" has successfully been deleted.")20        else:21           st.error("Break "+del_id+" does not exist, therefore nothing was deleted.")22		23    db.commit()24    db.close()25    26#----------------------- check whether break ID was entered or not --------------------------27def delete_one_coffee_check(del_id,del_person):28    if del_id=="":29        del_id = last_breaks[len(last_breaks)-1][0]30    delete_one_coffee(del_id,del_person)31    32    33	 #---------------------- deleting a coffee from a break ----------------34def delete_one_coffee(id_ext, name):35	db = init_connection()36	cursor = db.cursor(buffered=True)37	38	cursor.execute("select persons, coffees from drinkers where id_ext = '"+id_ext+"'")39	tmp=cursor.fetchall()40	persons = tmp[0][0].split("-")41	coffees = tmp[0][1].split("-")42	for i in range(len(persons)):43		if persons[i] == name.upper():44			coffees[i] = int(coffees[i]) - 145			cursor.execute("update mbr_"+name.upper()+" set n_coffees = "+str(coffees[i])+" where id_ext = '"+id_ext+"'")46		if coffees[i] == 0:47			cursor.execute("delete from mbr_"+name.upper()+" where id_ext = '"+id_ext+"'")48			49			cursor.execute("select size from break_sizes where id_ext = '"+id_ext+"'")50			tmp1 = cursor.fetchall()51			cursor.execute("update break_sizes set size = "+str(int(tmp1[0][0])-1)+" where id_ext = '"+id_ext+"'")52	persons_new = ""53	coffees_new = ""54	for i in range(len(persons)):55		if coffees[i] == 0:56			pass57		else:58			if persons_new == "":59				persons_new += persons[i]60				coffees_new += str(coffees[i])61			else:62				persons_new = persons_new + "-" + persons[i]63				coffees_new = coffees_new + "-" + str(coffees[i])64	if persons_new == "":65		cursor.execute("DELETE FROM breaks WHERE id_ext='"+id_ext+"'")66		cursor.execute("delete from break_sizes where id_ext = '"+id_ext+"'")67	else:68		cursor.execute("update drinkers set persons = '"+persons_new+"' where id_ext = '"+id_ext+"'")69		cursor.execute("update drinkers set coffees = '"+coffees_new+"' where id_ext = '"+id_ext+"'")70	db.commit()71	db.close()72    73    74    75    76    77########################################################################################################################################################################78#####################################################    MAIN    #######################################################################################################79########################################################################################################################################################################80st.subheader("**:x:** Delete a coffee break")81if 'logged_in' not in st.session_state or 'user_name' not in st.session_state or 'admin' not in st.session_state or 'attempt' not in st.session_state:82    st.warning("Warning! Your session was terminated due to inactivity. Please return to home to restart it and regain access to all features.")83else:84	85	if st.session_state.admin != "1":86	  st.warning("You do not have the permission to delete a coffee or break. Please contact a system administrator for further information.")87	elif st.session_state.admin == "1":88	  st.markdown("Please enter the extended ID of the break you want to delete.")89	  last_breaks=get_last_breaks(10)90	  col1,col2,col3 = st.columns([1,0.5,3])91	  del_id = col1.text_input("Extended ID of break", placeholder=last_breaks[len(last_breaks)-1][0])92	  df=pd.DataFrame(last_breaks,columns=['Extended ID','Date','Drinkers','Coffees'])93	  col3.markdown("Last 10 breaks")94	  col3.dataframe(df, width=600, height=400)95	  delete = col1.button("Delete break", on_click=clear_one_break, args=(del_id,""))96	  col1.write("-" * 34)97	  del_person = col1.text_input("Delete for person", placeholder="Username")98	  col1.button("Delete coffee from break", on_click=delete_one_coffee_check, args=(del_id,del_person))99#------- footer ----------------100footer="""<style>101.footer {102position: fixed;103left: 0;104bottom: 0;105width: 100%;106background-color: white;107color:  grey;108text-align: center;109}110</style>111<div class="footer">112<p>Developed by P. C. Brehm and T. Kalisch. Web design by T. Kalisch <a style='display: block; text-align: center</a></p>113</div>114"""...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
