'''

    Isabela Server Project made by Miguel Marques and Paulo Cardoso
        The project was made in Linux, so we're not sure if
                        this will work in windows.

    All of this was made with Python 2.7.15rc1 and for GUI we used Tkinter.

    This file only has the client part of the project, don't forget
            to have isabella_layout.png in the folder. To run
                this file use python3 isabela_client.py

'''
import socket
import sys
import cmd
from _thread import *
import signal
import struct
from tkinter import *
import time
def substhreadserver():
    global text_subs
    global ssubs
    time.sleep(2)
    global subsport
    try:
        ssubs = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    except socket.error:
        print("Failed to connect the socket")
        sys.exit()
    try:
        ssubs.bind((host,subsport))
    except socket.error:

        print("Binding Failed")
        sys.exit()
    ssubs.listen()
    print("Subs Socket Created")
    subsconnection, subsaddr = ssubs.accept()
    subsconnection.send("CONNECTION CREATED".encode())
    while True:
        subsdata = subsconnection.recv(4096)
        if not subsdata:
            break
        reply = subsdata.decode()
        if (reply == "sss"):
            reply = ""
            text_subs.delete(0.0,END)
        text_subs.insert(END,reply)

def catch_ctrl_c(sig, frame):
    ignore()

def gotoserver():
    time.sleep(1)
    global subsport
    global output_info
    aux = s.recv(2)
    subsport = struct.unpack('!H',aux)[0]
    print("SUBSPORT --> {0}".format(subsport))
    while True:
        reply = s.recv(4096)
        print(reply.decode(),end="")
        if not reply:
            break
        if reply.decode() == "Exit\n":
            s.close()
            sys.exit()
        output_info.insert(END,reply)

def click():
    global output_info
    global text_input
    output_info.delete(0.0,END)
    var =text_input.get()+str("_")
    try:
        s.send(var.encode())
    except socket.error:
        print("Did not send successfully")
        s.close()
        sys.exit()
    text_input.delete(0,END)

def enter_key(event):
    click()

def leave():
    global janela
    global ssubs
    var = "3478GFDgu4w639_"
    s.send(var.encode())
    janela.destroy()
    s.close()
    ssubs.close()
    sys.exit()

def ignore():
    pass

def interface():
    global text_input
    global output_info
    global text_subs
    global janela
    janela = Tk()
    frame = Frame(master=janela, width=500, height=500, bg='#2C2C2C')
    janela.title("Isabela App")
    janela.configure(background = "#2C2C2C")
    janela.bind("<Return>",enter_key)
    janela.protocol("WM_DELETE_WINDOW", ignore)
    janela.resizable(width = False, height = False)
    isabella_layout = PhotoImage(file ="isabella_layout.png")
    Label(janela,text ="WELCOME TO ISABELA SERVER",bg = "#2C2C2C",fg="#33D3B3",font ="none 20 bold").grid(row = 0, column =1,sticky = N)
    Label(janela,text ="SUBSCRITIONS",bg = "#2C2C2C",fg="#33D3B3",font ="none 20 bold").grid(row = 1, column =0,sticky = S)
    Label(janela,image = isabella_layout, bg = "#2C2C2C").grid(row = 1, column =0,sticky = N)
    text_input = Entry(janela,width=30,bg = "white",font ="none 13 bold")
    text_input.grid(row=2,column=1,sticky=N)
    text_subs = Text(janela,width = 35,height=20,fg = "#2C2C2C",bg="#33D3B3",font ="none 10 bold")
    text_subs.grid(row=2,column=0,columnspan=1, rowspan=1,sticky = N)
    output_info = Text(janela,width = 50,height = 20,bg = "#2C2C2C",fg="#33D3B3", wrap = WORD,font ="none 15 bold")
    output_info.grid(row = 1, column =1,sticky = N)
    Button(janela, text = "SUBMIT",fg = "#2C2C2C",bg="#33D3B3",width=10,height=9,command = click,font ="none 17 bold").grid(row = 2, column =1,sticky = E,padx=70, pady=60)
    Button(janela, text = "EXIT",fg = "#2C2C2C",bg="#FF4945",width=10,height=9,command = leave,font ="none 17 bold").grid(row = 2, column =1,sticky = W,padx=70, pady=60)

    janela.mainloop()

if __name__ == '__main__':
    global subsport
    global output_info
    global text_input
    global LOGIN
    global text_subs
    global janela
    LOGIN = False
    host = "localhost"
    port = 8880
    signal.signal(signal.SIGINT, catch_ctrl_c)
    try:
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
    except socket.error:
        print("Failed to connect");
        sys.exit()
    print("Socket Created")
    try:
        remote_ip=socket.gethostbyname(host)
        print(remote_ip)
    except socket.gaierror:
        print("Hostname could not be resolved")
        sys.exit()
    print("IP Address: "+ remote_ip)
    try:
        s.connect((remote_ip,port))
    except ConnectionRefusedError:
        print("Please make sure the server is on")
        sys.exit()
    print("Socket connected to: "+host+" using IP "+ remote_ip)

    start_new_thread(interface,( ))
    start_new_thread(substhreadserver,( ))
    gotoserver()
    print("Socket fechado")
    s.close()


# 1. 15663 - N과 M (9) (https://www.acmicpc.net/problem/15663)
"""
문제 설명
N개의 자연수와 자연수 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오.
N개의 자연수 중에서 M개를 고른 수열
"""

# 내 풀이
import sys
input=sys.stdin.readline
n, m=map(int, input().split())
li=list(map(int, input().split()))
li.sort()

li_co=[0]*10001
for i in li:
    li_co[i]+=1

final={}
result=[]
def check():
    if len(result)==m and tuple(result) not in final:
        print(' '.join(map(str, result)))
        final[tuple(result)]=1
    else:
        for i in li:
            if li_co[i]-1 >=0:
                result.append(i)
                li_co[i]-=1
                check()
                result.pop()
                li_co[i]+=1

check()

"""
insight 정리
1. 3중 조건문을 무리하게 쓰다가 시간 초과, 해시가 아닌 리스트로 final 변수를 활용하다 시간 초과, 무한 로프로 인한 런타임 오류 등등..
의도치 않게 많은 오류를 겪어버린 문제..
2. 백트래킹을 써야할 때 결과 값을 겹치치 않게 뽑아내는 방법, 주어진 수의 개수만큼만 활용하여 뽑아내는 방법을 구현해야 한다면 참고할 것
"""


import time
import keras
import random
from keras.layers import Dense
from keras.models import Sequential
from keras.callbacks import EarlyStopping
from keras.regularizers import l2
from keras.layers import Dropout
from keras.models import load_model
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import KFold
from sklearn.model_selection import RandomizedSearchCV

import matplotlib.pyplot as plt
import numpy as np

from nn_lib import (
    MultiLayerNetwork,
    Trainer,
    Preprocessor,
    save_network,
    load_network,
)
from illustrate import illustrate_results_FM

def evaluate_architecture(model, valdation_set):
    return None

def create_model(neurons=100, activation="relu", input_dim=(3,),
        output_dim=3, hidden_layers=2, learning_rate=0.001):

    model = Sequential()

    model.add(Dense(neurons, activation=activation, input_shape=input_dim))

    for i in range(hidden_layers - 1):
        model.add(Dense(neurons, activation=activation))
        #if (i != len(neurons) - 1):
            #model.add(Dropout(0.2))

    model.add(Dense(output_dim, activation="linear"))

    keras.optimizers.Adam(lr=learning_rate)

    model.compile(loss="mse", optimizer="adam", metrics=['mae'])

    return model

def train_and_evaluate(model, x_train, y_train, x_val, y_val, batch,
    num_epochs):

    early_stopper = EarlyStopping(monitor='val_loss',
                                  patience=20,
                                  verbose=0,
                                  restore_best_weights=True)

    model.fit(x_train, y_train,
              validation_data=(x_val, y_val),
              batch_size=batch,
              verbose=1,
              epochs=num_epochs,
              callbacks=[early_stopper])

    return model.evaluate(x_val, y_val, verbose=0)

def k_fold_cross_validation(k, x, y, model_parameters, training_parameters):
    neurons, activation, input_dim, output_dim, hidden_layers, learning_rate = model_parameters
    batch_size, num_epochs = training_parameters

    if (k <= 1): # don't cross validate if k <= 1
        split_idx = int(0.9 * len(x))

        x_train = x[:split_idx]
        y_train = y[:split_idx]
        x_val = x[split_idx:]
        y_val = y[split_idx:]

        model = create_model(neurons, activation, input_dim, output_dim, hidden_layers, learning_rate)
        mse, mae = train_and_evaluate(model, x_train, y_train, x_val, y_val,
                                        batch_size, num_epochs)
        return(mse, mae, model)

    else:
        kf = KFold(n_splits=k, shuffle=False)

        scores = []
        i = 1
        for train_index, test_index in kf.split(x):
            print("Running Fold", i, "/", k)
            model = None

            start = time.time()
            model = create_model(neurons, activation, input_dim, output_dim, hidden_layers, learning_rate)
            scores.append(train_and_evaluate(model, x[train_index], y[train_index],
                            x[test_index], y[test_index], batch_size, num_epochs))

            end = time.time()
            print("executed in", end - start, "seconds")
            i+=1

        mse, mae = np.mean(np.array(scores), axis=0)
        msestd, maestd = np.std(np.array(scores), axis=0)
        return (mse, mae, msestd, maestd, model)

def predict_hidden(dataset):
    model = load_model('best_model_FM.h5')
    return(model.predict(dataset))

def validate_model(x, y, activation, epochs, neurons, lr, batch_size, num_hidden):
        model_parameters = (neurons, activation, (3,), 3, num_hidden, lr)
        training_parameters = (batch_size, epochs)

        mse, mae, msestd, maestd, model = k_fold_cross_validation(5, x, y, model_parameters, training_parameters)

        return (mse, mae, msestd, maestd)

