#Time complexity: O(n) where  n is the number of houses
#Space complexity: O(1) as the colors are only 3
#Works on leetcode: yes
#Approach:Here dp is just a tuple of 3 cost values. At each house, we get minimum cost for all 3 colors which is achieved by
# adding current cost of one color and minimum of costs from other two colors from previous house.
class Solution:
	#function to find the minimum cost to paint houses using 3 colors given no adjacent house has same colors
    def minCost(self, costs: List[List[int]]) -> int:
        if not costs:
            return 0
        dp = costs[0]
        for i in range(1,len(costs)):
            prev = dp[:]
            for j in range(len(costs[0])):
                dp[j] = costs[i][j] + min(prev[:j]+prev[j+1:])
        return min(dp)
    #Base recurive method
    def minCost2(self, costs: List[List[int]]) -> int:
        case1 = self.helper(costs,0,0,0)
        case2 = self.helper(costs,0,0,1)
        case3 = self.helper(costs,0,0,2)
        return min(case1, case2, case3)
    #helper recursive function for base solution
    # Time = O(2^n)
    # Space = O(n) for recursive stack
    def helper(self, costs, minn, row, lastcolor):
        if row==len(costs):
            return minn
        case1, case2, case3 = float('inf'), float('inf'), float('inf')
        if lastcolor==0:
            case1 = min(self.helper(costs, minn+costs[row][1], row+1, 1), self.helper(costs, minn+costs[row][2], row+1, 2))
        if lastcolor==1:
            case2 = min(self.helper(costs, minn+costs[row][0], row+1, 0), self.helper(costs, minn+costs[row][2], row+1, 2))
        if lastcolor==2:
            case3 = min(self.helper(costs, minn+costs[row][0], row+1, 0), self.helper(costs, minn+costs[row][1], row+1, 1))
        return min(case1, case2, case3)


import datetime
import json
import ast

import pymysql
from homework import timetable

from homework import subjects
from modules.db import Connection

def saveHomework(message, subject, date):
    date =  getDay(str(date))
    subject = int(subject)

    if date == "Неверная дата":
        return date

    weekday = date.weekday()

    if weekday >= 5:
        return 'Викдей'

    tt = timetable.getTimeTable(weekday)

    for t in json.loads(tt['json']):
        if(t == int(subject)):
            addHomework(message, subject, date)
            return True
            break

def getHomework(date):
    date = getDay(date)

    if date == 'Неверная дата':
        return 0

    weekday = date.weekday()

    res = "Домашка: \n"

    if weekday < 5:
        sbjcts = list(set(json.loads(timetable.getTimeTable(weekday)['json'])))
        for sbjct in sbjcts:
            sbjct_obj = subjects.getSubject(sbjct)
            res +=  "\n\n" + sbjct_obj[0]['name'] + ": \n"
            hw = getHomeworkBySubjAndDate(sbjct, date)

            if len(hw) == 0:
                continue

            res += hw[0]['text']

        return res

    return 1

def getHomeworkBySubjAndDate(subject, date):
    cursor = Connection.db.cursor(pymysql.cursors.DictCursor)
    sql = "SELECT * FROM homework WHERE subject_id = " + str(subject) + " AND date = '" + str(date) + "'"
    cursor.execute(sql)
    data = cursor.fetchall()
    return data

def addHomework(message, subject, date):
    if subjects.subjectExist(int(subject)) == False:
        clearHomework(subject, date)
        return 0

    old_hw = getHomeworkBySubjAndDate(subject, date)

    if len(old_hw) == 0:
      cursor = Connection.db.cursor()
      sql = "INSERT INTO homework VALUES (null, " + str(int(subject)) + ", '" + message + "', '" + str(date) + "')"
      cursor.execute(sql)
      Connection.db.commit()
      return True
    else:
        cursor = Connection.db.cursor()
        sql = "UPDATE homework SET text = '" + old_hw[0]['text'] + '\n'+ message + "' WHERE subject_id = " + str(int(subject))+ " AND date = '"+ str(date)+"' "
        cursor.execute(sql)
        Connection.db.commit()
        return True

def clearHomework(date, subject):
    date = getDay(str(date))

    if date == 'Неверная дата':
        return date

    cursor = Connection.db.cursor()
    sql = "DELETE FROM homework WHERE subject_id = "+str(int(subject))+" AND date = '"+str(date)+"' "
    cursor.execute(sql)
    Connection.db.commit()
    clearAttachments(date)
    return True

def getDay(message_date):
    if 'сегодня' in message_date.lower():
        return datetime.date.today()
    elif 'послезавтра' in message_date.lower():
        return datetime.date.today() + datetime.timedelta(days=2)
    elif 'завтра' in message_date.lower():
        return datetime.date.today() + datetime.timedelta(days=1)
    elif 'позавчера' in message_date.lower():
        return datetime.date.today() + datetime.timedelta(days=-2)
    elif 'вчера' in message_date.lower():
        return datetime.date.today() + datetime.timedelta(days=-1)
    else:
        try:
            return datetime.datetime.strptime(str(datetime.datetime.today().year) + '.' +
                                              message_date.replace(' ', ''), "%Y.%m.%d").date()
        except:
            return 'Неверная дата'

#Аттачменты

def getAttachments(date):
    cursor = Connection.db.cursor()
    sql = "SELECT * FROM homework_attachments WHERE date = '" + date +"' "
    cursor.execute(sql)
    data = cursor.fetchall()
    return data

def addAttachment(date, attachments):
    cursor = Connection.db.cursor()
    sql = "INSERT INTO  homework_attachments VALUES (null, '" + date +"', \""+ str(attachments) +"\")"
    cursor.execute(sql)
    Connection.db.commit()
    return True

def setAttachment(date, attachments):
    cursor = Connection.db.cursor()
    sql = "UPDATE homework_attachments SET attachments = \"" + str(attachments)+ "\" WHERE date = '" + date +"'"
    cursor.execute(sql)
    Connection.db.commit()

def addAttachments(date, attachments):

    if(len(attachments) == 0):
        return False

    old_attachments = getAttachments(str(date))

    if len(old_attachments) == 0:
        return addAttachment(str(date), attachments)
    else:
        oa = ast.literal_eval(old_attachments[0][2])
        oa.extend(attachments)
        setAttachment(str(date), oa)
        return True

def clearAttachments(date):
    cursor = Connection.db.cursor()
    sql = "DELETE FROM homework_attachments WHERE date = '" + date + "'"
    cursor.execute(sql)
    Connection.db.commit()

def deleteAttachment(date, num):
    old_attachments = getAttachments(str(date))

    if len(old_attachments) == 0:
        return True
    else:
        oa = ast.literal_eval(old_attachments[0][2])

        if num > 0 and num <= len(oa):
            del oa[num-1]
            setAttachment(str(date), oa)
        else:
            return False
        return True


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 16 22:22:51 2018

