# List that will keep a copy of the dictionaries created.
listForPersonData = []
ageSum = 0

while True:
    print('-' * 40, '\n')
    print(' ' * 8 + 'REGISTER A PERSON')
    print('\n' + '-' * 40)
    print()

    # Create a new dictionary for each person.
    personData = {"Name": '', "Age": []}
    personData["Name"] = str(input("Name: "))

    # Loop using try-except to validate the person's age.
    while True:
        try:
            Age = int(input("Age: "))
            personData["Age"].append(Age)
            break
        except ValueError:
            pass
    ageSum += Age

    # Create a key in the dictionary for gender, with validation.
    personData["Gender"] = input("Gender [M/F]: ").upper().strip()[0]
    while personData["Gender"] not in ['M', 'F']:
        personData["Gender"] = str(input('Gender [M/F]: ')).upper().strip()[0]

    # Copying the person data to the list.
    listForPersonData.append(personData.copy())
    personData.clear()

    # Separte the registration from the stop condition.
    print('\n' + '-' * 40)

    # Stop contition.
    Continuation_Option = str(input('\nDo you want to continue? [Y/N]: ')).upper().strip()[0]
    print()

    # Validate the stop condition.
    if Continuation_Option in 'YN':
        if Continuation_Option == 'Y':
            continue
        if Continuation_Option == 'N':
            break
    else:
        while Continuation_Option not in 'YN':
            Continuation_Option = str(input('\nDo you want to continue? [Y/N]: ')).upper().strip()[0]
            print()
        if Continuation_Option == 'N':
            break

# Calculate the average age.
averageOfAge = ageSum / len(listForPersonData)

#Final results.
print(f'''A) {len(listForPersonData)} people were registered.
B) The average age is {averageOfAge:.1f}''')
print(f'C) The female(s) registred was: ',end='')

# For each dictionary in our list that stores the data, we check if the person has the key "Gender" with the value "F".
for person in listForPersonData:
    if person["Gender"] == 'F':
        print(person["Name"], end=' ')
print()

# Loop "for" with another "for" loop inside to check if the key "Age" in the personData dictionary is above the average.
print('D) People list whose age is above the average: ')

# Iterate through each dictionary created for each person.
for person in listForPersonData:

    # Create another "for" loop to check if the person's age is above the average.
    for age in person['Age']:

        # Perform the validation.
        if age >= averageOfAge:
            print(' ')
            for key, value in person.items():
                print(f'{key} = {value} ', end='')


# 198. 打家劫舍
# 你是一个专业的小偷，计划偷窃沿街的房屋。每间房内都藏有一定的现金，影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统，
# 如果两间相邻的房屋在同一晚上被小偷闯入，系统会自动报警。
# 给定一个代表每个房屋存放金额的非负整数数组，计算你 不触动警报装置的情况下 ，一夜之内能够偷窃到的最高金额。
def rob(nums):
    if not nums:
        return 0
    if len(nums) < 3:
        return max(nums)
    cashWithDistanceOf2 = nums[0]
    cashWithDistanceOf1 = max(nums[0], nums[1])
    for i in range(2, len(nums)):
        cashWithDistanceOf2, cashWithDistanceOf1 = cashWithDistanceOf1, max(cashWithDistanceOf2 + nums[i], cashWithDistanceOf1)
    return cashWithDistanceOf1

numss = [[2, 7, 9, 3, 1], [1, 2, 3, 1]]
for nums in numss:
    print('输入：{}\t结果：{}'.format(nums, rob(nums)))


from imageai.Detection import ObjectDetection
import os

imgOutput = "image_output.jpg"

def get_img_src(src):
    return src

def config_remote_detection(img, probability):
    obj_detect = ObjectDetection()
    obj_detect.setModelTypeAsYOLOv3()

    obj_detect.setModelPath("yolo.h5")
    obj_detect.loadModel()

    obj_detect.CustomObjects(remote=True)

    detected_obj = obj_detect.detectObjectsFromImage(
        input_image=get_img_src(img),
        output_image_path=imgOutput,
        minimum_percentage_probability=probability,
    )
    os.remove(imgOutput)
    os.remove(img)
    return detected_obj

def find_remote(img, probability):
    remote_detected = config_remote_detection(img, probability)
    for obj in remote_detected:
        if obj["name"] == "remote":
            return 1
        else:
            return 0

# im = PIL.Image.open("test_image_output.jpg")
# im.show()


import sys

input=sys.stdin.readline

n=int(input())
arr=[]
ans=[0,0,0]
for _ in range(n):
    arr.append(list(map(int,input().split())))

def sol(n,x1,y1,x2,y2):               # x2 y2 필요없을듯
    if n==1:
        ans[arr[y1][x1]+1]+=1
        return
    chk=True
    for i in range(y1,y2):
        if chk==False:
            break
        for j in range(x1,x2):
            if arr[i][j]!=arr[y1][x1]:
                chk=False
                div=n//3
                for k in range(3):
                    for l in range(3):
                        sol(div,x1+k*div,y1+l*div,x1+(k+1)*div,y1+(l+1)*div) # 분할하는거 반복문으로 줄일 수 있음
                break # return 해서 chk 필요 없게
    if chk:
        ans[arr[y1][x1]+1]+=1

