# -*- coding: utf-8 -*-

from knock30 import load_mecab
from knock36 import morpheme_count
import matplotlib.pyplot as plt

def log_log_graph(rank):
    x = []
    y = []
    for i, (morpheme, count) in enumerate(rank):
        x.append(i+1)
        y.append(count)
    plt.scatter(x, y, s=10, marker='.')
    plt.yscale('log')
    plt.xscale('log')
    plt.show()

if __name__ == '__main__':
    path = 'neko.txt.mecab'
    rank = sorted(morpheme_count(load_mecab(path)).items(), key=lambda x: -x[1])
    log_log_graph(rank)


# coding: utf-8

import json
import codecs
import os

with codecs.open('golang-tour.json',encoding='utf-8') as f:
    root = json.load(f)
i = 0
for x in root:
    t = '%.2d-%s' % (i,root[x]["Title"])
    if not os.path.exists(t):
        os.mkdir(t)
    j = 1
    for p in root[x]['Pages']:
        with codecs.open('%s/%.2d-%s.html'%(t,j,p['Title']),'w',encoding='utf-8') as fw:
            fw.write(p['Content'])
        for f in p['Files']:
            with codecs.open('%s/%.2d-%s'%(t,j,f['Name']),'w',encoding='utf-8') as fw:
                fw.write(f['Content'])
        j += 1
    i += 1


import curses
import time

from cellauto.core import GameWin
from cellauto.grids import life, ant, multi_ant

class TermWin(GameWin):

    def __init__(self):
        GameWin.__init__(self)
        self.stdscr = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.curs_set(0)
        self.stdscr.keypad(1)

        self.win_coords = self.stdscr.getmaxyx()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        curses.echo()
        curses.nocbreak()
        curses.curs_set(1)
        self.stdscr.keypad(0)

        curses.endwin()

    def add_game(self, game_grid):
        super(TermWin, self).add_game(game_grid)
        self.game_grid.rebuild(self.win_coords[0] - 2, self.win_coords[1] - 2)

    def draw_welcome(self):
        try:
            self.stdscr.clear()
            if self.stdscr.getmaxyx() != self.win_coords:
                self.win_coords = self.stdscr.getmaxyx()
            self.stdscr.addstr(1,1, 'WELCOME TO THE GAME OF LIFE')
            self.stdscr.addstr(3,1, 'Please choose a game:')
            self.stdscr.addstr(4,2, '1 - Life')
            self.stdscr.addstr(5,2, '2 - Langton\'s Ant')
            self.stdscr.addstr(6,2, '3 - Multi-Ant')
            self.stdscr.addstr(7,2, '4 - 34 Life')
            self.stdscr.addstr(8,2, 'h - Help')
            self.stdscr.addstr(9,2, 'q - quit')
            self.stdscr.refresh()
            while True:
                command = self.stdscr.getch()
                if command == 49:
                    self.add_game(life.LifeGrid(20, 20))
                    break
                elif command == 50:
                    self.add_game(ant.AntGrid(20, 20))
                    break
                elif command == 51:
                    self.add_game(multi_ant.MultiAntGrid(20,20))
                    break
                elif command == 52:
                    self.add_game(life.LifeGrid(20, 20, [3,4], [3,4]))
                    break
                elif command == 104:
                    pass
                elif command == 113:
                    return 1
                else:
                    self.stdscr.addstr(9,1, 'Command not recognised.')
                    self.stdscr.refresh()
            self.stdscr.clear()
            self.stdscr.addstr(1,1, 'WELCOME TO THE GAME OF LIFE')
            self.stdscr.addstr(3,1, 'Please press a key:')
            self.stdscr.addstr(4,2, 'r - Random start')
            self.stdscr.addstr(5,2, 'e - Empty start')
            self.stdscr.addstr(6,2, 'h - Help')
            self.stdscr.addstr(7,2, 'q - Quit')
            self.stdscr.refresh()
            while True:
                command = self.stdscr.getch()
                if command == 114:
                    self.game_grid.random_grid(0.2)
                    return 0
                elif command == 101:
                    self.game_grid.clear_grid()
                    return 0
                elif command == 104:
                    pass
                elif command == 113:
                    return 1
                else:
                    self.stdscr.addstr(9,1, 'Command not recognised.')
                    self.stdscr.refresh()
        except curses.error:
            print('Why did you make the terminal so bloody small?')
            return 1

    def draw_grid(self):
        self.stdscr.clear()
        if self.stdscr.getmaxyx() != self.win_coords:
            self.win_coords = self.stdscr.getmaxyx()
            self.game_grid.rebuild(self.win_coords[0] - 2, self.win_coords[1] - 2)
        hori_bar = "#"*(self.game_grid.x_size)
        self.stdscr.addstr(0, 1, hori_bar)
        self.stdscr.addstr(0, 2, self.title)
        for i, row in enumerate(self.game_grid.grid):
            self.stdscr.addstr(i+1, 0, '#')
            for j, item in enumerate(row):
                if item != 0:
                    self.stdscr.addstr(i+1, j+1, self.game_grid.char_map(i, j))
            self.stdscr.addstr(i+1, self.game_grid.x_size+1, '#')
        self.stdscr.addstr(self.game_grid.y_size + 1, 1, hori_bar)
        self.stdscr.refresh()

    def edit_grid(self):
        self.title = "Editting"
        curses.curs_set(1)
        self.stdscr.move(1,1)
        cursor_pos = [0, 0]
        while True:
            time.sleep(0.03)
            self.draw_grid()
            try:
                self.stdscr.move(cursor_pos[0]+1, cursor_pos[1]+1)
            except curses.error:
                cursor_pos = [0, 0]
                self.stdscr.move(cursor_pos[0]+1, cursor_pos[1]+1)
            command = self.stdscr.getch()
            if command == 103:
                curses.curs_set(0)
                return 0
            elif command == 113:
                curses.curs_set(0)
                return 1
            # elif command == 120:
            #     self.game_grid.grid[cursor_pos[0]][cursor_pos[1]] = 0
            # elif command == 99:
            #     self.game_grid.grid[cursor_pos[0]][cursor_pos[1]] = 1
            elif command == 122:
                self.game_grid.clear_grid()
            elif command == 114:
                self.game_grid.random_grid(0.2)
            elif command == curses.KEY_UP:
                if cursor_pos[0] == 0:
                    pass
                else:
                    cursor_pos[0] = cursor_pos[0] - 1
            elif command == curses.KEY_DOWN:
                if cursor_pos[0] == len(self.game_grid.grid) - 1:
                    pass
                else:
                    cursor_pos[0] = cursor_pos[0] + 1
            elif command == curses.KEY_LEFT:
                if cursor_pos[1] == 0:
                    pass
                else:
                    cursor_pos[1] = cursor_pos[1] - 1
            elif command == curses.KEY_RIGHT:
                if cursor_pos[1] == len(self.game_grid.grid[0]) - 1:
                    pass
                else:
                    cursor_pos[1] = cursor_pos[1] + 1
            elif command == -1:
                pass
            else:
                self.game_grid.edit_map(cursor_pos[0], cursor_pos[1], command)

    def run_grid(self, time_delay=0.05):
        self.stdscr.nodelay(True)
        while True:
            self.title = "Running"
            self.draw_grid()
            command = self.stdscr.getch()
            if command == 113:
                self.stdscr.nodelay(False)
                return
            elif command == 101:
                state = self.edit_grid()
                if state == 0:
                    pass
                else:
                    self.stdscr.nodelay(False)
                    return
            elif command == 112:
                self.title = "Paused"
                self.draw_grid()
                self.stdscr.nodelay(False)
                while True:
                    command = self.stdscr.getch()
                    if command == 113:
                        return
                    elif command == 103:
                        self.stdscr.nodelay(True)
                        break
                    elif command == 101:
                        self.stdscr.nodelay(True)
                        state = self.edit_grid()
                        if state == 0:
                            break
                        else:
                            self.stdscr.nodelay(False)
                            return
                    else:
                        self.stdscr.addstr(len(self.game_grid.grid)+1, 0, 'Command not recognised.')
                        self.stdscr.refresh()
            elif command == curses.KEY_UP:
                if time_delay > 0.01:
                    time_delay -= 0.01
            elif command == curses.KEY_DOWN:
                time_delay += 0.01
            elif command == curses.KEY_RIGHT:
                time_delay = 0.05
            self.game_grid.evolve()
            time.sleep(time_delay)

    def run_prog(self):
        while True:
            if self.draw_welcome() == 0:
                self.run_grid()
            else:
                break


from sacred import Ingredient
from schnetpack.metrics import *

metrics_ing = Ingredient("metrics")

@metrics_ing.config
def config():
    r"""
    Settings for metrics that will be used for logging the training session.
    """
    element_wise = ["forces"]  # list of elementwise properties (e.g. forces)

@metrics_ing.capture
def build_metrics(names, property_map, element_wise):
    """
    builds a list with schnetpack.metrics.Metric objects

    Args:
        names (list): names of the metrics that should be used
        property_map (dict): mapping between model properties and dataset
            properties
        element_wise (list): list of the element_wise properties

    Returns:
        list of schnetpack.metrics.Metric objects
    """
    metrics_objects = []
    for metric in names:
        metric = metric.lower()
        if metric == "mae":
            metrics_objects += [
                MeanAbsoluteError(tgt, p, element_wise=p in element_wise)
                for p, tgt in property_map.items()
                if tgt is not None
            ]
        elif metric == "rmse":
            metrics_objects += [
                RootMeanSquaredError(tgt, p, element_wise=p in element_wise)
                for p, tgt in property_map.items()
                if tgt is not None
            ]
        else:
            raise NotImplementedError
    return metrics_objects


def getPuzzleInput():
    return [int(char) for char in "253149867"]

def solvePart1(cups):
    u = 0
    max_label = max(cups)

    for i in range(100):
        current = cups[u % 9]
        to_be_moved = [cups[(u+k+1) % 9] for k in range(3)]
        for each in to_be_moved:
            cups.remove(each)
        destination = current - 1
        if destination == 0:
            destination = max_label
        while destination not in cups or destination == current:
            destination -= 1
            if destination == 0:
                destination = max_label
        dest_index = cups.index(destination)
        cups.insert(dest_index + 1, to_be_moved[0])
        cups.insert(dest_index + 2, to_be_moved[1])
        cups.insert(dest_index + 3, to_be_moved[2])

        u = (cups.index(current) + 1) % 9
    return cups[(cups.index(1) + 1):] + cups[:cups.index(1)]

class Cup:
    def __init__(self, value):
        self.next = None
        self.value = value

def solvePart2(cups):
    total = 1000 * 1000
    moves = 10 * total
    lookup = {}
    prev = None
    for i in range(total):
        value = int(cups[i]) if i < len(cups) else i + 1
        cup = Cup(value)
        lookup[value] = cup
        if prev:
            prev.next = cup
        else:
            first = cup
        prev = cup
    prev.next = first
    current = first
    for x in range(moves):
        removed = current.next
        current.next = removed.next.next.next
        label = current.value
        while True:
            label -= 1
            if not label:
                label = total
            if label not in (removed.value, removed.next.value, removed.next.next.value):
                break
        dest = lookup[label]
        removed.next.next.next = dest.next
        dest.next = removed
        current = current.next

    one = lookup[1]

    return one.next.value * one.next.next.value

if __name__ == "__main__":
    puzzleInput = getPuzzleInput()
    answer1 = solvePart1(puzzleInput)
    answer1String = ''.join(str(e) for e in answer1)
    print(f"Res Part 1: {answer1String}")

    puzzleInput = getPuzzleInput()
    answer2 = solvePart2(puzzleInput)
    print(f"Res Part 2: {answer2}")


"""
CPU functionality.
Constructor that contains all of the instructions for the CPU
"""

import sys
from main_ops import main_branch
from alu_ops import alu_branch

# Branchtable variables
HLT = 0b00000001
CALL = 0b01010000
RET = 0b00010001
IRET = 0b00010011
JEQ = 0b01010101
JGE = 0b01011010
JGT = 0b01010111
JLE = 0b01011001
JLT = 0b01011000
JMP = 0b01010100
JNE = 0b01010110

