import os, pickle, tqdm, keras
import numpy as np
np.random.seed(0)
from copy import deepcopy
from util.Datahelper import data_preprocessing, list_partition, list_sampling, list_padding, mat_partition, mat_sampling, mat_padding, set_top_n, list2mat

num_courses = 2830
num_majors = 266
num_semesters = 12
token_dict = {
    '[PADDING]':0 + num_courses,
    '[MASK]':1 + num_courses,
    '[PREDICTION]':2 + num_courses,
    '[SEP]':3 + num_courses}

def RoBERTa_masking(List, num_courses):
    '''
    Dynamic Masking from 'RoBERTa: A Robustly Optimized BERT Pretraining Approach'
    15% of possible replacement.

    80% use [MASK] token.
    10% are unchanged.
    10% are randomly changed.
    '''

    List_2 = deepcopy(List)
    random_list = np.random.rand(len(List), 2)
    replace_courses = np.random.randint(low=0, high=num_courses, size=[len(List)])

    possible_replacement_index = (random_list[:, 0] < 0.15) * (List_2 < num_courses) # Never replace tokens.
    mask_index = possible_replacement_index * (random_list[:, 1] < 0.8)
    unchange_index = possible_replacement_index * (random_list[:, 1] > 0.8) * (random_list[:, 1] < 0.9)
    replace_index = possible_replacement_index * (random_list[:, 1] > 0.9)

    List_2[mask_index] = token_dict['[MASK]']
    List_2[replace_index] = replace_courses[replace_index]
    return List_2, possible_replacement_index

def onehot_encoding(List, shape):
    List_2 = np.zeros(shape)
    List_2[np.arange(len(List)).astype(int), np.array(List).astype(int)] = 1
    return List_2

class MultihotGenerator(keras.utils.Sequence):
    def __init__(self, data, stu_ids,
                 num_semesters, num_courses, num_majors,
                 predict_future, input_config,
                 batch_size=32, shuffle=True, fixed_seed=False):
        super(MultihotGenerator, self).__init__()

        self.data = data
        self.stu_ids = stu_ids

        self.num_semesters = num_semesters
        self.num_courses = num_courses
        self.num_majors = num_majors
        self.predict_future = predict_future

        self.input_config = input_config
        assert self.input_config['input_type'] in ['sample', 'history', 'same']
        if input_config['input_type'] == 'sample':
            self.sample_num = input_config['sample_num']
            self.sample_window = input_config['sample_window']
        elif self.input_config['input_type'] == 'history':
            self.history_number = input_config['history_number']

        print('Length of dataset : {}'.format(len(self.stu_ids)))

        self.batch_size = batch_size
        self.shuffle = shuffle

        self.fixed_seed = fixed_seed
        self.num_epoch = 0

        self.on_epoch_end()

    def __len__(self):
        return int(len(self.stu_ids) / self.batch_size)

    def __getitem__(self, batch_index):
        stu_indexes = self.stu_ids[(batch_index * self.batch_size):((batch_index + 1) * self.batch_size)]
        X0 = []
        X1 = []
        X2 = []
        X3 = []
        P = []
        Y = []

        for stu_index in stu_indexes:
            x0, x1, x2, x3, y, p = self.__data_generation(stu_index)
            X0.append(x0[np.newaxis, :, :])
            X1.append(x1[np.newaxis, :, :])
            X2.append(x2[np.newaxis, :, :])
            X3.append(x3[np.newaxis, :, :])
            Y.append(y[np.newaxis, :, :])
            P.append(p[np.newaxis, :])

        X0 = np.concatenate(X0, axis=0)
        X1 = np.concatenate(X1, axis=0)
        X2 = np.concatenate(X2, axis=0)
        X3 = np.concatenate(X3, axis=0)
        Y = np.concatenate(Y, axis=0)
        P = np.concatenate(P, axis=0)
        return [X0, X1, X2, X3, Y, P], []

    def on_epoch_end(self):
        if self.shuffle == True:
            self.num_epoch += 1
            # Shuffle the order of inputs.
            np.random.seed(self.num_epoch)
            np.random.shuffle(self.stu_ids)

    def __data_generation(self, index):
        # If use fixed seed, use the ppsk of students as the seed of sampling.
        temp_seed = index if self.fixed_seed else (index + self.num_epoch % 5)
        temp_start = self.data[index]['start']
        temp_courses = self.data[index]['courses'].astype(int)
        temp_majors = self.data[index]['majors'].astype(int)

        course_mat = list2mat(temp_courses, [self.num_semesters, self.num_courses])
        major_mat = list2mat(temp_majors, [self.num_semesters, self.num_majors])

        if self.input_config['input_type'] == 'sample':
            x0, y = mat_sampling(course_mat, self.sample_num, self.sample_window, seed=temp_seed)
            x1 = np.tile(major_mat[0][np.newaxis, :], [self.num_semesters, 1])
            x2 = np.eye(self.num_semesters)
            x3 = np.zeros([self.num_semesters, 3])
            x3[np.arange(self.num_semesters), np.mod(np.arange(self.num_semesters) + temp_start, 3)] = 1
            p = np.ones([self.num_semesters, ])
        elif self.input_config['input_type'] == 'history':
            x0, y = mat_split(course_mat, self.history_number)
            x1 = major_mat
            x1[(self.history_number + 1):] = 0
            x2 = np.eye(self.num_semesters)
            x3 = np.zeros([self.num_semesters, 3])
            x3[np.arange(self.num_semesters), np.mod(np.arange(self.num_semesters) + temp_start, 3)] = 1
            p = np,zeros([self.num_semesters, ])
            p[self.history_number:] = 1
        else:
            x0 = course_mat
            y = course_mat
            x1 = major_mat
            x2 = np.eye(self.num_semesters)
            x3 = np.zeros([self.num_semesters, 3])
            x3[np.arange(self.num_semesters), np.mod(np.arange(self.num_semesters) + temp_start, 3)] = 1
            p = np.ones([self.num_semesters, ])

        if self.predict_future:
            x0 = np.concatenate([np.zeros([1, x0.shape[-1]]), x0[:-1]], axis=0)
        return x0, x1, x2, x3, y, p

class MaskedLanguageModelGenerator(keras.utils.Sequence):
    def __init__(self, data, train_keys, test_keys, input_len, mask_function,
                 num_semesters, num_courses, num_majors,
                 batch_size=32, shuffle=True, fixed_seed=False):
        super(MaskedLanguageModelGenerator, self).__init__()

        self.data = data
        self.train_keys = train_keys
        self.test_keys = test_keys

        self.num_semesters = num_semesters
        self.num_courses = num_courses
        self.num_majors = num_majors
        self.input_len = input_len

        self.mask_function = mask_function

        self.batch_size = batch_size
        self.shuffle = shuffle

        self.fixed_seed = fixed_seed
        self.num_epoch = 0

        self.keys = []
        for stu in self.train_keys:
            self.keys.append([self.num_semesters, stu])
        if self.test_keys:
            for sem in self.test_keys:
                for stu in self.test_keys[sem]:
                    self.keys.append([sem, stu])
        self.on_epoch_end()

    def __len__(self):
        return int(len(self.keys) / self.batch_size)

    def __getitem__(self, batch_index):
        batch_keys = self.keys[(batch_index * self.batch_size):((batch_index + 1) * self.batch_size)]
        X0 = []
        X1 = []
        X2 = []
        X3 = []
        P = []
        Y = []

        for key in batch_keys:
            x0, x1, x2, x3, p, y = self.__data_generation(key)
            X0.append(x0[np.newaxis, :, :])
            X1.append(x1[np.newaxis, :, :])
            X2.append(x2[np.newaxis, :, :])
            X3.append(x3[np.newaxis, :, :])
            P.append(p[np.newaxis, :])
            Y.append(y[np.newaxis, :, :])

        X0 = np.concatenate(X0, axis=0)
        X1 = np.concatenate(X1, axis=0)
        X2 = np.concatenate(X2, axis=0)
        X3 = np.concatenate(X3, axis=0)
        P = np.concatenate(P, axis=0)
        Y = np.concatenate(Y, axis=0)
        return [X0, X1, X2, X3, Y, P], []

    def on_epoch_end(self):
        if self.shuffle == True:
            self.num_epoch += 1
            # Shuffle the order of inputs.
            np.random.seed(self.num_epoch)
            np.random.shuffle(self.stu_ids)

    def __data_generation(self, key):
        # x0: Course List.
        # x1: Multi-hot Major Vector.
        # x2: One-hot Relative Semester Vector.
        # x3: One-hot Semesters' Name Vector.
        # p, The place is masked or not.

        known_semesters = key[0]
        ppsk = key[1]

        temp_seed = ppsk if self.fixed_seed else (ppsk + self.num_epoch % 5)

        temp_start = self.data[ppsk]['start']
        temp_courses = self.data[ppsk]['courses'].astype(int)
        temp_courses = temp_courses[temp_courses[:, 0] < known_semesters] # Delete the courses student still hasn't take.
        temp_majors = self.data[ppsk]['majors'].astype(int)

        courses_list, padding_index = list_padding(temp_courses[:, 1], self.input_len, token_dict['[PADDING]'])
        courses_list_masking, p_list = self.mask_function(courses_list, self.num_courses)
        major_mat_sem = list2mat(temp_majors, [self.num_semesters, self.num_majors])

        y = onehot_encoding(courses_list, [self.input_len, self.num_courses + len(token_dict)])
        x0 = onehot_encoding(courses_list_masking, [self.input_len, self.num_courses + len(token_dict)])

        x1 = np.zeros([self.input_len, self.num_majors])
        x1[np.arange(temp_courses.shape[0]).astype(int)] = major_mat_sem[temp_courses[:, 0]]

        x2 = np.zeros([self.input_len, self.num_semesters])
        x2[np.arange(temp_courses.shape[0]).astype(int), temp_courses[:, 0]] = 1

        x3 = np.zeros([self.input_len, 3])
        x3[np.arange(temp_courses.shape[0]).astype(int), np.mod(temp_courses[:, 0] + temp_start, 3)] = 1

        return x0, x1, x2, x3, np.array(p_list), y