def main():
    dataset = np.loadtxt("FM_dataset.dat")
    #######################################################################
    #                       ** START OF YOUR CODE **
    #######################################################################

    ############################ Question 1 ###############################
    model = Sequential([
        Dense(36, activation='relu', input_shape=(3,)),
        Dense(36, activation='relu'),
        Dense(36, activation='relu'),
        Dense(36, activation='relu'),
        Dense(36, activation='relu'),
        Dense(36, activation='relu'),
        Dense(36, activation='relu'),
        Dense(36, activation='relu'),
        Dense(36, activation='relu'),
        Dense(36, activation='relu'),
        Dense(36, activation='relu'),
        Dense(3, activation='linear')
    ])

    model = create_model(neurons=36, activation="relu", input_dim=(3,),
            output_dim=3, hidden_layers=200, learning_rate=0.001)

    keras.optimizers.Adam(lr=0.001)
    keras.optimizers.RMSprop(lr=0.001)
    model.compile(loss="mean_squared_error", optimizer="adam", metrics=['mae'])
    early_stopper = EarlyStopping(monitor='val_loss', patience=20, verbose=1, restore_best_weights=True)

    np.random.shuffle(dataset)
    x, y = dataset[:, :3], dataset[:, 3:]

    split_idx = int(0.8 * len(x))

    x_train = x[:split_idx]
    y_train = y[:split_idx]
    x_val = x[split_idx:]
    y_val = y[split_idx:]

    history = model.fit(x_train, y_train, validation_data=(x_val, y_val), batch_size=100, epochs=500, callbacks=[early_stopper])
    mse, mae = model.evaluate(x_val, y_val)
    #out = open("initial_results_bigger_model.txt", "w")
    #out.write("mse: " + str(mse) + " mae: " + str(mae))
    #out.close()
    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'validation'], loc='upper left')
    plt.show()

    ############################ Question 2/3 ###############################

    # # see how learning rate affects accuracy
    # lr_history = []
    # mse_history = []
    #
    # neuron= 128
    # hidden_layer = 4
    # k = 1
    # learning_rates = (np.linspace(0.00005, 0.05, 50)).tolist()
    # for lr in learning_rates:
    #     model_parameters = (neuron, "relu", (3,), 3, hidden_layer, lr)
    #     training_parameters = (100, 100)
    #
    #     mse, mae, model = k_fold_cross_validation(1, x, y, model_parameters, training_parameters)
    #
    #     lr_history.append(lr)
    #     mse_history.append(mse)
    #
    # plt.scatter(lr_history, mse_history)
    # plt.show()

    # # see how neurons affects accuracy
    # neuron_history = []
    # mse_history = []
    # neurons = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]
    # lr = 0.001
    # for neuron in neurons:
    #     model_parameters = (neuron, "relu", (3,), 3, 4, lr)
    #     training_parameters = (100, 100)
    #
    #     mse, mae, model = k_fold_cross_validation(1, x, y, model_parameters, training_parameters)
    #
    #     neuron_history.append(neuron)
    #     mse_history.append(mse)
    #
    # plt.scatter(neuron_history, mse_history)
    # plt.show()

    # # see how hidden_layers affects accuracy
    # layer_history = []
    # mse_history = []
    # hidden_layers = range(1, 17, 1)
    # lr = 0.001
    # for hidden_layer in hidden_layers:
    #     model_parameters = (128, "relu", (3,), 3, hidden_layer, lr)
    #     training_parameters = (100, 100)
    #
    #     mse, mae, model = k_fold_cross_validation(1, x, y, model_parameters, training_parameters)
    #
    #     layer_history.append(hidden_layer)
    #     mse_history.append(mse)
    #
    # plt.scatter(layer_history, mse_history)
    # plt.show()

    # # see how batch_sizes affects accuracy
    # batch_history = []
    # mse_history = []
    # hidden_layer = 4
    # batch_sizes = [2, 4, 8, 16, 32, 64, 128, 512, 1024]
    # lr = 0.001
    # for batch in batch_sizes:
    #     model_parameters = (128, "relu", (3,), 3, hidden_layer, lr)
    #     training_parameters = (batch, 100)
    #
    #     mse, mae, model = k_fold_cross_validation(1, x, y, model_parameters, training_parameters)
    #
    #     batch_history.append(batch)
    #     mse_history.append(mse)
    #
    # plt.scatter(batch_history, mse_history)
    # plt.show()

    split_idx = int(0.9 * len(x))

    x_train = x[:split_idx]
    y_train = y[:split_idx]
    x_val = x[split_idx:]
    y_val = y[split_idx:]

    k = 1
    min_mse = 9999
    best_model = None
    best_params = None

    #random search with replacement over the following hyper-parameters
    learning_rates = (np.linspace(0.00005, 0.05, 50)).tolist()
    activations = ["relu"]
    neurons = range(128, 257)
    hidden_layers = range(3, 13, 1)
    epochs = [100]
    batch_sizes = [8, 16, 32, 64]

    output_layer = 3

    #out = open("random_search_results.txt", "w")

    x_train = x[:split_idx]
    y_train = y[:split_idx]
    x_test = x[split_idx:]
    y_test = y[split_idx:]

    model = load_model('best_model_FM.h5')
    print(model.evaluate(x_test, y_test))

    return
    for i in range(70):
        learning_rate = learning_rates[random.randrange(len(learning_rates))]
        activation = activations[random.randrange(len(activations))]
        neuron = neurons[random.randrange(len(neurons))]
        hidden_layer = hidden_layers[random.randrange(len(hidden_layers))]
        epoch = epochs[random.randrange(len(epochs))]
        batch_size = batch_sizes[random.randrange(len(batch_sizes))]

        model_parameters = (neuron, activation, (3,), output_layer, hidden_layer, learning_rate)
        training_parameters = (batch_size, epoch)

        parameters = {"learning_rate":learning_rate,
                      "activation_function": activation,
                      "neurons":neuron,
                      "hidden_layers":hidden_layer,
                      "epochs":epoch,
                      "batch_size":batch_size}

        # skip models when capacity is too high
        if (neuron*hidden_layer >= 6400):
            continue

        print(parameters)

        mse, mae, model = k_fold_cross_validation(k, x_train, y_train, model_parameters, training_parameters)

        #out.write(str(parameters) + " mse: " + str(mse) + " mae: " + str(mae) + "\n")

        if mse < min_mse:
            min_mse = mse
            best_model = model
            best_params = parameters

    #out.close()
    print("best mean square error", min_mse)
    print("achived with", best_params)

    best_model.save("best_model_FM.h5")

    print("test set results")
    print(model.evaluate(x_test, y_test))

    #######################################################################
    #                       ** END OF YOUR CODE **
    #######################################################################
    #illustrate_results_FM(network, prep)

if __name__ == "__main__":
    main()


#-*- coding: utf-8 -*-
import copy
from apps.oclib.model import UserModel
from apps.config import game_config

class UserTeams(UserModel):
    pk = 'uid'
    fields = ['uid','team','develop_last','develop_info','teams_info']
    def __init__(self):
        """用户佣兵基本信息
        """
        self.uid = ''
        self.team = []           #出站中的佣兵列表（现版本为1个）
        #佣兵培养信息
        self.develop_info = {}
        #存储培养临时信息
        self.develop_last = {'vitality':0,'strength':0,'stealth':0,'intelligence':0}
        #佣兵信息
        self.teams_info = {}

    @classmethod
    def get_instance(cls,uid):
        obj = super(UserTeams,cls).get(uid)
        if obj is None:
            obj = cls._install(uid)
        return obj

    @classmethod
    def get(cls,uid):
        obj = super(UserTeams,cls).get(uid)
        return obj

    @classmethod
    def _install(cls,uid):
        obj = cls()
        obj.uid = uid
        obj.put()
        return obj

    @property
    def user_base(self):
        if not hasattr(self, '_user_base'):
            from apps.models.user_base import UserBase
            self._user_base = UserBase.get(self.uid)
        return self._user_base

    def add_team(self,tid):
        """开放佣兵，tid = 1/2/3
        """
        from apps.models.user_cards import UserCards
        from apps.models.virtual.card import Card as CardMod
        user_cards_obj = UserCards.get(self.uid)
        card_mod = CardMod(user_cards_obj.cid)
        card_teams = card_mod.teams #获取佣兵的信息
        tcid = card_teams[str(tid)]
        card_config = game_config.card_config[tcid]
        self.teams_info[str(tid)] = {
                'cid':tcid,
                'equipments':{
                    'mainWeap':'',  #01主手武器
                    'secWeap':'',   #02副手武器
                    'armor':'',     #05胸甲
                    'pants':'',     #09裤子
                },
                'refresh_num':0,
                'skill_list':{'1':{"skill":card_config["skill"][0],"is_lock":0}},
        }
        self.develop_info[str(tid)] = {'vitality':0,'strength':0,'stealth':0,'intelligence':0}
        self.put()

    def card_obj(self,tid):
        """获取佣兵的信息
        """
        #获取主将的mod对象
        from apps.models.virtual.card import Card as CardMod
        lv = self.user_base.property_info.property_info["lv"]
        tcid = self.teams_info[str(tid)]["cid"]
        cardmod = CardMod.get(tcid,lv,equip_attr = self.get_equip_attr(str(tid)))
        return cardmod

    def category(self,tid):
        """主角色类型
        """
        card_config = game_config.card_config
        return card_config[self.teams_info[tid]["cid"]]["category"]

    def get_equip_attr(self,tid):
        """获取装备的属性,ctype:'1','2','3'代表佣兵
        """
        attr_list = {'vitality':0,'strength':0,'stealth':0,'intelligence':0,'hp':0,\
            'physDef':0,'magDef':0,'durability':0,'mp':0,'mpRecover':0,'critical':0,\
            'invasion':0,'evasion':0,'minDamage':0,'maxDamage':0}
        from apps.models.user_equipments import UserEquipments
        user_equipments_obj = UserEquipments.get_instance(self.uid)
        equipments = user_equipments_obj.equipments

        #佣兵身上的装备信息
        user_equipments = self.teams_info[str(tid)]["equipments"].values()
        #佣兵培养的信息
        develop_info = self.develop_info.get(str(tid),{})

        strengthen_config  = game_config.equipment_strengthen_config
        class_influence = strengthen_config["class_influence"]
        effect_base = strengthen_config["effect_base"]

        material_config = game_config.material_config
        gem_config = game_config.gem_config["gem_upgrade"]
        for equip in user_equipments:
            if equip and (equip in equipments):
                equip_dict = copy.deepcopy(equipments[equip])
                quality = equip_dict["quality"]
                minilv = equip_dict["minilv"]
                main_attr = equip_dict['main_attr']
                vice_attr = equip_dict['vice_attr']
                #把主属性加到attr_list,并加上强化的效果
                for k,v in main_attr.items():
                    if minilv > 0:
                        main_attr_effect = int(v * effect_base[str(minilv)] / 100 * class_influence[str(quality)]["effect_multiplier"])
                        main_attr = main_attr_effect + v
                    else:
                        attr_list[k] += int(v)
                #把副属性加到attr_list
                for k_,v_ in vice_attr.items():
                    attr_list[k_] += int(v_)
                #把镶嵌的宝石的属性加到attr_list
                for _,_v in equip_dict["gem_hole"].items():
                    if _v not in [0,1]:
                        item_config = material_config[_v]
                        gem_effect = item_config['gem_effect']
                        gem_lv = item_config['lv']
                        effect = gem_config[str(gem_lv)]['effect']
                        attr_list[gem_effect] += int(effect)

        attr_list["vitality"] += develop_info.get("vitality",0)
        attr_list["strength"] += develop_info.get("strength",0)
        attr_list["stealth"] += develop_info.get("stealth",0)
        attr_list["intelligence"] += develop_info.get("intelligence",0)
        return attr_list


import random
from tkinter import filedialog
from tkinter.filedialog import *

root = Tk()
root.title("learn English irregular verbs")
root.geometry('570x125')
root.resizable(width=False, height=False)

word = ''

def open_files():
    files = filedialog.askopenfilename(initialdir="/", title="Select file",
                                     filetypes=(("txt", "*.txt"), ("all files", "*.*")))
    temp = []
    f = open(files,'r')
    for i in f.readlines():
        temp.append(i)
    f.close()

    f = open('verbs.txt', 'w')
    f.writelines(temp)
    f.close()

def read_file():
    temp = []
    if os.path.isfile("verbs.txt"):
        f = open("verbs.txt", 'r')
        for i in f.readlines():
            temp.append(i)
        f.close()
        return temp