class CPU:
    """Main CPU class."""

    def __init__(self):
        # ram that holds 256 bytes (list of 0)
        self.ram = [0] * 256
        # 8 registers (list of 0)
        self.reg = [0] * 8
        # reg7 resets/defaults to 0xF4
        self.reg[7] = 0XF0
        # internal pc register = 0
        self.pc = 0
        # setup branch table
        self.is_running = False
        # use pattern 00000LGE for FL register
        self.FL = 0b00000000
        # use R5 for interrupt mask, R6 for interrupt status
        self.IM = self.reg[5]
        self.IS = self.reg[6]
        self.main_branch = main_branch
        self.alu_branch = alu_branch

    def ram_read(self, MAR): # MAR = Memory address register
        # uses an address to read and returns the value stored at that address
        return self.ram[MAR]

    def ram_write(self, MAR, MDR): # MDR = Memory data register
        self.ram[MAR] = MDR

    def load(self, filename):
        """Load a program into memory."""

        try:
            address = 0
            with open(filename) as f:
                for line in f:
                    comment_split = line.split('#')
                    n = comment_split[0].strip()
                    if n:
                        value = int(n,2)
                        self.ram[address] = value
                        address += 1

        except FileNotFoundError:
            print(f"{sys.argv[0]}: {filename} not found")

    def alu(self, op, reg_a, reg_b):
        """
        ALU operations.
        Operations which perform math must bitwise-AND
        w/ 0xFF (255) to ensure they stay in the range
        of 0 - 255
        """

        if op == "ADD":
            self.reg[reg_a] += self.reg[reg_b]
            self.reg[reg_a] &= 0xFF

        elif op == 'MUL':
            self.reg[reg_a] *= self.reg[reg_b]
            self.reg[reg_a] &= 0xFF

        elif op == 'AND':
            self.reg[reg_a] &= self.reg[reg_b]
            self.reg[reg_a] &= 0xFF

        elif op == 'CMP':
            if self.reg[reg_a] == self.reg[reg_b]:
                # set E to true and leave others alone
                self.FL = self.FL | 0b00000001
            elif self.reg[reg_a] > self.reg[reg_b]:
                # set G to true and leave others alone
                self.FL = self.FL | 0b00000010
            elif self.reg[reg_a] < self.reg[reg_b]:
                # set L to true and leave others alone
                self.FL = self.FL | 0b00000100

        elif op == 'DEC':
            self.reg[reg_a] -= 1
            self.reg[reg_a] &= 0xFF

        elif op == 'DIV':
            if self.reg[reg_b]:
                self.reg[reg_a] /= self.reg[reg_b]

            else:
                self.main_branch[HLT]
                raise Exception("Cannot divide by 0")

        elif op == 'INC':
            self.reg[reg_a] += 1
            self.reg[reg_a] &= 0xFF

        elif op == 'MOD':
            if self.reg[reg_b]:
                self.reg[reg_a] %= self.reg[reg_b]

            else:
                self.main_branch[HLT]
                raise Exception("Cannot divide by 0")

        elif op == 'NOT':
            self.reg[reg_a] = self.reg[reg_a] ^ 0b11111111

        elif op == 'OR':
            self.reg[reg_a] |= self.reg[reg_b]

        elif op == 'SHL':
            self.reg[reg_a] = (self.reg[reg_a] << self.reg[reg_b])

        elif op == 'SHR':
            self.reg[reg_a] = (self.reg[reg_a] >> self.reg[reg_b])

        elif op == 'SUB':
            self.reg[reg_a] -= self.reg[reg_b]

        elif op == 'XOR':
            self.reg[reg_a] = self.reg[reg_a] ^ self.reg[reg_b]

        else:
            raise Exception("Unsupported ALU operation")

    def trace(self):
        """
        Handy function to print out the CPU state. You might want to call this
        from run() if you need help debugging.
        """

        print(f"TRACE: %02X | %02X %02X %02X |" % (
            self.pc,
            #self.fl,
            #self.ie,
            self.ram_read(self.pc),
            self.ram_read(self.pc + 1),
            self.ram_read(self.pc + 2)
        ), end='')

        for i in range(8):
            print(" %02X" % self.reg[i], end='')

        print()

    def run(self):
        """Run the CPU."""
        self.is_running = True

        while self.is_running:
            # read the memory address stored in PC and store it in IR(instruction register local to this method)
            ir = self.ram_read(self.pc)

            operand_a = self.ram_read(self.pc + 1)
            operand_b = self.ram_read(self.pc + 2)

            add_to_pc = (ir >> 6) + 1

            if ir in main_branch.keys():
                self.main_branch[ir](self, operand_a, operand_b)
            elif ir in alu_branch.keys():
                self.alu_branch[ir](self, operand_a, operand_b)

            jumps = [CALL, RET, JEQ, JGE, JGT, JLE, JLT, JMP, JNE, IRET]

            if ir not in jumps:
                self.pc += add_to_pc


from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

class TableRead:
    def __init__(self,url):
        self.table1_tr_list = list()
        self.table1_tr_list2 = list()
        self.url = urlopen(url) #주소
        self.soup = BeautifulSoup(self.url, "html.parser")  #html코드 저장

    def tables_read(self,class_name):
        self.tables = self.soup.find_all('table',{'class':class_name}) #테이블태그 클래스이름으로 전부 찾기

    def trs_read(self,num):
        self.trs = self.tables[num].find_all('tr')  #몇번째(찾는) 테이블에서 tr코드 전부 찾기
        for i in range(len(self.trs)):  #html코드 버리고 텍스트 부분만 추출
            self.table1_tr_list.append(self.trs[i].text.strip())

    def mk_df(self,start,colname):  #행의 시작지점과 열의 이름위치를 인자로 받기
        for i in range(len(self.table1_tr_list)):   #df에 들어갈 값들을 임시리스트로 정리, 최종 리스트에 2차원으로 저장
            if i >= start:
                self.tr_list_value = self.table1_tr_list[i].split('\n')

                for j in range(len(self.tr_list_value)-1):  #누적사망자수열을 제외한 총 열의 길이만큼 반복
                    for k in range(len(self.tr_list_value[j])): #문자열의 크기만큼 반복
                        if self.tr_list_value[j][k] == '(':
                            self.tr_list_value[j] = int(self.tr_list_value[j][k+1:-1].replace(',',''))
                            break
                # print(self.tr_list_value)
                self.table1_tr_list2.append(self.tr_list_value)
        self.df = pd.DataFrame(self.table1_tr_list2)    #데이터프레임 생성
        self.df.columns = self.table1_tr_list[colname].split('\n')  #columns에 들어갈 행 추출 및 정리
        self.df = self.df.drop('누적사망자수', axis=1)    #누적사망자수 열 삭제

    def show_df(self):
        print(self.df)

    def graph(self,day):
        plt.rc('font', family='Malgun Gothic', size=6.5)
        sns.barplot(data=self.df, x=day, y='국가/일').set_title(f'{day} 당일 코로나 확진자 수')
        plt.show()

if __name__ == '__main__':

    covid_df = TableRead("http://ncov.mohw.go.kr/bdBoardList_Real.do?brdId=1&brdGubun=14&ncvContSeq=&contSeq=&board_id=&gubun=")
    covid_df.tables_read('num')
    covid_df.trs_read(1)
    covid_df.mk_df(1,0)
    covid_df.graph('05.15')
    # covid_df.test()


from cnn_tensorflow_classifier import *
from sklearn.model_selection import cross_val_score
from sklearn.neural_network import MLPClassifier
from sklearn import linear_model
from random import shuffle
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import numpy as np
from math import ceil
from sklearn.feature_selection import VarianceThreshold
import matplotlib.pyplot as plt

def get_top_feat(coef, feats, n_top):
    coef_np = np.array(coef[0])
    coef_abs = np.absolute(np.array(coef[0]))
    # sorted_coef = sorted(coef_abs.tolist(), reverse=True)
    sorted_coef = sorted(coef_np.tolist(), reverse=True)
    # cond = coef_abs > sorted_coef[n_top]
    cond = coef_np > sorted_coef[n_top]
    # print(coef_abs[cond])
    # print(coef_np[cond])
    # plt.hist(coef_np[cond], bins=np.arange(-4.0, 4.0, 0.1))
    # plt.show()
    # exit()
    selected_filter = [i for i, x in enumerate(cond) if x]
    feats = np.asarray(feature)
    new_feat = [feat[selected_filter] for feat in feats]
    new_feat_np = np.asarray(new_feat)
    return new_feat_np

# dir_list = ['converted_60_40', 'converted_120_80', 'converted_240_160']
dir_list = ['converted_60_40']
for d in dir_list:
    print(d)
    print("Spectogram:")
    files = get_all_converted_file(d)
    wave, spec = separate_wave_spec(files)
    feature, label = get_feature_and_label_list(spec, 0, 181, False)

    sel = VarianceThreshold()
    feature = sel.fit_transform(feature)

    # for n in range(1, 1000):
    #     lda = LinearDiscriminantAnalysis(n_components=n)
    #     lda.fit(feature, label)
    #     print("{},{}".format(n, lda.explained_variance_ratio_))

    lda = LinearDiscriminantAnalysis()
    x = np.array(feature)
    y = np.array(label)
    lda.fit(x, y)
    nf = lda.decision_function(feature)
    # print(nf)
    # exit()

    # scores = cross_val_score(lda, feature, label, cv=5, n_jobs=8)
    # print("Average score: {}".format(sum(scores)/len(scores)))
    #
    # # print(nf)
    # exit()
    coef = lda.coef_

    # print(sorted_coef[ceil(len(sorted_coef)/5)])
    # exit()
    # print("Mean :", coef.mean())
    # print("shape :", coef.shape)
    # print("new shape :", coef[coef < coef.mean()].shape)
    # print("selected feat :", coef < coef.mean())
    # cond = coef < coef.mean()
    # print(selected)
    # print(coef[0][741])
    # print(coef[0][881])
    # print(coef[0][3618])
    # print(coef[0][5780])
    # exit()

    clf = linear_model.LogisticRegression(random_state=1)
    scores = cross_val_score(clf, feature, label, cv=5, n_jobs=8)
    # print(scores)
    print("Average score no selected - logistic: {}".format(
        sum(scores)/len(scores)))

    # clf = MLPClassifier(
    #     hidden_layer_sizes=(1024),
    #     learning_rate='adaptive'
    # )
    # scores = cross_val_score(clf, feature, label, cv=5, n_jobs=8)
    # # print(scores)
    # print("Average score no selected - NN: {}".format(sum(scores)/len(scores)))

    for i in [10, 20, 40, 80, 160, 320, 640, 1280]:
        print("Top {}".format(i))
        new_feat_np = get_top_feat(coef, feature, i)
        print(new_feat_np.shape)

        clf = linear_model.LogisticRegression()
        scores = cross_val_score(clf, new_feat_np, label, cv=5, n_jobs=8)
        # print(scores)
        print("Average score selected - logistic: {}".format(
            sum(scores)/len(scores)))

        # clf = MLPClassifier(
        #     hidden_layer_sizes=(500),
        #     random_state=1,
        #     alpha=0.01,
        #     max_iter=100000000,
        #     learning_rate='adaptive',
        #     solver='sgd',
        #     learning_rate_init=0.1,
        # )
        # scores = cross_val_score(clf, new_feat_np, label, cv=5, n_jobs=8)
        # # print(scores)
        # print("Average score selected - NN: {}".format(sum(scores)/len(scores)))
    print("------------------------------------------------")


from tkinter import *
import pygame
import tkinter.ttk as ttk
import os
import sys, time, random
import numpy as np
import pyglet
from pygame.locals import *
from PIL import Image , ImageTk
from tkinter import filedialog
from mutagen.mp3 import MP3
from tkinter.ttk import Progressbar
from random import randint
from tkinter import ttk

path = os.path.dirname(os.path.abspath(__file__))