class PLANGenerator(keras.utils.Sequence):
    def __init__(self, data, keys, input_len, sampling_max, sampling_function,
                 num_semesters, num_courses, num_majors,
                 batch_size=32, shuffle=True, fixed_seed=False):
        super(PLANGenerator, self).__init__()
        self.data = data
        self.keys = keys

        self.num_semesters = num_semesters
        self.num_courses = num_courses
        self.num_majors = num_majors
        self.input_len = input_len

        self.sampling_max = sampling_max
        self.sampling_function = sampling_function

        self.batch_size = batch_size
        self.shuffle = shuffle

        self.fixed_seed = fixed_seed
        self.num_epoch = 0

        self.on_epoch_end()

    def __len__(self):
        return int(len(self.keys) / self.batch_size)

    def __getitem__(self, batch_index):
        batch_keys = self.keys[(batch_index * self.batch_size):((batch_index + 1) * self.batch_size)]
        X0 = []
        X1 = []
        X2 = []
        X3 = []
        P = []
        Y = []

        for key in batch_keys:
            x0, x1, x2, x3, p, y = self.__data_generation(key)
            X0.append(x0[np.newaxis, :, :])
            X1.append(x1[np.newaxis, :, :])
            X2.append(x2[np.newaxis, :, :])
            X3.append(x3[np.newaxis, :, :])
            P.append(p[np.newaxis, :])
            Y.append(y[np.newaxis, :, :])

        X0 = np.concatenate(X0, axis=0)
        X1 = np.concatenate(X1, axis=0)
        X2 = np.concatenate(X2, axis=0)
        X3 = np.concatenate(X3, axis=0)
        P = np.concatenate(P, axis=0)
        Y = np.concatenate(Y, axis=0)
        return [X0, X1, X2, X3, Y, P], []

    def on_epoch_end(self):
        if self.shuffle == True:
            self.num_epoch += 1
            # Shuffle the order of inputs.
            np.random.seed(self.num_epoch)
            np.random.shuffle(self.keys)

    def __data_generation(self, key):
        # x1: Course List.
        # x2: Multi-hot Major Vector.
        # x3: One-hot Relative Semester Vector.
        # x4: One-hot Semesters' Name Vector.

        ppsk = key

        temp_seed = ppsk if self.fixed_seed else (ppsk + (self.num_epoch % 5))

        temp_start = self.data[ppsk]['start']
        temp_courses = self.data[ppsk]['courses'].astype(int)
        temp_majors = self.data[ppsk]['majors'].astype(int)

        sampling_list, remaining_list = self.sampling_function(temp_courses, self.sampling_max, seed=temp_seed)
        sampling_array = np.array(sampling_list)
        remaining_array = np.array(remaining_list)
        sampling_sem = sampling_array[:, 0]
        sampling_courses = sampling_array[:, 1]
        remaining_sem = remaining_array[:, 0]
        remaining_courses = remaining_array[:, 1]

        prediction_tokens_list = [token_dict['[PREDICTION]']] * self.num_semesters
        courses_list, padding_index = list_padding(sampling_courses, self.input_len, token_dict['[PADDING]'])

        remaining_courses_mat = list2mat(remaining_list, [self.num_semesters, self.num_courses + len(token_dict)])
        prediction_tokens_mat = onehot_encoding(prediction_tokens_list, [self.num_semesters, self.num_courses + len(token_dict)])
        courses_mat = onehot_encoding(courses_list, [self.input_len, self.num_courses + len(token_dict)])

        major_mat_sem = list2mat(temp_majors, [self.num_semesters, self.num_majors]) # [num_semesters, num_majors]
        major_mat_courses = mat_padding(major_mat_sem[sampling_sem, :], [self.input_len, self.num_majors], token=0) # [num_sampling, num_majors]

        relative_mat_sem = np.eye(self.num_semesters)
        relative_mat_courses = onehot_encoding(sampling_sem, [self.input_len, self.num_semesters])

        name_mat_sem = onehot_encoding(np.arange(temp_start, temp_start + self.num_semesters) % 3, [self.num_semesters, 3])
        name_mat_courses = onehot_encoding(sampling_sem % 3, [self.input_len, 3])

        p_list = np.zeros([self.num_semesters + self.input_len,])
        p_list[:self.num_semesters] = 1

        y = np.concatenate([remaining_courses_mat, courses_mat])
        x0 = np.concatenate([prediction_tokens_mat, courses_mat])
        x1 = np.concatenate([major_mat_sem, major_mat_courses])
        x2 = np.concatenate([relative_mat_sem, relative_mat_courses])
        x3 = np.concatenate([name_mat_sem, name_mat_courses])

        return x0, x1, x2, x3, p_list, y

if __name__ == '__main__':
    path = '/home/AlbertShao/research/data/course.pkl'
    num_courses = 2830
    num_majors = 266
    num_semesters = 12

    with open(path, 'rb') as f:
        stu_dict = pickle.load(f)
        print('Total Number of Students : ' + str(len(stu_dict)))

    tv_keys, test_keys = data_preprocessing(stu_dict, 15)
    train_keys, valid_keys = list_partition(tv_keys, 0.8, seed=0)

    generator_1 = PLANGenerator(data=stu_dict, keys=train_keys, input_len=10, sampling_max=10, sampling_function=list_sampling,
                       num_semesters=num_semesters,
                       num_courses=num_courses,
                       num_majors=num_majors,
                       batch_size=32, shuffle=True, fixed_seed=False)
    generator_2 = MaskedLanguageModelGenerator(data=stu_dict, train_keys=train_keys, test_keys=None,
                                 input_len=64, mask_function=RoBERTa_masking,
                                 num_semesters=num_semesters,
                                 num_courses=num_courses,
                                 num_majors=num_majors,
                                 batch_size=32, shuffle=True, fixed_seed=False)


#important
import numpy as np
import matplotlib.pyplot as plt
from reg_utils import sigmoid, relu, plot_decision_boundary, load_2D_dataset, predict_dec
from reg_utils import compute_cost, predict, forward_propagation, backward_propagation, update_parameters
import sklearn
import sklearn.datasets
import scipy.io
from testCases import *

import dlFramework.frame as fw

