#!/usr/bin/env python3
"""
 Open a window and clear it to a specified colour.
 Draw a rectangle in the middle with various possible
 shaders applied to it.
"""
import random
import pyglet
from pyglet.gl import *
from pyglet.window import key
import ctypes
from ctypes import byref, cast, POINTER

from shaders import Shader, ShaderProgram
import tnvmesh

SIMPLE_VSHADER = b"""
void main()
{
  gl_Position = ftransform();
  gl_TexCoord[0] = gl_MultiTexCoord0;
}
"""

GRAPHPAPER_FSHADER = b"""
uniform vec4 paper = vec4(1.0, 1.0, 0.95, 1.0);
uniform vec4 ink = vec4(0.6, 0.9, 1.0, 1.0);

void main()
{
   vec2 texgrid = fract(gl_TexCoord[0] * 10.0).st;
   if (any(lessThan(texgrid,vec2(0.1))))
      gl_FragColor = ink;
   else
      gl_FragColor = paper;
}
"""

GINGHAM_FSHADER = b"""
uniform vec4 paper = vec4(1.0);
uniform vec4 ink = vec4(1.0, 0.6, 0.6, 1.0);

void main()
{
   vec2 texgrid = fract(gl_TexCoord[0] * 10.0).st;
   float cmix = 0.0;
   if (texgrid.s < 0.5) cmix += 0.5;
   if (texgrid.t < 0.5) cmix += 0.5;
   gl_FragColor = mix(paper, ink, cmix);
}
"""

EDGES_FSHADER = b"""
uniform vec4 paper = vec4(1.0);
uniform vec4 ink = vec4(0.7, 0.7, 0.7, 1.0);

void main()
{
   vec2 dists = abs(vec4(0.5) - fract(gl_TexCoord[0])).st;
   float cmix = smoothstep(0.4, 0.5, max(dists.s, dists.t));
   gl_FragColor = mix(paper, ink, cmix);
}
"""

class Mesh:
    def __init__(self, vertexdata, indices=None, contains_texture=False, primitive=GL_TRIANGLES):
        self.bufs = (GLuint*2)()
        glGenBuffers(2, cast(self.bufs, POINTER(GLuint)))
        vbuf, ibuf = self.bufs
        self.prim = primitive
        T = GLfloat * len(vertexdata)
        data = T(*vertexdata)
        glBindBuffer(GL_ARRAY_BUFFER, vbuf)
        glBufferData(GL_ARRAY_BUFFER, len(data) * 4, byref(data), GL_STATIC_DRAW)
        self.pervertex = 3
        self.vtexture = contains_texture
        if contains_texture:
            self.pervertex = 5
        self.nvertices = len(vertexdata) // self.pervertex
        if indices is None:
            indices = range(self.nvertices)
        self.nindices = len(indices)
        T = GLushort * len(indices)
        idata = T(*indices)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(idata) * 2, byref(idata), GL_STATIC_DRAW)

    def __del__(self):
        glDeleteBuffers(2, cast(self.bufs, POINTER(GLuint)))

    def draw(self):
        glBindBuffer(GL_ARRAY_BUFFER, self.bufs[0])
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.bufs[1])
        stride = 20 if self.vtexture else 0
        glVertexPointer(3, GL_FLOAT, stride, 0)
        if self.vtexture:
            glTexCoordPointer(2, GL_FLOAT, stride, 12)
            glEnableClientState(GL_TEXTURE_COORD_ARRAY)
        glEnableClientState(GL_VERTEX_ARRAY)
        glDrawElements(self.prim, self.nindices, GL_UNSIGNED_SHORT, 0)

class TWin:
    def __init__(self, width, height, *args, **kw):
        try:
            self.bg_colour = kw["bg"]
            del kw["bg"]
        except KeyError:
            self.bg_colour = (0,0,0,1)
        w = self.win = pyglet.window.Window(width, height, *args, **kw)
        self.mesh = Mesh(
            (-0.5, -0.5, 0.0, 0.0, 0.0,
              0.5, -0.5, 0.0, 1.0, 0.0,
              0.5,  0.5, 0.0, 1.0, 1.0,
             -0.5,  0.5, 0.0, 0.0, 1.0), contains_texture=True, primitive=GL_QUADS)
#        self.mesh = tnvmesh.make_cuboid(0.5, 0.5, 0.2)
        vshader = Shader(SIMPLE_VSHADER, GL_VERTEX_SHADER)
        gingham = ShaderProgram(vshader, Shader(GINGHAM_FSHADER))
        graph = ShaderProgram(vshader, Shader(GRAPHPAPER_FSHADER))
        edges = ShaderProgram(vshader, Shader(EDGES_FSHADER))
        self.shaders = [gingham, graph, edges]
        self.shaderindex = 0
        w.set_handlers(self.on_draw, self.on_resize, self.on_key_press)

    @property
    def shadprog(self):
        return self.shaders[self.shaderindex]

    def on_resize(self, w, h):
        """ coord system from -1 to 1 with origin in the middle """
        glViewport(0, 0, w, h)
        glMatrixMode(gl.GL_PROJECTION)
        glLoadIdentity()
        glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)
        glMatrixMode(gl.GL_MODELVIEW)
        return pyglet.event.EVENT_HANDLED

    def on_key_press(self, sym, modifiers):
        """ switch shader programs and colours """
        if sym == key.SPACE:
            self.shaderindex = (self.shaderindex + 1) % len(self.shaders)
        elif sym == key.P:
            paper = [1.0, 1.0, 1.0, 1.0]
            paper[random.randint(0,2)] = 0.5 * random.random() + 0.5
            self.shadprog.set(paper=paper)
        elif sym == key.I:
            ink = [0.5, 0.5, 0.5, 1.0]
            ink[random.randint(0,2)] = random.random()
            self.shadprog.set(ink=ink)

    def on_draw(self):
        glClearColor(*self.bg_colour)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        glColor4f(1.0, 1.0, 1.0, 1.0)
        glRectf(10, 10, 20, 20)
        self.shadprog.use()
        self.mesh.draw()

if __name__ == '__main__':
    win = TWin(200,200,caption="Test",bg=(0.4, 0.2, 0.5, 1.0), resizable=True)
    pyglet.app.run()


"""
day : 0524
num : 1806
idea : 투 포인터, 부분합
ref :
"""

n, s = map(int, input().split())
tmp = list(map(int, input().split()))

# 접두사 합(Prefix Sum) 배열 계산
arr = [0]
for t in tmp:
    arr.append(t + arr[-1])

ans = 1e9
end = 0
# start를 차례대로 증가시키며 반복
for start in range(n):
    # end를 가능한 만큼 이동시키기
    # 구간 합 계산
    while arr[end] - arr[start] < s and end < n:
        end += 1
    # 부분합이 s이상일 때, 길이가 짧으면 바꿔준다.
    if arr[end] - arr[start] >= s:
        if end - start < ans:
            ans = end - start

print(ans if ans != 1e9 else 0)


'''
r=input("请输入圆的半径：")
r=int(r)
s=r*r*3.14
l=2*3.14*r
print("面积为："+str(s))
print("周长为："+str(l))
'''

  # 求绝对值
num = input("输入一个数字：")
num=float(num)
if num>=0:
    print("%s 的绝对值为：%s" %(num,num))
else:
    print("%s 的绝对值为：%s" %(num,-num))


import gym
import random
import time
import signal

import numpy as np

import rospy
from sensor_msgs.msg import Image
from gazebo_msgs.msg import ModelStates
from geometry_msgs.msg import Twist
from std_srvs.srv import Empty

import numpy as np
import matplotlib.pyplot as plt

from util import process_image, interuppt_handler

def simulate(env, q_table, alpha, epsilon, epsilon_decay):
    rewards = []
    avgrewards = []
    try:
        for episode in range(1, MAX_EPISODES):
            print("============= STARTING NEW EPISODE ===============")

            state = env.reset()
            total_reward = 0
            total_steps = 0

            if state == None:
                episode -= 1
                continue

            done = False

            while not done:
                # In the beginning, do random action to learn
                if random.uniform(0, 1) < epsilon:
                    action = env.action_space.sample()
                else:
                    action = np.argmax(q_table[state])

                next_state, reward, done, _ = env.step(action)
                total_reward += reward
                print("-----------------------------")
                print("EPISODE:", episode)
                print("STATE: ", state)
                print("NEXT STATE: ", next_state)
                print("REWARD: ", reward)
                print("TOTAL REWARD: ", total_reward)
                print("EPSILON:", epsilon)
                # print("REWARDS:", rewards)
                print("AVG REWARDS:", avgrewards)
                print("-----------------------------")

                if next_state == None:
                    next_state = env.observation_space.high

                # Q(s, a) <- (1 - α) * Q(s, a) + α * (r + γ + max(Q(s', a)))
                q_table[state][action] = (1 - alpha) * q_table[state][action] \
                                       + alpha * (reward + gamma * np.max(q_table[next_state]))

                best_actions = [np.argmax(q_table[state]) for state in range(q_table.shape[0])]
                print("Best actions:", best_actions)

                state = next_state
                total_steps += 1

            print("Episode %d finished with total reward = %f." % (episode, total_reward))
            rewards.append(total_reward/total_steps)
            avgrewards.append(np.mean(rewards[-50:]))

            if epsilon >= 0.005:
                epsilon *= epsilon_decay

            # if episode % 10 == 0:
            #     np.save("qtable-"+str(episode)+".npy", q_table)
            #     np.save("reward-"+str(episode)+".npy", np.array(rewards))

        plt.plot(np.array(avgrewards))
        plt.xlabel("No. of Episodes")
        plt.ylabel("Avg. Rewards")
        plt.show()

    except KeyboardInterrupt:
        pass

class GazeboAutoVehicleEnv():
    def __init__(self, H, W):
        self.IMAGE_TOPIC = "/vehicle_camera/image_raw"
        self.CMDVEL_TOPIC = "vehicle/cmd_vel"
        self.GZRESET_TOPIC = "/gazebo/reset_world"
        # self.GZPAUSE_TOPIC = '/gazebo/pause_physics'
        # self.GZUNPAUSE_TOPIC = '/gazebo/unpause_physics'
        self.MODEL_TOPIC = '/gazebo/model_states'

        self.H,self.W = H,W
        self.finished = False

        self.action_space = gym.spaces.Discrete(3)
        self.observation_space = gym.spaces.Box(np.array([0]),
                                            np.array([3]),
                                            dtype=np.int32)
        rospy.init_node('gym', anonymous=True)
        rospy.Subscriber(self.IMAGE_TOPIC, Image, self.image_callback)
        rospy.Subscriber(self.MODEL_TOPIC, ModelStates, self.modelstate_callback)
        self.vel_pub = rospy.Publisher(self.CMDVEL_TOPIC, Twist, queue_size=5)

        rospy.wait_for_service(self.GZRESET_TOPIC)
        self.reset_proxy = rospy.ServiceProxy(self.GZRESET_TOPIC, Empty)
        # self.pause = rospy.ServiceProxy(self.GZPAUSE_TOPIC, Empty)
        # self.unpause = rospy.ServiceProxy(self.GZUNPAUSE_TOPIC, Empty)

    def image_callback(self, img):
        state = process_image(img, True)
        if state == None:
            self.state = None
            return

        error = state * 90 * (self.W / 180)

        if error <= -20:
            self.state = 0
        elif -20 < error < 20:
            self.state = 1
        elif error >= 20:
            self.state = 2

    def modelstate_callback(self, states):
        vehicle_pose = states.pose[states.name.index("vehicle")].position
        goal_pose = states.pose[states.name.index("Mailbox")].position
        if vehicle_pose.x > goal_pose.x and vehicle_pose.y > goal_pose.y:
            print("FINISHED!")
            self.finished = True

    def step(self, action):
        self.speed = 0.3
        self.turn = 0.0
        if action == 0:
            self.turn = 0.2
        elif action == 1:
            self.speed = 0.5
        elif action == 2:
            self.turn = -0.2

        twist = Twist()
        twist.linear.x = self.speed
        twist.angular.z = self.turn

        # self.unpause()
        self.vel_pub.publish(twist)
        # self.pause()

        state = self.state
        obs = state

        print("-----------------------------")
        print("STATE:", state)
        print("ACTION:", action)
        print("-----------------------------")

        if state != None:
            done = False
            if action == self.prev_state:
                reward = 1
            else:
                reward = -1
        else:
            done = True
            reward = -1e2

        self.prev_state = state
        if self.finished:
            done = True

        return obs, reward, done, {}

    def reset(self):
        print("======================= RESETTING ==================")

        self.reset_proxy()
        self.finished = False

        # self.unpause()
        time.sleep(1)
        # self.pause()

        state = None
        while state is None:
            state = self.state

        obs = state
        self.prev_state = state

        return obs

