"""
Class: Single Attempt of application
"""

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
import time
# from PIL import Image

class Attempt:

    def __init__(self, client):
        self.driver = webdriver.Chrome('./bin/chromedriver')
        self.client = client
        self.alive = False

    def go(self):

        while not self.alive:

            # Make sure no cookie
            self.driver.delete_all_cookies()

            self.alive = self.processFirstPage()

            if self.alive:
                self.alive = self.processSencondPage()
            # if self.alive:
            #     self.alive = self.processWarningPage()
            if self.alive:
                self.alive = self.processThirdPage()

        print("** Server is Up! **")
        if self.alive:
            self.alive = self.processForthPage()
        if self.alive:
            self.alive = self.processFifthPage()
        if self.alive:
            self.processLastPage()

    def killAttempt(self):
        self.driver.quit()

    def processFirstPage(self):

        # create the chrome driver
        driver = self.driver

        # Page 1:
        # https://eapps2.td.gov.hk/repoes/td-es-app517/Welcome.do?language=zh
        # task 1: select radio button 2
        driver.get(
            'https://eapps2.td.gov.hk/repoes/td-es-app517' +
            '/Welcome.do?language=zh')

        print("[Start]: " + driver.current_url + "\n")
        radioChoice = driver.find_element_by_xpath(
            '//*[@id="contentPanel"]/div[3]/div[1]/div/' +
            'div[2]/table/tbody/tr/td/table/tbody/tr/td/form/input[2]')
        radioChoice.click()

        # task 2: goto next Page
        nextPage = driver.find_element_by_xpath(
            '//*[@id="contentPanel"]/div[4]/div/a[@class="redbutton"]')
        nextPage.click()

        return True

    def processSencondPage(self):

        driver = self.driver
        # Page 2:
        # https://eapps2.td.gov.hk/repoes/td-es-app517/SelectServiceAction.do
        # task 1: wait the page to be loaded
        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.NAME, "app517Form"))
            )
        except:
            driver.quit()
            return False

        print("[Start]: " + driver.current_url + "\n")

        radioChoice = driver.find_element_by_xpath(
            '//input[@name="serviceChoice"][@value="appointment"]')
        radioChoice.click()

        # task 2: goto next page, rely on the class="redbutton"
        nextButton = driver.find_element_by_xpath('//a[@class="redbutton"]')
        nextButton.click()

        return True

    def processWarningPage(self):

        driver = self.driver
        # Page 2:
        # https://eapps2.td.gov.hk/repoes/checkclientconfig/warning.jsp
        # task 1: wait the page to be loaded
        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.CLASS_NAME, "errorPanel"))
            )
        except:
            driver.quit()
            return False

        print("[Start]: " + driver.current_url + "\n")

        # task 2: goto next page, rely on the class="redbutton"
        nextButton = driver.find_element_by_css_selector('input.actionBtnCom')
        nextButton.click()

        return True

    def processThirdPage(self):

        driver = self.driver

        def waitForInput():

            count = 0
            elem = driver.find_element_by_id('jcaptcha_response')

            while True:
                count += 1
                if count > 40:
                    print(">> Key entered or Timing out after 20 seconds..\n")
                    return False
                if len(elem.get_attribute('value')) == 6:
                    return True
                time.sleep(.5)

            return True

        # Page 3:
        # https://eapps2.td.gov.hk/repoes/td-es-app517/Welcome.do?language=zh
        # task 1: wait the page to be loaded
        try:
            WebDriverWait(driver, 3).until(
                EC.presence_of_element_located((By.NAME, "instructionForm"))
            )
        except:
            # driver.quit()
            return False

        print("[Start]: " + driver.current_url + "\n")

        # task 2: check agree radio
        radioChoice = driver.find_element_by_xpath('//input[@name="agree"]')
        radioChoice.click()

        # task 3: check captcha
        # captcha = driver.find_element_by_id('jcaptcha_response')
        driver.execute_script(
            "window.scrollTo(0,document.body.scrollHeight);" +
            "document.getElementById('jcaptcha_response').focus();")

        # captcha = driver.find_element_by_xpath('//*[@id="contentPanel"]/form/div[3]/div/table/tbody/tr[2]/td/div/table/tbody/tr[1]/td/img')
        # location = element.location
        # size = element.size
        # im = Image.open(StringIO(base64.decodestring(driver.get_screenshot_as_base64())))
        # left = location['x']
        # top = location['y']
        # right = location['x'] + size['width']
        # bottom = location['y'] + size['height']
        # im = im.crop((left, top, right, bottom))
        # im.save('screenshot.png')

        # Check if the captcha has been filled
        if not waitForInput():
            return False

        driver.find_element_by_xpath('//a[@class="redbutton"]').click()

        print(">> Jumping to next page..\n")
        return True

    def processForthPage(self):
        driver = self.driver
        client = self.client
        # check if the page is loaded
        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.NAME, "main"))
            )
        except:
            print(">> Can't load first input page\n")
            driver.quit()
            return False

        finally:
            driver.switch_to_default_content
            driver.switch_to_frame('main')

        print("[Start]: First input page\n")

        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (By.ID, "testFormNumForLastAttempt"))
            )
        finally:
            print(">> Ready to input..\n")

        # Inputs the client's data:
        try:
            driver.find_element_by_id(
                'testFormNumForLastAttempt').send_keys(client['code'])
            driver.find_element_by_id(
                'testFormBirthYear').send_keys(client['b-year'])
            driver.find_element_by_id(
                'testFormBirthMonth').send_keys(client['b-month'])
            driver.find_element_by_id(
                'testFormBirthDay').send_keys(client['b-date'])

            driver.find_element_by_xpath('//a[@class="redbutton"]').click()
        except:
            print('>> Cant assign inputs..\n')
            driver.quit()
            return False

        print(">> Jumping to next page..\n")
        return True

    def processFifthPage(self):

        driver = self.driver
        client = self.client

        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located(
                    (By.XPATH, '//input[@name="telephoneNo"]'))
            )
            print("[Start]: Second input page\n")
        except:
            print(">> Can't load second inputendar page\n")
            driver.quit()
            return False

        # Inputs the client's data:
        print(">> Ready to input..\n")
        try:
            driver.find_element_by_xpath(
                '//input[@name="telephoneNo"]').send_keys(client['mobile'])

            if client["lens"] == "n":
                driver.find_elements_by_xpath(
                    '//input[@name="wearLensesInd"]')[1].click()
            else:
                driver.find_elements_by_xpath(
                    '//input[@name="wearLensesInd"]')[0].click()

            driver.find_elements_by_xpath(
                '//input[@name="wearAidsInd"]')[1].click()
            driver.find_elements_by_xpath(
                '//input[@name="physicalHandicapInd"]')[1].click()

            driver.find_element_by_xpath('//a[@class="redbutton"]').click()
        except:
            raise
            driver.quit()
            return False

        print(">> Jumping to next page..\n")
        return True

    def processLastPage(self):

        # This method aims to located the available's link and
        # click on it if possible

        driver = self.driver
        client = self.client
        timeslot = None
        nextMonth = None
        testAreaCodeOption = None

        # check if the page is loaded
        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.XPATH, "/html"))
            )
            print("[Start]: Calendar page\n")
        except:
            print(">> Can't load calendar page\n")
            driver.quit()
            return False
        else:
            driver.switch_to_default_content()
            driver.switch_to_frame('main')

        # If user are from kowloon, change to kowloon then
        if client["district"] == 'kowloon':
            # Try find the availale link and click it
            try:
                testAreaCodeOption = select = Select(driver.find_element_by_id('testAreaCode'))
            except:
                print(">> trouble selecting areaCode..\n")
            else:
                testAreaCodeOption.select_by_value('2')

        # check if the page is loaded
        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.XPATH, "/html"))
            )
            print("[Start]: Calendar page\n")
        except:
            print(">> Can't load calendar page\n")
            driver.quit()
            return False
        else:
            driver.switch_to_default_content()
            driver.switch_to_frame('main')

        # Try find the availale link and click it
        try:
            timeslot = driver.find_element_by_xpath(
                '//td[@class="inner-table-cell"]/a')
        except:
            print(">> Couldn't find available timeslot..\n")
        else:
            timeslot.click()

        # If no available link if find,
        # try find the next month's link and click it
        if timeslot is None:
            try:
                nextMonth = driver.find_element_by_xpath(
                    '//td[@class="calendar-table-header"][3]/a')
            except:
                print(">> Next Month is not available as well..\n")
            else:
                nextMonth.click()

                # Try find the availale link and click it
                try:
                    timeslot = driver.find_element_by_xpath(
                        '//td[@class="inner-table-cell"]/a')
                except:
                    print(">> Couldn't find available timeslot in next month too..\n")
                else:
                    timeslot.click()

        if timeslot is not None:
            try:
                WebDriverWait(driver, 10).until(
                    EC.presence_of_element_located((By.XPATH, "/html"))
                )
                print("Almost there!!! Agree to print the booking\n")
            except:
                print(">> Can't load printing page\n")
                # driver.quit()
                return False
            else:
                # task 1: check agree radio
                radioChoice = driver.find_element_by_xpath('//input[@name="agree"]')
                radioChoice.click()
                driver.find_element_by_xpath('//a[@class="redbutton"]').click()

        print(">> I have done my job!\n")
        print("< Input 'q' to quit the program >")

        return True


import os
import numpy as np
from PIL import Image
import glob
import cv2
import torch
import torchvision

from data.datasets.utils import *