plt.rcParams['figure.figsize'] = (7.0, 4.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'

train_X, train_Y, test_X, test_Y = load_2D_dataset()
plt.show()

print(train_X.shape)

model = fw.MultiLayer()

model.addLayerInput(train_X.shape[0])

model.addHidenLayer(20,act_func=fw.relu)

model.addHidenLayer(3,act_func=fw.relu)

model.addOutputLayer(train_Y.shape[0],act_func=fw.sigmoid)

model.initialize_parameters(seed=1)

parm = {}

parm['beta'] = 0.98
#make drop out 0.8 , and reg = 0.01 compare of regulrization
parameters,costs = model.train(train_X,train_Y,num_iterations=10000,print_cost=True , cont=0 ,learning_rate=0.03 ,batch_size=20,print_cost_each=100,opt_func=fw.gd_optm,param_dic=parm,reg_term=0.01,drop=0 )

#print(parameters)

acc = model.test(train_X,train_Y)

print(acc)

acc = model.test(test_X,test_Y)

print(acc)

plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations')
plt.show()

plot_decision_boundary(lambda x: (model.predict(x.T) > 0.5) * 1, train_X, train_Y)
plt.show()


import pygame
class Gamestate():
	@staticmethod
	def start(GS):
		font = pygame.font.SysFont("comicsansms", 72)
		text = font.render("Press SPACE to start the game..", True, GS.font_color)
		GS.screen.fill(GS.screen_background)
		GS.screen.blit(text, (GS.screen_width/2 - text.get_width() / 2, GS.screen_height/2 - text.get_height() / 2))
		pygame.display.flip()

	@staticmethod
	def game(GS,Square):
		GS.screen.fill(GS.screen_background)
		Square.draw()
		pygame.display.flip()

	@staticmethod
	def defeat(GS):
		font = pygame.font.SysFont("comicsansms", 72)
		text = font.render("Defeat! - You miss-clicked once", True, GS.font_color)
		text2 = font.render("Press SPACE for restart...", True, GS.font_color)
		GS.screen.fill(GS.screen_background)
		GS.screen.blit(text, (GS.screen_width/2 - text.get_width() / 2, GS.screen_height/2 - text.get_height() / 2-80))
		GS.screen.blit(text2, (GS.screen_width/2 - text2.get_width() / 2, GS.screen_height/2 - text2.get_height() / 2+80))
		pygame.display.flip()


'''
    author: TangXiaojuan
    date: 2021-04-14
    content: Reliable file transfer using Go-Back-N
'''
# 1. 定义结构帧{data(1KB)、checksum(CRC-CCITT)、seq、ack}
# 2.
import gl
import socket
import CRC16CCITT
from Frame import *
import sys

UDPPort = 30207
Recv_nr_expected = 0
WFileName = "receiver.txt"
Cur_Acked = -1
STATUS = ['OK','DataError','NoError']
OK = 0
DATAERROR = 1
NOERROR = 2

k = 0

def recv_data(s,wf):
    global Cur_Acked

    global k,Recv_nr_expected
    k += 1
    temp = Recv_nr_expected

    r_data = s.recv(gl.DataSize)  # 一次接收4*1024字节
    # print("recv_data:",r_data)
    # print("r_data[-6:]",r_data[-6:])
    r_frame = Frame.ToFrame(r_data[:-6])
    # print(r_data[:-6])
    # print("接收到发送端的包：", r_frame.seq)
    # 开始校验
    if CRC16CCITT.CheckCRC(r_data):
        if r_frame.seq == -2:
            print("文件接收完毕")
            s.close()
            wf.close()
            sys.exit(0)
        # 校验成功
        if r_frame.seq == Recv_nr_expected:
            # print("收到期待的包,发送确认包")
            status = OK
            Cur_Acked = r_frame.id
            # 写入文件？？
            wf.write(r_frame.data.decode('utf-8'))

            # 发送确认包
            s_frame = Frame(-1,r_frame.seq,id=r_frame.id)
            Recv_nr_expected = (Recv_nr_expected + 1) % gl.MaxSeq
        else:
            status = NOERROR
            s_frame = Frame(-1,Cur_Acked%gl.MaxSeq,id=Cur_Acked)

    else:
        status = DATAERROR
        # print("校验失败")
        # 再发一次当前的确认包
        s_frame = Frame(-1,Cur_Acked,id=Cur_Acked)

    s_data = s_frame.ToBytes()
    s.sendto(s_data, ("127.0.0.1", 40207))

    print("%d,pdu_exp=%d,pdu_recv=%d,status=%s,id=%d" % (k, temp, r_frame.seq, STATUS[status],r_frame.id))

if __name__ == '__main__':

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind(("", UDPPort))  # 绑定服务器的ip和端口
    wf = open(WFileName, 'w')
    while True:
        recv_data(s,wf)

    # load_data("123",1,2)


import threading
from websocket_server import WebsocketServer
import time
import socket
import os
import random
import ftplib

tcp_server_bind_ip = ""
tcp_server_bind_port = 17789
tcp_server_maxclientnum = 5

websocket_server_port=9998

blockly_cmd=""
daemon_websocket_server = WebsocketServer(websocket_server_port)

tcpClient_list_connect=[]
tcpClient_list_name=[]

tensorflow_img_recognize = "tensorflowimg##"
maxmsp_cmdStart= "maxmsp#########"

# def clientIsTensorflow(clientName,tcp_server_recv):

isRpiMode = False
feature_takephoto = "takephoto"
photo_name = []

# task: tcp server
def tcpclient_thread(tcp_server_connect,clientIp,clientPort):
    print("[+] New server socket thread started for " + clientIp + ":" + str(clientPort))
    tcp_server_recv = (tcp_server_connect.recv(1024)).strip().decode('ISO-8859-1')

    clientName = tcp_server_recv[0:15]
    print('client is ' + clientName)

    global tcpClient_list_connect
    tcpClient_list_connect.append(tcp_server_connect)
    global tcpClient_list_name
    tcpClient_list_name.append(clientName)

    daemon_websocket_server.send_message_to_all(tcp_server_recv)

    while True:
        try:
            tcp_server_recv = (tcp_server_connect.recv(1024)).strip().decode('ISO-8859-1')
            print("client(" + clientIp + ":" + str(clientPort) + ")said: " + tcp_server_recv)
            daemon_websocket_server.send_message_to_all(tcp_server_recv)

            # inputMsg = input("Enter response to client(" + clientIp + ":" + str(clientPort) + "): ")
            # tcp_server_connect.send(inputMsg.strip().encode('utf-8'))
        except:
            print("client disconnect!")
            break

def tcp_server():
    tcp_server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    tcp_server_socket.bind((tcp_server_bind_ip,tcp_server_bind_port))
    threads = []
    while True:
        tcp_server_socket.listen(tcp_server_maxclientnum)
        print("Multithreaded Python server : Waiting for connections from TCP clients...")
        (tcp_server_connect, (clientIp,clientPort)) = tcp_server_socket.accept()
        print('('+clientIp + ":" + str(clientPort)+')tcp_server_connect:' +tcp_server_connect)
#sarah3 what's this?

        childThread_tcpclient_thread = threading.Thread(target=tcpclient_thread, args=(tcp_server_connect,clientIp,clientPort))
        childThread_tcpclient_thread.start()
        threads.append(childThread_tcpclient_thread)

    for t in threads:
# sarah2 why after while need this, is it excuted? join() would block process until done
        t.join()

def my_websocket_server():
    daemon_websocket_server.set_fn_new_client(new_client)
    print("daemon is ready!")
    print("wait for blockly")
    daemon_websocket_server.set_fn_client_left(client_left)
    daemon_websocket_server.set_fn_message_received(message_received)
    daemon_websocket_server.run_forever()

def new_client(client, server):
#       print("client id %d" % client['id'])
#       daemon_websocket_server.send_message_to_all("defg")
        print("-----------------------")
        print("blockly in!")

def client_left(client, server):
#       print("Client(%d) disconnected" % client['id'])
        print("")

def message_received(client, server, message):
        if len(message) > 200:
                message = message[:200]+'..'
        global blockly_cmd
        blockly_cmd = message

        print("blockly said: %s" % (blockly_cmd))
        cmdToWho = blockly_cmd[0:15]
        print('cmd to who? ' + cmdToWho)
        if blockly_cmd.find(feature_takephoto):
            photo_name.append(random.randrange(9999999))
            os.system("raspistill -w 100 -h 100 -o "+str(photo_name[len(photo_name)-1])+".jpg")
            print("take photo: "+str(photo_name[len(photo_name)-1])+".jpg")
            session = ftplib.FTP('192.168.43.180','sarahcheng','tuhbnygj')
            file = open(str(photo_name[len(photo_name)-1])+".jpg",'rb')
            session.storbinary('STOR '+"~/Desktop/tensorflow_db/rpi"+str(photo_name[len(photo_name)-1])+".jpg",file)
            file.close()
            session.quit()
            daemon_websocket_server.send_message_to_all(str(photo_name[len(photo_name)-1])+".jpg")
            print("send photo successful")

        if not isRpiMode:
            print(str(tcpClient_list_connect[tcpClient_list_name.index(cmdToWho)]))
            tcpClient_list_connect[tcpClient_list_name.index(cmdToWho)].send((str(blockly_cmd)+'\n').encode('utf-8'))
            if cmdToWho == maxmsp_cmdStart:
# zeo1 why remove?
                tcpClient_list_connect.remove(tcpClient_list_connect[tcpClient_list_name.index(cmdToWho)])
                tcpClient_list_name.remove(cmdToWho)
            print("send to client: " + blockly_cmd)
os.system("uname "+"-a > myEnv.txt")
if os.system("grep raspberry myEnv.txt") == 0:
    print("RPI mode!")
    isRpiMode = True

mainThread_websocket_server = threading.Thread(target=my_websocket_server, args=())
mainThread_websocket_server.start()
mainThread_tcp_server = threading.Thread(target=tcp_server, args=())
mainThread_tcp_server.start()

mainThread_tcp_server.join()
mainThread_websocket_server.join()


OWNER_ID = '' #botun sahibinin id'si
BOT_PREFIX = 'm!'
TOKEN = '' #buraya botun token'i
GAME_CHANNEL = '' #botu oynayacağınız kanal id'si
DEBUG_CHANNEL = '' #botun sistem mesajlarını atacağı kanal id'si
WEREWOLF_SERVER = '' #botun çalışacağı sunucu'nun id'si
PLAYERS_ROLE_NAME = 'Players'
ADMINS_ROLE_NAME = 'Mafia'
WEREWOLF_NOTIFY_ROLE_NAME = 'Notify'
ADMINS = [''] #oyundaki adminlerin id'leri. Birden fazla admin için aralara virgül koyun amk çocukları.
IGNORE_LIST = []
TOKENS_GIVEN = 5
TOKEN_RESET = 10
IGNORE_THRESHOLD = 7
NOTIFY_FILE = 'notify.txt'
BACKUP_INTERVAL = 300
MESSAGE_LANGUAGE = 'en'
LOG_FILE = 'debug.txt'
MIN_LOG_LEVEL = 1
# 0 to log everything, 1 to log only gameplay-related info, 2 to log only warnings
STASIS_FILE = 'stasis.json'
PLAYING_MESSAGE = '{0}info | {0}help | {0}join'.format(BOT_PREFIX)


num = int(input('Digite um inteiro:'))

print('Escolha uma das bases para conversão: \n [ 1 ] converter para BINÁRIO \n [ 2 ] converter para OCTAL \n [ 3 ] converter para hexadecimal')

opcao = int(input('Sua opção: '))

if opcao ==1:
    bi = format(num, "b")
    print('{} convertido para BINÁRIO é igual: {}'.format(num, bi))
elif opcao ==2:
    oc = format(num, "o")
    print('{} convertido para OCTAL é igual: {}'.format(num, oc))
elif opcao == 3:
    he = format(num, "x")
    print('{} convertido para HEXADECIMAL é igual: {}'.format(num, he))
else:
    print('ERRO!')


import io
import os

# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types

#Perform VisionAI Image Recognition on Image BEFORE

# Instantiates a client
client = vision.ImageAnnotatorClient()

# The name of the image file to annotate
file_nameB = os.path.abspath('images/vegetables_before.jpg')

# Loads the image into memory
with io.open(file_nameB, 'rb') as image_file:
    content = image_file.read()

image = types.Image(content=content)

# Performs label detection on the image file
response = client.label_detection(image=image)
itemsBefore = response.label_annotations

#Repeat process for Image AFTER
# The name of the image file to annotate
file_nameA = os.path.abspath('images/vegetables_after.jpg')

# Loads the image into memory
with io.open(file_nameA, 'rb') as image_file:
    content = image_file.read()

image = types.Image(content=content)

# Performs label detection on the image file
response = client.label_detection(image=image)
itemsAfter = response.label_annotations

missingItems = [item for item in itemsBefore if item not in itemsAfter]
newItems = [item for item in itemsAfter if item not in itemsBefore]

print('Labels Before:')
for label in itemsBefore:
    print(label.description)

print('\n')
print('Labels After:')
for label in itemsAfter:
    print(label.description)

print('\n')

print('Items Missing:')
for label in missingItems:
    print(label.description)

print('\n')
print('Items Newly Added:')
for label in newItems:
    print(label.description)


from __future__ import absolute_import

from ..exceptions import NotInitializedException
from .ratchet import Ratchet

class SymmetricKeyRatchet(Ratchet):
    """
    An implementation of the Ratchet interface, which internally manages two chains: A
    chain to derive sending keys and a chain to derive receiving keys. The ratchet step
    alternately replaces the sending and the receiving chains with new ones.
    """

    def __init__(self, sending_chain_class, receiving_chain_class):
        """
        Initialize a new SymmetricKeyRatchet.

        :param sending_chain_class: An implementation of the Chain interface to be used
            for the sending chains.
        :param receiving_chain_class: An implementations of the Chain interface to be used
            for the receiving chains.
        """

        super(SymmetricKeyRatchet, self).__init__()

        self.__SendingChain   = sending_chain_class
        self.__ReceivingChain = receiving_chain_class

        self.__sending_chain   = None
        self.__receiving_chain = None

        self.__previous_sending_chain_length = None

    def serialize(self):
        sending_chain = self.__sending_chain
        sending_chain = None if sending_chain == None else sending_chain.serialize()

        receiving_chain = self.__receiving_chain
        receiving_chain = None if receiving_chain == None else receiving_chain.serialize()

        return {
            "super"  : super(SymmetricKeyRatchet, self).serialize(),
            "schain" : sending_chain,
            "rchain" : receiving_chain,
            "prev_schain_length" : self.__previous_sending_chain_length
        }

    @classmethod
    def fromSerialized(cls, serialized, *args, **kwargs):
        self = super(SymmetricKeyRatchet, cls).fromSerialized(
            serialized["super"],
            *args,
            **kwargs
        )

        if serialized["schain"] != None:
            self.__sending_chain = self.__SendingChain.fromSerialized(
                serialized["schain"],
                None
            )

        if serialized["rchain"] != None:
            self.__receiving_chain = self.__ReceivingChain.fromSerialized(
                serialized["rchain"],
                None
            )

        self.__previous_sending_chain_length = serialized["prev_schain_length"]

        return self

    def step(self, key, chain):
        """
        Perform a rachted step, replacing one of the internally managed chains with a new
        one.

        :param key: A bytes-like object encoding the key to initialize the replacement
            chain with.
        :param chain: The chain to replace. This parameter must be one of the two strings
            "sending" and "receiving".
        """

        if chain == "sending":
            self.__previous_sending_chain_length = self.sending_chain_length

            self.__sending_chain = self.__SendingChain(key)

        if chain == "receiving":
            self.__receiving_chain = self.__ReceivingChain(key)

    @property
    def previous_sending_chain_length(self):
        """
        Get the length of the previous sending chain.

        :returns: Either an integer representing the length of the previous sending chain
            or None, if the current one is the first sending chain.
        """

        return self.__previous_sending_chain_length

    @property
    def sending_chain_length(self):
        """
        Get the length of the current sending chain.

        :returns: Either an integer representing the length of the current sending chain
            or None, if there is no sending chain.
        """

        return None if self.__sending_chain == None else self.__sending_chain.length

    @property
    def receiving_chain_length(self):
        """
        Get the length of the receiving chain.

        :returns: Either an integer representing the length of the receiving chain or
            None, if there is no receiving chain.
        """

        return None if self.__receiving_chain == None else self.__receiving_chain.length

    def nextEncryptionKey(self):
        """
        Use the sending chain to derive the next encryption key.

        :returns: A bytes-like object encoding the next encryption key.
        :raises NotInitializedException: If there is no sending chain yet.
        """

        if self.__sending_chain == None:
            raise NotInitializedException(
                "Can not get the next encryption key from the symmetric key ratchet, " +
                "there is no sending chain yet."
            )

        return self.__sending_chain.next()

    def nextDecryptionKey(self):
        """
        Use the receiving chain to derive the next decryption key.

        :returns: A bytes-like object encoding the next decryption key.
        :raises NotInitializedException: If there is no receiving chain yet.
        """

        if self.__receiving_chain == None:
            raise NotInitializedException(
                "Can not get the next decryption key from the symmetric key ratchet, " +
                "there is no receiving chain yet."
            )

        return self.__receiving_chain.next()


import os
import sys
import random
import math
import re
import time
import numpy as np
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import shutil
import glob
import os.path as osp

# Root directory of the project
ROOT_DIR = os.path.abspath("../../")

# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn import utils
from mrcnn import visualize_edited as visualize
from mrcnn.visualize_edited import display_images
import mrcnn.model as modellib
from mrcnn.model import log
import skimage.draw
import cv2

# %matplotlib inline

# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")

# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
    utils.download_trained_weights(COCO_MODEL_PATH)

# Path to Shapes trained weights
SHAPES_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_shapes.h5")

from mrcnn.config import Config

class ObjectDetectionConfig(Config):
    """Configuration for training on the buildings and ground detection.
    Derives from the base Config class and overrides some values.
    """
    # Give the configuration a recognizable name
    NAME = "objectDetection"

    # We use a GPU with 12GB memory, which can fit two images.
    # Adjust down if you use a smaller GPU.
    IMAGES_PER_GPU = 2

    # Number of classes (including background)
    NUM_CLASSES = 1 + 5  # Background + building-ground classes

    # Number of training steps per epoch
    STEPS_PER_EPOCH = 500

    # Skip detections with < 90% confidence
    DETECTION_MIN_CONFIDENCE = 0.9

class InferenceConfig(ObjectDetectionConfig):
    # Set batch size to 1 since we'll be running inference on
    # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

# my object detection config:
config = InferenceConfig()
data_DIR_images = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\images\\"
data_DIR_lables = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\labels\\"
data_DIR_thermals = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\thermals\\"
data_DIR_predicts = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\predicts\\"

# Override the training configurations with a few
# changes for inferencing.
class InferenceConfig(config.__class__):
    # Run detection on one image at a time
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

config = InferenceConfig()

DEVICE = "/cpu:0"  # /cpu:0 or /gpu:0

# Inspect the model in training or inference modes
# values: 'inference' or 'training'
# TODO: code for 'training' test mode not ready yet
TEST_MODE = "inference"

class_names = ['background','building_roof', 'ground_cars', 'building_facade', 'ground_cars', 'building_roof']

# Create model in inference mode
with tf.device(DEVICE):
    model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR,
                              config=config)