if __name__ == "__main__":
    signal.signal(signal.SIGINT, interuppt_handler)

    env = GazeboAutoVehicleEnv(600, 800)

    MAX_EPISODES = 100
    epsilon = 1
    epsilon_decay = 0.9
    # epsilon = 0.1
    # epsilon_decay = 1
    alpha = 0.1
    gamma = 0.6
    num_box = tuple((env.observation_space.high + np.ones(env.observation_space.shape)).astype(int))
    q_table = np.zeros(num_box + (env.action_space.n,))
    print("num_box.shape:", np.array(num_box).shape)
    print("q_table.shape:", q_table.shape)
    print("num_box", num_box)
    print(env.observation_space.high, env.observation_space)

    simulate(env, q_table, alpha, epsilon, epsilon_decay)


from prints import *
from Adaugare import *
from Cautari import *
from Undo import *
apart = {}
new_list = []

def run():
    """
    Implement the UI
    """
    printMenu_lab()
    true = True
    while true:
        user = input("Selectati comanda meniu:")
        if user == "6":
            break
        global apart
        lista_comenzi = user.split(",")
        for x in lista_comenzi:
            new_list.append(x.split(" "))
        for comenzi in new_list:
            if comenzi[0] == "1" and comenzi[1] == "1":
                try:
                    curatare_stack()
                    adaugare_apartament(comenzi[2], apart)
                    add_to_stack("Apartamentul " + comenzi[2])
                    create_stiva_adaugare()
                except:
                    print("Comanda adaugari invalida!")
            elif comenzi[0] == "1" and comenzi[1] == "2":
                try:
                    curatare_stack()
                    adaugare_cheltuiala(
                        "Apartamentul " + str(comenzi[2]), comenzi[3], comenzi[4], comenzi[5], apart)
                    add_to_stack("Apartamentul " + comenzi[2])
                    add_to_stack(comenzi[3])
                    add_to_stack(comenzi[4])
                    add_to_stack(comenzi[5])
                    create_stiva_adaugare_chl()
                except:
                    print("Comanda modificari invalida!")
            elif comenzi[0] == "2":
                try:
                    curatare_stack()
                    stergere_cheltuieli(
                        "Apartamentul " + str(comenzi[2]), apart)
                    add_to_stack("Apartamentul " + str(comenzi[2]))
                    creare_stiva_sterge()
                except:
                    print("Comanda stergeri invalida!")

            elif comenzi[0] == "3":
                try:
                    print(cheltuieli_mai_mari(comenzi[2], apart))
                except:
                    print("Comanda cautari invalida!")
            elif comenzi[0] == "6" and comenzi[1] == "1":
                try:
                    s_pop()
                    apart = return_last()
                except:
                    stergeri_invalide()
            elif comenzi[0] == "6" and comenzi[1] != "1":
                print("Comanda undo invalida!")
            print(apart)

        lista_comenzi.clear()
        new_list.clear()
        print(apart)

run()


from translator.models import Translator
import speech_recognition as sr
import os
import contextlib
import wave
import math
from queue import Queue
from threading import Thread
from translator.utilities import get_audio_duration

def recognize_thread(q: Queue, result):
    while not q.empty():
        work_args_tuple = q.get()
        r = sr.Recognizer()
        _audio = sr.AudioFile(work_args_tuple[1])
        try:
            with _audio as source:
                r.adjust_for_ambient_noise(source)
                audio = r.record(
                    source, offset=work_args_tuple[0]*work_args_tuple[2], duration=work_args_tuple[2])

                # Using Google Speech Recognizer
                text = r.recognize_google(audio, language="en-GB")
                result[work_args_tuple[0]] = text
        except:
            # result[work_args_tuple[0]] = '...'
            # print(f"Failed to transcribe task {work_args_tuple[0]}")
            raise Exception(f"Failed to transcribe task {work_args_tuple[0]}")

        q.task_done()
    return True

def extract_text(object_id):
    """Transcribes audio file to text and saves it to the object"""
    # Get the object
    translator_object = Translator.objects.get(pk=object_id)

    # raise exceptions
    if not translator_object:
        raise Exception("Object not found")
    if not os.path.isfile(translator_object.source_audio.path):
        raise Exception("No source audio exists in the specified path")

    duration = 10
    audio_source_file_path = translator_object.source_audio.path
    total_duration = get_audio_duration(audio_source_file_path) / duration
    total_duration = math.ceil(total_duration)

    # Create queue
    queue = Queue(maxsize=0)
    num_theads = min(50, int(total_duration))

    # Create array to share to store transcriptions in each threads
    transcriptions_list = ['' for x in range(0, total_duration)]
    for task_index in range(0, total_duration):
        queue.put((task_index, audio_source_file_path, duration))

    # Recognize speech
    for thread_index in range(num_theads):
        worker = Thread(target=recognize_thread,
                        args=(queue, transcriptions_list))
        worker.setDaemon(True)
        worker.start()
    queue.join()

    # Joint transcriptions_list into a single string
    transcribed_text = ""
    for text in transcriptions_list:
        transcribed_text += text+" "

    # Save transcribed text to DB
    translator_object.extracted_text = transcribed_text
    translator_object.save()


"""
This file is a part of the 'Pygame Examples (pgex)' source code.
The source code is distributed under the MIT license.

The main module
"""

import asyncio

import pygame

from .colored_rectangle import ColoredRect

async def main():
    """
    Function that contains game variables and the game loop
    """
    screen = pygame.display.set_mode((600, 500))
    pygame.display.set_caption("Timer!")
    clock = pygame.time.Clock()

    colored_rect = ColoredRect(
        pos=(50, 50),
        size=(500, 400),
        colors=("lightblue", "lightblue1", "lightblue2", "lightblue3"),
    )

    # A custom event that will change the rectangle's color
    color_change_event = pygame.event.custom_type()
    # color_change_event will occur every 1000 milliseconds (1 second)
    pygame.time.set_timer(color_change_event, 1000)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                raise SystemExit
            if event.type == color_change_event:
                colored_rect.change_color()

        screen.fill("black")
        colored_rect.draw(screen)

        clock.tick(60)
        pygame.display.flip()
        await asyncio.sleep(0)

def run():
    """
    Function that runs the example
    """
    asyncio.run(main())

if __name__ == "__main__":
    run()


"""
This is the FIT2085 implementation of Binary Tree

"""
from linked_list import LinkedList
from typing import TypeVar, Generic, Callable, List
K = TypeVar('K')
I = TypeVar('I')

class BinarySearchTreeNode(Generic[K, I]):

    def __init__(self, key: K, item:I=None)->None:
        self.key = key
        self.item = item
        self.left = None
        self.right = None

    def __str__(self)->str:
        return "( " + str(self.key) + " , " + str(self.item) + " )"

class BinarySearchTree(Generic[K, I]):

    def __init__(self)->None:
        self.root = None

    def is_empty(self)->bool:
        return self.root is None

    def __len__(self):
        return self._len_aux(self.root)

    def _len_aux(self, current:BinarySearchTreeNode[K, I])->int:
        if current is None:
            return 0
        else:
            return 1+ self._len_aux(current.left) + self._len_aux(current.left)

    # def find(self, key:K)->bool:
    #     return self.find_aux(self.root, key)

    def find_aux(self, current: BinarySearchTreeNode[K, I], key, K)->bool:
        if current is None:
            return False
        elif current.key == key:
            return True
        elif key < current.key:
            return self.find_aux(current.left, key)
        else:
            return self.find_aux(current.right, key)

    def __contains__(self, key:K):
        return self.find_aux(self.root, key)

    def __getitem__(self, key: K) -> I:
        return self.getitem_aux(self.root, key)

    def getitem_aux(self, current: BinarySearchTreeNode[K, I], key: K) -> I:
        if current is None:  # base case: empty
            raise KeyError("Key not found")
        elif key == current.key:  # base case: found
            return current.item
        elif key < current.key:
            return self.getitem_aux(current.left, key)
        else:  # key > current.key
            return self.getitem_aux(current.right, key)

    def __setitem__(self, key: K, item: I) -> None:
        self.root = self.insert_aux(self.root, key, item)

    def insert_aux(self, current: BinarySearchTreeNode[K, I], key: K, item: I) -> None:
        if current is None:  # base case: at the leaf
            current = BinarySearchTreeNode(key, item)
        elif key < current.key:
            current.left = self.insert_aux(current.left, key, item)
        elif key > current.key:
            current.right = self.insert_aux(current.right, key, item)
        else:  # key == current.key
            current.item = item
        return current

    def height(self):
        return self.height_aux(self.root)

    def height_aux(self, current: BinarySearchTreeNode[K,I]):
        if current is None:
            return 0
        else:
            return 1 + max(self.height_aux(current.left), self.height_aux(current.right))

    def is_leaf(self, node: BinarySearchTreeNode[K,I])->bool:
        return node.left is None and node.right is None

    def get_leaves(self) -> LinkedList:
        a_list = LinkedList(len(self))
        self.get_leaves_aux(self.root, a_list)
        return a_list

    def get_leaves_aux(self, current: BinarySearchTreeNode[K, I], a_list: LinkedList) -> None:
        if current is not None:
            if self.is_leaf(current):
                a_list.append(current.item)
            else:
                self.get_leaves_aux(current.left, a_list)
                self.get_leaves_aux(current.right, a_list)

    def sum_leaves(self)->int:
        return self.sum_leaves_aux(self.root)

    def sum_leaves_aux(self, current:BinarySearchTreeNode[K,I])->int:
        if current is None:
            return 0
        elif self.is_leaf(current):
            return current.item
        else:
            return self.sum_leaves_aux(current.left) + self.sum_leaves_aux(current.right)

    def in_between(self, a: K, b:K)->List[I]:
        lst=[]
        self.in_between_aux(self.root, a,b,lst)
        return lst

    def in_between_aux(self, current: BinarySearchTreeNode[K,I], a: K, b:K, lst:List[I])->None:
        if current is not None:
            if current.key > a:
                self.in_between_aux(current.left,a,b,lst)
            # if current.key > a and current.key < b:
            if a <=  current.key <= b:
                lst.append(current.item)
            if current.key < b:
                self.in_between_aux(current.right,a,b,lst)

    def pre_order(self, f:Callable)->None:
        self.pre_order_aux(self.root, f)

    def pre_order_aux(self, current: BinarySearchTreeNode[K, I], f:Callable)->None:
        if current is not None:
            f(current.item)
            self.pre_order_aux(current.left)
            self.pre_order_aux(current.right)

    def k_largest(self,k:int)->I:
        lst = []
        self.k_largest_aux(self.root, k, lst)
        return lst[-1]

    def k_largest_aux(self, current: BinarySearchTreeNode[K,I],k,lst)->None:
        if current is not None:
            print(current.item)
            self.k_largest_aux(current.right,k,lst)
            if len(lst) < k:
                lst.append(current.item)
                self.k_largest_aux(current.left,k,lst)

    def find_min(self)->K:
        if self.root is None:
            return None
        else:
            return self.find_min_aux(self.root)

    def find_min_aux(self, current:BinarySearchTreeNode[K,I])->K:
        if current.left is None:
            return current.key
        else:
            self.find_min_aux(current.left)