@author: tysl
"""

import matplotlib.pyplot as plt

input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.plot(input_values, squares, linewidth=5)

# Set chart title and label axes
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)

# Set size of tick labels.
plt.tick_params(axis='both', labelsize=14)

plt.savefig('squares_plot.png', bbox_inches='tight')


 # Hint1: This method will help you: https://www.w3schools.com/python/ref_file_readlines.asp
# Hint2: This method will also help you: https://www.w3schools.com/python/ref_string_replace.asp
# Hint3: THis method will help you: https://www.w3schools.com/python/ref_string_strip.asp

PLACE_HOLDER = "[name]"

with open("./Input/Names/invited_names.txt") as names_file:
    names = names_file.readlines()
    # print(names)

with open("./Input/Letters/starting_letter.docx") as letter_file:
    letter_content = letter_file.read()
    # print(f"\nletter_content \n{letter_content}")
    for name in names:
        stripped_name = name.strip()
        # print(f"stripped_name {stripped_name}")
        new_letter = letter_content.replace(PLACE_HOLDER, stripped_name)
        # print(f"\nnew Letter \n{new_letter}")
        with open(f"./Output/ReadyToSend/letter_for_{stripped_name}.docx", mode="w") as completed_letter:
            completed_letter.write(new_letter)


import random

def choice_checker(question, valid_list, error):

    valid = False
    while not valid:

        # Ask user for choice (and put choice in lowercase)
        response = input(question).lower()

        # iterates through list and if response is an item
        # in the list ( or the first letter of an item), the
        # full item name is returned

        for item in valid_list:
            if response == item[0] or response == item:
                return item

        # output error if item is not in list
        print(error)
        print()

# List of operators
comparisons = ["<", ">", "=="]
add_sub = ["+", "-"]
mul = ["*"]

# List of valid responses
valid_responses = ["true", "false"]
difficulty_list = ["easy", "normal", "hard", "xxx"]
yes_no_list = ["yes", "no"]

# Define correct and incorrect questions + list
tf_questions = ["incorrect_question", "correct_question"]
true_answer = "true"
false_answer = "false"

# Define select_difficulty and set 'questions_answered' to 0
select_difficulty = ""
questions_answered = 0

# Stuf
tf_answer = ""
questions_correct = 0
questions_incorrect = 0
quiz_summary = []

# Ask user what difficulty of questions they want to play
select_difficulty = choice_checker("Select between a 'Easy', 'Normal', or 'Hard' quiz... ", difficulty_list, "Please enter 'Easy', 'Normal' or 'Hard'... \n")
print()

# For selected difficulty print matching heading and questions_answered number
if select_difficulty == "easy":
    question_number = 10
    heading = "--- 10 Easy Difficulty Math Questions ---\n"
    print(heading)

if select_difficulty == "normal":
    question_number = 15
    heading = "--- 15 Normal Difficulty Math Questions ---\n"
    print(heading)

if select_difficulty == "hard":
    question_number = 25
    heading = "--- 25 HARD DIFFICULTY Math Questions ---\n"
    print(heading)

# Start of Loop
while questions_answered != question_number:

    print("Questions correct", questions_correct)

    # Print heading and add 1 for each question answered
    question_heading = "-- Question {} / {} --".format(questions_answered + 1, question_number)
    print(question_heading)
    questions_answered += 1

    # Randomly generate operator
    if select_difficulty == "easy":
        operator = random.choice(comparisons)

    if select_difficulty == "normal":
        operator = random.choice(add_sub)

    if select_difficulty == "hard":
        operator = random.choice(mul)

    # Randomly generate numbers
    num1 = random.randint(1,10)
    num2 = random.randint(1,10)

    # Generate question and evaluate correct answer and incorrect answer
    question = "{} {} {}".format(num1, operator, num2)
    correct_answer = eval(question)
    incorrect_answer = correct_answer - random.randint(1,7)

    # Make evaluate variables ('True' / 'False') equal to strings so
    # user_choice can recognise answer for 'Easy Difficulty'
    if correct_answer == True:
        answer = "true"

    elif correct_answer == False:
        answer = "false"

    # Randomly choose between a correct or incorrect statment
    gen_question = random.choice(tf_questions)

    # If 'Easy Difficulty' was selected print out question without answer
    # e.g 5 > 3 instead of 5 > 3 = True
    if select_difficulty == "easy":

        # Ask user (T/F) question
        print("{} ".format(question))
        user_choice = choice_checker("True or False? ", valid_responses, "Please choose between 'True' or 'False'")

        # Compare choices and print "Correct" or "Incorrect"
        if user_choice == answer:
            questions_correct += 1
            print("Correct\n")

        else:
            questions_incorrect += 1
            print("INCORRECT\n")

    # If 'Easy Difficulty' is not selected, print out question with answer
    # e.g 5 + 5 = 10
    else:

        # If randomly generated question is "correct_question",
        # print out a correct math statement
        if gen_question == "correct_question":

            # Ask user (T/F) question
            print("{} = {}".format(question, correct_answer))
            user_choice = choice_checker("True or False? ", valid_responses, "Please choose between 'True' or 'False'")

            # Compare choices and print "Correct" or "Incorrect"
            if user_choice == true_answer:
                tf_answer = "true"
                questions_correct =+ 1
                print("Correct\n")
            else:
                questions_incorrect += 1
                print("INCORRECT\n")

        # If randomly generated question is "incorrect_question",
        # print out a correct math statment
        else:

            # Ask user (T/F) question
            print("{} = {}".format(question, incorrect_answer))
            user_choice = choice_checker("True or False? ", valid_responses, "Please choose between 'True' or False'")

            # Compare choices and print "Correct" or "Incorrect"
            if user_choice == false_answer:
                tf_answer = "false"
                questions_correct =+ 1
                print("Correct\n")
            else:
                print("INCORRECT\n")

        outcome = "Round {}: {} - You said {}, the right answer is {}".format(questions_answered, question, user_choice, tf_answer)
        quiz_summary.append(outcome)

percent_correct = questions_correct / question_number * 100

print("-- Stats --")
print("You got {:.0f}% correct".format(percent_correct))
print("{} / {} \n".format(questions_correct, question_number))

game_history = choice_checker("Do you want to see game history? ", yes_no_list, "Please answer with 'Yes' no 'No' ")
if game_history == "yes":
    print("\n**** Game History****")
    for quiz in quiz_summary:
        print(quiz)

print("\nThanks for playing the quiz")


import math
n = int(input())

speeds = list()
for x in range(n):
    speeds.append(list(map(int, input().split(' '))))

speeds.sort()
minSpeed = math.fabs((speeds[1][1] - speeds[0][1]) / (speeds[1][0] - speeds[0][0]))

checkSpeed = 0
for x in range(2, n):
    checkSpeed = math.fabs((speeds[x][1] - speeds[x-1][1]) / (speeds[x][0] - speeds[x-1][0]))
    if checkSpeed > minSpeed:
        minSpeed = checkSpeed

print(minSpeed)


from django.conf.urls import url
from .views import bio, portfolio, home, post

app_name = 'portfolio'

urlpatterns = [
    url(r'^bio/?$', bio, name='bio'),
    url(r'^portfolio/?$', portfolio, name='projects'),
    url(r'^post/(?P<slug>[-\w]+)/?$', post, name='post'),
    url(r'^$', home, name='home'),
]


import sqlite3
import urllib
from email.mime.text import MIMEText

from bs4 import BeautifulSoup
import smtplib

from email.mime.multipart import MIMEMultipart

main_url = "https://courses.illinois.edu"
database_path = "/Users/harishmanikantan/PycharmProjects/untitled/test.db"

def create_UserRequests_database():
    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    cursor.execute('CREATE TABLE IF NOT EXISTS UserRequests(email text, subject_code text, course_number text, course_section text, crn text, course_url text)')

    cursor.execute('CREATE TABLE IF NOT EXISTS CourseUrls(course_url text)')

    connect.commit()
    connect.close()

#create_UserRequests_database()

def insertUrl(course_url):
    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    cursor.execute('SELECT * FROM CourseUrls WHERE (course_url = ?)', (course_url, ))

    if cursor.fetchone() is None:
        cursor.execute('INSERT INTO CourseUrls VALUES (?)', (course_url, ))

    connect.commit()
    connect.close()

def add_row_to_UserRequests_crn(email, course_crn):
    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    cursor.execute('SELECT * FROM Courses WHERE (crn = ?)', (course_crn, ))
    row = cursor.fetchone()

    if row is None:
        return

    subject_code = row[0]
    course_number = row[1]
    course_section = row[2]
    course_url = row[4]

    cursor.execute('INSERT INTO UserRequests VALUES (?, ?, ?, ?, ?, ?)',
                   (email, subject_code, course_number, course_section, course_crn, course_url))

    connect.commit()
    connect.close()

    insertUrl(course_url)

def update_courses_database(subject_code, course_number, course_section):

    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    fall17 = "https://courses.illinois.edu/schedule/2017/fall"
    url = fall17 + "//" + subject_code + "//" + course_number

    req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    html = urllib.request.urlopen(req).read()
    soup = BeautifulSoup(html, "html.parser")

    script = soup.find_all("script")[2].string

    courses = script.split('{')

    for i in courses:
        if course_section in i:
            index = i.find("crn")
            crn = str(i[index + 6: index + 11])
            cursor.execute(
                'UPDATE Courses SET course_section = ? WHERE (subject_code = ? AND course_number = ? AND crn = ?)',
                (course_section, subject_code, course_number, crn))
            connect.commit()
            connect.close()
            return True

    return False

def add_row_to_UserRequests_courseSection(email, subject_code, course_number, course_section):
    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    cursor.execute('SELECT * FROM Courses WHERE (subject_code = ? AND course_number = ? AND course_section = ?)',
                   (subject_code, course_number, course_section))

    row = cursor.fetchone()

    if row is None:
        if update_courses_database(subject_code, course_number, course_section) is False:
            return
        else:
            cursor.execute(
                'SELECT * FROM Courses WHERE (subject_code = ? AND course_number = ? AND course_section = ?)',
                (subject_code, course_number, course_section))

            row = cursor.fetchone()

    course_crn = row[3]
    course_url = row[4]

    cursor.execute('INSERT INTO UserRequests VALUES (?, ?, ?, ?, ?, ?)',
                   (email, subject_code, course_number, course_section, course_crn, course_url))

    connect.commit()
    connect.close()

    insertUrl(course_url)

def send_mock_email():
    #print ("HEY")
    message = MIMEMultipart()

    message['Subject'] = " Section Availability Change"

    message['From'] = "harishchess98@gmail.com"
    message['To'] = "hsm2@illinois.edu"

    body = "Hey"
    body = MIMEText(body)

    message.attach(body)

    email_list = ["hsm2@illinois.edu"]

    server = smtplib.SMTP('smtp.gmail.com:587')
    server.ehlo()
    server.starttls()
    server.login("harishchess98", "Harish17!")
    server.sendmail("harishchess98@gmail.com", email_list, message.as_string())
    server.quit()

#send_mock_email()

def check_user_requests():
    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    cursor.execute('SELECT * FROM UserRequests')

    for row in cursor.fetchall():
        print (row)

    connect.close()

def check_course_urls():
    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    cursor.execute('SELECT * FROM CourseUrls')

    for row in cursor.fetchall():
        print (row)

    connect.close()

def drop_user_requests():
    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    cursor.execute('DROP TABLE IF EXISTS UserRequests')

    connect.commit()
    connect.close()

def drop_course_urls():
    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    cursor.execute('DROP TABLE IF EXISTS CourseUrls')

    connect.commit()
    connect.close()

#create_UserRequests_database()

#drop_course_urls()
#drop_user_requests()

check_user_requests()
check_course_urls()

#add_row_to_UserRequests_crn("notify.course@gmail.com", "43357")
#add_row_to_UserRequests_crn("notify.course@gmail.com", "30109")
#add_row_to_UserRequests_courseSection("harishmanikantan@gmail.com", "ABE", "445", "A")

def change_data():
    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    cursor.execute('UPDATE Courses SET availability = ? WHERE (crn = ?)', ("open", "67023"))

    connect.commit()
    connect.close()

#change_data()
#recurring_database_update()

def add_all_cs_courses(code):
    connect = sqlite3.connect(database_path)
    cursor = connect.cursor()

    #cursor.execute('SELECT * FROM Courses')
    #print (len(cursor.fetchall()))

    cursor.execute('SELECT * FROM Courses WHERE (subject_code = ?)', (code, ))

    rows = cursor.fetchall()

    for row in rows:
        add_row_to_UserRequests_crn("notify.course@gmail.com", row[3])

    connect.close()

def add_courses():
    codes = ["ECE", "MATH", "MCB", "ME", "PHYS"]

    for code in codes:
        add_all_cs_courses(code)

#add_courses()

#add_all_cs_courses()
#check_user_requests()
#check_course_urls()


#!/usr/bin/env python3.7

#import argparse

#parser = argparse.ArgumentParser(description='Fix IASE DISA STIG encoding Errors')
#parser.add_argument('stream', help='The files to fix',nargs='+')
#parser.add_argument('--version', '-v', action='version', version='%(prog)s 1.0')
#args = parser.parse_args()

def fix_ckl(stream):
    """
    This script is inteded to fix the encoding error that was inheried by IASE DISA STIGS. Specifically fixes
    the lessthan and greater than symbols.
    """
    lessthan = [line.replace('<','<') for line in stream ]
    morethan = [line.replace('>','>') for line in lessthan]
    join = ''.join(morethan)
    return join

#def new_filegen(filename):
#    try:
#        f2 = open(f"{filename.strip('.xml')}"+"_encode_fix.xml",'x',encoding='utf-8')
#    except FileExistsError as err:
#        print(f"You have already fixed file:\n --> {filename}")
#    else:
#        """
#        This fucntion writes a new file using the new output
#        """
#        f2.write(replace_char(filename))
#    f2.close()