weights_path = model.find_last()

# Load weights
print("Loading weights ", weights_path)
model.load_weights(weights_path, by_name=True)

names = [x for x in os.listdir(data_DIR_images) if ".jpg" in x] #new

for name in names:
    name = name.split(".")[0]

    image = skimage.io.imread(data_DIR_images + name+".jpg")
    thermal = skimage.io.imread(data_DIR_thermals + name+".jpg")

    image = np.concatenate((image, thermal), axis=2)

    gt_image = cv2.imread(data_DIR_lables+name+".png")
    # Run object detection
    results = model.detect([image], verbose=1)

    # Display results

    r = results[0]
    pred_image = visualize.return_save(image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores'], title="Predictions")

    gt_image = cv2.cvtColor(gt_image, cv2.COLOR_BGR2RGB)
    pred_image = pred_image[:, :, ::-1]
    # pred_image = np.array(pred_image,dtype=np.uint8)
    # pred_image = cv2.cvtColor(pred_image, cv2.COLOR_BGR2RGB)

    plt.imshow(pred_image)
    plt.show()
    plt.imshow(image)
    plt.show()
    plt.imshow(gt_image)
    plt.show()

    print(gt_image[900,400])
    print(pred_image[1000,400])
    # cv2.imwrite(data_DIR_predicts+name+".png", pred_image)
    skimage.io.imsave(data_DIR_predicts+name+".png", pred_image)


#!/usr/bin/env python3
# Use to connect to the Agilent Multimeter
# Coded by David on Jul 19 2019
# Only methods to query ac/dc current or voltage are currently included

#     _         _ _            _     _____ _  _   _  _    ___  _    _
#    / \   __ _(_) | ___ _ __ | |_  |___ /| || | | || |  / _ \/ |  / \
#   / _ \ / _` | | |/ _ \ '_ \| __|   |_ \| || |_| || |_| | | | | / _ \
#  / ___ \ (_| | | |  __/ | | | |_   ___) |__   _|__   _| |_| | |/ ___ \
# /_/   \_\__, |_|_|\___|_| |_|\__| |____/   |_|    |_|  \___/|_/_/   \_\
#         |___/

import serial
import sys

class Agilent34401A():
    def __init__(self, settings={}):
        self.defaults = {'port':'/dev/ttyUSB0',
            'baudrate':9600,
            'lf':'\r\n',
            'timeout': 0.5,
            'mode':'DC'}
        self.shortname = 'Multimeter'
        self.fullname = 'Agilent - 34401A Multimeter'
        self.manual_fname = './zialab/man/'+self.fullname + '.pdf'
        self.platform = sys.platform
        self.notes = '''This to read voltages, currents, and the like.'''
        if settings: # if settings are given, then set it up like so
            self.settings = settings
        else: # else use defaults
            print("Using default settings:")
            print(self.defaults)
            self.settings = self.defaults
        self.baudrate = self.settings['baudrate']
        self.port = self.settings['port']
        self.timeout = self.settings['timeout']
        self.lf = self.settings['lf']
        self.mode = self.settings['mode']
        try:
            print("Setting up the serial connection.")
            self.serialconn = serial.Serial(port=self.port,
                baudrate=self.baudrate,
                timeout=self.timeout)
            print("Setting up the system to remote mode...")
            self.sendtodev('SYST:REMOTE')
            print("Setting up the AC/DC mode...")
            self.sendtodev('CONF:VOLT:%s' % self.mode.upper())
        except:
            print("There was a problem setting up the serial connection.")
    def makecmd(self,command):
        '''composes command according to serial config'''
        return command+self.lf
    def sendtodev(self,command):
        '''sends command through the serial connection'''
        self.serialconn.write(self.makecmd(command).encode())
        return '\n'.join([s.decode()[:-2] for s in self.serialconn.readlines()])
    def get_dc_voltage(self):
        '''get DC voltage'''
        if self.mode.upper() != 'DC':
            print("Changing mode to DC.")
            self.sendtodev('CONF:VOLT:DC')
        return float(self.sendtodev('MEAS:VOLT:DC?'))
    def get_dc_current(self):
        '''get DC current'''
        if self.mode.upper() != 'DC':
            print("Changing mode to DC.")
            self.sendtodev('CONF:CURR:DC')
            self.mode = 'DC'
        return float(self.sendtodev('MEAS:CURR:DC?'))
    def get_ac_voltage(self):
        '''get AC voltage'''
        if self.mode.upper() != 'AC':
            print("Changing mode to AC.")
            self.sendtodev('CONF:VOLT:AC')
        return float(self.sendtodev('MEAS:VOLT:AC?'))
    def get_ac_current(self):
        '''get AC current'''
        if self.mode.upper() != 'AC':
            print("Changing mode to AC.")
            self.sendtodev('CONF:CURR:AC')
            self.mode = 'AC'
        return float(self.sendtodev('MEAS:CURR:AC?'))


from cosine_sim import cosine_sim
#from pearson_sim import pearson_sim
from reco_cosine import reco_cosine
from operator import itemgetter
#from reco_pearson import reco_pearson
#from cosinecaseamp_sim import cosinecaseamp_sim
from math import log10
#from pearson_sim_IUF import pearson_sim_IUF
#import logging as log
#from pearson_sim_IUF_caseamp import pearson_sim_IUF_caseamp
#from pearson_sim_caseamp import pearson_sim_caseamp

user_train={0:{0:3,1:0,2:0,3:2,4:3,5:1,6:0,7:0},1:{0:1,1:0,2:0,3:3,4:4,5:2,6:3,7:0},2:{0:0,1:0,2:3,3:2,4:3,5:1,6:0,7:0}}
user_test={3:{0:4,2:2,4:2,5:0},4:{0:0,3:3,5:2,6:1}}

def recommender(user_train,user_test,movie_train,k):

    user_avg={}
    for user in user_train:
        count2=0
        sum=0
        for movie in user_train[user]:
            if user_train[user][movie]!=0:
                sum=sum+user_train[user][movie]
                count2=count2+1

        if count2==0:
            avg=0
        else :
            avg=float(sum)/float(count2)
        user_avg[user]=avg

    IUF_train={}
    for movie in movie_train:
        count2=0
        for user in movie_train[movie]:
            if  movie_train[movie][user]!=0:
                count2=count2+1
        if count2 ==0:
            IUF==0
        else:
            a=1000/count2
            IUF=log10(a)
        IUF_train[movie]=IUF

    sim_user={}
    sim_userabs={}
    for user in user_test:
        dict1={}
        dict2={}
        for user1 in user_train:
            if user!=user1:
                '''if user==201 and user1==2:
                    print 'user_train'
                    print user_train[user1]
                    print 'user_test'
                    print user_test[user]'''
                #print 'train '+ str(user1)+' '+'test '+ str(user)
                sim=cosine_sim(user_train[user1],user_test[user],IUF_train)
                dict1[user1]=sim
                dict2[user1]=abs(sim)
        sim_user[user]=dict1
        sim_userabs[user]=dict2

    reco_dict1={}
    for user in user_test:
        dict2={}
        for movie in user_test[user]:
            if user_test[user][movie]==0:
                #print user
                #print movie
                lista=sorted(sim_userabs[user].items(),key=itemgetter(1), reverse=True)
                #print lista
                count=0
                topklist=[]
                for user1,sim in lista:
                    #print user1
                    #print movie
                    #print 'user'+str(user)
                    if user_train[user1][movie]!=0:
                        topklist.append(user1)
                        count=count+1
                        if count==k:
                            break

                rating=reco_cosine(user,movie,user_train,user_test,topklist,sim_user,user_avg,k)
                #print rating

                a=int(rating)
                #a=int(round(rating))
                #if a==0:
                #   a=1
                dict2[movie]=a
        #reco_dict[user]=dict2
        reco_dict1[user]=dict2

    #print reco_dict[205]

    return reco_dict1

#recommender(user_train,user_test,3)

 #user_train, user_test,k


"""Add a container environment to a dataset"""

__docformat__ = 'restructuredtext'

import re
import logging
import os.path as op
from simplejson import loads

from datalad.interface.base import Interface
from datalad.interface.base import build_doc
from datalad.support.param import Parameter
from datalad.distribution.dataset import datasetmethod, EnsureDataset
from datalad.distribution.dataset import require_dataset
from datalad.interface.utils import eval_results
from datalad.support.constraints import EnsureStr
from datalad.support.constraints import EnsureNone
from datalad.support.exceptions import InsufficientArgumentsError
from datalad.interface.results import get_status_dict
from datalad.support.network import get_local_file_url

# required bound commands
from datalad.coreapi import save

from .definitions import definitions

lgr = logging.getLogger("datalad.containers.containers_add")

def _resolve_img_url(url):
    """Takes a URL and tries to resolve it to an actual download
    URL that `annex addurl` can handle"""
    if op.exists(url):
        lgr.debug(
            'Convert local path specification into a file:// URL')
        # annex wants a real url
        url = get_local_file_url(url)
    elif url.startswith('shub://'):
        lgr.debug('Query singularity-hub for image download URL')
        import requests
        req = requests.get(
            'https://www.singularity-hub.org/api/container/{}'.format(
                url[7:]))
        shub_info = loads(req.text)
        url = shub_info['image']
    return url

def _guess_call_fmt(ds, name, url):
    """Helper to guess a container exec setup based on
    - a name (to be able to look up more config
    - a plain url to make inference based on the source location

    Should return `None` is no guess can be made.
    """
    if url is None:
        return None
    elif url.startswith('shub://'):
        return 'singularity exec {img} {cmd}'
    elif url.startswith('dhub://'):
        return 'python -m datalad_container.adapters.docker run {img} {cmd}'

@build_doc
# all commands must be derived from Interface
class ContainersAdd(Interface):
    # first docstring line is used a short description in the cmdline help
    # the rest is put in the verbose help and manpage
    """Add a container to a dataset
    """

    # parameters of the command, must be exhaustive
    _params_ = dict(
        dataset=Parameter(
            args=("-d", "--dataset"),
            doc="""specify the dataset to add the container to. If no dataset is
            given, an attempt is made to identify the dataset based on the
            current working directory""",
            constraints=EnsureDataset() | EnsureNone()
        ),
        name=Parameter(
            args=("name",),
            doc="""The name to register the container under. This also
                determines the default location of the container image
                within the dataset.""",
            metavar="NAME",
            constraints=EnsureStr(),
        ),
        url=Parameter(
            args=("-u", "--url"),
            doc="""A URL (or local path) to get the container image from. If
            the URL scheme is 'shub://', the command format string will be
            auto-guessed when [CMD: --call-fmt CMD][PY: call_fmt PY] is not
            specified. For the scheme 'dhub://', the rest of the URL will be
            interpreted as the argument to 'docker pull', the image will be
            saved to the location specified by `name`, and the call format will
            be auto-guessed if not given.""",
            metavar="URL",
            constraints=EnsureStr() | EnsureNone(),
        ),

        # TODO: The "prepared command stuff should ultimately go somewhere else
        # (probably datalad-run). But first figure out, how exactly to address
        # container datasets
        call_fmt=Parameter(
            args=("--call-fmt",),
            doc="""Command format string indicating how to execute a command in
            this container, e.g. "singularity exec {img} {cmd}". Where '{img}'
            is a placeholder for the path to the container image and '{cmd}' is
            replaced with the desired command.""",
            metavar="FORMAT",
            constraints=EnsureStr() | EnsureNone(),
        ),
        image=Parameter(
            args=("-i", "--image"),
            doc="""Relative path of the container image within the dataset. If not
                given, a default location will be determined using the
                `name` argument.""",
            metavar="IMAGE",
            constraints=EnsureStr() | EnsureNone(),

        )
    )

    @staticmethod
    @datasetmethod(name='containers_add')
    @eval_results
    def __call__(name, url=None, dataset=None, call_fmt=None, image=None):
        if not name:
            raise InsufficientArgumentsError("`name` argument is required")

        ds = require_dataset(dataset, check_installed=True,
                             purpose='add container')

        # prevent madness in the config file
        if not re.match(r'^[0-9a-zA-Z-]+$', name):
            raise ValueError(
                "Container names can only contain alphanumeric characters "
                "and '-', got: '{}'".format(name))

        if not image:
            loc_cfg_var = "datalad.containers.location"
            # TODO: We should provide an entry point (or sth similar) for extensions
            # to get config definitions into the ConfigManager. In other words an
            # easy way to extend definitions in datalad's common_cfgs.py.
            container_loc = \
                ds.config.obtain(
                    loc_cfg_var,
                    where=definitions[loc_cfg_var]['destination'],
                    # if not False it would actually modify the
                    # dataset config file -- undesirable
                    store=False,
                    default=definitions[loc_cfg_var]['default'],
                    dialog_type=definitions[loc_cfg_var]['ui'][0],
                    valtype=definitions[loc_cfg_var]['type'],
                    **definitions[loc_cfg_var]['ui'][1]
                )
            image = op.join(ds.path, container_loc, name, 'image')
        else:
            image = op.join(ds.path, image)

        result = get_status_dict(
            action="containers_add",
            path=image,
            type="file",
            logger=lgr,
        )

        if call_fmt is None:
            # maybe built in knowledge can help
            call_fmt = _guess_call_fmt(ds, name, url)

        # collect bits for a final and single save() call
        to_save = []
        imgurl = url
        if url:
            imgurl = _resolve_img_url(url)
            lgr.debug('Attempt to obtain container image from: %s', imgurl)
            if url.startswith("dhub://"):
                from .adapters import docker
                from subprocess import check_call

                docker_image = url[len("dhub://"):]

                lgr.debug(
                    "Running 'docker pull %s and saving image to %s",
                    docker_image, image)
                check_call(["docker", "pull", docker_image])
                docker.save(docker_image, image)
            else:
                try:
                    # ATM gives no progress indication
                    ds.repo.add_url_to_file(image, imgurl)
                except Exception as e:
                    result["status"] = "error"
                    result["message"] = str(e)
                    yield result
            # TODO do we have to take care of making the image executable
            # if --call_fmt is not provided?
            to_save.append(image)
        # continue despite a remote access failure, the following config
        # setting will enable running the command again with just the name
        # given to ease a re-run
        if not op.lexists(image):
            result["status"] = "error"
            result["message"] = ('no image at %s', image)
            yield result
            return

        # store configs
        cfgbasevar = "datalad.containers.{}".format(name)
        if imgurl != url:
            # store originally given URL, as it resolves to something
            # different and maybe can be used to update the container
            # at a later point in time
            ds.config.set("{}.updateurl".format(cfgbasevar), url)
        # force store the image, and prevent multiple entries
        ds.config.set(
            "{}.image".format(cfgbasevar),
            op.relpath(image, start=ds.path),
            force=True)
        if call_fmt:
            ds.config.set(
                "{}.cmdexec".format(cfgbasevar),
                call_fmt,
                force=True)
        # store changes
        to_save.append(op.join(".datalad", "config"))
        for r in ds.save(
                path=to_save,
                message="[DATALAD] Configure containerized environment '{name}'".format(
                    name=name)):
            yield r
        result["status"] = "ok"
        yield result


from matplotlib.colors import ListedColormap
from Perceptron import Perceptron
from Adaline import AdalineGD
from AdalineSGD import AdalineSGD
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import operator

def plot_decision_regions(X, y, classifier, resolution=0.02):

    # setup marker generator and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')

    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
				np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    # plot class samples
    for idx, cl in enumerate(np.unique(y)):
    		plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
			alpha=0.8, c=cmap(idx),
			marker=markers[idx], label=cl)