if __name__=="__main__":
    b = BinarySearchTree()
    b[5] = 5
    b[1] = 1
    b[9] = 9
    b[8] = 8
    b[3] = 3
    b[4] = 4
    b[2] = 2
    b[10] = 10
    b[7] = 7
    b[6] = 6
    print("---", b.k_largest(3))


import random
from assignment7.helpers import train_test_split, mean, standard_deviation
from assignment7.dataset import Dataset
from assignment7.rbf import RBF
from assignment7.realization import Realization
from assignment7.scores import Scores, RegressionScores
from assignment7.normalizer import Normalizer

# Import plotting modules, if they're available
try:
    from assignment7.plot_helper import plot_decision_surface, plot_regression_surface
    import matplotlib.pyplot as plt
    plotting_available = True
except ModuleNotFoundError:
    plotting_available = False

def select_hyper_parameters(dataset, k=5):
    random.shuffle(dataset)
    fold_size = int(len(dataset) / k)

    hidden_layers = list(range(2, 70))
    results = list()

    for num_hidden in hidden_layers:
        # for sigma in sigmas:
        realizations = list()
        for i in range(k):
            test_start = i * fold_size
            test_end = (i + 1) * fold_size

            # Make training and test sets
            training_set = list()
            test_set = list()
            for j in range(len(dataset)):
                if j < test_start or j >= test_end:
                    training_set.append(dataset[j].copy())
                else:
                    test_set.append(dataset[j].copy())

            model = RBF(num_hidden=num_hidden, regression=False)
            model.train(training_set)

            d = list()
            y = list()

            # Validate the model
            for row in test_set:
                d.append(row[-1])
                y.append(model.predict(row[:-1]))

            realization = Realization(training_set, test_set, None, Scores(d, y), None)
            realizations.append(realization)

        accuracies = list(map(lambda r: r.scores.accuracy, realizations))
        mean_accuracy = mean(accuracies)
        print(
            "Hidden: {}     Accuracy: {:.2f}%".format(
                num_hidden, mean_accuracy * 100
            )
        )

        results.append((num_hidden, mean_accuracy))

    results = sorted(results, key=lambda r: r[1], reverse=True)
    best_hyper_parameters = results[0]
    print("\n\n>>> Best hyper parameters:")
    print("Hidden: {}     Accuracy: {:.2f}%".format(best_hyper_parameters[0], best_hyper_parameters[1] * 100))

def evaluate(model, dataset, normalize=True, regression=False, ratio=0.8, num_realizations=20):
    if normalize:
        normalizer = Normalizer()
        normalizer.fit(dataset)
        if regression:
            normalized_dataset = [normalizer.normalize(row) for row in dataset]
        else:
            normalized_dataset = [normalizer.normalize(row[:-1]) + [row[-1]] for row in dataset]
    else:
        normalized_dataset = dataset

    realizations = list()
    for i in range(0, num_realizations):
        # Train the model
        training_set, test_set = train_test_split(normalized_dataset, ratio, shuffle=True)
        model.train(training_set)

        d = list()
        y = list()

        # Test the model
        for row in test_set:
            d.append(row[-1])
            y.append(model.predict(row[:-1]))

        # Caching realization values
        if regression:
            realization = Realization(training_set,
                                      test_set,
                                      model.xi_t,
                                      model.sigmas,
                                      model.weights,
                                      RegressionScores(y, d))
            print("Realization {}: {:.5f}".format(i + 1, realization.scores.rmse))
        else:
            realization = Realization(training_set,
                                      test_set,
                                      model.xi_t,
                                      model.sigmas,
                                      model.weights,
                                      Scores(d, y))
            print("Realization {}: {:.2f}%".format(i + 1, realization.scores.accuracy * 100))
        realizations.append(realization)

    if regression:
        # Sort realizations by mse
        realizations = sorted(realizations, key=lambda r: r.scores.mse)

        # MSE Stats
        mses = list(map(lambda r: r.scores.mse, realizations))
        avg_mse = mean(mses)
        std_mse = standard_deviation(mses)
        print("MSE: {:.5f} ± {:.5f}".format(avg_mse, std_mse))

        # RMSE Stats
        rmses = list(map(lambda r: r.scores.rmse, realizations))
        avg_rmse = mean(rmses)
        std_rmse = standard_deviation(rmses)
        print("RMSE: {:.5f} ± {:.5f}".format(avg_rmse, std_rmse))

        # Realization whose mse is closest to the mean
        avg_realization = sorted(realizations, key=lambda r: abs(avg_mse - r.scores.mse))[0]

        # Plot decision surface
        if len(dataset[0][:-1]) == 1 and plotting_available:
            # Set models with the "mean weights"
            model.xi_t = avg_realization.xi_t
            model.sigmas = avg_realization.sigmas
            model.weights = avg_realization.weights
            plot_regression_surface(model,
                                    avg_realization.training_set + avg_realization.test_set,
                                    x_label="X",
                                    y_label="Y",
                                    scatter_label='Base de dados',
                                    model_label='Predição do modelo',
                                    title="Regression surface")
    else:
        # Accuracy Stats
        accuracies = list(map(lambda r: r.scores.accuracy, realizations))
        mean_accuracy = mean(accuracies)
        std_accuracy = standard_deviation(accuracies)
        print("Accuracy: {:.2f}% ± {:.2f}%".format(mean_accuracy * 100, std_accuracy * 100))

        # Realization whose accuracy is closest to the mean
        avg_realization = sorted(realizations, key=lambda r: abs(mean_accuracy - r.scores.accuracy))[0]

        print("Confusion matrix")
        avg_realization.scores.print_confusion_matrix()

        # Plot decision surface
        if len(dataset[0][:-1]) == 2 and plotting_available:
            # Set models with the "mean weights"
            model.xi_t = avg_realization.xi_t
            model.sigmas = avg_realization.sigmas
            model.weights = avg_realization.weights
            plot_decision_surface(model,
                                  normalized_dataset,
                                  title="Superfície de Decisão",
                                  xlabel="X1",
                                  ylabel="X2")

# Dataset descriptors (lazy loaded)
# Artificial
artificial_dataset = Dataset("assignment7/datasets/artificial.csv")

# Iris
iris_dataset = Dataset("assignment7/datasets/iris.csv")

# Vertebral column
column_dataset = Dataset("assignment7/datasets/vertebral-column.csv")

# Dermatology
dermatology_dataset = Dataset("assignment7/datasets/dermatology.csv")

# Breast Cancer
breast_cancer_dataset = Dataset("assignment7/datasets/breast-cancer.csv")

# Artificial
artificial_regression_dataset = Dataset("assignment7/datasets/artificial-regression.csv", regression=True)

# Abalone
abalone_dataset = Dataset("assignment7/datasets/abalone.csv", regression=True)

# Car
car_dataset = Dataset("assignment7/datasets/car.csv", regression=True)

# Motor
motor_dataset = Dataset("assignment7/datasets/motor.csv", regression=True)

# Best hyper parameter found using grid search with k-fold cross validation
hyper_parameters = {
    'artificial': (artificial_dataset, False, 10),
    'iris': (iris_dataset, False, 20),
    'column': (column_dataset, False, 40),
    'dermatology': (dermatology_dataset, False, 49),
    'breast_cancer': (breast_cancer_dataset, False, 2),
    'artificial_regression': (artificial_regression_dataset, True, 8),
    'abalone': (abalone_dataset, True, 20),
    'car': (car_dataset, True, 30),
    'motor': (motor_dataset, True, 20),
}

# Select best hyper parameters
# datasets = ['artificial', 'iris', 'column', 'dermatology', 'breast_cancer']
# for ds in datasets:
#     print(">>>>>>>>>>>>>> {}".format(ds))
#     dataset, _, _, _ = hyper_parameters['artificial']
# select_hyper_parameters(dermatology_dataset.load())
#     print("\n\n\n\n\n")

dataset, regression, hidden_layers = hyper_parameters['artificial']

split_ratio = 0.8
num_realizations = 20

print("Dataset: {}".format(dataset.filename))
print("Hidden Layers: {}".format(hidden_layers))
model = RBF(num_hidden=hidden_layers, regression=regression)
evaluate(model,
         dataset.load(),
         normalize=not regression,
         regression=regression,
         ratio=split_ratio,
         num_realizations=num_realizations)

print("Done!")


import sympy
x, y = sympy.symbols('x y')
func1 = x**2
func2 = sympy.sin(x)
func3 = sympy.cos(x)
integral1 = sympy.integrate(func1, (x, 0, y), (y, 0, 1))
integral2 = sympy.integrate(func2, (x, 0, y), (y, 0, 1))
integral3 = sympy.integrate(func3, (x, 0, y), (y, 0, 1))
print("Integral of x^2:", integral1)
print("Integral of sin(x):", integral2)
print("Integral of cos(x):", integral3)


'''
The sieve of Eratosthenes is a simple algorithm for finding all prime numbers up to a specified integer. It was created by the ancient Greek mathematician Eratosthenes.
The algorithm to find all the prime numbers less than or equal to a given integer n:

    Create a list of integers from two to n: 2, 3, 4, ..., n
    Start with a counter i set to 2, i.e. the first prime number
    Starting from i+i, count up by i and remove those numbers from the list, i.e. 2*i, 3*i, 4*i, aso..
    Find the first number of the list following i. This is the next prime number.
    Set i to the number found in the previous step
    Repeat steps 3 and 4 until i is greater than n. (As an improvement: It's enough to go to the square root of n)
    All the numbers, which are still in the list, are prime numbers
'''
from math import sqrt

def sieve(n):
	# returns all primes between 2 and n
	primes = list(range(2,n+1))
	max = sqrt(n)
	num = 2
	while num < max:
		i = num
		while i <= n:
			i += num
			if i in primes:
				primes.remove(i)
		for j in primes:
			if j > num:
				num = j
				break
	return primes

num = int(input("The below program will display the first N prime numbers\nEnter a number N:"))
print(sieve(num))