if __name__ == '__main__':
    fix_ckl(stream)


"""
script to make postfit comparisons
"""
from PostFits.postFitScripts import MakePostPlot, result2json, MakeWpTPostFitPlots
from PostFits.CombineHarvester.plotImpacts import plotImpacts
import ROOT
ROOT.gROOT.SetBatch(True)

doInclusive = True
doWpT = False
doRebin = True

# boolean flag to config if the pull
# distribution should be included in the plots
showPULL = True
if doInclusive:
    suffix = "_Rebin.root" if doRebin else ".root"
    MakePostPlot("cards/datacard_muplus_lepEta_bin0_WpT_bin0" + suffix, "muplus", "", showPULL)
    MakePostPlot("cards/datacard_eplus" + suffix,  "eplus", "", showPULL)

    result2json("cards/datacard_muplus_lepEta_bin0_WpT_bin0" + suffix, "w_muplus_sig_mu", "cards/impacts_muplus_lepEta_bin0_WpT_bin0.json")
    result2json("cards/datacard_eplus" + suffix,       "w_eplus_sig_mu",  "cards/impacts_eplus.json")

    plotImpacts("cards/impacts_muplus_lepEta_bin0_WpT_bin0.json", "impacts_muplus_lepEta_bin0")
    plotImpacts("cards/impacts_eplus.json",       "impacts_eplus_lepEta")

    # plot the impacts on QCD
    result2json("cards/datacard_muplus_lepEta_bin0_WpT_bin0" + suffix, "QCD_muplus_lepEta_bin0_WpT_bin0_mu", "cards/impacts_muplus_lepEta_bin0_WpT_bin0_qcd.json")
    result2json("cards/datacard_eplus" + suffix,       "QCD_eplus_lepEta_bin1_WpT_bin0_mu",  "cards/impacts_eplus_qcd.json")

    plotImpacts("cards/impacts_muplus_lepEta_bin0_WpT_bin0_qcd.json", "impacts_muplus_lepEta_bin0_qcd")
    plotImpacts("cards/impacts_eplus_qcd.json",       "impacts_eplus_lepEta_qcd")

if doWpT:
    MakePostPlot("cards/datacard_muplus_lepEta_bin0_WpT.root", "muplus", "WpT", showPULL)

    wpttruthbins  = ["WpT_truth_bin1", "WpT_truth_bin2", "WpT_truth_bin3", "WpT_truth_bin4", "WpT_truth_bin5", "WpT_truth_bin6", "WpT_truth_bin7", "WpT_truth_bin8", "WpT_truth_bin9"]

    jsonNames = []
    for wpttruthbin in wpttruthbins:
        result2json("cards/datacard_muplus_lepEta_bin0_WpT.root", "w_muplus_{}_sig_mu".format(wpttruthbin), "cards/impacts_muplus_{}_sig_mu.json".format(wpttruthbin))
        jsonNames.append("cards/impacts_muplus_{}_sig_mu.json".format(wpttruthbin))
        plotImpacts("cards/impacts_muplus_{}_sig_mu.json".format(wpttruthbin), "impacts_muplus_{}".format(wpttruthbin))

    MakeWpTPostFitPlots(jsonNames)


from Util.Diretorio import LeitorDiretorio
from Util.Keel import LeitorKeel
from SistemaFuzzy.BaseConhecimento.BaseDados import BaseDados
from SistemaFuzzy.BaseConhecimento.BaseRegras import BaseRegras
from SistemaFuzzy.Raciocinio.Geral import Classificacao
from SistemaFuzzy.BaseConhecimento.AlgoritmoPesos.HisaoIshibuchi import PesoHisao
from AlgoritmoGenetico import main_nsgaii_fuzzy as nsgaii
import parametros

arquivos_treinamento = LeitorDiretorio.datasets("tra")
arquivos_teste = LeitorDiretorio.datasets("tst")
for nome_arquivo_train, nome_arquivo_test in zip(arquivos_treinamento, arquivos_teste):
    #Leitura DataSets Treinamento
    treinamento = open(nome_arquivo_train, "r", encoding="utf8")
    extracao_keel_train = LeitorKeel.LeitorKeel(treinamento)
    extracao_keel_train.extracaoDados()

    # Leitura DataSets Teste
    teste = open(nome_arquivo_test, "r", encoding="utf8")
    extracao_keel_test = LeitorKeel.LeitorKeel(teste)
    extracao_keel_test.extracaoDados()

    #Semente
    default = parametros.Default(extracao_keel_train.qtdCaracteristicas)
    bd = BaseDados(extracao_keel_train.limites_inferiores_x, extracao_keel_train.limites_superiores_x, default.discretizacoes, default.particoes )
    particoes = bd.criarParticoes()
    br = BaseRegras(particoes, extracao_keel_train.instancias, extracao_keel_train.classes)
    regras = br.getRegras() #"Wang-Mendel"
    pesoHisao = PesoHisao(particoes, regras, extracao_keel_train.instancias, extracao_keel_train.classes)
    pesoHisao.getPesos(False)

    #Classificação Sem AG
    resultadoTrainSAG = Classificacao(particoes, regras, extracao_keel_train.instancias, extracao_keel_train.classes)
    resultadoTesteSAG = Classificacao(particoes, regras, extracao_keel_test.instancias, extracao_keel_test.classes)

    # Algoritmo Genético MultiObjetivo
    particoesAG, regrasAG = nsgaii.nsgaii_train(particoes.copy(), regras.copy(), extracao_keel_train.instancias, extracao_keel_train.classes)
    resultadoTrainCAG = Classificacao(particoesAG, regrasAG, extracao_keel_train.instancias,extracao_keel_train.classes)
    resultadoTesteCAG = Classificacao(particoesAG, regrasAG, extracao_keel_test.instancias, extracao_keel_test.classes)

    print("Resultados Finais Sem AG")
    print(resultadoTrainSAG.classificar(), resultadoTesteSAG.classificar()[0])
    print("Resultados Finais Com AG")
    print(resultadoTrainCAG.classificar(), resultadoTesteCAG.classificar()[0])


import pytest

