import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import showinfo
import tkinter.font as tkFont
import sqlite3, time, datetime, random

name_of_db = 'inventory_master.db'
my_conn = sqlite3.connect(name_of_db)
cdb = my_conn.cursor()

def create_table():
    cdb.execute(
        'CREATE TABLE IF NOT EXISTS customer_master('
        'idno INTEGER PRIMARY KEY,'
        'datestamp TEXT, '
        'customer_name TEXT, '
        'address TEXT, '
        'town TEXT, '
        'post_code TEXT, '
        'contact TEXT)')

def show_ID():
    frmList = tk.Tk()
    frmList.title("List of customer")
    width = 665
    height = 500
    screenwidth = frmList.winfo_screenwidth()
    screenheight = frmList.winfo_screenheight()
    alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    frmList.geometry(alignstr)
    frmList.resizable(width=False, height=False)
    customerID = txtID.get()
    txtName.focus_set()
    txtName.insert(INSERT,"Hello")
    data_set = my_conn.execute("SELECT * FROM customer_master WHERE idno=?", (customerID,))
    # btnFullName.grid(columnspan=2, padx=15, pady=15)
    output_data(data_set, frmList)
    clear_form()

def show_Name():
    frmList = tk.Tk()
    frmList.title("List of customer")
    width = 665
    height = 500
    screenwidth = frmList.winfo_screenwidth()
    screenheight = frmList.winfo_screenheight()
    alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    frmList.geometry(alignstr)
    frmList.resizable(width=False, height=False)
    customerName = txtName.get()
    data_set = my_conn.execute("SELECT * FROM customer_master WHERE customer_name like?", (customerName,))
    # btnFullName.grid(columnspan=2, padx=15, pady=15)
    output_data(data_set, frmList)
    clear_form()

def show_Contact():
    frmList = tk.Tk()
    frmList.title("List of customer")
    width = 665
    height = 500
    screenwidth = frmList.winfo_screenwidth()
    screenheight = frmList.winfo_screenheight()
    alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    frmList.geometry(alignstr)
    frmList.resizable(width=False, height=False)
    contact = txtContact.get()
    data_set = my_conn.execute("SELECT * FROM customer_master WHERE contact like?", (contact,))
    # btnFullName.grid(columnspan=2, padx=15, pady=15);2
    output_data(data_set, frmList)
    clear_form()

def update_record():
    with my_conn:
        customer_id = txtID.get()
        customer_name = txtName.get()
        address = txtAddress.get()
        town = txtTown.get()
        post_code = txtPostCode.get()
        contact = txtContact.get()
        cdb.execute("UPDATE customer_master SET customer_name=?, address=?, town=?, post_code=?, contact=? WHERE idno=?",
                    (customer_name, address, town, post_code, contact, customer_id))
        my_conn.commit()
        msg = f'Record Successfully Saved!'
        showinfo(title='Information', message=msg)
    clear_form()

def delete_record():
    with my_conn:
        customer_id = txtID.get()
        cdb.execute("DELETE FROM customer_master WHERE idno=?", (customer_id,))
        my_conn.commit()
        clear_form()

def output_data(data_set, frmList):
    i = 0  # row value inside the loop
    for person in data_set:
        for j in range(len(person)):
            e = Entry(frmList, width=15, fg='black')
            e.grid(row=i, column=j)
            e.insert(END, person[j])
        i = i + 1
    return frmList

def clear_form():
    txtID.delete(0, END)
    txtName.delete(0, END)
    txtAddress.delete(0, END)
    txtTown.delete(0, END)
    txtContact.delete(0, END)
    txtPostCode.delete(0, END)

def btnClose_Command():
    clear_form()
    exit()

create_table()

frmCustomerUpdate = tk.Tk()
frmCustomerUpdate.title("Customer Update")
width = 513
height = 364
screenwidth = frmCustomerUpdate.winfo_screenwidth()
screenheight = frmCustomerUpdate.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
frmCustomerUpdate.geometry(alignstr)
frmCustomerUpdate.resizable(width=False, height=False)

txtID = tk.Entry(frmCustomerUpdate)
txtID["borderwidth"] = "1px"
ft = tkFont.Font(family='Times', size=10)
txtID["font"] = ft
txtID["fg"] = "#333333"
txtID["justify"] = "center"
txtID["text"] = "Customer ID"
txtID.place(x=100, y=60, width=251, height=30)

txtName = tk.Entry(frmCustomerUpdate)
txtName["borderwidth"] = "1px"
ft = tkFont.Font(family='Times', size=10)
txtName["font"] = ft
txtName["fg"] = "#333333"
txtName["justify"] = "left"
txtName["text"] = "Customer Name"
txtName.place(x=100, y=110, width=251, height=30)

