from tkinter import *
import tkinter.font as tkFont
import tkinter.ttk as ttk
import tkinter.messagebox as tkMsgBox
import tkinter as tk
from tkinter import ttk
import json
from eventos2 import NuevoEvento
from eventos3 import Evento

class Editar(ttk.Frame):

    def __init__(self, parent, marco):
        super().__init__(parent, padding=(20))
        self.parent = parent
        self.marco = marco
        parent.title("Calendario de eventos tp final upteco")
        parent.geometry("400x180+180+100")
        parent.configure(bg='orange')
        self.grid(sticky=(tk.N, tk.S, tk.E, tk.W))
        parent.columnconfigure(0, weight=1)
        parent.rowconfigure(0, weight=1)
        parent.resizable(False, False)
        parent.configure(bg='orange')

        self.id = None
        self.ingresar_nombre = tk.StringVar()
        self.ingresar_fecha = tk.StringVar()
        self.ingresar_hora = tk.StringVar()
        self.ingresar_descripcion = tk.StringVar()
        self.ingresar_importancia = tk.StringVar()

        ttk.Label(self, text="Nombre:").grid(row=1, column=1)
        ttk.Entry(self, textvariable=self.ingresar_nombre).grid(row=1, column=2)
        ttk.Label(self, text="Fecha:").grid(row=2, column=1)
        ttk.Entry(self, textvariable=self.ingresar_fecha).grid(row=2, column=2)
        ttk.Label(self, text="Hora:").grid(row=3, column=1)
        ttk.Entry(self, textvariable=self.ingresar_hora).grid(row=3, column=2)
        ttk.Label(self, text="Descripcion:").grid(row=4, column=1)
        ttk.Entry(self, textvariable=self.ingresar_descripcion).grid(row=4, column=2)
        ttk.Label(self, text=" Importancia:").grid(row=5, column=1)
        ttk.Entry(self, textvariable=self.ingresar_importancia).grid(row=5, column=2)

        ttk.Button(self, text="Guardar", command=self.editar_evento).grid(row=12, column=3)
        ttk.Button(self, text="Cerrar", command=parent.destroy).grid(row=12, column=4)

    def set_id(self, id):
        self.id = id

    def set_ingresar_nombre(self,nombre):
        self.ingresar_nombre.set(nombre)

    def set_ingresar_fecha(self, ingresar_fecha):
        self.ingresar_fecha.set(ingresar_fecha)

    def set_ingresar_hora(self, ingresar_hora):
        self.ingresar_hora.set(ingresar_hora)

    def set_ingresar_descripcion(self, ingresar_descripcion):
        self.ingresar_descripcion.set(ingresar_descripcion)

    def set_ingresar_importancia(self, ingresar_importancia):
        self.ingresar_importancia.set(ingresar_importancia)

    def editar_evento(self):
        evento = Evento()
        evento.set_id(self.id)
        evento.set_nombre(self.ingresar_nombre.get())
        evento.set_fecha(self.ingresar_fecha.get())
        evento.set_hora(self.ingresar_hora.get())
        evento.set_descripcion(self.ingresar_descripcion.get())
        evento.set_importancia(self.ingresar_importancia.get())
        # eventos.editar(self.id)
        print(evento)
        print('el evento')
        # self.marco.clear_all()
        self.marco.get_elemento_lista(evento)

        self.parent.destroy()


from sklearn.externals import joblib
import numpy as np
from numpy import genfromtxt
from sklearn.svm import NuSVC
from sklearn import svm
if __name__ == "__main__":

	data = genfromtxt('data.csv', delimiter=',')

	y_train = []
	# print(data[4][0:10])
	for i in range(len(data)):
		y_train.append(data[i][10])
	x_train = np.delete(data, 10, 1)

	test_data = genfromtxt('test_data.csv', delimiter=',')

	y_test = []
	# print(test_data[4][0:10])
	for i in range(len(test_data)):
		y_test.append(test_data[i][10])
	x_test = np.delete(test_data, 10, 1)

	# ## NuSVC classification model
	# clf1 = NuSVC(gamma='scale', decision_function_shape='ovo')
	# clf1.fit(x_train, y_train)

	# print(clf1.score(x_test, y_test))
	# print(clf1.get_params(deep=True))

	## SVC classification model

	clf2 = svm.SVC(gamma='scale', decision_function_shape='ovo')
	clf2.fit(x_train, y_train)

	print(clf2.score(x_test, y_test))
	print(clf2.get_params(deep=True))

	##saving model
	# joblib.dump(clf1,"NuSVC_model.joblib")
	joblib.dump(clf2,"SVC_model.joblib")


import re
import time

class Kayit:
    def __init__(self, programad):
        self.programad=programad
        self.dongu=True

    def program(self):
        secim=self.menu()

        if secim=="1":
            print("Kayit ekleme menusune yonlendiriliyorsunuz...")
            time.sleep(3)
            self.kayitekle()

        if secim=="2":
            print("Kayit silme menusune yonlendiriliyorsunuz...")
            time.sleep(3)
            self.kayitcikar()

        if secim=="1":
            print("Kayitlara erisiliyor...")
            time.sleep(3)
            self.kayitoku()

        if secim=="4":
            self.cikis()

    def menu(self):
        def kontrol(secim):
            if re.search("[^1,4]", secim):
                raise Exception ("Lutfen 1 ve 4 arasinda gecerli bir secim yapiniz...")
            elif len(secim) !=1:
                raise Exception ("Lutfen 1 ve 4 arasinda gecerli bir secim yapiniz...")

        while True:
            try:
                secim=input("Merhabalar,{} otomasyon sistemine hosgeldiniz.\n\nLutfen yapmak istediginiz islemi seciniz...\n\n[1]-Kayit Ekle\n[2]-Kayit Sil\n[3]-Kayit oku\n[4]-Cikis\n\n".format(self.programad))
                kontrol(secim)
            except Exception as hata:
                print(hata)
                time.sleep(3)
            else:
                break
        return secim

    def kayitekle(self):
        def kontrolad(Ad):
            if Ad.isalpha()==False:
                raise Exception ("Adiniz sadece alfabetik karakterlerden olusmalidir...")
        while True:
            try:
                Ad=input("adiniz: ")
                kontrolad(Ad)
            except Exception as hataad:
                print(hataad)
                time.sleep(3)
            else:
                break

        def kontrolsoyad(Soyad):
            if Soyad.isalpha()==False:
                raise Exception ("Soyadiniz sadece alfabetik karakterlerden olusmalidir...")
        while True:
            try:
                Soyad=input("Soyadiniz: ")
                kontrolsoyad(Soyad)
            except Exception as hatasoyad:
                print(hatasoyad)
                time.sleep(3)
            else:
                break

        def kontrolyas(Yas):
            if Yas.isdigit()==False:
                raise Exception ("Yasiniz sadece rakamlardan olusmalidir...")
        while True:
            try:
                Yas=input("Yasiniz: ")
                kontrolyas(Yas)
            except Exception as hatayas:
                print(hatayas)
                time.sleep(3)
            else:
                break

        def kontroltc(TC):
            if TC.isdigit()==False:
                raise Exception ("Kimlik numaraniz sadece rakamlardan olusmalidir...")
            elif len(TC) != 11:
                raise Exception ("Kimlik numaraniz on bir rakamdan olusmalidir...")

        while True:
            try:
                TC=input("Kimlik numaraniz: ")
                kontroltc(TC)
            except Exception as hatatc:
                print(hatatc)
                time.sleep(3)
            else:
                break

        def kontrolmail(Mail):
            if not re.search("@" and ".com", Mail):
                raise Exception ("Gecerli bir mail adresi giriniz...")

        while True:
            try:
                Mail=input("Mail adresiniz: ")
                kontrolmail(Mail)
            except Exception as hatamail:
                print(hatamail)
                time.sleep(3)
            else:
                break

        with open("C:/Users/rahime/Desktop/Bilgiler.txt", "r", encoding="utf-8") as Dosya:
            satirsayisi=Dosya.readlines()
        if len(satirsayisi)==0:
            Id=1
        else:
            with  open("C:/Users/rahime/Desktop/Bilgiler.txt", "r", encoding="utf-8") as Dosya:
                 Id=int(Dosya.readlines()[-1].split("-")[0])+1

        with  open("C:/Users/rahime/Desktop/Bilgiler.txt", "a+", encoding="utf-8") as Dosya:
            Dosya.write("{} {} {} {} {}\n".format(Id, Ad, Soyad, TC, Yas, Mail))
            print("Veriler Islenmistir..")
        self.menudon()

    def kayitcikar(self):
        y=input("Lutfen silmek istediginiz kisinin ID numarasini giriniz..")
        with open("C:/Users/rahime/Desktop/Bilgiler.txt", "r", encoding="utf-8") as Dosya:
            liste=[]
            liste2=Dosya.readlines()
            for i in range(0,len(liste2)):
                liste.append(liste2[i].split("-")[0])
        del liste2[liste.index(y)]

        with open("C:/Users/rahime/Desktop/Bilgiler.txt", "w+", encoding="utf-8") as YeniDosya:
            for i in liste2:
                YeniDosya.write(i)
                print("Kayit Siliniyor...")

                time.sleep(3)

                print("Kayit basariyla silinmistir..")
            self.menudon()

    def kayitoku(self):

        with open("C:/Users/rahime/DEsktop/Bilgiler.txt", "r", encoding="utf-8") as Dosya:
            for i in Dosya:
                print(i)
            self.menudon()

    def cikis(self):
        print("Otomasyondan cikiliyor. Tesekkur ederiz..")
        time.sleep(3)
        self.dongu=False
        exit()

    def menudon(self):
        while True:
            x=input("Ana menuye donmek icin 6'ya, cikmak icin lutfen 5'e basiniz:...")
            if x=="6":
                print("Ana menuye donduruluyor...")
                time.sleep(3)
                self.program()
                break
            elif x=="5":
                self.cikis()
                break
            else:
                print("Lutfen gecerli bir secim yapiniz...")