# -*- coding: utf-8 -*-
from Carac import *
from Textes.ReadTextes import *
from Functions import *
import string
class PartialFormatter(string.Formatter):
    def __init__(self, missing=' ', bad_fmt=' '):
        self.missing, self.bad_fmt=missing, bad_fmt

    def get_field(self, field_name, args, kwargs):
        # Handle a key not found
        try:
            val=super(PartialFormatter, self).get_field(field_name, args, kwargs)
            # Python 3, 'super().get_field(field_name, args, kwargs)' works
        except (KeyError, AttributeError):
            val=None,field_name
        return val

    def format_field(self, value, spec):
        # handle an invalid format
        #if value==None: return self.missing
        if value==None: value=" "
        try:
            return super(PartialFormatter, self).format_field(value, spec)
        except ValueError:
            if self.bad_fmt is not None: return self.bad_fmt
            else: raise
fmt=PartialFormatter()
def xstr(s):
    return '' if s is None else str(s)

def PrintFichePerso(Perso):
    UpdateCarac(Perso)
    PersoAsDict=vars(Perso)

    print("""########################################################################################################
|_______________________________________FICHE DE PERSONNAGE____________________________________________|
|                                                                                |""")
    print(fmt.format("""| IDENTITE_____________________________________________________________________________________________|"""))

    ListIdType=[["Nom","Nom"],["Age","Age"],["Planete","Planète d'origine"],["Sexe","SexeType"],["Regne","Règne"],["Race","Race"]]
    First=True
    iLine = 0
    for id in ListIdType:

        if id[0] in PersoAsDict.keys():
            if id[0]=="Sexe":
                id[1]=Perso.SexeType
            if First:

                strL = "| {:39s}".format(id[1] + " : " + str(PersoAsDict[id[0]]))
                First=False
                continue
            else:

                strL = strL + " {:33s}".format(id[1] + " : " + str(PersoAsDict[id[0]]))
                First = True
                if Perso.Miroir:
                    strL += "|{:27s}|".format(' ')
                else :
                    strL += " {:27s}|".format(' ')
                print(strL)
                iLine += 1

    if not First:
        strL = strL + " {:33s}".format(" ")
        if Perso.Miroir:
            strL += "|{:27s}|".format(' ')
        else :
            strL += " {:27s}|".format(' ')

        print(strL)
        iLine += 1
        First=True
    if Perso.Miroir :
        while iLine < 14 :
            if iLine == 5:
                print("| {:73s}|{:^27s}|".format("", "COLLEZ"))
            elif iLine == 7:
                print("| {:73s}|{:^27s}|".format("", "VOTRE PORTRAIT"))
            elif iLine == 9:
                print("| {:73s}|{:^27s}|".format("", "ICI"))
            else:
                print("| {:73s}|{:27s}|".format("", ""))
            iLine += 1
    # if "Nom" in PersoAsDict.keys():
    #     print(fmt.format("| Nom : {Nom:50s} Planète d'origine : {Planete:22s} |",**PersoAsDict))
    # print(fmt.format("| Règne : {Regne:25s}   Race : {Race:18s}                                       |",**PersoAsDict))

    # if "Age" in PersoAsDict.keys():
    #     StrAge="| Age : {:10s} ".format(str(PersoAsDict["Age"]))
    # else:
    #     StrAge="|       {:10s} ".format(" ")
    # if "Sexe" in PersoAsDict.keys():
    #     StrSex="                   {:12s} : {:13s}                                    |".format(Perso.SexeType,Perso.Sexe)
    # else:
    #     StrSex="                   {:12s}   {:13s}                                    |".format(" ", " ")
    # if "Age" in PersoAsDict.keys() or "Sexe" in PersoAsDict.keys():
    #     print(StrAge+StrSex)

    if not Perso.Miroir:
        print("|                                                                                |")
    if "Descr" in PersoAsDict.keys():
        print(fmt.format("""| BIOGRAPHIE __________________________________________________________________________________________|"""))
        istr=0
        strL=""
        prevBlank=False
        for sL in Perso.Descr:
            if istr==0:
                strL="| "+sL
                istr+=1
            elif istr==99:
                if prevBlank :
                    strL+="  |"
                    print(strL)
                    strL="| "+sL
                    istr=1

                elif sL==" " :
                    strL+=sL+" |"
                    print(strL)
                    strL=""
                    istr=0
                else :
                    strL+="- |"
                    print(strL)
                    strL="| "+sL
                    istr=1

            else:
                if sL==" ":
                    prevBlank=True
                else:
                    prevBlank=False

                strL+=sL
                istr+=1

        while istr<100:
            strL+=" "
            istr+=1
        strL+=" |"
        print(strL)
        print("|                                                                                |")
    if "Carac" in PersoAsDict.keys():
        print(fmt.format("""| CARACTERISTIQUES  ___________________________________________________________________________________|"""))
        ipos=0
        for c in Perso.Carac.keys():
            value=Perso.Carac[c]
            if ipos==0:
                strL="| {:25s}".format(c+" : "+str(value))
                ipos+=1
            elif ipos<3:
                strL+="{:25s}".format(c+" : "+str(value))
                ipos+=1
            else :
                strL+="{:25s} |".format(c+" : "+str(value))
                print(strL)
                ipos=0
                strL=""

        if ipos!=0:
            for ii in range(ipos,4):
                strL+="{:25s}".format(" ")
            strL+=" |".format(" ")
            print(strL)

        print("|                                                                                |")
        ipos=0

        Carac2=Perso.Carac2
        for c in Carac2:
            value=Carac2[c]
            if ipos==0:
                strL="| {:25s}".format(c+" : "+str(value))
                ipos+=1
            elif ipos<3:
                strL+="{:25s}".format(c+" : "+str(value))
                ipos+=1
            else :
                strL+="{:25s} |".format(c+" : "+str(value))
                print(strL)
                ipos=0
                strL=""

        if ipos!=0:
            for ii in range(ipos,4):
                strL+="{:25s}".format(" ")
            strL+=" |".format(" ")
            print(strL)

        print("|                                                                                |")

    if "Comp" in PersoAsDict.keys():
        print(fmt.format("""| COMPETENCES _________________________________________________________________________________________|"""))
        ListComp=dict()
        AllCompList=ReadCompList()

        for key0 in AllCompList.keys():
            print("| {:^99s}  |".format(key0," "))
            ipos=0
            for key1 in AllCompList[key0].keys():
                for compCheck in AllCompList[key0][key1].keys():
                    if compCheck in Perso.Comp.keys():
                        if key1=="langues" or key1=="mécanique":
                            strLL="{:33s}{:7s}".format(key1+" "+compCheck," niv "+str(Perso.Comp[compCheck]))
                        else:
                            strLL="{:33s}{:7s}".format(compCheck," niv "+str(Perso.Comp[compCheck]))

                        if ipos==0:
                            strL="| {:60s}".format(strLL)
                            ipos+=1
                        else :
                            strL+="{:40s} |".format(strLL)
                            print(strL)
                            ipos=0

                            strL=""

            if ipos!=0:
                for ii in range(ipos,2):
                    strL+="{:40s}".format(" ")
                strL+=" |".format(" ")
                print(strL)

    print("|______________________________________________________________________________________________________|")


from abc import ABC, abstractmethod

class _AeroSurfacePrints(ABC):
    def __init__(self, aero_surface):
        self.aero_surface = aero_surface
        return None

    def identity(self):
        """Prints the identity of the aero surface.

        Returns
        -------
        None
        """
        print(f"Identification of the AeroSurface:")
        print(f"----------------------------------")
        print(f"Name: {self.aero_surface.name}")
        print(f"Python Class: {str(self.aero_surface.__class__)}\n")
        return None

    @abstractmethod
    def geometry(self):
        pass

    def lift(self):
        """Prints the lift information of the aero surface.

        Returns
        -------
        None
        """
        print(f"Lift information of the AeroSurface:")
        print(f"-----------------------------------")
        print(
            f"Center of Pressure position in local coordinates: ({self.aero_surface.cpx:.3f}, {self.aero_surface.cpy:.3f}, {self.aero_surface.cpz:.3f})"
        )
        print(
            f"Lift coefficient derivative at Mach 0 and AoA 0: {self.aero_surface.clalpha(0):.3f} 1/rad\n"
        )
        return None

    def all(self):
        """Prints all information of the aero surface.

        Returns
        -------
        None
        """
        self.identity()
        self.geometry()
        self.lift()
        return None

class _NoseConePrints(_AeroSurfacePrints):
    """Class that contains all nosecone prints."""

    def __init__(self, nosecone):
        """Initialize the class

        Parameters
        ----------
        nosecone : rocketpy.AeroSurface.NoseCone
            Nosecone object to be printed

        Returns
        -------
        None
        """
        super().__init__(nosecone)
        return None

    def geometry(self):
        """Prints the geometric information of the nosecone.

        Returns
        -------
        None
        """
        print(f"Geometric information of NoseCone:")
        print(f"----------------------------------")
        print(f"Length: {self.aero_surface.length:.3f} m")
        print(f"Kind: {self.aero_surface.kind}")
        print(f"Base radius: {self.aero_surface.base_radius:.3f} m")
        print(f"Reference rocket radius: {self.aero_surface.rocket_radius:.3f} m")
        print(f"Reference radius ratio: {self.aero_surface.radius_ratio:.3f}\n")
        return None

class _FinsPrints(_AeroSurfacePrints):
    def __init__(self, fin_set):
        """Initialize the class

        Parameters
        ----------
        fin_set : rocketpy.AeroSurface.fin_set
            fin_set object to be printed

        Returns
        -------
        None
        """
        super().__init__(fin_set)
        return None

    def geometry(self):
        print(f"Geometric information of the fin set:")
        print(f"-------------------------------------")
        print(f"Number of fins: {self.aero_surface.n}")
        print(f"Reference rocket radius: {self.aero_surface.rocket_radius:.3f} m")
        try:
            print(f"Tip chord: {self.aero_surface.tip_chord:.3f} m")
        except AttributeError:
            pass  # it isn't a trapezoidal fin, just don't worry about tip chord
        print(f"Root chord: {self.aero_surface.root_chord:.3f} m")
        print(f"Span: {self.aero_surface.span:.3f} m")
        print(
            f"Cant angle: {self.aero_surface.cant_angle:.3f} ° or {self.aero_surface.cant_angle_rad:.3f} rad"
        )
        print(f"Longitudinal section area: {self.aero_surface.Af:.3f} m²")
        print(f"Aspect ratio: {self.aero_surface.AR:.3f} ")
        print(f"Gamma_c: {self.aero_surface.gamma_c:.3f} m")
        print(f"Mean aerodynamic chord: {self.aero_surface.Yma:.3f} m\n")
        return None

    def airfoil(self):
        """Prints out airfoil related information of the fin set.

        Returns
        -------
        None
        """
        if self.aero_surface.airfoil:
            print(f"Airfoil information:")
            print(f"--------------------")
            print(
                f"Number of points defining the lift curve: {len(self.aero_surface.airfoil_cl.x_array)}"
            )
            print(
                f"Lift coefficient derivative at Mach 0 and AoA 0: {self.aero_surface.clalpha(0):.5f} 1/rad\n"
            )
        return None

    def roll(self):
        """Prints out information about roll parameters
        of the fin set.

        Returns
        -------
        None
        """
        print(f"Roll information of the fin set:")
        print(f"--------------------------------")
        print(
            f"Geometric constant: {self.aero_surface.roll_geometrical_constant:.3f} m"
        )
        print(
            f"Damping interference factor: {self.aero_surface.roll_damping_interference_factor:.3f} rad"
        )
        print(
            f"Forcing interference factor: {self.aero_surface.roll_forcing_interference_factor:.3f} rad\n"
        )
        return None

    def lift(self):
        """Prints out information about lift parameters
        of the fin set.

        Returns
        -------
        None
        """
        print(f"Lift information of the fin set:")
        print(f"--------------------------------")
        print(
            f"Lift interference factor: {self.aero_surface.lift_interference_factor:.3f} m"
        )
        print(
            f"Center of Pressure position in local coordinates: ({self.aero_surface.cpx:.3f}, {self.aero_surface.cpy:.3f}, {self.aero_surface.cpz:.3f})"
        )
        print(
            f"Lift Coefficient derivative (single fin) at Mach 0 and AoA 0: {self.aero_surface.clalpha_single_fin(0):.3f}"
        )
        print(
            f"Lift Coefficient derivative (fin set) at Mach 0 and AoA 0: {self.aero_surface.clalpha_multiple_fins(0):.3f}"
        )
        return None

    def all(self):
        """Prints all information of the fin set.

        Returns
        -------
        None
        """
        self.identity()
        self.geometry()
        self.airfoil()
        self.roll()
        self.lift()
        return None