txtAddress = tk.Entry(frmCustomerUpdate)
txtAddress["borderwidth"] = "1px"
ft = tkFont.Font(family='Times', size=10)
txtAddress["font"] = ft
txtAddress["fg"] = "#333333"
txtAddress["justify"] = "left"
txtAddress["text"] = "Address"
txtAddress.place(x=100, y=160, width=250, height=30)

txtTown = tk.Entry(frmCustomerUpdate)
txtTown["borderwidth"] = "1px"
ft = tkFont.Font(family='Times', size=10)
txtTown["font"] = ft
txtTown["fg"] = "#333333"
txtTown["justify"] = "left"
txtTown["text"] = "Town"
txtTown.place(x=100, y=210, width=248, height=30)

txtPostCode = tk.Entry(frmCustomerUpdate)
txtPostCode["borderwidth"] = "1px"
ft = tkFont.Font(family='Times', size=10)
txtPostCode["font"] = ft
txtPostCode["fg"] = "#333333"
txtPostCode["justify"] = "left"
txtPostCode["text"] = "Post Code"
txtPostCode.place(x=100, y=260, width=248, height=30)

txtContact = tk.Entry(frmCustomerUpdate)
txtContact["borderwidth"] = "1px"
ft = tkFont.Font(family='Times', size=10)
txtContact["font"] = ft
txtContact["fg"] = "#333333"
txtContact["justify"] = "left"
txtContact["text"] = "Contact"
txtContact.place(x=100, y=310, width=247, height=30)

lblID = tk.Label(frmCustomerUpdate)
ft = tkFont.Font(family='Times', size=10)
lblID["font"] = ft
lblID["fg"] = "#333333"
lblID["justify"] = "left"
lblID["text"] = "Customer ID"
lblID.place(x=10, y=60, width=89, height=30)

lblName = tk.Label(frmCustomerUpdate)
ft = tkFont.Font(family='Times', size=10)
lblName["font"] = ft
lblName["fg"] = "#333333"
lblName["justify"] = "left"
lblName["text"] = "Customer Name"
lblName.place(x=10, y=110, width=91, height=30)

lblAddress = tk.Label(frmCustomerUpdate)
ft = tkFont.Font(family='Times', size=10)
lblAddress["font"] = ft
lblAddress["fg"] = "#333333"
lblAddress["justify"] = "left"
lblAddress["text"] = "Address"
lblAddress.place(x=10, y=160, width=91, height=30)

lblTown = tk.Label(frmCustomerUpdate)
ft = tkFont.Font(family='Times', size=10)
lblTown["font"] = ft
lblTown["fg"] = "#333333"
lblTown["justify"] = "left"
lblTown["text"] = "Town"
lblTown.place(x=10, y=210, width=92, height=30)

lblPostCode = tk.Label(frmCustomerUpdate)
ft = tkFont.Font(family='Times', size=10)
lblPostCode["font"] = ft
lblPostCode["fg"] = "#333333"
lblPostCode["justify"] = "left"
lblPostCode["text"] = "Post Code"
lblPostCode.place(x=10, y=260, width=91, height=30)

lblContact = tk.Label(frmCustomerUpdate)
ft = tkFont.Font(family='Times', size=10)
lblContact["font"] = ft
lblContact["fg"] = "#333333"
lblContact["justify"] = "left"
lblContact["text"] = "Mobile No."
lblContact.place(x=10, y=310, width=91, height=30)

lblTitle = tk.Label(frmCustomerUpdate)
ft = tkFont.Font(family='Times', size=22)
lblTitle["font"] = ft
lblTitle["fg"] = "#333333"
lblTitle["justify"] = "center"
lblTitle["text"] = "CUSTOMER UPDATE"
lblTitle.place(x=10, y=10, width=488, height=37)

btncustomerID = tk.Button(frmCustomerUpdate)
btncustomerID["bg"] = "#efefef"
ft = tkFont.Font(family='Times', size=10)
btncustomerID["font"] = ft
btncustomerID["fg"] = "#000000"
btncustomerID["justify"] = "center"
btncustomerID["text"] = "Search Customer ID"
btncustomerID.place(x=370, y=60, width=130, height=30)
btncustomerID["command"] = show_ID

btncustomerName = tk.Button(frmCustomerUpdate)
btncustomerName["bg"] = "#efefef"
ft = tkFont.Font(family='Times', size=10)
btncustomerName["font"] = ft
btncustomerName["fg"] = "#000000"
btncustomerName["justify"] = "center"
btncustomerName["text"] = "Search Customer Name"
btncustomerName.place(x=370, y=110, width=130, height=30)
btncustomerName["command"] = show_Name