class KITTI_Odometry(torch.utils.data.Dataset):
    '''
    KITTI odometry color dataset
    data_path/pose/00.txt - 10.txt
    data_path/sequences/[00 - 10]/[image_2, image_3, calib.txt, times.txt]/[000000.png - xxxxxx.png]
    '''
    def __init__(self, path, sequence, train_nums=2, stride=1, eval_nums=None, out_size=(256, 832)):
        super(KITTI_Odometry, self).__init__()
        self._name = 'KITTI_Odometry'
        self.out_size = out_size
        self.root = path
        self.train_nums = train_nums
        self.stride = stride
        self.eval_nums = eval_nums
        self.save_prefix = ''

        self.seqs = ['train', '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10']
        assert sequence in self.seqs
        self.sequences = self.seqs[1:10] if sequence == 'train' else [sequence]

        self.frame_ids = np.arange(2) if train_nums == 2 else np.arange(train_nums) - 1
        self.image_list = self.collect_scenes()
        self.image_list = self.image_list[0::stride]

        brightness = (0.8, 1.2)
        contrast = (0.8, 1.2)
        saturation = (0.8, 1.2)
        hue = (-0.1, 0.1)
        self.fn_resize = torchvision.transforms.Resize(self.out_size)
        self.fn_color_aug = torchvision.transforms.ColorJitter(brightness, contrast, saturation, hue)
        self.to_tensor = torchvision.transforms.ToTensor()

        self.do_flip = True
        if sequence != 'train':
            self.gt_pose_file = os.path.join(path, 'poses', sequence + '.txt')
            self.do_flip = False
            if eval_nums is not None:
                star = 520
                end = np.minimum(star + eval_nums, len(self.image_list))
                self.image_list = self.image_list[star:end]

    def collect_scenes(self):
        scenes_list = [os.path.join(self.root, 'sequences', q_) for q_ in self.sequences]
        train_list = []
        for scene in scenes_list:
            cam_file = os.path.join(scene, 'calib.txt')
            images = sorted(glob.glob(os.path.join(scene, 'image_2', '*.png')))

            # get image pair
            iids = np.arange(0, len(images), 1)
            iids = np.reshape(iids, (1, iids.shape[0]))
            for i in range(self.train_nums-1):
                iids = np.concatenate([iids, np.roll(iids[-1:, :], -self.stride)], axis=0)
            iids = iids[:, :(1-self.train_nums) * self.stride]

            # to list
            for i in np.transpose(iids, (1, 0)):
                str_ = ''
                for j in i:
                    str_ = str_ + images[j].replace(self.root, '')[1:] + ' '
                str_ = str_ + cam_file.replace(self.root, '')[1:]
                train_list.append(str_)
        return train_list

    def __len__(self):
        return len(self.image_list)

    def pre_process(self, outputs, image_lists, do_flip):
        # step 1: load resize, flip and color transforms
        for i, p in enumerate(image_lists):
            # load left
            filename_left = os.path.join(self.root, p)
            im_left = load_rgb_from_file(filename_left, do_flip)
            W, H = im_left.size
            im_left = self.fn_resize(im_left)

            outputs[('color', self.frame_ids[i])] = self.to_tensor(im_left)

            # load transforms left
            outputs[('color_aug', self.frame_ids[i])] = self.to_tensor(self.fn_color_aug(im_left))

            # load right
            if self.frame_ids[i] == 0:
                filename_right = os.path.join(self.root, p.replace('image_2', 'image_3'))
                im_right = load_rgb_from_file(filename_right,do_flip)
                im_right = self.fn_resize(im_right)
                outputs[('color', 'stereo')] = self.to_tensor(im_right)
                outputs[('color_aug', 'stereo')] = self.to_tensor(self.fn_color_aug(im_right))
        return (H, W)

    def __getitem__(self, idx):
        """ Returns a single training item from the dataset as a dictionary.
            Values correspond to torch tensors.
            Keys in the dictionary are either strings or tuples:
                ("color", <frame_id>)          for raw colour images,
                ("color_aug", <frame_id>)      for augmented colour images,
                ("K") or ("inv_K")             for camera intrinsics,
                "stereo_T"                     for camera extrinsics
            <frame_id> is either:
                an integer (e.g. 0, -1, or 1) representing the temporal step relative to 'index',
            or
                "stereo" for the opposite image in the stereo pair.
        """
        data = self.image_list[idx].split(' ')
        image_lists, cam_file = data[:-1], data[-1]

        # load image seqs
        outputs = {}
        do_flip = np.random.rand() > 0.5 if self.do_flip else False
        in_size = self.pre_process(outputs, image_lists, do_flip)

        # load camera intrinsics
        cam_file = os.path.join(self.root, cam_file)
        outputs['K'] = load_cam_intrinsic(cam_file, in_size, self.out_size, position='P2')
        outputs['K_inv'] = outputs['K'].inverse()

        # load camera extrinsics of right camera
        stereo_T = np.eye(4, dtype=np.float32)
        baseline_sign = -1 if do_flip else 1
        stereo_T[0, 3] = -1 * baseline_sign * 0.015
        outputs["stereo_T"] = torch.from_numpy(stereo_T)

        return outputs

class KITTI_OdometryEx(torch.utils.data.Dataset):
    '''
    KITTI odometry color dataset
    data_path/sequences_***/[09 - 10]/image_2/[000000.png - xxxxxx.png]
    mode = [g1-g3, s2-s3, p1-p6]
    '''
    def __init__(self, path, mode='g1', sequence='09', out_size=(256, 832)):
        super(KITTI_OdometryEx, self).__init__()
        self._name = 'KITTI_OdometryEx'
        self.path = path
        self.out_size = out_size
        self.eval_nums = None
        self.sequences = [sequence]
        self.stride = 1

        assert sequence in ['09', '10']
        seq_mode = ['sequences_Geometric_Noise', 'sequences_Low_FPS', 'sequences_Photometric_Noise']
        if mode[0] == 'g':
            scene_name = os.path.join(path, seq_mode[0] + '_' + mode, sequence)
        elif mode[0] == 's':
            scene_name = os.path.join(path, seq_mode[1] + '_' + mode, sequence)
            self.stride = int(mode[1])
        elif mode[0] == 'p':
            scene_name = os.path.join(path, seq_mode[2] + '_' + mode, sequence)
        else:
            raise ValueError
        self.save_prefix = '_' + scene_name.split('/')[-2].replace('sequences_', '')

        self.image_list = self.collect_scenes(scene_name)
        self.gt_pose_file = os.path.join(path, 'poses', sequence + '.txt')
        self.frame_ids = np.arange(2)

        self.fn_resize = torchvision.transforms.Resize(out_size, interpolation=Image.ANTIALIAS)
        self.to_tensor = torchvision.transforms.ToTensor()

    def __len__(self):
        return len(self.image_list)

    def collect_scenes(self, scene):
        train_list = []

        cam_file = os.path.join(scene, 'calib.txt')
        images = sorted(glob.glob(os.path.join(scene, 'image_2', '*.png')))

        # get image pair
        iids = np.arange(0, len(images), 1)
        iids = np.reshape(iids, (1, iids.shape[0]))
        iids = np.concatenate([iids, np.roll(iids[-1:, :], -1)], axis=0)
        iids = iids[:, :-1]

        # to list
        for i in np.transpose(iids, (1, 0)):
            str_ = ''
            for j in i:
                str_ = str_ + images[j].replace(self.path, '')[1:] + ' '
            str_ = str_ + cam_file.replace(self.path, '')[1:]
            train_list.append(str_)
        return train_list

    def __getitem__(self, idx):
        data = self.image_list[idx].split(' ')
        image_lists, cam_file = data[:-1], data[-1]

        # load image seqs
        outputs = {}
        for i, imname in enumerate(image_lists):
            im = load_rgb_from_file(os.path.join(self.path, imname), False)
            W, H = im.size
            im = self.fn_resize(im)
            outputs[('color', self.frame_ids[i])] = self.to_tensor(im)

        # load camera intrinsics
        cam_file = os.path.join(self.path, cam_file)
        outputs['K'] = load_cam_intrinsic(cam_file, (H, W), self.out_size, position='P2')
        outputs['K_inv'] = outputs['K'].inverse()

        return outputs

if __name__ == '__main__':
    pass


import requests
a = requests.get("https://www.okex.com/api/v1/future_kline.do?symbol=eth_usd&type=1min&since=15000000000&contract_type=quater&size=3000").json()
len(a)

import psycopg2
import subprocess
import os
import glob
import pandas as pd
import time
from enum import Enum

def get_conn_url():
    url = 'postgresql://{}:{}@{}:5432/{}'.format(
            'crypto',
            'analyzer',
            '199.169.0.99',
            'crypto_analyzer_dev')
    return url

def conn(n_try=5):
    exception = None
    while n_try > 0:
        try:
            return psycopg2.connect(get_conn_url())
        except Exception as e:
            exception = e
            time.sleep(0.5)
            n_try -= 1
    print(exception)

def do_sql(sql):
    c = conn()
    with c.cursor() as cursor:
        try:
            cursor.execute(sql)
            c.commit()
        except Exception as e:
            print(e)

def fetch_all_sql(sql):
    c = conn()
    with c.cursor() as cursor:
        try:
            cursor.execute(sql)
            result = cursor.fetchall()
            c.commit()
            return result
        except Exception as e:
            print(e)
            return None

def fetch_one_sql(sql):
    c = conn()
    with c.cursor() as cursor:
        try:
            cursor.execute(sql)
            result = cursor.fetchone()
            c.commit()
            return result
        except Exception as e:
            print(e)
            return None

def execute_sql_path(sql_path):
    from crypto_analyzer.config import app_config
    print('\nexecute {}...'.format(os.path.basename(sql_path)))
    db = app_config().DB
    args = db.connect_kwargs
    command = 'psql -h {} -U {} -p 5432 {} < {}'.format(
            args['host'],
            args['user'],
            db.database,
            sql_path)
    print(subprocess.getoutput(command))

def do_migration():
    dir_name = os.path.dirname(os.path.abspath(__file__))
    for sql_path in sorted(glob.glob(os.path.join(dir_name, 'migrations', '*.sql'))):
        execute_sql_path(sql_path)

class Query:
    class Type(Enum):
        INSERT = 'INSERT'
        SELECT_MANY = 'SELECT_MANY'
        SELECT_ONE = 'SELECT_ONE'
        PANDAS = 'PANDAS'

    def __init__(self):
        self.sql = None
        self.mode = 'normal'

    def query(self, query):
        self.sql = query
        return self

    def fetch_mode(self, mode):
        self.mode = mode
        return self

    def run(self):
        if self.sql is None:
            return None

        if self.mode is Query.Type.PANDAS:
            return pd.read_sql_query(self.sql, get_conn_url())
        elif self.mode is Query.Type.SELECT_MANY:
            return fetch_all_sql(self.sql)
        elif self.mode is Query.Type.SELECT_ONE:
            return fetch_one_sql(self.sql)
        elif self.mode is Query.Type.INSERT:
            return do_sql(self.sql)
        else:
            return None

def candlestick_prices(period, currency_code, from_time, to_time, offset, limit,
        desc=False, exchange=None):
    order_by = 'DESC' if desc else ''
    where_exchange = "AND exchange = '{}'".format(exchange) if exchange else ''
    sql = """
    SELECT time_bucket('{}', time) AS period,
    last(last, time) as v_t,
    MAX(last) as v_hi,
    MIN(last) as v_lo,
    last(bid, time) as bid,
    last(ask, time) as ask
    FROM exchange_tickers
    WHERE currency_code = '{}' AND '{}' <= time AND time <= '{}' {}
    GROUP BY period
    ORDER BY period {}
    OFFSET {}
    LIMIT {};
    """.format(period, currency_code, from_time, to_time, where_exchange, order_by, offset, limit)
    return Query().query(sql).fetch_mode(Query.Type.PANDAS).run()

def BTC_csv(candle, path):
    csv = candle.to_csv(path)
    return

def BTC_df(path):
    df = pd.read_csv(path)
    df.drop(columns={"Unnamed: 0", "bid", "ask"},inplace=True)
    df["Open"] = df["v_t"].shift()
    df.rename(columns={"v_t":"Close", "v_hi":"High", "v_lo":"Low"}, inplace=True)
    df = df.set_index("period")
    return df


import os

import pandas as pd

from pydemic.models import Model
from pydemic.utils import fmt
from pydemic.utils import pc
from .. import info
from .. import st
from ..components import md_description
from ..decorators import title
from ..i18n import _, __
from ..utils import natural_date, get_some_attr

NO_ICU_MESSAGE = __(
    """
The location does not have any ICU beds. At peak demand, it needs to reserve {n}
beds from neighboring cities.
"""
)

ICU_OVERFLOW_MESSAGE = __(
    """
The location will **run out of ICU beds at {date}**. At peak demand, it will need **{n}
new ICUs**. This demand corresponds to **{surge} times** the number of beds dedicated
to COVID-19 and {total} of the total number of ICU beds.
"""
)

GOOD_CAPACITY_MESSAGE = __(
    """
The number of ICU beds is sufficient for the expected demand in this scenario.
"""
)

EQUIPMENT_MESSAGE = __(
    """
The table bellow show the recommended usage of PPE by healthcare workers
during the period of simulation.
"""
)