Sistem=Kayit("Rahime Veritabani")
while Sistem.dongu:
    Sistem.program()


#!/usr/bin/env python3
# Display a countdown clock
# Useful for workshops.
# Can be used as a live countdown clock with OBS for on-line events.
# Specify the number of minutes, as a command line argument.
# Tested on MS-Windows. Remove winsound if you want to use it on Mac or Linux OS.
# (c) Rudiger Wolf 2020-11-09
# https://github.com/rnwolf/pyclockcountdown
#

import sys
import tkinter as tk
import winsound

def _create_circle(self, x, y, r, **kwargs):
    return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
tk.Canvas.create_circle = _create_circle

def _create_circle_arc(self, x, y, r, **kwargs):
    if "start" in kwargs and "end" in kwargs:
        kwargs["extent"] = kwargs["end"] - kwargs["start"]
        del kwargs["end"]
    return self.create_arc(x-r, y-r, x+r, y+r, **kwargs)
tk.Canvas.create_circle_arc = _create_circle_arc

class Count_down_App(tk.Tk):
    def __init__(self,seconds,scalingfactor=1.0):
        tk.Tk.__init__(self)
        self.scalingfactor = scalingfactor
        self.width = 990 * self.scalingfactor
        self.height = 450 * self.scalingfactor
        print(f"{self.width:.0f}x{self.height:.0f}")
        #self.geometry(f"{self.width:.0f}x{self.height:.0f}")
        #self.geometry("800x450")
        self.resizable(False,False)
        self.canvas = tk.Canvas(self, width=self.width, height=self.height)
        self.label_text = tk.StringVar()
        self.label_text.set("")
        self.label = tk.Label(self, text=self.label_text, width=8, anchor='sw')
        self.canvas.pack(fill="both",expand=False)
        self.label.pack()
        self.remaining = 0
        self.starting = seconds
        self.countdown(self.starting)

    def countdown(self, remaining = None):
        self.label.config(font=("Arial", 64))
        self.canvas.create_circle(self.width/3, self.height/4*2, (self.height/4*2), fill="blue", outline="#DDD", width=4)
        self.canvas.create_circle_arc(self.width/3, self.height/4*2, (self.height/4*2-4),
                fill="red",
                outline="",
                start=(0+90),
                end=(360/self.starting*(self.starting-self.remaining)+90))
        if remaining is not None:
            self.remaining = remaining

        if self.remaining <= 0:
            self.canvas.create_circle(self.width/3,  self.height/4*2, (self.height/4*2), fill="red", outline="#DDD", width=4)
            self.label.configure(text="STOP")
            # Probably play Windows default sound, if any is registered (because
            # "*" probably isn't the registered name of any sound).
            winsound.PlaySound("*", winsound.SND_ALIAS)
            #sys.stdout.write('\a')  # Make a beep in a cross platform way.
        else:
            mins,secs = divmod(self.remaining,60)
            #self.label_text.set("{min:2}:{secs:2}")
            labelstr=f"{mins:02.0f}:{secs:02.0f}"
            self.title("Countdown "+labelstr)     # Add a title
            self.label.configure(text=labelstr )  #"%d" % secs ) #self.remaining )
            self.remaining = self.remaining - 1
            self.after(1000, self.countdown)

if __name__ == "__main__":
    minutes = 5.0 # Default is 5 minutes countdown if none is specified.
    scalingfactor = 1.0 # Default scaling factor to make clock window bigger or smaller.
    if len(sys.argv) == 1:
        print("""
        Usage:

           python clockcountdown.py [Time in minutes (default=5.0)] [Clock Window scaling factor (default=1.0)]

        Example:

           python clockcountdown.py 10

           Will start a 10 minute countdown timer.
           If no number is provided then 5 minutes is assumed to be the default.

        Tip: Minimize timer window to pause clock.
        """)
    if len(sys.argv) >= 2:
        minutes = float(sys.argv[1:][0])
    if len(sys.argv) ==3:
        scalingfactor = float(sys.argv[1:][1])

    seconds = minutes * 60
    app = Count_down_App(seconds,scalingfactor)
    app.mainloop()


import math
#Example baseline ResNet 18
time_1 = 1.22
time_4 = 2.19
time_8 = 3.63
FLOPs_G = 1.83
Params_M = 11.70
ACC = 0.7098

def main():
    avg_time = (time_1 + time_4 + time_8)/3.0
    p = math.sqrt(math.pow(FLOPs_G,2)+math.pow(Params_M,2)+math.pow(avg_time,2))
    print("The complexity index ρ is",p)
    y = -14.6*math.pow(ACC,2)+2.5*ACC+2.9
    _lambda = 1/(1+math.pow(math.exp( 1 ) ,-y))
    TALES = (ACC*100)/(_lambda*p)
    print('TALES (Cost Effective Evaluation Metrics):',TALES)

if __name__ =="__main__":
    main()


import json
import uuid
import datetime
import xlsxwriter
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from io import BytesIO
import mysql.connector

# import xlsx2pdf.transformators