from app import models, common, db
from app import exceptions as ex
from sqlalchemy.orm.exc import NoResultFound

# Testing the functions in common.py, assuming authors in the final format of
# a list of dictionaries with keys first_name and last_name

########################
# TAG HELPER FUNCTIONS #
########################

# get_user_tags()

def test_get_user_tags(user1):
    """get_user_tags gets all of the user's tags."""

    tags = common.get_user_tags(user1)

    assert len(tags) == 5

def test_get_user_tags_no_tags(user0):

    tags = common.get_user_tags(user0)

    assert not tags

# get_user_tag()

def test_get_user_tag(user1):
    """get_user_tag() gets the correct tag."""

    tag = common.get_user_tag(user1, "tag0")

    assert tag.name == "tag0"

def test_get_user_tag_raises_ex(user1):
    """get_user_tag() rasies exception if no user tag by provided name."""

    with pytest.raises(NoResultFound):
        common.get_user_tag(user1, "tag5")

# delete_orphaned_tags()

def test_delete_orphaned_tags0(user1):
    """Orphaned tags are deleted when tags are removed manually."""

    doc = user1.documents.first()

    doc.tags.clear()
    db.session.commit()

    common.delete_orphaned_tags()
    db.session.commit()

    tags = models.Tags.query.all()

    assert len(tags) == 4 and "tag1" not in tags

###########################
# AUTHOR HELPER FUNCTIONS #
###########################

def test_get_user_authors1(user1):
    """get_user_authors() returns all user's authors."""

    authors = common.get_user_authors(user1)

    assert len(authors) == 4

def test_get_user_authors2(user0):
    """get_user_authors() returns no authors if user has none."""

    authors = common.get_user_authors(user0)

    assert not authors

def test_get_user_author1(user1):
    """get_user_author() returns correct author."""

    author = common.get_user_author(user1, "Jane", "Johnson")

    assert author.id == 4

def test_get_user_author2_raises_ex(user1):
    """get_user_author() raises exception if author in user's authors."""

    with pytest.raises(NoResultFound):
        common.get_user_author(user1, "Kris", "Warner")

###################
# ADDING DOCUMENTS#
###################

def test_add_no_title_raises_ex(user0):
    content = {"title": ""}
    with pytest.raises(ex.NoTitleException):
        common.add_item(content, user0)

def test_duplicate_link_raises_ex(user0):

    content1 = {"title": "Test", "link": "http://whatyouveread.com/1"}
    content2 = {"title": "Test2", "link": "http://whatyouveread.com/1"}

    common.add_item(content1, user0)

    with pytest.raises(ex.DuplicateLinkException):
        common.add_item(content2, user0)

def test_http_added_to_link(user0):

    content1 = {"title": "Test", "link": "www.whatyouveread.com/1"}

    common.add_item(content1, user0)

    doc = user0.documents.first()

    assert doc.link == "http://www.whatyouveread.com/1"

def test_add_unexpected_read_value_defaults_to_1(user0):
    content = {"title": "Test", "read": 3}
    common.add_item(content, user0)
    doc = user0.documents.first()
    assert doc.read == 1

def test_add_no_read_value_defaults_to_1(user0):
    content = {"title": "Test", "read": ""}
    common.add_item(content, user0)
    doc = user0.documents.first()
    assert doc.read == 1

def test_add_str_read_value_converted_to_int1(user0):
    content = {"title": "Test", "read": "1"}
    common.add_item(content, user0)
    doc = user0.documents.first()
    assert doc.read == 1

def test_add_str_read_value_converted_to_int2(user0):
    content = {"title": "Test", "read": "0"}
    common.add_item(content, user0)
    doc = user0.documents.first()
    assert doc.read == 0

def test_add_one_minimal(user0):
    content = {"title": "Test"}
    common.add_item(content, user0)
    doc = user0.documents.first()
    assert doc.title == "Test"

def test_add_two_minimal(user0):
    content = [{"title": "Test"}, {"title": "Test2"}]
    for item in content:
        common.add_item(item, user0)
    doc = user0.documents.all()
    assert len(doc) == 2

def test_add_four_full(user0, four_items):
    for item in four_items:
        common.add_item(item, user0)

    doc = user0.documents.all()
    assert len(doc) == 4

def test_add_wrong_year_format_ok1(user0):
    content = {"title": "Test", "year": "12"}
    common.add_item(content, user0)
    doc = user0.documents.first()
    assert doc.year == "12"

def test_add_wrong_year_format_ok2(user0):
    content = {"title": "Test", "year": "Smith; Jane"}
    common.add_item(content, user0)
    doc = user0.documents.first()
    assert doc.year == "Smith; Jane"

###############
# EDITING DOCS#
###############

def test_edit_not_user_doc_raises_ex(user0, user1, four_items):
    content = {"id": "1", "title": "Test"}  # not a user0 doc

    with pytest.raises(ex.NotUserDocException):
        common.edit_item(content, user0)

def test_edit_no_title_raises_ex(user1):

    content = {"id": "1", "title": ""}

    with pytest.raises(ex.NoTitleException):
        common.edit_item(content, user1)

def test_http_added_to_link_in_edit(user1):

    content = {"id": "1", "title": "Test", "link": "example.com"}

    common.edit_item(content, user1)

    doc = user1.documents.first()

    assert doc.link == "http://example.com"

def test_edit_no_read_value_defaults_to_1(user1):

    content = {
        "id": "1",
        "title": "Test",
        "link": "http://whatyouveread.com/1",
        "tags": ["tag0", "tag1"],
        "authors": [
            {"last_name": "Smith", "first_name": "Joe"},
            {"last_name": "Smith", "first_name": "Jane"},
        ],
        "year": "2018",
        "notes": "This is a note.",
        "read": "",
    }

    common.edit_item(content, user1)
    doc = user1.documents.first()
    assert doc.read == 1

def test_edit_unexpected_read_value_defaults_to_1(user1):
    """Read value other than 0 or 1 defaults to 1."""

    content = {
        "id": "1",
        "title": "Test",
        "link": "http://whatyouveread.com/1",
        "tags": ["tag0", "tag1"],
        "authors": [
            {"last_name": "Smith", "first_name": "Joe"},
            {"last_name": "Smith", "first_name": "Jane"},
        ],
        "year": "2018",
        "notes": "This is a note.",
        "read": "3",
    }

    common.edit_item(content, user1)
    doc = user1.documents.first()
    assert doc.read == 1

def test_edit_str_read_value_converted_to_int1(user1):
    """Read value of '0' converted to 0."""

    content = {
        "id": "1",
        "title": "Test",
        "link": "http://whatyouveread.com/1",
        "tags": ["tag0", "tag1"],
        "authors": [
            {"last_name": "Smith", "first_name": "Joe"},
            {"last_name": "Smith", "first_name": "Jane"},
        ],
        "year": "2018",
        "notes": "This is a note.",
        "read": "0",
    }

    common.edit_item(content, user1)
    doc = user1.documents.first()
    assert doc.read == 0

def test_edit_str_read_value_converted_to_int2(user1):
    """Read value of '1' converted to 1."""

    content = {
        "id": "1",
        "title": "Test",
        "link": "http://whatyouveread.com/1",
        "tags": ["tag0", "tag1"],
        "authors": [
            {"last_name": "Smith", "first_name": "Joe"},
            {"last_name": "Smith", "first_name": "Jane"},
        ],
        "year": "2018",
        "notes": "This is a note.",
        "read": "1",
    }

    common.edit_item(content, user1)
    doc = user1.documents.first()
    assert doc.read == 1

# tags

def test_edit_remove_one_tag(user0, three_items_tags_only):
    """ Removing one tag works properly."""

    for item in three_items_tags_only:
        common.add_item(item, user0)

    content = {"id": "1", "title": "Test", "tags": ["tag0"]}

    common.edit_item(content, user0)

    doc = user0.documents.first()

    assert doc.tags[0].name == "tag0" and len(doc.tags) == 1

def test_edit_remove_all_tags(user0, three_items_tags_only):
    """ Removing all tags works properly."""

    for item in three_items_tags_only:
        common.add_item(item, user0)

    content = {"id": "1", "title": "Test", "tags": []}

    common.edit_item(content, user0)

    doc = user0.documents.first()

    assert len(doc.tags) == 0

def test_edit_add_one_tag(user0, three_items_tags_only):
    """Adding one tag works properly - count."""

    for item in three_items_tags_only:
        common.add_item(item, user0)

    content = {"id": "1", "title": "Test", "tags": ["tag0", "tag1", "tag2"]}

    common.edit_item(content, user0)

    doc = user0.documents.first()

    assert len(doc.tags) == 3

def test_edit_only_one_tag_correct_text(user0, three_items_tags_only):
    """Adding one tag works properly - value."""

    for item in three_items_tags_only:
        common.add_item(item, user0)

    content = {"id": "1", "title": "Test", "tags": ["tag0", "tag1", "tag2"]}

    common.edit_item(content, user0)

    doc = user0.documents.first()

    assert doc.tags[2].name == "tag2"