sol(n,0,0,n,n)
for i in ans:
    print(i)


#!/usr/bin/env python

"""
This script is for deploying the staging server. It automatically updates the
codebase and restarts paster in daemon mode. Optionally, pass it -d to go into
staging debug mode (no daemon and with the debugger turned on)
"""
import os, sys
import subprocess
from mercurial.localrepo import localrepository
from mercurial.ui import ui
from deploy import deploy

REPOPATH = os.path.join(os.environ['REPOSITORY'], 'masterapp')

#Change to repository
os.chdir(REPOPATH)

#Update repository
subprocess.check_call(['hg', 'up'])

#Update compressed javascript
os.chdir('./helpers')
sys.path.append('.')
import compressor
compressor.main()

#Install changes in stage server
deploy('STAGING', '-d' in sys.argv or '--debug' in sys.argv)

#Update database schema
os.chdir(os.path.join(
    os.environ['REPOSITORY'], 'masterapp', 'masterapp', 'model', 'manage')
)
subprocess.check_call(['python', 'mysqlmgr.py', 'upgrade'])

#Record the current version.
repo = localrepository(ui(), os.environ['REPOSITORY'])
fd = open(os.path.join(os.environ['STAGING'], 'changeset'), 'w')
fd.write(str(repo.changectx()))
fd.close()


"""
<Brute Force>
"""

from itertools import permutations
from sys import *

"""
N = int(stdin.readline().rstrip())

# number list
NUMBER = list(map(int, stdin.readline().rstrip().split()))

# answer
ANSWER = 0

PER = permutations(NUMBER)

for per in PER:
    total = 0
    for i in range(len(per) - 1):
        total += abs(per[i] - per[i + 1])

    ANSWER = max(ANSWER, total)

print(ANSWER)
"""

"""
<INCORRECT> - There would be same elements in NUMBER
<SOLUTION> - check index visited or not
"""

def permutation(LIST, NUMBER):
    global N, ANSWER
    if len(LIST) == N:
        total = 0
        for i in range(len(LIST) - 1):
            total += abs(LIST[i] - LIST[i + 1])

        ANSWER = max(ANSWER, total)
        return

    for i in range(N):
        if not visited[i]:
            LIST.append(NUMBER[i])
            visited[i] = True
            permutation(LIST, NUMBER)
            LIST.pop()
            visited[i] = False

N = int(stdin.readline().rstrip())

# number list
NUMBER = list(map(int, stdin.readline().rstrip().split()))

# answer
ANSWER = 0

# visited
visited = [False] * N

# permutation
permutation([], NUMBER)
print(ANSWER)


import matplotlib.pyplot as plt
import numpy as np
import os

deg_sign = u'\N{DEGREE SIGN}'
folder4 = ""
folder3 = ""
folder2 = ""
folder1 = "default"
#specify model names below here:

#folder1 = "narrow0.50-cj18.0"
#folder1 = "narrow_in-low_cj5-long"
#folder2 = "sigma0.5-in450-cj25-long"
#folder2 = "narrow_in-low_cj-fixed_in"
#folder1 = "sigma0.5-in450-cj25"
#folder2 = 'halfVel_cj38_long'
#folder3 = "halfVel_cj36_long"
#folder1 = "sigma0.5-in450-cj25"
#folder2 = "sigma0.5-in450-cj25-long"

#folder1 ="narrow0.50-cj18.0"
#folder2 ="sigma0.5-in450-cj25"

#folder1 = "sigma0.5_cj25"
#folder2 = "LinPop10_sigma0.5_ovar0.3"

#folder2 = "pop4-narrow"
#folder2 = "pop5-narrow"
#folder3 = "pop6-narrow"

#folder1 = 'sigma0.5_cj25'
#folder1 = "sigma0.5-in450-cj25-long"
#folder2 = 'LinPop10_sigma0.5_ivar0.1_ovar0_long'
#folder1 = 'LinPop10_sigma0.5_ovar0.3'
# folder1 = 'sigma0.5_cj35'
# folder3 = 'sigma0.5_cj15'
# folder2 = 'LinPop10_sigma0.5_ovar0.3_cj35'
# folder4 = 'LinPop10_sigma0.5_ovar0.3_cj15'

# folder1 = "LinPop10_sigma0.5_ivar0.1_ovar0_long"
# folder2 = "LinPop10_sigma0.5_ivar0.5_ovar0_long"

#folder1 = "LinPop10_sigma0.5_ivar0.1_ovar0_long"
#folder1 = "LinPop10_sigma0.5_ivar0.5_ovar0_long"
#folder2 = "LinPop10_sigma0.5_ivar0.5_ovar0.5_excj550"
#folder3 = "LinPop10_sigma0.5_ivar0.5_ovar0.5_excj750"

#folder1 = "sigma0.5-in450-cj25-long"
#folder1 = "LinPop10_sigma0.5_ivar0.1_ovar0_long"
#folder2 = "LinPop10_sigma0.5_ivar0.3_ovar0"
#folder3 = "LinPop10_sigma0.5_ivar0.5_ovar0_long"