if __name__ == "__main__":
    df=pd.read_csv('car.data')

    features = np.array([3,5])
    classifiers = []
    classinds = {}

    df = df.sample(frac=1)

    # training data
    Xtrain = df.iloc[0:1727:2, features].values
    ytrain = df.iloc[0:1727:2, 6].values

    # test data
    Xtest = df.iloc[1:1728:2, features].values
    ytest = df.iloc[1:1728:2, 6].values

    ind = 0
    for type in set(ytrain):
        classinds[type]=ind
        classinds[ind] = type
        ind+=1
        #print(type)
        ytrain_type = np.where(ytrain == type, 1, -1)
        ppn = AdalineSGD(eta=0.001, n_iter=25) # use of method
        ppn.fit(Xtrain,ytrain_type)
        classifiers.append(ppn)

    y_pred = []
    confusion_mat = np.zeros([4,4])
    for ind in range(0,Xtest.shape[0]):
        xi = Xtest[ind,:]
        scores = []
        for classifier in classifiers:
            score=classifier.predict(xi)
            scores.append(score)
        index,value = max(enumerate(scores),key=operator.itemgetter(1))
        y_pred.append(classinds[index])
        #print('predicted: %s   actual: %s' % (classinds[index],ytest[ind]))
        confusion_mat[classinds[ytest[ind]],index]+=1

    error = (y_pred != ytest).sum()
    print("Misclassified: %d" % error)
    print(confusion_mat)

    '''
    for ind in range(0,3):
        print("\n%s vs rest decision boundary" % classinds[ind])
        plot_decision_regions(Xtest, ytest, classifiers[ind], resolution=0.02)
        plt.xlabel('sepal width [cm]')
        plt.ylabel('petal width [cm]')
        plt.legend(loc='upper left')
        plt.show()
    '''


#다음과 같이 import를 사용할 수 있습니다.
#import math

def solution(scores):
    answer=0
    for i in scores:
        answer+=i
    answer=answer//len(scores)
    return answer

#아래는 테스트케이스 출력을 해보기 위한 코드입니다.
scores1 = [35, 28, 98, 34, 20, 50, 85, 74, 71, 7]
ret1 = solution(scores1)

#[실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
print("solution 함수의 반환 값은", ret1, "입니다.")

scores2 = [1, 1, 1, 1, 1]
ret2 = solution(scores2)

#[실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
print("solution 함수의 반환 값은", ret2, "입니다.")


'''
Adam Stallard
Spring Programming Contest 2017
Problem 1 - POKER
'''

from sys import stdin
from operator import itemgetter

def reform(card):
    Lmapping = {'T':10, 'J':11, 'Q':12, 'K':13, 'A':14}
    Lmapping.update({str(i):i for i in range(2, 10)})
    Rmapping = {'S':0, 'H':1, 'C':2, 'D':3}
    return (Lmapping[card[0]], Rmapping[card[1]])

def cardsort(hand):
    hand = sorted(hand, key=itemgetter(0), reverse=True)
    for i in range(1, 14):
        sames = list(j for j in range(len(hand)) if hand[j][0] == i)
        if len(sames) > 1:
            hand[min(sames):max(sames)+1] = sorted(hand[min(sames):max(sames)+1], key=itemgetter(1), reverse=True)
    return hand

def flush(hand):
    nums = set(i[0] for i in hand)
    return (len(nums) == 5) and (max(nums) - min(nums) == 4) and (len(set(i[1] for i in hand)) == 1)

def counts(hand):
    nums, cnts = list(i[0] for i in hand), {}
    for n in nums:
        cnts[n] = cnts.setdefault(n, 0) + 1
    return cnts

def four(hand):
    cnts = counts(hand)
    return any(c > 3 for c in cnts.values())

def full(hand):
    cnts = counts(hand)
    return len(cnts) == 2 and cnts[list(cnts.keys())[0]] in (2, 3)

def pairs(hand):
    cnts = counts(hand)
    return len(list(i for i in cnts.values() if i == 2)) == 2

def high(hand, i):
    return cardsort(hand)[i]

def comp(c1, c2):
    if c1[0] > c2[0]:
        return 1
    elif c1[0] < c2[0]:
        return 2
    else:
        return 0

def winner(a, b):
    for func in (flush, four, full, pairs):
        if func(a) and func(b):
            break
        elif func(a):
            return 1
        elif func(b):
            return 2
    for i in range(5):
        h1, h2 = high(a, i), high(b, i)
        win = comp(h1, h2)
        if win:
            return win
    return 0

def main():
    lines = stdin.readlines()
    n, lines = int(lines[0]), lines[1:]
    for i in range(n):
        cards = list(map(reform, lines[i].split()))
        A, B = cards[:5], cards[5:]
        win = winner(A, B)
        if not win:
            print('TIE')
        else:
            print('PLAYER {}'.format(win))

main()


import warnings

import numpy
import numpy as np
import gym
import time
from numba import autojit

ENV_NAME = 'CartPole-v1'
warnings.filterwarnings('ignore')