def test_edit_add_tag_no_previous_tags(user0, three_items_tags_only):
    """Add one tag to doc with no previous tags."""

    for item in three_items_tags_only:
        common.add_item(item, user0)

    content = {"id": "3", "title": "Test", "tags": ["new tag"]}

    common.edit_item(content, user0)

    doc = user0.documents.filter(models.Documents.id == 3).one()

    assert len(doc.tags) == 1 and doc.tags[0].name == "new tag"

def test_delete_orphaned_tags1(user1):
    """Orphaned tags are deleted when item is deleted."""

    doc = user1.documents.first()

    common.delete_item(doc.id, user1)

    tags = common.get_user_tags(user1)

    assert len(tags) == 4 and "tag1" not in tags

def test_delete_orphaned_tags2(user1):
    """Orphaned tags are deleted when item is edited."""

    content = {
        "id": 1,
        "title": "Test",
        "link": "http://whatyouveread.com/1",
        "tags": ["tag0"],
        "authors": [
            {"last_name": "Smith", "first_name": "Joe"},
            {"last_name": "Smith", "first_name": "Jane"},
        ],
        "year": "2018",
        "notes": "This is a note.",
        "read": 1,
    }

    common.edit_item(content, user1)

    tags = common.get_user_tags(user1)

    assert len(tags) == 4 and "tag1" not in tags

# authors

def test_edit_add_one_author(user0, three_items_authors_only):
    """Adding one author works properly."""

    for item in three_items_authors_only:
        common.add_item(item, user0)

    content = {
        "id": "1",
        "title": "Test",
        "authors": [
            {"last_name": "Smith", "first_name": "Joe"},
            {"last_name": "Smith", "first_name": "Jane"},
            {"last_name": "Williams", "first_name": "Regina"},
        ],
    }

    common.edit_item(content, user0)

    doc = user0.documents.first()

    assert (
        len(doc.authors) == 3
        and doc.authors[2].first_name == "Regina"
        and doc.authors[2].last_name == "Williams"
    )

def test_edit_only_one_author_correct_text(user0, three_items_authors_only):
    """Editing one author results in correct author name."""

    for item in three_items_authors_only:
        common.add_item(item, user0)

    content = {
        "id": "1",
        "title": "Test",
        "authors": [{"last_name": "Smith", "first_name": "Jane"}],
    }

    common.edit_item(content, user0)

    doc = user0.documents.first()

    assert doc.authors[0].last_name == "Smith" and doc.authors[0].first_name == "Jane"

def test_edit_add_author_no_previous_authors(user0, three_items_authors_only):
    """Adding an author to a doc that previously had no authors."""

    for item in three_items_authors_only:
        common.add_item(item, user0)

    content = {
        "id": "3",
        "title": "Test",
        "authors": [{"last_name": "Smith", "first_name": "Jane"}],
    }

    common.edit_item(content, user0)

    doc = user0.documents.filter(models.Documents.id == 3).one()

    assert (
        len(doc.authors) == 1
        and doc.authors[0].first_name == "Jane"
        and doc.authors[0].last_name == "Smith"
    )

def test_delete_orphaned_authors1(flask_client, user1):
    """Orphaned authors are deleted when item is deleted."""

    doc = user1.documents.first()

    common.delete_item(doc.id, user1)

    authors = common.get_user_authors(user1)

    assert len(authors) == 3

def test_delete_orphaned_authors2(user1):
    """Orphaned authors are deleted when item is edited."""

    content = {
        "id": 1,
        "title": "Test",
        "link": "http://whatyouveread.com/1",
        "tags": ["tag0", "tag1"],
        "authors": [{"last_name": "Smith", "first_name": "Jane"}],
        "year": "2018",
        "notes": "This is a note.",
        "read": 1,
    }

    common.edit_item(content, user1)

    authors = common.get_user_authors(user1)

    assert len(authors) == 3

# multiple different edits

def test_edit_remove_all_tags_and_authors(user1):
    """ Removing all tags and authors works properly."""

    content = {
        "id": "1",
        "title": "Test",
        "link": "http://whatyouveread.com/1",
        "tags": [],
        "authors": [],
        "year": "2018",
        "notes": "This is a note.",
        "read": 1,
    }

    common.edit_item(content, user1)

    doc = user1.documents.first()

    assert len(doc.tags) == 0 and len(doc.authors) == 0

def test_edit_all(user1):
    """Editing everything works properly."""

    content = {
        "id": "1",
        "title": "Test Now",
        "link": "http://whatyouveread.com/5",
        "tags": ["tag2"],
        "authors": [{"last_name": "Williams", "first_name": "Regina"}],
        "year": "2017",
        "notes": "This is an edited note.",
        "read": 0,
    }

    common.edit_item(content, user1)

    doc = user1.documents.first()

    assert (
        doc.title == "Test Now"
        and doc.link == "http://whatyouveread.com/5"
        and len(doc.tags) == 1
        and doc.tags[0].name == "tag2"
        and len(doc.authors) == 1
        and doc.authors[0].first_name == "Regina"
        and doc.authors[0].last_name == "Williams"
        and doc.year == "2017"
        and doc.notes == "This is an edited note."
        and doc.read == 0
    )

def test_edit_clear_all_but_title(user1):
    """Removing everything but title works properly."""

    content = {
        "id": "1",
        "title": "Test Now",
        "link": "",
        "tags": [],
        "authors": [],
        "year": "",
        "notes": "",
        "read": 0,
    }

    common.edit_item(content, user1)

    doc = user1.documents.first()

    assert (
        doc.title == "Test Now"
        and doc.link == ""
        and len(doc.tags) == 0
        and len(doc.authors) == 0
        and doc.year == ""
        and doc.notes == ""
        and doc.read == 0
    )

def test_db_is_empty_after_previous_tests(flask_client):
    docs = models.Documents.query.all()
    assert not docs

################
# DELETING DOCS#
################

def test_delete_item(user1):
    """delete_item() works."""

    doc = user1.documents.first()

    common.delete_item(doc.id, user1, source="native")

    assert user1.documents.count() == 3

def test_delete_not_user_doc_raises_ex(user1, user2):
    """delete_item() only deletes user's own docs."""

    with pytest.raises(ex.NotUserDocException):
        common.delete_item(5, user1)

def test_delete_doc_that_does_not_exist_raises_ex(flask_client, user4):
    """delete_item() raises exception when trying to delete doc that doesn't exist."""

    with pytest.raises(ex.NotUserDocException):
        common.delete_item(5, user4)

################
# GETTING DOCS #
################

def test_get_all_docs1(flask_client, user4):
    docs = common.get_docs(user4)
    assert len(docs) == 4

def test_get_all_docs2(flask_client, user0):
    docs = common.get_docs(user0)
    assert not docs

def test_get_all_docs3(flask_client, user0, user4):
    """get_docs() only gets docs for user we pass in function."""
    docs = common.get_docs(user0)
    assert not docs

def test_get_read_docs(flask_client, user4):
    docs = common.get_docs(user4, read_status="read")
    assert len(docs) == 1

def test_get_to_read_docs(flask_client, user4):
    docs = common.get_docs(user4, read_status="to-read")
    assert len(docs) == 3

def test_get_docs_by_tag1(flask_client, user4):
    docs = common.get_docs(user4, read_status="read", tag="tag0")
    assert len(docs) == 1

def test_gets_docs_by_tag2(flask_client, user4):
    docs = common.get_docs(user4, read_status="to-read", tag="tag2")
    assert len(docs) == 2

def test_get_docs_by_tag3(flask_client, user4):
    docs = common.get_docs(user4, tag="tag0")
    assert len(docs) == 2

def test_get_docs_by_tag4(flask_client, user4):
    """get_docs returns no docs if user has no docs with that tag."""
    docs = common.get_docs(user4, tag="tag5")
    assert not docs

def test_get_docs_by_tag5(flask_client, user4, user5):
    """Only docs for passed user are returned (tag4 in both user4 and user5 docs)."""
    docs = common.get_docs(user4, tag="tag4")
    assert len(docs) == 1

def test_get_docs_by_author1(flask_client, user4):
    docs = common.get_docs(user4, author_id=1)
    assert len(docs) == 1

def test_get_docs_by_author2(flask_client, user4):
    docs = common.get_docs(user4, author_id=3)
    assert len(docs) == 1

def test_get_docs_by_author3(flask_client, user4, user5):
    """Can't access other user's authors."""
    docs = common.get_docs(user4, author_id=5)
    assert not docs

def test_get_docs_by_bunch1(flask_client, user6):

    docs = common.get_docs(user6, bunch="bunch 1")

    assert len(docs) == 4

def test_get_docs_by_bunch2(flask_client, user6):

    docs = common.get_docs(user6, bunch="bunch 2")
    assert len(docs) == 2

def test_get_docs_by_bunch3(flask_client, user6):
    "Undefined bunch."

    with pytest.raises(ex.NoBunchException):
        common.get_docs(user6, bunch="nobunch")