def question(event):
    global word

    if os.path.isfile("verbs.txt"):
        temp = read_file()
        word = random.choice(temp)
        word = word.split(",")
        Label_output['text'] = word[3]
        Label_verb1_output["text"] = " "
        Label_verb2_output["text"] = " "
        Label_verb3_output["text"] = " "

        entry_verbs1_input.delete(0, END)
        entry_verbs2_input.delete(0, END)
        entry_verbs3_input.delete(0, END)
        Label_verbtest_output["text"] = " "
    else:
        Label_output['text'] = 'Absent file verbs.txt'

def chek(event):
    if os.path.isfile("verbs.txt"):
        verb1 = entry_verbs1_input.get()
        verb2 = entry_verbs2_input.get()
        verb3 = entry_verbs3_input.get()
        verb = verb1 + " " + verb2 + " " + verb3
        verb = verb.split(" ")
        if len(word) != 0:
            if verb[0] == word[0]:
                Label_verb1_output["text"] = "ok"
            else:
                Label_verb1_output["text"] = "no"
            if verb[1] == word[1]:
                Label_verb2_output["text"] = "ok"
            else:
                Label_verb2_output["text"] = "no"
            if verb[2] == word[2]:
                Label_verb3_output["text"] = "ok"
            else:
                Label_verb3_output["text"] = "no"

            Label_verbtest_output["text"] = word[:-1]
        else:
            Label_output['text'] = 'Click the button Begin'
    else:
        Label_output['text'] = 'Absent file verbs.txt'

def close_win():
    root.destroy()

m = Menu(root)
root.config(menu=m)
fm = Menu(m, tearoff=0)
m.add_cascade(label="File", menu=fm)
fm.add_command(label="Open...", command=open_files)
fm.add_command(label="Exit", command=close_win)

frame_1 = Frame(root,bg = "black",bd = 1)
frame_1.grid(row = 1,column =2)
frame_2 = Frame(root,bg = "black",bd = 1)
frame_2.grid(row = 2,column =2)
frame_3 = Frame(root,bg = "black",bd = 1)
frame_3.grid(row = 3,column =2)
frame_4 = Frame(root,bg = "black",bd = 1)
frame_4.grid(row = 4,column =1)
frame_5 = Frame(root,bg = "black",bd = 1)
frame_5.grid(row = 0,column =1)

Label_input = Label(root, text='Read and translate')
Label_input.grid(column=0, row=0, sticky='w')

Label_input = Label(root, text='Write 3 forms irregular verbs')
Label_input.grid(column=0, row=1, sticky='w')

entry_verbs1_input = Entry(root)
entry_verbs1_input.grid(row=1, column=1, sticky='w')

entry_verbs2_input = Entry(root)
entry_verbs2_input.grid(row=2, column=1, sticky='w')

entry_verbs3_input = Entry(root)
entry_verbs3_input.grid(row=3, column=1, sticky='w')

Label_output = Label(frame_5, width=40, bg="white", fg="black", height = 2)
Label_output.grid(column=1, row=0, sticky='w')

Label_verb1_output = Label(frame_1, width=5, bg="white", fg="black")
Label_verb1_output.grid(column=2, row=1)

Label_verb2_output = Label(frame_2, width=5, bg="white", fg="black")
Label_verb2_output.grid(column=2, row=2)

Label_verb3_output = Label(frame_3, width=5, bg="white", fg="black")
Label_verb3_output.grid(column=2, row=3)

Label_verbtest_output = Label(frame_4, width=40, bg="white", fg="black")
Label_verbtest_output.grid(column=1, row=4)

Button_input = Button(root, text='Begin')
Button_input.grid(column=2, row=0)
Button_input.bind("<Button-1>", question)

Button_input = Button(root, text='check')
Button_input.grid(column=2, row=4)
Button_input.bind("<Button-1>", chek)

root.mainloop()


from collections import Counter

class Char:
    def __init__(self):
        self.occurrences = []
        self.count = 0

    def add(self, c):
        self.occurrences.append(c)
        self.count += 1

    def popular(self):
        counter = Counter(self.occurrences)
        common = counter.most_common(1)
        return common[0][0]

    def least(self):
        counter = Counter(self.occurrences)
        least = counter.most_common(self.count)
        return least[len(least) - 1][0]

def corrected(strings, popular=True):
    characters = []
    char_count = len(strings[0])
    for i in range(char_count):
        characters.append(Char())

    for s in strings:
        for i in range(char_count):
            characters[i].add(s[i])

    out = ""
    for c in characters:
        if (popular):
            out += c.popular()
        else:
            out += c.least()

    return out

if __name__ == '__main__':
    strings = [s.rstrip() for s in open("input.txt", "r").readlines()]
    out = corrected(strings)
    print("Answer:", out)
    out = corrected(strings, False)
    print("Answer:", out)


# -*-coding: utf-8-*-
"""
    函数作用域是函数中的基础问题，也是函数变量执行空间的优先级准则。
"""
__author__ = "George"
__date__ = "2018/10/09"

"""
    下面从一个闭包函数来分析常见的函数作用域
"""

file_name = "function_scope.py"
def wrapper():
    filename = "enclosed.py"

    def show_filename():
        return "filename : % s" % filename

    # 输出filename
    print(filename)
    return show_filename

wrapper()


import pygame
from pygame.locals import *
import time
from drawingPrimitives import *

graph = {}
visited = {}
queue = []

def DFS(rootNode):
    if (visited[rootNode] == False):
        visited[rootNode] = True
        TraversalDraw()
        time.sleep(1)
        for i in graph[rootNode]:
            DFS(i)

def BFS():
    global queue
    if(len(queue) == 0):
        return 0
    node = queue.pop(0)
    for tempNode in graph[node]:
        if(not(tempNode in queue)):
            queue.append(tempNode)
    if(visited[node] == False):
        visited[node] = True
    TraversalDraw()
    time.sleep(1)
    for x in visited:
        if(visited[x] == False):
            BFS()

def TraversalDraw():
    #glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    index = 0
    for i in graph:
        if visited[i] == True:
            drawFilledCircle(i[0], i[1])
            index += 1
    for i in graph:
        if visited[i] == True and graph[i]:
            for endpoint in graph[i]:
                if visited[endpoint] == True:
                    drawLine(i[0], i[1], endpoint[0], endpoint[1])
    pygame.display.flip()

def draw():
    index = 0
    for pos in graph:
        drawHollowCircle(pos[0], pos[1], index)
        index += 1
        # textsurface = myfont.render('0', False, (0, 0, 255))
        # screen.blit(textsurface, dest=(pos[0], pos[1]))
    for node in graph:
        if(graph[node]):
            for endPoint in graph[node]:
                drawLine(node[0], node[1], endPoint[0], endPoint[1])

def main():
    pygame.init()
    pygame.font.init()
    display = (WIDTH, HEIGHT)
    pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
    gluOrtho2D(0, WIDTH, HEIGHT, 0)

    # default mode
    mode = "view-only"
    print("current mode is "+mode)
    print("key-bindings are")
    print("i: Thêm node, c: Thêm cạnh, d: Xóa cạnh, e: Xóa nốt, a: Duyệt DFS , b: Duyệt BFS, any other key for view-only")

    connections = 0
    conNode = None
    deletions = 0
    delNode = None
    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                keyPressed = event.key
                if pygame.key.name(keyPressed) == 'i':
                    mode = "insert"
                elif pygame.key.name(keyPressed) == 'c':
                    mode = "connect"
                elif pygame.key.name(keyPressed) == 'd':
                    mode = "disconnect"
                elif pygame.key.name(keyPressed) == 'e':
                    mode = "eliminate"
                elif pygame.key.name(keyPressed) == 'a':
                    mode = "DFS"
                elif pygame.key.name(keyPressed) == 'b':
                    mode = "BFS"
                else:
                    mode = "view-only"
                    print(
                        "i for insert, c for connect, d for disconnect, e for eliminate, a for DFS , b for BFS, any other key for view-only")
                print("key "+pygame.key.name(keyPressed) +
                      " pressed, mode is "+mode)

            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1 and mode == "insert":
                    pos = pygame.mouse.get_pos()
                    flag = 0
                    if((pos[0] <= RAD or pos[0] >= WIDTH-RAD) or (pos[1] <= RAD or pos[1] >= HEIGHT-RAD)):
                        flag = 1
                    for pos1 in graph:
                        if(flag == 1):
                            break
                        dist = distance(pos[0], pos[1], pos1[0], pos1[1])
                        if(dist <= 2*RAD):
                            flag = 1
                            break
                    if(flag == 0):
                        graph[pos] = []
                elif event.button == 1 and mode == "connect":
                    pos = pygame.mouse.get_pos()
                    for node in graph:
                        if (distance(node[0], node[1], pos[0], pos[1]) <= RAD):
                            connections += 1
                            if(connections == 1):
                                conNode = node
                                break
                            elif(connections == 2):
                                if (node != conNode) and (not (node in graph[conNode])):
                                    graph[conNode].append(node)
                                    graph[node].append(conNode)
                                connections = 0
                                break

                elif event.button == 1 and mode == "disconnect":
                    pos = pygame.mouse.get_pos()
                    for node in graph:
                        if (distance(node[0], node[1], pos[0], pos[1]) <= RAD):
                            deletions += 1
                            if(deletions == 1):
                                delNode = node
                                print('delNode', delNode)
                                break
                            elif(deletions == 2):
                                print('node', node)
                                if delNode in graph[node]:
                                    graph[delNode].remove(node)
                                    graph[node].remove(delNode)
                                deletions = 0
                                break

                elif event.button == 1 and mode == "eliminate":
                    pos = pygame.mouse.get_pos()
                    for node in graph:
                        if (distance(node[0], node[1], pos[0], pos[1]) <= RAD):
                            for key in graph:
                                for temp in graph[key]:
                                    if temp == node:
                                        graph[key].remove(temp)
                            del graph[node]
                            break

                elif event.button == 1 and mode == "DFS":
                    pos = pygame.mouse.get_pos()
                    for node in graph:
                        if (distance(node[0], node[1], pos[0], pos[1]) <= RAD):
                            # clearing the visited list
                            for i in graph:
                                visited[i] = False
                            DFS(node)
                            print("DFS COMPLETED, Setting mode to view-only")
                            mode = "view-only"
                            break

                elif event.button == 1 and mode == "BFS":
                    pos = pygame.mouse.get_pos()
                    for node in graph:
                        if (distance(node[0], node[1], pos[0], pos[1]) <= RAD):
                            # clearing the visited list
                            for i in graph:
                                visited[i] = False
                            global queue
                            print(queue)
                            del queue[:]
                            queue.append(node)
                            BFS()
                            print("BFS COMPLETED, Setting mode to view-only")
                            mode = "view-only"
                            break

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glClearColor(0.607, 0.278, 0.3, 1)
        draw()
        pygame.display.flip()

main()


import eg

eg.RegisterPlugin(
    name = "System Tray Menu",
    description = (
        "Allows you to add custom menu entries to the tray menu of EventGhost."
    ),
    author = "Bitmonster",
    version = "1.0",
    guid = "{842BFFE8-DCB9-4C72-9877-AB2EF49794C5}",
)

class Text:
    labelHeader = "Label"
    eventHeader = "Event"
    editLabel = "Label:"
    editEvent = "Event:"
    addBox = "Append:"
    addItemButton = "Menu Item"
    addSeparatorButton = "Separator"
    deleteButton = "Delete"
    unnamedLabel = "New Menu Item %s"
    unnamedEvent = "Event%s"