btnMobile = tk.Button(frmCustomerUpdate)
btnMobile["bg"] = "#efefef"
ft = tkFont.Font(family='Times', size=10)
btnMobile["font"] = ft
btnMobile["fg"] = "#000000"
btnMobile["justify"] = "center"
btnMobile["text"] = "Search Mobile No."
btnMobile.place(x=370, y=160, width=129, height=30)
btnMobile["command"] = show_Contact

btnUpdate = tk.Button(frmCustomerUpdate)
btnUpdate["bg"] = "#efefef"
ft = tkFont.Font(family='Times', size=10)
btnUpdate["font"] = ft
btnUpdate["fg"] = "#000000"
btnUpdate["justify"] = "center"
btnUpdate["text"] = "Update"
btnUpdate.place(x=370, y=210, width=128, height=30)
btnUpdate["command"] = update_record

btnDelete = tk.Button(frmCustomerUpdate)
btnDelete["bg"] = "#efefef"
ft = tkFont.Font(family='Times', size=10)
btnDelete["font"] = ft
btnDelete["fg"] = "#000000"
btnDelete["justify"] = "center"
btnDelete["text"] = "Delete"
btnDelete.place(x=370, y=260, width=126, height=30)
btnDelete["command"] = delete_record

btnClose = tk.Button(frmCustomerUpdate)
btnClose["bg"] = "#efefef"
ft = tkFont.Font(family='Times', size=10)
btnClose["font"] = ft
btnClose["fg"] = "#000000"
btnClose["justify"] = "center"
btnClose["text"] = "Close"
btnClose.place(x=370, y=310, width=126, height=30)
btnClose["command"] = btnClose_Command

frmCustomerUpdate.mainloop()  # run form by default


import pygame

pygame.init()

pygame.display.set_caption("WannabePong")

size = 800, 600
screen = pygame.display.set_mode(size)
width, height = size
speed = [1, 1]
bgc = 255, 255, 255
fontControls = pygame.font.SysFont("monospace", 16)
font = pygame.font.SysFont("monospace", 26)
fontCount = pygame.font.SysFont("monospace", 42)
pelota = pygame.image.load("pelota.png")
pelotaRect = pelota.get_rect()
palaRoja = pygame.image.load("palaRoja.png")
palaRojaRect = palaRoja.get_rect()
palaAzul = pygame.image.load("palaAzul.png")
palaAzulRect = palaAzul.get_rect()
divisor = pygame.image.load("divisor.png")
divisorRect = divisor.get_rect()
strikesRojo = 0
strikesAzul = 0
countdown = 10
run = True

divisorRect.move_ip(400, 0)
palaRojaRect.move_ip(1, 300)
palaAzulRect.move_ip(773, 300)

while countdown > 0:
  count = fontCount.render("{0}".format(countdown), 1, (0,0,0))
  redControls = fontControls.render("Moves with W and S keys", 1, (0,0,0))
  blueControls = fontControls.render("Moves with UP and DOWN arrows", 1, (0,0,0))
  screen.fill(bgc)
  screen.blit(redControls, (5, 50))
  screen.blit(blueControls, (505, 50))
  screen.blit(count, (388, 250))
  pygame.display.flip()
  pygame.time.wait(1000)
  countdown -= 1

while run:
  pygame.time.delay(2)
  pelotaRect = pelotaRect.move(speed)
  keys = pygame.key.get_pressed()
  strikesRojoDisplay = font.render("Strikes: {0}".format(strikesRojo), 1, (0,0,0))
  strikesAzulDisplay = font.render("Strikes: {0}".format(strikesAzul), 1, (0,0,0))
  winnerRojo = font.render("RED WINS!", 1, (0,0,0))
  winnerAzul = font.render("BLUE WINS!", 1, (0,0,0))

  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      run = False
  if keys[pygame.K_w] and palaRojaRect.top <= 0:
    palaRojaRect = palaRojaRect.move(0, 0)
  elif keys[pygame.K_w]:
    palaRojaRect = palaRojaRect.move(0, -1)
  if keys[pygame.K_s] and palaRojaRect.bottom >= height:
    palaRojaRect = palaRojaRect.move(0, 0)
  elif keys[pygame.K_s]:
    palaRojaRect = palaRojaRect.move(0, 1)
  if keys[pygame.K_UP] and palaAzulRect.top <= 0:
    palaAzulRect = palaAzulRect.move(0, 0)
  elif keys[pygame.K_UP]:
    palaAzulRect = palaAzulRect.move(0, -1)
  if keys[pygame.K_DOWN] and palaAzulRect.bottom >= height:
    palaAzulRect = palaAzulRect.move(0, 0)
  elif keys[pygame.K_DOWN]:
    palaAzulRect = palaAzulRect.move(0, 1)
  if palaRojaRect.colliderect(pelotaRect):
    speed[0] = -speed[0]
  if palaAzulRect.colliderect(pelotaRect):
    speed[0] = -speed[0]
  if pelotaRect.left <= 0 or pelotaRect.right >= width:
    speed[0] = -speed[0]
    if pelotaRect.left <= 0:
      strikesRojo += 1
    elif pelotaRect.right >= width:
      strikesAzul += 1
  if pelotaRect.top <= 0 or pelotaRect.bottom >= height:
    speed[1] = -speed[1]
  if strikesRojo == 3 or strikesAzul == 3:
    run = False

  screen.fill(bgc)
  screen.blit(divisor, divisorRect)
  screen.blit(pelota, pelotaRect)
  screen.blit(palaRoja, palaRojaRect)
  screen.blit(palaAzul, palaAzulRect)
  screen.blit(strikesRojoDisplay, (5, 10))
  screen.blit(strikesAzulDisplay, (633, 10))
  pygame.display.flip()