class ClassicMachineLearningAgent:
    """
    Author: 李昕旸
    """
    def __init__(self):
        np.random.seed(1)
        self.env = gym.make(ENV_NAME)
        self.best_reward = 0.0
        self.factors = np.random.rand(5)
        print("inited_factors", self.factors)

    def train(self):
        """
        使用爬山算法训练模型
        """
        for _ in range(10000):
            self.__hill_climbing()
            if self.best_reward >= 499:
                break

        print(self.best_reward, self.factors)
        return self.best_reward, self.factors

    def get_action(self, observation1) -> int:
        """
        在训练后调用此函数 得到决策
        :param observation1: 即 env 返回的四维向量 分别对应 小车位置 小车速度 木棍角度正弦值 木棍角度变化率
        :return: 根据训练出的模型做出的决策
        """
        return self.__get_action(observation1, factors=self.factors)

    @autojit
    def __get_action(self, observation, factors: numpy.ndarray) -> int:
        """
        用线性方程 y = ax + by + cz + dw + e 计算结果
        根据 y 的符号做出决策
        :param factors: 为一个五个浮点数的数组 分别对应上述方程的 a b c d e
        :param observation: 即 env 返回的四维向量 分别对应 小车位置 小车速度 木棍角度正弦值 木棍角度变化率
        :return: 做出的决策 0 或 1
        """

        y = factors[0] * observation[0] + factors[1] * observation[1] + factors[2] * observation[2] \
            + factors[3] * observation[3] + factors[4]
        if y >= 0.0:
            return 1
        else:
            return 0

    def __get_avg_reward_by_factors(self, factors: numpy.ndarray, show=False) -> float:
        """
        训练过程中尝试新的参数时
        调用本方法以得到 10 次 测试得分的均值
        :param factors: 测试使用的参数
        :param show: 是否绘制训练过程
        :return: 10次 游戏的得分均值
        """
        sum_reward = 0.0
        for _ in range(10):
            _observation1 = self.env.reset()
            for t in range(1000):
                if show:
                    time.sleep(0.01)
                    self.env.render()
                _action = self.__get_action(_observation1, factors=factors)
                _observation1, _reward, _done, _info = self.env.step(_action)
                sum_reward += _reward
                # print(sum_reward, action, observation, reward, done, info)
                if _done:
                    break
        return sum_reward / 10.0

    def __random_walk(self):
        """
        给现有的参数加上一个随机偏移
        :return: 返回 随机游走后的参数数组
        """
        return self.factors + np.random.normal(0, 0.2, 5)

    def __hill_climbing(self):
        cur_factors = self.__random_walk()
        cur_sum_reward = self.__get_avg_reward_by_factors(cur_factors)

        if cur_sum_reward > self.best_reward:
            self.best_reward = cur_sum_reward
            self.factors = cur_factors
            print(self.best_reward)

if __name__ == '__main__':
    agent = ClassicMachineLearningAgent()
    agent.train()
    env = gym.make(ENV_NAME)
    for i in range(3):
        obs = env.reset()
        sum_reward = 0.0
        while True:
            time.sleep(0.01)
            env.render()
            action = agent.get_action(obs)
            obs, reward, done, info = env.step(action)
            sum_reward += reward
            # print(sum_reward, action, observation, reward, done, info)
            if done:
                print(sum_reward)
                break
    env.close()
    print("end")


from sys import exit
from . import winchecker
#in this class we are defining all the general movement functions for the game
class Game:
    P1 = 'P1'
    P2 = 'P2'

    def __init__(self, board):  #function used to initially setup the game

        self.current_player = self.P1   #set the first player to move as P1
        self.board = board      #set local board to equal the input board
        self.winchecker = winchecker.WinChecker(game=self, board=self.board)  #initiate the winchecker class and pass in the current game and board
        print("Welcome to connect four! ")
        self.make_move()        #start game by calling for the first move

    def make_move(self):    #this function will be used to get user input and make the necessary changes to the board
        print("{}\n{}, you're up! ".format(self.board, self.current_player))  # ask current player to make a move
        column_choice = self.get_column_choice()    #get players move from function get_column_choice and store it
        valid_column = self.place_checker(column=column_choice) #place the piece using place_checker function with the selected column
        if not valid_column:       #make sure it is legal
            print("That column is full. Please enter a non-full column. ")  #if column is not legal, tell the user
            self.make_move()  #call make_move again in order to make the user make a legal move
            return False
        win = True if self.check_for_win() else False   #check if a player has won the game using check_for_win function
        if not win:      #if they did not win then change players and begin their turn
            self.toggle_players()
            self.make_move()
        if win:            #if a player has won then print the board and congratulate the winner
            print(self.board)
            print("\ncongratulations {}, you win!\n".format(self.current_player))

    def get_column_choice(self):    #function used to get the users move
        print("What column what you like to place your piece?\n")
        column_choice = input("Valid choices are columns 0 through 6: ")
        try:
            if column_choice == "exit": exit()   #if player hits exit then quit
            column_choice = int(column_choice)  #otherwise store the column they chose
            return column_choice if 0 <= column_choice <= 6 else self.get_column_choice()   #if the user chose a location outside the board then get new input
        except ValueError:  #if player entered incorrect character then restart function
            return self.get_column_choice()

    def place_checker(self, column):    #this function will find the location for the piece the user has placed and put a piece there
        print("You've selected column {}".format(column))      #tell the player what column they selected
        if(self.board.board[0][column] != ' . '):   #check to see if that column is full
            # column is full, force player to re-choose
            return False
        lowest_available_row = self.find_lowest_row_in_column(column=column)    #find the lowest position in the chosen column
        try:
            self.board.board[lowest_available_row][column] = self.players_piece()   #place the players piece in that position
            return True
        except IndexError:   #just in case there is a array error we can catch it
            # this should never happen
            print("Array out of bounds error! Exiting...")
            exit()

    def find_lowest_row_in_column(self, column):    #this function actually finds the next location in the selected column
        column_as_list = []
        for row in self.board.board:    #loop through all the rows in the board
            column_as_list.append(row[column])  #add all these values to the array
        try:
            first_red = column_as_list.index(self.board.RED) - 1 #find location above first red piece in the column
        except ValueError:
            first_red = None    #set it to none if there are no red pieces
        try:
            first_blue = column_as_list.index(self.board.BLUE) - 1  #find the location above first blue piece in the column
        except ValueError:
            first_blue = None   #set it to none if there are no blue pieces

        if first_blue == None and first_red == None:
            return 5       #if there are no pieces in the column then our row value is 5
        elif first_blue == None or first_red == None:
            return first_blue if first_blue != None else first_red   # if there is only one colour then send the location above the highest one
        else:
            return min(first_blue, first_red)   #if there are two colours then send the location above the highest piece

    def check_for_win(self):    #this function simply checks to see if there is a winner using the winchecker class
        return self.winchecker.check_for_win()

    def toggle_players(self):   #this function changes which player's turn it is
        self.current_player = self.P2 if self.current_player == self.P1 else self.P1

    def players_piece(self):    #this function returns the colour of the current players pieces
        return self.board.RED if self.current_player == self.P1 else self.board.BLUE


import sys
from cpprb import ReplayBuffer
import numpy as np

print(sys.path)

from torch.optim import Adam
from torch.nn import Parameter

from adabelief_pytorch import AdaBelief

import gym
import safety_gym
from safety_gym.envs.engine import Engine

from utils import *
from ppo_algos import *
from agent_types import *

import wandb
# wandb.login()

# wandb.init(project=PROJECT_NAME)

from train_expert_ppo import *

# Experimentation
# We have two experimentation options: Experiment Grid and wandb hyperparameter sweep
#  128, 128, 128, 128

hyperparameter_defaults = dict(
    # hid = 64,
    # l = 2,
    gamma = 0.99,
    cost_gamma = 0.99,
    seed = 0,
    cost_lim = 10,
    steps = 4000,
    epochs = 50,
    cpu=2
    )

sweep_config = {
  "name": "Training Steps Sweep",
  # "method": "grid",  # think about switching to bayes
    "method": "bayes",
    "metric": {
        "name": "reward rate",
        "goal": "maximize"
    },
  "parameters": {
        "hid": {
            "values": [128]
        },
        "l": {
            "values" : [2, 4]
        },

        "gamma": {
            "values" : [0.98, 0.985]
        },

      "lam": {
          "values": [0.97, 0.98]
      },
    "steps": {
          "values": [4000, 8000]
      },
        # "cost_gamma": {
        #     "values" : [0.98, 0.985, 0.99, 0.995]
        # },
        # "cost_lim": {
        #     "values" : [0, 10, 25, 40]
        #     # "min" : 0,
        #     # "max" : 25
        # },
      # "penalty_lr" : {
      #     "min" : 5e-3,
      #     "max" : 5e-2
      # }
    }
}

exp_name = 'exp0'
PROJECT_NAME = 'penalized-ppo-agent-sweep'

def safe_ppo_train():
    run = wandb.init(project=PROJECT_NAME, config=hyperparameter_defaults)
    # print("new seed: ", run.config.seed)

    # mpi_fork(run.config.cpu)
    logger_kwargs = setup_logger_kwargs(exp_name, run.config.seed)

    ppo(lambda: gym.make('Safexp-PointGoal1-v0'),
        actor_critic=MLPActorCritic,
        agent=PPOAgent(),
        ac_kwargs=dict(hidden_sizes=[run.config.hid] * run.config.l),
        seed=0,
        steps_per_epoch=run.config.steps,
        epochs=run.config.epochs,
        max_ep_len=1000,
        # Discount factors:
        gamma=run.config.gamma,
        lam=run.config.lam,
        cost_lam=0.97,
        # Policy Learning:
        ent_reg=0.,
        # Cost constraints / penalties:
        cost_lim=10,
        penalty_init=1.,
        # penalty_lr=run.config.penalty_lr,
        penalty_lr=0.005,
        # KL divergence:
        target_kl=0.01,
        # Value learning:
        vf_lr=1e-3,
        train_v_iters=80,
        # Policy Learning:
        pi_lr=3e-4,
        train_pi_iters=80,
        # Clipping
        clip_ratio=0.2,
        logger_kwargs=logger_kwargs,
        save_every=10)
    print("config:", dict(run.config))

sweep_id = wandb.sweep(sweep_config, entity="feloundou", project=PROJECT_NAME)
wandb.agent(sweep_id, function= safe_ppo_train)

wandb.finish()

#
# here are some okay params
# penalty lr:  0.005
# cost limit:  25
# gamma:  0.99
# cost gamma 0.99
# seed:  0

# Look at https://wandb.ai/feloundou/penalized-ppo-agent-sweep/sweeps/ikgcj25k/table?workspace=user-feloundou for some
# promising setups.
# scarlet-sweep in the training steps sweep is one of my guiding principles for now
# penalty lr: 0.005
# cost limit: 10
# gamma: 0.985
# lam : 0.98
# seed : 0
# training steps: 8000
# layers: 128 x 2

# cost gamma does not really do anything


from django.contrib import admin
from django.forms.models import BaseInlineFormSet

from adminsortable2.admin import SortableAdminMixin
from django_2gis_maps.admin import DoubleGisAdmin

from apps.brand.models import (
    Brand, BrandImage, Filial, FilialImage, FilialPhone, WorkTime
)
from apps.brand.service import WorkDayService

class ImageInlineFormSet(BaseInlineFormSet):
    """
    This formset class is for check main image count
    max count of main image is equal to 1
    """
    def clean(self):
        super(ImageInlineFormSet, self).clean()
        main_photo_count = 0
        for form in self.forms:
            is_main_image = (
                form.cleaned_data and not form.cleaned_data.get('DELETE') and
                form.cleaned_data['is_main']
            )

            if is_main_image:
                main_photo_count += 1

            if main_photo_count > 1 and form.cleaned_data['is_main']:
                form.add_error(
                    'is_main',
                    'Допускается только одно изображение, как основное'
                )

        if self.forms and not main_photo_count:
            self.forms[0].add_error(
                'is_main',
                'Хотя бы одно изображение должно быть, как основное'
            )

class NumberInlineFormSet(BaseInlineFormSet):
    """
    This formset class is for check number
    """
    def clean(self):
        super(NumberInlineFormSet, self).clean()
        for form in self.forms:
            is_valid_number_object = (
                form.cleaned_data and not form.cleaned_data.get('DELETE') and (
                    form.cleaned_data['is_phone'] or
                    form.cleaned_data['is_whatsapp']
                )
            )

            if not is_valid_number_object:
                form.add_error(
                    'is_phone',
                    'У номера должна быть включена хотя бы одна функция'
                )
                form.add_error(
                    'is_whatsapp',
                    'У номера должна быть включена хотя бы одна функция'
                )