import wx
import wx.gizmos
import types

class MenuItemData:
    pass

class MenuTreeListCtrl(wx.gizmos.TreeListCtrl):

    def __init__(self, parent, text, menuData, selectedItem=None):
        self.highestMenuId = 0
        wx.gizmos.TreeListCtrl.__init__(
            self,
            parent,
            style = wx.TR_FULL_ROW_HIGHLIGHT
                |wx.TR_DEFAULT_STYLE
                |wx.VSCROLL
                |wx.ALWAYS_SHOW_SB
                |wx.CLIP_CHILDREN
        )
        self.SetMinSize((10, 150))
        self.AddColumn(text.labelHeader)
        self.AddColumn(text.eventHeader)
        root = self.AddRoot(text.name)
        for data in menuData:
            name, kind, eventName, menuId = data
            if menuId > self.highestMenuId:
                self.highestMenuId = menuId
            eventName = data[2]
            item = self.AppendItem(root, name)
            self.SetItemText(item, eventName, 1)
            self.SetPyData(item, data)
            if menuId == selectedItem:
                self.SelectItem(item)

        self.SetColumnWidth(0, 200)
        self.ExpandAll(root)

        self.__inSizing = False
        self.GetMainWindow().Bind(wx.EVT_SIZE, self.OnSize)

    def GetNewMenuId(self):
        newMenuId = self.highestMenuId + 1
        self.highestMenuId = newMenuId
        return newMenuId

    def OnSize(self, event):
        event.Skip()
        if not self.__inSizing:
            self.__inSizing = True
            wx.CallAfter(self.OnSize2)

    def OnSize2(self):
        w, h = self.GetMainWindow().GetClientSize()
        newWidth = w - self.GetColumnWidth(0)
        if self.GetColumnWidth(1) != newWidth:
            self.SetColumnWidth(1, newWidth)
        self.__inSizing = False

    def GetPrevious(self, item):
        previous = self.GetPrevSibling(item)
        if previous.IsOk():
            return previous
        previous = self.GetItemParent(item)
        if not self.HasChildren(previous):
            return previous
        return self.GetLastChild(previous)[0]

    def GetNext(self, item):
        if self.HasChildren(item):
            return self.GetFirstChild()
        while 1:
            next = self.GetNextSibling(item)
            if next.IsOk():
                return next
            item = self.GetItemParent(item)
            if item == self.GetRootItem():
                return None

    def CopyItem(self, item, parent, prev=None):
        text = self.GetItemText(item)
        img = self.GetItemImage(item, wx.TreeItemIcon_Normal)
        selImg = self.GetItemImage(item, wx.TreeItemIcon_Selected)
        data = self.GetPyData(item)
        if prev is None:
            id = self.InsertItemBefore(parent, 0, text, img, selImg)
        else:
            id = self.InsertItem(parent, prev, text, img, selImg)
        self.SetPyData(id, data)
        self.SetItemText(id, self.GetItemText(item, 1), 1)
        return id

    def GetSelectedId(self):
        selectedId = self.GetSelection()
        data = self.GetPyData(selectedId)
        if data is not None:
            return data[3]

class SysTrayMenu(eg.PluginBase):
    text = Text

    def __init__(self):
        self.AddAction(Enable)
        self.AddAction(Disable)

    def Compile(self, menuData=[]):
        self.menuIdToData = {}
        # convert menuData to the new format
        newData = []
        i = 0
        for data in menuData:
            if len(data) < 4:
                name, kind, eventName  = data
                i += 1
                data = (name, kind, eventName, i)
            newData.append(data)
            self.menuIdToData[data[3]] = data
        self.menuData = newData
        return newData

    def __start__(self, dummy=None):
        self.wxIdToData = {}
        self.menuIdToWxItem = {}
        self.menuIdToData = {}
        if len(self.menuData) == 0:
            return
        menu =  eg.taskBarIcon.menu
        self.menuIdToWxItem[-1] = menu.PrependSeparator()
        for data in reversed(self.menuData):
            name, kind, eventName, menuId = data
            if kind == "item":
                wxId = wx.NewId()
                wxItem = menu.Prepend(wxId, name)
                wx.EVT_MENU(menu, wxId, self.OnMenuItem)
                self.wxIdToData[wxId] = data
            elif kind == "separator":
                wxItem = menu.PrependSeparator()
            self.menuIdToWxItem[menuId] = wxItem
            self.menuIdToData[menuId] = data

    def __stop__(self):
        for item in self.menuIdToWxItem.values():
            eg.taskBarIcon.menu.RemoveItem(item)
        self.menuIdToWxItem.clear()
        self.wxIdToData.clear()

    @eg.LogIt
    def OnMenuItem(self, event):
        data = self.wxIdToData[event.GetId()]
        self.TriggerEvent(data[2])

    def Configure(self, menuData=[]):
        menuData = self.Compile(menuData)
        panel = eg.ConfigPanel(resizable=True)
        text = self.text

        tree = MenuTreeListCtrl(panel, text, menuData)
        root = tree.GetRootItem()

        @eg.LogIt
        def OnSelectionChanged(dummyEvent):
            itemType = 0
            item = tree.GetSelection()
            if item == root:
                enableMoveFlag = False
                enableEditFlag = False
            elif tree.GetPyData(item)[1] == "separator":
                enableMoveFlag = True
                enableEditFlag = False
                itemType = 2
            else:
                enableMoveFlag = True
                enableEditFlag = True
            upButton.Enable(enableMoveFlag)
            downButton.Enable(enableMoveFlag)
            deleteButton.Enable(enableMoveFlag)
            labelBox.Enable(enableEditFlag)
            eventBox.Enable(enableEditFlag)
            labelBox.SetLabel(tree.GetItemText(item, 0))
            eventBox.SetLabel(tree.GetItemText(item, 1))
            #itemTypeCtrl.SetSelection(itemType)
            #event.Skip()
        tree.Bind(wx.EVT_TREE_SEL_CHANGED, OnSelectionChanged)

        # Delete button
        deleteButton = wx.Button(panel, -1, text.deleteButton)
        deleteButton.Enable(False)
        def OnDelete(dummyEvent):
            item = tree.GetSelection()
            next = tree.GetNextSibling(item)
            if not next.IsOk():
                next = tree.GetPrevSibling(item)
                if not next.IsOk():
                    next = tree.GetItemParent(item)
            tree.SelectItem(next)
            tree.Delete(item)
            tree.EnsureVisible(next)
        deleteButton.Bind(wx.EVT_BUTTON, OnDelete)

        # Up button
        bmp = wx.ArtProvider.GetBitmap(wx.ART_GO_UP, wx.ART_OTHER, (16, 16))
        upButton = wx.BitmapButton(panel, -1, bmp)
        upButton.Enable(False)
        def OnUp(dummyEvent):
            item = tree.GetSelection()
            previous = tree.GetPrevSibling(item)
            if previous.IsOk():
                id = tree.GetPrevSibling(previous)
                if not id.IsOk():
                    id = None
                newId = tree.CopyItem(item, tree.GetItemParent(previous), id)
                tree.SelectItem(newId)
                tree.EnsureVisible(newId)
                tree.Delete(item)
        upButton.Bind(wx.EVT_BUTTON, OnUp)

        # Down button
        bmp = wx.ArtProvider.GetBitmap(wx.ART_GO_DOWN, wx.ART_OTHER, (16, 16))
        downButton = wx.BitmapButton(panel, -1, bmp)
        downButton.Enable(False)
        def OnDown(dummyEvent):
            item = tree.GetSelection()
            nextId = tree.GetNext(item)
            if nextId is not None:
                newId = tree.CopyItem(item, tree.GetItemParent(nextId), nextId)
                tree.Delete(item)
                tree.SelectItem(newId)
                tree.EnsureVisible(newId)
        downButton.Bind(wx.EVT_BUTTON, OnDown)

        # Add menu item button
        addItemButton = wx.Button(panel, -1, text.addItemButton)
        @eg.LogIt
        def OnAddItem(dummyEvent):
            numStr = str(tree.GetCount() + 1)
            item = tree.AppendItem(root, text.unnamedLabel % numStr)
            data = ("", "item", "", tree.GetNewMenuId())
            tree.SetPyData(item, data)
            tree.SetItemText(item, text.unnamedEvent % numStr, 1)
            tree.Expand(tree.GetItemParent(item))
            tree.SelectItem(item)
            tree.EnsureVisible(item)
            tree.Update()
        addItemButton.Bind(wx.EVT_BUTTON, OnAddItem)

        # Add separator button
        addSeparatorButton = wx.Button(panel, -1, text.addSeparatorButton)
        def OnAddSeparator(dummyEvent):
            item = tree.AppendItem(root, "---------")
            tree.SetPyData(item, ("", "separator", "", tree.GetNewMenuId()))
            tree.Expand(tree.GetItemParent(item))
            tree.SelectItem(item)
            tree.EnsureVisible(item)
            tree.Update()
        addSeparatorButton.Bind(wx.EVT_BUTTON, OnAddSeparator)

        # Label edit box
        labelBox = wx.TextCtrl(panel, -1)
        def OnLabelTextChange(event):
            item = tree.GetSelection()
            tree.SetItemText(item, labelBox.GetValue(), 0)
            event.Skip()
        labelBox.Bind(wx.EVT_TEXT, OnLabelTextChange)

        # Event edit box
        eventBox = wx.TextCtrl(panel, -1)
        def OnEventTextChange(event):
            item = tree.GetSelection()
            tree.SetItemText(item, eventBox.GetValue(), 1)
            event.Skip()
        eventBox.Bind(wx.EVT_TEXT, OnEventTextChange)

        # Item type control
        #choices = ["Menu item", "Check menu item", "Separator"]
        #itemTypeCtrl = wx.Choice(dialog, choices=choices)

        # construction of the dialog with sizers
        staticBox = wx.StaticBox(panel, -1, text.addBox)
        addSizer = wx.StaticBoxSizer(staticBox, wx.VERTICAL)
        addSizer.Add(addItemButton, 0, wx.EXPAND)
        addSizer.Add((5, 5))
        addSizer.Add(addSeparatorButton, 0, wx.EXPAND)

        editSizer = wx.FlexGridSizer(2, 2, 5, 5)
        editSizer.AddGrowableCol(1)
        editSizer.AddMany((
            (panel.StaticText(text.editLabel), 0, wx.ALIGN_CENTER_VERTICAL),
            (labelBox, 0, wx.EXPAND),
            (panel.StaticText(text.editEvent), 0, wx.ALIGN_CENTER_VERTICAL),
            (eventBox, 0, wx.EXPAND),
        ))

        mainSizer = eg.HBoxSizer(
            (
                eg.VBoxSizer(
                    (tree, 1, wx.EXPAND),
                    (editSizer, 0, wx.EXPAND|wx.TOP, 5),
                ), 1, wx.EXPAND
            ),
            ((5, 5)),
            (
                eg.VBoxSizer(
                    (deleteButton, 0, wx.EXPAND),
                    ((5, 5), 1, wx.EXPAND),
                    (upButton),
                    (downButton, 0, wx.TOP, 5),
                    ((5, 5), 1, wx.EXPAND),
                    (addSizer, 0, wx.EXPAND),
                ), 0, wx.EXPAND
            ),
        )
        panel.sizer.Add(mainSizer, 1, wx.EXPAND)

        nextId = tree.GetFirstChild(root)[0]
        if nextId.IsOk():
            tree.SelectItem(nextId)
        else:
            tree.SelectItem(root)

        while panel.Affirmed():
            resultList = []
            def Traverse(item):
                child, cookie = tree.GetFirstChild(item)
                while child.IsOk():
                    name, kind, eventString, menuId = tree.GetPyData(child)
                    name = tree.GetItemText(child, 0)
                    eventString = tree.GetItemText(child, 1)
                    resultList.append((name, kind, eventString, menuId))
                    if tree.HasChildren(child):
                        Traverse(child)
                    child, cookie = tree.GetNextChild(item, cookie)
            Traverse(root)
            self.Compile(resultList)
            panel.SetResult(resultList)