def generate_report(cursor, id, workbook, need_attendance=False, need_remarks='', need_pdf=False):
    def with_permission_fun(from_prefix, to_prefix, from_suffix, to_suffix):
        prefix = []
        if from_prefix and to_prefix:
            prefix.append(f"{from_prefix.strftime('%d-%m-%Y')} to {to_prefix.strftime('%d-%m-%Y')}")
        elif not from_prefix and to_prefix:
            prefix.append(f"{to_prefix.strftime('%d-%m-%Y')}")
        elif from_prefix and not to_prefix:
            prefix.append(f"{from_prefix.strftime('%d-%m-%Y')}")

        suffix = []
        if from_suffix and to_suffix:
            suffix.append(f"{from_suffix.strftime('%d-%m-%Y')} to {to_suffix.strftime('%d-%m-%Y')}")
        elif not from_suffix and to_suffix:
            suffix.append(f"{to_suffix.strftime('%d-%m-%Y')}")
        elif from_suffix and not to_suffix:
            suffix.append(f"{from_suffix.strftime('%d-%m-%Y')}")

        on_permission = []
        if prefix and suffix:
            on_permission.append(f"{prefix[0]} & {suffix[0]}")
        elif not prefix and suffix:
            on_permission.append(suffix[0])
        elif prefix and not suffix:
            on_permission.append(prefix[0])

        return on_permission

    def attendence_register(dep, year):
        query = "SELECT register_name FROM `attendance_register` WHERE department = %s AND year = %s;"
        cursor.execute(query, (dep, year))
        data = cursor.fetchall()

        return data

    def getdata(type, id):
        if type == 'el':
            cursor.reset()
            query = "SELECT `from`, `to`, `from_prefix`, `to_prefix`, `from_suffix`, `to_suffix`, `date_of_rejoin`, `total` FROM " + type + " WHERE id=" + id + "; "
            cursor.execute(query)
            data_final = cursor.fetchall()

            on_permission = []
            for i in data_final:
                on_permission.append(with_permission_fun(i[2], i[3], i[4], i[5]))
            remark = []
            for i in data_final:
                remark.append(attendence_register(data[0][2], i[0].year))
            remark = [item[0] for sublist in remark for item in sublist]

            data_final_updated = []
            for i, sublist in enumerate(data_final):
                columns_to_keep = sublist[:2] + ((on_permission[i],) if on_permission else ()) + sublist[6:] + ((remark[i],) if remark else ())
                data_final_updated.append(columns_to_keep)
            data_final_updated = [sublist + (type,) for sublist in data_final_updated]
            return data_final_updated
        else:
            cursor.reset()
            query = "SELECT `from`,`to`,`total`, `medical_fittness_on`, `from_prefix`, `to_prefix`, `from_suffix`, `to_suffix`, `doj` FROM " + type + " WHERE id=" + id + ";; "
            cursor.execute(query)
            data_final = cursor.fetchall()
            on_permission = []
            for i in data_final:
                on_permission.append(with_permission_fun(i[4], i[5], i[6], i[7]))
            remark = []
            for i in data_final:
                remark.append(attendence_register(data[0][2], i[0].year))
            remark = [item[0] for sublist in remark for item in sublist]
            data_final_updated = []
            for i, sublist in enumerate(data_final):
                columns_to_keep = sublist[:4] + ((on_permission[i],) if on_permission else ()) + sublist[8:] + ((remark[i],) if remark else ())
                data_final_updated.append(columns_to_keep)
            data_final_updated = [sublist + (type,) for sublist in data_final_updated]
            return data_final_updated

    def generate_random_name():
        random_uuid = str(uuid.uuid4())

        random_name = random_uuid[:8]
        return random_name

    query = f"SELECT * FROM `staff` WHERE id={id};"
    cursor.execute(query)
    data = cursor.fetchall()
    data_el = getdata('el', id)
    data_ml = getdata('ml', id)
    data_lop = getdata('lop', id)
    data_mtl = getdata('mtl', id)
    sorted_data = sorted(data_lop + data_el + data_ml + data_mtl, key=lambda x: x[0])
    xlname = generate_random_name()
    worksheet = workbook.add_worksheet("EL")
    worksheet.set_column('A:L', 12)

    merge_ranges = [
        (2, 0, 2, 3),
        (2, 4, 2, 11),
        (3, 0, 3, 3),
        (3, 4, 3, 11),
        (4, 0, 4, 3),
        (4, 4, 4, 11),
        (5, 0, 5, 3),
        (5, 4, 5, 11),
        (6, 0, 6, 3),
        (6, 4, 6, 11),
        (7, 0, 7, 11),
        (8, 0, 8, 4),
        (8, 5, 8, 10)

    ]
    cell_format_center = workbook.add_format({
        'align': 'center',  # Center alignment
        'text_wrap': True,  # Wrap text
        'valign': 'vcenter',  # Center vertically
        'border': 1
    })
    cell_format_left = workbook.add_format({
        'align': 'center',  # Center alignment
        'text_wrap': True,  # Wrap text
        'valign': 'vcenter',  # Center vertically
        'border': 1
    })

    # Perform the defined merges
    worksheet.merge_range(*(0, 0, 0, 11), 'Annexure -II', cell_format_center)
    worksheet.merge_range(*(1, 0, 1, 11), 'Anna univeristy chennai', cell_format_center)
    worksheet.merge_range(*merge_ranges[0], 'Name', cell_format_center)
    worksheet.merge_range(*merge_ranges[1], data[0][1], cell_format_left)
    worksheet.merge_range(*merge_ranges[2], 'Designation', cell_format_left)
    worksheet.merge_range(*merge_ranges[3], '', cell_format_left)
    worksheet.merge_range(*merge_ranges[4], 'Department', cell_format_left)
    worksheet.merge_range(*merge_ranges[5], "MBA" if data[0][2] == "MS" else data[0][2], cell_format_left)
    worksheet.merge_range(*merge_ranges[6], 'Date of joining in service', cell_format_left)
    worksheet.merge_range(*merge_ranges[7], data[0][3].strftime('%d-%m-%Y'), cell_format_left)
    worksheet.merge_range(*merge_ranges[8], 'Campus', cell_format_left)
    worksheet.merge_range(*merge_ranges[9], 'ANNA UNIVERSITY REGIONAL CAMPUS   -   TIRUNELVELI', cell_format_center)
    worksheet.merge_range(*merge_ranges[10], 'DETAILS OF LEAVE', cell_format_left)
    worksheet.merge_range(*merge_ranges[11], 'Earned Leave  (EL)', cell_format_left)
    worksheet.merge_range(*merge_ranges[12], 'Medical Leave  (ML)  /  Maternity Leave  (MTL) / Loss of pay (LOP)',
                          cell_format_left)
    worksheet.write('L9', 'Type of Leave', cell_format_left)
    if need_attendance:
        worksheet.write('M10', 'Attendance Register', cell_format_left)

    head_list = [['From', 'To', 'with permission on', 'Date of Joining on Duty after EL', 'Total No. of Days',
                  'From', 'To', 'Total No. of Days', 'Medical Fitness on', 'with permission on',
                  'Date of Joining on Duty after leave', '(ML/ EL/LOP/MTL)']
                 ]

    # Define the starting row
    start_row = 9

    # Iterate through each sublist and its values
    for sublist in head_list:
        column_index = 0  # Start writing from the first column
        for value in sublist:
            worksheet.write(start_row, column_index, value, cell_format_left)
            column_index += 1  # Move to the next column for the next value
        start_row += 1

    start_row = 10
    for sublist in sorted_data:
        # Start writing from the first column
        if sublist[-1] == 'el':
            column_index = 0
            for value in sublist:
                if value == 'el':
                    worksheet.write(start_row, 11, value.upper(), cell_format_left)
                elif isinstance(value, datetime.date):
                    worksheet.write(start_row, column_index, value.strftime('%d-%m-%Y'), cell_format_left)
                    column_index += 1
                elif isinstance(value, str) and value.startswith("AURCT"):
                    if need_attendance:
                        worksheet.write(start_row, 12, value, cell_format_left)
                elif isinstance(value, list):

                    if value:
                        worksheet.write(start_row, column_index, value[0], cell_format_left)
                    else:
                        worksheet.write(start_row, column_index, "-", cell_format_left)

                    column_index += 1

                elif isinstance(value, bytes):
                    byte_data = value
                    byte_data_str = byte_data.decode('utf-8')
                    str_data = json.loads(byte_data_str)
                    worksheet.write(start_row, column_index, str_data[0], cell_format_left)
                    column_index += 1
                else:
                    worksheet.write(start_row, column_index, value, cell_format_left)
                    column_index += 1  # Move to the next column for the next value
            for i in range(column_index, 11):
                worksheet.write(start_row, i, "-", cell_format_center)

            start_row += 1
        else:
            column_index = 5
            for value in sublist:
                if value == 'lop' or value == 'mtl' or value == 'ml':
                    worksheet.write(start_row, 11, value.upper(), cell_format_left)
                elif isinstance(value, datetime.date):
                    worksheet.write(start_row, column_index, value.strftime('%d-%m-%Y'), cell_format_left)
                    column_index += 1

                elif isinstance(value, str) and value.startswith("AURCT"):
                    if need_attendance:
                        worksheet.write(start_row, 12, value, cell_format_left)

                elif isinstance(value, bytes):
                    byte_data = value
                    byte_data_str = byte_data.decode('utf-8')
                    str_data = json.loads(byte_data_str)
                    print(str_data)
                    formatted_date = '-' if str_data[0] == '-' else datetime.datetime.strptime(str_data[0], "%Y-%m-%d")
                    worksheet.write(start_row, column_index,
                                    formatted_date.strftime('%d-%m-%Y') if isinstance(formatted_date,
                                                                                datetime.date) else formatted_date,
                                    cell_format_left)
                    column_index += 1

                elif isinstance(value, list):
                    if value:
                        worksheet.write(start_row, column_index, value[0], cell_format_left)
                    else:
                        worksheet.write(start_row, column_index, "-", cell_format_left)
                    column_index += 1

                else:
                    worksheet.write(start_row, column_index, value, cell_format_left)
                    column_index += 1  # Move to the next column for the next value
            for i in range(0, 5):
                worksheet.write(start_row, i, "-", cell_format_center)

            start_row += 1
    if need_remarks:
        worksheet.merge_range(*(start_row, 0, start_row, 12), need_remarks, cell_format_center)
    if need_pdf:
        return {"name": xlname, "type": "pdf"}
    else:
        return {"name": xlname, "type": "xlsx"}