def checkio(matrix):
    n = len(matrix)
    dec1 = dec2 = dec3 = dec4 = False

    def check(exp1):
        if exp1[0] == exp1[1] ==exp1[2] ==exp1[3]:
            return True
        else:
            return False

    for i in range(n):
        for j in range(n - 3):
            if check(matrix[i][j : j + 4]):
                dec1 = True
                break

    if dec1 == False:
        for i in range(n):
            for j in range(n - 3):
                express = [matrix[j][i], matrix[j + 1][i], matrix[j + 2][i], matrix[j + 3][i]]
                if check(express):
                    dec2 = True
                    break

    if dec2 == False:
        for i in range(3, n):
            for j in range(n - 3):
                express = [matrix[i][j], matrix[i - 1][j + 1], matrix[i - 2][j + 2], matrix[i - 3][j + 3]]
                if check(express):
                    dec3 = True
                    break

    if dec3 == False:
         for i in range(n - 3):
            for j in range(n - 3):
                express = [matrix[i][j], matrix[i + 1][j + 1], matrix[i + 2][j + 2], matrix[i + 3][j + 3]]
                if check(express):
                    dec4 = True
                    break

    return dec1 or dec2 or dec3 or dec4


#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020 jiangyc <0599jiangyc@gmail.com>
#
# Distributed under terms of the MIT license.

import random
import csv
import string

"""
insert into Users (userId, type, userName, userPassword, lastName, firstName, phoneNumber, registrationDate, email, active) values
insert into RecentLocations (customerId, location, lastUsingTime) values
insert into CreditCards (cardNo, customerId, bank) values
insert into Restaurants (restaurantId, name, minOrderCost) values
insert into Foods (foodId, name, restaurantId, dailyLimit, quantity, price, isSold) values
insert into FoodCategories (foodId, category) values
insert into Carts (cartId, quantity, foodId, restaurantId) values
insert into DeliveryRiders (riderId, type) values
insert into WWS (workId, riderId, startDate, endDate, isUsed, workDays, baseSalary) values
insert into MWS (workId, riderId, startDate, endDate, isUsed, baseSalary, workDays, shifts) values
insert into WWS_Schedules (workId, weekday, startTime, endTime) values
insert into FullTimers (riderId, workId) values
insert into PartTimers (riderId, workId) values
insert into RestaurantStaffs (staffId, restaurantId) values
insert into FDSmanagers (managerId) values
insert into Promotions (promoId, type, value, startDate, endDate, condition, description) values
insert into RestaurantPromotions (promoId, restaurantId) values
insert into FDSPromotions (promoId, managerId) values
insert into Orders (orderId, customerId, riderId, restaurantId, orderTime, paymentMethod, cardNo, foodFee, deliveryFee, deliveryLocation, promoId) values
insert into Reviews (orderId, reviewDate, rating, feedback) values
"""

f=open("data.sql", "aw")

parttimers = [13,20,25,26,31,36,39,42,53,67,71,87,90,91,97,107,109,111,113,114,119,120,121,123,124,126,131,133,134,135,136,137,138,141,144,145,146,149,150,152,155,157,158,160,161,163,166,167,169,172,173,174,175,177,178,179,180,182,184,186,187,189,190,193,194,197,199,200]
fulltimers = [3,5,9,17,35,44,47,69,79,95,101,102,103,104,105,106,108,110,112,115,116,117,118,122,125,127,128,129,130,132,139,140,142,143,147,148,151,153,154,156,159,162,164,165,168,170,171,176,181,183,185,188,191,192,195,196,198]
def ran_letters(digit):
    ran_str = ''.join(random.sample(string.ascii_letters, digit))
    return ran_str

def ran_num(digit):
    ran_str = ''.join(random.sample(string.digits, digit))
    return ran_str

def ran_str(digit):
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, digit))
    return ran_str

for i in range(50):
    s = "INSERT INTO Foods VALUES ({}, '{}', {}, {}, {}, {}, DEFAULT);\n".format(i, ran_letters(7), i, ran_num(3), ran_num(3), ran_num(3))
    f.write(s)

for i in range(50):
    s = "insert into Restaurants values ({}, '{}', {});\n".format(i, ran_letters(7), ran_num(4))
    f.write(s)

for i in range(50):
    s = "insert into FoodCategories values ({}, {}, '{}');\n".format(i, 49-i, str(i)+ran_letters(5))
    f.write(s)

#insert into WWS (workId, riderId, startDate, endDate, baseSalary) values (1, 17, '5/8/2020', null, 115.36);

for i in range(400):
    s = "insert into WWS (workId, riderId, startDate, endDate, baseSalary) values ({}, {}, NOW()::date, null, {});\n ".format(i, random.choice(parttimers), float(random.randrange(10000,20000)/100))
    f.write(s)

for i in range(200):
    s = "insert into WWS (workId, riderId, startDate, endDate, baseSalary) values ({}, {}, (NOW() + (random() * interval '2 years') + (random() * interval '23 hours') + (random() * interval '59 minutes') + (random() * interval '59 seconds'))::date, null, {});\n ".format(i, random.choice(parttimers), float(random.randrange(10000,20000)/100))
    f.write(s)

for i in range(400):
    s = "SELECT * FROM new_mws({}, NOW()::date, {},{} , ARRAY[{},{},{},{},{}]);\n ".format(str(random.choice(fulltimers)), float(random.randrange(70000,90000)/100), random.randrange(1,5), random.randrange(1,4),random.randrange(1,4),random.randrange(1,4),random.randrange(1,4),random.randrange(1,4))
    f.write(s)

for i in range(200):
    s = "SELECT * FROM new_mws({}, (NOW() + (random() * interval '2 years') + (random() * interval '23 hours') + (random() * interval '59 minutes') + (random() * interval '59 seconds'))::date, {},{} , ARRAY[{},{},{},{},{}]);\n ".format(str(random.choice(fulltimers)), float(random.randrange(70000,90000)/100), random.randrange(1,5), random.randrange(1,4),random.randrange(1,4),random.randrange(1,4),random.randrange(1,4),random.randrange(1,4))
    f.write(s)

f.close()
##SELECT * FROM new_mws(56, 20, '2020-06-02 00:00:00', '700.28',3 , ARRAY[3,2,4,1,2]);


import pandas as pd
import math

def __truncate(f, n):
    return math.floor(f * 10 ** n) / 10 ** n

def charge(table, mode):
    ch_m = 0
    ch_a = 0
    if mode == 'M':
        ch_m = (2 * table.loc['HYP'].monoisotopic) + table.loc['OXY'].monoisotopic
        ch_a = (2 * table.loc['HYP'].average) + table.loc['OXY'].average
    elif mode == 'MH+':
        ch_m = (3 * table.loc['HYP'].monoisotopic) + table.loc['OXY'].monoisotopic
        ch_a = (3 * table.loc['HYP'].average) + table.loc['OXY'].average
    return ch_m, ch_a

def get_masses(masses_sheet, matr, mode='null'):
    table = pd.read_csv(masses_sheet, sep=',')
    table = table.set_index("code")

    ch_m, ch_a = charge(table, mode)

    monoisotopic_masses = []
    average_masses = []
    fullseq = str(''.join(matr))
    tempmatr = list(matr)
    tempmatr.append(fullseq)
    for peptide_piece in tempmatr:
        mono = 0
        avg = 0
        for c in peptide_piece:
            mono += table.loc[c].monoisotopic
            avg += table.loc[c].average
        monoisotopic_masses.append(__truncate(mono + ch_m, 3))
        average_masses.append(__truncate(avg + ch_a, 3))

    return monoisotopic_masses[:-1], average_masses[:-1], \
           monoisotopic_masses[len(monoisotopic_masses)-1], average_masses[len(average_masses)-1]


"""Monitoring object models."""
from time import time

from django.db import models
from django.utils import timezone
from .tasks import process_csv_task

def get_upload_file_name(instance, filename):
    """Process upload file name."""
    return "upload/{}_{}".format(str(time()).replace('.', '_'), filename)

class CSVUpload(models.Model):
    """CSV Upload object model class."""

    csv = models.FileField(
        upload_to=get_upload_file_name,
    )
    date = models.DateTimeField(
        default=timezone.now
    )

    def process_upload_file(self):
        """Process upload file task"""
        process_csv_task.delay(self.pk)

    def save(self, *args, **kwargs):
        """Override the save method to process task."""
        super(CSVUpload, self).save(*args, **kwargs)
        self.process_upload_file()

    def publish(self):
        """Call save method."""
        self.date = timezone.now()
        self.save()

    def __str__(self):
        return self.csv.name

class Login(models.Model):
    """Login Data object model class."""

    server_name = models.CharField(
        max_length=255,
        blank=True,
    )
    server_ip = models.CharField(
        max_length=20,
    )
    username = models.CharField(
        max_length=500,
    )
    full_name = models.CharField(
        max_length=500,
    )
    contact_email = models.EmailField(
        blank=True,
    )
    contact_number = models.CharField(
        max_length=255,
        blank=True,
    )
    login_time = models.DateTimeField(

    )

    def publish(self):
        """Call save method."""
        self.save()

    def __str__(self):
        return "Logged on {server_name} by {username} at {login_time}".format(
            server_name=self.server_name,
            username=self.username,
            login_time=self.login_time,
        )