class Enable(eg.ActionBase):

    class text:
        name = "Enable Item"
        description = "Enables a menu item."

    def __call__(self, menuId):
        item = self.plugin.menuIdToWxItem.get(menuId, None)
        if item is not None:
            item.Enable(True)

    def GetLabel(self, menuId):
        return self.name + ": " + self.plugin.menuIdToData[menuId][0]

    def Configure(self, menuId=None):
        plugin = self.plugin
        panel = eg.ConfigPanel()
        tree = MenuTreeListCtrl(panel, plugin.text, plugin.menuData, menuId)
        panel.sizer.Add(tree, 1, wx.EXPAND)
        while panel.Affirmed():
            panel.SetResult(tree.GetSelectedId())

class Disable(Enable):

    class text:
        name = "Disable Item"
        description = "Disables a menu item."

    def __call__(self, menuId):
        item = self.plugin.menuIdToWxItem.get(menuId, None)
        if item is not None:
            item.Enable(False)


#
# Test Functions

from opencog.atomspace import types, Atom, TruthValue
from opencog.type_constructors import *

def print_arguments(argOne, argTwo):
    print ("argOne = ", argOne)
    print ("argTwo = ", argTwo)
    atom = ATOMSPACE.add_link(types.ListLink, [argOne, argTwo])
    print ("atom = ", atom)
    return atom

def add_link(atom_one, atom_two):
    link_atom = ATOMSPACE.add_link(types.ListLink, [atom_one, atom_two])
    return link_atom

def bogus_tv(atom_one, atom_two):
    return TruthValue(0.6, 0.234)

green = 0
red = 0

def initialize_counts():
    global red
    global green
    green = 0
    red = 0

def increment_green():
    global green
    green += 1

def increment_red():
    global red
    red += 1

def green_count():
    global green
    return green

def red_count():
    global red
    return red

def stop_go(atom):
    compare_green = ConceptNode("green light")
    compare_red = ConceptNode("red light")
    if atom == compare_green:
        print ("got a green light!")
        increment_green()
        return TruthValue(1,1)
    elif atom == compare_red:
        print ("got a red light")
        increment_red()
        return TruthValue(0,1)
    else:
        print ("got no match :-(")
        assert(false)

    return TruthValue(0,0)


import loadData
import personaModel

import argparse
from nltk.translate import bleu_score
import chainer
from chainer import training
from chainer.training import extensions
import numpy as np
from chainer.backends import cuda
import chainer.functions as F
import random

UNK = 0
EOS = 1
PAD = -1

def main():
    parser = argparse.ArgumentParser(description='Chainer persona test')
    parser.add_argument('VOCAB', help='vocabulary file')
    parser.add_argument('PERSONA_VOCAB', help='persona vocabulary file')
    parser.add_argument('--batch', '-b', type=int, default=64,
                        help='number of sentence pairs in each mini-batch')
    parser.add_argument('--gpu', '-g', type=int, default=-1,
                        help='GPU ID (negative value indicates CPU)')
    parser.add_argument('--unit', '-u', type=int, default=300,
                        help='number of units')#defalt=1024
    parser.add_argument('--layer', '-l', type=int, default=3,
                        help='number of layers')
    parser.add_argument('--min-source-sentence', type=int, default=1,
                        help='minimium length of source sentence')
    parser.add_argument('--max-source-sentence', type=int, default=50,
                        help='maximum length of source sentence')
    parser.add_argument('--min-target-sentence', type=int, default=1,
                        help='minimium length of target sentence')
    parser.add_argument('--max-target-sentence', type=int, default=50,
                        help='maximum length of target sentence')
    parser.add_argument('--out', '-o', default='result',
                        help='directory to output the result')
    parser.add_argument('--use', '-use', default='null',
                        help='use made model file path')
    args = parser.parse_args()

    vocabulary = loadData.word_ids(args.VOCAB)
    peVocabulary = loadData.word_ids(args.PERSONA_VOCAB)
    model = personaModel.Model(vocabulary, peVocabulary, args.unit, args.batch, args.gpu)
    chainer.serializers.load_npz(args.out+"/"+args.use)
    if args.gpu >= 0:
        chainer.backends.cuda.get_device(args.gpu).use()
        model.to_gpu(args.gpu)
        xp = cuda.cupy
    else:
        xp = np

    print("input persona")
    persona = input()
    persona = model.personaEmbed(persona)

    while(True):
        print("input sentence")
        inputSentence = input()
        words = inputSentence.strip.split()
        idsArray = xp.asarray([vocabulary.get(w, UNK) for w in words], dtype=xp.int32)
        idsArray = F.concat((idsArray, EOS), axis=1)
        result = model.predict(idsArray, persona)
        result = ' '.join([vocabulary.get(w, UNK) for w in result[0]])
        print("output")
        print(result)


"""
.. module:: Settings
   :synopsis: System settings for SecML

.. moduleauthor:: Marco Melis <marco.melis@unica.it>

"""
import os
import sys
import shutil
from configparser import ConfigParser, NoSectionError, NoOptionError