if __name__ == "__main__":
    mydb = mysql.connector.connect(host="localhost", port="3306", user="root",
                                   database="facultyleavedb")

    cursor = mydb.cursor()
    workbook = xlsxwriter.Workbook("test.xlsx")
    generate_report(cursor, '21002', workbook)
    workbook.close()


import argparse
import os.path as osp
import mrcfile
import numpy as np

def getMaskCorrectedFSC(array1, array2, mask, samplingRate,
                        nIter=1, rndThr=0.8, rndOffset=4):

    unmaskedArray1 = np.fft.fftshift(np.fft.fftn(array1))
    unmaskedArray2 = np.fft.fftshift(np.fft.fftn(array2))

    if mask is not None:
        maskedArray1 = np.fft.fftshift(np.fft.fftn(array1*mask))
        maskedArray2 = np.fft.fftshift(np.fft.fftn(array2*mask))

    iSize = array1.shape[0]
    iSize2 = int(iSize/2)

    xV = np.arange(iSize) - iSize2
    XXmesh = np.meshgrid(xV, xV, xV, copy=False, indexing='ij')

    radii = np.zeros((iSize,)*3)

    for k in range(3):
        radii += XXmesh[k]**2
    radii = np.sqrt(radii)

    nShells = iSize2 + 1
    shellList = [None]*nShells

    for k in range(nShells):
        shellList[k] = np.where((radii >= k) * (radii < (k+1)))

    unmaskedCCF = np.real(unmaskedArray1 * unmaskedArray2.conj())
    unmaskedInt1 = np.real(unmaskedArray1 * unmaskedArray1.conj())
    unmaskedInt2 = np.real(unmaskedArray2 * unmaskedArray2.conj())

    if mask is not None:
        maskedCCF = np.real(maskedArray1 * maskedArray2.conj())
        maskedInt1 = np.real(maskedArray1 * maskedArray1.conj())
        maskedInt2 = np.real(maskedArray2 * maskedArray2.conj())

    unmaskedCCF_1D = np.zeros(nShells)
    unmaskedInt1_1D = np.zeros(nShells)
    unmaskedInt2_1D = np.zeros(nShells)

    if mask is not None:
        maskedCCF_1D = np.zeros(nShells)
        maskedInt1_1D = np.zeros(nShells)
        maskedInt2_1D = np.zeros(nShells)

    for k in range(nShells):
        unmaskedCCF_1D[k] = unmaskedCCF[shellList[k]].sum()
        unmaskedInt1_1D[k] = unmaskedInt1[shellList[k]].sum()
        unmaskedInt2_1D[k] = unmaskedInt2[shellList[k]].sum()
        if mask is not None:
            maskedCCF_1D[k] = maskedCCF[shellList[k]].sum()
            maskedInt1_1D[k] = maskedInt1[shellList[k]].sum()
            maskedInt2_1D[k] = maskedInt2[shellList[k]].sum()

    # FSC profiles
    unmaskedFSC = unmaskedCCF_1D/np.sqrt(unmaskedInt1_1D * unmaskedInt2_1D)
    maskedFSC = None
    correctedFSC = None
    phaseRndFSC = None
    if mask is not None:
        maskedFSC = maskedCCF_1D/np.sqrt(maskedInt1_1D * maskedInt2_1D)

        # Index for phase rondimization
        rndIdx = np.where(unmaskedFSC < rndThr)[0]

        if len(rndIdx) == 0:
            rndIdx = nShells - 1
        elif rndIdx[0] > 0:
            rndIdx = rndIdx[0]
        else:
            rndIdx = rndIdx[1]

        print(f'Phase randomization at pixel {rndIdx} =\
              {(iSize*samplingRate)/rndIdx:.2g} Å')

        rndMask = radii >= rndIdx
        nRnd = rndMask.sum()
        angleArray1 = np.angle(unmaskedArray1)
        angleArray2 = np.angle(unmaskedArray2)
        absArray1 = np.abs(unmaskedArray1)
        absArray2 = np.abs(unmaskedArray2)

    # We repeat the phase randomization to average

        correctedFSCum = np.zeros(nShells)
        phaseRndFSCum = np.zeros(nShells)

        for k in range(nIter):
            rndAngleArray1 = angleArray1.copy()
            rndAngleArray2 = angleArray2.copy()

            rndAngleArray1[rndMask] = np.random.rand(nRnd)*2*np.pi
            rndAngleArray2[rndMask] = np.random.rand(nRnd)*2*np.pi

            rndArray1FT = absArray1 * np.exp(1j*rndAngleArray1)
            rndArray2FT = absArray2 * np.exp(1j*rndAngleArray2)

            rndArray1 = np.fft.ifftn(np.fft.ifftshift(rndArray1FT))
            rndArray2 = np.fft.ifftn(np.fft.ifftshift(rndArray2FT))

            maskedRndArray1FT = np.fft.fftshift(np.fft.fftn(rndArray1*mask))
            maskedRndArray2FT = np.fft.fftshift(np.fft.fftn(rndArray2*mask))

            maskedRndCCF = np.real(maskedRndArray1FT * maskedRndArray2FT.conj())
            maskedRndInt1 = np.real(maskedRndArray1FT * maskedRndArray1FT.conj())
            maskedRndInt2 = np.real(maskedRndArray2FT * maskedRndArray2FT.conj())

            maskedRndCCF_1D = np.zeros(nShells)
            maskedRndInt1_1D = np.zeros(nShells)
            maskedRndInt2_1D = np.zeros(nShells)
            for k in range(nShells):
                maskedRndCCF_1D[k] = maskedRndCCF[shellList[k]].sum()
                maskedRndInt1_1D[k] = maskedRndInt1[shellList[k]].sum()
                maskedRndInt2_1D[k] = maskedRndInt2[shellList[k]].sum()

            maskedRndFSC = maskedRndCCF_1D / \
                np.sqrt(maskedRndInt1_1D * maskedRndInt2_1D)

            # Mask-corrected FSC
            correctedFSCTmp = maskedFSC.copy()
            correctedFSCTmp[rndIdx+rndOffset:] = \
                (maskedFSC[rndIdx+rndOffset:] - maskedRndFSC[rndIdx+rndOffset:]) /\
                (1 - maskedRndFSC[rndIdx+rndOffset:])
            correctedFSCum += correctedFSCTmp
            phaseRndFSCum += maskedRndFSC
            correctedFSC = correctedFSCum/nIter
            phaseRndFSC = phaseRndFSCum/nIter

    inv_resolution = np.arange(nShells) / (iSize*samplingRate)
    return inv_resolution, unmaskedFSC, maskedFSC, phaseRndFSC, correctedFSC

def determine_fsc_resolution(inv_resolution, fsc_values, threshold=0.143):

    index = np.where(fsc_values < threshold)[0][0]  #TODO: add try except for IndexError, probably caused by too tight mask
    inv_res_at_threshold = inv_resolution[index - 1] + (inv_resolution[index] - inv_resolution[index - 1]) * (
                threshold - fsc_values[index - 1]) / (fsc_values[index] - fsc_values[index - 1])
    res_at_threshold = 1 / inv_res_at_threshold
    return inv_res_at_threshold, res_at_threshold

def plot_fsc(ax, inv_resolution, fsc_values, inv_res_at_threshold, label):
    ax.plot(inv_resolution, fsc_values, label=label)
    ax.axvline(x=inv_res_at_threshold, color='r', linestyle='-.')
    ticks = inv_resolution[::10]
    ticks[0]=1/999
    ax.set_xticks(ticks)
    ax.set_xticklabels(np.round(1 / ticks, decimals=2))
    ax.set_xlabel('Resolution (Å)')
    ax.set_ylabel('FSC')

def getFSCResolution(array1, array2, mask, samplingRate, resolution_threshold=0.143):
    inv_resolution, unmaskedFSC, maskedFSC, phaseRndFSC, correctedFSC = \
        getMaskCorrectedFSC(array1, array2, mask, samplingRate)
    _, res_unmasked = determine_fsc_resolution(inv_resolution, unmaskedFSC, threshold=resolution_threshold)
    if maskedFSC is not None:
        _, res_masked = determine_fsc_resolution(inv_resolution, maskedFSC, threshold=resolution_threshold)
        _, res_phaseRnd = determine_fsc_resolution(inv_resolution, phaseRndFSC, threshold=resolution_threshold)
        _, res_corrected = determine_fsc_resolution(inv_resolution, correctedFSC, threshold=resolution_threshold)
    else:
        res_masked, res_phaseRnd, res_corrected = [None]*3
    return res_unmasked, res_masked, res_phaseRnd, res_corrected