class WorkTimeInline(admin.TabularInline):
    model = WorkTime
    can_delete = False
    fields = ['day', 'start_work', 'end_work']
    readonly_fields = ['day']

    def has_add_permission(self, request, obj=None):
        return False

class BrandImageAdmin(admin.TabularInline):
    model = BrandImage
    extra = 0

@admin.register(Brand)
class BrandAdmin(SortableAdminMixin, admin.ModelAdmin):
    inlines = (BrandImageAdmin,)
    list_display = ('position', 'title', 'address', 'link',)
    list_display_links = ['title']
    search_fields = ['title']

class FilialImageAdmin(admin.TabularInline):
    model = FilialImage
    extra = 0
    formset = ImageInlineFormSet

class FilialPhoneAdmin(admin.TabularInline):
    model = FilialPhone
    extra = 0
    formset = NumberInlineFormSet

@admin.register(Filial)
class FilialAdmin(SortableAdminMixin, DoubleGisAdmin):
    inlines = (FilialImageAdmin, FilialPhoneAdmin, WorkTimeInline)
    list_display = ('position', 'title', 'address',)
    list_display_links = ['title']
    search_fields = ['title']

    def get_inline_instances(self, request, obj=None):
        inline_instances = []
        try:
            work_time_obj = obj.works_time.all()
            if work_time_obj:
                pass
            else:
                WorkDayService.create_weekday(obj)

        except Exception:
            pass

        for inline_class in self.inlines:
            inline = inline_class(self.model, self.admin_site)
            if request:
                inline_has_add_permission = inline._has_add_permission(request,
                                                                       obj)
                if not (inline.has_view_or_change_permission(request, obj) or
                        inline_has_add_permission or
                        inline.has_delete_permission(request, obj)):
                    continue
                if not inline_has_add_permission:
                    inline.max_num = 0
            inline_instances.append(inline)

        return inline_instances


'''
문제 : 연속합 (1912번)
난이도 : 실버2

점화식 (인터넷 서치함,,,)
: dp[n] = max(dp[n-1]+ arr[n], arr[n])

- 직전까지의 연속합 dp[n-1]이 양수인 경우에는 n번째 원소(arr[n])까지 더한 값이 최댓값
- 직전까지의 연속합이 음수인 경우에는 n번째 원소만 있는 경우가 최댓값

점화식에 맞는 코드를 작성해보자~

dp는 정말 점화식만 잘 찾으면 엄청 쉬워진다!
근데 점화식 찾기가 너무 어렵다ㅜㅜ
'''
import sys
n = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.readline().split()))

dp = [0] * n
dp[0] = arr[0]

for i in range(1, n):
    dp[i] = max(dp[i-1]+arr[i], arr[i])
print(max(dp))


from django.urls import path
from lpzx import views as view
from django.conf.urls import url

from .views import (
    Detail_View,
    List_View,
    Create_View,
    Update_View,
    Delete_View,
    Date_View,
    Date_New_View,
    download
    )

app_name = "lpzx"
urlpatterns = [
    path('', List_View.as_view(),name='lpzx-list'),
    path('create/', Create_View.as_view(),name='lpzx-create'),
    path('<int:id>/', Detail_View.as_view(),name='lpzx-detail'),
    path('<int:id>/update/', Update_View.as_view(),name='lpzx-update'),
    path('<int:id>/delete/', Delete_View.as_view(),name='lpzx-delete'),
    path('date/', Date_View,name='lpzx-date'),
    path('date_view/', Date_New_View,name='lpzx-date-view'),
    url(r'^ajax_handler/$', view.ajax_handler),
    url(r'^download/',view.download,name="download"),
    url(r'^$', view.index),

#
]


# Copyright (c) 2016, System Engineering Software Society
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the System Engineering Software Society nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.
# IN NO EVENT SHALL SYSTEM ENGINEERING SOFTWARE SOCIETY BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
The Table data type includes an additional container, besides the data
container, for storing attributes. An attribute is stored as a scalar value
together with a header.