#folder1 = "sigma0.5-in450-cj25-long"
folder1 = "sigma0.5_cj25"

dir = ""
if folder2=="":
    dir = "results/comparisons/"+folder1+"/"
    if not os.path.exists(f'results/comparisons/{folder1}'):
        os.makedirs(f'results/comparisons/{folder1}')
elif folder3=="":
    dir = "results/comparisons/"+folder1+" "+folder2+"/"
    if not os.path.exists(f'results/comparisons/{folder1} {folder2}'):
        os.makedirs(f'results/comparisons/{folder1} {folder2}')
elif folder4=="":
    dir = "results/comparisons/"+folder1+" "+folder2+" "+folder3+"/"
    if not os.path.exists(f'results/comparisons/{folder1} {folder2} {folder3}'):
        os.makedirs(f'results/comparisons/{folder1} {folder2} {folder3}')
else:
    dir = "results/comparisons/"+folder1+" "+folder2+" "+folder3+" "+folder4+"/"
    if not os.path.exists(f'results/comparisons/{folder1} {folder2} {folder3} {folder4}'):
        os.makedirs(f'results/comparisons/{folder1} {folder2} {folder3} {folder4}')

def fetch(folder):
    X = []
    Y = []
    Z = []
    W = []
    f = open("results/" + folder + "/vel_drift_data.txt")
    for row in f:
        row = row.split(' ')
        X.append(float(row[0]))
        Y.append(float(row[1]))
        Z.append(float(row[2]))
        if(len(row)>3):
            W.append(float(row[3]))
    Y = [y for _,y in sorted(zip(X,Y))]
    Z = [z for _,z in sorted(zip(X,Z))]
    if(len(W)>0):
        W = [w for _,w in sorted(zip(X,W))]
    X.sort()
    params = open("results/" + folder + "/Parameters.txt").readlines()
    pop = int(params[11].split()[1])
    W = [elem / pop for elem in W]
    return X, Y, Z, W

def Denoise(Y):
    nY = Y
    nY[0] = 0.67 * Y[0] + 0.33*Y[1]
    nY[-1] = 0.67 * Y[-1] + 0.33*Y[-2]
    for i in range(1,len(Y)-1):
        nY[i] = 0.33 * Y[i-1] + 0.34 * Y[i] + 0.33 * Y[i+1]
    return nY

def draw(x_lim, x_min = 0, rates=False, denoise=False):
    X1, _Y1, Z1, W1 = fetch(folder1)
    if(folder2!=""):
        X2, _Y2, Z2, W2 = fetch(folder2)
    if(folder3!=""):
        X3, _Y3, Z3, W3 = fetch(folder3)
    if(folder4!=""):
        X4, _Y4, Z4, W4 = fetch(folder4)
    if(denoise):
        if(folder1!="default"):
            _Y1 = Denoise(_Y1)
        if(folder2!=""):
            _Y2 = Denoise(_Y2)
        if(folder3!=""):
            _Y3 = Denoise(_Y3)
        if(folder4!=""):
            _Y4 = Denoise(_Y4)
    fig,ax = plt.subplots()
    ax.hlines(0, 0, 1000, 'k', alpha=0.5)
    ax.plot(X1, _Y1, 'bo-', markersize=1, label="Rate of Drift")#"180" + deg_sign + " rotation")
    if(folder2!=""):
        ax.plot(X2, _Y2, 'go-', markersize=1, label=folder2)#"720" + deg_sign + " rotation")
    if(folder3!=""):
        ax.plot(X3, _Y3, 'ro-', markersize=1, label=folder2)#label="Reduced AHV current and Narrow Inhibition")
    if(folder4!=""):
        ax.plot(X4, _Y4, 'o-', color='orange', markersize=1, label=folder4)#label="Reduced AHV current and Narrow Inhibition")
    ax.set_xlim([x_min, x_lim])
    #plt.ylim([-80, 80])
    ax.set_ylabel("Rate of drift (" + deg_sign + "/s)",color="Black",fontsize=14)
    ax.set_xlabel("Constant AHV (" + deg_sign + "/s)",fontsize=14)
    ax.set_ylim([-80, 20])
    if folder2=="" and rates:
        ax2=ax.twinx()
        ax2.plot(X1, W1, 'ro-', markersize=0.5, alpha=0.7, label="CJ spike rate")
        ax2.plot(X1, Z1, 'o-', color='orange', markersize=0.5, alpha=0.7, label="EX spike rate")
        ax2.set_ylabel("Average peak CJ firerate (Hz)",color="Black",fontsize=14)
        ax2.set_ylim([0, 100])
    if folder2!="" and rates:
        ax2=ax.twinx()
        ax2.plot(X1, W1, 'ro-', markersize=0.5, alpha=0.7, label=folder1+" CJ spike rate")
        ax2.plot(X2, W2, 'o-', color='orange', markersize=0.5, alpha=0.7, label=folder2+" CJ spike rate")
        ax2.set_ylabel("Average peak CJ firerate (Hz)",color="Black",fontsize=14)
    if folder3!="" and rates:
        ax2.plot(X3, W3, 'yo-', markersize=0.5, alpha=0.7, label=folder3+" CJ spike rate")
    fig.legend()
    dn = ""
    if(denoise):
        dn="_denoise"
    fig.savefig(dir+"/DriftThruVel_"+str(x_lim)+dn+".png", dpi=300,bbox_inches="tight")
    plt.clf()