if __name__ == "__main__":

    parser = argparse.ArgumentParser("FSC calculation")
    parser.add_argument("-i", "--inputMap", required=True, type=str, help="The input map or half map 1")
    parser.add_argument("-r", "--referenceMap", required=True, type=str, help="The reference map or half map 2")
    parser.add_argument("-m", "--mask", required=False, type=str, help="A mask to limit computations. It shoud have soft edges")
    parser.add_argument("-p", "--show_plot", action="store_true",
                        help="Show an interactive FSC resolution plot ")
    parser.add_argument("-o", "--plot_fname", required=False, type=str,
                        help="The filename for the plot to be saved")
    parser.add_argument("-t", "--resolution_threshold", required=False, type=float, default=0.143,
                        help="The thresold for the FSC resolution determination")
    args = parser.parse_args()

    threshold = args.resolution_threshold

    with mrcfile.open(osp.expanduser(args.inputMap)) as f:
        array1 = f.data.copy()
        samplingRate = float(f.voxel_size.x)
    with mrcfile.open(osp.expanduser(args.referenceMap)) as f:
        array2 = f.data.copy()
        assert round(samplingRate,3) == round(float(f.voxel_size.x),3), ("Error, input and reference map have different"
                                                                 " sampling rate")
    if args.mask is not None:
        with mrcfile.open(osp.expanduser(args.mask)) as f:
            mask = f.data.copy()
            assert round(samplingRate,3) == round(float(f.voxel_size.x),3), (f"Error, input map and mask have "
                                                                             f"different sampling rate "
                                                                             f"{samplingRate, f.voxel_size.x}")
    else:
        mask=None
    (inv_resolution, unmaskedFSC, maskedFSC,
     phaseRndFSC, correctedFSC) = getMaskCorrectedFSC(array1, array2, mask, samplingRate)
    inv_res_at_threshold, resolution = determine_fsc_resolution(inv_resolution, unmaskedFSC, threshold=threshold)
    print(f"Resolution {resolution} Å  (Sampling rate {samplingRate})")

    from matplotlib import pyplot as plt
    fig, ax = plt.subplots()
    ax.axhline(y=threshold, color='r', linestyle='--')
    plot_fsc(ax, inv_resolution, unmaskedFSC, inv_res_at_threshold,
             label=f'Unmasked FSC ({np.round(1/inv_res_at_threshold, 2)})')

    if maskedFSC is not None:
        inv_res_at_threshold, maskedResolution = determine_fsc_resolution(inv_resolution, maskedFSC)
        print(f"Masked Resolution {maskedResolution}")
        plot_fsc(ax, inv_resolution, maskedFSC, inv_res_at_threshold,
                 label=f'Masked FSC ({np.round(1/inv_res_at_threshold, 2)})')

    ax.legend()
    plt.show()

"""
-i ~/tmp/ConorData/bound/halfs/docks_simulted_micSim0_half1.mrc -r ~/tmp/ConorData/bound/halfs/docks_simulted_micSim0_half2.mrc
"""


# 1. Discount Price

"""
Algorithm
get original_price
discount = original_price * 0.2
new_price = original_price – discount
print new_price
"""

original_price = float(input("Enter your original price:$ "))
DISCOUNT_RATE = 0.2
discount_value = original_price * DISCOUNT_RATE
new_price = original_price - discount_value
print("This is your price after apply the discount:$", new_price, sep="")

# 2. Kilometres to Miles

""""
Algorithm
get distance_in_kilometers
distance_in_miles = distance_in_kilometers * 0.621371
display distance_in_miles
"""

distance_in_kilometers = float(input("Please enter the distance in Kilometers:"))
CONVERSION_RATE = 0.621371
distance_in_miles = distance_in_kilometers * CONVERSION_RATE
print("The distance in miles will be: ", distance_in_miles, sep="" )

# 3. Holiday Cost

"""
Algorithm
get daily_food_cost, daily_activities_cost, number_of_days
total_trip_cost = (daily_hotel_cost + daily_food_cost + daily_activities_cost) * number_of_days
display number_of_days and total_trip_cost

"""
daily_food_cost = float(input("Daily food cost:$"))
daily_activities_cost = float(input("Daily activities cost:$"))
number_of_days = int(input("Number of days:"))
DAILY_HOTEL_COST = 75
total_trip_cost = (daily_food_cost + daily_activities_cost + DAILY_HOTEL_COST) * number_of_days

print("")
print("Total trip cost:$", total_trip_cost, sep="")

# 4. Deep Sleep Calculation (Percentage)

"""
Algorithm
get total_sleep_in_seconds, deep_sleep_in_seconds
percentage = deep_sleep_in_seconds  / total_sleep_in_seconds * 100
deep_sleep_minutes = deep_sleep_in_seconds // 60
deep_sleep_seconds = deep_sleep_in_seconds % 60
total_sleep_minutes = total_sleep_in_seconds // 60
total_sleep_seconds = total_sleep_in_seconds % 60

display  deep_sleep_minutes"m" deep_sleep_seconds"s", total_sleep_minutes"m" total_sleep_seconds"s", percentage

"""
total_sleep_in_seconds = int(input("Total sleep in seconds: "))
deep_sleep_in_seconds = int(input("Deep sleep in seconds: "))

SECONDS = 60
PERCENTAGE = 100

total_sleep_minutes = total_sleep_in_seconds // SECONDS
total_sleep_seconds = total_sleep_in_seconds % SECONDS

deep_sleep_minutes = deep_sleep_in_seconds //SECONDS
deep_sleep_seconds = deep_sleep_in_seconds % SECONDS

percentage = deep_sleep_in_seconds / total_sleep_in_seconds * PERCENTAGE

print("")
print("Deep sleep: ", deep_sleep_minutes, " m ",deep_sleep_seconds, "s" ,sep="")
print("Total sleep: ", total_sleep_minutes, " m ",total_sleep_seconds, "s",  sep="")
print("Percentage: ", percentage, "%", sep="")


import random, time, sys

name = "Джон Доу"
power = 15
health = 100
money = 0
events = ["Бой", "Тайник", "Еда", "Удача"]
monsters = ["Скелет", "Павший рыцарь", "Мёртвый лучник", "Дух смерти", "Летучая мышь", "Бессмертный воин"]
vaib = ["Вы чувствуете страх", "Вам кажется что вас кто-то преследует", "Находясь здесь, вас не покидало чувство того, что за вами кто-то следит", "Вы краем глаза заметили движение в тени, или вам показалось?", "Проходя мимо одного из рыцарских доспехов вы споткнулись об его железный сапог и упали. Больно, но не критично"]
event = "Событие"
chest = ["Красное зелье", "Зелёное зелье", "Синее зелье", "Чёрное зелье"]
day = 1
stamina = 100

def decor():
  print()
  print("="*40)
  print("*"*40)
  print("="*40)
  print()

def death():
  sys.exit()

def info():
  print("Ваше здоровье равно", health)
  print("Ваша сила равна", power)
  print("Ваша энергия равна", stamina)
  print("В вашем кошельке", money, "монет")
  input("Зайти в какую-то комнату (Нажмите Enter чтобы продолжить) ")

#GAME

print("Приветсвую в тебя в своём замке, смертный")
name = input("Скажи мне своё имя ")
print(name + "?", "Как примитивно")
print("Да начнётся Игра!")
time.sleep(0.5)

decor()