class _TrapezoidalFinsPrints(_FinsPrints):
    def __init__(self, fin_set):
        """Initialize the class

        Parameters
        ----------
        fin_set : rocketpy.AeroSurface.fin_set
            fin_set object to be printed

        Returns
        -------
        None
        """
        super().__init__(fin_set)
        return None

class _EllipticalFinsPrints(_FinsPrints):
    """Class that contains all elliptical fins prints."""

    def __init__(self, fin_set):
        """Initialize the class

        Parameters
        ----------
        fin_set : rocketpy.AeroSurface.fin_set
            fin_set object to be printed

        Returns
        -------
        None
        """
        super().__init__(fin_set)
        return None

class _TailPrints(_AeroSurfacePrints):
    """Class that contains all tail prints."""

    def __init__(self, tail):
        """Initialize the class

        Parameters
        ----------
        tail : rocketpy.AeroSurface.Tail
            Tail object to be printed

        Returns
        -------
        None
        """
        super().__init__(tail)
        return None

    def geometry(self):
        """Prints the geometric information of the tail.

        Returns
        -------
        None
        """
        print(f"Geometric information of the Tail:")
        print(f"----------------------------------")
        print(f"Top radius: {self.aero_surface.top_radius:.3f} m")
        print(f"Bottom radius: {self.aero_surface.bottom_radius:.3f} m")
        print(f"Reference radius: {2*self.aero_surface.rocket_radius:.3f} m")
        print(f"Length: {self.aero_surface.length:.3f} m")
        print(f"Slant length: {self.aero_surface.slant_length:.3f} m")
        print(f"Surface area: {self.aero_surface.surface_area:.6f} m²\n")
        return None

class _RailButtonsPrints(_AeroSurfacePrints):
    """Class that contains all rail buttons prints."""

    def __init__(self, rail_buttons):
        super().__init__(rail_buttons)
        return None

    def geometry(self):
        print(f"Geometric information of the RailButtons:")
        print(f"-----------------------------------------")
        print(
            f"Distance from one button to the other: {self.aero_surface.buttons_distance:.3f} m"
        )
        print(
            f"Angular position of the buttons: {self.aero_surface.angular_position:.3f} deg\n"
        )
        return None


import sys

semesterNumber = int(sys.stdin.readline().rstrip())

for i in range(semesterNumber):
    gradeSum = 0
    creditSum = 0

    subjectNumber = int(sys.stdin.readline().rstrip())

    for j in range(subjectNumber):
        credit, grade = map(float, sys.stdin.readline().rsplit())

        gradeSum += credit * grade
        creditSum += credit

    print(int(creditSum), round(gradeSum / creditSum, 1))


#!/usr/bin/env python

import argparse
import logging
import os
import sys
from pytodo.utils import options, database, misc, exceptions
from pytodo.utils.database import Base, Task, Project

# The log.
log = logging.getLogger(__name__)

engine, session = database.open_db_session()

DESCRIPTION = "Add new task to todo"

def add_task(args):
    '''
    '''
    log.info('Adding new task in project: %s', args.project)

    detail = args.detail
    status = args.status
    priority = args.priority
    project = session.query(Project).filter_by(name=args.project).first()
    deadline = args.deadline
    new_task = Task(details=detail, status=status, deadline=deadline,
            priority=priority, project=project)
    session.add(new_task)
    session.commit()

def main():
    '''
    '''
    with exceptions.log():
        # create the parser
        parser = argparse.ArgumentParser(DESCRIPTION)
        options.loglevel(parser)
        options._add_task(parser)

        # add the task
        args=parser.parse_args()
        misc.set_log_level(args.loglevel)
        add_task(args)


# -*- coding: utf-8 -*-
"""
Created on Sat Nov 24 21:28:41 2018
#program that implements a decision tree using the ID3 algorithm presented
#Read a set of attributes and print to xml file
@author: Karthik
"""
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 17 22:38:48 2018