import os
import sys

def _check():
    beta_flag = "TAMR_CLIENT_BETA"
    beta_enabled = "1"
    beta = os.environ.get(beta_flag)

    if beta != beta_enabled:
        msg = (
            f"ERROR: 'tamr_client' package is in BETA, but you do not have the '{beta_flag}' environment variable set to '1'."
            "\n\nHINT: Use 'tamr_unify_client' package instead for non-BETA features"
            f"\nHINT: Set environment variable '{beta_flag}=1' to opt-in to BETA features."
            "\n\nWARNING: Do not rely on BETA features in production workflows."
            " Support from Tamr may be limited."
        )
        print(msg)
        sys.exit(1)


from tkinter import *
from time import sleep

root = Tk()
var = StringVar()
var.set('Hello')

l = Label(root, textvariable=var)
l.pack()

for i in range(6):
	sleep(0.25)
	var.set('Goodbye' if i%2 else 'Hello')
	root.update_idletasks()


import serial
import serial.tools.list_ports
import csv
import os
from messagecontroller import nurseMessageParser as msgParser

from kivymd.uix.button import MDIconButton
from kivymd.uix.label import MDLabel

class serialClass:
    vendorId = ""
    processId = ""
    device = ""
    fileData = []

    def __init__(self):
        print('created')

    def ports(self):
        ports = list(serial.tools.list_ports.comports())
        print(ports)
        for port in ports:
            if port.vid == 6790 and port.pid == 21972 or port.vid == 1240 and port.pid == 61336:
                self.vendorId = port.vid
                self.processId = port.pid
                self.device = port.device
                print(port.device)

    def readIncomingMessage(self, buttons, queue, test1):
        print("in serial")
        buttons = buttons
        #print(buttons)
        while True:
            try:
                arduino = serial.Serial('/dev/ttyACM0', 9600)
                test1.update_conn_status("Connected")
                arduino.bytesize = 8
                arduino.timeout = .1
                value = str(arduino.readline())  # .decode("utf-8"))
                value = value[2: -1]
                if value:
                    #print(value)
                    messageData = msgParser(value)
                    if messageData is not None:
                        if messageData[2] == '0':
                            bob = buttons.get(messageData[0])
                            arduino.write(f'{bob.id}-0-{bob.sendAck}'.encode())
                            #print(f'{bob.id}-0-{bob.sendAck} sent')
                            queue.append(messageData)
                        else:
                            bob = buttons.get(messageData[0])
                            arduino.write(f'{bob.id}-0-ack'.encode())
                            #print(f'{bob.id}-0-ack sent')
                            queue.append(messageData)

            except:
                test1.update_conn_status("Connection Error")
                arduino.close()
        #return messageData

    def readcsv(self):
        with open(os.getcwd() + '/carecalldata.csv', 'rt')as f:
            file = csv.reader(f)
            for row in file:
                self.fileData.append(row)
        return self.fileData

    def write_data(self, item):
        arduino = serial.Serial('/dev/ttyUSB0', 9600)
        arduino.write(item.encode())
        #print(f"{item} sent")


import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")
Handlers=[
    (r"/", MainHandler),
]
application = tornado.web.Application(Handlers)
if __name__ == "__main__":
    application.listen(8000)
    print("Server Listening on 8000...")
    tornado.ioloop.IOLoop.current().start()


import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.nn.functional as F
from torch.optim import Adam
import matplotlib.pyplot as plt
import sys
sys.path.append('../')
from data_utils import load_data
import os
import shutil
import numpy as np
import math

# 使用 Squeeze and Excitation块，这个块提出每个通道的重要性，并对他们进行加权