while True:

  info()
  time.sleep(0.5)

  event = random.choice(events)

  if event == "Бой":
    name_m = random.choice(monsters)
    power_m = random.randint(5, 25)
    health_m = random.randint(15, 50)

    print("Вы зашли в комнату похожую на арену. В её центре стоял", name_m + ".", "Вы решили дать ему бой!")
    input("Нажмите Enter чтобы продолжить")
    time.sleep(0.5)

    while health > 0 and health_m > 0:

      knock = random.randint(power, power+10)
      print("Вы нанесли монстру удар на ", knock)
      health_m -= knock
      time.sleep(0.5)
      if health_m <= 0:
        print("Вы убили монстра! Это шд братик")
        new_money = random.randint(50, 200)
        money += new_money
        print("В его карманах вы нашли",new_money,"монет, теперь они ваши. Всего у вас",money,"денег")
        input("Нажмите Enter чтобы продолжить")
        time.sleep(0.5)
      else:
        print("У него осталось",health_m,"здоровья")
        input("Нажмите Enter чтобы продолжить")
        knock = power_m
        print()
        print("Монстр атаковал вас в ответ! Он нанёс вам",knock,"урона")
        health -= knock
        print("У вас осталось",health,"здоровья")
        input("Нажмите Enter чтобы продолжить")
        time.sleep(0.5)
        if health <= 0:
          print("Вы умерли смертью храбрых...")
          input("Нажмите Enter чтобы продолжить")
          time.sleep(0.5)
          death()

  elif event == "Тайник": #COMPLATE
    print("Вы нашли комнату с сундуком!")
    loot = random.choice(chest)
    print("В сундуке лежало", loot+".", "Вы решили его выпить")
    input("Нажмите Enter чтобы продолжить")
    if loot == "Красное зелье":
      print("Выпив зелье вы чувствуете как ваши раны излечиваются, вы чувствуете себя лучше")
      health += 25
    elif loot == "Зелёное зелье":
      print("Выпив зелье вы чувствуете прилив сил и невероятную мотивацию, теперь вы чувствуете что можете победить любого монстра!")
      power += 15
    elif loot == "Синее зелье":
      print("Выпив зелье вы чувствуете что ваш рассудок прояснился, и кажется тени в углу комнаты перестали двигаться. Кажется вам стало легче и вы готовы продолжить свой путь!")
      stamina += 50
    elif loot == "Чёрное зелье":
      print("Вам стало плохо, всё тело болит, а каждый шаг даётся с болью, но надо продолжать путь!")
      health -= 50
      if health <= 0:
        print("Сделав очередной шаг вы подвернули ногу и упали на пол, тем самым сломав себе челюсть. Это стало смертельным ударом для вас.")
        death()
    input("Нажмите Enter чтобы продолжить")
    time.sleep(0.5)

  elif event == "Еда": #COMPLATE
    print("Вы нашли кухню! Теперь вы можете хорошо подкрепиться перед продолжением путешествия")
    input("Нажмите Enter чтобы продолжить")
    health += 25
    print("Вы хорошо поели, теперь продолжать путь будет легче. Ваше здоровье теперь равно", health)
    time.sleep(0.5)

  elif event == "Удача": #COMPLATE
    choice = input("Перед вами 2 двери, совершенно одинаковые. Какую вы выберете? (Введите 1 или 2) ")
    lucky_door = random.randint(1, 2)
    if lucky_door == int(choice):
      print("За дверью стоял красивый алтарь, на нём лежал кожанный кошелёк, вам кажется что вам эти деньги нужнее")
      new_money = random.randint(0, 500)
      money += new_money
      print("В кошельке лежало", new_money, "монет. Всего у вас", money, "монет")
    else:
      print("За дверью оказался пустой коридор. Обидно =(")
    input("Нажмите Enter чтобы продолжить")
    time.sleep(0.5)

  else:
    print("Вы чувствуете что что-то пошло не так")

  decor()


"""Cache for SSH tunnels."""
import collections
import getpass
import logging
import os
import subprocess
import threading
import time
import weakref
from contextlib import suppress

import psutil

Context = collections.namedtuple('Context', (
    'uri',
    'interface',
    'local_socket',
    'remote_socket',
    'username',
    'hostname',
    'port',
    'identity_file',
    'ignore_hosts',
    'known_hosts',
))
Context.__new__.__defaults__ = (None, ) * len(Context._fields)

class Portal(collections.MutableMapping):
    """Expiring container for tunnels."""

    def __init__(self, sweap=25):
        """Construct portal, reap tunnels every sweap seconds."""
        self.data = collections.OrderedDict()
        self.sweap = sweap
        self.ttl = sweap * 2
        self.lock = threading.RLock()
        self._schedule_reaper()

    def __getitem__(self, key):
        """Given uri return tunnel and update TTL."""
        with self.lock:
            value, _ = self.data[key]
            self.data[key] = (value, time.time() + self.ttl)
            self.data.move_to_end(key)
            return value

    def __setitem__(self, key, value):
        """Store given tunnel keyed with uri."""
        if not isinstance(value, Tunnel):
            raise ValueError('Portals only support Tunnels.')

        with self.lock:
            self.data[key] = (value, time.time() + self.ttl)
            self.data.move_to_end(key)

    def __delitem__(self, key):
        """Remove and close tunnel from portal."""
        with self.lock:
            value, _ = self.data[key]
            del self.data[key]
            value.close()
            del value

    def __iter__(self):
        """Iterate tunnels."""
        with self.lock:
            values = self.data.values()

        for tunnel, _ in values:
            yield tunnel

    def __len__(self):
        """Return number of tunnels in portal."""
        with self.lock:
            return len(self.data)

    def _schedule_reaper(self):
        timer = threading.Timer(interval=self.sweap, function=self.reap)
        timer.setName('PortalReaper')
        timer.setDaemon(True)
        timer.start()

    def reap(self):
        """Remove tunnels who's TTL has expired."""
        now = time.time()
        with self.lock:
            reaped_data = self.data.copy()
            for entry in reaped_data.items():
                if entry[1][1] < now:
                    del self.data[entry[0]]
                else:
                    # StopIteration as soon as possible
                    break
            self._schedule_reaper()

class Tunnel():
    """SSH tunnel."""

    def __init__(self, context):
        """Construct Tunnel."""
        self.context = context
        self._closed = True

    @property
    def closed(self):
        """Is tunnel closed."""
        return self._closed

    def bore(self):
        """Create SSH tunnel from given context."""
        cmd = ['ssh', '-fNT']

        if logging.getLogger().getEffectiveLevel() == logging.DEBUG:
            cmd.append('-v')
        else:
            cmd.append('-q')

        if self.context.port:
            cmd.extend(('-p', str(self.context.port)))

        cmd.extend(('-L', '{}:{}'.format(self.context.local_socket,
                                         self.context.remote_socket)))

        if self.context.ignore_hosts:
            cmd.extend(('-o', 'StrictHostKeyChecking=no',
                        '-o', 'UserKnownHostsFile=/dev/null'))
        elif self.context.known_hosts:
            cmd.extend(('-o', 'UserKnownHostsFile={known_hosts}'.format(
                known_hosts=self.context.known_hosts)))

        if self.context.identity_file:
            cmd.extend(('-i', self.context.identity_file))

        cmd.append('{}@{}'.format(self.context.username,
                                  self.context.hostname))

        logging.debug('Opening tunnel "%s", cmd "%s"', self.context.uri,
                      ' '.join(cmd))

        tunnel = subprocess.Popen(cmd, close_fds=True)
        # The return value of Popen() has no long term value as that process
        # has already exited by the time control is returned here. This is a
        # side effect of the -f option. wait() will be called to clean up
        # resources.
        for _ in range(300):
            # TODO: Make timeout configurable
            if os.path.exists(self.context.local_socket) \
                    or tunnel.returncode is not None:
                break
            with suppress(subprocess.TimeoutExpired):
                # waiting for either socket to be created
                # or first child to exit
                tunnel.wait(0.5)
        else:
            raise TimeoutError(
                'Failed to create tunnel "{}", using: "{}"'.format(
                    self.context.uri, ' '.join(cmd)))
        if tunnel.returncode is not None and tunnel.returncode != 0:
            raise subprocess.CalledProcessError(tunnel.returncode,
                                                ' '.join(cmd))
        tunnel.wait()

        self._closed = False
        weakref.finalize(self, self.close)
        return self

    def close(self):
        """Close SSH tunnel."""
        logging.debug('Closing tunnel "%s"', self.context.uri)

        if self._closed:
            return

        # Find all ssh instances for user with uri tunnel the hard way...
        targets = [
            p
            for p in psutil.process_iter(attrs=['name', 'username', 'cmdline'])
            if p.info['username'] == getpass.getuser()
            and p.info['name'] == 'ssh'
            and self.context.local_socket in ' '.join(p.info['cmdline'])
        ]  # yapf: disable

        # ask nicely for ssh to quit, reap results
        for proc in targets:
            proc.terminate()
        _, alive = psutil.wait_procs(targets, timeout=300)

        # kill off the uncooperative, then report any stragglers
        for proc in alive:
            proc.kill()
        _, alive = psutil.wait_procs(targets, timeout=300)

        for proc in alive:
            logging.info('process %d survived SIGKILL, giving up.', proc.pid)

        with suppress(OSError):
            os.remove(self.context.local_socket)
        self._closed = True


import configparser
import requests
import csv
import os