The standard library contains two nodes for setting and getting Table
attributes.
"""
import numpy as np

from sympathy.api import node as synode
from sympathy.api import table
from sympathy.api.nodeconfig import Port, Ports, Tag, Tags

def get_table_attributes(in_table, out_table):
    """Add table attribute in in_table as column in out_table."""
    for key, value in in_table.get_table_attributes().items():
        out_table.set_column_from_array(key, np.array([value]))

def set_table_attributes(attr_table, out_table):
    """Update table attributes in out_table with the content of attr_table."""
    new_attr = {}
    for key in attr_table.column_names():
        new_attr[key] = attr_table.get_column_to_array(key)[0]

    out_attr = out_table.get_table_attributes()
    out_attr.update(new_attr)
    out_table.set_table_attributes(out_attr)

def set_column_attributes(attr_table, out_table, parameters):
    """Update column attributes in out_table with the content of attr_table."""
    names = attr_table.get_column_to_array(
        parameters['columns'].list[parameters['columns'].value[0]])
    attrs = attr_table.get_column_to_array(
        parameters['attributes'].list[parameters['attributes'].value[0]])
    values = attr_table.get_column_to_array(
        parameters['values'].list[parameters['values'].value[0]])

    for name in set(names):
        if out_table.has_column(name):
            mask = names == name
            data_attributes = out_table.get_column_attributes(name)

            new_attributes = {
                attr: value for attr, value in zip(
                    attrs[mask], values[mask])}

            data_attributes.update(new_attributes)
            out_table.set_column_attributes(name, data_attributes)

def get_column_attributes(in_table, out_table):
    """Add column attributes in in_table as data in out_table."""
    part_tables = []
    for column in in_table.column_names():
        part_table = table.File()
        part_table.set_column_from_array(
            'Column names', np.array([column]))
        for key, value in in_table.get_column_attributes(column).items():
            part_table.set_column_from_array(
                'Attribute names', np.array([key]))
            part_table.set_column_from_array(
                'Attribute values', np.array([value]))

        part_tables.append(part_table)

    out_table.vjoin(part_tables)

class SuperNodeAttributes(synode.Node):
    author = 'Daniel Hedendahl <daniel.hedendahl@combine.se>'
    copyright = '(C) 2016 System Engineering Software Society'
    version = '1.0'
    tags = Tags(Tag.DataProcessing.TransformMeta)

class GetColumnAttributesTable(SuperNodeAttributes):
    name = 'Get column attributes in Table'
    description = 'Get column attributes in Table.'
    nodeid = 'org.sysess.sympathy_course.getcolumnattributestable'

    inputs = Ports([
        Port.Table('Input Data', name='data')])
    outputs = Ports([
        Port.Table('Attributes', name='attributes')])

    def execute(self, node_context):
        in_table = node_context.input[0]
        out_table = node_context.output[0]
        get_column_attributes(in_table, out_table)

class GetColumnAttributesTables(SuperNodeAttributes):
    name = 'Get column attributes in Tables'
    description = 'Get column attributes in Tables.'
    nodeid = 'org.sysess.sympathy_course.getcolumnattributestables'

    inputs = Ports([
        Port.Tables('Input Data', name='data')])
    outputs = Ports([
        Port.Tables('Attributes', name='attributes')])

    def execute(self, node_context):
        in_tables = node_context.input[0]
        out_tables = node_context.output[0]

        for in_table in in_tables:
            out_table = table.File()
            get_column_attributes(in_table, out_table)
            out_tables.append(out_table)

class SuperNodeSetColAttributes(SuperNodeAttributes):
    parameters = synode.parameters()
    parameters.set_list(
        'columns', label='Column names', value=[0],
        description='Select column with column names',
        editor=synode.Util.combo_editor().value())
    parameters.set_list(
        'attributes', label='Attribute names', value=[0],
        description='Select column with attributes',
        editor=synode.Util.combo_editor().value())
    parameters.set_list(
        'values', label='Attribute values', value=[0],
        description='Select column with values',
        editor=synode.Util.combo_editor().value())

class SetColumnAttributesTable(SuperNodeSetColAttributes):
    """
    :Ref. nodes :ref:`Set column attributes in Tables`
    """
    name = 'Set column attributes in Table'
    description = 'Set column attributes in Table.'
    nodeid = 'org.sysess.sympathy_course.setcolumnattributestable'

    inputs = Ports([
        Port.Table(
            'Table with, at least, three column, one for column '
            'names, another for attribute names and a third for '
            'attribute values', name='attributes'),
        Port.Table('Table with data columns', name='in_data')])
    outputs = Ports([
        Port.Table('Table with updated columns attributes', name='out_data')])

    def adjust_parameters(self, node_context):
        columns = []
        parameters = node_context.parameters
        tablefile = node_context.input['attributes']
        if tablefile.is_valid():
            columns = tablefile.column_names()
        parameters['columns'].list = sorted(columns)
        parameters['attributes'].list = sorted(columns)
        parameters['values'].list = sorted(columns)

    def execute(self, node_context):
        parameters = node_context.parameters
        attr_table = node_context.input['attributes']
        data_table = node_context.input['in_data']
        out_table = node_context.output['out_data']
        out_table.update(data_table)
        set_column_attributes(attr_table, out_table, parameters)

class SetColumnAttributesTables(SuperNodeSetColAttributes):
    """
    :Ref. nodes :ref:`Set column attributes in Table`
    """
    name = 'Set column attributes in Tables'
    description = 'Set column attributes in Tables.'
    nodeid = 'org.sysess.sympathy_course.setcolumnattributestables'

    inputs = Ports([
        Port.Tables('Table with, at least, three column, one for column '
                   'names, another for attribute names and a third for '
                   'attribute values', name='attributes'),
        Port.Tables('List of Tables with data columns', name='in_data')])
    outputs = Ports([
        Port.Tables('List of Tables with updated columns attributes',
                    name='out_data')])

    def adjust_parameters(self, node_context):
        columns = []
        parameters = node_context.parameters
        tablefiles = node_context.input['attributes']
        if tablefiles.is_valid():
            if len(tablefiles) > 0:
                columns = tablefiles[0].column_names()

        parameters['columns'].list = sorted(columns)
        parameters['attributes'].list = sorted(columns)
        parameters['values'].list = sorted(columns)

    def execute(self, node_context):
        parameters = node_context.parameters
        attr_tables = node_context.input['attributes']
        data_tables = node_context.input['in_data']
        out_tables = node_context.output['out_data']

        for attr_table, data_table in zip(attr_tables, data_tables):
            out_table = table.File()
            out_table.update(data_table)
            set_column_attributes(attr_table, out_table, parameters)
            out_tables.append(out_table)

class GetTableAttributes(SuperNodeAttributes):
    name = 'Get Table attributes'
    description = 'Get Table attributes.'
    nodeid = 'org.sysess.sympathy_course.gettableattributes'

    inputs = Ports([
        Port.Table('Table with data.', name='in_data')])
    outputs = Ports([
        Port.Table(
            'Table with a single row where the columns are representing '
            'the exported attributes', name='attributes')])

    def execute(self, node_context):
        in_table = node_context.input[0]
        out_table = node_context.output[0]
        get_table_attributes(in_table, out_table)

class GetTablesAttributes(SuperNodeAttributes):

    name = 'Get Tables attributes'
    description = 'Get Tables attributes.'
    nodeid = 'org.sysess.sympathy_course.gettablesattributes'

    inputs = Ports([
        Port.Tables('Table with data', name='in_data')])
    outputs = Ports([
        Port.Tables(
            'Table with a single row where the columns are representing '
            'the exported attributes', name='attributes')])

    def execute(self, node_context):
        in_tables = node_context.input[0]
        out_tables = node_context.output[0]

        for in_table in in_tables:
            out_table = table.File()
            get_table_attributes(in_table, out_table)
            out_tables.append(out_table)

class SetTableAttributes(SuperNodeAttributes):
    """
    Set the attributes in Table with the headers and values in another Table,
    only the values on the first row.
    """
    name = 'Set Table attributes'
    description = 'Set Table attributes.'
    nodeid = 'org.sysess.sympathy_course.settableattributes'

    inputs = Ports([
        Port.Table(
            'A Table with attributes along the columns. Only the first row of '
            'the Table will be imported as attributes, due to that an '
            'attribute is defined to be a scalar value', name='attributes'),
        Port.Table('Table with data', name='in_data')])
    outputs = Ports([
        Port.Table('Table with updated attribute container', name='out_data')])

    def execute(self, node_context):
        attr_table = node_context.input['attributes']
        data_table = node_context.input['in_data']
        out_table = node_context.output['out_data']
        out_table.update(data_table)

        set_table_attributes(attr_table, out_table)

class SetTablesAttributes(SuperNodeAttributes):
    """
    Set the attributes in Tables with the headers and values in
    attribute Tables, only the values on the first row.
    """
    name = 'Set Tables attributes'
    description = 'Set Tables attributes.'
    nodeid = 'org.sysess.sympathy_course.settablesattributes'

    inputs = Ports([
        Port.Tables(
            'Table with attributes along the columns. Only the first row of '
            'the Table will be imported as attributes, due to that an '
            'attribute is defined to be a scalar value', name='attributes'),
        Port.Tables('Table with data', name='in_data')])
    outputs = Ports([
        Port.Tables(
            'Table with updated attribute container', name='out_data')])

    def execute(self, node_context):
        attr_tables = node_context.input[0]
        data_tables = node_context.input[1]
        out_tables = node_context.output[0]

        for data_table, attr_table in zip(data_tables, attr_tables):
            out_table = table.File()
            out_table.update(data_table)
            set_table_attributes(attr_table, out_table)
            out_tables.append(out_table)


from __future__ import unicode_literals

import pytest

def test_ok():
    from temboardagent.cli import cli

    @cli
    def main(argv, environ):
        assert 'TESTVALUE' in argv
        return 0xcafe

    with pytest.raises(SystemExit) as ei:
        main(argv=['TESTVALUE'])

    assert 0xcafe == ei.value.code

def test_bdb_quit():
    from temboardagent.cli import cli
    from bdb import BdbQuit

    @cli
    def main(argv, environ):
        raise BdbQuit()

    with pytest.raises(SystemExit) as ei:
        main()

    assert 1 == ei.value.code

def test_interrupt():
    from temboardagent.cli import cli

    @cli
    def main(argv, environ):
        raise KeyboardInterrupt()

    with pytest.raises(SystemExit) as ei:
        main(argv=[])

    assert 1 == ei.value.code

def test_user_error():
    from temboardagent.cli import cli
    from temboardagent.errors import UserError

    @cli
    def main(argv, environ):
        raise UserError('POUET', retcode=0xd0d0)

    with pytest.raises(SystemExit) as ei:
        main()

    assert 0xd0d0 == ei.value.code

def test_unhandled_error_prod():
    from temboardagent.cli import cli

    @cli
    def main(argv, environ):
        raise KeyError('name')

    with pytest.raises(SystemExit) as ei:
        main()

    assert 1 == ei.value.code

def test_unhandled_error_debug(mocker):
    from temboardagent.cli import cli
    pm = mocker.patch('temboardagent.cli.pdb.post_mortem')

    @cli
    def main(argv, environ):
        raise KeyError('name')

    with pytest.raises(SystemExit) as ei:
        main(environ=dict(DEBUG='y'))

    assert 1 == ei.value.code
    assert pm.called is True

def test_bootstrap(mocker):
    mocker.patch('temboardagent.cli.Application.read_file', autospec=True)
    mocker.patch('temboardagent.cli.Application.apply_config', autospec=True)
    mocker.patch('temboardagent.cli.MergedConfiguration')
    from temboardagent.cli import Application, bootstrap

    app = Application()
    app.config.temboard.configfile = 'pouet'
    app.bootstrap(args=None, environ={})

    assert repr(app)

    app = bootstrap(args=None, environ={})

    assert app.apply_config.called is True

def test_apply_config_with_plugins(mocker):
    mod = 'temboardagent.cli.'
    mocker.patch(mod + 'Postgres', autospec=True)
    mocker.patch(mod + 'Application.setup_logging', autospec=True)
    cp = mocker.patch(mod + 'Application.create_plugins', autospec=True)
    mocker.patch(mod + 'Application.update_plugins', autospec=True)
    mocker.patch(mod + 'Application.purge_plugins', autospec=True)
    from temboardagent.cli import Application

    app = Application()
    app.config_sources = dict()
    app.config = mocker.Mock(name='config')
    app.config.postgresql = dict()
    cp.return_value = ['plugin']

    app.apply_config()

    assert app.postgres
    assert app.setup_logging.called is True
    assert app.update_plugins.called is True
    assert app.purge_plugins.called is True

def test_apply_config_without_plugins(mocker):
    mod = 'temboardagent.cli.'
    mocker.patch(mod + 'Postgres', autospec=True)
    mocker.patch(mod + 'Application.setup_logging', autospec=True)
    from temboardagent.cli import Application

    app = Application(with_plugins=False)
    app.config_sources = dict()
    app.config = mocker.Mock(name='config')
    app.config.postgresql = dict()

    app.apply_config()

    assert app.postgres
    assert app.setup_logging.called is True

def test_application_specs():
    from temboardagent.cli import Application

    app = Application()
    list(app.bootstrap_specs())
    list(app.core_specs())

    app = Application(with_plugins=None)
    specs = [str(s) for s in app.core_specs()]
    assert 'temboard_plugins' not in specs

def test_app_pickle():
    from pickle import dumps as pickle, loads as unpickle
    from temboardagent.cli import Application

    empty_generator = (x for x in [])
    orig = Application(specs=empty_generator)
    orig.config.update(dict(a=1))
    copy = unpickle(pickle(orig))
    assert [] == copy.specs
    assert copy.config

def test_read_file(mocker):
    from temboardagent.cli import Application, UserError

    app = Application()
    open_ = mocker.patch('temboardagent.cli.open', create=True)
    app.read_file(mocker.Mock(name='parser'), 'pouet.conf')

    open_.side_effect = IOError()
    with pytest.raises(UserError):
        app.read_file(mocker.Mock(name='parser'), 'pouet.conf')

def test_reload(mocker):
    mocker.patch('temboardagent.cli.Application.read_file', autospec=True)
    mocker.patch('temboardagent.cli.Application.apply_config', autospec=True)

    from temboardagent.cli import Application

    app = Application()
    app.config = mocker.Mock(name='config')
    app.reload()

def test_fetch_plugin(mocker):
    iter_ep = mocker.patch('temboardagent.cli.iter_entry_points')
    from temboardagent.cli import Application

    app = Application()
    ep = mocker.Mock(name='found')
    ep.name = 'found'
    ep.load.return_value = 'PLUGIN OBJECT'
    iter_ep.return_value = [ep]

    assert 'PLUGIN OBJECT' == app.fetch_plugin(['found'])

def test_fetch_failing(mocker):
    iter_ep = mocker.patch('temboardagent.cli.iter_entry_points')
    from temboardagent.cli import Application, UserError

    app = Application()
    ep = mocker.Mock(name='ep')
    ep.load.side_effect = Exception('Pouet')
    iter_ep.return_value = [ep]

    with pytest.raises(UserError):
        app.fetch_plugin('myplugin')

def test_fetch_missing(mocker):
    iter_ep = mocker.patch('temboardagent.cli.iter_entry_points')
    from temboardagent.cli import Application, UserError

    app = Application()
    iter_ep.return_value = []

    with pytest.raises(UserError):
        app.fetch_plugin('myplugin')

def test_create_plugins(mocker):
    mocker.patch(
        'temboardagent.cli.Application.fetch_plugin', autospec=True)
    llp = mocker.patch('temboardagent.cli.load_legacy_plugins', autospec=True)
    from temboardagent.cli import Application

    app = Application()
    app.config = mocker.Mock(name='config')
    app.config.temboard.plugins = ['legacy', 'ng']

    llp.return_value = dict(legacy=dict())

    app.create_plugins()

    assert 'legacy' not in app.plugins
    assert 'legacy' in app.config.plugins
    assert 'ng' in app.plugins
    assert 'ng' not in app.config.plugins

def test_update_plugins(mocker):
    from temboardagent.cli import Application

    app = Application()

    unloadme = mocker.Mock(name='unloadme')
    old_plugins = dict(unloadme=unloadme)

    loadme = mocker.Mock(name='loadme')
    app.plugins = dict(loadme=loadme)

    app.update_plugins(old_plugins=old_plugins)

    assert loadme.load.called is True
    assert unloadme.unload.called is True

def test_purge_plugins():
    from temboardagent.cli import Application, MergedConfiguration

    app = Application()
    app.plugins = dict(destroyme=1, keepme=1)
    app.config = MergedConfiguration()
    app.config.update(dict(temboard=dict(plugins=['keepme'])))
    app.purge_plugins()
    assert 'destroyme' not in app.plugins

def test_debug_arg():
    from argparse import ArgumentParser, SUPPRESS
    from temboardagent.cli import define_core_arguments

    parser = ArgumentParser(argument_default=SUPPRESS)
    define_core_arguments(parser)

    args = parser.parse_args([])
    assert 'logging_debug' not in args

    args = parser.parse_args(['--debug'])
    assert args.logging_debug is True

    args = parser.parse_args(['--debug', 'myplugin'])
    assert 'myplugin' == args.logging_debug

def test_debug_var():
    from temboardagent.cli import detect_debug_mode

    assert not detect_debug_mode(dict())
    assert not detect_debug_mode(dict(DEBUG=b'N'))

    env = dict(DEBUG=b'1')
    assert detect_debug_mode(env) is True
    assert b'__debug__' == env['TEMBOARD_LOGGING_DEBUG']

    env = dict(DEBUG=b'mymodule')
    assert detect_debug_mode(env)
    assert b'mymodule' == env['TEMBOARD_LOGGING_DEBUG']


from tkinter import *
import calendar

window = Tk()
window.title("Calendar")
window.geometry("270x340")

def search():

    months = month.get()
    years = year.get()
    month_int = int(months)
    year_int = int(years)

    cal = calendar.month(year_int, month_int)

    textfield.delete(0.0, END)

    textfield.insert(INSERT, cal)

month_label = Label(window, text = "Select Month : ", font=('monaco', 15, 'bold'))
month_label.place(x = 10, y = 10)

month = Spinbox(window, from_ = 1, to = 12, width = 5, font=("monaco", 15, "bold"))
month.place(x = 160, y = 10)

year_label = Label(window, text = "Select Year : ", font=('monaco', 15, 'bold'))
year_label.place(x = 10, y = 50)

year = Spinbox(window, from_ = 1900, to = 2100, width = 5, font=("monaco", 15, "bold"))
year.place(x = 160, y = 50)

search_button = Button(window, text = "Search", relief=GROOVE, width=10, font=("monaco", 15, "bold"), command = search)
search_button.place(x = 70, y = 100)

textfield = Text(window, height = 10, bd = 5, width = 25, relief=GROOVE, fg = 'red')
textfield.place(x = 17, y = 150)

window.mainloop()

search()