draw(80, rates=True, denoise=False)
#draw(80, denoise=True)
print("DONE")


from django.db import transaction, models
from .base import BasePlugin
from ...main.models.history import HistoryLines

class Plugin(BasePlugin):
    __slots__ = ()
    writeable = True
    readable = True

    async def _write_line(self, line: str, number: int, endl: str = ''):
        await HistoryLines.objects.abulk_create([
            HistoryLines(line_gnumber=number, line_number=1, line=line + endl, history=self.history)
        ])

    def get_lines(self):
        return HistoryLines.objects.filter(history=self.history)

    def get_facts_data(self):
        return self.get_raw(
            original=False,
            excludes=(
                models.Q(line__contains="No config file") | models.Q(line__contains="as config file"),
            )
        )

    @transaction.atomic()
    def clear(self, msg=''):
        self.get_lines().delete()
        if msg:
            self.write_line(msg, number=1, endl='')


from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivymd.uix.button import MDFloatingActionButton
from kivymd.app import MDApp
from kivymd.uix.dialog import MDDialog
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.pickers import MDDatePicker
from datetime import datetime
from kivymd.uix.screen import MDScreen
from kivymd.uix.list import ThreeLineAvatarIconListItem, ILeftBodyTouch
from kivymd.uix.selectioncontrol import MDCheckbox
from kivy.core.text.markup import MarkupLabel
from kivy.uix.label import Label
from kivymd.toast import toast
from kivymd.uix.pickers import MDDatePicker
from kivy.utils import platform

if platform == "android":
    from android.permissions import request_permissions, Permission
    request_permissions([Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE])

class DialogContent(MDBoxLayout):
    """OPENS A DIALOG BOX THAT GETS THE INPUT FROM THE USER"""
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # set the date_text label to today's date when user first opens dialog box
        self.ids.date_text.text = str(datetime.now().strftime('%A %d %B %Y'))
        self._noofpeople = "3"
        self.final = 0

    def show_date_picker(self):
        """Opens the date picker"""
        date_dialog = MDDatePicker()
        date_dialog.bind(on_save=self.on_save)
        date_dialog.open()

    def on_save(self, instance, value, date_range):
        """This functions gets the date from the date picker and converts its it a
        more friendly form then changes the date label on the dialog to that"""

        date = value.strftime('%A %d %B %Y')
        self.ids.date_text.text = str(date)

    def noofpeople_increment(self):
        """This function will get make the plus sign button work"""
        self._noofpeople = MarkupLabel(self._noofpeople).markup
        self._noofpeople = int(self._noofpeople[0])
        self._noofpeople += 1
        self._noofpeople = f'{self._noofpeople}'
        self.ids.noofpeople.text = self._noofpeople

    def noofpeople_decrement(self):
        """This function will get make the minus sign button work"""
        self._noofpeople = MarkupLabel(self._noofpeople).markup
        self._noofpeople = int(self._noofpeople[0])
        if self._noofpeople > 2:
            self._noofpeople -= 1
        self._noofpeople = f'{self._noofpeople}'
        self.ids.noofpeople.text = self._noofpeople

    def show_popup(self):
        """define a toast message for the input to input the total amount of bills"""
        if self.ids.amount.text== '':
            toast("Please input the total amount of bills")

    def final_calc(self):
        """Thia is the calculation part"""
        if self.ids.amount.text== '':
            def show_popup(self):
                 toast("Please input the total amount of bills")
        else:
            #convert amount input from user into float
            numofinput = float(self.ids.amount.text)
            self._noofpeople = MarkupLabel(self.ids.noofpeople.text).markup
            #convert no of people into integer
            self._noofpeople = int(self._noofpeople[0])
            #compute
            self.final = round(((numofinput)/(self._noofpeople)), 1)
            self._noofpeople = f'{self._noofpeople}'
            self.ids.noofpeople.text = self._noofpeople
            #convert the result into string so that can be display
            last_bill =  str(self.final)
            #change the label in total_bill into the result
            self.ids.total_bill.text = last_bill

class ListItemWithCheckbox(ThreeLineAvatarIconListItem):
    '''Custom list item'''

    def __init__(self, pk=None, **kwargs):
        super().__init__(**kwargs)
        # state a pk which we shall use link the list items with the database primary keys
        self.pk = pk

    def mark(self, check, the_list_item):
        '''mark the task as complete or incomplete'''
        if check.active == True:
            # add strikethrough to the text if the checkbox is active
            the_list_item.text = '[s]'+the_list_item.text+'[/s]'
        else:

            pass

    def delete_item(self, the_list_item):
        '''Delete the task'''
        self.parent.remove_widget(the_list_item)

class LeftCheckbox(ILeftBodyTouch, MDCheckbox):
    '''Custom left container'''