home = os.path.expanduser('~/')
config = configparser.ConfigParser()
config.read(f'{home}key_vault.config')

headers = {
'Authorization': config['SMARTSHEET']['api-key'],
'Content-Type': 'application/json',
}

users_to_remove = []
def read_smartsheet_csv():
    with open('smartsheet_users.csv', 'r') as smartsheet_users:
        reader = csv.reader(smartsheet_users)
        next(reader)
        for row in reader:
            users_to_remove.append(row)
            smartsheet_ids(row[0])

def smartsheet_ids(row):
    params = (
        ('email', '{}'.format(row)),
        ('include', 'lastLogin'),
    )

    response = requests.get('https://api.smartsheet.com/2.0/users', headers=headers, params=params)
    data = response.json()
    remove_licence(data['data'][0]['id'])

def remove_licence(row):
    data = '{"admin": false, "licensedSheetCreator": false}'
    response = requests.put('https://api.smartsheet.com/2.0/users/{}'.format(row), headers=headers, data=data)
    data = response.json()
    print (data['message'], '\nname:', data['result']['email'], '\nlicense_status:', data['result']['licensedSheetCreator'], '\n')

read_smartsheet_csv()


import os
from flask import Flask, request
from utils import check_count_args, foo

app = Flask(__name__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, "data")

@app.route("/perform_query")
def perform_query():
    kwargs = {
    "cmd1": request.args.get('cmd1'),
    "cmd2": request.args.get('cmd2'),
    "val1": request.args.get('val1'),
    "val2": request.args.get('val2'),
    "file_name": request.args.get('file_name')
}
    kwargs["file_path"] = os.path.join(DATA_DIR, str(kwargs["file_name"]))

    check_count_args(**kwargs)

    f = open(kwargs["file_path"])
    res = foo(f, kwargs["cmd1"], kwargs["val1"])

    if kwargs["cmd2"] and kwargs["val2"]:
        res = foo(res, kwargs["cmd2"], kwargs["val2"])
    res = res = "\n".join(res)
    f.close()

    return app.response_class(res, content_type="text/plain"), 200

if __name__ == "__main__":
    app.run()


"""
A dialog widget for selecting an item.
"""

from PyQt4.QtGui import QDialog, QWidget, QVBoxLayout, QDialogButtonBox, \
                        QStringListModel, QLabel, QSizePolicy

from PyQt4.QtCore import Qt
from PyQt4.QtCore import pyqtSignal as Signal

from . import previewbrowser

class PreviewDialog(QDialog):
    """A Dialog for selecting an item from a PreviewItem.
    """
    currentIndexChanged = Signal(int)

    def __init__(self, parent=None, flags=Qt.WindowFlags(0),
                 model=None, **kwargs):
        QDialog.__init__(self, parent, flags, **kwargs)

        self.__setupUi()
        if model is not None:
            self.setModel(model)

    def __setupUi(self):
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setContentsMargins(0, 0, 0, 0)

        heading = self.tr("Preview")
        heading = u"
{0}
".format(heading)
        self.__heading = QLabel(heading, self,
                                objectName="heading")

        self.__heading.setContentsMargins(12, 12, 12, 0)

        self.__browser = previewbrowser.PreviewBrowser(self)

        self.__buttons = QDialogButtonBox(QDialogButtonBox.Open | \
                                          QDialogButtonBox.Cancel,
                                          Qt.Horizontal,)
        self.__buttons.button(QDialogButtonBox.Open).setAutoDefault(True)

        # Set the Open dialog as disabled until the current index changes
        self.__buttons.button(QDialogButtonBox.Open).setEnabled(False)

        # The QDialogButtonsWidget messes with the layout if it is
        # contained directly in the QDialog. So we create an extra
        # layer of indirection.
        buttons = QWidget(objectName="button-container")
        buttons_l = QVBoxLayout()
        buttons_l.setContentsMargins(12, 0, 12, 12)
        buttons.setLayout(buttons_l)

        buttons_l.addWidget(self.__buttons)

        layout.addWidget(self.__heading)
        layout.addWidget(self.__browser)

        layout.addWidget(buttons)

        self.__buttons.accepted.connect(self.accept)
        self.__buttons.rejected.connect(self.reject)
        self.__browser.currentIndexChanged.connect(
            self.__on_currentIndexChanged
        )
        self.__browser.activated.connect(self.__on_activated)

        layout.setSizeConstraint(QVBoxLayout.SetFixedSize)
        self.setLayout(layout)
        self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

    def setItems(self, items):
        """Set the items (a list of strings) for preview/selection.
        """
        model = QStringListModel(items)
        self.setModel(model)

    def setModel(self, model):
        """Set the model for preview/selection.
        """
        self.__browser.setModel(model)

    def model(self):
        """Return the model.
        """
        return self.__browser.model()

    def currentIndex(self):
        return self.__browser.currentIndex()

    def setCurrentIndex(self, index):
        """Set the current selected (shown) index.
        """
        self.__browser.setCurrentIndex(index)

    def setHeading(self, heading):
        """Set `heading` as the heading string ('
Preview
'
        by default).

        """
        self.__heading.setText(heading)

    def heading(self):
        """Return the heading string.
        """
    def __on_currentIndexChanged(self, index):
        button = self.__buttons.button(QDialogButtonBox.Open)
        button.setEnabled(index >= 0)
        self.currentIndexChanged.emit(index)

    def __on_activated(self, index):
        if self.currentIndex() != index:
            self.setCurrentIndex(index)

        self.accept()


#% matplotlib inline
import requests
from bs4 import BeautifulSoup
import urllib
load_url="https://news.yahoo.co.jp/"
html=requests.get(load_url)
#html.encoding=html.apparent_encoding

soup=BeautifulSoup(html.content,"html.parser")
topic=soup.find(class_="topics")
filename="yahoo.txt"
#print(topic)
with open(filename,mode="w") as f:
    for element in topic.find_all("a"):
        url=element.get("href")
        link_url=urllib.parse.urljoin(load_url,url)
        print(element.text)
        print(link_url)
        f.write(element.text+"\n")
        f.write(link_url+"\n")
        f.write("\n")


import sys
from os.path import abspath, join, dirname

sys.path.insert(0, join(abspath( dirname(__file__)), '../'))
from model.dataModel import CASSI, HSISingleData, X0FromLS, get_rand_mask, normalizeByMax, repeatDim

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

DATASETNAME="Harvard"
# DATASETNAME="ICVL"

import h5py

class showHSI:
    def __init__(self, Xdata, Ydata=None):
        self.Xdata = Xdata
        self.Ydata = Ydata
        if self.Ydata is not None:
            assert Xdata.shape == Ydata.shape
            self.vmin = min(np.min(self.Xdata), np.min(self.Ydata))
            self.vmax = min(np.max(self.Xdata), np.max(self.Ydata))
            self.fig, self.ax = plt.subplots(1, 2)
            self.axX = self.ax[0]
            self.axY = self.ax[1]
        else:
            self.vmin = np.min(self.Xdata)
            self.vmax = np.max(self.Xdata)
            self.fig, self.ax = plt.subplots(1, 1)
            self.axX = self.ax

        print(self.vmin,self.vmax)

        self.currentDataIndex = 0
        if len(Xdata.shape) == 2:
            self.dataLen = 1
            self.currentXData = Xdata
        elif len(Xdata.shape) == 3:
            self.dataLen = Xdata.shape[2]
            self.currentXData = Xdata[:,:,self.currentDataIndex]
        else:
            print(f"UnExpect Shape: {Xdata.shape}")

        self.Xplt = self.axX.imshow(self.currentXData, cmap="gray", vmin=self.vmin, vmax=self.vmax)
        self.axX.set_title(f"X: {self.currentDataIndex}/{self.dataLen-1}")
        self.fig.colorbar(self.Xplt, ax=self.axX)

        if self.Ydata is not None:
            self.currentYData = Ydata[:,:,self.currentDataIndex]
            self.Yplt = self.axY.imshow(self.currentYData, cmap="gray", vmin=self.vmin, vmax=self.vmax)
            self.axY.set_title(f"Y: {self.currentDataIndex}/{self.dataLen-1}")
            self.fig.colorbar(self.Yplt, ax=self.axY)
        if len(Xdata.shape) == 3:
            plt.subplots_adjust(bottom=0.2)
            self.setButtons()

    def show(self):
        plt.show()

    def _next(self, event):
        if self.currentDataIndex < self.dataLen-1:
            self.currentDataIndex += 1
            self.setData()

    def _prev(self, event):
        if self.currentDataIndex > 0:
            self.currentDataIndex -= 1
            self.setData()

    def setData(self):
        self.currentXData = self.Xdata[:,:,self.currentDataIndex]
        self.Xplt.set_data(self.currentXData)
        self.axX.set_title(f"X: {self.currentDataIndex}/{self.dataLen-1}")
        if self.Ydata is not None:
            self.currentYData = self.Ydata[:,:,self.currentDataIndex]
            self.Yplt.set_data(self.currentYData)
            self.axY.set_title(f"Y: {self.currentDataIndex}/{self.dataLen-1}")
        plt.draw()

    def setButtons(self):
        ax_prev = plt.axes([0.41, 0.05, 0.07, 0.075])
        ax_next = plt.axes([0.51, 0.05, 0.07, 0.075])
        # btn_prev = Button(ax_prev,"<")
        self.prev_button = Button(ax_prev,"<")
        self.prev_button.on_clicked(self._prev)
        self.next_button = Button(ax_next,">")
        self.next_button.on_clicked(self._next)