# Logger for this module only. Use `secml.utils.CLog` elsewhere
import logging
_logger = logging.getLogger(__name__)
_logger.setLevel(logging.INFO)
_logger_handle = logging.StreamHandler(sys.stdout)
_logger_handle.setFormatter(logging.Formatter(
    "%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
_logger.addHandler(_logger_handle)

__all__ = ['SECML_HOME_DIR', 'SECML_CONFIG',
           'SECML_DS_DIR', 'SECML_MODELS_DIR', 'SECML_EXP_DIR',
           'SECML_STORE_LOGS', 'SECML_LOGS_DIR',
           'SECML_LOGS_FILENAME', 'SECML_LOGS_PATH',
           'SECML_PYTORCH_DIR', 'SECML_PYTORCH_USE_CUDA',
           'parse_config']

def parse_config(conf_files, section, parameter, default=None, dtype=None):
    """Parse input `parameter` under `section` from configuration files.

    Parameters file must have the following structure:

    .. code-block::

       [section1]
       param1=xxx
       param2=xxx

       [section2]
       param1=xxx
       param2=xxx

    Parameters
    ----------
    conf_files : list
        List with the paths of the configuration files to parse.
    section : str
        Section under which look for specified parameter.
    parameter : str
        Name of the parameter. This is not case-sensitive.
    default : any, optional
        Set default value of parameter.
        If None (default), parameter is considered required and
        so must be defined in the input configuration file.
        If not None, the value will be used if configuration file
        does not exists, section is not defined, or the parameter
        is not defined under section.
    dtype : type or None, optional
        Expected dtype of the parameter.
        If None (default), parameter will be parsed as a string.
        Other accepted values are: float, int, bool, str.

    """
    # Parsing parameters
    _config = ConfigParser()

    # Parse configuration files (even if not exists)
    # The first item of the list has LOWER priority (so we reverse)
    _config.read(reversed(conf_files))

    # Try to parse the parameter from section
    try:
        # Call the get function appropriate to specified dtype
        if dtype is None or dtype == str:
            param = _config.get(section, parameter)
        elif dtype == int:
            param = _config.getint(section, parameter)
        elif dtype == float:
            param = _config.getfloat(section, parameter)
        elif dtype == bool:
            param = _config.getboolean(section, parameter)
        else:
            raise TypeError(
                "accepted dtypes are int, float, bool, str (or None)")
    except NoSectionError:
        if default is not None:
            # Use default if config file does not exists
            # or does not have the desired section
            return default
        raise RuntimeError(
            "no section `[{:}]` found in configuration files.".format(section))
    except NoOptionError:
        if default is not None:
            # Use default if desired parameter is not specified under section
            return default
        raise RuntimeError(
            "parameter `{:}` not found under section `[{:}]` in "
            "configuration files.".format(parameter, section))

    return param

def _parse_env(name, default=None, dtype=None):
    """Parse input variable from `os.environ`.

    Parameters
    ----------
    name : str
        Name of the variable to parse from env.
    default : any, optional
        Set default value of variable.
        If None (default), parameter is considered required and
        so must be defined in environment.
        Otherwise, RuntimeError will be raised.
    dtype : type or None, optional
        Expected dtype of the variable.
        If None (default), variable will be parsed as a string.
        Other accepted values are: float, int, bool, str.

    """
    try:
        val = os.environ[name]
    except KeyError:
        if default is not None:
            # Let's use the default value if var not in env
            return default
        raise RuntimeError("variable {:} not specified".format(name))

    # Parse var from env using the specified dtype
    if dtype is None or dtype == str:
        return str(val)
    if dtype == int or dtype == float or dtype == bool:
        return dtype(val)
    else:
        raise TypeError(
            "accepted dtypes are int, float, bool, str (or None)")

def _parse_env_config(name, conf_files, section, parameter,
                      default=None, dtype=None):
    """Parse input variable from `os.environ` or configuration files.

    If input variable `name` is not found in `os.environ`,
    the corresponding parameter is parsed from configuration files.
    If not found, default variable value will be returned.
    If no default value has been defined, RuntimeError will be raised.

    Parameters
    ----------
    name : str
        Name of the variable to parse from env.

    For description of other input parameters see `.parse_config`.

    """
    try:  # Firstly let's try to get variable from environment
        # Don't pass default to _parse_env as we want
        # to catch KeyError and RuntimeError
        return _parse_env(name, default=None, dtype=dtype)
    except (KeyError, RuntimeError):
        # Probably the variable is not in env, try read config
        return parse_config(conf_files, section, parameter, default, dtype)

SECML_HOME_DIR = _parse_env(
    'SECML_HOME_DIR',
    default=os.path.join(os.path.expanduser('~'), 'secml-data'))
"""Main directory for storing datasets, experiments, temporary files.

This is set by default to:
    * Unix -> ``${HOME}/secml-data``
    * Windows -> ``(${HOME}, ${USERPROFILE}, ${HOMEPATH}, ${HOMEDRIVE})/secml-data``

"""
if not os.path.isdir(SECML_HOME_DIR):
    os.makedirs(os.path.abspath(SECML_HOME_DIR))
    _logger.info('New `SECML_HOME_DIR` created: {:}'.format(SECML_HOME_DIR))

SECML_CONFIG_FNAME = 'secml.conf'
"""Name of the configuration file (default `secml.conf`)."""
if not os.path.isfile(os.path.join(SECML_HOME_DIR, SECML_CONFIG_FNAME)):
    def_config = os.path.normpath(os.path.join(os.path.dirname(
        os.path.abspath(__file__)), SECML_CONFIG_FNAME))
    home_config = os.path.join(SECML_HOME_DIR, SECML_CONFIG_FNAME)
    # Copy the default config file to SECML_HOME_DIR if not already available
    shutil.copy(def_config, home_config)
    _logger.info(
        'Default configuration file copied to: {:}'.format(home_config))

def _config_fpath():
    """Returns the path of the active configuration file(s).

    The list of active configuration files is sorted from the highest
    to the lowest priority, as follows:
     - `${PWD}/secml.conf`
     - `{SECML_CONFIG}` if it is not a directory
     - `{SECML_CONFIG}/secml.conf`
     - `{SECML_HOME_DIR}/secml.conf`
        - On Unix, `${HOME}/secml-data/secml.conf`
        - On Windows, `(${HOME}, ${USERPROFILE}, ${HOMEPATH}, ${HOMEDRIVE})/secml-data/secml.conf`
     - Lastly, it looks in `INSTALL/secml/secml.conf` for a
       system-defined copy.
       INSTALL should be `/usr/lib/python3.5/site-packages` on Linux,
       and `C:\\Python35\\Lib\\site-packages` on Windows.

    Returns
    -------
    list
        The list of active configuration files is sorted from the highest
        to the lowest priority.

    """
    def gen_candidates():
        yield os.path.join(os.getcwd(), SECML_CONFIG_FNAME)
        try:
            secml_config = os.environ['$SECML_CONFIG']
        except KeyError:
            pass
        else:
            yield secml_config
            yield os.path.join(secml_config, 'SECML_CONFIG_FNAME')
        yield os.path.join(SECML_HOME_DIR, SECML_CONFIG_FNAME)
        yield os.path.normpath(os.path.join(os.path.dirname(
            os.path.abspath(__file__)), SECML_CONFIG_FNAME))

    candidates = []
    for fname in gen_candidates():
        if os.path.isfile(fname):
            candidates.append(fname)

    return candidates

SECML_CONFIG = _config_fpath()
"""Active `secml.conf` configuration files."""

# ------- #
# [SECML] #
# ------- #

SECML_DS_DIR = _parse_env_config(
    'SECML_DS_DIR', SECML_CONFIG, 'secml', 'ds_dir',
    dtype=str, default=os.path.join(SECML_HOME_DIR, 'datasets')
)
"""Main directory for storing datasets.

This is set by default to: ``{SECML_HOME_DIR}/datasets``

"""
if not os.path.isdir(SECML_DS_DIR):
    os.makedirs(os.path.abspath(SECML_DS_DIR))
    _logger.info('New `SECML_DS_DIR` created: {:}'.format(SECML_DS_DIR))

SECML_MODELS_DIR = _parse_env_config(
    'SECML_MODELS_DIR', SECML_CONFIG, 'secml', 'models_dir',
    dtype=str, default=os.path.join(SECML_HOME_DIR, 'models')
)
"""Main directory where pre-trained models are stored.

This is set by default to: ``{SECML_HOME_DIR}/models``

"""
if not os.path.isdir(SECML_MODELS_DIR):
    os.makedirs(os.path.abspath(SECML_MODELS_DIR))
    _logger.info('New `SECML_MODELS_DIR` created: {:}'.format(SECML_MODELS_DIR))

SECML_EXP_DIR = _parse_env_config(
    'SECML_EXP_DIR', SECML_CONFIG, 'secml', 'exp_dir',
    dtype=str, default=os.path.join(SECML_HOME_DIR, 'experiments')
)
"""Main directory of experiments data.

This is set by default to: ``{SECML_HOME_DIR}/experiments``

"""
if not os.path.isdir(SECML_EXP_DIR):
    os.makedirs(os.path.abspath(SECML_EXP_DIR))
    _logger.info('New `SECML_EXP_DIR` created: {:}'.format(SECML_EXP_DIR))

# ------------ #
# [SECML:LOGS] #
# ------------ #

SECML_STORE_LOGS = _parse_env_config(
    'SECML_STORE_LOGS', SECML_CONFIG, 'secml:logs', 'store_logs',
    dtype=bool, default=False
)
"""Whether to store logs to file. Default False."""

SECML_LOGS_DIR = _parse_env_config(
    'SECML_LOGS_DIR', SECML_CONFIG, 'secml:logs', 'logs_dir',
    dtype=str, default=os.path.join(SECML_HOME_DIR, 'logs')
)
"""Directory where logs will be stored.

This is set by default to: ``{SECML_HOME_DIR}/logs``

"""
if not os.path.isdir(SECML_LOGS_DIR):
    os.makedirs(os.path.abspath(SECML_LOGS_DIR))
    _logger.info('New `SECML_LOGS_DIR` created: {:}'.format(SECML_LOGS_DIR))

SECML_LOGS_FILENAME = _parse_env_config(
    'SECML_LOGS_FILENAME', SECML_CONFIG, 'secml:logs', 'logs_filename',
    dtype=str, default='logs.log'
)
"""Name of the logs file on disk. Default: `logs.log`."""

SECML_LOGS_PATH = os.path.join(SECML_LOGS_DIR, SECML_LOGS_FILENAME)
"""Full path to the logs file: ``{SECML_LOGS_DIR}/{SECML_LOGS_FILENAME}``."""

# --------------- #
# [SECML:PYTORCH] #
# --------------- #

SECML_PYTORCH_USE_CUDA = _parse_env_config(
    'SECML_PYTORCH_USE_CUDA', SECML_CONFIG, 'secml:pytorch', 'use_cuda',
    dtype=bool, default=True
)
"""Controls if CUDA should be used by the PyTorch wrapper when available."""

SECML_PYTORCH_DIR =_parse_env(
    'SECML_PYTORCH_DIR',
    default=os.path.join(os.path.expanduser('~'), 'secml-data/pytorch-data'))
if not os.path.isdir(SECML_PYTORCH_DIR):
    os.makedirs(os.path.abspath(SECML_PYTORCH_DIR))
    _logger.info('New `SECML_PYTORCH_DIR` created: {:}'.format(SECML_PYTORCH_DIR))
"""Directory for storing PyTorch data.

This is set by default to: `{SECML_HOME_DIR}`/pytorch-data`

"""


#!/usr/bin/env python3
import yaml
import sys

def main():
    data = yaml.safe_load(open(sys.argv[1]))
    output = yaml.dump(data["spec"]["values"])
    print(output)

if __name__ == "__main__":
    try:
        main()
    except IndexError:
        print(f"Usage: {sys.argv[0]} <helmrelease.yaml>")
    except OSError:
        print(f"Error: {sys.argv[1]} not found")


import re
import statistics
import matplotlib.pyplot as plt

# CONSTANTS
FILENAME = "C:\\Users\\smith\\Downloads\\BundleLogs-1619384191142\\var\\log\\web.stdout.log"
START_ASSEMBLY = "Inside Controller.java, attempting to assemble file"
FILE_LENGTH = "Assembling file of length"
CUSTOM_REGEX = "Loaded \d custom instructions"

# FUNTIONS
def countAssembles():
    file = open(FILENAME, "r")
    data = file.read()
    occurrences = data.count(START_ASSEMBLY)
    print('Total Assembles :', occurrences)

def printLineSummary(lineCounts):
    """Using log with assembly file line and count, compute metrics"""
    totalLines = sum(lineCounts)
    totalFiles = len(lineCounts)
    mean = totalLines / totalFiles
    median = statistics.median(lineCounts)
    print(f"Total Lines: {totalLines}\tTotal Files: {totalFiles}\tMean Lines: {round(mean, 2)}\tMedian Lines: {median}")

    fig = plt.figure(figsize =(10, 7))
    # Creating plot
    plt.boxplot(lineCounts)
    # show plot
    plt.show()

def printCustomSummary(customCounts):
    """Using log with assembly file line and count, compute metrics"""
    totalCustom = sum(customCounts)
    totalFiles = len(customCounts)
    mean = totalCustom / totalFiles
    median = statistics.median(customCounts)
    print(f"Total Custom: {totalCustom}\tTotal Files: {totalFiles}\tAverage Custom: {round(mean, 2)}\tMedian Custom: {median}")

def countFileLength():
    file = open(FILENAME, "r")
    lines = file.readlines()
    lineCounts =[]
    for line in lines:
        if FILE_LENGTH in line:
            substring = line[line.index(FILE_LENGTH):]
            words = substring.split()
            countString = words[len(words)-1]
            countInt = int(countString)
            lineCounts.append(countInt)

    # end for
    printLineSummary(lineCounts)

def countCustomInstructions():
    file = open(FILENAME, "r")
    lines = file.readlines()
    customCounts =[]
    for line in lines:
        if bool(re.search(CUSTOM_REGEX, line)):
            substring = line[line.index("Loaded"):]
            words = substring.split()
            countString = words[1]
            countInt = int(countString)
            customCounts.append(countInt)

    # end for
    printCustomSummary(customCounts)

countAssembles()
countFileLength()
countCustomInstructions()


# -*- coding: utf-8 -*-
__author__ = 'Bohdan Mushkevych'

import unittest

from odm import document, fields
from odm.errors import ValidationError

DEFAULT_VALUE = 'default value'

class TestDocument(unittest.TestCase):
    def test_field_autonaming(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(null=False)

        value = 'abcdefghijklmnopqrstuvwxyz'
        model = FieldContainer()
        model.field_string = value

        self.assertEqual(FieldContainer.field_string.name, 'field_string')
        self.assertIn('field_string', model.to_json())
        self.assertEqual(model.to_json()['field_string'], value)
        self.assertEqual(model.field_string, value)

    def test_valid_inputs(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', null=False)

        fixtures = {
            '1': '1',
            1: '1',
            150.001: '150.001',
            u'а ти диню нині їв, га?': u'а ти диню нині їв, га?',
            u'абвгдеєжзиіїйклмнопрстуфхцчшщюяь': u'абвгдеєжзиіїйклмнопрстуфхцчшщюяь',
            u'ウィキペディアにようこそ': u'ウィキペディアにようこそ',
            'abcdefghijklmnopqrstuvwxyz': 'abcdefghijklmnopqrstuvwxyz',
            'Jan 06, 2010': 'Jan 06, 2010',
        }

        model = FieldContainer()
        for key, value in fixtures.items():
            model.field_string = key
            self.assertEqual(model.field_string, value)

    def test_constraints(self):
        min_length = 5
        max_length = 10

        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', min_length=min_length, max_length=max_length)

        valid_min = 'a' * min_length
        valid_middle = 'b' * int((min_length + max_length) / 2)
        valid_max = 'c' * max_length
        invalid_min = 'i' * (min_length - 1)
        invalid_max = 'm' * (max_length + 1)

        model = FieldContainer()
        for value in [valid_min, valid_middle, valid_max]:
            model.field_string = value
            self.assertEqual(model.field_string, value)

        for value in [invalid_min, invalid_max]:
            try:
                model.field_string = value
                self.assertTrue(False, 'ValidationError should have been thrown')
            except ValidationError:
                self.assertTrue(True, 'ValidationError was expected and caught')

    def test_choices(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', choices=['111aaa', '222bbb', '333ccc'])

        model = FieldContainer()
        model.field_string = '111aaa'
        self.assertEqual(model.field_string, '111aaa')

        try:
            model.field_string = 'tra'
            self.assertTrue(False, 'ValidationError should have been thrown')
        except ValidationError:
            self.assertTrue(True, 'ValidationError was expected and caught')

    def test_nullable_non_default(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', null=True)

        model = FieldContainer()

        try:
            model.validate()
            self.assertTrue(True, 'Validation should succeed')
        except ValidationError:
            self.assertTrue(False, 'ValidationError should not have been thrown')

        model.field_string = None
        self.assertTrue(True, 'Validation should succeed')

    def test_non_nullable_non_default(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', null=False)

        model = FieldContainer()
        try:
            model.validate()
            self.assertTrue(False, 'Validation should have failed')
        except ValidationError:
            self.assertTrue(True, 'ValidationError should not have been thrown')

        model.field_string = 'first-level string field'
        self.assertEqual(model.field_string, 'first-level string field')

        try:
            model.field_string = None
            self.assertTrue(False, 'ValidationError should have been thrown')
        except ValidationError:
            self.assertTrue(True, 'ValidationError was expected and caught')

    def test_non_nullable_default(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', null=False, default=DEFAULT_VALUE)
            field_string_empty = fields.StringField(name='empty', null=False, default='')

        model = FieldContainer()
        self.assertEqual(model.field_string, DEFAULT_VALUE)
        self.assertEqual(model.field_string_empty, '')

    def test_nullable_default(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', null=True, default=DEFAULT_VALUE)

        model = FieldContainer()
        self.assertIsNone(model.field_string)

        model.field_string = None
        self.assertIsNone(model.field_string)

    def test_nullable_non_default_jsonification(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', null=True)

        model = FieldContainer()
        json_data = model.to_json()
        self.assertIsInstance(json_data, dict)
        m2 = FieldContainer.from_json(json_data)

        self.assertIsNone(m2.field_string)

    def test_non_nullable_non_default_jsonification(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', null=False)

        model = FieldContainer()
        json_data = model.to_json()
        self.assertIsInstance(json_data, dict)
        m2 = FieldContainer.from_json(json_data)

        self.assertIsNone(m2.field_string)

    def test_non_nullable_default_jsonification(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', null=False, default=DEFAULT_VALUE)

        model = FieldContainer()
        json_data = model.to_json()
        self.assertIsInstance(json_data, dict)
        m2 = FieldContainer.from_json(json_data)

        self.assertEqual(m2.field_string, DEFAULT_VALUE)

    def test_nullable_default_jsonification(self):
        class FieldContainer(document.BaseDocument):
            field_string = fields.StringField(name='s', null=True, default=DEFAULT_VALUE)

        model = FieldContainer()
        json_data = model.to_json()
        self.assertIsInstance(json_data, dict)
        m2 = FieldContainer.from_json(json_data)

        self.assertIsNone(m2.field_string)

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


import cv2
import numpy as np
import matplotlib.pyplot as plt
import SaliencyRC
import segmentImage
def processImage(filename):
    img3i = cv2.imread(filename)
    img3f = img3i.astype(np.float32)
    img3f *= 1. / 255
    sal = SaliencyRC.GetHC(img3f)
    #idxs = np.where(sal < (sal.max() + sal.min()) / 4.96)
    #img3i[np.where(sal < (sal.max() + sal.min())/4)] = 0
    idxs = np.where(sal >= (sal.max() + sal.min()) / 2)
    I = [np.min(idxs[0]),np.max(idxs[0])]
    J = [np.min(idxs[1]),np.max(idxs[1])]
    imgBBox = img3i.copy()
    imgBBox[I[0]:I[0]+1,J[0]:J[1]+1] = [0,0,255]
    imgBBox[I[0]:I[1]+1,J[1]:J[1]+1] = [0,0,255]
    imgBBox[I[1]:I[1]+1,J[0]:J[1]+1] = [0,0,255]
    imgBBox[I[0]:I[1]+1,J[0]:J[0]+1] = [0,0,255]
    resImg = np.zeros(img3i.shape,img3i.dtype)
    resImg[I[0]:I[1],J[0]:J[1]] = img3i[I[0]:I[1],J[0]:J[1]]
    resImg[np.where(sal < (sal.max() + sal.min())/ 4)] = 0
    sal *= 255
    cv2.imwrite("{}process.jpg".format(filename),resImg)
    cv2.imwrite("{}bbox.jpg".format(filename),imgBBox)
    cv2.imwrite("{}hc.jpg".format(filename),sal.astype(np.int16))

def processImage1(filename):
    img3i = cv2.imread(filename)
    img3f = img3i.astype(np.float32)
    img3f *= 1. /255
    regNum, regIdx1i = segmentImage.SegmentImage(img3f, None, 0.5,200,50)
    bdgReg1u = SaliencyRC.GetBorderReg(regIdx1i,regNum,0.02,0.4)
    bdgIdxs = np.where(bdgReg1u == 255)
    img3i[bdgIdxs] = 0
    cv2.imwrite("{}process.jpg".format(filename),img3i)


import os
import numpy
from scipy import signal
#suppress dll loading messages
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import tensorflow as tf
import requests
from io import BytesIO
from PIL import Image
import matplotlib
import matplotlib.pyplot as plt

"""
Understanding Convolution Neural Networks
"""

"""
Part1.a: 1d operation with Python
"""
print('Part 1\n')
#Let h represent an image and x the kernel
h = [2, 1, 0]
x = [3, 4, 5]

y = numpy.convolve(x, h)
#verify y[n] = sum_(k -> -inf to inf) (x[k] * h[n - k]) [discrete convolution]
conv_h = str()
for i in range(len(h)+len(x)-1): conv_h += y[i].__str__() + " "
print("1d convolution of image h = [2, 1, 0] and kernel x = [3, 4, 5]:\n{0}\n".format(conv_h))

"""
Part1.b: Convolution with 'full' padding
"""

#Let h represent an image and x the kernel
x = [6, 2]
h = [1, 2, 5, 4]

y = numpy.convolve(x, h, 'full')

#The convolution includes zero padding around the image 0 [1, 2, 5, 4] 0
conv_h = str()
for i in range(len(h)+len(x)-1): conv_h += y[i].__str__() + " "
print("Convolution of image h = [1, 2, 5, 4] and kernel x = [6, 2] with 'full' padding:\n{0}\n".format(conv_h))

"""
Part1.c: Convolution with 'same' padding
"""

#Let h represent an image and x the kernel
x = [6, 2]
h = [1, 2, 5, 4]

y = numpy.convolve(x, h, 'same')

#Convolution is identical to 'full' with the exception that it returns
# a result that is of dimension max(x,h)
conv_h = str()
for i in range(max(len(x),len(h))): conv_h += y[i].__str__() + " "
print("Convolution of image h = [1, 2, 5, 4] and kernel x = [6, 2] with 'same' padding:\n{0}\n".format(conv_h))

"""
Part1.d: Convolution with 'valid' padding
"""

#Let h represent an image and x the kernel
x = [6, 2]
h = [1, 2, 5, 4]

y = numpy.convolve(x, h, 'valid')

#Convolution does not include zero padding and reduces the dimensions of output
conv_h = str()
for i in range(max(len(x),len(h))-min(len(x),len(y))+1): conv_h += y[i].__str__() + " "
print("Convolution of image h = [1, 2, 5, 4] and kernel x = [6, 2] with 'valid' padding:\n{0}\n".format(conv_h))

"""
Part2: Convolution 2d operation with Python/Numpy
"""
print('\n\nPart 2\n')
#2d Convolution defined as I'=sum_u,v( I(x-u, y-v)g(u,v) )

I = [[255, 7, 3],
     [212, 240, 4],
     [218, 216, 230]]

g = [[-1,1]]

#Convolution of image I and kernel g
print('Convolution of image {0} with kernel {1} without zero padding:'.format(I, g))
print('{0}\n'.format(signal.convolve(I, g, 'valid')))

print('Convolution of image {0} with kernel {1} with zero padding:'.format(I, g))
print('{0}\n'.format(signal.convolve(I, g)))

#increasing the dimension of the kernel g
g = [[-1, 1],
     [2, 3]]

#Convolution using the newly defined kernel
print('Convolution of image {0} with kernel {1} without zero padding:'.format(I, g))
print('{0}\n'.format(signal.convolve(I, g, 'valid')))

print('Convolution of image {0} with kernel {1} with zero padding:'.format(I, g))
print('{0}\n'.format(signal.convolve(I, g)))

print('Convolution of image {0} with kernel {1}with same zero padding:'.format(I, g))
print('{0}\n'.format(signal.convolve(I, g, 'same')))

"""
Part3: Convolution of images with TensorFlow
"""

print('\n\nPart3\n')

#let filter be a 4d tensor: [width, height, channels, number of filters]
#let input represent and image 4d tensor: [batch size, height, width, number of channels]
lab4_part3 = tf.compat.v1.Graph()
with lab4_part3.as_default():

    filter = tf.Variable(tf.compat.v1.random_normal([3,3,1,1]))
    input = tf.Variable(tf.compat.v1.random_normal([1,10,10,1]))

    op = tf.compat.v1.nn.conv2d(input, filter, strides=[1,1,1,1], padding='VALID')
    op2 = tf.compat.v1.nn.conv2d(input, filter, strides=[1,1,1,1], padding='SAME')

    init = tf.compat.v1.global_variables_initializer()

with tf.compat.v1.Session(graph=lab4_part3) as sess:
    sess.run(init)

    print('Image input:\n\n{0}\n'.format(input.eval()))
    print('Filter/Kernel:\n\n{0}\n'.format(filter.eval()))
    result = sess.run(op)
    print('\nConvolution of image without zero padding:\n\n{0}\n'.format(result))
    result = sess.run(op2)
    print('\nConvolution of image with zero padding:\n\n{0}\n'.format(result))

"""
Part4: Convolution applied to images
"""

print('\n\nPart4\n')

"""
Part4.a: Edge detection on a bird image
"""

#Load image from URL
image_url = 'https://www.sciencemag.org/sites/default/files/styles/article_main_large/public/bird_16x9_3.jpg?itok=PjlMM1pn'
image_data = requests.get(image_url).content

#Load image data
image = Image.open(BytesIO(image_data))

#Convert image to black and white
image_gr = image.convert("L")

#Convert image to array of 0 to 255 uint8
image_arr = numpy.asarray(image_gr)

#plot image
image_plot = plt.imshow(image_arr)
image_plot.set_cmap('gray')
plt.title('Grayscale Bird Image')
plt.show(block=image_plot)

#Define an edge detector kernel
kernel = numpy.array([[0,1,0],
                      [1,-4,1],
                      [0,1,0]])

grad = signal.convolve2d(image_arr, kernel, mode='same', boundary='symm')

#plot convolution
fig, aux = plt.subplots(figsize=(10, 10))
aux.imshow(numpy.absolute(grad), cmap='gray')
plt.title('Edge Detection Convolution')
plt.show(block=fig)

#Note: CNNs automatically modify kernel to determine features that best describe data

#When dealing with CNNs pixels are generally converted to values between 0 to 1
# in a process called 'Normalization'

grad_biases = numpy.absolute(grad) + 100
grad_biases[grad_biases > 255] = 255

fig, aux = plt.subplots(figsize=(10, 10))
aux.imshow(numpy.absolute(grad_biases), cmap='gray')
plt.title('Gradient Magnitude Convolution')
plt.show(block=fig)

"""
Part4.b: Edge detection on a digit image
"""

#load image
image_url = 'https://ibm.box.com/shared/static/vvm1b63uvuxq88vbw9znpwu5ol380mco.jpg'
image_data = requests.get(image_url).content
image = Image.open(BytesIO(image_data))
image_gr = image.convert('L')
image_arr = numpy.array(image_gr)

#plot source image
fig, aux = plt.subplots(figsize=(10, 10))
image_plot = plt.imshow(image_arr)
image_plot.set_cmap('gray')
plt.title('Original Digit Image')
plt.show(block=image_plot)

#convolve using edge detection kernel
grad = signal.convolve2d(image_arr, kernel, mode='same', boundary='symm')

#plot convolution
fig, aux = plt.subplots(figsize=(10, 10))
aux.imshow(numpy.absolute(grad), cmap='gray')
plt.title('Edge Detection of Digit Image')
plt.show(block=fig)


"""update user is_deleted attribute

Revision ID: e619152902ba
Revises: 3903a3baa2e9
Create Date: 2021-07-03 12:31:30.059263

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'e619152902ba'
down_revision = '3903a3baa2e9'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('users', 'is_deleted',
               existing_type=sa.BOOLEAN(),
               nullable=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('users', 'is_deleted',
               existing_type=sa.BOOLEAN(),
               nullable=True)
    # ### end Alembic commands ###


"""Mapping tests"""

import unittest
from unittest.mock import MagicMock, Mock, create_autospec

from robotics.body.part import Part
from robotics.motion.mapping import CommonMotionsMapping
from robotics.motion.mapping import MotionMapping
from robotics.motion.mapping import CommonMotions
from robotics.typings.types import GeneratorMap

class TestMotionMapping(unittest.TestCase):
    """Mapping tests"""

    def test_register(self):
        """test registration method"""
        part = create_autospec(Part)
        part.name = 'test'
        part_mapping = Mock()

        mapping = MotionMapping()
        mapping.register(part, part_mapping)
        result = mapping[part]

        self.assertEqual(part_mapping, result)

    def test_register_as_operator(self):
        """test registration method"""
        part = create_autospec(Part)
        part.name = 'test'
        part_mapping = Mock()

        mapping = MotionMapping()
        mapping[part] = part_mapping
        result = mapping[part]

        self.assertEqual(part_mapping, result)

    def test_get_part_mapping(self):
        """test getting map"""
        part = create_autospec(Part)
        part.name = 'test'
        part_mapping = Mock()

        mapping = MotionMapping({ 'test': part_mapping })
        result = mapping.get_part_mapping(part)

        self.assertEqual(part_mapping, result)

    def test_get_motion(self):
        """test getting motion"""
        expected = 5
        part = create_autospec(Part)
        motion_map = MagicMock()
        motion_map.get().get.return_value = expected

        mapping = MotionMapping(motion_map)
        result = mapping.get_part_motion(part, CommonMotions.FORWARD)

        self.assertEqual(expected, result)

    def test_get_motion_by_name(self):
        """test getting motion"""
        expected = {}
        motion_map = MagicMock()
        motion_map.get.return_value = expected

        mapping = MotionMapping(motion_map)
        result = mapping.get_part_mapping_by_name('test')

        self.assertEqual(expected, result)

class TestCommonMotionMapping(unittest.TestCase):
    """Common mapping tests"""

    @staticmethod
    def _motion_helper(expected: int) -> GeneratorMap:
        """Get a mocked motion helper

        Args:
            expected (int): the expected output

        Returns:
            GeneratorMap: helper mapping
        """
        part_map = MagicMock()
        part_map.get().__getitem__().return_value = expected

        return part_map

    def test_forward(self):
        """test forward"""
        expected = 5
        motions = self._motion_helper(expected)
        mapping = CommonMotionsMapping(motions)
        motion = mapping.forward(Mock())

        self.assertEqual(expected, motion())

    def test_backward(self):
        """test backward"""
        expected = 5
        motions = self._motion_helper(expected)
        mapping = CommonMotionsMapping(motions)
        motion = mapping.backward(Mock())

        self.assertEqual(expected, motion())

    def test_left(self):
        """test left"""
        expected = 5
        motions = self._motion_helper(expected)
        mapping = CommonMotionsMapping(motions)
        motion = mapping.left(Mock())

        self.assertEqual(expected, motion())

    def test_right(self):
        """test right"""
        expected = 5
        motions = self._motion_helper(expected)
        mapping = CommonMotionsMapping(motions)
        motion = mapping.right(Mock())

        self.assertEqual(expected, motion())

    def test_turn_left(self):
        """test turn left"""
        expected = 5
        motions = self._motion_helper(expected)
        mapping = CommonMotionsMapping(motions)
        motion = mapping.turn_left(Mock())

        self.assertEqual(expected, motion())

    def test_turn_right(self):
        """test turn right"""
        expected = 5
        motions = self._motion_helper(expected)
        mapping = CommonMotionsMapping(motions)
        motion = mapping.turn_right(Mock())

        self.assertEqual(expected, motion())

    def test_diag_left_forward(self):
        """test diagonal left forward"""
        expected = 5
        motions = self._motion_helper(expected)
        mapping = CommonMotionsMapping(motions)
        motion = mapping.diag_left_forward(Mock())

        self.assertEqual(expected, motion())

    def test_diag_left_backward(self):
        """test diagonal left backward"""
        expected = 5
        motions = self._motion_helper(expected)
        mapping = CommonMotionsMapping(motions)
        motion = mapping.diag_left_backward(Mock())

        self.assertEqual(expected, motion())

    def test_diag_right_forward(self):
        """test diagonal right backward"""
        expected = 5
        motions = self._motion_helper(expected)
        mapping = CommonMotionsMapping(motions)
        motion = mapping.diag_right_forward(Mock())

        self.assertEqual(expected, motion())

    def test_diag_right_backward(self):
        """test diagonal right backward"""
        expected = 5
        motions = self._motion_helper(expected)
        mapping = CommonMotionsMapping(motions)
        motion = mapping.diag_right_backward(Mock())

        self.assertEqual(expected, motion())


from django.conf.urls import url

from . import views

urlpatterns = [
	url(r'^$', views.index, name='index'),
	url(r'^login/$', views.index, name='login'),
	url(r'^logout/$', views.logging_out, name='logging_out'),
	url(r'^register/$', views.register, name='register'),
	url(r'^reg_success/$', views.reg_success, name='reg_success'),
	url(r'^rate/$', views.rate, name='rate'),
	url(r'^remove_from_wardrobe/$', views.remove_from_wardrobe, name='remove'),
	url(r'^add_to_wardrobe/$', views.add_to_wardrobe, name='add'),
	url(r'^wardrobe/$', views.wardrobe, name='wardrobe'),
	url(r'^wardrobe/(?P<category_name>\D+)/$', views.wardrobe, name='wardrobe_category'),
	url(r'^catalogue/$', views.catalogue, name='catalogue'),
	url(r'^catalogue/(?P<category_name>\D+)/$', views.catalogue, name='catalogue_category'),
	url(r'^item/(?P<item_id>[0-9]+)/$', views.item, name='item'),
	#url(r'^recommend/$', views.recommend, name='recommend'),
	#url(r'^recommend/(?P<recommender>\D+)/$', views.recommend, name='recommender'),
	url(r'^recommendations/$', views.recommendations, name='recommendations'),
	url(r'^rate_recommendation/$', views.rate_recommendation, name='rate_recommendation'),
]


import fileinput
import re

L = list([l.strip() for l in fileinput.input()])
R = {}
C = {}

def match_list(line, st, ed, rules):
    key = (st, ed, tuple(rules))

    if st==ed and not rules:
        return True
    if st==ed:
        return False
    if not rules:
        return False

    ret = False
    for i in range(st+1, ed+1):
        if i==ed and len(rules)>1: # have to leave something for the other rules
            continue
        if match(line, st, i, rules[0]) and match_list(line, i, ed, rules[1:]):
            return True

    return False

DP = {}
def match(line, st, ed, rule):
    key = (st, ed, rule)
    if key in DP:
        return DP[key]

    ret = False
    if rule in C:
        ret = (line[st:ed] == C[rule])
    else:
        for option in R[rule]:
            if match_list(line, st, ed, option):
                ret = True
                DP[key] = True
                return True

    DP[key] = ret
    return ret

def solve(p2):
    ans = 0
    for line in L:
        if ':' in line:
            words = line.split()
            name = words[0][:-1]
            if name == '8' and p2:
                rest = '42 | 42 8'
            elif name == '11' and p2:
                rest = '42 31 | 42 11 31'
            else:
                rest = ' '.join(words[1:])
            if "\"" in rest:
                C[name] = rest[1:-1]
            else:
                options = rest.split(' | ')
                R[name] = [x.split(' ') for x in options]
        elif line:
            DP.clear()
            if match(line, 0, len(line), '0'):
                ans += 1
    return ans

print(solve(False))
print(solve(True))


import ctypes
import time

'''This code is used because GTA uses direct X so it translates the buttons we are pushing
to the necessary code when typed for example 0x11 is equivilent to w'''
#https://stackoverflow.com/questions/14489013/simulate-python-keypresses-for-controlling-a-game
SendInput = ctypes.windll.user32.SendInput

#needing to define the constants
W = 0x11
A = 0x1E
S = 0x1F
D = 0x20

# C struct redefinitions
PUL = ctypes.POINTER(ctypes.c_ulong)
class KeyBdInput(ctypes.Structure):
    _fields_ = [("wVk", ctypes.c_ushort),
                ("wScan", ctypes.c_ushort),
                ("dwFlags", ctypes.c_ulong),
                ("time", ctypes.c_ulong),
                ("dwExtraInfo", PUL)]

class HardwareInput(ctypes.Structure):
    _fields_ = [("uMsg", ctypes.c_ulong),
                ("wParamL", ctypes.c_short),
                ("wParamH", ctypes.c_ushort)]

class MouseInput(ctypes.Structure):
    _fields_ = [("dx", ctypes.c_long),
                ("dy", ctypes.c_long),
                ("mouseData", ctypes.c_ulong),
                ("dwFlags", ctypes.c_ulong),
                ("time",ctypes.c_ulong),
                ("dwExtraInfo", PUL)]

class Input_I(ctypes.Union):
    _fields_ = [("ki", KeyBdInput),
                 ("mi", MouseInput),
                 ("hi", HardwareInput)]

class Input(ctypes.Structure):
    _fields_ = [("type", ctypes.c_ulong),
                ("ii", Input_I)]

# Actuals Functions

def PressKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

def ReleaseKey(hexKeyCode):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    ii_.ki = KeyBdInput( 0, hexKeyCode, 0x0008 | 0x0002, 0, ctypes.pointer(extra) )
    x = Input( ctypes.c_ulong(1), ii_ )
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

# directx scan codes http://www.gamespp.com/directx/directInputKeyboardScanCodes.html
if __name__=='__main__':
    while (True):
        PressKey(0x11)
        time.sleep(1)
        ReleaseKey(0x11)
        time.sleep(1)