class MainApp(MDApp):
    task_list_dialog = None
    def build(self):
        # Setting theme to my favorite theme
        self.theme_cls.primary_palette = "Indigo"

    def show_task_dialog(self):
        if not self.task_list_dialog:
            self.task_list_dialog = MDDialog(
                title="Create Bill",
                type="custom",
                content_cls=DialogContent(),
            )

        self.task_list_dialog.open()

    def close_dialog(self, *args):
        self.task_list_dialog.dismiss()

    def add_task(self, name, bill_date , total_bill, amount, no_of_people):
        '''Add task to the list of tasks'''

        print(name.text, bill_date, total_bill.text, no_of_people.text)
        self.root.ids['container'].add_widget(ListItemWithCheckbox(text='[b]'+name.text+'[/b]',
        secondary_text=bill_date ,  tertiary_text="bills to pay per person: " + total_bill.text + " | " + no_of_people.text + " people"))
        name.text = '' # set the dialog entry to an empty string(clear the text entry)
        total_bill.text = '0' # set the total bill display on screen to become 0
        amount.text = ''

class ContentNavigationDrawer(BoxLayout):
    screen_manager = ObjectProperty()
    nav_drawer = ObjectProperty()

if __name__ == '__main__':
    app = MainApp()
    app.run()


from scipy.stats import friedmanchisquare
import pandas as pd

data = pd.read_csv('algo_performance.csv')
# print(data)

sample1 = data['C4.5'].tolist()
sample2 = data['1-NN'].tolist()
sample3 = data['NaiveBayes'].tolist()
sample4 = data['Kernel'].tolist()
sample5 = data['CN2'].tolist()

stat, p = friedmanchisquare(sample1, sample2, sample3, sample4, sample5)
print(p)

# alpha = 0.01
alpha = 0.05
# alpha = 0.1

if p > alpha:
    print('H0 is True')
else:
    print('H0 is False')


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from random import randint

import qdarkstyle
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

# from CustomListWidget import CustomListWidget
from TaskSettingsWidget import TaskSettingsWidget
from TaggingWidget import TaggingWidget
from ConfigWidget import ConfigWidget
from TrainWidget import TrainWidget
from TestWidget import TestWidget
from MapWidget import MapWidget
from AnchorWidget import AnchorWidget

sys.path.append("..")

"""
主页面
"""
import os

print(os.getcwd())

class Winform(QWidget):
    def __init__(self, *args, **kwargs):
        super(Winform, self).__init__(*args, **kwargs)

        self.resize(1280, 720)
        #self.setFixedSize(QSize(1280, 720))
        self.setMinimumSize(QSize(1280, 720))
        # 左侧列表
        self.listWidget = QListWidget(self, objectName="listWidget")

        # 右侧层叠窗口
        self.stackedWidget = QStackedWidget(self)

        # 左右布局(左边一个QListWidget + 右边QStackedWidget)
        layout = QHBoxLayout(self, spacing=0)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.listWidget)
        layout.addWidget(self.stackedWidget)

        self.initUi()

        self.setWindowTitle("Yolo V4 模型训练工具")
        self.setWindowIcon(QIcon("image/darknet.png"))

    def initUi(self):
        self.listWidget.setStyleSheet("""QListWidget {
                                        min-width: 180px;
                                        max-width: 180px;
                                        outline: 0px;
                                        font-size: 15px;
                                        border-right: 10px;
                                        }
                                        /*被选中时的背景颜色和左边框颜色*/
                                        QListWidget::item:selected {
                                        background-color: SkyBlue;
                                        color: black;
                                        border-left: 3px solid rgb(9, 187, 7);
                                        }

                                        """)
        self.stackedWidget.setStyleSheet("""QStackedWidget {
                                        background-color: white;
                                        border-left: 2px solid rgb(0, 0, 0);
                                        }""")
        # 初始化界面
        self.listWidget.setIconSize(QSize(50, 50))
        # 通过QListWidget的当前item变化来切换QStackedWidget中的序号
        self.listWidget.currentRowChanged.connect(
            self.stackedWidget.setCurrentIndex)
        # 去掉边框
        self.listWidget.setFrameShape(QListWidget.NoFrame)
        # 隐藏滚动条
        self.listWidget.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.listWidget.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)

        # 1.任务设置
        startItem = QListWidgetItem(
                QIcon('image/home.png'), "1.任务设置", self.listWidget)
        startItem.setSizeHint(QSize(16777215, 100))
        startItem.setTextAlignment(Qt.AlignCenter)

        # 2.导入标注
        taggingItem = QListWidgetItem(
                QIcon('image/tagging.png'), "2.导入标注", self.listWidget)
        taggingItem.setSizeHint(QSize(16777215, 100))
        taggingItem.setTextAlignment(Qt.AlignCenter)

        # 3.修改配置
        configItem = QListWidgetItem(
                QIcon('image/setting.png'), "3.修改配置", self.listWidget)
        configItem.setSizeHint(QSize(16777215, 100))
        configItem.setTextAlignment(Qt.AlignCenter)

        # 4.开始训练
        trainItem = QListWidgetItem(
                QIcon('image/train.png'), "4.开始训练", self.listWidget)
        trainItem.setSizeHint(QSize(16777215, 100))
        trainItem.setTextAlignment(Qt.AlignCenter)

        # 5.测试模型
        testItem = QListWidgetItem(
                QIcon('image/test.png'), "5.测试模型", self.listWidget)
        testItem.setSizeHint(QSize(16777215, 100))
        testItem.setTextAlignment(Qt.AlignCenter)

        # 6.性能统计
        mapItem = QListWidgetItem(
                QIcon('image/性能统计.png'), "6.性能统计", self.listWidget)
        mapItem.setSizeHint(QSize(16777215, 100))
        mapItem.setTextAlignment(Qt.AlignCenter)

        # 7.聚类分析
        anchorItem = QListWidgetItem(
                QIcon('image/anchor.png'), "7.聚类分析", self.listWidget)
        anchorItem.setSizeHint(QSize(16777215, 100))
        anchorItem.setTextAlignment(Qt.AlignCenter)

        taskSettingsWidget = TaskSettingsWidget()
        taskSettingsWidget.setContentsMargins(200, 50, 200, 50)
        self.stackedWidget.addWidget(taskSettingsWidget)

        taggingWidget = TaggingWidget()
        taggingWidget.setContentsMargins(0, 0, 0, 0)
        self.stackedWidget.addWidget(taggingWidget)

        configWidget = ConfigWidget()
        configWidget.setContentsMargins(50, 50, 50, 50)
        self.stackedWidget.addWidget(configWidget)

        trainWidget = TrainWidget()
        trainWidget.setContentsMargins(50, 50, 50, 50)
        self.stackedWidget.addWidget(trainWidget)

        testWidget = TestWidget()
        testWidget.setContentsMargins(50, 50, 50, 50)
        self.stackedWidget.addWidget(testWidget)

        mapWidget = MapWidget()
        mapWidget.setContentsMargins(50, 50, 50, 50)
        self.stackedWidget.addWidget(mapWidget)

        anchorWidget = AnchorWidget()
        anchorWidget.setContentsMargins(50, 50, 50, 50)
        self.stackedWidget.addWidget(anchorWidget)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = Winform()
    win.show()
    sys.exit(app.exec_())