def summary_cards(model, where=st):
    """
    Show list of summary cards for the results of simulation.
    """

    def datum(x):
        return f"{fmt(int(x))} ({pc(x / population)})"

    st = where

    region = model.region
    disease = model.disease
    results = model.results

    deaths = results["data.deaths"]
    hospitalizations = results["data.hospitalized_cases"]
    extra_icu = model["icu_overflow:max"]
    extra_hospitals = model["hospital_overflow:max"]
    recovered = results["data.recovered"]
    population = model.population

    # Print friendlier messages if region has no ICU or hospital beds
    if model.icu_capacity > 0:
        icu_overflow = model.info["event.icu_overflow"].date
    else:
        icu_overflow = _("No ICU beds!")
    if model.hospital_capacity > 0:
        hospital_overflow = model.info["event.hospital_overflow"].date
    else:
        hospital_overflow = _("No hospital beds!")

    # A peak of cases in the final date is bogus: it probably corresponds
    # to a simulation that simply did not run long enough to see the peak
    peak_cases = model["infectious:peak-date"]
    if peak_cases == model.date:
        peak_cases = _("Still coming...")

    # Do not reference Brasil.io as a data source :(
    brasil_io = 'Brasil.io'
    cases_title = _("Confirmed cases*").format(link=brasil_io)
    deaths_title = _("Confirmed deaths*").format(link=brasil_io)
    st.cards(
        {
            cases_title: fmt(info.get_confirmed_cases_for_region(region, disease)),
            deaths_title: fmt(info.get_confirmed_deaths_for_region(region, disease)),
        },
        escape=False,
        color="st-red",
    )
    st.html('

')
    st.cards(
        {
            _("Deaths"): datum(deaths),
            _("Hospitalizations"): datum(hospitalizations),
            _("Required extra ICU beds"): fmt(extra_icu),
            _("Required extra hospital beds"): fmt(extra_hospitals),
            _("No more ICU beds available by"): natural_date(icu_overflow),
            _("No more hospital beds available by"): natural_date(hospital_overflow),
            _("Estimated date for the peak"): natural_date(peak_cases),
            _("Cumulative attack rate"): pc(recovered / population),
        }
    )
    st.markdown(_("* Compiled from local Healthcare Secretaries"))

@title(__("Advanced epidemiological information"))
def epidemiological_parameters(model, where=st):
    """
    Basic report with epidemiological parameters.
    """

    st = where

    days = model.iter
    mortality = model["deaths:final:pp"]
    fatality = model["empirical-CFR:final"]
    infected = model["infected:final:pp"]

    mortality *= 100_000
    mortality = fmt(mortality)
    fatality = pc(fatality)
    infected = pc(infected)
    symptomatic = pc(model.prob_symptoms)

    st.md_description(
        {
            _("Number of cases generated by a single case"): fmt(model.R0),
            _("Mortality (deaths per 100k population)"): mortality,
            _("Letality ({pc} of deaths among the ill)").format(pc="%"): fatality.rstrip(
                "%"
            ),
        }
    )
    lang = os.environ.get("LANGUAGE", "en_US")

    namespace = locals()
    del namespace["st"], namespace["model"], namespace["where"]
    st.footnote_disclaimer(**namespace)

@title(__("Personal protection equipment"))
def ppe_demand_table(model, where=None):
    """
    A simple table with the required personal protection equipment demand.
    """

    st = where

    h_days = model["severe"].sum()
    i_days = model["critical"].sum()
    table = healthcare_equipment_resources(h_days, i_days)
    table.iloc[:, -1] = table.iloc[:, -1].apply(fmt)

    st.markdown(str(EQUIPMENT_MESSAGE))  # TODO: add source
    st.table(table)

    # Legend explaining M, B, etc
    clean = lambda st: "".join(c for c in st if c.isalpha())
    letters = set(table.iloc[:, -1].apply(clean))

    lines = []
    if "M" in letters:
        lines.append(_("M = million"))
    if "B" in letters:
        lines.append(_("B = billion"))
    if lines:
        data = ", ".join(lines)
        st.html(f'
* {data}
')

@title(__("Summary of model attributes and constants"))
def summary_table(
    model,
    roles=("epidemic", "clinical_rates", "clinical_periods", "mortality"),
    humanize=True,
    where=st,
):
    """
    Show table of tables with model parameters.
    """

    if isinstance(roles, str):
        roles = [roles]

    for role in roles:
        df = model.summary_table(role, humanize=humanize, translate=_)
        if df.index.name:
            df = df.reset_index().set_axis([""] * len(df))
        display_role = _(role.replace("_", " "))

        where.markdown(f"**{display_role.title()}**")
        where.table(df, role + ".csv")

@title(__("Healthcare system"))
def healthcare_parameters(model: Model, where=st):
    """
    Write base healthcare parameters.
    """

    icu_surge_capacity = get_some_attr(
        model, "icu_surge_capacity", "region.icu_surge_capacity"
    )
    hospital_surge_capacity = get_some_attr(
        model, "hospital_surge_capacity", "region.hospital_surge_capacity"
    )
    icu_capacity = get_some_attr(model, "icu_capacity", "region.icu_capacity")

    icu_overflow_date = model.info["event.icu_overflow"].date
    extra_icu = model["icu_overflow:max"]

    md_description(
        {
            _("COVID/SARI ICUs"): fmt(int(icu_surge_capacity)),
            _("COVID/SARI hospital beds"): fmt(int(hospital_surge_capacity)),
        },
        where=where,
    )

    if icu_capacity == 0:
        msg = NO_ICU_MESSAGE.format(n=fmt(extra_icu))
    elif icu_overflow_date:
        peak_icu = extra_icu + icu_surge_capacity
        msg = ICU_OVERFLOW_MESSAGE.format(
            date=natural_date(icu_overflow_date),
            n=fmt(int(peak_icu - icu_surge_capacity)),
            surge=fmt(peak_icu / icu_surge_capacity),
            total=fmt(peak_icu / icu_capacity),
        )
    else:
        msg = str(GOOD_CAPACITY_MESSAGE)

    where.markdown(msg)

def healthcare_equipment_resources(hospital_days, icu_days):
    """
    Return the recommended usage of protection equipment by healthcare staff
    from the number of hospitalization x days and ICU x days.
    """

    columns = [_("Quantity"), _("Total")]
    tuples = zip([_("Patients/day"), ""], columns)

    N = int(hospital_days + icu_days)
    a = 1  # / 5
    b = 1  # / 15
    df = pd.DataFrame(
        [
            [_("Cirurgical masks"), 25, 25 * N],
            [_("N95 mask"), a, a * N],
            [_("Waterproof apron"), 25, 25 * N],
            [_("Non-sterile glove"), 50, 50 * N],
            [_("Faceshield"), b, b * N],
        ]
    ).set_index(0)

    df.index.name = _("Name")
    df.columns = pd.MultiIndex.from_tuples(tuples)
    return df


import sys
import re
import subprocess
from typing import List

# decorator to handle ctrl+c in cli
def handle_ctrl_c(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except KeyboardInterrupt:
            print("\n\nExiting due to keyboard interrupt...")
            sys.exit(0)
    return wrapper

def fuzzy_match(query: str, string: str) -> bool:
    """fuzzy match query as regex to string
    parse and accept query as regex if it looks like it
    """
    if query.startswith("/") and query.endswith("/"):
        query = query[1:-1]
        return bool(re.search(query, string, re.IGNORECASE))
    return query in string

def interactive_pick_text(options: List[str]) -> str:
    """interactive pick from options"""
    print("Pick one of the following options:")
    for i, option in enumerate(options):
        print(f"{i+1}. {option}")
    while True:
        try:
            choice = int(input("Enter your choice: "))
            if choice < 1 or choice > len(options):
                raise ValueError
            return options[choice-1]
        except ValueError:
            print("Invalid choice, try again...")

def interactive_pick_dmenu(options: List[str]) -> str:
    out = subprocess.run(
        ["_themenu.sh", "-p", "Select SSID"],
        input="\n".join(options),
        capture_output=True,
        text=True,
    )
    return out.stdout.strip()


'''
Created on 19 Jan 2015

@author: Yuan
'''
'''
We consider two possible solutions to this problem.
1. One is to use a hashmap, to maintian the count of each number.
    if a number has count 1, it is the single number.
2. The other is to use bit manipulation.
    we get the exclusive or (^) of all numbers.
    If the numbers are pairwise, final results should be 0, with the additional single number, the results is the single number.

The following shows the bit manipulation solution.
'''
class Solution:
    # @param A, a list of integer
    # @return an integer
    def singleNumber(self, A):
        result = A[0]
        for i in range(1,len(A)):
            result = result ^ A[i]
        return result


import numpy as np
import os
import random as rn

#fix random seed
os.environ['PYTHONHASHSEED'] = '0'
np.random.seed(42)
rn.seed(12345)
import torch
torch.manual_seed(2019)
torch.cuda.manual_seed(2019)
torch.cuda.manual_seed_all(2019)
torch.backends.cudnn.deterministic = True

import argparse
import pandas as pd
import gc
import logging
from datetime import datetime
import warnings
from tqdm import tqdm
from sklearn.metrics import cohen_kappa_score
from sklearn.model_selection import StratifiedKFold
import pickle
from pathlib import Path

from azureml.core import Workspace, Experiment
from torch.utils.tensorboard import SummaryWriter

import utils
import slack
from dataset import RetinopathyDataset

parser = argparse.ArgumentParser(description='aptos2019 blindness detection on kaggle')
parser.add_argument("--debug", help="run debug mode",
                    action="store_true")
parser.add_argument("--cv", help="do cross validation",
                    action="store_true")
parser.add_argument("--multi", help="use multi gpu",
                    action="store_true")
parser.add_argument('--config', '-c', type=str, help='path to config')
args = parser.parse_args()

def main():
    config = utils.load_yaml(args.config)
    task = config['task']
    EPOCHS = config['epoch']
    N_FOLDS = 5
    BATCH_SIZE = config['batchsize']
    IMAGE_SIZE = config['image_size']
    model_name = config['model']
    optimizer_name = config['optimizer']
    loss = config['loss']
    lr = float(config['lr'])
    n_class = config['n_class']
    lr_scheduler = config.get('lr_scheduler')
    azure_run = None
    tb_writer = None
    num_workers = 64
    experiment_name = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')

    print(f'found {torch.cuda.device_count()} gpus !!')
    try:

        if args.debug:
            print('running in debug mode')
            EPOCHS = 1
            N_FOLDS = 2
        if args.debug:
            result_dir = Path(utils.RESULT_DIR) / ('debug-' + experiment_name)
        else:
            result_dir = Path(utils.RESULT_DIR) / experiment_name
            ws = Workspace.from_config('.aml_config/config.json')
            exp = Experiment(workspace=ws, name='kaggle-aptos2019')
            azure_run = exp.start_logging()
            azure_run.log('experiment name', experiment_name)
            azure_run.log('epoch', EPOCHS)
            azure_run.log('batch size', BATCH_SIZE)
            azure_run.log('image size', IMAGE_SIZE)
            azure_run.log('model', model_name)
            azure_run.log('optimizer', optimizer_name)
            azure_run.log('loss_name', loss['name'])
            azure_run.log('lr', lr)
            azure_run.log('lr_scheduler', lr_scheduler)
            azure_run.log('task', task)
            if args.cv:
                azure_run.log('cv', N_FOLDS)
            else:
                azure_run.log('cv', 0)

        if args.multi:
            print('use multi gpu !!')

        os.mkdir(result_dir)
        print(f'created: {result_dir}')
        utils.save_yaml(result_dir / Path(args.config).name, config)

#         if not args.debug:
#             tb_writer = SummaryWriter(log_dir=result_dir)

        device = torch.device("cuda:0")
        config = {
                  'epochs': EPOCHS,
                  'multi': args.multi,
                  'batch_size': BATCH_SIZE,
                  'image_size': IMAGE_SIZE,
                  'model_name': model_name,
                  'n_class': n_class,
                  'optimizer_name': optimizer_name,
                  'loss': loss,
                  'lr': lr,
                  'lr_scheduler': lr_scheduler,
                  'task': task,
                  'device': device,
                  'num_workers': num_workers,
        }

        print(config)

        if not args.debug:
            slack.notify_start(experiment_name, config)
        train_df = pd.read_csv(utils.TRAIN_CSV_PATH)
        if args.debug:
            train_df = train_df[:1000]
        config['df'] = train_df

        skf = StratifiedKFold(n_splits=N_FOLDS, random_state=41, shuffle=True)
        indices = list(skf.split(train_df, train_df['diagnosis']))
        if not args.cv:
            print('do not use cross validation')
            indices = [indices[0]]

        # cross validation
        oof_preds = np.zeros((len(train_df), n_class))
        for i_fold, (train_index, valid_index) in tqdm(enumerate(indices)):
            model_path = result_dir / f'model_fold{i_fold}'
            config['train_index'] = train_index
            config['valid_index'] = valid_index
            config['model_path'] = str(model_path)
            if azure_run:
                if i_fold == 0:
                    config['azure_run'] = azure_run
                    y_pred, y_true = utils.run_model(**config)
                else:
                    with azure_run.child_run() as child:
                        config['azure_run'] = child
                        y_pred, y_true = utils.run_model(**config)
            else:
                y_pred, y_true = utils.run_model(**config)
            if args.cv:
                oof_preds[valid_index] = y_pred
        if args.cv:
            valid_preds = oof_preds
            valid_true = train_df['diagnosis']
        else:
            valid_preds = y_pred
            valid_true = y_true
        if task == 'class':
            round_valid_preds = np.argmax(valid_preds, axis=1)
        elif task == 'reg':
            print('optimizing threshold ...')
            optR = utils.OptimizedRounder()
            optR.fit(valid_preds, valid_true)
            coef = optR.coefficients()
            print(f'best coef: {coef}')
            if azure_run:
                azure_run.log('coef', coef)
            round_valid_preds = optR.predict(valid_preds, coef)
        val_kappa = cohen_kappa_score(round_valid_preds, valid_true,
                                      weights='quadratic')

        print(f'best val kappa: {val_kappa}')
        if azure_run:
            azure_run.log('best val kappa', val_kappa)

        test_csv = pd.read_csv(utils.TEST_CSV_PATH)
        #test_tfms = utils.build_transform(size=IMAGE_SIZE, mode='test')
        test_tfms = utils.build_transform(size=IMAGE_SIZE, mode='val')
        test_dataset = RetinopathyDataset(df=test_csv, mode='test', transform=test_tfms,
                                          auto_crop=True, add_blur=True)
        test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=BATCH_SIZE,
                                                  shuffle=False, pin_memory=True,
                                                  num_workers=num_workers)

        test_preds = np.zeros((len(test_csv), n_class))
        for i in range(len(indices)):
            model = utils.load_pytorch_model(model_name, result_dir / f'model_fold{i}', n_class)
            test_preds += utils.predict(model, test_loader, n_class=n_class, device=device, tta=1)
        test_preds /= len(indices)
        if task == 'class':
            round_test_preds = np.argmax(test_preds, axis=1)
        elif task == 'reg':
            round_test_preds = optR.predict(test_preds, coef)
        submission_csv = pd.read_csv(utils.SAMPLE_SUBMISSION_PATH)
        submission_csv['diagnosis'] = round_test_preds
        submission_csv.to_csv(result_dir / 'submission.csv', index=False)

        print('finish!!!')
        if not args.debug:
            slack.notify_finish(experiment_name, config, val_kappa)

    except KeyboardInterrupt as e:
        if not args.debug:
            slack.notify_fail(experiment_name, config,
                              e.__class__.__name__, str(e))
    except Exception as e:
        if azure_run:
            azure_run.fail(e)
        if not args.debug:
            slack.notify_fail(experiment_name, config,
                              e.__class__.__name__, str(e))
        raise
    finally:
        if azure_run:
            azure_run.complete()
            print('close azure_run')
        if tb_writer:
            tb_writer.export_scalars_to_json(os.path.join(result_dir,
                                                       'all_scalars.json'))
            tb_writer.close()
            print('close tb_writer')

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
"""Select server (this or subserver) for detection.
"""

import os
import sys
import time
import json
import glob
import pickle
import shutil
import requests

import numpy as np # type: ignore
import cv2

from multiprocessing import Process#, Queue, Value # pylint: disable=W0611
from threading import Thread, Semaphore, get_ident, Lock
from queue import Queue
#import threading, queue
#from multiprocessing import shared_memory#, Lock
import shared_memory
#from NamedAtomicLock import NamedAtomicLock
from named_atomic_lock import NamedAtomicLock
from constants import SHM_PRF

from pipesworker import PipesWorker
from images_bytes_conversions import get_np_image_from_base64, get_base64_from_np_image, get_base64_from_np_array
sys.path.append('../System')
from conversions import int_to_bytes, int_from_bytes # pylint: disable=E0401, C0413
from load_config import load_config

from constants import RUNNED, NEED_STOP_PROC, NEED_STOP_THRD, STOPPED, WAIT_DET_PROC_RESP

#from zmq_wrapper import ZmqWrapper, MON_HOST, DET_HOST, EMB_HOST, SRV_HOST
from shm_wrapper_t import ShmWrapperT

SENTINEL = -1
QUARTER_QUEUE_TEST_CID = 9900
pipe_in_name = './pipes/pipe_detector_main_'
pipe_out_name = './pipes/pipe_main_detector_'

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

import logging

logger = logging.getLogger('RunnerDetect')
logger.setLevel(logging.INFO)

# Create file handler
logger_handler = logging.FileHandler('./logs/runner_detect.log')
logger_handler.setLevel(logging.INFO)
# Create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)

#logger_formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
logger_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
logger_handler.setFormatter(logger_formatter)

logger.addHandler(logger_handler)
#logger.addHandler(ch)

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

"""class Lock():
    def __init__(self):
        self.flag = False

    def locked(self):
        return self.flag

    def release(self):
        self.flag = False

    def acquire(self):
        while self.flag:
            time.sleep(0.1 / 1000)
        self.flag = True
"""

class RunnerDetect(PipesWorker):
    def __init__(self, json_name):
        PipesWorker.__init__(self, '', '', blocked=False)

        self.json_name = json_name
        CONF_DCT = load_config(json_name)
        self.CONF_DCT = CONF_DCT
        self.DET_PROCS = CONF_DCT['DET_PROCS']
        self.EMBEDDER_BATCH = CONF_DCT['EMBEDDER_BATCH']
        self.IMAGE_SIZE = CONF_DCT['IMAGE_SIZE']
        self.N_GPUS = CONF_DCT['N_GPUS']

        self.last_loaded_id = 0

        self.imgs_dt_lst = []
        self.imgs_dt_len = 0
        self.imgs_dt_lock = Lock()

        self.shm_stop = shared_memory.SharedMemory2(name=SHM_PRF+'stop') # last_handled_id, last_saved_id, reserve
        self.shm_a = shared_memory.SharedMemory2(name=SHM_PRF+'a') # last_handled_id, last_saved_id, reserve
        self.shm_b = shared_memory.SharedMemory2(name=SHM_PRF+'b') # 4*EMBEDDER_BATCH of 160*160*3 images + 13 rect+keypoints+agegender
        self.shm_c = shared_memory.SharedMemory2(name=SHM_PRF+'c') # 4*EMBEDDER_BATCH of 512 embeddeings
        #self.shm_a_lock = NamedAtomicLock(SHM_PRF+'a_lock')
        self.shm_b_lock = Lock()  # NamedAtomicLock(SHM_PRF+'b_lock')
        #self.shm_c_lock = NamedAtomicLock(SHM_PRF+'c_lock')
        self.start_lock = Lock()
        self.stop_resp_thrd = False

        self.zmq_mon = ShmWrapperT('runner_v3_detect', 'monitor', 4096)
        self.zmq_dets = []
        for detector_id in range(self.DET_PROCS):
            zmq_detector = ShmWrapperT(f'detect_thread_{detector_id}', f'detector_{detector_id}', 4*1024*1024)
            self.zmq_dets.append(zmq_detector)
        self.last_worked_detector_id = self.DET_PROCS - 1
        self.start_string = 'python3 src/runner_v3_detect.py %s' % json_name

    def push_quarter_queue_for_all_detectors_test(self):
        fname = './saved_for_internal_tests/000000000000000000000001_9900.pkl'
        f = open(fname, 'rb')
        (req_id, client_id, img_id, nparr, status, dict_stat) = pickle.load(f)
        req_id, client_id, img_id = 0, QUARTER_QUEUE_TEST_CID, ''
        dict_stat['det_load_from_saved_tm'] = time.time()
        dict_stat['saved_queue_len'] = 100500
        #dict_stat['qsize'] = self.q.qsize()
        dict_stat['det_put_to_internal_queue_tm'] = time.time()
        data = (req_id, client_id, img_id, nparr, status, dict_stat)
        identifier, tm, msg_type = 'server3_mt', time.time(), 'send_image_test'
        dt = (identifier, tm, msg_type, data)
        for i in range(self.DET_PROCS * 2):
            self.zmq_callback_func(dt)

    def zmq_callback_func(self, dt):
        #print(f'runner_v3_detect: Runner_V3_Detect: zmq_callback_func')
        (identifier, tm, msg_type, data) = dt
        if data:
            (req_id, client_id, img_id, nparr, status, dict_stat) = data
            print(f'runner_detect: RunnerDetect: zmq_callback_func: req_id={req_id}  self.imgs_dt_len={self.imgs_dt_len}')
            self.imgs_dt_lock.acquire()
            self.imgs_dt_lst.append((req_id, client_id, img_id, nparr, status, dict_stat))
            self.imgs_dt_len += 1
            self.shm_a.buf[3*8:3*8+8] = self.imgs_dt_len.to_bytes(8, 'big')
            self.imgs_dt_lock.release()
        else:
            print(f'runner_detect: RunnerDetect: zmq_callback_func: req_id={None}  self.imgs_dt_len={self.imgs_dt_len}')

    def run(self):
        # Main thread
        print('RunnerDetect main thread started')
        id_to_load = 1 # first id to load
        last_quarter_filled_queue_tm = time.time()
        while True:
            if self.need_stop_all_processes():
                print('RunnerDetect main thread exited by need_stop_all_processes')
                break

            self.zmq_mon.send({'act': 'running', 'start_string': self.start_string}, msg_type='run')
            if self.imgs_dt_len >= 1:
                last_quarter_filled_queue_tm = time.time()
            if time.time() - last_quarter_filled_queue_tm >= 30:  # All detectors test once in 30 seconds
                self.push_quarter_queue_for_all_detectors_test()

            start_tm = time.time()
            # Load images and detect
            # # load images
            last_svd_req_id = int.from_bytes(self.shm_a.buf[0:8], 'big')

            if self.imgs_dt_len == 0:
                time.sleep(0.05)
                continue

            gogogo = False
            for _ in range(self.DET_PROCS):
                self.last_worked_detector_id += 1
                if self.last_worked_detector_id >= self.DET_PROCS:
                    self.last_worked_detector_id = 0
                shft = 8 * (6 + self.last_worked_detector_id)
                is_detector_busy_flag = int.from_bytes(self.shm_a.buf[shft:shft+8], 'big')
                if is_detector_busy_flag == 0:
                    one = 1
                    self.shm_a.buf[shft:shft+8] = one.to_bytes(8, 'big')
                    gogogo = True
                    break
            if not gogogo:
                time.sleep(0.025)
                continue

            self.imgs_dt_lock.acquire()
            (req_id, client_id, img_id, nparr, status, dict_stat) = self.imgs_dt_lst[0]
            dict_stat['det_load_from_saved_tm'] = time.time()
            dict_stat['saved_queue_len'] = self.imgs_dt_len
            self.imgs_dt_lst = self.imgs_dt_lst[1:]
            self.imgs_dt_len -= 1
            self.imgs_dt_lock.release()

            #print('Runner_V3_Detect  shm_b_empty=', shm_b_empty, '  shm_b_filled=', shm_b_filled, '  self.q.qsize()=', self.q.qsize())
            np_image = nparr #cv2.imdecode(nparr, -1)[..., ::-1]
            precisedetection = False
            dict_stat['qsize'] = 0  # self.q.qsize()
            dict_stat['det_put_to_internal_queue_tm'] = time.time()
            dict_stat['det_get_from_internal_queue_tm'] = time.time()
            #self.q.put((req_id, client_id, img_id, np_image, status, dict_stat), block=False)
            self.zmq_dets[self.last_worked_detector_id].send((req_id, client_id, img_id, np_image, dict_stat, precisedetection), msg_type='run')

        #self.stop_resp_thrd = True
        logger.error('Main thread stopped')
        logger.error('RunnerDetect: main thread stopped')
        # Join resp thread
        #resp_thr.join()

def main():
    if len(sys.argv) != 2:
        print("""USAGE: runner_detect.py cnf_file_name
EXAMPLE: runner_detect.py config_all.txt""")
        exit(1)

    r = RunnerDetect(sys.argv[1])
    r.run()

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

if __name__ == "__main__":
    main()

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


# -*- coding: UTF-8 -*-
'''
@Time: 19年6月17日 下午4:44
@Author: ChanKee
@FileName: response.py
@Description: 响应提示信息
'''
PRODUCT_ADD_SUCCESS = {
    "code": "0001",
    "status": True,
    "msg": "产品添加成功"
}

PRODUCT_EXISTS = {
    "code": "0101",
    "status": False,
    "msg": "该产品已存在"
}

PRODUCT_NOT_EXISTS = {
    "code": "0102",
    "status": False,
    "msg": "产品不存在"
}


from django.urls import path, include
from django.contrib import admin

urlpatterns = [
    path('archive/', include('archive.urls')),
    path('auth/', include('authentication.urls')),
    path('oauth/', include('oauth2_provider.urls', namespace='oauth2_provider')),
    path('timeline/', include('timeline.urls')),
    path('source/', include('source.urls')),
    path('destination/', include('destination.urls')),
]


from setuptools import find_packages, setup

INSTALL_REQUIRES = [
    "attrs>=21.4.0",
    "bs4>=0.0.1",
    "click>=7.1.2",
    "requests>=2.27.1",
    "python-dotenv>=0.19.2",
    "azure-cognitiveservices-speech>=1.20.0",
]

config = {
    "name": "chat-to-speech",
    "version": "0.0.1",
    "description": "Module for converting chat logs in html format to speech using TTS",
    "author": "Marlene Staib",
    "author_email": "marlene.staib@gmail.com",
    "packages": find_packages(include=["chat_to_speech", "chat_to_speech.*"]),
    "install_requires": INSTALL_REQUIRES,
    "entry_points": {
        "console_scripts": ["chat-to-speech=chat_to_speech.cli.main:cli"],
    },
}

setup(**config)


print("*** WELCOME TO KON BNEGA KRODPATI ***")
#INPUT NAME
contestantName = input("* What is your Name:\n")
print("WELCOME TO KBC MR.",contestantName)
#LOCATION
contestantLocation = input("* Where you came from:")
#how you feel at kbc
contestantThought = input("* Are You Excited....")
#START THE GAME
print("*** LET'S START THE GAME ***")
#QUESTIONS
questions = ["Capital of India?","India's Natinal Bird?","Longest River In World?"]
#ANSWERS
answers = ["New Delhi","Peacock","Nile 6650km"]
#PRIZE MONEY
a = 1000
b = 2000
c = 4000
d = 8000
#ADD MONEY
money = 0000
#MATCH
answer1 = input(questions[0])
if answer1 == answers[0]:
    money += a
    print("\n Congratulation You have Won ",money , "Rupees")
else:
    money =0000
    print("\n It's Wrong Answer You Loose ", a,"Rupees")

print("You Have",money,"Prize money")

## SECOND QUESTION ANS

answer2 = input(questions[1])
if answer2 == answers[1]:
    money += b
    print("\n Congratulation You have Won ",money , "Rupees")
else:
    money =money
    print("\n It's Wrong Answer You Loose ", b,"Rupees")

print("You Have",money,"Prize money")

## THIRD QUESTION ANS

answer3 = input(questions[2])
if answer3 == answers[2]:
    money += c
    print("\n Congratulation You have Won ",money , "Rupees")
else:
    money =money
    print("\n It's Wrong Answer You Loose ", c,"Rupees")

print("You Have",money,"Prize money")


import os
from flask import Flask

app = Flask(__name__)

# 使用Session必须配置如下信息
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SECRET_KEY'] = os.urandom(24)

def get_current_time_string():
    import time
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

@app.route("/")
def index():
    return """

cookie

session

    """

@app.route("/cookie")
def interface_cookie():
    def get_current_cookies_string():
        import json
        from flask import request
        return json.dumps(request.cookies)
    # end def

    from flask import make_response
    response = make_response(get_current_cookies_string())
    response.headers['Content-Type'] = 'text/json'
    #
    response.set_cookie('cookie_last', get_current_time_string())
    return response

@app.route("/session")
def interface_session():
    def get_current_sessions_string(sess):
        import json
        return json.dumps(dict(sess))
    # end def

    from flask import session
    from flask import make_response
    response = make_response(get_current_sessions_string(session))
    response.headers['Content-Type'] = 'text/json'
    #
    session['session_last'] = get_current_time_string()
    return response

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


class Student:
    def get_data(self):
        self.rollno=input("Enter student Roll no:-")
        self.name=input("Enter student Name:-")
        self.age=eval(input("Enetr student Age:-"))
    def show_data(self):
        print("Roll no:-",self.rollno)
        print("Name:-",self.name)
        print("Age:-",self.age)
class Test(Student):      #single inheritance
    def get_marks(self):
        self.sub1=eval(input("Enter marks of sub1:-"))
        self.sub2=eval(input("Enter marks of sub2:-"))
        self.sub3=eval(input("Enter marks of sub3:-"))
        #self.sub4=eval(input("Enter marks of sub4:-"))
    def put_marks(self):
        print("Marks of subject 1:-",self.sub1)
        print("Marks of subject 2:-",self.sub2)
        print("Marks of subject 3:-",self.sub3)
        self.total=self.sub1+self.sub2+self.sub3
class Result(Test):           #multilevel inheritance
    def display(self):
        self.total=self.sub1+self.sub2+self.sub3
        self.per=self.total/3
        print("Total Marks:- ",self.total)
        print("percantage:-",self.per)
r1=Result()
r1.get_data()
r1.get_marks()
r1.show_data()
r1.put_marks()
r1.display()


from montysolr.initvm import JAVA as j
from montysolr.utils import make_targets

"""The following module holds targets that do not
depend on invenio, their value is mostly for
testing"""

import os

def get_field_value(message):
    """This simply assumes the field we got passed in is a
    link to the filesystem"""

    value = message.getParam('externalVal')
    if not value:
        return
    value = str(value)
    if os.path.exists(value):
        fo = open(value, 'r')
        val = fo.read()
        fo.close()
        message.setResults(val)

def montysolr_targets():
    return make_targets(
                        "PythonTextField:get_field_value", get_field_value,
                        )


import os, sys, time

if os.path.basename(os.getcwd()) == "examples":
    base_dir = ".."
    config_path = "register.ini"
else:
    base_dir = "."
    config_path = "examples/register.ini"

sys.path.append(base_dir)
sys.path.append(f"{base_dir}/at_client/common")
sys.path.append(f"{base_dir}/at_client/connections")
sys.path.append(f"{base_dir}/at_client/util")

from configparser import ConfigParser
from argparse import ArgumentParser

import onboarding
from at_client.util import RegisterUtil, RegisterApiResult, RegisterApiTask, ApiCallStatus
from at_client.exception import AtRegistrarException

class Register:
    def __init__(self):
        self.params = {}
        self.is_registrar_v3 = False

    def main(self, args):
        parser = ArgumentParser()
        parser.add_argument("-e", "--email", help="email to register a free atsign using otp-auth")
        parser.add_argument("-k", "--api-key", help="register an atsign using super-API key")
        args = parser.parse_args(args)

        if args.email and not args.api_key:
            self.is_registrar_v3 = False
        elif not args.email and args.api_key:
            self.is_registrar_v3 = True
        else:
            parser.print_help()
            sys.exit(1)

        self.read_parameters(args.email, args.api_key)

        if self.is_registrar_v3:
            registration_flow = RegistrationFlow(self.params)
            registration_flow.add(GetAtsignV3()).add(ActivateAtsignV3()).start()
        else:
            self.params["confirmation"] = "false"
            registration_flow = RegistrationFlow(self.params)
            registration_flow.add(GetFreeAtsign()).add(RegisterAtsign()).add(ValidateOtp()).start()

        onboard_args = ["-r", self.params["rootDomain"] + ":" + self.params["rootPort"], "-a", self.params["atSign"], "-c", self.params["cram"]]
        print("Waiting 10 Seconds for server to save atsign info...")
        time.sleep(10)
        onboarding.main(onboard_args)

        return "Done."

    def read_parameters(self, email, api_key):
        try:
            config = ConfigParser()
            config.read(config_path)

            self.params["rootDomain"] = config.get("rootServer", "domain", fallback="ROOT_DOMAIN")
            self.params["rootPort"] = config.get("rootServer", "port", fallback="ROOT_PORT")
            self.params["registrarUrl"] = config.get("registrarV3" if self.is_registrar_v3 else "registrar", "url", fallback="REGISTRAR_URL")
            if not self.is_registrar_v3 and not api_key:
                self.params["apiKey"] = config.get("registrar", "apiKey", fallback="API_KEY")

            if not self.is_registrar_v3:
                self.params["email"] = email
            else:
                self.params["apiKey"] = api_key

            required_params = ["rootDomain", "rootPort", "registrarUrl", "apiKey"]
            if not all(param in self.params for param in required_params):
                print("Please make sure to set all relevant configuration in examples/register.ini")
                sys.exit(1)
        except FileNotFoundError:
            print("Config file not found.")
            sys.exit(1)

class RegistrationFlow:
    def __init__(self, params):
        self.process_flow = []
        self.result = RegisterApiResult()
        self.params = params
        self.register_util = RegisterUtil()

    def add(self, task):
        self.process_flow.append(task)
        return self

    def start(self):
        for task in self.process_flow:
            task.init(self.params, self.register_util)
            self.result = task.run()
            if self.result.api_call_status == ApiCallStatus.RETRY:
                while task.should_retry() and self.result.api_call_status == ApiCallStatus.RETRY:
                    self.result = task.run()
                    task.retry_count += 1
            if self.result.api_call_status == ApiCallStatus.SUCCESS:
                self.params.update(self.result.data)
            else:
                raise self.result.at_exception

class GetFreeAtsign(RegisterApiTask):
    def run(self):
        print("Getting free atsign ...")
        try:
            self.result.data["atSign"] = self.register_util.get_free_atsign(self.params["registrarUrl"], self.params["apiKey"])
            self.result.api_call_status = ApiCallStatus.SUCCESS
            print("Got atsign: " + self.result.data["atSign"])
        except AtRegistrarException as e:
            self.result.at_exception = e
        except Exception as e:
            print(e)
            self.result.at_exception = AtRegistrarException("error while getting free atsign")
            self.result.api_call_status = ApiCallStatus.RETRY if self.retry_count < self.max_retries else ApiCallStatus.FAILURE
        return self.result

class RegisterAtsign(RegisterApiTask):
    def run(self):
        print("Sending one-time-password to: " + self.params["email"])
        try:
            self.result.data["otpSent"] = self.register_util.register_atsign(self.params["email"], self.params["atSign"],
                                                                             self.params["registrarUrl"], self.params["apiKey"])
            self.result.api_call_status = ApiCallStatus.SUCCESS
        except Exception as e:
            self.result.at_exception = AtRegistrarException(str(e))
            self.result.api_call_status = ApiCallStatus.RETRY if self.retry_count < self.max_retries else ApiCallStatus.FAILURE
        return self.result

class ValidateOtp(RegisterApiTask):
    def run(self):
        print("Enter OTP received on " + self.params["email"] + " [note: otp is case sensitive]")
        try:
            if "otp" not in self.params:
                self.params["otp"] = input()

            print("Validating OTP ...")
            api_response = self.register_util.validate_otp(self.params["email"], self.params["atSign"],
                                                           self.params["otp"], self.params["registrarUrl"],
                                                           self.params["apiKey"], bool(self.params["confirmation"]))

            if api_response == "retry":
                print("Incorrect OTP!!! Please re-enter your OTP")
                self.params["otp"] = input()
                self.result.api_call_status = ApiCallStatus.RETRY
                self.result.at_exception = AtRegistrarException("Only 3 retries allowed to re-enter OTP - Incorrect OTP entered")
            elif api_response == "follow-up":
                self.params["confirmation"] = "true"
                self.result.api_call_status = ApiCallStatus.RETRY
            elif api_response.startswith("@"):
                self.result.data["cram"] = api_response.split(":")[1]
                print("your cram secret: " + self.result.data["cram"])
                print("Done.")
                self.result.api_call_status = ApiCallStatus.SUCCESS
        except AtRegistrarException as e:
            self.result.at_exception = e
            self.result.api_call_status = ApiCallStatus.RETRY if self.retry_count < self.max_retries else ApiCallStatus.FAILURE
        except Exception as e:
            self.result.at_exception = AtRegistrarException("Failed while validating OTP")
            self.result.api_call_status = ApiCallStatus.RETRY if self.retry_count < self.max_retries else ApiCallStatus.FAILURE
        return self.result

class GetAtsignV3(RegisterApiTask):
    def run(self):
        print("Getting atSign ...")
        try:
            self.result.data.update(self.register_util.get_atsign_v3(self.params["registrarUrl"], self.params["apiKey"]))
            print("Got atsign: " + self.result.data["atSign"])
            self.result.api_call_status = ApiCallStatus.SUCCESS
        except AtRegistrarException as e:
            self.result.at_exception = e
            self.result.api_call_status = ApiCallStatus.RETRY if self.retry_count < self.max_retries else ApiCallStatus.FAILURE
        except Exception as e:
            self.result.at_exception = AtRegistrarException("Failed while getting atSign")
            self.result.api_call_status = ApiCallStatus.RETRY if self.retry_count < self.max_retries else ApiCallStatus.FAILURE
        return self.result

class ActivateAtsignV3(RegisterApiTask):
    def run(self):
        try:
            self.result.data["cram"] = self.register_util.activate_atsign(self.params["registrarUrl"], self.params["apiKey"],
                                                                          self.params["atSign"], self.params["ActivationKey"]).split(":")[1]
            self.result.api_call_status = ApiCallStatus.SUCCESS
            print("Your cram secret: " + self.result.data["cram"])
        except AtRegistrarException as e:
            self.result.at_exception = e
            self.result.api_call_status = ApiCallStatus.RETRY if self.retry_count < self.max_retries else ApiCallStatus.FAILURE
        except Exception as e:
            self.result.at_exception = AtRegistrarException("Failed while activating atSign")
            self.result.api_call_status = ApiCallStatus.RETRY if self.retry_count < self.max_retries else ApiCallStatus.FAILURE
        return self.result

if __name__ == "__main__":
    register = Register()
    register.main(sys.argv[1:])


import zipfile
# import cloudshell.api.cloudshell_api as api
import qualipy.api.cloudshell_api as api

NameOfDriver = 'AdminOptions_CreateConnection'
ZipAddress = NameOfDriver + '.zip'
z = zipfile.ZipFile(ZipAddress, "w")
# z.write("drivermetadata.xml")
# z.write("requirements.txt")
# z.write("CreateResource.py")
z.write("CreateConnection.py")
z.write("get_cs_session.py")
z.write("__main__.py")
z.close()

ss = api.CloudShellAPISession('q1.cisco.com', 'admin', 'admin', 'Global')
# ss.UpdateScript(NameOfDriver, ZipAddress)


from os import name
import numpy as np
import pandas as pd
from sklearn import preprocessing
import matplotlib.pyplot as plt

# df = pd.read_csv(r'C:\Users\Testing\Fauzan1-02-03-20.csv')
# x=df.values
# min_max = preprocessing.MinMaxScaler()
# x_scaled = min_max.fit_transform(x)
# # df = pd.Dataframe(data=x_scaled[1:,1:], index=x_scaled[1:,0], columns=x_scaled[0,1:])
# df = pd.DataFrame.from_records(x_scaled)

# plt.plot(df.iloc[-200:,44], color = "red", label = "roll")
# plt.plot(df.iloc[-200:,45], color = "green", label = "yaw")
# plt.plot(df.iloc[-200:,46], color = "blue", label = "pitch")
# plt.plot(df.iloc[-200:,47], color = "orange", label = "pressure")

df = pd.read_csv("C:\\Users\\Testing\\Downloads\\position3d.csv")
df.drop(columns = ['Unnamed: 0'], inplace = True)

# df['Xdif'] = df['Left_ankleX'] - df['Left_ankleX'].min()
# df['Ydif'] = df['Left_ankleY'] - df['Left_ankleY'].min()
# df['Zdif'] = df['Left_ankleZ'] - df['Left_ankleZ'].min()

for i in df.columns:
    df['{}dif'.format(i)] = df[i] - df[i].mean()

for i in df.columns[-54:][2::3][8:14][:3]:
    plt.plot(df.loc[1150:1200,i], label = i)
    # plt.plot(df[i], label = i)

# plt.plot(df.loc[1000:1200,'Xdif'], color = "red", label = "X")
# plt.plot(df.loc[1000:1200,'Ydif'], color = "green", label = "Y")
# plt.plot(df.loc[1000:1200,'Zdif'], color = "blue", label = "Z")

plt.legend()
plt.title('Right Lower joints normalized with mean')
plt.show()

for i in df.columns[-54:][2::3][8:14][3:]:
    plt.plot(df.loc[1150:1200,i], label = i)

plt.legend()
plt.title('Left Lower joints normalized with mean')
plt.show()

for i in df.columns[0:54][2::3][8:14]:
    plt.scatter(df[i].std(),df[i].mean(), label = i)

plt.legend()
plt.title('Mean vs Standard Deviation')
plt.show()

for i in df.columns[0:54][2::3][8:14]:
    plt.hist(df[i], bins=72)
    plt.axvline(df[i].mean(), color='blue', linestyle='dashed', linewidth=1, label='Mean')
    plt.axvline(df[i].median(), color='red', linestyle='dashed', linewidth=1, label='Median')
    plt.legend()
    plt.title(i)
    plt.show()


# -*- coding: utf-8 -*-
import time

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as TF
from tabulate import tabulate

import megengine as mge
import megengine.functional as MF
import megengine.module as MM

module_cache = {
    "conv2d": (MM.Conv2d(32, 32, 3, 1, 0), nn.Conv2d(32, 32, 3, 1, 0).cuda()),
    "dw_conv2d": (
        MM.Conv2d(32, 32, 3, 1, 0, groups=32),
        nn.Conv2d(32, 32, 3, 1, 0, groups=32).cuda(),
    ),
    "conv3d": (MM.Conv3d(32, 32, 3, 1, 0), nn.Conv3d(32, 32, 3, 1, 0).cuda()),
    "ConvTranspose2d": (
        MM.ConvTranspose2d(32, 32, 3, 1, 0),
        nn.ConvTranspose2d(32, 32, 3, 1, 0).cuda(),
    ),
    "BatchNorm2d": (MM.BatchNorm2d(64), nn.BatchNorm2d(64).cuda()),
    "Linear": (MM.Linear(1000, 1000), nn.Linear(1000, 1000).cuda()),
}

test_cases = [
    # (mge op, torch op, small inps, large inps, unpack_inps, rep)
    (
        "adaptive_avg_pool2d",
        lambda x: MF.adaptive_avg_pool2d(x, (7, 7)),
        lambda x: TF.adaptive_avg_pool2d(x, (7, 7)),
        [(2, 32, 16, 16)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "adaptive_max_pool2d",
        lambda x: MF.adaptive_max_pool2d(x, (7, 7)),
        lambda x: TF.adaptive_max_pool2d(x, (7, 7)),
        [(2, 32, 16, 16)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    ("argsort", MF.argsort, torch.argsort, [(1000,)], [(1000, 1000),], True, 1000),
    (
        "avg_pool2d",
        lambda x: MF.avg_pool2d(x, 2),
        lambda x: TF.avg_pool2d(x, 2),
        [(2, 32, 16, 16)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "broadcast",
        lambda x: MF.broadcast_to(x, (5,) + x.shape),
        lambda x: torch.broadcast_to(x, (5,) + x.shape),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "batchedmatmul",
        MF.matmul,
        torch.matmul,
        [(8, 64, 32), (8, 32, 64)],
        [(8, 2048, 512), (8, 512, 2048)],
        True,
        1000,
    ),
    (
        "batchnrom2d",
        lambda x: module_cache["BatchNorm2d"][0](x),
        lambda x: module_cache["BatchNorm2d"][1](x),
        [(2, 64, 16, 16)],
        [(64, 64, 128, 128)],
        True,
        1000,
    ),
    (
        "concat",
        MF.concat,
        torch.cat,
        [(20, 100), (50, 100), (30, 100)],
        [(64, 512, 16, 16), (64, 512, 16, 16), (64, 512, 16, 16)],
        False,
        1000,
    ),
    (
        "conv2d",
        lambda x: module_cache["conv2d"][0](x),
        lambda x: module_cache["conv2d"][1](x),
        [(2, 32, 16, 16)],
        [(32, 32, 128, 128)],
        True,
        1000,
    ),
    (
        "conv3d",
        lambda x: module_cache["conv3d"][0](x),
        lambda x: module_cache["conv3d"][1](x),
        [(2, 32, 8, 8, 8)],
        [(32, 32, 16, 16, 16)],
        True,
        1000,
    ),
    (
        "convTranspose2d",
        lambda x: module_cache["ConvTranspose2d"][0](x),
        lambda x: module_cache["ConvTranspose2d"][1](x),
        [(2, 32, 16, 16)],
        [(32, 32, 128, 128)],
        True,
        1000,
    ),
    (
        "dropout",
        lambda x: MF.dropout(x, 0.5),
        TF.dropout,
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "dw_conv2d",
        lambda x: module_cache["dw_conv2d"][0](x),
        lambda x: module_cache["dw_conv2d"][1](x),
        [(2, 32, 16, 16)],
        [(32, 32, 128, 128)],
        True,
        1000,
    ),
    (
        "elemwise.unary",
        MF.log,
        torch.log,
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "elemwise.binary",
        MF.add,
        torch.add,
        [(100, 100), (100, 100)],
        [(64, 512, 16, 16), (64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "expand_dims",
        lambda x: MF.expand_dims(x, 0),
        lambda x: torch.unsqueeze(x, 0),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    ("gelu", MF.gelu, TF.gelu, [(100, 100)], [(64, 512, 16, 16)], True, 1000),
    ("hswish", MF.hswish, TF.hardswish, [(100, 100)], [(64, 512, 16, 16)], True, 1000),
    (
        "hsigmoid",
        MF.hsigmoid,
        TF.hardsigmoid,
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    ("isinf", MF.isinf, torch.isinf, [(100, 100)], [(64, 512, 16, 16)], True, 1000),
    (
        "indeixngMultiAxisVec",
        lambda x: x[[1, 3, 5], [1, 3, 5], [1, 3, 5], [1, 3, 5]],
        lambda x: x[[1, 3, 5], [1, 3, 5], [1, 3, 5], [1, 3, 5]],
        [(10, 10, 10, 10)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "logsigmoid",
        MF.logsigmoid,
        TF.logsigmoid,
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "leaky_relu",
        lambda x: MF.leaky_relu(x, 0.5),
        lambda x: TF.leaky_relu(x, 0.5),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "linear",
        lambda x: module_cache["Linear"][0](x),
        lambda x: module_cache["Linear"][1](x),
        [(10, 1000)],
        [(64, 128, 1000)],
        True,
        1000,
    ),
    ("matinv", MF.matinv, torch.inverse, [(10, 10)], [(30, 30)], True, 1000),
    (
        "matmul",
        MF.matmul,
        torch.matmul,
        [(64, 32), (32, 64)],
        [(2048, 1024), (1024, 2048)],
        True,
        1000,
    ),
    (
        "max_pool2d",
        lambda x: MF.max_pool2d(x, 2),
        lambda x: TF.max_pool2d(x, 2),
        [(2, 32, 16, 16)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "normal",
        lambda x: mge.random.normal(0, 1, x.shape),
        lambda x: torch.randn(x.shape, device="cuda"),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "prelu",
        MF.prelu,
        TF.prelu,
        [(100, 100), (1,)],
        [(64, 512, 16, 16), (1,)],
        True,
        1000,
    ),
    (
        "reduce.max",
        lambda x: MF.max(x, 0),
        lambda x: torch.max(x, 0),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "reduce.mean",
        lambda x: MF.mean(x, 0),
        lambda x: torch.mean(x, 0),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "reduce.mean",
        lambda x: MF.mean(x, 0),
        lambda x: torch.mean(x, 0),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    ("relu", MF.relu, TF.relu, [(100, 100)], [(64, 512, 16, 16)], True, 1000),
    ("relu6", MF.relu6, TF.relu6, [(100, 100)], [(64, 512, 16, 16)], True, 1000),
    (
        "repeat",
        lambda x: MF.repeat(x, 5),
        lambda x: torch.repeat_interleave(x, 5),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    ("silu", MF.silu, TF.silu, [(100, 100)], [(64, 512, 16, 16)], True, 1000),
    (
        "split",
        lambda x: MF.split(x, 5),
        lambda x: torch.split(x, 5),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    ("sigmoid", MF.sigmoid, TF.sigmoid, [(100, 100)], [(64, 512, 16, 16)], True, 1000),
    (
        "softmax",
        lambda x: MF.softmax(x, axis=1),
        lambda x: TF.softmax(x, dim=1),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "softplus",
        MF.softplus,
        TF.softplus,
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "squeeze",
        lambda x: MF.squeeze(x, 0),
        lambda x: torch.squeeze(x, 0),
        [(1, 100, 100)],
        [(1, 64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "stack",
        MF.stack,
        torch.stack,
        [(100, 100), (100, 100)],
        [(64, 512, 16, 16), (64, 512, 16, 16)],
        False,
        10000,
    ),
    (
        "subtensor",
        lambda x: x[0:20, 10:60],
        lambda x: x[0:20, 10:60],
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "topk",
        lambda x: MF.topk(x, 10),
        lambda x: torch.topk(x, 10),
        [(100, 100)],
        [(1000, 1000)],
        True,
        1000,
    ),
    (
        "tile",
        lambda x: MF.tile(x, (2,) * len(x.shape)),
        lambda x: torch.tile(x, (2,) * len(x.shape)),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "transpose",
        lambda x: MF.transpose(x, list(range(len(x.shape)))[::-1]),
        lambda x: torch.permute(x, list(range(len(x.shape)))[::-1]),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "where",
        lambda x: MF.where(x > 0.5, x, x),
        lambda x: torch.where(x > 0.5, x, x),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
    (
        "uniform",
        lambda x: mge.random.uniform(0, 1, x.shape),
        lambda x: torch.rand(x.shape, device="cuda"),
        [(100, 100)],
        [(64, 512, 16, 16)],
        True,
        1000,
    ),
]

def perf_func(func, inps, reps, unpack_inps, is_mge):
    if is_mge:
        mge._full_sync()
        tik = time.time()
        for _ in range(reps):
            if unpack_inps:
                out = func(*inps)
            else:
                out = func(inps)
        mge._full_sync()
    else:
        torch.cuda.synchronize()
        with torch.no_grad():
            tik = time.time()
            for _ in range(reps):
                if unpack_inps:
                    out = func(*inps)
                else:
                    out = func(inps)
        torch.cuda.synchronize()
    return time.time() - tik

def get_avg_time(func, inps, reps, unpack_inps, is_mge):
    # warm up
    for _ in range(2):
        t = perf_func(func, inps, reps, unpack_inps, is_mge)

    times = []
    for _ in range(5):
        t = perf_func(func, inps, reps, unpack_inps, is_mge)
        times.append(t)
    return np.mean(times)

def get_perf_results(mge_func, torch_func, shapes, unpack_inps, reps):
    inps = [np.random.randn(*shape) for shape in shapes]

    inps_mge = [mge.tensor(inp, dtype="float32") for inp in inps]
    avg_time_mge = get_avg_time(mge_func, inps_mge, reps, unpack_inps, True)

    inps_torch = [torch.Tensor(inp).type(torch.float).cuda() for inp in inps]
    avg_time_torch = get_avg_time(torch_func, inps_torch, reps, unpack_inps, False)

    return avg_time_mge, avg_time_torch

if __name__ == "__main__":
    header = [
        "opr_name",
        "time(mge/pytorch; small input)",
        "time(mge/pytorch; large input)",
    ]
    table = []
    for case in test_cases:
        assert len(case) == 7
        name, mge_func, torch_func, small_shapes, large_shapes, unpack_inps, reps = case
        data = []
        data.append(name)
        print("========== op: {}".format(name))

        avg_time_mge, avg_time_torch = get_perf_results(
            mge_func, torch_func, small_shapes, unpack_inps, reps
        )
        print("mge time: {}".format(avg_time_mge))
        print("torch time: {}".format(avg_time_torch))
        data.append("{:.2f}".format(avg_time_mge / avg_time_torch))

        avg_time_mge, avg_time_torch = get_perf_results(
            mge_func, torch_func, large_shapes, unpack_inps, reps
        )
        print("mge time: {}".format(avg_time_mge))
        print("torch time: {}".format(avg_time_torch))
        data.append("{:.2f}".format(avg_time_mge / avg_time_torch))
        table.append(data)
    print(tabulate(table, header, tablefmt="github"))


from import_list import *
from population import population
from datetime import datetime, timedelta
import multiprocessing
import sys
import random

import matplotlib.pyplot as plt
import numpy as np

def stop_condition(pop):
    if  pop.best_fitness["HC1"]==0 and \
        pop.best_fitness["HC2"]==0 and \
        pop.best_fitness["HC3"]==0 and \
        pop.best_fitness["SC1_max"]<=5:
        return True
    return False

def run(args):
    print("Main seed:",args["seed"])

    time_pop = datetime.now()
    pop = population(args)
    print(datetime.now()-time_pop)

    # print(pop.best_fitness, pop.best_tot_fitness)

    i = 0
    while not stop_condition(pop):
    # while datetime.now() - time_pop < timedelta(minutes=20):
    # while i < args["n_gen"]:
        # if stop_condition(pop):
        #     break
        i+=1

        print("\nGeneration",i)
        time_gen = datetime.now()

        pop.find_pop_diversity()

        # pop.tournament_selection()
        pop.variation_tournament_selection()

        pop.mutate_mp()

        pop.elitism()

        pop.find_best_individual()

        print(pop.best_fitness)
        print("tot fitness",pop.best_tot_fitness)
        print(datetime.now()-time_gen)

    # show best
    print("-----------------------------------------------")
    print("Best individual")
    print(pop.best_fitness, pop.best_tot_fitness)
    print(datetime.now()-time_pop)

if __name__ == '__main__':

    args = {}
    args["fname"] = "./data.csv"
    args["fixed_fname"] = "./fixed_data.csv"

    args["pop_size"] = 20
    args["n_gen"] = 50

    args["cpu"] = 5

    args["seed"] = random.randint(0,sys.maxsize) // args["pop_size"]

    args["t_size"] = int(0.2*args["pop_size"]) if args["pop_size"]>=10 else 1
    args["hill_climb"] = True
    args["swaps"] = 10

    run(args)


from flask import Flask, render_template, request
import cv2
import numpy as np
from tensorflow.keras.models import load_model

app = Flask(__name__)

# 감정 분석을 위한 딥 러닝 모델 로드
emotion_model = load_model('emotion_model.h5')

# 웹페이지 렌더링
@app.route('/')
def index():
    return render_template('index.html')

# 이미지 업로드 및 처리
@app.route('/upload', methods=['POST'])
def upload():
    # 업로드된 이미지를 받아옵니다.
    uploaded_image = request.files['image']

    # OpenCV를 사용하여 이미지를 읽고 얼굴을 인식합니다.
    image = cv2.imdecode(np.fromstring(uploaded_image.read(), np.uint8), cv2.IMREAD_COLOR)

    # 얼굴 인식을 위한 OpenCV 코드 (예를 들어, Haar Cascade Classifier 사용)

    # 이미지를 모델에 맞게 전처리합니다.
    resized_image = cv2.resize(face_image, (48, 48))
    grayscale_image = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)
    image_data = np.array(grayscale_image) / 255.0
    image_data = np.expand_dims(image_data, axis=0)
    image_data = image_data.reshape((1, 48, 48, 1))

    # 감정 분석 모델로 감정을 예측합니다.
    emotion_labels = ['Angry', 'Disgust', 'Fear', 'Happy', 'Sad', 'Surprise', 'Neutral']
    emotion_prediction = emotion_model.predict(image_data)
    emotion_index = np.argmax(emotion_prediction)
    predicted_emotion = emotion_labels[emotion_index]

    # 결과를 웹페이지로 반환합니다.
    return f"감정: {predicted_emotion}"

if __name__ == '__main__':
    app.run(debug=True)


from hubbot.channel import IRCChannel
from hubbot.response import IRCResponse, ResponseType
from hubbot.moduleinterface import ModuleInterface

class Join(ModuleInterface):
    triggers = ["join"]
    help = 'join <channel> - makes the bot join the specified channel(s)'

    def on_trigger(self, message):
        """
        @type message: hubbot.message.IRCMessage
        """
        if len(message.parameter_list) > 0:
            responses = []
            for param in message.parameter_list:
                channel = param
                if not channel.startswith('#'):
                    channel = '#' + channel
                responses.append(IRCResponse(ResponseType.RAW, 'JOIN {}'.format(channel), ''))
                self.bot.channels[channel] = IRCChannel(channel)
            return responses
        else:
            return IRCResponse(ResponseType.SAY, "{}, you didn't say where I should join".format(message.user.name), message.reply_to)


import inspect
from functools import update_wrapper
from typing import Any, Optional, Callable, Dict, List

from homeworks.homework2.task3.smart_args import Isolated, Evaluated, SmartArgument

class SmartArgsHandler:
    def __init__(self, function: Callable, positional_args_included: bool = False):
        """Handles smart function arguments

        :param function: function that can contain smart arguments
        :param positional_args_included: if False, then only kwargs-only parameters will be processed.
             All other parameters, including those that can be both positional and named,
             are considered positional here. This is consistent with the module inspect documentation.
        """
        self.__positional_args_included = positional_args_included

        full_arg_spec = inspect.getfullargspec(function)
        self.__positional_defaults = full_arg_spec.defaults or ()
        self.__positional_args = full_arg_spec.args
        self.__kwonly_defaults = full_arg_spec.kwonlydefaults or {}

        if not self.__positional_args_included and any(
            isinstance(arg, Isolated) or isinstance(arg, Evaluated) for arg in self.__positional_defaults
        ):
            raise ValueError(
                "The default value of the positional parameter is a Smart argument, "
                "but the ability to handle them is disabled."
            )

        self.__number_of_positional_args_without_default = len(self.__positional_args) - len(self.__positional_defaults)

        self.__function = function
        update_wrapper(self, function)

    def __handle_kwonly_args(self, kwargs: Dict[str, Any]) -> None:
        """
        Changes the value of kwargs by changing the current arguments

        :param kwargs: dictionary containing current arguments
        """
        for key in self.__kwonly_defaults:
            if isinstance(self.__kwonly_defaults[key], SmartArgument):
                kwargs[key] = self.__kwonly_defaults[key].get_new_argument(kwargs[key] if key in kwargs else None)

    def __handle_positional_args(self, args_as_list: List, kwargs: Dict[str, Any]) -> None:
        """
        Changes the value of kwargs and args_as_list, changing the current arguments

        :param args_as_list: list containing current positional arguments
        :param kwargs: dictionary containing current keyword arguments
        """
        args_as_list_len = len(args_as_list)
        for index, value in enumerate(self.__positional_defaults):
            index_in_args = index + self.__number_of_positional_args_without_default
            if args_as_list_len > index_in_args:
                if isinstance(value, SmartArgument):
                    args_as_list[index_in_args] = value.get_new_argument(args_as_list[index_in_args])
            elif self.__positional_args[index_in_args] in kwargs:
                key = self.__positional_args[index_in_args]
                args_as_list += (
                    [value.get_new_argument(kwargs[key])] if isinstance(value, SmartArgument) else [kwargs[key]]
                )
                kwargs.pop(key)
            else:
                args_as_list += [value.get_new_argument(None)] if isinstance(value, SmartArgument) else [value]

    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        args_as_list = list(args)

        self.__handle_kwonly_args(kwargs)

        if self.__positional_args_included:
            self.__handle_positional_args(args_as_list, kwargs)
        return self.__function(*args_as_list, **kwargs)

def smart_args(function: Optional[Callable] = None, *, positional_args_included: bool = False) -> Callable:
    """
    Decorator that supports smart argument handling

    :param function: function to handle smart arguments
    :param positional_args_included: if False, then only kwargs-only parameters will be processed.
        All other parameters, including those that can be both positional and named,
        are considered positional here.
    """
    if function is None:
        return lambda func: SmartArgsHandler(func, positional_args_included)

    return SmartArgsHandler(function, positional_args_included)


from neutron_lib.callbacks import events as local_events
from neutron_lib.callbacks import registry as local_registry
from neutron_lib.callbacks import resources as local_resources
from oslo_log import log as logging
import oslo_messaging
from oslo_config import cfg
import os
import netaddr
from neutron.api.rpc.callbacks.consumer import registry
from neutron.api.rpc.callbacks import events
from neutron.api.rpc.callbacks import resources
from neutron.api.rpc.handlers import resources_rpc
from neutron.services.trunk import constants
from neutron.services.trunk.rpc import agent

from kaloom_kvs_agent.common \
    import utils as kvs_utils

from kaloom_kvs_agent.common \
     import constants as a_const

from kaloom_kvs_agent \
    import kvs_net

from kaloom_kvs_agent.common \
     import config as kaloom_config

LOG = logging.getLogger(__name__)

class _TrunkAPI(object):
    def __init__(self, trunk_stub):
        self.server_api = trunk_stub

    def get_trunk(self, context, port_id):
        try:
            t = self.server_api.get_trunk_details(context, port_id)
            LOG.debug("Found trunk %(t)s for port %(p)s", dict(p=port_id, t=t))
            return t
        except resources_rpc.ResourceNotFound:
            return None
        except oslo_messaging.RemoteError as e:
            if e.exc_type != 'CallbackNotFound':
                raise
            LOG.debug("Trunk plugin disabled on server. Assuming port %s is "
                      "not a trunk.", port_id)
            return None
    def set_trunk_status(self, context, trunk_id, status):
        self.server_api.update_trunk_status(context, trunk_id, status)

@local_registry.has_registry_receivers
class KVSTrunkSkeleton(agent.TrunkSkeleton):
    """It processes Neutron Server events to create the physical resources
    associated to a logical trunk in response to user initiated API events
    (such as trunk subport add/remove). It collaborates with the KVS to
    implement the trunk control plane.
    """
    def __init__(self):
        super(KVSTrunkSkeleton, self).__init__()
        registry.unsubscribe(self.handle_trunks, resources.TRUNK)
        self._tapi = _TrunkAPI(agent.TrunkStub())
        self.kvs_rpc = kvs_utils.kvsPluginApi(a_const.TOPIC_KNID)
        kaloom_config.register_kaloomkvs_opts()
        self.vhostuser_socket_dir = cfg.CONF.kaloom_kvs.vhostuser_socket_dir

    def _get_vhost_path(self, port_id):
        sock_name = (a_const.KVS_VHOSTUSER_PREFIX + port_id)
        vhost_path = os.path.join(self.vhostuser_socket_dir, sock_name)
        return vhost_path

    def _manages_this_trunk(self, context, trunk_id):
        result = self.kvs_rpc.get_parent_port_info(context, trunk_id)
        LOG.info("rpc get_parent_port_info called %s", result)
        if a_const.KVS_PARENT_PORT_ID not in result:
            LOG.error("rpc get_parent_port_info failed result: %s", result)
            return None
        parent_port_id = result[a_const.KVS_PARENT_PORT_ID]
        ports = kvs_net.listPorts(self.vhostuser_socket_dir, a_const.KVS_VHOSTUSER_PREFIX)
        if parent_port_id in ports.keys():
            parent_port_info =  {}
            parent_port_info['kvs_device_name'] = self._get_vhost_path(parent_port_id)
            parent_port_info['kvs_port_id'] = ports[parent_port_id]
            parent_port_info['mac'] = result[a_const.KVS_MAC]
            return parent_port_info
        return None

    def _dhcp_discover_rule_pairs(self, pairs, mac):
        ipv4_addresses = {pair["ip"] for pair in pairs
                 if netaddr.IPNetwork(pair["ip"]).version == 4}

        ipv6_addresses = {pair["ip"] for pair in pairs
                 if netaddr.IPNetwork(pair["ip"]).version == 6}

        new_pairs=[]
        ##allow "dhcp discover/solicit" through kvs
        if len(ipv4_addresses) > 0:
            pair = {"ip": "0.0.0.0", "mac": mac}
            new_pairs.append(pair)

        if len(ipv6_addresses) > 0:
            pair = {"ip": kvs_utils.mac2ipv6(mac), "mac": mac}
            new_pairs.append(pair)

        return new_pairs

    def handle_trunks(self, context, resource_type, trunk, event_type):
        """This method is not required by the KVS Agent driver.
        """
        LOG.info("handle_trunks get called trunk: %s , event_type: %s", trunk, event_type)
        raise NotImplementedError()

    @local_registry.receives(local_resources.PORT_DEVICE,
                       [local_events.AFTER_DELETE])
    def agent_port_delete(self, resource, event, trigger, context, port_id,
                          **kwargs):
        """Agent informed us a VIF was removed."""
        #LOG.info("Trunk driver receives: agent port delete: port_id %s", port_id)
        #nothing to do: port_delete already deleted port and multiple attachment, anti-spoofing, static-mac.
        pass

    @local_registry.receives(local_resources.PORT_DEVICE,
                       [local_events.AFTER_UPDATE])
    def agent_port_change(self, resource, event, trigger, context,
                          device_details, **kwargs):
        """The agent has informed us a port update or create."""
        # check if the port has trunk_details, if yes plumb subports
        port_id = device_details['port_id']
        trunk = self._tapi.get_trunk(context, port_id)
        if trunk is not None:
            LOG.info("Trunk driver receives agent's trunk port_id %s event %s", port_id, event)
            if len(trunk.sub_ports)>0:
                #use existing function to handle subports
                self.handle_subports(context,'',trunk.sub_ports, events.CREATED)

    def handle_subports(self, context, resource_type, subports, event_type):
        # Subports are always created with the same trunk_id and there is
        # always at least one item in subports list
        trunk_id = subports[0].trunk_id

        parent_port_info = self._manages_this_trunk(context, trunk_id)
        if parent_port_info is None:
            LOG.info("The trunk %s is not managed by this host/agent", trunk_id)
        else:
            if event_type not in (events.CREATED, events.DELETED):
                LOG.error("Unknown or unimplemented event %s", event_type)
                return

            try:
                kvs_port_id = parent_port_info['kvs_port_id']
                LOG.debug("Event %s for subports: %s", event_type, subports)
                subport_ids = [subport.port_id for subport in subports]
                result = self.kvs_rpc.get_info_sub_port(context, subport_ids)
                if event_type == events.CREATED:
                    LOG.info("event CREATED: trunk_id %s, subports %s ", trunk_id, subports)
                    for subport in subports:
                        vlan = subport.segmentation_id
                        knid = result[subport.port_id]['knid']
                        if knid is not None:
                           # add anti-spoofing rules
                           pairs = result[subport.port_id]['pairs']
                           mac = None
                           if len(pairs) > 0:
                              mac = pairs[0]['mac']
                              #we need extra dhcp discover/solicit rules
                              pairs.extend(self._dhcp_discover_rule_pairs(pairs, mac))
                              for pair in pairs:
                                 _ip = pair['ip']
                                 _mac = pair['mac']
                                 kvs_net.add_anti_spoofing_rule(kvs_port_id, _mac, _ip, vlan = vlan )
                           ## attach interface to network, with access vlan
                           kvs_net._attach_interface(parent_port_info['kvs_device_name'], kvs_port_id, knid, vlan)
                           ## add static-mac rule
                           if mac is not None:
                              kvs_net.add_mac_entry(knid, mac, kvs_port_id, vlan)
                        else:
                           LOG.error("KNID not found for trunk's subport %s", subport.port_id)
                    #update status of trunk
                    #self._tapi.set_trunk_status(context, trunk_id, constants.ACTIVE_STATUS)
                elif event_type == events.DELETED:
                    LOG.info("event DELETED: trunk_id %s, subport_ids %s ", trunk_id, subports)
                    for subport in subports:
                        vlan = subport.segmentation_id
                        knid = result[subport.port_id]['knid']
                        if knid is not None:
                           # detach interface from network
                           kvs_net._detach_interface(parent_port_info['kvs_device_name'], kvs_port_id, vlan)
                           pairs = result[subport.port_id]['pairs']
                           if len(pairs) > 0:
                              ## delete static-mac rule
                              mac = pairs[0]['mac']
                              kvs_net.delete_mac_entry(knid, mac)
                              # delete anti-spoofing rules
                              #we need to delete extra dhcp discover/solicit rules
                              pairs.extend(self._dhcp_discover_rule_pairs(pairs, mac))
                              for pair in pairs:
                                 ip = pair['ip']
                                 mac = pair['mac']
                                 kvs_net.delete_anti_spoofing_rule(kvs_port_id, mac, ip, vlan = vlan)

            except oslo_messaging.MessagingException as e:
                LOG.error(
                    "Error on event %(event)s for subports "
                    "%(subports)s: %(err)s",
                    {'event': event_type, 'subports': subports, 'err': e})

def init_handler(resource, event, trigger, payload=None):
    """Handler for agent init event."""
    # Set up agent-side RPC for receiving trunk events;
    LOG.debug("trunk init_handler get called")
    KVSTrunkSkeleton()