screen.fill(bgc)
if strikesRojo == 3:
  screen.blit(winnerAzul, (333, 250))
  pygame.display.flip()
elif strikesAzul == 3:
  screen.blit(winnerRojo, (333, 250))
  pygame.display.flip()
pygame.time.wait(5000)
pygame.QUIT()


from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import Dense
from keras.utils import np_utils
from tensorflow.keras.models import Sequential
import matplotlib.pyplot as plt
from scipy.io import loadmat
import numpy as np

def display(i):
    img = X[i]
    plt.title('Example'+ str(i)+ 'Label:'+str(Y[i])+ 'Predicted:'+str(ypred[i]))
    plt.imshow(img.reshape((28,28)),cmap=plt.cm.gray_r)
    plt.show()

def plot_accuracy(history):
    plt.plot(history.history['accuracy'])
    plt.plot(history.history['val_accuracy'])
    plt.title('Model accuracy')
    plt.ylabel('Accuracy')
    plt.xlabel('Epoch')
    plt.legend(['Train', 'Test'], loc='upper left')
    plt.show()

def plot_loss(history):
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('Model loss')
    plt.ylabel('Loss')
    plt.xlabel('Epoch')
    plt.legend(['Train', 'Test'], loc='upper left')
    plt.show()

mnist = loadmat('mnist-original')
X , Y = mnist['data'] , mnist['label']
X= X.T
Y = Y.T
X_train , X_test , Y_train , Y_test = train_test_split(X,Y,test_size=0.1,shuffle = True)
X_train , X_val , Y_train , Y_val = train_test_split(X_train,Y_train,test_size=0.2,shuffle = True)

X_train = X_train/255
X_test = X_test/255
X_val = X_val/255
Ytrain = np_utils.to_categorical(Y_train)
Ytest = np_utils.to_categorical(Y_test)
Yval = np_utils.to_categorical(Y_val)

model = Sequential()
model.add(Dense(784,input_shape=(784,),activation='relu',kernel_initializer='normal'))
model.add(Dense(10, activation = 'softmax',kernel_initializer='normal'))
model.compile(loss='categorical_crossentropy' , optimizer = 'adam' , metrics = ['accuracy'])

history = model.fit(X_train ,Ytrain,batch_size = 512 ,epochs=30,verbose=2, validation_data=(X_val,Yval))

test_accuracy = model.evaluate(x=X_test,y=Ytest,batch_size=200,verbose=2)
print("Test results : ", test_accuracy)

Ypred = model.predict(X)
ypred = []
for i in Ypred:
    ypred.append(np.argmax(i))

plot_accuracy(history)
plot_loss(history)


import re
import requests
from bs4 import BeautifulSoup

URL = "https://sourcesup.renater.fr/scm/viewvc.php/rec/2019-CONVECS/REC/"
page = requests.get(URL)

soup = BeautifulSoup(page.content, "html.parser")
for link in soup.find_all('a', href=True):
    print(link['href'])
    if 'name' in link:
        print(link['name'])
    m = re.search(r"/(\w+)\.rec", link["href"])
    if m is not None:
        print(m.group(1))
        name = m.group(1)
        URL = f"https://sourcesup.renater.fr/scm/viewvc.php/rec/2019-CONVECS/REC/{name}.rec?revision=3&view=co"

        page = requests.get(URL)
        print(page.content)
        f = open(f"rec/{name}.rec", "wb")
        f.write(page.content)
        f.close()