# 输入的是一个已经卷积过的块
class SEModule(nn.Module):
    def __init__(self, in_channel, reduction):
        super(SEModule, self).__init__()

        self.avgpool = nn.AdaptiveAvgPool2d(1) # 1 * 1 * in_channel

        self.layer1 = nn.Sequential(
            nn.Conv2d(in_channel, in_channel // reduction, kernel_size=1),
            # 1 * 1 * in_channel//reduction 减少参数
            nn.BatchNorm2d(in_channel // reduction),
            nn.ReLU()
            )
        self.layer2 = nn.Sequential(
            nn.Conv2d(in_channel // reduction, in_channel, kernel_size=1), # 1 * 1 * in_channel
            nn.Sigmoid(),
            )

    def forward(self, x):
        module_input = x
        out = self.avgpool(x)
        out = self.layer1(out)
        out = self.layer2(out)
        return module_input * out

class SEBottleneckBlock(nn.Module):
    expansion = 4

    def __init__(self, in_channel, out_channel, stride=1, downsample=None, reduction=16):
        # 当 in_channel = out_channel 时，立刻可以直接相加
        super(SEBottleneckBlock, self).__init__()
        # 1 * 1 卷积 缩小想输出的维度
        # 这里的out_channel为输出的out_channel 的1/4
        self.layer1 = nn.Sequential(
            nn.Conv2d(in_channel, out_channel // self.expansion, kernel_size=1),
            nn.BatchNorm2d(out_channel // self.expansion))

        self.relu = nn.ReLU(inplace=True)

        # 特征图可能大小的改变发生在这里
        self.layer2 = nn.Sequential(
            nn.Conv2d(out_channel // self.expansion, out_channel // self.expansion, kernel_size=3, stride=stride, padding=1),
            nn.BatchNorm2d(out_channel // self.expansion))

        # 1 * 1 、卷积还原通道数
        self.layer3 = nn.Sequential(
            nn.Conv2d(out_channel // self.expansion, out_channel, kernel_size=1),
            nn.BatchNorm2d(out_channel)
            )

        self.se_module = SEModule(out_channel, reduction=reduction)
        self.downsample = downsample
        self.stride = stride

    def forward(self,x):
        residual = x

        out = self.layer1(x)
        out = self.relu(out)
        out = self.layer2(out)
        out = self.relu(out)
        out = self.layer3(out)
        out = self.relu(out)

        out = self.se_module(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out = out + residual
        out = self.relu(out)
        return out

class SENet(nn.Module):
    def __init__(self, block, layers, num_classes=10, reduction=16):

        # 输入 224 * 224 * 3
        super(SENet,self).__init__()

        self.in_channel = 64

        self.layer0 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3),
            # (224 - 7 + 3 * 2) // 2 + 1 = 112.5
            # 舍弃 ？
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
            # (112 - 3 + 2 * 1)// 2 + 1 = 57?
            # 56 * 56 * 64
            )

        # 传入瓶颈块走一下流程
        # 传入需要重复的基础块， 传入需要输出的通道数， 传入基础块需要循环的次数
        self.layer1 = self._make_layer(block, 64, layers[0], reduction=reduction)
        # 第一次 x = 56 * 56 * 64, layers[0] = 3
        # f(x) => (56 - 3 + 2 * 1)/ 1 + 1 = 56 (卷积两次形状不变)， out_channel = 64
        # 输出 56 * 56 * 64

        # 也就是说，特征图的长宽大小由stride决定，通道数由out_channel决定
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2, reduction=reduction)
        # 输出 (56 - 3 + 2 * 1)// 2 + 1= 28 out_channel = 128
        # 输出 28 * 28 * 128
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2, reduction=reduction)
        # 输出 14 * 14 * 256
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2, reduction=reduction)
        # 输出 7 * 7 * 512

        self.avgpool = nn.AvgPool2d(7)
        # 输出512
        self.fc = nn.Sequential(
            nn.Linear(512, num_classes),
            nn.BatchNorm1d(num_classes)
#             nn.ReLU()
            )

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            if isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def _make_layer(self, block, out_channel, blocks, stride=1, reduction=16):
        # channel 需要输出的通道数，blocks 需要叠加几次block
        downsample = None
        if stride != 1 or self.in_channel != out_channel:
            downsample = nn.Sequential(
                nn.Conv2d(self.in_channel, out_channel,
                    kernel_size=1, stride=stride),
                nn.BatchNorm2d(out_channel)
                )
        layers = []

        layers.append(block(self.in_channel, out_channel, stride, downsample, reduction))

        self.in_channel = out_channel

        for i in range(1, blocks):
            layers.append(block(self.in_channel, out_channel=out_channel, reduction=reduction))

        return nn.Sequential(*layers)

    def forward(self, x):
        out = self.layer0(x)
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        out = self.avgpool(out)
        out = out.reshape(out.size(0), -1)
        out = self.fc(out)

        return out

class senet_model(object):

    def __init__(self, dataset_path, save_model_path, save_history_path, epochs, batchsize, device, mode):
        """
        dataset_path:'./data/train_data'
        save_path:'./data_save'
        epochs:10
        bacth_size:20
        z_dim:100
        device: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        """
        self.model_name = 'senet'

        self.dataset_path = dataset_path
        self.save_model_path = save_model_path
        self.save_history_path = save_history_path
#         self.epochs = epochs
        self.epochs = 10
#         self.batch_size = batch_size
        self.batch_size = 20
        self.mode = mode
        self.learning_rate = 5e-3
        self.num_classes = 10
        if device == "cuda" and torch.cuda.is_available():
            self.device = torch.device("cuda:1")
        else:
            self.device = torch.device("cpu")
        self.criterion = nn.CrossEntropyLoss().to(self.device)

        self.train_data, self.test_data = load_data(self.dataset_path, net_name=self.model_name)

        self.train_loader = torch.utils.data.DataLoader(self.train_data, batch_size=self.batch_size, shuffle=True)
        self.test_loader = torch.utils.data.DataLoader(self.test_data, batch_size=self.batch_size, shuffle=False)

        self.trian_batch_nums = len(self.train_loader) // self.batch_size
        self.test_batch_nums = len(self.test_loader) // self.batch_size

        self.train_loss_history = []
        self.val_loss_history = []
        self.train_accuracy_history = []
        self.val_accuracy_history = []
        self.cur_model_name = os.path.join(self.save_model_path, 'current_{}.t7'.format(self.model_name))
        self.best_model_name = os.path.join(self.save_model_path, 'best_{}.t7'.format(self.model_name))
        self.max_loss = 0
        self.min_loss = float("inf")

    # def adjust_learning_rate(self, epoch, optimizer):
    #     """Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
    #     self.learning_rate *= (0.1 ** (epoch // 30))
    #     for param_group in optimizer.param_groups:
    #         param_group['lr'] = self.learning_rate

    def train(self):
        try:
            model = torch.load(self.cur_model_name).to(self.device)
            print("continue train the last model")
        except FileNotFoundError:
            model = SENet(SEBottleneckBlock, layers=[3, 4, 6, 3], num_classes=self.num_classes, reduction=16).to(self.device)

        optimizer = Adam(model.parameters(), betas=(.5, 0.999), lr=self.learning_rate)
        scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=10, eta_min=8e-4)

        for epoch in range(self.epochs):

#             self.adjust_learing_rate(epoch, optimizer)
            scheduler.step()
            print("Main epoch:{}".format(epoch))
            # count the accuracy when train data
            correct = 0
            total = 0
            step = 0
            for i, (images, labels) in enumerate(self.train_loader):

                # batch_size=100,所以step = 50000/100 = 500
                step += 1

                images = images.to(self.device)
                labels = labels.to(self.device)
                # compute output
                outputs = model(images)
                train_loss = self.criterion(outputs, labels)

                # compute accuracy
                _, predicted = torch.max(outputs.data, 1)
                total += labels.size(0)
                correct += (predicted == labels).sum().item()

                # compute gradient and do Adam step
                optimizer.zero_grad()
                train_loss.backward()
                optimizer.step()
                if step % 100 == 0:
                    print("epoch:{}, step:{}, loss:{}, accuracy:{}".format(epoch, step, train_loss.item(),(100 * correct / total)))

                #show result and save model
                # step = epochs * (50000 // batch_size) = 100 * 50000 // 100 = 50000
                # if (step % 100) == 0:
            # each epoch store the history and accurate
            self.train_loss_history.append(train_loss)
            self.max_loss = max(self.max_loss, train_loss)
            self.min_loss = min(self.min_loss, train_loss)
            # 计算模型在训练集上准确率
            train_accuracy = 100 * correct / total
            self.train_accuracy_history.append(train_accuracy)

            # 保存当前模型
            torch.save(model, self.cur_model_name)

            # 计算当前模型在测试集上的准确率的准确率
            val_accuracy = self.validate()
            self.val_accuracy_history.append(val_accuracy)

            # 如果准确率高，则替换最佳模型为当前模型
            if epoch > 0 and val_accuracy > max(self.val_accuracy_history[:-1]):
                # 每一轮训练之后进行验证，如果平均准确率高
                # 这里加上准确率的判断，如果在验证集的前多少取得的准确率较高，则替换模型
                shutil.copyfile(self.cur_model_name, self.best_model_name) # 把cur_model复制给best_model

        # 调用print_history将loss画出来并保存为图片
        # print_accarucy将在验证集上的准确率保存下来，存到图片里
        self.min_loss = self.min_loss.item()
        self.max_loss = self.max_loss.item()
        self.plot_curve()

    def validate(self):
        model = torch.load(self.cur_model_name).to(self.device)
        # Test model
        model.eval()

        # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
        with torch.no_grad():
            correct = 0
            total = 0
            for i, (images, labels) in enumerate(self.test_loader):
                #  reshape images to (batch, input_size)
                images = images.to(self.device)
                labels = labels.to(self.device)
                # forward pass
                outputs = model(images)
                val_loss = self.criterion(outputs, labels)
                # print(outputs.data.shape, type(outputs.data))
                # print(outputs.shape, type(outputs))
                _, predicted = torch.max(outputs.data, 1)
                total += labels.size(0)
                correct += (predicted == labels).sum().item()
            print("current accuracy in this epoch is {}".format(100 * correct / total ))
            val_accuracy = 100 * correct / total
            self.val_loss_history.append(val_loss)
            self.max_loss = max(self.max_loss, val_loss)
            self.min_loss = min(self.min_loss, val_loss)
        return val_accuracy

    def test(self):
        model = torch.load(self.best_model_name).to(self.device)
        # Test model
        model.eval()

        # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
        with torch.no_grad():
            correct = 0
            total = 0
            for i, (images, labels) in enumerate(self.test_loader):
                #  reshape images to (batch, input_size)
                images = images.to(self.device)
                labels = labels.to(self.device)
                # forward pass
                outputs = model(images)

                _, predicted = torch.max(outputs.data, 1)
                total += labels.size(0)
                correct += (predicted == labels).sum().item()
            print("current accuracy in this epoch is {}".format(100 * correct / total))

    def plot_curve(self):

        title = 'the accuracy curve of train/validate'

        dpi = 80
        width, height = 1200, 800
        legend_fontsize = 10
        scale_distance = 48.8
        figsize = width / float(dpi), height / float(dpi)

        fig = plt.figure(figsize=figsize)
        x_axis = np.array([i for i in range(self.epochs)]) # epochs
        y_axis = np.zeros(self.epochs)

        plt.xlim(0, self.epochs)
        plt.ylim(0, 100)
        interval_y = 5
        interval_x = 5
        plt.xticks(np.arange(0, self.epochs + interval_x, interval_x))
        plt.yticks(np.arange(0, 100 + interval_y, interval_y))
        plt.grid()
        plt.title(title, fontsize=20)
        plt.xlabel('the training epoch', fontsize=16)
        plt.ylabel('accuracy', fontsize=16)

        y_axis = self.train_accuracy_history
        plt.plot(x_axis, y_axis, color='g', linestyle='-', label='train_accuracy', lw=2)
        plt.legend(loc=4, fontsize=legend_fontsize)

        y_axis = self.val_accuracy_history
        plt.plot(x_axis, y_axis, color='y', linestyle='-', label='valid_accuracy', lw=2)
        plt.legend(loc=4, fontsize=legend_fontsize)

        fig_name = self.save_history_path + "{}_accuracy_history".format(self.model_name)
        fig.savefig(fig_name, dpi=dpi, bbox_inches='tight')
        print ('---- save accuracy history figure {} into {}'.format(title, self.save_history_path))
        plt.close(fig)

        title = 'the loss curve of train/validate'
        fig = plt.figure(figsize=figsize)

        x_axis = np.array([i for i in range(self.epochs)]) # epochs
        y_axis = np.zeros(self.epochs)

        plt.xlim(0, self.epochs)
        plt.ylim(self.min_loss, self.max_loss)
        interval_y = (self.max_loss - self.min_loss) / 20
        interval_x = 5
        plt.xticks(np.arange(0, self.epochs + interval_x, interval_x))
        plt.yticks(np.arange(max(0,self.min_loss - 5 * interval_y), self.max_loss + 2 * interval_y, interval_y))
        plt.grid()
        plt.title(title, fontsize=20)
        plt.xlabel('the training epoch', fontsize=16)
        plt.ylabel('loss', fontsize=16)

        y_axis = self.train_loss_history
        plt.plot(x_axis, y_axis, color='g', linestyle=':', label='train_loss', lw=2)
        plt.legend(loc=4, fontsize=legend_fontsize)

        y_axis = self.val_loss_history
        plt.plot(x_axis, y_axis, color='y', linestyle=':', label='val_loss', lw=2)
        plt.legend(loc=4, fontsize=legend_fontsize)

        fig_name = self.save_history_path + "{}_loss_history".format(self.model_name)
        fig.savefig(fig_name, dpi=dpi, bbox_inches='tight')
        print ('---- save loss_history figure {} into {}'.format(title, self.save_history_path))
        plt.close(fig)