def cutAndSave(file, num = 4):
    """ 从大的训练数据上切下来一部分以进行观察
    """
    dataset = HSISingleData(file, (3, 0, 1, 2), lambda x:X0FromLS(*CASSI(x), labelName="label"))
    cal_x, orl_y = np.zeros((num, 48, 48, 31)), np.zeros((num, 48, 48, 31))
    for i in range(4):
        cal_x[i], orl_y[i] = dataset[i]
        # print("X:\n", cal_x[i])
        # print("Y:\n", orl_y[i])
        # print("\n")
    np.save(f"save/cutData/cal_x_{num}", cal_x)
    np.save(f"save/cutData/orl_y_{num}", orl_y)

def getCut(num = 4):
    """ 读取切下来的数据
    """
    return np.load(f"./save/cutData/cal_x_{num}.npy"), np.load(f"save/cutData/orl_y_{num}.npy")

if __name__ == "__main__":
    # 测试showHSI的可用性
    # arr3 = np.ones((10,10,3))
    # arr = np.arange(300.)
    # arr3 = arr.reshape((10,10,3),order='F')/450.0
    # arr3y = np.ones((10,10,3))
    # arr = np.arange(150,450.)
    # arr3y = arr.reshape((10,10,3),order='F')/450/0
    # showHSI(arr3,arr3y).show()

    # 测试直接读取原始48*48*31的数据
    # cutAndSave(f'./data/Train/Training_Data_{DATASETNAME}_48.mat')
    # data   = h5py.File(file, 'r')
    # labels = data['label']                        # 获取其中数据标签
    # del data
    # new_labels = np.transpose(labels, (0, 3, 2, 1))   # 调整维度的顺序（batch_size，h,w,c）
    # one_label = new_labels[0]
    # showHSI(one_label).show()

    # 测试生成的mask
    # mask = get_rand_mask(48, 48, 31)
    # showHSI(mask).show()

    # 测试使用最小二乘后的 X0
    # file = f'./data/Train/Training_Data_{DATASETNAME}_48.mat'
    # x,y = getCut()
    # showHSI(x[0], y[0]).show()

    # file = f'./data/Train/Training_Data_{DATASETNAME}_48.mat'
    # data = HSISingleData(file, (3, 0, 1, 2), labelName="label")
    # 测试集中512*512的原始数据
    file = f'./data/Test/{DATASETNAME}48/44.mat'
    data = HSISingleData(file, None, lambda x:X0FromLS(*CASSI(x)), labelName="hyper_image")
    showHSI(data[0][0], data[0][1]).show()


# CSV file format : Id Num, Source Name, RA, Dec, isobserved, dummy, description
# JSON file for Publications format: {{Id : Id Num, {} }}

import csv
import os
with open("AS_observations_cat_Sept2018.txt", "r") as in_text:
    in_reader = csv.reader(in_text, delimiter='\t')
    with open("AS_observations_cat_Sept2018.csv", "w") as out_csv:
        out_writer = csv.writer(out_csv, delimiter=',')
        for row in in_reader:
            out_writer.writerow(row)

with open('AS_observations_cat_Sept2018.csv') as csv_file:
    dr = csv.DictReader(csv_file)
    with open('summaryb.csv', mode='w') as csv_file2:
        writer = csv.writer(csv_file2, delimiter=',')
        writer.writerow(['idx', 'date_time','proposal_id','target_id','obsid','object', 'ra', 'dec', 'ins'])
        for row in dr:
            if "::" in row['obsid_object']:
                writer.writerow([row['idx'],row['date'],row['Proposal_ID'],row['Target_ID'],
                                 row['obsid_object'].partition("::")[0].strip(),row['obsid_object'].partition("::")[2].strip(), row['ra'], row['dec'], row['ins']])
            else:
                writer.writerow([row['idx'],row['date'],row['Proposal_ID'],row['Target_ID'],
                                 "",row['obsid_object'], row['ra'], row['dec'], row['ins']])

propsals={}

with open('proposals.csv') as pf:
    dr = csv.DictReader(pf)
    for row in dr:
        propsals[row["PROPOSALID"]] = [row["ABSTRACT"],row["PI"]]

with open('summaryb.csv',mode='r') as f1:
    dr = csv.DictReader(f1)
    with open('summaryB.csv', mode='w') as csv_file2:
        writer = csv.writer(csv_file2, delimiter=',')
        writer.writerow(['idx', 'date_time','proposal_id','target_id','obsid','object', 'ra', 'dec', 'ins','abstract','PI'])
        for row in dr:
            if row["proposal_id"] in propsals:
                a = propsals[row["proposal_id"]]
                abst = a[0]
                pi = a[1]
            else:
                abst=""
                pi=""
            writer.writerow([row["idx"],row["date_time"],row["proposal_id"],row["target_id"],
                row["obsid"],row["object"],row["ra"],row["dec"],row["ins"],abst,
                pi])

os.remove("summaryb.csv")


import src.lookml.lookml as lookml
import src.lookml.lkml as lkml
import unittest, copy
from pprint import pprint
import configparser, json
# from looker_sdk import client, models, methods
from looker_sdk import models, methods, init31
config = configparser.ConfigParser()
config.read('settings.ini')

class testScenariosGenerateFromSchema(unittest.TestCase):
    '''
        Objective: test end to end common use case scenarios
    '''
    def setUp(self):
        pass

    def test_create_view_from_info_schema(self):
        def column_to_dimension(col):
            if col['LOOKER_TYPE'] == 'time':
                tmpDim = lookml.DimensionGroup(
                        lookml.lookCase(col['COLUMN_NAME'])
                        )
            else:
                tmpDim = lookml.Dimension(lookml.lookCase(col['COLUMN_NAME']))
            tmpDim.setType(col['LOOKER_TYPE'])
            tmpDim.sql = "${TABLE}." + col['COLUMN_NAME']
            return tmpDim

        sdk = init31("tests/api.ini")
        sql = """
                SELECT
                    t.TABLE_NAME
                    ,t.TABLE_SCHEMA
                    ,t.COLUMN_NAME
                    ,t.DATA_TYPE
                    , CASE
                        WHEN t.DATA_TYPE IN ('TIMESTAMP_LTZ') THEN 'time'
                        WHEN t.DATA_TYPE IN ('FLOAT','NUMBER') THEN 'number'
                        ELSE 'string' END as "LOOKER_TYPE"
                FROM
                    information_schema.COLUMNS as t
                WHERE
                    1=1
                    AND t.table_name = 'ORDER_ITEMS'
                    AND t.table_schema = 'PUBLIC'
                LIMIT 100
        """
        query_config = models.WriteSqlQueryCreate(sql=sql, connection_id="snowlooker")
        query = sdk.create_sql_query(query_config)
        response = sdk.run_sql_query(slug=query.slug, result_format="json")
        response_json = json.loads(response)
        order_items = lookml.View('order_items_3')
        order_items.sql_table_name = 'PUBLIC.ORDER_ITEMS'

        for column in response_json:
            order_items + column_to_dimension(column)

        order_items.sumAllNumDimensions()
        order_items.addCount()

        proj = lookml.Project(
                 repo= config['github']['repo']
                ,access_token=config['github']['access_token']
                ,looker_host="https://profservices.dev.looker.com/"
                ,looker_project_name="russ_sanbox"
        )
        myNewFile = lookml.File(order_items)
        proj.put(myNewFile)
        proj.deploy()

    def tearDown(self):
        pass