@author: Karthik
"""
import copy
import numpy as np
import pandas as pd
import math
import argparse as ag
import os

flag = 1
treeEntropy = 0

def check_location(loc_file):
    if not os.path.exists(loc_file):
        raise ag.ArgumentTypeError("{0} does not exist".format(loc_file))
    return loc_file

def calculateEntropy(target_col,class_log):
    Entropy = 0
    value, sum1 = np.unique(target_col, return_counts=True)
    for i in range(len(value)):
        Entropy = Entropy-(float(sum1[i])/sum(sum1)) * math.log(float(sum1[i])/sum(sum1),class_log)
    return Entropy

def InformationGain(data, feature, class_log):
    global flag
    total_Entropy = calculateEntropy(data["target_class"], class_log)

    if flag == 1:
        treeEntropy = total_Entropy
    flag = 0
    #print total_Entropy
    Entropy = 0
    value, sum1 = np.unique(data[feature], return_counts=True)
  #  print total_Entropy
   # print value,feature,sum1
    sum11 = sum(sum1)
    weightedEntropy = 0
    #print value,sum1
    Entropy = [0] * len(value)
    for i in range(len(value)):
         Entropy[i] = calculateEntropy(data.where(data[feature] == value[i]).dropna()["target_class"], class_log)
         weightedEntropy = weightedEntropy + ((float(sum1[i])/sum11) * Entropy[i])
  #  print "weighted entropy",weightedEntropy
    InfoGain = total_Entropy - weightedEntropy
    #print feature,attribute_entropy
    return InfoGain

def ID3(data, original_data, remaining_attributes, class_log):
    if len(data) == 0:
        return
    elif len(np.unique(data["target_class"])) == 1:
      #  print np.unique(data["target_class"])
        #print data
        #print remaining_attributes
        print(np.unique(data["target_class"])[0])
        return np.unique(data["target_class"])[0]
    elif len(remaining_attributes) == 0:
        value, count = np.unique(data["target_class"],return_counts = True)
        print(value[np.argmax(count)])
        return value[np.argmax(count)]

    else:
        attribute_values = [InformationGain(data,feature,class_log) for feature in remaining_attributes]
        best_feature = remaining_attributes[np.argmax(attribute_values)]
        tree = {best_feature:{}}
        #remaining_attributes.remove(best_feature)

        remaining_attributes = [i for i in remaining_attributes if i != best_feature]
        for value in data[best_feature].unique():
            split_data = data.where(data[best_feature] == value).dropna()
            entropy = calculateEntropy(split_data["target_class"], class_log)
            print("<node " + " entropy= \"" + str(entropy) + "\" feature=\"" + str(best_feature) + "\" value=\"" + str(value) + "\">")

            subtree = ID3(split_data, original_data, remaining_attributes, class_log)
            print("</node>")
            tree[best_feature][value] = subtree
    return tree

def main():
    parser = ag.ArgumentParser()
    parser.add_argument("--data", help="data filename", type=check_location)
    # parser.add_argument("--output", help="output file for final decision tree")
    args = parser.parse_args()
    file_name = args.data
    data = pd.read_csv(file_name, header=None)
    list = []
    for i in range(len(data.columns)-1):
      list.append("attr"+str(i))
    required_attribute = copy.deepcopy(list)
    list.append("target_class")
    data.columns = list
    class_log = float(len(data["target_class"].unique()))
    tree_entropy = calculateEntropy(data["target_class"], class_log)
    print("<tree " + "entropy = \"" + str(tree_entropy) + "\">")
    tree = ID3(data[:][:-1], data, required_attribute, class_log)
    print("</tree>")

if __name__ == "__main__":
    main()


class Node:
    def __init__(self, key, left=None, right=None):
        self.key = key
        self.left = left
        self.right = right

class SplayTree:
    def __init__(self):
        self.root = None

    def find(self, key):
        cur = self.root
        while cur:
            if cur.key == key:
                # do splay
                return cur
            else:
                cur = cur.left if cur.key > key else cur.right
        return None

    def rotate_right(self, node):
        t = node.left
        node.left = t.right
        t.right = node
        return t

    def rotate_left(self, node):
        t = node.right
        node.right = t.left
        t.left = node
        return t

    def splay(self, root, key):
        if root.key == key:
            return root

        if root.key > key:
            if root.left.key > key:
                root.left.left = self.splay(root.left.left, key)
                root = self.rotate_right(root)
            elif root.left.key < key:
                root.left.right = self.splay(root.left.right, key)
                root.left = self.rotate_left(root.left)
            root = self.rotate_right(root)
        else:
            if root.right.key > key:
                root.right.left = self.splay(root.right.left, key)
                root.right = self.rotate_right(root.right)
            elif root.right.key < key:
                root.right.right = self.splay(root.right.right, key)
                root = self.rotate_left(root)
            root = self.rotate_left(root)
        return root

    def insert(self, key):
        cur = self.root
        prev = None
        while cur:
            prev = cur
            cur = cur.left if cur.key > key else cur.right
        node = Node(key)
        if not prev:
            self.root = node
        elif prev.key > key:
            prev.left = node
        else:
            prev.right = node
        self.root = self.splay(self.root, key)

    def __str__(self):
        stack = [self.root]
        keys = []
        while stack:
            node = stack.pop()
            if node is None:
                continue
            keys.append(node.key)
            stack.append(node.right)
            stack.append(node.left)
        return " ".join(map(str, keys))

tree = SplayTree()
tree.insert(50)
tree.insert(20)
tree.insert(10)
tree.insert(25)
tree.insert(21)
# print tree


from robotsetting import Link
from robotsetting import Circle

# add module
import os , sys
import tensorflow as tf     # py -3.6
import matplotlib
import numpy as np
import random as rd

class Configuration:
    def __init__(self):
        print("###configuration###")
        self.startpath = os.getcwd()
        self.problem = "random"
        self.ALL_mode = ["baum"]       # object for cnn ex) 研究の対象：an object of study
        self.angle_mode = ["Link1_angle","Link2_angle"]
        matplotlib.use("Agg")   # memory flash

    def setProblemenvironment(self):
        self.train_data_num = 45
        self.test_data_num = 45
        self.problem = "circle"
        # simulation environment??
        if self.problem == "circle":
            self.test_data_num = 36

    def setCompare(self):
        self.comparelist = ["_CGP","_CNN"]

    def setSR(self):
        self.Inputs = ["Link1_x","Link1_y","Link2_x","Link2_y"]
        self.Outputs = ["Link1_angle","Link2_angle"]

    def setRobotsimulation(self):
        # Simulation Experiment
        self.num_Links = 2
        self.L1 = 12
        self.L2 = 10
        self.margin = 2
        self.Link_info = [[0,self.L1],[0,self.L2]]
        self.arm_height = 0.5
        ###train###
        self.train_Links = []
        for i in range(self.num_Links):  # Sampling By Genetic Programming
            self.train_Links.append(Link(self.Link_info[i][0],self.Link_info[i][1]))
        ###test###
        self.test_Links = []
        for i in range(self.num_Links):  # Sampling By Genetic Programming
            self.test_Links.append(Link(self.Link_info[i][0],self.Link_info[i][1]))

        self.circle = Circle()

        # Simulation Environment
        self.train_data_num = 10
        self.test_data_num = 10

    def setCNN(self):
        self.machine = "CPU"
        self.CNN_trial = 3
        self.target_size_Original = 112
        self.optimizer = "Adam"
        self.maxepochs = 300
        self.batch_size = 32
        self.validation_split = 0.2
        self.verbose = 1
        self.shuffle = True
        self.GRAYSCALE = True
        self.verbose = 1

        self.split = 2      # under train dataset size

    def setPreprocess(self):
        self.problem = "random"

    def reset_seed(self,seed=1):    # environment variables
        os.environ['TF_DETERMINISTIC_OPS'] = '{}'.format(seed)
        tf.random.set_seed(seed)
        os.environ['TF_DETERMINISTIC_OPS'] = 'true'
        os.environ['TF_CUDNN_DETERMINISTIC'] = 'true'

        np.random.seed(seed)
        rd.seed(seed)

        session_conf = tf.compat.v1.ConfigProto(intra_op_parallelism_threads=32, inter_op_parallelism_threads=32)
        tf.compat.v1.set_random_seed(seed)
        sess = tf.compat.v1.Session(graph=tf.compat.v1.get_default_graph(), config=session_conf)


from typing import List
from ..model.results.DecodeResult import DecodeResult
from ..model.results.DetectionResult import DetectionResult
from ..model.BBox import BBox

class InferenceService:

    def __init__(self) -> None:
        pass

    def detection_qr_collision_merge(self, detection_result: DetectionResult, decode_result: DecodeResult) -> List[BBox]:
        detection_result = BBox.toBBoxList(detection_result.labels, detection_result.bboxes, detection_result.type)
        decode_result = BBox.toBBoxList(decode_result.labels, decode_result.bboxes, decode_result.type)

        for bb in decode_result:
            detection_result = sorted(detection_result, key=lambda x: self.find_collision(x, bb), reverse=True)

        return detection_result + decode_result

    def find_collision(self, aa: BBox, bb: BBox) -> float:
        try:
            iou = self.calculate_iou(aa, bb)
            assert aa.label == bb.label
            return iou
        except:
            return 0.0

    def calculate_iou(self, bb1: BBox, bb2: BBox) -> float:
        assert bb1.x1 < bb1.x2
        assert bb1.y1 < bb1.y2
        assert bb2.x1 < bb2.x2
        assert bb2.y1 < bb2.y2

        x_left = max(bb1.x1, bb2.x1)
        y_top = max(bb1.y1, bb2.y1)
        x_right = min(bb1.x2, bb2.x2)
        y_bottom = min(bb1.y2, bb2.y2)

        if x_right < x_left or y_bottom < y_top:
            return 0.0

        intersection_area = (x_right - x_left) * (y_bottom - y_top)
        bb1_area = (bb1.x2 - bb1.x1) * (bb1.y2 - bb1.y1)
        bb2_area = (bb2.x2 - bb2.x1) * (bb2.y2 - bb2.y1)

        iou = intersection_area / (bb1_area + bb2_area - intersection_area)
        assert 0.0 <= iou <= 1.0

        return iou


a,b= list(map(int, input().split()))

l= [4,7,47,744,]
hasValue=False
for i in range(a,b):
    if i in l:
        hasValue = True
        print(i, end=" ")

if not hasValue:
    print(-1)


import sys
from itertools import combinations
import re
input = sys.stdin.readline

N, K = map(int, input().split())
answer = 0

if K < 5:  # a, n, t, i, c
    print(0)

elif K >26:  # 알파벳 개수 26
    print(N)

else:
    K -= 5
    words = [0] * N
    for i in range(N):
        temp = set(re.sub(r'[acint]','',input().rstrip()))
        for t in temp:
            words[i] |= (1 << (ord(t)-ord('a'))) # 알파벳 하나씩 비트마스킹

    candidate = ['b','d','e','f','g','h','j','k','l','m','o','p','q','r','s','u','v','w','x','y','z']
    # 조합 만들기
    for c in list(combinations(candidate, K)):
        each = 0
        cnt = 0
        # 조합 비트마스킹 만들기
        for i in c:
            each |= (1 << (ord(i)-ord('a')))

        # 단어와 조합의 비교
        for j in words:
            if each & j == j:
                cnt += 1

        # 최댓값 갱신
        if answer < cnt:
            answer = cnt

    print(answer)


driving = input('请问你有没有开过车？')
if driving != '有' and driving != '没有':
	print('只能输入 有/没有')
	raise SystemExit
age = input('请问你的年龄？')
age = int(age)
if driving == '有':
	if age >= 18:
		print('原来你考过驾照了！水哦！')
	else:
		print('你该不会无照驾驶吧？')
elif driving == '没有':
	if age >= 18:
		print('那你什么时候才要去考？')
	else:
		print('没关系 再过几年就能考驾照了！')


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

import tornado.web

from sems.monitors import monitors as list_monitors
from sems.repository.monitor import Monitor
from sems.settings import WEB_POLLING_INTERVAL

from sems import VERSION

class Dashboard(tornado.web.RequestHandler):

    def get(self):

        monitor_types = [
            ('Select...', '')
        ]

        for monitor in list_monitors:
            item = (list_monitors[monitor]['description'], monitor)
            monitor_types.append(item)

        monitors = {}
        for monitor in Monitor().ordered_by_position():
            if hasattr(monitor, "group"):
                group = monitor.group
            else:
                group = ""

            if group not in monitors:
                monitors[group] = []
            monitors[group].append(monitor)

        groups = set([monitor for monitor in monitors])

        self.render("dashboard.slim.html",
                    monitor_types=monitor_types,
                    groups_monitors=monitors,
                    groups=groups,
                    polling_interval=WEB_POLLING_INTERVAL,
                    version=VERSION)


from libraries import *
from utils import *
#from debug import *
from utils import *
from libraries import *
import torch as tch
import os
from collections import OrderedDict
from itertools import chain

class ConvNet():
    def __init__(self, n1, n2, k1, k2, resume_value, d, n_len, K, eta = 0.001, rho = 0.9):

        self.resume_value = resume_value

        self.best_model_comp = 0
        self.best_model_params = []

        self.n = [n1, n2]
        self.k = [k1, k2]
        self.n1 = n1
        self.n2 = n2
        self.k1 = k1
        self.k2 = k2

        self.n_len = n_len
        self.d = d
        self.K = K

        self.n_len1 = self.n_len - k1 + 1
        self.n_len2 = self.n_len1 - k2 + 1
        self.fsize = n2 * self.n_len2

        self.eta = eta
        self.rho = rho

        self.R1 = np.zeros((self.d, self.k1, self.n1))
        self.R2 = np.zeros((self.n1, self.k2, self.n2))
        self.RW = np.zeros((self.K, self.fsize))

        self.MFs = []

        # He_init
        self.F1 = 1 * np.random.normal(size=self.d * self.n1 * self.k1).reshape(self.d, self.k1, self.n1)
        self.F2 = np.sqrt(2 / self.k2) * np.random.normal(size=self.n1 * self.n2 * self.k2).reshape(self.n1, self.k2, self.n2)
        self.W = np.sqrt(2 / self.fsize) * np.random.normal(size=self.K * self.fsize).reshape(self.K, self.fsize)

        self.F = [self.F1, self.F2]
        self.len_fs = [self.n_len, self.n_len1]

    def train(self, batch_size, X, Y, num_train_updts, balance, y):
        print('')
        print('INITIALIZING BATCH FORMATION')

        if balance == True:
            X_batches, Y_batches, idxs_batches = genBatches_Balanced(batch_size, X[0], y, self.K)

        else:
            X_batches, Y_batches, idxs_batches = genBatches(batch_size, X[0], Y[0])

        print('BATCH FORMATION CONCLUDED')

        acc_train = []
        Loss = []
        acc_val = []
        Loss_val = []
        self.MFs = []
        for i in range(len(self.F)):
            self.MFs.append(makeMFMatrix(self.F[i], self.len_fs[i]))

        print('INITIALIZING TRAINING')

        counter = 0
        for e in range(1, num_train_updts + 1):
            print('')
            print('Epoch: ', e)
            print('Total Batches: ', len(idxs_batches))
            random_indexes = permutation(np.arange(len(idxs_batches)))
            for b in random_indexes:
                X1_batch, X2_batch, P_train = self.forward(X_batch = X_batches[b], MFs = self.MFs, W=self.W)
                _, _, P_val = self.forward(X_batch = X[1], MFs = self.MFs, W=self.W)
                grad_W, grad_F2, grad_F1 = self.compute_grads(X_batch=X_batches[b], X_batch1=X1_batch, X_batch2=X2_batch,
                                                              Y_batch=Y_batches[b], P_batch=P_train, MFs=self.MFs)
                self.backward(grad_W, grad_F2, grad_F1)

                self.MFs = []
                self.F = [self.F1, self.F2]
                for i in range(len(self.F)):
                    self.MFs.append(makeMFMatrix(self.F[i], self.len_fs[i]))

                if counter % self.resume_value == 0:
                    acc_train.append(Accuracy(P_train, Y_batches[b]))
                    Loss.append(cost(X_batches[b], Y_batches[b], P_train))

                    acc_val.append(Accuracy(P_val, Y[1]))
                    Loss_val.append(cost(X[1], Y[1], P_val))

                counter += 1

                best_model_params = self.Best_Model(acc_inp=Accuracy(P_val, Y[1]))

        return [acc_train, acc_val], [Loss, Loss_val], best_model_params

    def test_gradients(self, X, Y):
        self.MFs = []
        for i in range(len(self.F)):
            self.MFs.append(makeMFMatrix(self.F[i], self.len_fs[i]))

        X1_batch, X2_batch, P_ = self.forward(X_batch=X, MFs=self.MFs, W=self.W)
        ga1, ga2, ga3 = self.compute_grads(X, X1_batch, X2_batch, P_, Y, self.MFs)
        gn1, gn2, gn3 = self.num_grads(X, Y, self.MFs, self.W, 1e-07)
        check1 = self.computeRelativeError(ga1, gn1, 1e-07)
        check2 = self.computeRelativeError(ga2, gn2, 1e-07)
        check3 = self.computeRelativeError(ga3, gn3, 1e-07)
        return check1, check2, check3

    def forward(self, X_batch, MFs, W):  # forward pass
        X_batches = [X_batch]
        for i in range(len(MFs)):
            #print(MFs[i].shape)
            #print(X_batches[i].shape)
            new_X_batch = np.maximum(np.dot(MFs[i], X_batches[i]), 0)
            X_batches.append(new_X_batch)
        S_batch = np.dot(W, X_batches[-1])
        P_batch = softmax2(S_batch)
        return X_batches[1], X_batches[2], P_batch

    def backward(self, dL_dW, dL_dF2, dL_dF1):
        self.R1 = self.rho * self.R1 - self.eta * dL_dF1
        self.R2 = self.rho * self.R2 - self.eta * dL_dF2
        self.RW = self.rho * self.RW - self.eta * dL_dW
        self.F1 += self.R1
        self.F2 += self.R2
        self.W += self.RW

    def compute_grads(self, X_batch, X_batch1, X_batch2, P_batch, Y_batch, MFs):
        G_batch = - (Y_batch - P_batch)
        grad_W = np.dot(G_batch, X_batch2.T) / X_batch2.shape[1]

        G_batch = np.multiply(np.dot(self.W.T, G_batch), np.where(X_batch2 > 0, 1, 0))
        G_batch1 = np.multiply(np.dot(MFs[1].T, G_batch), np.where(X_batch1 > 0, 1, 0))

        v2 = 0
        v1 = 0
        for j in range(X_batch1.shape[1]):
            gj = G_batch[:, j]
            M_inputj_vec = makeMXMatrixVec(X_batch1[:, j], self.n1, self.k2)
            g_eff = gj.reshape(int(gj.shape[0] / self.n2), self.n2)
            v2 += np.dot(M_inputj_vec.T, g_eff)

            gj = G_batch1[:, j]
            M_inputj_vec = makeMXMatrixVec(X_batch[:, j], self.d, self.k1)
            g_eff1 = gj.reshape(int(gj.shape[0] / self.n1), self.n1)
            v1 += np.dot(M_inputj_vec.T, g_eff1)

        grad_F = [v1.reshape(self.d, self.k1, self.n1, order='F') / X_batch.shape[1],
                  v2.reshape(self.n1, self.k2, self.n2, order='F') / X_batch1.shape[1]]
        return grad_W, grad_F[1], grad_F[0]

    def num_grads(self, X, Y, MF, W, h):
        dW = np.zeros_like(W)
        (a, b) = W.shape
        for i in range(a):
            for j in range(b):
                C = []
                for m in [-1, 1]:
                    W_try = np.copy(W)
                    W_try[i, j] += m * h
                    C.append(self.cost2(X, Y, MF, W_try))
                dW[i, j] = (C[1] - C[0]) / (2 * h)

        dF = [np.zeros(self.F[f].shape) for f in range(len(self.F))]
        for i in range(len(self.F)):
            (a, b, c) = self.F[i].shape
            for j in range(a):
                for k in range(b):
                    for q in range(c):
                        C = []
                        for m in [-1, 1]:
                            Fi_try = np.copy(self.F[i])
                            Fi_try[j, k, q] += m * h
                            MFi_try = makeMFMatrix(Fi_try, self.len_fs[i])
                            MF_lst = []
                            for ii in range(len(self.F)):
                                MF_lst.append(MFi_try if ii == i else MF[ii])
                            C.append(self.cost2(X, Y, MF_lst, W))
                        dF[i][j, k, q] = (C[1] - C[0]) / (2 * h)
        return dW, dF[1], dF[0]

    def computeRelativeError(self, ga, gn, eps):
        return np.max(np.absolute(np.subtract(ga, gn)) / np.maximum(np.add(np.absolute(ga), np.absolute(gn)),
                                                                    np.full(ga.shape, eps)))

    def CELoss(self, X, Y, MFs, W):
        _, _, P = self.forward(X, MFs, W)
        Y = np.reshape(Y, (P.shape))
        loss = -(np.multiply(Y, np.log(P)))  # check this:  - np.sum(Y*np.log(P)), removed  np.sum
        return loss

    def cost2(self, X, Y, MFs, W):
        J = np.sum(self.CELoss(X, Y, MFs, W)) / X.shape[1]
        return J

    def Best_Model(self, acc_inp):
        save_params = []
        if self.best_model_comp < acc_inp:
            self.best_model_comp = acc_inp
            save_params.append(self.F1)
            save_params.append(self.F2)
            save_params.append(self.W)
        return save_params

    '''
    def predict(self, X):
        MFs_learned = []
        for i in range(len(self.F)):
            MFs_learned.append(makeMFMatrix(self.F[i], self.len_f[i]))
        _, _, P = self.forward(OneHot_X(X), MFs_learned, self.W)
        pred = np.argmax(P, axis=0)
        return [x + 1 for x in pred]
    '''


import torch.nn as nn

class SurvivalModel(nn.Module):

    def __init__(self, n_input_dim=21, n_hidden1 = 300, n_hidden2 = 100, n_output =  1):

        super(SurvivalModel, self).__init__()
        self.n_input_dim = n_input_dim
        self.layer_1 = nn.Linear(n_input_dim, n_hidden1)
        self.layer_2 = nn.Linear(n_hidden1, n_hidden2)
        self.layer_out = nn.Linear(n_hidden2, n_output)

        self.relu = nn.ReLU()
        self.sigmoid =  nn.Sigmoid()
        self.dropout = nn.Dropout(p=0.1)
        self.batchnorm1 = nn.BatchNorm1d(n_hidden1)
        self.batchnorm2 = nn.BatchNorm1d(n_hidden2)

    def forward(self, inputs):
        x = self.relu(self.layer_1(inputs))
        x = self.batchnorm1(x)
        x = self.relu(self.layer_2(x))
        x = self.batchnorm2(x)
        x = self.dropout(x)
        x = self.sigmoid(self.layer_out(x))

        return x

    def serialize_params(self):
        return {
            "model": {
                "n_input_dim": self.n_input_dim
            }
        }


# -*- coding: utf-8 -*-
"""
Created on Thu Jun 16 16:51:54 2022