try:
    for i in range('a', 'g'):
        print(ord(i) ** 2)
except:
    print("cannot multiply literal")

for i in range(ord('a'), ord('g')):
    print(i ** 2)

x = 5
y = 0
try:
    z = x/y
except ZeroDivisionError as e:
    print("Can't divide by Zero")
finally:
    print("Divided")

while True:
    try:
        n = int(input("Input an Integer >"))
    except:
        print("Cannot convert literal to integer, try entering integer ")
        continue
    else:
        print("inside else block")
        print(n**2)
        break
    finally:
        print("You're a devil !")


import dbfuncs as db
######### Packages ########
import pandas as pd
import pandas.io.sql as sqlio
import psycopg2
from sodapy import Socrata
import matplotlib as mpl
import yaml
import dbfuncs as db
from datetime import datetime

## Read Config
config = yaml.safe_load(open("config.yaml"))
databasename = config["postgreSQL"]["database"]

#Fionn

avg_week_year = """SELECT date_part('year', date_day::date) as year,
       date_part('week', date_day::date) AS weekly,
       AVG(total) as total, AVG(acf) as acf, AVG(aer) as aer,
       AVG(apg) as apg, AVG(grf) as grf, AVG(hcs) as hcs,
       AVG(tws) as tws, AVG(retail) as retail, AVG(retail_nogroc) as retail_nogroc
       FROM cosp
       GROUP BY year, weekly
       ORDER BY year, weekly;"""

try:
    conn = db.getDBConnection(config,databasename)
    cosp_df = sqlio.read_sql_query(avg_week_year, conn)
    cosp_df.to_csv('all_avg_week_year.csv')
except (Exception , psycopg2.Error) as dbError :
    print ("Error:", dbError)
finally:
    if(conn):
        conn.close()
print("test")

# cosp_df.info()
# print(cosp_df.head())

#Sean

avg_week_year = """SELECT *
       FROM close_price_change
       ;"""

try:
    conn = db.getDBConnection(config,databasename)
    changeDf = sqlio.read_sql_query(avg_week_year, conn)

except (Exception , psycopg2.Error) as dbError :
    print ("Error:", dbError)
finally:
    if(conn):
        conn.close()

# changeDf.info()
# print(changeDf.head())

#Donal
avg_week_year = """SELECT *
       FROM tweetsentiment
       ;"""

try:
    conn = db.getDBConnection(config,databasename)
    dfTwitterSentiment = sqlio.read_sql_query(avg_week_year, conn)

except (Exception , psycopg2.Error) as dbError :
    print ("Error:", dbError)
finally:
    if(conn):
        conn.close()

# dfTwitterSentiment.info()
# print(dfTwitterSentiment.head())

#dfTwitterSentiment

cosp_df['date'] = pd.to_datetime(cosp_df.apply(lambda x: datetime.strptime('{0} {1} 1'.format(int(x['year']), int(x['weekly'])), '%Y %W %w'), axis=1),utc=True)

dfTwitterSentiment['tweetdate'] = pd.to_datetime(dfTwitterSentiment['tweetdate'],utc=True)

combinedDf = pd.merge(dfTwitterSentiment, cosp_df, left_on='tweetdate', right_on='date', how = 'inner')