def Rock_Paper_Scissor():

    root = Toplevel(Home_Page)

    root.title('Rock, Paper, Scissors')
    # root.iconbitmap('')
    root.geometry("600x600")
    root.config(bg = "white")
    root.resizable(False, False)

    Bg = PhotoImage(file=os.path.join(path,"GUI","images","GAMER_2.png"))
    # CREATING LABEL
    my_label = Label(root, image = Bg)
    my_label.place(x=0, y=0, relwidth=1, relheight=1)

    # Define our images
    rock = PhotoImage(file = os.path.join(path,"GUI","images","ROCK_5.png"))
    paper = PhotoImage(file = os.path.join(path,"GUI","images","PAPER_5.png"))
    scissors = PhotoImage(file = os.path.join(path,"GUI","images","SCISSORS_5.png"))

    # Add Images to a list
    image_list = [rock, paper, scissors]

    # Pick random number between 0 and 2
    pick_number = randint(0, 2)

    # Throw up an image when the program starts
    image_label = Label(root, image=image_list[pick_number], bd=0)
    image_label.pack(pady=20)

    # SPIN FUNCTION
    def spin():
        # Pick random numnber
        pick_number = randint(0, 2)
        # Show image
        image_label.config(image=image_list[pick_number])

        # Convert Dropdown choice to a number

        if user_choice.get() == "Rock":
            user_choice_value = 0
        elif user_choice.get() == "Paper":
            user_choice_value = 1
        elif user_choice.get() == "Scissors":
            user_choice_value = 2

        # Determine WIN OR LOSE

        if user_choice_value == 0:  # Rock
            if pick_number == 0:
                win_lose_label.config(text = " IT'S A TIE !!! ")
            elif pick_number == 1:  # Paper
                win_lose_label.config(text = " PAPER COVERS ROCK !!! You Lose... ")
            elif pick_number == 2:  # Scissors
                win_lose_label.config(text = " ROCK SMASHES SCISSORS !!!  You Win... ")

        # If USer Picks Paper
        if user_choice_value == 1:  # Paper
            if pick_number == 1:
                win_lose_label.config(text=" IT'S A TIE !!! ")
            elif pick_number == 0:  # Rock
                win_lose_label.config(text=" PAPER COVERS ROCK !!! You Win... ")
            elif pick_number == 2:  # Scissors
                win_lose_label.config(text=" SCISSORS CUTS PAPER !!! You Lose...")

        # If User Pics Scissors
        if user_choice_value == 2:  # Scissors
            if pick_number == 2:
                win_lose_label.config(text=" IT'S A TIE !!! ")
            elif pick_number == 0:  # Rock
                win_lose_label.config(text=" ROCK SMASHES SCISSORS !!! You Lose...")
            elif pick_number == 1:  # Paper
                win_lose_label.config(text=" SCISSORS CUTS PAPER !!! You Win!!!")

    # MAKING CHOICE

    user_choice = ttk.Combobox(root, value=("Rock", "Paper", "Scissors"))
    user_choice.current(0)
    user_choice.pack(pady=20)

    # SPIN BOX
    spin_button = Button(root, text="Spin!", command = spin, font=("Impact",12),fg="white", bg="black")
    spin_button.pack(pady=10)

    # RESULTS
    win_lose_label = Label(root, text="", font=("Helvetica", 18), bg="white")
    win_lose_label.pack(pady=50)

    root.mainloop()

###############################################################################