@author: Ra, S.J., Cho, S.
"""

import pandas as pd
import numpy as np
import sklearn
import os

import matplotlib.pyplot as plt
import joblib
import random

from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.initializers import RandomNormal

from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping

os.chdir(r'C:\Users\YourPCPC\Desktop\DS_MetaLr')
#%% ANN function
def build_ANN(output_size, input_size, hidden_size):
    ann_ = Sequential()
    ann_.add(Input(input_size))
    for nodes in hidden_size:
        ann_.add(Dense(nodes, activation = 'relu',
                       kernel_initializer = RandomNormal(stddev=0.005),
                       bias_initializer = RandomNormal(stddev=0.005)))

    ann_.add(Dense(output_size))

    ann_.compile(
                 loss='mean_squared_error',
                 optimizer=Adam(learning_rate=0.001),
                 metrics=['RootMeanSquaredError', 'MeanAbsoluteError'])
    return ann_

def cv_rmse(mea_y, pred_y):
    rmse_ = np.sqrt(np.mean(np.power((mea_y - pred_y), 2), axis=0))
    cvrmse_ = rmse_/np.mean(mea_y, axis=0)*100
    return cvrmse_

def mbe(mea_y, pred_y):
    mbe_ = np.sum((mea_y - pred_y), axis=0)/np.mean(mea_y, axis=0)/(len(mea_y)-1)*100
    return mbe_

#%% make dir function
def createFolder(directory):
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
    except OSError:
        print ('Error: Creating directory. ' +  directory)

createFolder('./Model')
#%%
virtual_Data = pd.read_csv('./dataMeta_vs2.csv', header = [0])
virtual_Data['CDU_oper'] = virtual_Data[['CDU1', 'CDU2', 'CDU3', 'CDU4']].sum(axis = 1)
virtual_Data['Fan'] = virtual_Data['Fan']*2

inputData = virtual_Data[['CDU_oper', 'Fan', 'OAT', 'OAH']]
outputData = virtual_Data[['SAT']]

### Make scalers
inputScaler = MinMaxScaler()
outputScaler = MinMaxScaler()

inputScaler = inputScaler.fit(inputData)
outputScaler = outputScaler.fit(outputData)

joblib.dump(inputScaler, './Model/input_scaler.save')
joblib.dump(outputScaler, './Model/output_scaler.save')

### Scale input/output data
inputScaled = inputScaler.transform(inputData)
outputScaled = outputScaler.transform(outputData)

###
inputTrain = inputScaled
outputTrain = outputScaled

#%%
train_input, test_input, train_output, test_output = train_test_split(inputTrain, outputTrain, test_size = 0.3, shuffle = False, random_state = 12)
meta_ANN = build_ANN(outputTrain.shape[1], (inputTrain.shape[1],), (30, 30, 30))

#%%
checkpoint = ModelCheckpoint('./Model/saPred_EP_weight.h5', monitor = 'loss', verbose = 1, save_best_only = True)
#es = EarlyStopping(monitor='loss', mode='min', patience = 30)

meta_ANN.fit(train_input, train_output, epochs = 200, callbacks = [checkpoint])
#%%
meta_ANN.load_weights('./Model/saPred_EP_weight.h5')
meta_ANN.save('./Model/saPred_EP.h5')

#%%
prediction = outputScaler.inverse_transform(meta_ANN.predict(test_input))
true = outputScaler.inverse_transform(test_output)
print(cv_rmse(true, prediction))
#%%
parameters = {'axes.labelsize': 23,
          'axes.titlesize': 23,
          'xtick.labelsize': 23,
          'ytick.labelsize': 23,
          'font.family': 'Times New Roman'}
plt.rcParams.update(parameters)

#%%
fig, ax1 = plt.subplots(1,1, figsize = (20, 5))

ax1.plot(true[0:144*10], color = 'b', label = 'measured')
ax1.plot(prediction[0:144*10], color = 'r', label = 'predicted')

ax1.set_xlabel('data points [10min]')
ax1.set_ylim([12.5, 35.5])
ax1.set_yticks(list(range(13,35,5)))
ax1.set_ylabel(u'temperature [\u00B0C]')

ax1.grid()
ax1.legend(loc = 'upper center', fontsize = 23, ncol = 2)

ax1.set_title('CVRMSE: {}%,       MBE: {}%'.format(np.round(cv_rmse(true,prediction), 2)[0],
                                                   np.round(mbe(true, prediction), 2)[0]))

fig.savefig('./Figure/epModel_test.png', dpi = 350, bbox_inches = 'tight')

#%%
test_input_unscaled = inputScaler.inverse_transform(test_input)

fig, ax1 = plt.subplots(1,1, figsize = (20, 5))

ax1.plot(test_input_unscaled[0:144*10, 0], color = 'g', label = 'CDU operation')

ax1.set_xlabel('data points [10min]')
ax1.set_ylim([-0.2, 5.2])
ax1.set_yticks([0, 1, 2, 3, 4])
ax1.set_ylabel('no. of CDUs')

ax1.grid()
# ax1.legend(loc = 'upper center', fontsize = 23, ncol = 2)
ax2 = ax1.twinx()
ax2.plot(test_input_unscaled[0:144*10, 1], color = 'magenta', label = 'fan on/off')

ax2.set_ylim([-0.2, 5.2])
ax2.set_yticks([0, 2])
ax2.set_yticklabels(['off', 'on'])
ax2.set_ylabel('on/off')

fig.legend(ncol = 2, bbox_to_anchor = (0.5, 0.88), fontsize = 23, loc = 'upper center')
fig.savefig('./Figure/epModel_input_operation.png', dpi = 350, bbox_inches = 'tight')


import requests
import json
import os

BASE_URL = 'http://app.nanonets.com/api/v2/MultiLabelClassification/'
AUTH_KEY = os.environ.get('NANONETS_API_KEY')
MODEL_ID = os.environ.get('NANONETS_MODEL_ID')

def get_model(model_id):
    url = BASE_URL + "Model/%s"%(model_id)
    response = requests.request('GET', url, auth=requests.auth.HTTPBasicAuth(AUTH_KEY,''))
    res =  json.loads(response.text)
    state, status  = res['state'], res['status']
    if state != 5:
        print("The model isn't ready yet, it's status is:", status)
        print("We will send you an email when the model is ready. If your imapatient, run this script again in 10 minutes to check.")
        print("\n\nmore details at:")
        print("https://app.nanonets.com/multilabelclassification/#/classify/"+model_id)
    else:
        print("NEXT RUN: python ./code/prediction.py ./multilabel_data/ImageSets/1067.jpg")

if __name__=="__main__":
    get_model(MODEL_ID)


import sys
import os.path
import logging

def parse_compliance(compliance_aux):
    compliance = {}
    for l in compliance_aux:
        document, requirement, status = l.strip().split(':')
        compliance.setdefault(document, {})
        compliance[document][requirement] = status
    return compliance

def parse_explanations(explanations_aux):
    explanations = {}
    state = 0
    lastd = None
    lastr = None
    for l in explanations_aux:
        if state == 0:
            document, requirement, throwaway = l.strip().split(':')
            explanations.setdefault(document, {})
            explanations[document][requirement] = ''
            lastd = document
            lastr = requirement
            state = 1
        elif state == 1:
            if l.strip() == ':':
                state = 0
            else:
                explanations[lastd][lastr] += l
    return explanations

def table_rows(docname, meaning, compliance_for_document,
        explanations_for_document):
    yield (
        'STIG',
        'STIG ID',
        'IA Controls',
        'Title',
        'Rule ID',
        'Severity',
        'Compliant?',
        'Explanation/Mitigation',
        )
    for rg in meaning.selected_rule_groups():
        for r in rg.rules():
            try:
                compliant = compliance_for_document[r.version]
            except KeyError:
                compliant = '(nothing written)'
            try:
                explanation = explanations_for_document[r.version]
            except KeyError:
                explanation = ''
            yield (
                    docname,
                    r.version,
                    ', '.join(rg.ia_controls),
                    r.title,
                    r.id,
                    r.severity,
                    compliant,
                    explanation,
                    )

def values_to_csv(iterable_of_tuples):
    for row in iterable_of_tuples:
        # HACK: replace double quotes in values with single quotes, so that
        # when we use double quotes to delimit values, quotes inside the
        # values won't screw up the file format
        yield u','.join(u'"%s"' % (x.replace('"', "'")) for x in row)

def compliance2csv(checklists, compliance_aux, explanations_aux):
    """Read aux files created by LaTeX and yield CSV table of compliance.

    meaning is an XCCDFMeaning object.

    compliance_aux and explanations_aux are iterables of lines from a
    the respective files (e.g., open file objects).
    """
    log = logging.getLogger('compliance2csv')
    compliance = parse_compliance(compliance_aux)
    explanations = parse_explanations(explanations_aux)
    for docname, meaning in checklists.items():
        if docname in compliance:
            this_compliance = compliance[docname]
        else:
            log.warning('no notations of compliance found for %s',
                    docname)
            this_compliance = {}
        if docname in explanations:
            this_explanations = explanations[docname]
        else:
            log.info('no explanations of non-compliance '
                    'found for %s. (Maybe there is no '
                    'non-compliance to explain!)',
                    docname)
            this_explanations = {}
        rows = table_rows(docname, meaning, this_compliance, this_explanations)
        for x in values_to_csv(rows):
            yield x


import torch
from torch.utils.data import ConcatDataset, Subset, random_split

import os
import time
import random

import pickle

from torchvision.datasets import ImageFolder

from config_loader import *
from lidar_preprocessing import preprocess_image

class LidarDataset(ImageFolder):

    # Source: https://github.com/pytorch/vision/issues/2930
    # This creates a dataset with the same functionality as ImageFolder but with our custom targets.
    def __init__(self, name: str) -> None:

        input_folder = os.path.join(DATASET_FOLDER, name)

        with open(os.path.join(DATASET_FOLDER, name, "targets.pickle"), "rb") as file:
            labels = pickle.load(file)

        super().__init__(input_folder, preprocess_image)
        paths, _ = zip(*self.imgs)
        self.targets = [torch.Tensor(labels[path]) for path in paths]
        self.samples = self.imgs = list(zip(paths, self.targets))

    def get_idx_of_turn_samples(self):
        idx = []
        for i, x in enumerate(self.targets):
            if abs(x[0]) > 0.15:
                idx.append(i)
            elif abs(x[0]) > 0.05 and random.random() < 0.3:
                idx.append(i)
            elif random.random() < 0.05:
                idx.append(i)

        return idx

def display_dataset_example(ds: LidarDataset):
    """Displays a few example inputs from the given Lidar Dataset."""
    ds_item = ds.__getitem__(0)
    ds_item['input'].show()
    ds_item = ds.__getitem__(1000)
    ds_item['input'].show()
    ds_item = ds.__getitem__(2000)
    ds_item['input'].show()
    ds_item = ds.__getitem__(3000)
    ds_item['input'].show()
    ds_item = ds.__getitem__(4000)
    ds_item['input'].show()

print("Starting dataset loading...")
start_time = time.time()

datasets = []

for i, x in enumerate(DATASET_LIST):
    ds = LidarDataset(x)
    if DATASET_FILTER_ONLY_TURNS:
        ds = Subset(ds, ds.get_idx_of_turn_samples())
    datasets.append(ds)
    print("Dataset " + str(i) + "/" + str(len(DATASET_LIST)) + " loaded...")
    if DEBUG_GENERATE_ONLY_ONE_DATASET:
        print("DEBUG_REDUCED_DATASET enabled. Ignoring other datasets...")
        break

full_dataset = ConcatDataset(datasets)

print("Concatenating and generating splits...")

train_length = round(0.8*len(full_dataset))
[dataset_train, dataset_test] = random_split(full_dataset, [train_length, len(full_dataset) - train_length])

print("Dataset loading complete!")
print("Loading time: %s" % (time.time() - start_time))


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

import mxnet as mx
import log
import logging
import data_tool
import yaml
import sys
import os
import argparse
from model import resnet
from model import resnext

logging.getLogger().setLevel(logging.DEBUG)
logger = log.get_logger(name='train', filename='train.log', filemode='a', level=log.DEBUG, file_and_line=True)

def process(train_params):
    """

    :param train_params:
    :return:
    """
    logger.info('prepare train data')
    features_train, labels_train, features_test, labels_test = data_tool.load_data(
        train_params['train']['traindatapath'], train_params['train']['testdatapath'],
        one_hot=False)

    train_iter = mx.io.NDArrayIter(data=features_train, label=labels_train,
                                   batch_size=train_params['train']['batchsize'], shuffle=True)
    eval_iter = mx.io.NDArrayIter(data=features_test, label=labels_test,
                                  batch_size=train_params['train']['batchsize'])

    logger.info('load symbol %s' % train_params['train']['net'])

    symbol = None
    if train_params['train']['net'] == 'resnext34':
        symbol = resnext.get_symbol(num_classes=train_params['classes'], num_layers=34,
                                    image_shape=train_params['inputshape'])
    elif train_params['train']['net'] == 'resnext50':
        symbol = resnext.get_symbol(num_classes=train_params['classes'], num_layers=50,
                                    image_shape=train_params['inputshape'])
    elif train_params['train']['net'] == 'resnext101':
        symbol = resnext.get_symbol(num_classes=train_params['classes'], num_layers=101,
                                    image_shape=train_params['inputshape'])
    elif train_params['train']['net'] == 'resnet34':
        symbol = resnext.get_symbol(num_classes=train_params['classes'], num_layers=34,
                                    image_shape=train_params['inputshape'])
    elif train_params['train']['net'] == 'resnet50':
        symbol = resnext.get_symbol(num_classes=train_params['classes'], num_layers=50,
                                    image_shape=train_params['inputshape'])
    elif train_params['train']['net'] == 'resnet101':
        symbol = resnext.get_symbol(num_classes=train_params['classes'], num_layers=101,
                                    image_shape=train_params['inputshape'])
    elif train_params['train']['net'] == 'resnet152':
        symbol = resnext.get_symbol(num_classes=train_params['classes'], num_layers=152,
                                    image_shape=train_params['inputshape'])

    logger.info('create model graph at %s' % train_params['train']['graphpath'])
    mx.viz.plot_network(symbol).render(train_params['train']['graphpath'])

    model = mx.mod.Module(symbol=symbol, logger=logger, context=mx.gpu(0))

    logger.info('begin to train==============, epoch: %d, optimizer: %s, learning_rate: %d, batchsize: %d'
                % (train_params['train']['trainepoch'], train_params['train']['optimizer'],
                    train_params['train']['learningrate'], train_params['train']['batchsize']))

    if train_params['preimagnettrain']:
        sym, arg_params, aux_params = get_imagenet_model(train_params['train']['net'])
    if train_params['pretrain']:
        sym, arg_params, aux_params = get_trainned_model(train_params['train']['modelprefix'])

    model.fit(train_data=train_iter,
              eval_data=eval_iter,
              arg_params=arg_params,
              aux_params=aux_params,
              eval_metric=train_params['train']['evalmetric'],
              optimizer=train_params['train']['optimizer'],
              optimizer_params={'learning_rate': train_params['train']['learningrate']},
              epoch_end_callback=mx.callback.do_checkpoint(prefix=train_params['train']['modelprefix'],
                                                           period=train_params['train']['modelepoch']),
              batch_end_callback=mx.callback.Speedometer(batch_size=train_params['train']['batchsize'],
                                                         frequent=1),
              num_epoch=train_params['train']['trainepoch'])

    metric = mx.metric.Accuracy()
    model.score(eval_iter, metric)
    logger.info('train end============== score %f' % metric.get()[1])

def get_imagenet_model(net_name):
    model_prefix = None
    if net_name == 'resnext50':
        model_prefix = 'imagenet/resnext-50'
    elif net_name == 'resnext101':
        model_prefix = 'imagenet/resnext-101'
    elif net_name == 'resnet34':
        model_prefix = 'imagenet/resnet-34'
    elif net_name == 'resnet50':
        model_prefix = 'imagenet/resnet-50'
    elif net_name == 'resnet101':
        model_prefix = 'imagenet/resnet-101'
    elif net_name == 'resnet152':
        model_prefix = 'imagenet/resnet-152'
    sym, arg_params, aux_params = mx.model.load_checkpoint(model_prefix, 0)
    return sym, arg_params, aux_params

def get_trainned_model(model_prefix):
    if model_prefix:
        if model_prefix.rindex('/') > 0:
            index = model_prefix[:model_prefix.rindex('/')]
            file_list = os.listdir(index)
        else:
            file_list = os.listdir('')
        params_file_list = []
        for item in file_list:
            if item.endswith('.params'):
                params_file_list.append(item)
        params_file_list.sort(reverse=True)
        if len(params_file_list) > 0:
            param_file = params_file_list[0]
            from_epoch = int(param_file[param_file.rindex('-')+1:param_file.rindex('.')])
            sym, arg_params, aux_params = mx.model.load_checkpoint(model_prefix,
                                                                   from_epoch)
            logger.info('load pretrainned model from %s %d' % (model_prefix, from_epoch))
            return sym, arg_params, aux_params
    return None, None, None

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='train input',
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--parampath', type=str, default='params.yaml',
                        help='path of params.yaml')
    args = parser.parse_args()

    logger.info('load params from %s' % args.parampath)

    params = None
    with open(args.parampath) as f:
        params = yaml.load(f)

    if params is None:
        logger.error('no params found from %s' % args.parampath)
        sys.exit(1)

    process(params)