print(combinedDf)

#changeDf.reset_index(inplace=True)
changeDf['Date'] = pd.to_datetime(changeDf['Date'],utc=True)
combinedDf2 = pd.merge(combinedDf, changeDf, left_on='tweetdate', right_on='Date', how = 'inner')

print(combinedDf2)

#Run Pearson correlation on all columns of the DataFrame.
correlationsDf = combinedDf2.corr()
correlationsDf.info()

#print(correlationsDf)


from PyQt5.uic import loadUi
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QDialog, QTableWidget, QHeaderView, \
    QTableWidgetItem, QAbstractItemView, QFileDialog, QMessageBox
from PyQt5.QtCore import QCoreApplication, Qt

import csv
import json

from Buttons import EditButton, DeleteButton
from UpdateEmployeeWindow import UpdateEmployeeWindow
from DataVisualizationWindow import DataVisualizationWindow

class EmployeesDashboard(QDialog):

    def __init__(self):
        super(EmployeesDashboard, self).__init__()

        self.edit_col_index = None
        self.delete_col_index = None
        self.widget = QtWidgets.QStackedWidget()
        self.widget.setFixedHeight(833)
        self.widget.setFixedWidth(1342)
        self.update_employee_window = None
        self.data_visualization_window = None
        self.index = 1  # Used to control data_visualization/update_employee windows
        self.update_emp_index = None
        self.data_vis_index = None

        loadUi("EmployeesGUI.ui", self)

        # Used to add new features to the employee table
        self.format_table_widget()

        self.employees_list = []

        # Fake Data
        with open('data/Sample_Employee_Data.json', 'r') as f:
            # Used to load each line as a json object and appends to the list
            self.employees_list = json.load(f)

        self.display_employees()

        # Used when the "Add Employee" button is clicked, and it opens a new window
        self.addEmployeeButton.clicked.connect(self.switch_dialog_to_new_emp)

        self.dataVisualizationButton.clicked.connect(self.switch_dialog_to_data_vis)

        self.CSV_Import.clicked.connect(self.import_csv)

        self.CSV_Download.clicked.connect(self.download_csv)

        # Used to connect sorting box to sort by the selected option
        self.sortComboBox.currentIndexChanged.connect(self.sort_employees)

    # Used to switch the window to the AddEmployeeWindow class
    def switch_dialog_to_new_emp(self):
        print("switch_dialog_to_new_emp() is called")
        self.widget.setCurrentIndex(1)

    # Used to switch the window to the UpdateEmployeeWindow class
    def switch_dialog_to_update_emp(self, current_emp):
        if self.update_employee_window is None:
            # New window for updating employees
            self.update_employee_window = UpdateEmployeeWindow(self.widget,
                                                               self.display_employees,
                                                               self.employees_list)
            self.widget.addWidget(self.update_employee_window)

            self.index = self.index + 1
            self.update_emp_index = self.index

        self.update_employee_window.find_current_emp(current_emp)
        self.widget.setCurrentIndex(self.update_emp_index)

    # Used to switch the window to the DataVisualization class
    def switch_dialog_to_data_vis(self):
        print("switch_dialog_to_data_visualization() is called")
        if self.data_visualization_window is None:
            self.data_visualization_window = DataVisualizationWindow(self.widget,
                                                                     self.employees_list)
            self.widget.addWidget(self.data_visualization_window)

            self.index = self.index + 1
            self.data_vis_index = self.index

        self.widget.setCurrentIndex(self.data_vis_index)

    def format_table_widget(self):
        # Used to stretch the columns
        self.tableWidget.horizontalHeader().setSectionResizeMode(
            QHeaderView.Stretch)

        # Used to locate the id column index
        self.id_col_index = 0

        # Used to locate the delete/edit column index
        self.delete_col_index = self.tableWidget.columnCount() - 1
        self.edit_col_index = self.tableWidget.columnCount() - 2

        self.tableWidget.horizontalHeader().setSectionResizeMode(
            self.id_col_index, QHeaderView.Fixed)

        # Used to design the delete/edit buttons width
        self.tableWidget.horizontalHeader().setSectionResizeMode(
            self.delete_col_index, QHeaderView.Fixed)
        self.tableWidget.horizontalHeader().setSectionResizeMode(
            self.edit_col_index, QHeaderView.Fixed)

        self.tableWidget.horizontalHeader().resizeSection(self.id_col_index, 100)

        self.tableWidget.horizontalHeader().resizeSection(self.delete_col_index, 80)
        self.tableWidget.horizontalHeader().resizeSection(self.edit_col_index, 80)

        # Used to remove the highlight when the row is selected
        self.tableWidget.setSelectionMode(QAbstractItemView.NoSelection)

        # Used to highlight the item on inside the table
        self.tableWidget.setSelectionMode(QTableWidget.SingleSelection)

        # Used to set focus on the item only when it is clicked
        self.tableWidget.setFocusPolicy(Qt.ClickFocus)

    # Sort the employees by using sorting box
    def sort_employees(self, index):
        if index == 0:  # Sort by ID
            self.employees_list.sort(key=lambda x: x["id"])
        elif index == 1:  # Sort by Name
            self.employees_list.sort(key=lambda x: x['name'])
        elif index == 2:  # Sort by Salary: High to Low
            self.employees_list.sort(key=lambda x: x['salary'], reverse=True)
        elif index == 3:  # Sort by Salary: Low to High
            self.employees_list.sort(key=lambda x: x['salary'])

        # Used to update the displayed employees
        self.display_employees()

    # Update the displayed employees
    def display_employees(self):

        # Used to check if employee list is empty or not
        if not self.employees_list:
            self.tableWidget.hideRow(0)
            self.tableWidget.clearContents()
            self.tableWidget.horizontalHeader().hideSection(self.delete_col_index)
            self.tableWidget.horizontalHeader().hideSection(self.edit_col_index)
            self.noDataLabel.show()
        else:
            self.tableWidget.showRow(0)
            self.tableWidget.horizontalHeader().showSection(self.delete_col_index)
            self.tableWidget.horizontalHeader().showSection(self.edit_col_index)
            self.noDataLabel.hide()

            row = 0
            self.tableWidget.setRowCount(len(self.employees_list))

            # Used to iterate over the employees and display them
            for employee in self.employees_list:
                id_item = QtWidgets.QTableWidgetItem(str(employee["id"]))
                id_item.setToolTip(str(employee["id"]))
                self.tableWidget.setItem(row, 0, id_item)

                name_item = QtWidgets.QTableWidgetItem(str(employee["name"]))
                name_item.setToolTip(str(employee["name"]))
                self.tableWidget.setItem(row, 1, name_item)

                position_item = QtWidgets.QTableWidgetItem(
                    str(employee["position"]))
                position_item.setToolTip(str(employee["position"]))
                self.tableWidget.setItem(row, 2, position_item)

                salary_converted = self.format_salary(employee["salary"])
                salary_item = QtWidgets.QTableWidgetItem(salary_converted)
                salary_item.setToolTip(salary_converted)
                self.tableWidget.setItem(row, 3, salary_item)

                country_item = QtWidgets.QTableWidgetItem(
                    str(employee["country"]))
                country_item.setToolTip(str(employee["country"]))
                self.tableWidget.setItem(row, 4, country_item)

                age_item = QtWidgets.QTableWidgetItem(
                    str(employee["age"]))
                age_item.setToolTip(str(employee["age"]))
                self.tableWidget.setItem(row, 5, age_item)

                # Create a fix/delete buttons
                edit_button = EditButton(self.tableWidget,
                                         self.display_employees,
                                         self.employees_list, row, employee)

                delete_button = DeleteButton(self.tableWidget,
                                             self.display_employees,
                                             self.employees_list, row, employee)

                # Passing the employee["id"] argument to the remove_employee method
                # when the button is clicked, using a lambda function as a wrapper.
                delete_button.del_button.clicked.connect(
                    lambda _, employee_id=employee["id"]:
                    delete_button.confirm_deletion(employee_id))

                edit_button.edit_button.clicked.connect(
                    lambda _, employee_id=employee["id"]:
                    self.switch_dialog_to_update_emp(employee_id)
                )

                row += 1

    def import_csv(self):
        fileName, _ = QFileDialog.getOpenFileName(self, 'Open file', './')

        if fileName:
            try:
                self.employees_list = []
                with open(fileName, 'r') as f:
                    csvReader = csv.DictReader(f)
                    for row in csvReader:
                        row["id"] = int(row["id"])
                        row["salary"] = int(row["salary"])
                        row["age"] = int(row["age"])
                        self.employees_list.append(row)
            except Exception as e:
                QMessageBox.warning(self, 'Error',
                                    'Failed to Import The File: ' + fileName)

        self.display_employees()

    def download_csv(self):
        # Open a save file dialog and get the chosen file path and name
        filename, _ = QFileDialog.getSaveFileName(self, "Save CSV", "",
                                                  "CSV Files (*.csv)")

        # Used to check if a file name was selected (cancel was not clicked)
        if filename != '':
            # If the file does not end in .csv, append .csv
            if not filename.endswith('.csv'):
                filename += '.csv'

            # Column names of the data
            fields = ["id", "name", "position", "salary", "country", "age"]

            # Used to write to the CSV file
            with open(filename, mode='w', newline='') as csvfile:
                # Creating a CSV writer object
                csvwriter = csv.writer(csvfile)

                # Used to write the column headers
                csvwriter.writerow(fields)

                # Used to write the data rows
                for row in self.employees_list:
                    csvwriter.writerow(
                        [row["id"], row["name"], row["position"], row["salary"],
                         row["country"], row["age"]])

            self.show_success_alert(filename)

    # An alert pops up to confirm that the file is saved successfully
    def show_success_alert(self, filename):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setText(f"CSV file has been saved to: {filename}")
        msg.setWindowTitle("SUCCESS")
        msg.exec_()

    def format_salary(self, salary):
        return "{:,.0f}$".format(salary)

    def mousePressEvent(self, event):
        # If there is no item at the clicked position, clear the selection
        self.tableWidget.clearSelection()
        # Call the superclass implementation to handle the event
        super().mousePressEvent(event)