def snake():

    Home_Page.resizable(False, False)

    # Difficulty settings
    # Easy      ->  10
    # Medium    ->  25
    # Hard      ->  40
    # Harder    ->  60
    # Impossible->  120
    difficulty = 10

    # Window size
    frame_size_x = 720
    frame_size_y = 480

    check_errors = pygame.init()

    # second number in tuple gives number of errors
    if check_errors[1] > 0:
        print(f'[!] Had {check_errors[1]} error found, exiting..')
        sys.exit(-1)
    else:
        print('>> Hard Work of Team Sounzonix :)')

    # This is the game window
    pygame.display.set_caption('Snake Eater')
    game_window = pygame.display.set_mode((frame_size_x, frame_size_y))

    # Colors (R, G, B)
    black = pygame.Color(0, 0, 0)
    white = pygame.Color(255, 255, 255)
    red = pygame.Color(255, 0, 0)
    green = pygame.Color(0, 255, 0)
    blue = pygame.Color(0, 0, 255)

    # FPS controller
    fps_controller = pygame.time.Clock()

    # Game variables
    snake_pos = [100, 50]
    snake_body = [[100, 50], [100 - 10, 50], [100 - (2 * 10), 50]]

    food_pos = [random.randrange(1, (frame_size_x // 10)) * 10, random.randrange(1, (frame_size_y // 10)) * 10]
    food_spawn = True

    direction = 'RIGHT'
    change_to = direction

    score = 0

    def show_score(choice, color, font, size):
        score_font = pygame.font.SysFont(font, size)
        score_surface = score_font.render('Score : ' + str(score), True, color)
        score_rect = score_surface.get_rect()
        if choice == 1:
            score_rect.midtop = (frame_size_x / 10, 15)
        else:
            score_rect.midtop = (frame_size_x / 2, frame_size_y / 1.25)
        game_window.blit(score_surface, score_rect)
        # pygame.display.flip()

    def game_over():
        my_font = pygame.font.SysFont('Impact', 90)
        game_over_surface = my_font.render('YOU DIED', True, red)
        game_over_rect = game_over_surface.get_rect()
        game_over_rect.midtop = (frame_size_x / 2, frame_size_y / 4)
        game_window.fill(black)
        game_window.blit(game_over_surface, game_over_rect)
        show_score(0, red, 'times', 20)
        pygame.display.flip()
        time.sleep(3)
        pygame.quit()
        sys.exit()

    # Main logic
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP or event.key == ord('w'):
                    change_to = 'UP'
                if event.key == pygame.K_DOWN or event.key == ord('s'):
                    change_to = 'DOWN'
                if event.key == pygame.K_LEFT or event.key == ord('a'):
                    change_to = 'LEFT'
                if event.key == pygame.K_RIGHT or event.key == ord('d'):
                    change_to = 'RIGHT'
                if event.key == pygame.K_ESCAPE:
                    pygame.event.post(pygame.event.Event(pygame.QUIT))

        if change_to == 'UP' and direction != 'DOWN':
            direction = 'UP'
        if change_to == 'DOWN' and direction != 'UP':
            direction = 'DOWN'
        if change_to == 'LEFT' and direction != 'RIGHT':
            direction = 'LEFT'
        if change_to == 'RIGHT' and direction != 'LEFT':
            direction = 'RIGHT'

        # snake direction
        if direction == 'UP':
            snake_pos[1] -= 10
        if direction == 'DOWN':
            snake_pos[1] += 10
        if direction == 'LEFT':
            snake_pos[0] -= 10
        if direction == 'RIGHT':
            snake_pos[0] += 10

        # Snake body grow
        snake_body.insert(0, list(snake_pos))
        if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
            score += 1
            food_spawn = False
        else:
            snake_body.pop()

        # Spawning food on the screen
        if not food_spawn:
            food_pos = [random.randrange(1, (frame_size_x // 10)) * 10, random.randrange(1, (frame_size_y // 10)) * 10]
        food_spawn = True

        game_window.fill(black)
        for pos in snake_body:
            pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], 10, 10))

        # Snake food
        pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

        # Game Over conditions
        # Getting out of bounds
        if snake_pos[0] < 0 or snake_pos[0] > frame_size_x - 10:
            game_over()
        if snake_pos[1] < 0 or snake_pos[1] > frame_size_y - 10:
            game_over()
        # Touching the snake body
        for block in snake_body[1:]:
            if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
                game_over()

        show_score(1, white, 'consolas', 20)
        # Refresh game screen
        pygame.display.update()
        # Refresh rate
        fps_controller.tick(difficulty)
###############################################################################

def Tic_Tak_Toe():

    Home_Page.resizable(False, False)

    # initializes pygame
    check_errors = pygame.init()
    # error check
    if check_errors[1] > 0:
        print(f'[!] Had {check_errors[1]} error found, exiting...')
        sys.exit(-1)
    else:
        print('>> Hard work of team soundzonix :)')

    # CONSTANTS
    WIDTH = 600
    HEIGHT = 600
    LINE_WIDTH = 15
    WIN_LINE_WIDTH = 15
    BOARD_ROWS = 3
    BOARD_COLS = 3
    SQUARE_SIZE = 200
    CIRCLE_RADIUS = 60
    CIRCLE_WIDTH = 15
    CROSS_WIDTH = 25
    SPACE = 55

    # rgb
    RED = (255, 0, 0)
    BG_COLOR = (28, 170, 156)
    LINE_COLOR = (23, 145, 135)
    CIRCLE_COLOR = (239, 231, 200)
    CROSS_COLOR = (239, 231, 200)
    BLACK_COLOR = (0,0,0)

    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption('TIC TAC TOE')
    screen.fill(BLACK_COLOR)

    # CONSOLE BOARD
    board = np.zeros((BOARD_ROWS, BOARD_COLS))

    def draw_lines():
        # 1 horizontal
        pygame.draw.line(screen, LINE_COLOR, (0, SQUARE_SIZE), (WIDTH, SQUARE_SIZE), LINE_WIDTH)
        # 2 horizontal
        pygame.draw.line(screen, LINE_COLOR, (0, 2 * SQUARE_SIZE), (WIDTH, 2 * SQUARE_SIZE), LINE_WIDTH)

        # 1 vertical
        pygame.draw.line(screen, LINE_COLOR, (SQUARE_SIZE, 0), (SQUARE_SIZE, HEIGHT), LINE_WIDTH)
        # 2 vertical
        pygame.draw.line(screen, LINE_COLOR, (2 * SQUARE_SIZE, 0), (2 * SQUARE_SIZE, HEIGHT), LINE_WIDTH)

    def draw_figures():
        for row in range(BOARD_ROWS):
            for col in range(BOARD_COLS):
                if board[row][col] == 1:
                    pygame.draw.circle(screen, CIRCLE_COLOR, (
                    int(col * SQUARE_SIZE + SQUARE_SIZE // 2), int(row * SQUARE_SIZE + SQUARE_SIZE // 2)),
                                       CIRCLE_RADIUS, CIRCLE_WIDTH)
                elif board[row][col] == 2:
                    pygame.draw.line(screen, CROSS_COLOR,
                                     (col * SQUARE_SIZE + SPACE, row * SQUARE_SIZE + SQUARE_SIZE - SPACE),
                                     (col * SQUARE_SIZE + SQUARE_SIZE - SPACE, row * SQUARE_SIZE + SPACE), CROSS_WIDTH)
                    pygame.draw.line(screen, CROSS_COLOR, (col * SQUARE_SIZE + SPACE, row * SQUARE_SIZE + SPACE),
                                     (col * SQUARE_SIZE + SQUARE_SIZE - SPACE, row * SQUARE_SIZE + SQUARE_SIZE - SPACE),
                                     CROSS_WIDTH)

    def mark_square(row, col, player):
        board[row][col] = player

    def available_square(row, col):
        return board[row][col] == 0

    def is_board_full():
        for row in range(BOARD_ROWS):
            for col in range(BOARD_COLS):
                if board[row][col] == 0:
                    return False

        return True

    def check_win(player):
        # vertical
        for col in range(BOARD_COLS):
            if board[0][col] == player and board[1][col] == player and board[2][col] == player:
                draw_vertical_winning_line(col, player)
                return True

        # horizontal
        for row in range(BOARD_ROWS):
            if board[row][0] == player and board[row][1] == player and board[row][2] == player:
                draw_horizontal_winning_line(row, player)
                return True

        # asc diagonal
        if board[2][0] == player and board[1][1] == player and board[0][2] == player:
            draw_asc_diagonal(player)
            return True

        # desc diagonal
        if board[0][0] == player and board[1][1] == player and board[2][2] == player:
            draw_desc_diagonal(player)
            return True

        return False

    def draw_vertical_winning_line(col, player):
        posX = col * SQUARE_SIZE + SQUARE_SIZE // 2

        if player == 1:
            color = CIRCLE_COLOR
        elif player == 2:
            color = CROSS_COLOR

        pygame.draw.line(screen, color, (posX, 15), (posX, HEIGHT - 15), LINE_WIDTH)

    def draw_horizontal_winning_line(row, player):
        posY = row * SQUARE_SIZE + SQUARE_SIZE // 2

        if player == 1:
            color = CIRCLE_COLOR
        elif player == 2:
            color = CROSS_COLOR

        pygame.draw.line(screen, color, (15, posY), (WIDTH - 15, posY), WIN_LINE_WIDTH)

    def draw_asc_diagonal(player):
        if player == 1:
            color = CIRCLE_COLOR
        elif player == 2:
            color = CROSS_COLOR

        pygame.draw.line(screen, color, (15, HEIGHT - 15), (WIDTH - 15, 15), WIN_LINE_WIDTH)

    def draw_desc_diagonal(player):
        if player == 1:
            color = CIRCLE_COLOR
        elif player == 2:
            color = CROSS_COLOR

        pygame.draw.line(screen, color, (15, 15), (WIDTH - 15, HEIGHT - 15), WIN_LINE_WIDTH)

    def restart():
        screen.fill(BG_COLOR)
        draw_lines()
        for row in range(BOARD_ROWS):
            for col in range(BOARD_COLS):
                board[row][col] = 0

    draw_lines()

    player = 1
    game_over = False

    # main Logic
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN and not game_over:

                mouseX = event.pos[0]  # x
                mouseY = event.pos[1]  # y

                clicked_row = int(mouseY // SQUARE_SIZE)
                clicked_col = int(mouseX // SQUARE_SIZE)

                if available_square(clicked_row, clicked_col):

                    mark_square(clicked_row, clicked_col, player)
                    if check_win(player):
                        game_over = True
                    player = player % 2 + 1

                    draw_figures()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    restart()
                    player = 1
                    game_over = False

        pygame.display.update()

###############################################################################

def Select_game():

    game_selection = Toplevel(Home_Page)
    global img2
    game_selection.title("Select Your Game")
    game_selection.geometry("600x600+330-50")
    game_selection.resizable(False, False)
    game_selection.iconbitmap(os.path.join(path,"GUI","images","icon_3.ico"))

    img1 = Image.open(os.path.join(path,"GUI","images","GAMER_1.png"))
    img2 = ImageTk.PhotoImage(img1)

    my_label_2 = Label(game_selection, image=img2)
    my_label_2.place(x=0,y=0)

    my_Label_1 = Label(game_selection, text="Enjoy Gaming!!", font=("Impact",40),fg="white", bg="black")
    my_Label_1.pack(pady=10)

    btn1=Button(game_selection, text = "Play Snake", command=snake, font = ("Impact",12),fg="white", bg="black")
    btn1.place(x=23, y=480)

    btn2 = Button(game_selection, text = "Play Tic Tac Toe", command=Tic_Tak_Toe, font = ("Impact",12),fg="white", bg="black")
    btn2.place(x=250, y=480)

    btn3 = Button(game_selection, text = "Play RPS", command = Rock_Paper_Scissor, font = ("Impact",12),fg="white", bg="black")
    btn3.place(x=497, y=480)

###############################################################################

def mp3():

    root = Toplevel(Home_Page)

    root.title('Soundzie')
    root.iconbitmap(os.path.join(path,"GUI","images","icon_3.ico"))
    root.geometry("1000x500+145-20")
    root.resizable(False, False)

    # Initialze Pygame Mixer
    pygame.mixer.init()

    # BACKGROUND IMAGE
    Bg = PhotoImage(file=os.path.join(path,"GUI","images","music_bg_5.png"))

    # CREATING LABEL
    my_label = Label(root, image = Bg)
    my_label.place(x=0, y=0, relwidth=1, relheight=1)

    # GET SONG LENGTH
    def play_time():

        # GET CURRENT SONG ELAPSED TIME
        current_time = pygame.mixer.music.get_pos() / 1000
        # CONVERT TO TIME FORMAT
        converted_current_time = time.strftime('%M:%S', time.gmtime(current_time))
        # Get the current playing song
        song = song_box.get(ACTIVE)
        # add directory structure and mp3 to song title
        #song = f'C:/Users/Pransh Gupta/Downloads/CSE PROJECT/audio/{song}.mp3'
        song = os.path.join(path,"audio","{}").format(song)

        # GET SONG LENGTH WITH MUTAGEN
        song_mut = MP3(song)
        song_length = song_mut.info.length

        # CHANGE TO TIME FORMAT
        converted_song_length = time.strftime('%M:%S', time.gmtime(song_length))

        # OUTPUT
        status_bar.config(text = f'Time Elapsed : {converted_current_time}  of  {converted_song_length}   ')
        status_bar.after(1000, play_time)

    # Add Song Function
    def add_song():
        song = filedialog.askopenfilename(initialdir=os.path.join(path,"audio"), title="Choose A Song", filetypes=(("mp3 Files", "*.mp3"),))

        # strip out the directory info and .mp3 extension from the song name
        # song = song.replace(os.path.join(path,"audio"), "")
        # song = song.replace(".mp3", "")

        # Add song to listbox
        song_box.insert(END, song)

    # Add many songs to playlist
    def add_many_songs():
        songs = filedialog.askopenfilenames(initialdir=os.path.join(path,"audio"), title="Choose A Song", filetypes=(("mp3 Files", "*.mp3"),))

        # Loop through song list and replace directory info and mp3
        # for song in songs:
        #     song = song.replace(os.path.join(path,"audio"), "")
        #     song = song.replace(".mp3", "")
        #     # Insert into playlist
        #     song_box.insert(END, song)

    # PLAY SELECTED SONG
    def play():
        song = song_box.get(ACTIVE)
        #song = os.path.join(path,"audio","{}").format(song)

        pygame.mixer.music.load(song)
        pygame.mixer.music.play(loops=0)

        play_time()

    # STOP SELECTED SONG
    def stop():
        pygame.mixer.music.stop()
        song_box.selection_clear(ACTIVE)
        status_bar.config(text='')

    # Create Global Pause Variable
    global paused
    paused = False

    # PAUSE AND UNPAUSE THE CURRENT SONG
    def pause(is_paused):
        global paused
        paused = is_paused

        if paused:
            # Unpause
            pygame.mixer.music.unpause()
            paused = False
        else:
            # Pause
            pygame.mixer.music.pause()
            paused = True

    # PLAY NEXT SONG IN THE PLAYLIST
    def next_song():

        # Get the current song tuple number
        next_one = song_box.curselection()
        # Add one to the current song number
        next_one = next_one[0] + 1
        # Grab song title from playlist
        song = song_box.get(next_one)
        # add directory structure and mp3 to song title
        song = os.path.join(path,"audio","{}").format(song)
        # Load and play song
        pygame.mixer.music.load(song)
        pygame.mixer.music.play(loops=0)

        # Clear active bar in playlist listbox
        song_box.selection_clear(0, END)

        # Activate new song bar
        song_box.activate(next_one)

        # Set Active Bar to Next Song
        song_box.selection_set(next_one, last=None)

    # PLAY PREVIOUS SONG IN THE PLAYLIST

    def previous_song():

        # Get the current song tuple number
        next_one = song_box.curselection()
        # Subtract one from the current song number
        next_one = next_one[0] - 1
        # Grab song title from playlist
        song = song_box.get(next_one)
        # add directory structure and mp3 to song title
        song = os.path.join(path,"audio","{}").format(song)
        # Load and play song
        pygame.mixer.music.load(song)
        pygame.mixer.music.play(loops=0)

        # Clear active bar in playlist listbox
        song_box.selection_clear(0, END)

        # Activate new song bar
        song_box.activate(next_one)

        # Set Active Bar to Next Song
        song_box.selection_set(next_one, last=None)

    # VOLUME INCREASE AND DECREASE

    def vol_up():
        vol = pygame.mixer.music.get_volume()
        if (vol >= vol * 100):
            pygame.mixer.music.set_volume(vol + 0.1)
        else:
            pygame.mixer.music.set_volume(vol + 0.01)
        ProgressbarVolumeLabel.config(text='{}%'.format(int(pygame.mixer.music.get_volume() * 100)))
        ProgressbarVolume['value'] = pygame.mixer.music.get_volume() * 100

    def vol_down():
        vol = pygame.mixer.music.get_volume()
        if (vol <= vol * 100):
            pygame.mixer.music.set_volume(vol - 0.01)
        else:
            pygame.mixer.music.set_volume(vol - 0.05)
        ProgressbarVolumeLabel.config(text='{}%'.format(int(pygame.mixer.music.get_volume() * 100)))
        ProgressbarVolume['value'] = pygame.mixer.music.get_volume() * 100

        # DELETE A SONG

    def delete_song():
        stop()
        # Delete Currently Selected Song
        song_box.delete(ANCHOR)
        # Stop Music if it's playing
        pygame.mixer.music.stop()

    # Delete All Songs from Playlist
    def delete_all_songs():
        stop()
        # Delete All Songs
        song_box.delete(0, END)
        # Stop Music if it's playing
        pygame.mixer.music.stop()

    # INTERFACE :-

    # Create Master Frame
    master_frame = Frame(root)
    master_frame.pack(pady = 60)

    # Create Playlist Box
    song_box = Listbox(master_frame, bg="black", fg="red", width=110, selectbackground = "green", selectforeground = "black")
    song_box.grid(row = 0, column = 0)

    # Create Player Control Frame
    controls_frame = Frame(master_frame)
    controls_frame.grid(row = 1, column = 0, pady = 20, padx = 0)

    # Define Player Control Button Images
    back_btn_img = PhotoImage(file = os.path.join(path,"GUI","images","BACKWARD.png"))
    forward_btn_img = PhotoImage(file = os.path.join(path,"GUI","images","FORWARD.png"))
    play_btn_img = PhotoImage(file = os.path.join(path,"GUI","images","PLAY.png"))
    pause_btn_img = PhotoImage(file = os.path.join(path,"GUI","images","PAUSE.png"))
    stop_btn_img = PhotoImage(file = os.path.join(path,"GUI","images","STOP.png"))
    vol_increase_btn_img = PhotoImage(file = os.path.join(path,"GUI","images","VOL_UP.png"))
    vol_decrease_btn_img = PhotoImage(file = os.path.join(path,"GUI","images","VOL_DOWN.png"))

    # Create Player Control Buttons
    back_button = Button(controls_frame, image = back_btn_img, borderwidth = 0, command = previous_song)
    forward_button = Button(controls_frame, image = forward_btn_img, borderwidth = 0, command = next_song)
    play_button = Button(controls_frame, image = play_btn_img, borderwidth = 0, command = play)
    pause_button = Button(controls_frame, image = pause_btn_img, borderwidth = 0, command =lambda: pause(paused))
    stop_button = Button(controls_frame, image = stop_btn_img, borderwidth = 0, command = stop)
    vol_increase_button = Button(controls_frame, image = vol_increase_btn_img, borderwidth = 0, command = vol_up)
    vol_decrease_button = Button(controls_frame, image = vol_decrease_btn_img, borderwidth = 0, command = vol_down)

    back_button.grid(row=0, column=0, padx=20)
    forward_button.grid(row=0, column=1, padx=20)
    play_button.grid(row=0, column=2, padx=20)
    pause_button.grid(row=0, column=3, padx=20)
    stop_button.grid(row=0, column=4, padx=20)
    vol_increase_button.grid(row=0, column=5, padx=20)
    vol_decrease_button.grid(row=0, column=6, padx=20)

    # PROGRESS BAR VOLUME

    ProgressbarLabel = Label(master_frame, text="", bg="red")
    ProgressbarLabel.grid(row=0, column=1, rowspan=1, padx=25, pady=0)

    ProgressbarVolume = Progressbar(ProgressbarLabel, orient=VERTICAL, mode="determinate", value=100, length=150)
    ProgressbarVolume.grid(row=0, column=0, ipadx=5)

    ProgressbarVolumeLabel = Label(ProgressbarLabel, text="100%", bg="red", width=3)
    ProgressbarVolumeLabel.grid(row=0, column=0)

    # PROGRESS BAR MUSIC

    ProgressbarMusicLabel = Label(controls_frame, text='', bg="red")
    ProgressbarMusicLabel.grid(row=1, column=0, columnspan=10, padx=10, pady=10)

    ProgressbarMusic_START_Label = Label(ProgressbarMusicLabel, text='00:00', bg="red")
    ProgressbarMusic_START_Label.grid(row=0, column=0)

    ProgressbarMusic = Progressbar(ProgressbarMusicLabel, orient=HORIZONTAL, mode="determinate", value = 0)
    ProgressbarMusic.grid(row=0, column=1, ipadx=240, ipady=5)

    ProgressbarMusic_END_Label = Label(ProgressbarMusicLabel, text='00:00', bg="red")
    ProgressbarMusic_END_Label.grid(row=0, column=2)

    # Create Menu
    my_menu = Menu(root)
    root.config(menu=my_menu)

    # ABOUT MENU
    about_menu = Menu(my_menu)
    my_menu.add_cascade(label="About", menu=about_menu)
    about_menu.add_command(label="This is a music player, build using Python & Tkinter by Team Soundzonix")

    # ADD SONG MENU
    add_song_menu = Menu(my_menu)
    my_menu.add_cascade(label="Add Songs", menu=add_song_menu)
    add_song_menu.add_command(label="Add One Song To Playlist", command=add_song)
    add_song_menu.add_command(label="Add Many Songs To Playlist", command=add_many_songs)

    # DELETE SONG MENU
    remove_song_menu = Menu(my_menu)
    my_menu.add_cascade(label="Remove Songs", menu=remove_song_menu)
    remove_song_menu.add_command(label="Delete A Song From Playlist", command=delete_song)
    remove_song_menu.add_command(label="Delete All Songs From Playlist", command=delete_all_songs)

    # Create Status Bar
    status_bar = Label(root, text='', bd=1, relief=GROOVE, anchor=E)
    status_bar.pack(fill=X, side=BOTTOM, ipady=2)

    root.mainloop()

###############################################################################

def mp4():

    Video1 = Toplevel(Home_Page)

    Video1.title("MP4 Player")
    Video1.geometry("150x100+400-300")
    Video1.resizable(False, False)
    Video1.iconbitmap(os.path.join(path,"GUI","images","icon_3.ico"))

    bg = PhotoImage(file=os.path.join(path,"GUI","images","1.png"))

    intro = Label(Video1, image =bg)
    intro.place(x=0, y=0, relwidth=1, relheight=1, )

    Select_Video = Button(Video1, text="Select Your Video", command=add_video, font=("Impact",12),fg="white", bg="black")
    Select_Video.place(x = 10, y = 30)

    Video1.mainloop()

    ###############################################################################

def add_video():

    video11 = filedialog.askopenfilename(initialdir=os.path.join(path,"GUI","video"), title="Choose A Video", filetypes=(("mp4 Files", "*.mp4"),))

    vidPath = video11
    # print(vidPath)

    window = pyglet.window.Window(fullscreen=True)
    player = pyglet.media.Player()

    MediaLoad = pyglet.media.load(vidPath)

    player.queue(MediaLoad)
    player.play()

    @window.event
    def on_draw():
        if player.source and player.source.video_format:
            player.get_texture().blit(50, 50)

    pyglet.app.run()

###############################################################################

Home_Page = Tk()
Home_Page.title("Main Menu")
Home_Page.geometry("600x600+330-50")
Home_Page.resizable(False, False)
Home_Page.iconbitmap(os.path.join(path,"GUI","images","icon_3.ico"))

bg = PhotoImage(file = os.path.join(path,"GUI","images","6.png"))

intro = Label(Home_Page, image=bg)
intro.place(x = 0,y = 0, relwidth = 1, relheight = 1)

my_text = Label(Home_Page, text="Welcome to Soundzie", font=("Impact",40),fg="white", bg="black")
my_text.pack(pady=10)

btn1 = Button(Home_Page, text="Open MP3", command=mp3, font = ("Impact",12),fg="white", bg="black")
btn1.place(x = 265, y = 360)

btn2 = Button(Home_Page, text="Open MP4", command=mp4, font = ("Impact",12),fg="white", bg="black")
btn2.place(x = 265, y = 260)

btn3 = Button(Home_Page, text="Play Games", command=Select_game, font = ("Impact",12),fg="white", bg="black")
btn3.place(x = 264, y = 460)

mainloop()


from flask import render_template, flash, redirect, session, url_for, request, g
from flask.ext.login import login_user, logout_user, current_user, login_required
from app import app, db, lm, googlelogin
from forms import AddTorrentForm
from models import User
from scripts import *

@app.before_request
def before_request():
	g.user = current_user

@lm.user_loader
def load_user(id):
	return User.query.get(int(id))

@app.route('/oauth2callback')
@googlelogin.oauth2callback
def create_or_update_user(token, userinfo, **params):
	user = User.filter_by(google_id=userinfo['id']).first()
	if user:
		user.name = userinfo['name']
	else:
		user = User(google_id=userinfo['id'],
			name = userinfo['name'])
	db.session.add(user)
	db.session.flush()
	login_user(user)
	return redirect(url_for('index'))

@app.route('/', methods=['GET','POST'])
@app.route('/index', methods=['GET','POST'])
@login_required
def index():
	form = AddTorrentForm()
	if form.validate_on_submit():
		flash('Adding torrent: "%s"' %	(form.torrent))
		output = AddTorrent(form.torrent.data)
		flash('Result: "%s"' % output)

	user = g.user
	posts = [
		{
			'author':{'nickname':'John'},
			'body': 'Beautiful day in Derpville'
		},
		{
			'author':{'nickname':'Jimothy'},
			'body': 'Oh Horatio'
		}
	]
	temp = GetTemperature()
	return render_template('index.html',
				title='Home',
				user=user,
				posts=posts,
				temp=temp,
				form=form)

@app.route('/login', methods=['GET','POST'])
#@oid.loginhandler
def login():
	if g.user is not None and g.user.is_authenticated():
		return redirect(url_for('index'))
	#form = LoginForm()
	#if form.validate_on_submit():
	#	session['remember_me'] = form.remember_me.data
	#	return oid.try_login(form.openid.data, ask_for=['nickname', 'email'])
	return """

Login

	""" % ( googlelogin.login_url(approval_prompt='force'))


#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import wavfile
from scipy.fftpack import fft

figure_index = 1

def DFTandPlot(Fs, audio):
    for i in range(0,int((NumOfSample/Fs - 1)/period)):
        # Define a time step which last 100ms
        step_time =  np.linspace(1+(i*period),1+(i+1)*period,int(Fs*period))
        step_amp = audio[(int(i*period*Fs) +Fs): (int((i+1)*period*Fs) +Fs)]

        if (i < 1):
            plt.figure(2)
            plt.plot(step_time,step_amp)

        audio_f = np.linspace(0, int(Fs), N_point)
        audio = fft(step_amp,N_point)
        plt.figure(i+3)
        plt.plot(audio_f[0: int(N_point/3)], 2/N_point * np.abs(audio)[0: int(N_point/3)], label ='Magnitude audio')
        plt.title('DFT - Spectral density of audio(t)')
        plt.xlabel('Frequency (Hz)')
        plt.ylabel('Magnitude')
        plt.legend()

def main():
    # - Define sampling parameters
    # - Highest frequency in this exercise is 2500 so
    # Fs must be at least 5000 (Nyquist Theorem), I chose 10000
    # to preserve waveform
    Fs = 10000
    SimulationTime = 3
    NumOfSample = int(SimulationTime*Fs)

    # Define 4 sine signal with given frequency
    # and different chosen amplitudes and phases
    t = np.linspace(0, SimulationTime,NumOfSample)
    x = [ 3*np.sin(2 * np.pi * 100 * t +1),
          1.5*np.sin(2 * np.pi * 500 * t +2),
          np.sin(2 * np.pi * 1500 * t +3),
          2*np.sin(2 * np.pi * 2500 * t +4)]

    x_sum = 0
    for i in range(0,len(x)):
        x_sum += x[i]

    wavfile.write('Sine.wav', Fs, x_sum)

    # Define DFT-point
    N_point = 512

    # Fast Fourier Transform summed signal to get output in frequency field
    # fftshift to plot both negative and positive part
    ff = np.linspace(0, int(Fs), N_point)
    xf = fft(x_sum,N_point)

    plot_range = int(Fs/300)
    plt.figure(1)
    for i in range(0,len(x)):
        plt.plot(t[0:plot_range],x[i][0:plot_range], label = 'x_' + str(i) + '(t)')
    plt.legend()
    plt.figure(2)
    plt.plot(t[0:plot_range],x_sum[0:plot_range])

    plt.figure(3)
    plt.plot(ff[0: int(N_point/3)], 2/N_point * np.abs(xf)[0: int(N_point/3)], label ='X_f')
    plt.title('DFT - Spectral density of x_sum(t)')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Magnitude')
    plt.legend()
    plt.show()

if __name__== "__main__":
    main()


import model
import pandas as pd

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegressionCV
from collections import OrderedDict
from sklearn.metrics import accuracy_score

df = pd.read_csv('phase2_df.csv')

X = df.drop(columns=['id', 'abuse_past_year', 'abuse_status', 'reassault'])
y = df[['reassault']]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .15, random_state = 0, stratify=y)

x_columns = ['slap',
             'threat_object',
             'beaten',
             'limit_family_contact',
             'kick_punch',
             'threat_hit',
             'push_shove',
             'jealous',
             'life_danger'
             ]

X = df[x_columns]
y = df[['reassault']]

clf, y_pred, y_pred_proba = model.log_reg(x_columns, X_train, y_train, cv_num=5, solver='liblinear')

print('Accuracy of Logistic Regression classifier on training set: {:.2f}'
     .format(clf.score(X_train[x_columns], y_train)))

print('Accuracy of Logistic Regression classifier on test set: {:.2f}'
     .format(clf.score(X_test[x_columns], y_test)))

def predictorizer(feature1, feature2, feature3, feature4, feature5, feature6, feature7, feature8, feature9):

    new_data = OrderedDict([
        ('slap', feature1),
        ('threat_object', feature2),
        ('beaten', feature3),
        ('limit_family_contact', feature4),
        ('kick_punch', feature5),
        ('threat_hit', feature6),
        ('push_shove', feature7),
        ('jealous', feature8),
        ('life_danger', feature9,)
        ])
    # .values.reshape(1, -1) because it must be 2-dim, because we passed only one new observation
    new_data = pd.Series(new_data).values.reshape(1,-1)
    # Use the model to make a prediction
    prediction = str(clf.predict_proba(new_data)[[0],[1]])
    prediction = prediction.replace('[','')
    prediction = prediction.replace(']','')
    prediction = "{:.1%}".format(float(prediction))
    return prediction

print(predictorizer('1','1','1','1','1','1','1','1','1'))


import re

from bs4 import BeautifulSoup

from lgsf.scrapers.councillors import HTMLCouncillorScraper

class Scraper(HTMLCouncillorScraper):
    disabled = False
    base_url = "https://www.stroud.gov.uk/council-and-democracy/your-councillors/your-councillors-by-name"  # noqa
    list_page = {
        "container_css_selector": ".container .col-md-8",
        "councillor_css_selector": ".col-sm-3",
    }

    def get_single_councillor(self, councillor_html):
        url = "https://www.stroud.gov.uk{}".format(
            councillor_html.find_all("a")[1]["href"]
        )
        identifier = url.split("/")[-1]
        name = councillor_html.find_all("a")[1].text
        division = (
            re.search("Ward: (.*)", councillor_html.find("p").text)
            .group(1)
            .strip()
        )
        party = (
            re.search("Political Party: (.*)", councillor_html.find("p").text)
            .group(1)
            .strip()
        )
        councillor = self.add_councillor(
            url,
            identifier=identifier,
            name=name,
            party=party,
            division=division,
        )

        req = self.get(url)
        soup = BeautifulSoup(req.text, "lxml")

        councillor.email = (
            soup.find(text="Email:").findNext("td").getText(strip=True)
        )

        return councillor


"""
Tyson Reimer
University of Manitoba
September 28th, 2021
"""

import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
import seaborn as sns
from scipy import stats

from umbms import get_proj_path, verify_path

from umbms.loadsave import load_birrs_txt
from umbms.sigproc import iczt

###############################################################################

__DATA_DIR = os.path.join(get_proj_path(), 'data/20210708-2/')

__OUT_DIR = os.path.join(get_proj_path(), 'output/20210708-2/')
verify_path(__OUT_DIR)

###############################################################################

if __name__ == "__main__":

    fd_data = np.zeros([8, 1001, 72], dtype=complex)
    scan_fs = np.linspace(1e9, 8e9, 1001)
    tar_fs = scan_fs >= 1.65e9

    viridis = get_cmap('magma')

    for ii in range(1, 9):
        fd_data[ii - 1, :, :] = load_birrs_txt(os.path.join(__DATA_DIR,
                                                            'expt0%d.txt'
                                                            % ii))
    td_data = np.zeros([8, 700, 72], dtype=complex)
    for ii in range(8):
        fd_here = fd_data[ii, tar_fs, :]
        td_data[ii, :, :] = iczt(fd_data=fd_here,
                                 ini_t=0.5e-9, fin_t=5.5e-9,
                                 ini_f=np.min(scan_fs[tar_fs]),
                                 fin_f=8e9, n_time_pts=700)

    expt_data = {
        'Adipose 1': td_data[0, : ,:],
        'Plastic 1': td_data[1, :, :],
        'Triton 1': td_data[2, :, :],
        'Adipose 2': td_data[3, :, :],
        'Plastic 2': td_data[4, :, :],
        'Triton 2': td_data[5, :, :],
        'Adipose 3': td_data[6, :, :],
        'Adipose 4': td_data[7, :, :],
    }

    plt_order = [
        'Triton 1',
        'Plastic 1',
        # 'Adipose 2',
        'Adipose 3',
        'Adipose 4'
    ]

    plt_cols = [
        viridis(0),
        viridis(0.3),
        viridis(0.6),
        viridis(0.9),
        viridis(0.9)
    ]

    ###########################################################################

    #
    ref_td = expt_data['Adipose 1']
    tri_td = expt_data['Triton 1']
    cal_tri = np.abs(tri_td - ref_td)
    roi = cal_tri >= 0.75 * np.max(cal_tri)

    plt.figure()
    plt.rc('font', family='Times New Roman')
    plt.tick_params(labelsize=18)

    for ii in range(len(plt_order)):
        tar_str = plt_order[ii]
        tar_td = expt_data[tar_str]

        pix_in_roi = np.abs(tar_td - ref_td)[roi]

        sns.distplot(pix_in_roi, color=plt_cols[ii], label=tar_str)

        s_mean = np.mean(pix_in_roi)
        s_std = np.std(pix_in_roi)
        #
        # plt.axvline(s_mean, color=plt_cols[ii], linestyle='-')
        # plt.axvline(s_mean + s_std, color=plt_cols[ii], linestyle='--')
        # plt.axvline(s_mean - s_std, color=plt_cols[ii], linestyle='--')

    plt.legend(fontsize=16)
    plt.xlabel(r'|S$_{\mathdefault{11}}$|', fontsize=22)
    plt.ylabel("Kernel Density Estimate", fontsize=22)
    plt.tight_layout()
    plt.show()
    plt.savefig(os.path.join(__OUT_DIR, 'kde_plts.png'),
                transparent=False, dpi=300)

    ###########################################################################

    thresholds = np.linspace(0, 1, 100)

    plt.figure(figsize=(9, 6))
    plt.rc('font', family='Times New Roman')
    plt.tick_params(labelsize=18)

    for ii in range(len(plt_order)):
        tar_str = plt_order[ii]
        tar_td = expt_data[tar_str]

        means = np.zeros_like(thresholds)
        stds = np.zeros_like(thresholds)

        for jj in range(len(thresholds)):
            cal_tri = np.abs(tri_td - ref_td)
            roi = cal_tri >= thresholds[jj] * np.max(cal_tri)

            pix_in_roi = np.abs(tar_td - ref_td)[roi]

            means[jj] = np.median(pix_in_roi)
            stds[jj] = np.std(pix_in_roi)

            q75, q25 = np.percentile(pix_in_roi, [75, 25])
            iqr = q75 - q25
            stds[jj] = iqr

        plt.plot(thresholds, means, color=plt_cols[ii], label=plt_order[ii])
        plt.fill_between(thresholds, y1=means - stds,
                         y2=means + stds, color=plt_cols[ii],
                         alpha=0.3)

    plt.legend(fontsize=16)
    plt.xlabel("ROI Threshold", fontsize=22)
    plt.ylabel(r"Median S$_{\mathdefault{11}}$", fontsize=22)
    plt.tight_layout()
    plt.show()
    plt.savefig(os.path.join(__OUT_DIR, 'tys_roi_plt_iqr.png'),
                transparent=False, dpi=300)


# -*- coding: utf-8 -*-

from odoo import models, fields, api, _

class velo_sales_order(models.Model):
	_inherit = 'sale.order'

	@api.model
	def create(self, vals):
		if vals.get('name', _('New')) == _('New'):
		    seq_date = None
		    if 'date_order' in vals:
		        seq_date = fields.Datetime.context_timestamp(self, fields.Datetime.to_datetime(vals['date_order']))
		    if 'company_id' in vals:
		        vals['name'] = self.env['ir.sequence'].with_context(force_company=vals['company_id']).next_by_code(
		            'velo_sale.order', sequence_date=seq_date) or _('New')
		    else:
		        vals['name'] = self.env['ir.sequence'].next_by_code('velo_sale.order', sequence_date=seq_date) or _('New')

		# Makes sure partner_invoice_id', 'partner_shipping_id' and 'pricelist_id' are defined
		if any(f not in vals for f in ['partner_invoice_id', 'partner_shipping_id', 'pricelist_id']):
		    partner = self.env['res.partner'].browse(vals.get('partner_id'))
		    addr = partner.address_get(['delivery', 'invoice'])
		    vals['partner_invoice_id'] = vals.setdefault('partner_invoice_id', addr['invoice'])
		    vals['partner_shipping_id'] = vals.setdefault('partner_shipping_id', addr['delivery'])
		    vals['pricelist_id'] = vals.setdefault('pricelist_id', partner.property_product_pricelist and partner.property_product_pricelist.id)
		result = super(velo_sales_order, self).create(vals)
		return result

	pop_name = fields.Many2one('pop.service.coverage',string="POP Name")
	pop_id = fields.Char(related="pop_name.pop_id",string="POP ID")
	pop_regional = fields.Many2one(related="pop_name.pop_regional", string="Province")
	pop_type = fields.Many2one(related="pop_name.pop_type", string="POP Type")
	pop_metroe = fields.Boolean(related="pop_name.pop_metroe",string="MetroE")

	email = fields.Char(related="partner_id.email",string="Email")
	phone = fields.Char(related="partner_id.phone",string="Phone")
	potential = fields.Boolean(string='Potential', default='1')
	partner_id = fields.Many2one(
        'res.partner', string='Customer', readonly=True,
        states={'draft': [('readonly', False)], 'sent': [('readonly', False)]},
        required=True, change_default=True, index=True, tracking=1,
        domain="['|','&', ('company_id', '=', False), ('company_id', '=', company_id), ('tenant', '=', potential)]",)
	program = fields.Many2one('velo.program',string="Program")
	discount_monthly_tariff = fields.Float(related="program.discount_monthly_tariff", string=""'Discount Monthly Tariff')

	@api.onchange('program')
	def _onchange_program(self):
		for rec in self:
			if rec.program:
				lines = [(5, 0, 0)]
				print("self.program", self.program)
				for line in self.program:
					val = {
						'product_id': line.product_ids.id,
						'name': line.product_ids.name,
						'product_uom_qty': 1.0,
						'product_uom': 1,
						'price_unit': line.product_ids.list_price
						}
					lines.append((0, 0, val))
				rec.order_line = lines

class velo_sales_order_line(models.Model):
	_inherit = 'sale.order.line'

	@api.depends('product_id','order_id.pop_name')
	def _product_group_function(self):
		for i in self:
			i.product_group = i.product_template_id.product_group
			i.product_category = i.product_template_id.categ_id.name

			pop_regional =  i.order_id.pop_regional.pop_regional_name
			pop_type =  i.order_id.pop_type.poptype_name
			pop_metroe =  i.order_id.pop_metroe
			product_template_id = i.product_template_id.id

			regional = ''
			for rec in i.product_template_id.validity_ids :
				regional = rec.region.pop_regional_name

			if pop_type == 'HRB' :
				 pop_type = 'hrb'
			else :
				 pop_type = 'nonhrb'

			if pop_metroe == True :
				 pop_metroe = 'Metro'
			else :
				 pop_metroe = 'Non Metro'

			if regional == 'All Region' :
				value = self.env['product.validity'].search([('region','=', regional),('validity_id','=', product_template_id),('status','=', True)])
			else :
				value = self.env['product.validity'].search([('region','=', pop_regional),('hrb','ilike', pop_type),('metroe','=', pop_metroe),('validity_id','=', product_template_id),('status','=', True)])

			i.price_unit = value.monthly_tariff
			i.one_time_charge = value.installation_fee

	def _compute_amount(self):
		for line in self:
			price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
			taxes = line.tax_id.compute_all(price, line.order_id.currency_id, line.product_uom_qty, product=line.product_id, partner=line.order_id.partner_shipping_id)
			one_time_charge = line.one_time_charge
			line.update({
					'price_tax': sum(t.get('amount', 0.0) for t in taxes.get('taxes', [])),
					'price_total': taxes['total_included'],
					'price_subtotal': float(taxes['total_excluded']) + float(one_time_charge),
				})

	product_group = fields.Char(string="Product Group", compute="_product_group_function")
	product_category = fields.Char(string="Product category", compute="_product_group_function")
	price_unit = fields.Float('Unit Price', required=True, digits='Product Price', default=0.0)
	one_time_charge = fields.Float(string="One Time Charge", compute="_product_group_function")
	discount_monthly_tariff = fields.Float(related="order_id.discount_monthly_tariff", string=""'Discount Monthly Tariff')


" Initialize variables, parameters, and data structures for simulation"

" Load necessary modules "
"============================================================================"
import numpy as np
import cantera as ct

" Load in user inputs "
"============================================================================"
from li_o2_inputs import *

"============================================================================"
"  CANTERA OJECT SETUP  "
# Import necessary phases from Cantera
# Make objects to handle calculations
gas = ct.Solution(ctifile,'gas')
ca_bulk = ct.Solution(ctifile,'graphite')
elyte = ct.Solution(ctifile,'electrolyte')
oxide = ct.Solution(ctifile,'Li2O2')
tpb = ct.Interface(ctifile,'cathode_tpb',[elyte, oxide, ca_bulk])
ca_surf = ct.Interface(ctifile,'cathode_surf',[elyte, ca_bulk])
air_elyte = ct.Interface(ctifile,'air_elyte',[gas, elyte])
Li_bulk = ct.Solution(ctifile,'Lithium')
Li_surf = ct.Interface(ctifile,'Li_surface',[Li_bulk, elyte])

# Set temperature and pressure for all phse objects:
gas.TP = TP
air_elyte.TP = TP
elyte.TP = TP
oxide.TP = TP
ca_surf.TP = TP
tpb.TP = TP
ca_bulk.TP = TP
Li_bulk.TP = TP
Li_surf.TP = TP

# Store these phases in a common 'objs' dict.
# This takes the data from Cantera and stores data for use in a Python
# dictionary so we can efficiently pass them to various functions. A dictionary
# associates a key word with a value.
objs = {}
objs['gas'] = gas
objs['ca_bulk'] = ca_bulk
objs['elyte'] = elyte
objs['oxide'] = oxide
objs['ca_surf'] = ca_surf
objs['tpb'] = tpb
objs['air_elyte'] = air_elyte
objs['Li_bulk'] = Li_bulk
objs['Li_surf'] = Li_surf

"============================================================================"
"  INPUT PARAMETER STORAGE  "
# Store parameters in a common 'params' dict
params = {}
params['i_ext'] = i_ext
params['TP'] = TP
params['rtol'] = rtol
params['atol'] = atol
params['N_y_ca'] = N_y_ca
# Inverse thickness of a single cathode volume discritization [1/m]
params['dyInv_ca'] =  N_y_ca / th_cath
params['N_y_sep'] = N_y_sep
# inverse thickness of a single separator volume discritization [1/m]
params['dyInv_sep'] =  N_y_sep / th_sep
params['C_dl'] = C_dl
# Carbon volume fraction [-]
params['eps_carbon'] = 1. - eps_elyte_init - eps_binder_init - eps_oxide_init

# Volume of a single carbon particle [m3]
V_carbon = 4./3. * np.pi * (d_part / 2.)**3.
# Surface area of a single carbon particle [m2]
A_carbon = 4. * np.pi * (d_part / 2.)**2.
# Initial carbon innterface area per unit volume cathode [m2/m3 total]
params['A_carbon_init'] = params['eps_carbon'] * A_carbon / V_carbon

# Oxide particle radius:
params['r_oxide'] = 0.5*d_oxide

# Index of the electrolyte species responsible for double layer current
#   (this is usually the Li ion).
params['i_dl_species'] = elyte.species_index(dl_species)

params['eps_sep_inv'] = 1./eps_sep

"============================================================================"
"  TRANSPORT PEROPERTIES -- CALCULATION AND STORAGE  "
# Transport model: dilute (dst) or concentrated (cst) solution theory:
params['transport'] = transport

# Bruggeman coefficient
params['bruggman'] = n_bruggeman

# Store elyte diffusion coefficients and elementary charge:
params['D_k_elyte_o'] = np.zeros_like(elyte.X)
params['Z_k_elyte'] = np.zeros_like(elyte.X)
for j in elyte.species_names:
    params['D_k_elyte_o'][elyte.species_index(j)] = D_k_elyte[j]
    params['Z_k_elyte'][elyte.species_index(j)] = elyte.species(j).charge

params['polarity_k'] = np.sign(params['Z_k_elyte'])
params['D_k_mig_elyte_o'] = params['D_k_elyte_o']*params['Z_k_elyte'] \
    * ct.faraday / ct.gas_constant / params['TP'][0]

# Cantera species indices for relevant species:
params['i_Li_elyte'] = elyte.species_index(Li_elyte_name)
params['i_counter_ion'] = elyte.species_index(counter_ion_elyte_name)
params['i_solvent_elyte'] = []
for n_sp in solvent_elyte_names:
    params['i_solvent_elyte'].append(elyte.species_index(n_sp))

if params['transport'] == 'cst':
    # Li diffusion coefficients:
    params['D_Li_CST'] = D_Li_CST
    # Transferrence number coefficients:
    params['t_elyte'] = t_elyte_CST
    # Ionic conductivity coefficients:
    params['sigma_elyte'] = sigma_elyte_CST
    # Li activity coefficients:
    params['gamma_elyte'] = gamma_elyte_CST
    # Magnitude of 1/z_k for electrolyte species.  Need to take care to prevent
    #  division by zero, so we really just staore the non-zero cahrges
    #  ('nz_charges'). First create a copy of the electrolyte species charges:
    nz_charges = abs(params['Z_k_elyte'])
    # Now overwrite all zeros with ones.
    nz_charges[nz_charges == 0] = 1.
    # Divide by this new array. For un-cahrged species, the transferrence number is already equal to zero, so the value of `div_charge` is irrelevant:
    params['div_charge'] = 1./nz_charges

# Use the user-provided electrolyte salt molarity to set the initial
#    electrolyte composition:
# Li+ and PF6- molar masses:
W_Li = elyte.molecular_weights[params['i_Li_elyte']]
Y_Li = W_Li*Molarity_elyte/elyte.density_mass
W_counter = elyte.molecular_weights[params['i_counter_ion']]
Y_counter = W_counter*Molarity_elyte/elyte.density_mass

# Save initial mass fractions from input file.  Assume all non-salt species should keep the same ratio.
Y_initial = elyte.Y

# Initial salt mass fraction from input file:
Y_salt_initial = Y_initial[params['i_Li_elyte']] \
    + Y_initial[params['i_counter_ion']]
# New salt mass fraction:
Y_salt_new = Y_Li + Y_counter
# CHange in salt mass fraction:
dY_salt = Y_salt_new - Y_salt_initial

# Scale all other species mass fractions so that the sum of all mass fractions
#    equals one:
scaling_factor = 1 - dY_salt/(1 - Y_salt_initial)
Y_new = Y_initial * scaling_factor

# Set salt species mass fractions:
Y_new[params['i_Li_elyte']] = Y_Li
Y_new[params['i_counter_ion']] = Y_counter

# Set Cantera object:
elyte.Y = Y_new

"============================================================================"
"  SOLUTION VECTOR SETUP  "
# Store solution vector pointers in a common 'SVptr' dict
SVptr = {}
# Variables per finite volume (aka 'node'): elyte electric potential, oxide
#     density, electrolyte species densities
nvars_node_ca = int(elyte.n_species + 2)

# double layer potential in solution vector SV
SVptr['phi_dl'] = range(0, nvars_node_ca*N_y_ca, nvars_node_ca)
# Oxide volume fraction in solution vector SV
SVptr['eps_oxide'] = range(1,nvars_node_ca*N_y_ca, nvars_node_ca)
# electrolyte species mass densities in solution vector SV
SVptr['C_k_elyte_ca'] = np.ndarray(shape=(N_y_ca, elyte.n_species),\
    dtype='int')
for j in range(N_y_ca):
    SVptr['C_k_elyte_ca'][j,:] = range(2 + j*nvars_node_ca, \
        2 + j*nvars_node_ca + elyte.n_species)

nvars_node_sep = int(elyte.n_species)
SVptr['C_k_elyte_sep'] = np.ndarray(shape=(N_y_sep, elyte.n_species),\
    dtype='int')
for j in range(N_y_sep):
    SVptr['C_k_elyte_sep'][j,:] = range(nvars_node_ca*N_y_ca \
        + j*nvars_node_sep, nvars_node_ca*N_y_ca + j*nvars_node_sep \
        + elyte.n_species)

# Set inital values
# Electrolyte species mass densities (kg per m^3 of electrolyte)
C_k_elyte_init = elyte.concentrations

# Store in an array:
SV_single_cath = np.r_[phi_elyte_init, eps_oxide_init, C_k_elyte_init]
# Tile for discritization
SV0_cath = np.tile(SV_single_cath, N_y_ca)

SV_single_sep = C_k_elyte_init
SV0_sep = np.tile(SV_single_sep, N_y_sep)

# SV0 = np.r_[SV0_cath,SV0_sep]                                       # combine initial values
SV0 = SV0_cath

"============================================================================"
"  POINTER FOR POST-PROCESSING / PLOTTING  "
# Store plot pointers in a common 'pltptr' dict
pltptr = {}
pltptr['O2'] = elyte.species_index('O2(e)')
pltptr['Li+'] = elyte.species_index('Li+(e)')
pltptr['PF6-'] = elyte.species_index('Pf6-(e)')
pltptr['EC'] = elyte.species_index('C3H4O3(e)')
pltptr['EMC'] = elyte.species_index('C4H8O3(e)')


from bs4 import BeautifulSoup as soup
import urllib
import requests
import pandas as pd
import time
import os
from flask import Flask, render_template,  session, redirect, request
from flask_cors import CORS,cross_origin
import re

# define global paths for Image and csv folders
#IMG_FOLDER = os.path.join('static', 'images')
#CSV_FOLDER = os.path.join('static', 'CSVs')
#app = Flask(__name__)
#app.config['IMG_FOLDER'] = IMG_FOLDER
#app.config['CSV_FOLDER'] = CSV_FOLDER
IMG_FOLDER = os.path.join('static', 'images')
CSV_FOLDER = os.path.join('static', 'CSVs')

class CleanCache:
    '''
    this class is responsible to clear any residual csv and image files
    present due to the past searches made.
    '''

    def __init__(self, directory=None):
        self.clean_path = directory
        # only proceed if directory is not empty
        if os.listdir(self.clean_path) != list():
            # iterate over the files and remove each file
            files = os.listdir(self.clean_path)
            for fileName in files:
                print(fileName)
                os.remove(os.path.join(self.clean_path, fileName))
        print("cleaned!")

class DataCollection:
    def __init__(self):
        self.data = {
		"Name": list(),
		"Price": list(),
        "Link-For-Product": list(),
        "Size-Of-Product": list()
        }

    def get_final_data(self, commentbox=None, i=None):

        try:
            Row = commentbox.find_all("div", {"class": "astra-shop-summary-wrap"})
            #self.data["Name"].append(Row[i].a.img["alt"])  woocommerce-loop-product__title
            fullnameWithSize = Row[i].h2.get_text().strip()
            #print(fullnameWithSize)
            producttitle, Size = fullnameWithSize.split('[')
            Size_Locked = Size[:-1]
            print("Product Title",producttitle)
            print("Product Size",Size_Locked)

            self.data["Name"].append(producttitle)

            #self.data["Size-Of-Product"].append(Size_Locked)
        except:
            self.data["Name"].append("No name")

        try:

            self.data["Price"].append(
                commentbox.find_all("span", {"class": "price"})[i].get_text().strip())
            # self.data["Regular Price (PKR)"].append("Fatima")
        except:
            self.data["Price"].append('0')
 ### ------------ Link and Size-Of-Product Tags ---------------------------------
        try:
            Row = commentbox.find_all("div", {"class": "astra-shop-summary-wrap"})

            #Prod_url = Row.find({"class":"ast - loop - product__link"})
            self.data["Link-For-Product"].append(Row[i].a['href'])
            #self.data["Link-For-Product"].append(Prod_url[i])

            #self.data["Link-For-Product"].append(commentbox.find_all("div", {"class": "cstm_brnd"})[i].get_text().strip())
            # self.data["Brand Name"].append("Siddiq")
        except:
            self.data["Link-For-Product"].append('none')

        ### Work On Sizes

        try:
            self.data["Size-Of-Product"].append(Size_Locked)
            # self.data["Brand Name"].append("Siddiq")
        except:
            self.data["Size-Of-Product"].append('none')

    def get_main_HTML(self, base_URL=None, cat = None , search_string=None):
        # construct the search url with base URL and search string
        # http://yayvo.com/search/result/?q=samsung+mobiles
        search_url = f"{base_URL}/product-category/{cat}/{search_string}"
        # usung urllib read the page
        with urllib.request.urlopen(search_url) as url:
            page = url.read()
        # return the html page after parsing with bs4
        return soup(page, "html.parser")

    def get_data_dict(self):
        return self.data

    def save_as_dataframe(self, dataframe, fileName=None):
        csv_path = os.path.join(CSV_FOLDER, fileName)
        fileExtension = '.csv'
        final_path = f"{csv_path}{fileExtension}"
        # clean previous files -
        CleanCache(directory=CSV_FOLDER)
        # save new csv to the csv folder
        dataframe.to_csv(final_path, index=None)
        print("File saved successfully!!")
        return final_path

    def FMJ_Scraped(self,intent,search_string,size,cat):
        #(intent, search_string, cust_ShalwarKurta_size, cat)
        #kurta - shalwar
        base_URL = 'http://fmjclothing.jhapto.com/'

        #if (intent == 'Shirts-size'):
            #http: // fmjclothing.jhapto.com / product - category / men / shirts /
        #cat = 'men'
        #search_string = 'shirts'
        search_string = search_string.replace(" ", "-")
        print('processing, Please wait')
        get_data = DataCollection()
        yayvo_HTML = get_data.get_main_HTML(base_URL,cat, search_string)
        print(yayvo_HTML)
        print("Length")
        print(len(yayvo_HTML))
        i=0
        #while (i <= len(yayvo_HTML)):
        while (i < 12):
            get_data.get_final_data(yayvo_HTML, i)
            i = i + 1

        yayvo_Scrapped = pd.DataFrame(get_data.get_data_dict())
        print(yayvo_Scrapped)

        #yayvo_Scrapped = yayvo_Scrapped.head(15)
        return yayvo_Scrapped


"""Unit test for treadmill.runtime.docker2._manifest.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

# Disable C0302: Too many lines in module.
# pylint: disable=C0302

import os
import shutil
import socket
import stat
import tempfile
import unittest

# Disable W0611: Unused import
import tests.treadmill_test_skip_windows   # pylint: disable=W0611

import mock

from treadmill.runtime.docker2 import _manifest as app_manifest

class Docker2RuntimeManifestTest(unittest.TestCase):
    """Tests for treadmill.runtime.docker2._manifest."""

    def setUp(self):
        self.tm_env = mock.Mock(
            root='/var/tmp/treadmill/app/approot',
            cell='testcell',
            zkurl='zookeeper://foo@foo:123',
            apps_dir='apps',
        )
        self.maxDiff = None

    def tearDown(self):
        pass

    @mock.patch('treadmill.dist.TREADMILL_BIN', '/path/to/treadcmill34')
    @mock.patch('treadmill.runtime.docker2._manifest._get_user_uid_gid',
                mock.Mock(return_value=(274091, 19290)))
    def test_generate_command(self):
        cmd = app_manifest._generate_command(
            'sleep 10', 'foo'
        )
        self.assertEqual(cmd, 'sleep 10')

        cmd = app_manifest._generate_command(
            'docker://testwt2', 'foo'
        )
        self.assertEqual(
            cmd,
            (
                'exec /path/to/treadcmill34 sproc docker'
                ' --unique_id foo'
                ' --envdirs /env,/services/foo/env'
                ' --image testwt2'
                ' --volume /var/tmp:/var/tmp:rw'
                ' --volume /var/spool:/var/spool:rw'
            )
        )

        cmd = app_manifest._generate_command(
            'docker://testwt2 foo bar', 'foo'
        )
        self.assertEqual(
            cmd,
            (
                'exec /path/to/treadcmill34 sproc docker'
                ' --unique_id foo'
                ' --envdirs /env,/services/foo/env'
                ' --image testwt2'
                ' --volume /var/tmp:/var/tmp:rw'
                ' --volume /var/spool:/var/spool:rw'
                ' --'
                ' foo bar'
            )
        )

if __name__ == '__main__':
    unittest.main()


#
# Author: Tiberiu Boros
#
# Copyright (c) 2018 Adobe Systems Incorporated. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import dynet as dy
import numpy as np
from character_embeddings import CharacterNetwork

class BDRNNLemmatizer:
    def __init__(self, lemmatizer_config, encodings, embeddings, runtime=False):
        self.config = lemmatizer_config
        self.encodings = encodings
        self.embeddings = embeddings
        self.losses=[]

        self.model = dy.Model()
        self.trainer = dy.AdamTrainer(self.model, alpha=2e-3, beta_1=0.9, beta_2=0.9)

        self.character_network = CharacterNetwork(self.config.tag_embeddings_size, encodings,
                                                  rnn_size=self.config.char_rnn_size,
                                                  rnn_layers=self.config.char_rnn_layers,
                                                  embeddings_size=self.config.char_embeddings,
                                                  model=self.model, runtime=runtime)

        self.upos_lookup = self.model.add_lookup_parameters(
            (len(self.encodings.upos2int), self.config.tag_embeddings_size))
        self.xpos_lookup = self.model.add_lookup_parameters(
            (len(self.encodings.xpos2int), self.config.tag_embeddings_size))
        self.attrs_lookup = self.model.add_lookup_parameters(
            (len(self.encodings.attrs2int), self.config.tag_embeddings_size))
        self.char_lookup=self.model.add_lookup_parameters((len(self.encodings.char2int),self.config.char_embeddings))

        if runtime:
            self.rnn = dy.LSTMBuilder(self.config.rnn_layers,
                                  self.config.char_rnn_size * 2 + self.config.char_embeddings, self.config.rnn_size,
                                  self.model)
        else:
            from utils import orthonormal_VanillaLSTMBuilder
            self.rnn = orthonormal_VanillaLSTMBuilder(self.config.rnn_layers,
                                      self.config.char_rnn_size * 2 + self.config.char_embeddings, self.config.rnn_size,
                                      self.model)

        self.att_w1 = self.model.add_parameters((200, self.config.char_rnn_size * 2))
        self.att_w2 = self.model.add_parameters((200, self.config.rnn_size+self.config.tag_embeddings_size))
        self.att_v = self.model.add_parameters((1, 200))

        self.start_lookup = self.model.add_lookup_parameters(
            (1, self.config.char_rnn_size * 2 + self.config.char_embeddings))

        self.softmax_w = self.model.add_parameters((len(self.encodings.char2int) + 1, self.config.rnn_size))
        self.softmax_b = self.model.add_parameters((len(self.encodings.char2int) + 1))
        self.softmax_casing_w = self.model.add_parameters((2, self.config.rnn_size))
        self.softmax_casing_b = self.model.add_parameters((2))

    def _attend(self, input_vectors, state, embeddings):
        w1 = self.att_w1.expr()
        w2 = self.att_w2.expr()
        v = self.att_v.expr()
        attention_weights = []

        w2dt = w2 * dy.concatenate([state.h()[-1], embeddings])
        for input_vector in input_vectors:
            attention_weight = v * dy.tanh(w1 * input_vector + w2dt)
            attention_weights.append(attention_weight)

        attention_weights = dy.softmax(dy.concatenate(attention_weights))

        output_vectors = dy.esum(
            [vector * attention_weight for vector, attention_weight in zip(input_vectors, attention_weights)])

        return output_vectors

    def _predict(self, word, upos, xpos, attrs, num_chars=0, gs_chars=None):
        if num_chars == 0:
            runtime = True
        else:
            runtime = False

        char_emb, states = self.character_network.compute_embeddings(word, runtime=runtime)

        num_predictions = 0
        softmax_list = []
        m1, m2, m3 = 0, 0, 0
        zero_vec = dy.vecInput(self.config.tag_embeddings_size)
        if upos in self.encodings.upos2int:
            upos_emb = self.upos_lookup[self.encodings.upos2int[upos]]
            m1 = 1
        else:
            upos_emb = zero_vec

        if xpos in self.encodings.xpos2int:
            xpos_emb = self.xpos_lookup[self.encodings.xpos2int[xpos]]
            m2 = 1
        else:
            xpos_emb = zero_vec

        if attrs in self.encodings.attrs2int:
            attrs_emb = self.attrs_lookup[self.encodings.attrs2int[attrs]]
            m3 = 1
        else:
            attrs_emb = zero_vec

        scale = float(4.0) / (m1 + m2 + m3 + 1.0)

        scale = dy.scalarInput(scale)
        tag_emb = (upos_emb + xpos_emb + attrs_emb + char_emb) * scale
        rnn = self.rnn.initial_state().add_input(self.start_lookup[0])
        char_emb=dy.inputVector([0]*self.config.char_embeddings)

        while True:
            attention = self._attend(states, rnn, tag_emb)

            input = dy.concatenate([attention, char_emb])
            rnn = rnn.add_input(input)

            softmax = dy.softmax(self.softmax_w.expr() * rnn.output() + self.softmax_b.expr())
            softmax_casing = dy.softmax(self.softmax_casing_w.expr() * rnn.output() + self.softmax_casing_b.expr())
            softmax_list.append([softmax, softmax_casing])
            if num_chars == 0:
                s_index=np.argmax(softmax.npvalue())
                if s_index == len(self.encodings.char2int):
                    break
                char_emb = self.char_lookup[s_index]
            else:
                if num_predictions<len(gs_chars):
                    char=gs_chars[num_predictions]
                    if char in self.encodings.char2int:
                        char_emb = self.char_lookup[self.encodings.char2int[char]]
                    else:
                        char_emb=self.char_lookup[self.encodings.char2int["<UNK>"]]

            num_predictions += 1
            if num_predictions == num_chars or num_predictions > 255:
                break

        return softmax_list

    def start_batch(self):
        self.losses=[]
        dy.renew_cg()

    def end_batch(self):
        total_loss=0
        if len(self.losses)>0:
            loss=dy.esum(self.losses)
            total_loss=loss.value()
            loss.backward()
            self.trainer.update()
        self.losses=[]
        return total_loss

    def learn(self, seq):
        total_loss=0
        for entry in seq:
            if entry.upos != 'NUM' and entry.upos != 'PROPN':
                losses = []
                unilemma = unicode(entry.lemma, 'utf-8')
                n_chars = len(unilemma)
                softmax_output_list = self._predict(entry.word, entry.upos, entry.xpos, entry.attrs, num_chars=n_chars + 1, gs_chars=unilemma)
                #print unilemma.encode('utf-8')#, softmax_output_list
                for softmax, char in zip(softmax_output_list[:-1], unilemma):

                    char_index = -1
                    if char.lower() == char:
                        casing = 0
                    else:
                        casing = 1
                    char = char.lower()
                    if char in self.encodings.char2int:
                        char_index = self.encodings.char2int[char]
                    if char_index != -1:
                        losses.append(-dy.log(dy.pick(softmax[0], char_index)))
                    losses.append(-dy.log(dy.pick(softmax[1], casing)))
                    #print np.argmax(softmax[0].npvalue()), char_index, softmax

                losses.append(-dy.log(dy.pick(softmax_output_list[-1][0], len(self.encodings.char2int))))
                loss = dy.esum(losses)
                self.losses.append(loss)

    def tag(self, seq):
        dy.renew_cg()
        lemmas = []
        for entry in seq:
            if entry.upos=='NUM' or entry.upos == 'PROPN':
                lemma=entry.word.decode('utf-8')
            else:
                softmax_output_list = self._predict(entry.word, entry.upos, entry.xpos, entry.attrs)
                lemma = ""
                for softmax in softmax_output_list[:-1]:
                    char_index=np.argmax(softmax[0].npvalue())
                    if char_index<len(self.encodings.characters):
                        char = self.encodings.characters[char_index]
                        if np.argmax(softmax[1].npvalue()) == 1:
                            char = char.upper()
                        lemma += char
            lemmas.append(lemma)
        return lemmas

    def save(self, path):
        self.model.save(path)

    def load(self, path):
        self.model.populate(path)


# Initialize App Engine and import the default settings (DB backend, etc.).
# If you want to use a different backend you have to remove all occurences
# of "djangoappengine" from this file.

import os, sys

# Django settings for crew_time project.

import os

PROJECT_ROOT = os.path.dirname(__file__)

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

sys.path.insert(0, os.path.join(BASE_DIR, '..'))

SECRET_KEY = '673trgfajdhsfj;djsfahfDFSLJHKFHhjl'

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'tastypie',
    'bingo',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware'
)

# This test runner captures stdout and associates tracebacks with their
# corresponding output. Helps a lot with print-debugging.
TEST_RUNNER = 'djangotoolbox.test.CapturingTestSuiteRunner'

DEBUG = True

STATIC_DOC_ROOT = os.path.join(BASE_DIR, 'static')

TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),)

ROOT_URLCONF = 'urls'
APPEND_SLASH = True

LOGIN_REDIRECT_URL = '/home/'
LOGIN_URL = '/login/'
LOGOUT_URL = '/logout/'

SITE_ID = 1

# Activate django-dbindexer if available
try:
    import dbindexer
    DATABASES['native'] = DATABASES['default']
    DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'}
    INSTALLED_APPS += ('dbindexer',)
except ImportError:
    pass

DATABASE_ENGINE = 'sqlite3'           # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = os.path.join(PROJECT_ROOT, 'crew_db')             # Or path to database file if using sqlite3.
DATABASE_USER = ''             # Not used with sqlite3.
DATABASE_PASSWORD = ''         # Not used with sqlite3.
DATABASE_HOST = ''             # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = ''             # Set to empty string for default. Not used with sqlite3.