import math as m
import time

from resolution import eval_, ramap
from tcasClass import *

class Dispvar:
    def __init__(self):
        """Group cor_prev"""
        self.goalcl = None #Own goal climb rate
        self.goaldes = None #Own goal descent rate
        self.raind = None #Strength of RA issued against a threat
        self.success = None #Set if any ITF.INCREASE flag is TRUE

        """Group crossing_RA"""
        self.proj_zint = None #Projected altitude of intruder at CPA

        """Group annunciation"""
        self.anyaltlost = None #Threat became non-altitude-reporting during RA
        self.anytrackdrop = None #Surveillance dropped track during RA

        """Group output"""
        self.aid = np.full(13, False, dtype=bool) #Mode A identity code
        self.ara = np.full(14, False, dtype=bool) #active RA
        self.cac = np.full(13, False, dtype=bool) #Mode C altitude code
        self.rac = np.full(4, False, dtype=bool) #RA complement
        self.mte = None #Multiple threat encounter

"""VALID"""
def determine_goal_rate(tf, g, p, dispvar):
    if(tf.permtent[6] == False):
        dispvar.goalcl = max(dispvar.goalcl, p.climbgoal[dispvar.raind])
        if(dispvar.raind == 8):
            if(g.clstrold < 8 or g.anynewthr == True):
                g.zdmodel = max(max(dispvar.goalcl, min(g.zdown, p.maxdrate)), g.zdmodel)
                if(g.anynewthr == True and g.zdmodel > p.inc_clmrate):
                    g.anyincrease = False
            dispvar.goalcl = max(dispvar.goalcl, g.zdmodel)
    else:
        dispvar.goaldes = min(dispvar.goaldes, p.desgoal[dispvar.raind])
        if(dispvar.raind == 8):
            if(g.destrold < 8 or g.anynewthr == True):
                g.zdmodel = min(min(dispvar.goaldes, max(g.zdown, p.mindrate)), g.zdmodel)
                if(g.anynewthr == True and g.zdmodel < p.inc_desrate):
                    g.anyincrease = False
            dispvar.goaldes = min(dispvar.goaldes, g.zdmodel)
"""VALID"""

"""VALID"""
def set_up_goal_rate(TF, g, p, dispvar):
    dispvar.goalcl = -p.huge
    dispvar.goaldes = p.huge
    for tf in TF:
        if(tf.iptr != None):
            dispvar.raind = eval_(tf.permtent)
            if(tf.iptr.increase_pending == False and tf.iptr.retention == False):
                if(dispvar.raind != 0):
                    determine_goal_rate(tf, g, p, dispvar)
    dispvar.success = False
    if(g.anyincrease == True):
        for tf in TF:
            if(dispvar.success != False):
                break
            if(tf.iptr.increase == True):
                dispvar.success = True
        if(dispvar.success == False):
            g.anyincrease = False
"""VALID"""

"""VALID"""
def corrective_preventive_test(g, p, dispvar):
    if(g.corrective_clm == True and g.clstrong < g.clstrold and ((m.fabs(dispvar.goalcl) > 1e-10 and g.zdown > dispvar.goalcl) or (m.fabs(dispvar.goalcl) < 1e-10 and g.zdown > -p.hystercor))):
        g.corrective_clm = False
    else:
        if(g.corrective_des == True and g.destrong < g.destrold and ((m.fabs(dispvar.goaldes) > 1e-10 and g.zdown < dispvar.goaldes) or (m.fabs(dispvar.goaldes) < 1e-10 and g.zdown < p.hystercor))):
            g.corrective_des = False
    if(g.corrective_clm == False and min(g.zdown, p.maxdrate) <= dispvar.goalcl):
        if((m.fabs(dispvar.goalcl) > 1e-10) or (m.fabs(dispvar.goalcl) < 1e-10 and g.zdown < -p.hystercor)):
            g.corrective_clm, g.anyprecor = True, True
            g.corrective_des = False
    else:
        if(g.corrective_des == False and max(g.zdown, p.mindrate) >= dispvar.goaldes):
            if((m.fabs(dispvar.goaldes) > 1e-10) or (m.fabs(dispvar.goaldes) < 1e-10 and g.zdown > p.hystercor)):
                g.corrective_des, g.anyprecor = True, True
                g.corrective_clm = False
"""VALID"""

"""VALID"""
def crossing_flag_check(itf, g, p, dispvar):
    if(itf.tacode == RA and itf.tptr != None and itf.trtru >= p.min_ri_time):
        if((itf.tptr.permtent[6] == False and itf.rz <= -p.crossthr) or (itf.tptr.permtent[6] == True and itf.rz >= p.crossthr)):
            if(itf.int_cross == False and itf.own_cross == False):
                if(itf.tptr.permtent[4] == False and itf.tptr.permtent[5] == False and itf.increase_pending == False and itf.retention == False):
                    g.anycross = True
                dispvar.proj_zint = itf.zint + (itf.zdint*min(p.tvpetbl[itf.lev], itf.trtru))
                if(g.ra[0] == False and g.ra[5] == False):
                    itf.int_cross = True
                elif(m.fabs(itf.zdint) > p.olev and ((g.ra[0] == True and g.zown > dispvar.proj_zint) or (g.ra[5] == True and g.zown < dispvar.proj_zint))):
                    itf.int_cross = True
                else:
                    itf.own_cross = True
            else:
                if((g.clstrong == 8 and g.clstrold <= 4) or (g.destrong == 8 and g.destrold <= 4)):
                    g.anycross = True
        else:
            if(itf.int_cross == True or itf.own_cross == True):
                if((itf.tptr.permtent[6] == False and itf.rz >= p.crossthr) or (itf.tptr.permtent[6] == True and itf.rz <= -p.crossthr)):
                    itf.int_cross = False
                    itf.own_cross = False
    else:
        itf.int_cross = False
        itf.own_cross = False
"""VALID"""

"""VALID"""
def load_display_and_aural_info(g, to_disp_aurl):
    if(True in g.ra[:10]):
        if(g.anycross == True):
            to_disp_aurl.vertical_control = CROSSING
            to_disp_aurl.crossing = True
        elif(g.anyreverse == True):
            to_disp_aurl.vertical_control = REVERSE
        elif(g.anyincrease == True):
            to_disp_aurl.vertical_control = INCREASE
        else:
            to_disp_aurl.vertical_control = VERTICAL_CONTROL_NONE
        if(g.maintain == True):
            to_disp_aurl.vertical_control = MAINTAIN
        if(g.corrective_clm == True):
            to_disp_aurl.combined_control = CLIMB_CORR
        elif(g.corrective_des == True):
            to_disp_aurl.combined_control = DESCEND_CORR
        else:
            to_disp_aurl.combined_control = PREVENTIVE
        if(g.ra[0] == True):
            to_disp_aurl.up_advisory = CLIMB
        elif(g.ra[1] == True):
            to_disp_aurl.up_advisory = DONT_DESCEND
        elif(g.ra[2] == True):
            to_disp_aurl.up_advisory = DONT_DESCEND500
        elif(g.ra[3] == True):
            to_disp_aurl.up_advisory = DONT_DESCEND1000
        elif(g.ra[4] == True):
            to_disp_aurl.up_advisory = DONT_DESCEND2000
        else:
            to_disp_aurl.up_advisory = UP_ADVISORY_NONE
        if(g.ra[5] == True):
            to_disp_aurl.down_advisory = DESCEND
        elif(g.ra[6] == True):
            to_disp_aurl.down_advisory = DONT_CLIMB
        elif(g.ra[7] == True):
            to_disp_aurl.down_advisory = DONT_CLIMB500
        elif(g.ra[8] == True):
            to_disp_aurl.down_advisory = DONT_CLIMB1000
        elif(g.ra[9] == True):
            to_disp_aurl.down_advisory = DONT_CLIMB2000
        else:
            to_disp_aurl.down_advisory = DOWN_ADVISORY_NONE
        to_disp_aurl.rate = g.zdmodel
    else:
        to_disp_aurl.vertical_control = VERTICAL_CONTROL_NONE
        to_disp_aurl.combined_control = COMBINED_CONTROL_NONE
        to_disp_aurl.up_advisory = UP_ADVISORY_NONE
        to_disp_aurl.down_advisory = DOWN_ADVISORY_NONE
        to_disp_aurl.rate = 0
        to_disp_aurl.crossing = False
        if(g.allclear == True):
            to_disp_aurl.combined_control = CLEAR_OF_CONFLICT
"""VALID"""

"""VALID"""
def set_up_display_outputs(g, p, to_disp_aurl, dispvar):
    if(True in g.ra[:10]):
        if(g.anyincrease == True):
            g.anyreverse, g.maintain, g.anycross = False, False, False
            if(g.previncrease == False):
                g.anycorchang, g.previncrease = True, True
        else:
            g.previncrease = False
            if((g.ra[0] == True and g.zdmodel > p.clmrt and g.zdown > p.clmrt) or (g.ra[5] == True and g.zdmodel < p.desrt and g.zdown < p.desrt)):
                g.maintain = True
                g.anyreverse = False
            else:
                if((g.clstrold == 4 and g.destrold == 4) and (g.clstrong == 0 or g.destrong == 0)):
                    g.maintain = False
            if(g.anyreverse == True):
                g.anycross = False
                g.maintain = False
            if(g.corrective_clm == False and g.corrective_des == False):
                if(g.ra[1] == True and g.ra[6] == True):
                    g.maintain = True
                else:
                    g.maintain = False
                    if(g.clstrong == 4 and g.clstrold == 8 and g.destrong == 0):
                        g.corrective_clm, g.anyprecor = True, True
                    else:
                        if(g.destrong == 4 and g.destrold == 8 and g.clstrong == 0 and g.extalt == False):
                            g.corrective_des, g.anyprecor = True, True
                g.zdmodel = 0
            else:
                if(g.ra[0] == False and g.ra[5] == False):
                    g.maintain = False
                    g.zdmodel = 0
        g.allclear = False
    else:
        g.maintain, g.anyincrease = False, False
        g.zdmodel = 0
        if(dispvar.anyaltlost == True):
            dispvar.anytrackdrop, g.allclear = False, False
        else:
            if(dispvar.anytrackdrop == True):
                g.allclear = False
    load_display_and_aural_info(g, to_disp_aurl)
"""VALID"""

"""VALID"""
def set_up_global_flags(ITF, g, p, to_disp_aurl, dispvar):
    g.alarm, g.anycorchang, g.anycross, g.allclear = False, False, False, False
    g.anyreverse, dispvar.anytrackdrop, dispvar.anyaltlost = False, False, False
    for itf in ITF:
        if(itf.tacode == RA and itf.tptr != None):
            if(g.corrective_clm == True or g.corrective_des == True):
                if(itf.tptr.permtent[10] == True or itf.tptr.permtent[11] == True):
                    if(itf.tptr.permtent[6] == False):
                        g.ra[1] = True
                        g.ra[2] = False
                        g.ra[3] = False
                        g.ra[4] = False
                    if(itf.tptr.permtent[6] == True):
                        g.ra[6] = True
                        g.ra[7] = False
                        g.ra[8] = False
                        g.ra[9] = False
                    itf.tptr.permtent[4] = True
                    itf.tptr.permtent[5] = False
                    itf.tptr.permtent[10] = False
                    itf.tptr.permtent[11] = False
                    g.zdmodel = 0
                    if(itf.tptr.permtent[6] == False):
                        g.clstrong = max(g.clstrong, eval_(itf.tptr.permtent))
                        dispvar.goalcl = 0
                    else:
                        g.destrong = max(g.destrong, eval_(itf.tptr.permtent))
                        dispvar.goaldes = 0
                    itf.tptr.poowrar = ramap(itf.tptr.permtent)
        if(np.array_equal(g.ra[:10], np.full(10, False, dtype=bool))):
            if(itf.altitude_lost == True):
                if(itf.rd <= 0):
                    dispvar.anyaltlost = True
                itf.altitude_lost = False
            else:
                if(itf.ditf == True):
                    dispvar.anytrackdrop = True
        else:
            crossing_flag_check(itf, g, p, dispvar)
            if(itf.reverse == True and (g.ra[0] == True or g.ra[5] == True)):
                g.anyreverse = True
            itf.reverse = False
            if(itf.altitude_lost == True and itf.rd > 0):
                itf.altitude_lost = False
        if(itf.clear_conflict == True):
            g.allclear = True
            itf.clear_conflict = False
    if(g.mac_reverse == True and (g.ra[0] == True or g.ra[5] == True)):
        g.anyreverse = True
        g.mac_reverse = False
    set_up_display_outputs(g, p, to_disp_aurl, dispvar)
    dispvar.success = False
    for itf in ITF:
        if(dispvar.success != False):
            break
        if(itf.int_cross == True or itf.own_cross == True):
            dispvar.success = True
    if(dispvar.success == True):
        g.crossing_ra = True
    else:
        g.crossing_ra = False
    if(g.anyreverse == True):
        g.reversal_ra = True
    if(g.anynewthr == True or g.anyprecor == True or g.anycorchang == True or (g.clstrong != 0 and (g.clstrong != g.clstrold or (g.destrong == 0 and g.destrold != 0))) or (g.destrong != 0
    and (g.destrong != g.destrold or (g.clstrong == 0 and g.clstrold != 0)))):
        g.alarm = True
"""VALID"""

"""VALID"""
def store_threat_info(TF, g, dispvar):
    dispvar.success = False
    for tf in TF:
        if(dispvar.success != False):
            break
        if(tf.new == True):
            if(tf.iptr.eqp != ATCRBS):
                g.id = tf.id
                g.active = 1
            else:
                g.pointer = tf.iptr
                g.active = 2
                g.altnew = tf.iptr.zrint
                g.rngnew = tf.iptr.r
                g.rngvalid = tf.iptr.rflg
                g.brngnew = tf.iptr.bearing
                g.brngvalid = tf.iptr.bearok
            dispvar.success = True
    for tf in TF:
        if(tf.new == True):
            tf.new = False
    for tf in TF:
        if(dispvar.success != False):
            break
        if(g.active == 2 and tf.iptr != None):
            if(tf.iptr == g.pointer):
                g.altnew = tf.iptr.zrint
                g.rngnew = tf.iptr.r
                g.rngvalid = tf.iptr.rflg
                g.brngnew = tf.iptr.bearing
                g.brngvalid = tf.iptr.bearok
                dispvar.success = True
"""VALID"""

"""VALID"""
def set_up_rac_and_mte(g, ra_to_trans, to_ground_station, dispvar):
    dispvar.rac = g.intent
    if(True in g.ra[:10]):
        if(g.macflg == True):
            dispvar.mte = True
            if(g.clstrong != 0 and g.destrong != 0):
                dispvar.ara[0] = False
            else:
                dispvar.ara[0] = True
        else:
            dispvar.mte = False
            dispvar.ara[0] = True
    else:
        for i in range(len(dispvar.ara)):
            dispvar.ara[i] = False
    if(True in g.ra[:10]):
        ra_to_trans.rai = False
    else:
        ra_to_trans.rai = True
    if((np.array_equal(g.ra[:10], np.full(10, False, dtype=bool))) and (True in g.prevra[:10])):
        to_ground_station.rat = True
    else:
        to_ground_station.rat = False
"""VALID"""

"""VALID"""
def set_up_ara(g, dispvar):
    for i in range(1,len(dispvar.ara)):
        dispvar.ara[i] = False
    if(dispvar.ara[0] == True):
        if((g.corrective_clm == True or g.corrective_des == True) and g.maintain == False):
            dispvar.ara[1] = True
        if(True in g.ra[5:10]):
            dispvar.ara[2] = True
        if(g.anyincrease == True):
            dispvar.ara[3] = True
        if(g.reversal_ra == True):
            dispvar.ara[4] = True
        if(g.crossing_ra == True):
            dispvar.ara[5] = True
        if(g.ra[0] == True or g.ra[5] == True):
            dispvar.ara[6] = True
    else:
        if(dispvar.mte == True):
            if(g.corrective_clm == True and g.maintain == False):
                dispvar.ara[1] = True
            if(g.ra[0] == True):
                dispvar.ara[2] = True
            if(g.corrective_des == True and g.maintain == False):
                dispvar.ara[3] = True
            if(g.ra[5] == True):
                dispvar.ara[4] = True
            if(g.crossing_ra == True):
                dispvar.ara[5] = True
            if(g.reversal_ra == True):
                dispvar.ara[6] = True
"""VALID"""

"""VALID"""
def set_up_tti_and_tid(g, ra_to_trans):
    ra_to_trans.tti[0] = False
    ra_to_trans.tti[1] = False
    for i in range(len(ra_to_trans.tid)):
        ra_to_trans.tid[i] = False
    if(g.active == 2):
        ra_to_trans.tti[0] = True
        ra_to_trans.tti[1] = False
        """Pass ra_to_trans.tid"""
    else:
        if(g.active == 1):
            ra_to_trans.tti[0] = False
            ra_to_trans.tti[1] = True
"""VALID"""

"""VALID"""
def set_up_ra_broadcast(g, ra_to_trans, to_ground_station, dispvar):
    set_up_rac_and_mte(g, ra_to_trans, to_ground_station, dispvar)
    if(True in g.ra[:10]):
        set_up_ara(g, dispvar)
    set_up_tti_and_tid(g, ra_to_trans)
    g.prevmte = g.macflg
"""VALID"""

"""OK"""
def broadcast(TF, g, o, p, ra_to_trans, to_ground_station, brdcst_data, dispvar):
    store_threat_info(TF, g, dispvar)
    set_up_ra_broadcast(g, ra_to_trans, to_ground_station, dispvar)
    if(g.brdcst == False):
        if(True in g.ra[:10]):
            g.brdcst = True
    if(g.brdcst == True and (g.ncycle == p.rabrdcst or to_ground_station.rat == True)):
        if(to_ground_station.rat == True):
            to_ground_station.ara = brdcst_data.prv_ara
            to_ground_station.rac = brdcst_data.prv_rac
            to_ground_station.mte = brdcst_data.prv_mte
            to_ground_station.aid = brdcst_data.prv_aid
            to_ground_station.cac = brdcst_data.prv_cac
        else:
            to_ground_station.ara = dispvar.ara
            to_ground_station.rac = dispvar.rac
            to_ground_station.mte = dispvar.mte
            g.aid = o.aid
            if(g.airdata == True):
                """Pass g.cac"""
                pass
            to_ground_station.aid = g.aid
            to_ground_station.cac = g.cac
            brdcst_data.prv_ara = dispvar.ara
            brdcst_data.prv_rac = dispvar.rac
            brdcst_data.prv_mte = dispvar.mte
            brdcst_data.prv_aid = g.aid
            brdcst_data.prv_cac = g.cac
        if(np.array_equal(g.ra[:10], np.full(10, False, dtype=bool))):
            g.brdcst, g.brngvalid, g.rngvalid = False, False, False
            g.crossing_ra, g.reversal_ra = False, False
            g.active, g.id = 0, 0
            g.altnew, g.brngnew, g.rngnew = 0, 0, 0
            g.pointer = None
            g.ncycle = p.rabrdcst
    if(g.brdcst == True):
        g.ncycle -= 1
    if(g.ncycle == 0):
        g.ncycle = p.rabrdcst
"""OK"""

# def send_atcrbs_info_to_surveillance(ITF, g, ATCRBSList):
#     ATCRBSList.clear()
#     if(g.tamode == True):
#         for itf in ITF:
#             if(itf.eqp == ATCRBS and itf.tacode >= TANMC):
#                 pass

"""VALID"""
def display_advisories(ITF, TF, g, o, p, realtime, to_disp_aurl, ra_to_trans, to_ground_station, brdcst_data, dispvar):
    time_lock_begin = time.time()
    while (g.colock == True):
        if ((time.time() - time_lock_begin) > p.tunlock):
            assert ()
        time.sleep(0.01)
    g.colock = True
    g.tlock = realtime.tclock
    g.clstrold = g.clstrong
    g.destrold = g.destrong
    g.anynewthr, g.anyprecor = False, False
    g.destrong, g.clstrong = 0, 0
    for tf in TF:
        if(tf.poowrar != 0):
            if(tf.iptr != None):
                if(tf.iptr.increase_pending == False and tf.iptr.retention == False):
                    if(tf.permtent[6] == False):
                        g.clstrong = max(g.clstrong, eval_(tf.permtent))
                    else:
                        g.destrong = max(g.destrong, eval_(tf.permtent))
            if(tf.new == True):
                g.anynewthr = True
    if(g.clstrong == 8):
        if(g.clstrold < 8):
            g.tposra = g.tcur
            g.ztv = g.zown
            g.zdtv = g.zdown
    else:
        if(g.destrong == 8):
            if(g.destrold < 8):
                g.tposra = g.tcur
                g.ztv = g.zown
                g.zdtv = g.zdown
    set_up_goal_rate(TF, g, p, dispvar)
    corrective_preventive_test(g, p, dispvar)
    set_up_global_flags(ITF, g, p, to_disp_aurl, dispvar)
    broadcast(TF, g, o, p, ra_to_trans, to_ground_station, brdcst_data, dispvar)
    if(g.transvi == 0):
        ra_to_trans.rac = g.intent
        ra_to_trans.ara = g.ra
    else:
        ra_to_trans.ara = dispvar.ara
        ra_to_trans.rac = dispvar.rac
        ra_to_trans.mte = dispvar.mte
    g.colock = False
    g.prevra = g.ra
    # send_atcrbs_info_to_surveillance()
"""VALID"""


import json
import requests

class IntStream:
    def __init__(self, api_key, leila1, leila2):
        self.api_key = api_key
        self.leila1 = leila1
        self.leila2 = leila2
        self.stream = []
        self.response = {'last': 0, 'new': 0}

    def get_api_response(self, base_url):
        response = requests.get(
                            base_url,
                            headers = {
                            "x-api-key": self.api_key,
                            },
                            verify = True,  # Verify SSL certificate
                        )
        data = response.json()['data']
        return data

    def sort_responses(self):
        leila1_response = self.get_api_response(self.leila1)
        leila2_response = self.get_api_response(self.leila2)
        self.stream.append(leila1_response['next'])
        self.stream.append(leila2_response['next'])
        self.stream.sort()
        return self.stream

    def insert_values(self):
        self.sort_responses()
        self.response['last']=self.response['new']
        self.response['new']= self.stream.pop(0)
        return self.response


import socket
import re

class _Proxy:
    proxyhost = "127.0.0.1"
    proxyport = 9999

    def __init__(self, host, port):
        self.host = host
        self.port = port
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        retval = sock.connect_ex((_Proxy.proxyhost, _Proxy.proxyport))
        if retval == 0:
            self.socket = sock
        else:
            self.socket = None

    def close(self):
        self.socket.close()

def makeConnection(location, port=80, proxy=False):
    """ Description: Establish a TCP connection from the client machine and
        process running this function to a presumed server listening at the
        given port (80 by default) and located at Internet endpoint given by
        location.

        Returns an established socket connection, if successful, and None on
        failure.
    """
    if proxy:
        proxy_object = _Proxy(location, port)
        return proxy_object

    endsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    retval = endsocket.connect_ex((location, port))
    if retval == 0:
        return endsocket
    print("Error connecting to", str((location, port)))
    return None

def sendStringRequest(connection, text):
    """ Description: given an established socket connection, take text, a string,
        and send it over the connection.  Before transmission over the network,
        a simple translation is done so that any LF characters in the string
        that do not have a preceeding CR are translated into CRLF, as expected
        by HTTP.  If text does not end in a LF or CRLF, one is appended.

        No return.
    """
    if isinstance(connection, _Proxy):
        conn = connection.socket
    else:
        conn = connection

    LF = '\n'
    CR = '\r'
    CRLF = '\r\n'

    offset = 0
    while offset < len(text):
        indexLF = text.find(LF, offset)
        if indexLF == -1:
            s = text[offset:]
            #print("Case 0: |{}| + CRLF".format(s))
            offset = len(text)
        elif indexLF == 0:          # starts with LF, no preceeding CR => CRLF
            s = ""
            #print("Case 1: || + CRLF")
            offset += 1
        elif text[indexLF - 1] == CR:
            s = text[offset:indexLF-1]
            #print("Case 2: |{}| + CRLF".format(s))
            offset = indexLF + 1
        else:
            s = text[offset:indexLF]
            #print("Case 3: |{}| + CRLF".format(s))
            offset = indexLF + 1

        s_crlf = s + CRLF
        conn.sendall(s_crlf.encode("utf-8"))

def receiveByLine(connection):
    line = ""
    abyte = connection.recv(1)
    achar = abyte.decode("utf-8")
    #print(achar)
    while achar != '\n':
        line += achar
        abyte = connection.recv(1)
        achar = abyte.decode("utf-8")
        #print(achar)
    if line[-1] == '\r':
        return line[:-1]
    else:
        return line

def receiveBySize(connection, size, eol=True):
    LF = '\n'
    CR = '\r'
    CRLF = '\r\n'

    fragments = []
    remaining = size
    while remaining > 0:
        chunk = connection.recv(remaining)
        if not chunk:
            break
        bytesread = len(chunk)
        fragments.append(chunk.decode("utf-8"))
        remaining -= bytesread
    s = "".join(fragments)
    if eol:
        return s.replace(CRLF, LF)
    else:
        return s

def receiveTillClose(connection, eol=True):
    LF = '\n'
    CR = '\r'
    CRLF = '\r\n'
    fragments = []
    chunk = connection.recv(1024)
    while chunk and chunk != '':
        bytesread = len(chunk)
        fragments.append(chunk.decode("utf-8"))
        chunk = connection.recv(1024)
    s = "".join(fragments)
    if eol:
        return s.replace(CRLF, LF)
    else:
        return s

def parseHeader(headerLine):
    pattern = r"^([\w\-_]+): (.*)$"
    match = re.search(pattern, headerLine)
    assert match
    return match.group(1), match.group(2)

def receiveStringResponse(connection, eol=True):
    if isinstance(connection, _Proxy):
        conn = connection.socket
    else:
        conn = connection
    LF = '\n'
    CR = '\r'
    CRLF = '\r\n'

    response = ""
    content_length = None
    connection_close = False
    startLine = receiveByLine(conn)
    response += startLine + LF
    endHeaders = False
    while not endHeaders:
        headerLine = receiveByLine(conn)
        if headerLine == "":
            endHeaders = True
        else:
            field, value = parseHeader(headerLine)
            #print(field, value)
            if field.lower() == "content-length":
                content_length = int(value)
            if field.lower() == "connection" and value.lower() == "close":
                connection_close = True
        response += headerLine + LF

    if content_length:
        response += receiveBySize(conn, content_length, eol)

    if connection_close:
        response += receiveTillClose(conn, eol)

    return response


# 데이터 중복 제거하기

import json
import pickle

open_file = open("test_img.pkl", "rb")
df = pickle.load(open_file)

print(df.head())
df_processed = df.drop_duplicates(subset=['title'])
print(df_processed.info())

js = df_processed.to_json(orient='index', force_ascii=False)
js_js = json.loads(js)

save_file_path = f'./coupang_data_img.json'

with open(save_file_path, 'w') as outfile:
    json.dump(js_js, outfile, indent=4, ensure_ascii = False)

print('done:',save_file_path)


from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect

from .forms import SeqForm

import os, sys

sys.path.append('./AMPSVM/code')
import descripGen_12, predictSVC

def seq(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = SeqForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            seq = form.cleaned_data['seq']
            if seq is not None:
                f = open('seqs.txt', 'w+')
                f.write('     1 ')
                f.write(seq)
                f.close()
            # redirect to a new URL:
            if len(seq) >= 8 and len(seq) <= 100:
                return redirect('/result/')
            else:
                return redirect('/fail/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = SeqForm()

    return render(request, 'svm/seq.html', {'form': form})

def result(request):

    os.chdir('./AMPSVM/code')

    descripGen_12.main('./aaindex','../../seqs.txt',1,1)
    predictSVC.main('descriptors.csv','Z_score_mean_std__intersect_noflip.csv','svc.pkl')

    with open('descriptors_PREDICTIONS.csv','r') as fin:
        line = fin.readline()
        headers = line.strip().split(',')
        line = fin.readline()
        data = line.strip().split(',')
        seqIndex = data[0]
        prediction = data[1]
        distToMargin = data[2]
        P_neg1 = data[3]
        P_plus1 = data[4]

    os.chdir('../..')

    distToMargin = '%6.2f' % (float(distToMargin))
    P_neg1 = '%6.2f' % (float(P_neg1))
    P_plus1 = '%6.2f' % (float(P_plus1))

    return render(request, 'svm/result.html', {'seqIndex' : seqIndex, 'prediction' : prediction, 'distToMargin' : distToMargin, 'P_neg1' : P_neg1, 'P_plus1' : P_plus1})

def fail(request):

    return render(request, 'svm/fail.html')


from flask import Flask, request
from datetime import datetime

amazon_killer = Flask(__name__)

USERS_DATABASE = {}
user_counter = 1

class NoSuchUser(Exception):
    def __init__(self, user_id):
        self.user_id = user_id

@amazon_killer.route('/users', methods=["POST"])
def create_user():
    global user_counter
    user = request.json
    user['user_id'] = user_counter
    response = {
        "registration_timestamp": datetime.now().isoformat(),
        "user_id": user_counter
    }
    user["registration_timestamp"] = response['registration_timestamp']
    USERS_DATABASE[user_counter] = user

    user_counter += 1

    return response, 201

@amazon_killer.errorhandler(NoSuchUser)
def no_such_user_handler(e):
    return {"error": "no such user with id 1"}, 404

@amazon_killer.route('/users/<int:user_id>')
def get_user(user_id):
    try:
        user = USERS_DATABASE[user_id]
    except KeyError:
        raise NoSuchUser(user_id)
    else:
        return user

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


# Independent t test for 4092 parameters

import numpy as np
from scipy import stats
import statsmodels.api as sm

params = np.load(r'D:\cnnface\gender_analysis\human_result\exp\gender\label/param_exp.npy')
label = np.load(r'D:\cnnface\gender_analysis\human_result\exp\gender\label/label_sum.npy')

label_0 = np.argwhere(label == 0).astype('int32')
label_1 = np.argwhere(label == 1).astype('int32')

s_sum = []
p_sum = []
dis_sum = []
for i in range(4092):
    x_5000 = params[:, i]
    x_0 = x_5000[label_0]
    x_1 = x_5000[label_1]

    s, p = stats.ttest_ind(x_0, x_1)
    s_sum.append(s)
    p_sum.append(p)

    d = lambda x1, x2: (x1.mean() - x2.mean()) / np.sqrt(((np.std(x1))**2 + (np.std(x2))**2)/2)
    #dis = np.abs(d(x_0,x_1))
    dis = d(x_0, x_1)
    dis_sum.append(dis)

p_sum = np.squeeze(np.array(p_sum))
s_sum = np.squeeze(np.array(s_sum))
p_sum_sign = p_sum[p_sum < (0.05/4092)]
#p_signIndex = np.squeeze(np.argwhere(p_sum < (0.05/4092)))
p_signIndexFDR = sm.stats.multipletests(p_sum,alpha=0.05,method='fdr_bh')
p_minsignIndex = np.squeeze(np.argwhere(p_sum == p_sum_sign.max()))

# np.save(r'D:\cnnface\gender_analysis\human_result\para_significant/p_sum.npy', p_sum)
# np.save(r'D:\cnnface\gender_analysis\human_result\para_significant/s_sum.npy', s_sum)
# np.save(r'D:\cnnface\gender_analysis\human_result\para_significant/cohensd_sum_.npy', dis_sum)
# np.save(r'D:\cnnface\gender_analysis\human_result\para_significant/p_signIndexFDR.npy', p_signIndexFDR)
# np.save(r'D:\cnnface\gender_analysis\human_result\para_significant/p_minsignIndex.npy', p_minsignIndex)

np.save(r'D:\cnnface\gender_analysis\human_result\para_significant/cohensd_unabs.npy', dis_sum)


from django.utils.translation import ugettext_lazy as _
from enum import Enum, IntEnum, unique

# @unique
# class OperatingActivities(Enum):  # Store As Integer
#     SALES = 10
#     PURCHASES = 20
#     INVENTORY = 30
#     PAYROLL = 40
#     SALES_TAXES = 50
#     OTHER = 60
#     NET = 70
#
#     @property
#     def label(self):
#         labels = {
#             self.NOT_YET_DUE: "Not Yet Overdue",
#             self.ZERO_TO_THIRTY: "30 or Less",
#             self.THIRTY_TO_SIXTY: "31 to 60",
#             self.SIXTY_TO_NINETY: "61 to 90",
#             self.OVER_NINETY: "91 or More",
#             self.TOTAL_UNPAID: "Total Unpaid",
#         }
#
#         return labels[self]

# class ChoiceEnum(Enum):  # Store As String
#     @classmethod
#     def choices(cls):
#         return tuple((x.name, x.value) for x in cls)
#
# class Car(models.Model):
#     # Encapsulation, we meet again.
#     class Colors(ChoiceEnum):
#         RED = 'red'
#         WHITE = 'white'
#         BLUE = 'blue'
#
#     color = models.CharField(max_length=5, choices=Colors.choices(), default=Colors.RED)

AWS_S3_STATICFILES = 'http://js-crm-staticfiles.s3.amazonaws.com'

@unique
class STATUS(Enum):
    INITIAL = 'Initial'  # default status while created
    CONTACTED = 'Contacted'  # After agent get back to the student
    CONSIDERATION = 'Consideration'  # student hasn't decided
    NOT_INTERESTED = 'Not Interested'  # no longer interested
    BECAME_STUDENT = 'Student'  # became student
    DROP_OUT = 'Drop Out'  # drop out after became student
    OTHER = 'Other'  # other undefined status

STATUS_NAME = {
    STATUS.INITIAL: _('Initial'),
    STATUS.CONTACTED: _('Contacted'),
    STATUS.CONSIDERATION: _('Consideration'),
    STATUS.NOT_INTERESTED: _('Not Interested'),
    STATUS.BECAME_STUDENT: _('Student'),
    STATUS.DROP_OUT: _('Drop Out'),
    STATUS.OTHER: _('Other'),
}

@unique
class OFFICE(IntEnum):
    TP = 1
    TC = 2
    KS = 3

OFFICE_NAME = {
    OFFICE.TP: _('TP'),
    OFFICE.TC: _('TC'),
    OFFICE.KS: _('KS'),
}

@unique
class TYPE(IntEnum):
    ESL = 10
    COOP = 20
    STUDY = 30
    CAMP = 40
    DIPLOMA = 50
    WORK = 60
    OTHER = 99

TYPE_NAME = {
    TYPE.ESL: _('ESL'),
    TYPE.COOP: _('COOP'),
    TYPE.STUDY: _('STUDY'),
    TYPE.CAMP: _('CAMP'),
    TYPE.DIPLOMA: _('DIPLOMA'),
    TYPE.WORK: _('WORK'),
    TYPE.OTHER: _('OTHER'),
}

@unique
class BUDGET(IntEnum):
    RANGE_1 = 10
    RANGE_2 = 20
    RANGE_3 = 30
    RANGE_4 = 40

BUDGET_NAME = {
    BUDGET.RANGE_1: _('budget_range_1'),
    BUDGET.RANGE_2: _('budget_range_2'),
    BUDGET.RANGE_3: _('budget_range_3'),
    BUDGET.RANGE_4: _('budget_range_4'),
}

@unique
class BUDGET_SOURCE(IntEnum):
    PERSONAL = 10
    FAMILY = 20
    LOAN = 30
    OTHER = 99

BUDGET_SOURCE_NAME = {
    BUDGET_SOURCE.PERSONAL: _('PERSONAL'),
    BUDGET_SOURCE.FAMILY: _('FAMILY'),
    BUDGET_SOURCE.LOAN: _('LOAN'),
    BUDGET_SOURCE.OTHER: _('OTHER'),
}

@unique
class TARGET_COUNTRY(IntEnum):
    CANADA = 10
    US = 20
    UK = 30
    IRELAND = 40
    PHILIPPINE = 50
    OTHER = 99

TARGET_COUNTRY_NAME = {
    TARGET_COUNTRY.CANADA: _('CANADA'),
    TARGET_COUNTRY.US: _('US'),
    TARGET_COUNTRY.UK: _('UK'),
    TARGET_COUNTRY.IRELAND: _('IRELAND'),
    TARGET_COUNTRY.PHILIPPINE: _('PHILIPPINE'),
    TARGET_COUNTRY.OTHER: _('OTHER'),
}

@unique
class TARGET_LENGTH(IntEnum):
    LENGTH_1 = 10
    LENGTH_2 = 20
    LENGTH_3 = 30
    LENGTH_4 = 40
    LENGTH_5 = 50

TARGET_LENGTH_NAME = {
    TARGET_LENGTH.LENGTH_1: _('target_length_1'),
    TARGET_LENGTH.LENGTH_2: _('target_length_2'),
    TARGET_LENGTH.LENGTH_3: _('target_length_3'),
    TARGET_LENGTH.LENGTH_4: _('target_length_4'),
    TARGET_LENGTH.LENGTH_5: _('target_length_5'),
}


from tkinter import *
import pyodbc
import tkinter as tk

from classAdd import *
from classShow import *
from classModify import *
from classDelete import *

class GUI:

    def __init__(self, master):

        '''
        GUI
        '''
        self.master = master
        self.frame = Frame(self.master)
        self.frame.pack()

        '''
        pyodbc
        '''
        # try:
        self.connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'
                                'SERVER=localhost;'
                                'DATABASE=dbBiblioteca;'
                                'Trusted_Connection=yes;')

        self.cursor = self.connection.cursor()

        self.master.title("Interfaz de DB")
        self.master.geometry("300x200")

        self.search_button = Button(self.master, text="Mostrar", command=self.show_window)
        self.search_button.place(relx=0.5, rely=0.1, anchor=CENTER)

        self.add_button = Button(self.master, text="Agregar", command=self.add_window)
        self.add_button.place(relx=0.5, rely=0.3, anchor=CENTER)

        self.modify_button = Button(self.master, text="Modificar", command=self.modify_window)
        self.modify_button.place(relx=0.5, rely=0.5, anchor=CENTER)

        self.delete_button = Button(self.master, text="Eliminar", command=self.delete_window)
        self.delete_button.place(relx=0.5, rely=0.7, anchor=CENTER)

    def show_window(self) -> None:
        self.show_Window = tk.Toplevel(self.master)
        self.app = Show(self.show_Window, self.cursor)

    def add_window(self) -> None:
        self.add_Window = tk.Toplevel(self.master)
        self.app2 = Add(self.add_Window, self.cursor)

    def modify_window(self) -> None:
        self.modify_Window = tk.Toplevel(self.master)
        self.app3 = Modify(self.modify_Window, self.cursor)

    def delete_window(self) -> None:
        self.delete_Window = tk.Toplevel(self.master)
        self.app4 = Delete(self.delete_Window, self.cursor)

def main():
    root = tk.Tk()
    GUI.show_window
    app = GUI(root)
    root.mainloop()

main()


# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long
# pylint: disable=too-many-lines
# pylint: disable=too-many-statements

from azure.cli.core.commands.parameters import (
    name_type,
    tags_type,
    get_enum_type,
    get_location_type
)
from azure.cli.core.commands.validators import get_default_location_from_resource_group

from knack.arguments import CLIArgumentType
from ._validators import iso_8601_timespan

environment_name_type = CLIArgumentType(id_part='name', help='The name of the Time Series Insights environment associated with the specified resource group.')

def load_arguments(self, _):

    with self.argument_context('timeseriesinsights operation list') as c:
        pass

    with self.argument_context('timeseriesinsights') as c:
        c.argument('location', get_location_type(self.cli_ctx), validator=get_default_location_from_resource_group)
        c.argument('tags', tags_type)

    # region environment
    with self.argument_context('timeseriesinsights environment') as c:
        from .vendored_sdks.timeseriesinsights.models import SkuName
        c.argument('environment_name', arg_type=name_type, id_part='name', help='The name of the Time Series Insights environment associated with the specified resource group.')
        c.argument('sku_name', arg_group="SKU", arg_type=get_enum_type(SkuName), help='The sku determines the type of environment, either standard (S1 or S2) or long-term (L1). For standard environments the sku determines the capacity of the environment, the ingress rate, and the billing rate.')
        c.argument('sku_capacity', type=int, arg_group="SKU", help='The capacity of the sku. For standard environments, this value can be changed to support scale out of environments after they have been created.')

    with self.argument_context('timeseriesinsights environment standard') as c:
        from .vendored_sdks.timeseriesinsights.models import StorageLimitExceededBehavior
        c.argument('storage_limit_exceeded_behavior', arg_type=get_enum_type(StorageLimitExceededBehavior))
        c.argument('data_retention_time', type=iso_8601_timespan, help='The minimum number of days the environment\'s events will be available for query.')
        c.argument('partition_key_properties', nargs='+')

    with self.argument_context('timeseriesinsights environment longterm') as c:
        c.argument('storage_account_name', arg_group="Storage Configuration", help='The name of the storage account that will hold the environment\'s long term data.')
        c.argument('storage_management_key', arg_group="Storage Configuration", help='The value of the management key that grants the Time Series Insights service write access to the storage account. This property is not shown in environment responses.')
        c.argument('time_series_id_properties', nargs='+')
        c.argument('data_retention', type=iso_8601_timespan, help='The number of days the environment\'s events will be available for query from the warm store.')
    # endregion

    # region event-source
    with self.argument_context('timeseriesinsights event-source') as c:
        from .vendored_sdks.timeseriesinsights.models import LocalTimestampFormat
        c.argument('environment_name', arg_type=environment_name_type)
        c.argument('event_source_name', arg_type=name_type, id_part='child_name_1', help='The name of the Time Series Insights event source associated with the specified environment.')
        c.argument('local_timestamp_format', arg_group="Local Timestamp", arg_type=get_enum_type(LocalTimestampFormat), help='An enum that represents the format of the local timestamp property that needs to be set. Currently only Embedded is supported.')
        c.ignore('time_zone_offset_property_name')
        # c.argument('time_zone_offset_property_name', arg_group="Local Timestamp", help='The event property that will be contain the offset information to calculate the local timestamp. When the LocalTimestampFormat is Iana, the property name will contain the name of the column which contains IANA Timezone Name (eg: Americas/Los Angeles). When LocalTimestampFormat is Timespan, it contains the name of property which contains values representing the offset (eg: P1D or 1.00:00:00)')
    # endregion

    # region reference-data-set
    with self.argument_context('timeseriesinsights reference-data-set') as c:
        c.argument('environment_name', arg_type=environment_name_type)
        c.argument('reference_data_set_name', arg_type=name_type, id_part='child_name_1', help='Name of the reference data set.')

    with self.argument_context('timeseriesinsights reference-data-set create') as c:
        from .vendored_sdks.timeseriesinsights.models import DataStringComparisonBehavior
        c.argument('key_properties', nargs='+', help='The list of key properties for the reference data set. Format: NAME TYPE ...')
        c.argument('data_string_comparison_behavior', arg_type=get_enum_type(DataStringComparisonBehavior))
    # endregion

    # region access-policy
    with self.argument_context('timeseriesinsights access-policy') as c:
        from .vendored_sdks.timeseriesinsights.models import AccessPolicyRole
        c.argument('environment_name', arg_type=environment_name_type)
        c.argument('access_policy_name', arg_type=name_type, id_part='child_name_1', help='The name of the Time Series Insights access policy associated with the specified environment.')
        c.argument('principal_object_id')
        c.argument('description', help='A description of the access policy.')
        c.argument('roles', arg_type=get_enum_type(AccessPolicyRole), nargs='+')
    # endregion

    for item in ['event-source', 'reference-data-set', 'access-policy']:
        with self.argument_context('timeseriesinsights {} list'.format(item)) as c:
            c.argument('environment_name', arg_type=environment_name_type, id_part=None)


# Created by yongxinwang at 2019-09-16 19:07
from PIL import Image, ImageDraw
import os
import numpy as np
import cv2

def draw_boxes(image, boxes):
    for j, box in enumerate(boxes):
        x0, y0, x1, y1 = box[0], box[1], box[0] + box[2], box[1] + box[3]
        id = curr_tracks[j, 1]
        cls = curr_tracks[j, 7]
        cv2.rectangle(image, (int(x0), int(y0)), (int(x1), int(y1)), color=(255, 255, 255))
        cv2.putText(image, str(id), (int(x0), int(y0-10)),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.7, (100,255,100), 2)

        cv2.putText(image, "cls: "+str(cls), (int(x0 + 70), int(y0 - 10)),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.7, (100, 255, 100), 2)
    return image

# sequence = "MOT17-02-DPM"
# sequence = "MOT17-13-DPM"
sequence = "MOT17-09-DPM"
image_dir = "/hdd/yongxinw/MOT17/MOT17/train/{}/img1/".format(sequence)
exp_dir = "/hdd/yongxinw/MOT17/experiments/debug9/{}".format(sequence)
track_file = "Sep-18-at-12-41.txt"

tracks = np.loadtxt(os.path.join(exp_dir, track_file))

for i, frame in enumerate(range(7, 525)):
    # curr_tracks = tracks[(tracks[:, 0] == frame) & (tracks[:, 7] == 1) & (tracks[:, 8] >= 0.6)]
    curr_tracks = tracks[(tracks[:, 0] == frame)]
    prev_tracks = tracks[(tracks[:, 0] == frame - 1)]
    # curr_tracks = curr_tracks[curr_tracks[:, 5] > 120]
    # curr_tracks = curr_tracks[:25]
    curr_boxes = curr_tracks[:, 2:6]
    prev_boxes = prev_tracks[:, 2:6]

    curr_image = cv2.imread(os.path.join(image_dir, "%06d.jpg" % frame))
    curr_image = draw_boxes(curr_image, curr_boxes)

    prev_image = cv2.imread(os.path.join(image_dir, "%06d.jpg" % (frame-1)))
    prev_image = draw_boxes(prev_image, prev_boxes)

    image = np.hstack((prev_image, curr_image))
    cv2.imwrite(os.path.join(exp_dir, "links", "track-%06d.jpg" % i), image)

    exit()

os.system("ffmpeg -framerate 15 -i {}/{}/track-%06d.jpg -c:v libx264 "
          "-profile:v high -crf 20 -pix_fmt yuv420p {}/{}/{}-120-det.avi".format(exp_dir, "images", exp_dir, "images", sequence))


s = 'qqaaabccccCCaBsssssdddddxxw'
# в конец добавлен фиктивный символ ~~~

def base_RLE_encode(txt):
    result, txt, pred, count = '', txt + '~~~', txt[0], 0
    for x in txt:
        if x == pred:
            count += 1
        else:
            result += str(count) * (count > 1) + pred
            pred, count = x, 1
    return result

print(baseRLEencode(s))


#!/usr/bin/env python3
# =============================================================================
"""
Code Information:
    Maintainer: Eng. John Alberto Betancourt G
	Mail: john@kiwicampus.com
	Kiwi Campus / Computer & Ai Vision Team
"""

# =============================================================================
import time
import cv2
import os

import rclpy
from rclpy.node import Node
from rclpy.callback_groups import ReentrantCallbackGroup

from usr_msgs.msg import VisualMessage
from usr_msgs.msg import Extrinsic

from vision.utils.vision_utils import printlog

from vision.extrinsic.extrinsic_utils import ExtrinsicClass

# =============================================================================
class VisualDebuggerSubscriber():

    def __init__(self, parent_node):

        # Timer with time to show message
        self._VISUAL_DEBUGGER_TIME = int(
            os.getenv(key="VISUAL_DEBUGGER_TIME", default=10))

        # Message to show in console
        self.visual_debugger_msg = ""
        # Type of message "info, err, warn"
        self.visual_debugger_type = "INFO"

        # Subscribers
        self._sub_visual_debugger = parent_node.create_subscription(
            msg_type=VisualMessage, topic='video_streaming/visual_debugger',
            callback=self.cb_visual_debugger, qos_profile=5,
            callback_group=parent_node.callback_group
            )

    def cb_visual_debugger(self, msg):
        """ Draws the visual debugger message
        Args:
            msg: `VisualMessage` message for visual debugger
                data: `string` message content
                type: `string` message type
        Returns:
        """

        self.visual_debugger_msg = msg.data
        self.visual_debugger_type = msg.type

        time.sleep(self._VISUAL_DEBUGGER_TIME)

        self.visual_debugger_msg = ""
        self.visual_debugger_type = "INFO"

class ExtrinsicSubscriber():

    def __init__(self, parent_node):

        # Subscribers
        self._sub_extrinsic_params = parent_node.create_subscription(
            msg_type=Extrinsic, topic='video_calibrator/extrinsic_parameters',
            callback=self.cb_extrinsic_params, qos_profile=2,
            callback_group=parent_node.callback_group
            )

        self.extrinsic = ExtrinsicClass()

    def cb_extrinsic_params(self, msg):
        """ Re-assing extrinsic calibration
        Args:
            msg: `VisualMessage` message for visual debugger
                data: `string` message content
                type: `string` message type
        Returns:
        """

        try:
            self.extrinsic.M = msg.projection_matrix
            self.extrinsic.p1 = msg.p1
            self.extrinsic.p2 = msg.p2
            self.extrinsic.p3 = msg.p3
            self.extrinsic.p4 = msg.p4
            self.extrinsic.vp = msg.vp
            self.extrinsic.dead_view = msg.dead_view
            self.extrinsic.ppmx = msg.ppmx
            self.extrinsic.ppmy = msg.ppmy
            self.extrinsic.warped_size = msg.unwarped_size
            self.extrinsic.image_size = msg.image_size

        except Exception as e:
            printlog(msg="Error getting extrinsic calibration"
                "from topic, {}".format(e), msg_type="ERROR")
            return False

        printlog(msg="Extrincid parameters updated", msg_type="INFO")

# =============================================================================


from utils import *
from sys import argv
import os

DEFUALT_PATH = os.path.realpath(__file__).replace("/format_files.py", "")

def make_image_dir(to_path, filenames):
    """ takes a list of filenames and makes a sample image for each to match kitti format"""
    image_dir = os.path.join(to_path, "image_2")
    os.makedirs(image_dir)
    for f in filenames:
        image_file = os.path.join(image_dir, f + ".png")
        os.system("cp sample.png {}".format(image_file))

def make_calib_dir(to_path, filenames):
    """ takes a list of filenames and makes a fake calib for each to match kitti format"""
    calib_dir = os.path.join(to_path, "calib")
    os.makedirs(calib_dir)
    for f in filenames:
        calib_file = os.path.join(calib_dir, f + ".txt")
        os.system("cp calib.txt {}".format(calib_file))

def make_velo_dir(to_path, bin_files):
    """ takes a list of bin files and makes a copies them to match kitti format"""
    velo_dir = os.path.join(to_path, "velodyne")
    os.makedirs(velo_dir)
    for bin_file in bin_files:
        # calib_file = os.path.join(calib_dir, f + ".txt")
        # os.system("cp calib.txt {}".format(calib_file))
        _, name = os.path.split(bin_file)
        velo_file = os.path.join(velo_dir, name)
        os.system("cp {} {}".format(bin_file, velo_file))

def create_image_set(to_path, filenames):
    set_dir = os.path.join(to_path, "ImageSets")
    os.makedirs(set_dir)
    test_file = os.path.join(set_dir, "test.txt")
    with open(test_file, "w") as f:
        for name in sorted(filenames):
            f.write(str(name) +"\n")
    train_file = os.path.join(set_dir, "train.txt")
    f = open(train_file, "w")

    val_file = os.path.join(set_dir, "val.txt")
    f = open(val_file, "w")

def main(from_path, to_path, split="testing"):
    filenames = [f.replace(".bin", "") for f in os.listdir(from_path) if f.endswith(".bin")]
    bin_files = [os.path.join(from_path, f) for f in os.listdir(from_path) if f.endswith(".bin")]

    create_image_set(to_path, filenames)

    if split == "testing":
        to_path = os.path.join(to_path, "testing")
    else:
        to_path = os.path.join(to_path, "training")

    make_image_dir(to_path, filenames)
    make_calib_dir(to_path, filenames)
    make_velo_dir(to_path, bin_files)

if __name__ == "__main__":
    """takes path as argument"""
    if len(argv) > 1:
        from_path = argv[1]
        to_path = os.path.join(DEFUALT_PATH, "data/kitti") if len(argv)==2  else argv[2]
        os.system("rm -r {}".format(to_path))
    else:
        raise Exception("please incluude from_dir and to_dir in args")

    main(from_path, to_path)


import uuid
from datetime import datetime

from sqlalchemy import create_engine
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('mysql+mysqldb://root:111111@localhost/arale-7moor?charset=utf8')
Base = declarative_base()

def generate_uuid():
    return uuid.uuid4().hex

class Record(Base):
    __tablename__ = 'records'

    id = Column(String(32), primary_key=True, default=generate_uuid)
    botid = Column(String(100), nullable=False)
    sessionid = Column(String(100))
    usertype = Column(String(100))
    msgcontent = Column(String(1024))
    msgtype = Column(String(100))
    msgtime = Column(String(100), default=datetime.now)
    flag = Column(Integer, default=0)

if __name__ == '__main__':
    Base.metadata.create_all(engine)


# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

import json
import os
import sys
import urllib.request

# Demonstrates code to register as an extension.

LAMBDA_AGENT_NAME_HEADER_KEY = "Lambda-Extension-Name"
LAMBDA_AGENT_IDENTIFIER_HEADER_KEY = "Lambda-Extension-Identifier"

class ExtensionsAPIClient():
    def __init__(self):
        try:
            runtime_api_address = os.environ['AWS_LAMBDA_RUNTIME_API']
            self.runtime_api_base_url = f"http://{runtime_api_address}/2020-01-01/extension"
        except Exception as e:
            raise Exception(f"AWS_LAMBDA_RUNTIME_API is not set {e}") from e

    # Register as early as possible - the runtime initialization starts after all extensions have registered.
    def register(self, agent_unique_name, registration_body):
        try:
            print(f"extension.extensions_api_client: Registering Extension at ExtensionsAPI address: {self.runtime_api_base_url}")
            req = urllib.request.Request(f"{self.runtime_api_base_url}/register")
            req.method = 'POST'
            req.add_header(LAMBDA_AGENT_NAME_HEADER_KEY, agent_unique_name)
            req.add_header("Content-Type", "application/json")
            data = json.dumps(registration_body).encode("utf-8")
            req.data = data
            resp = urllib.request.urlopen(req)
            if resp.status != 200:
                print(f"extension.extensions_api_client: /register request to ExtensionsAPI failed. Status:  {resp.status}, Response: {resp.read()}")
                # Fail the extension
                sys.exit(1)
            agent_identifier = resp.headers.get(LAMBDA_AGENT_IDENTIFIER_HEADER_KEY)
#            print(f"extension.extensions_api_client: received agent_identifier header  {agent_identifier}")
            return agent_identifier
        except Exception as e:
            raise Exception(f"Failed to register to ExtensionsAPI: on {self.runtime_api_base_url}/register \
                with agent_unique_name:{agent_unique_name}  \
                and registration_body:{registration_body}\nError: {e}") from e

    # Call the following method when the extension is ready to receive the next invocation
    # and there is no job it needs to execute beforehand.
    def next(self, agent_id):
        try:
            print(f"extension.extensions_api_client: Requesting /event/next from Extensions API")
            req = urllib.request.Request(f"{self.runtime_api_base_url}/event/next")
            req.method = 'GET'
            req.add_header(LAMBDA_AGENT_IDENTIFIER_HEADER_KEY, agent_id)
            req.add_header("Content-Type", "application/json")
            resp = urllib.request.urlopen(req)
            if resp.status != 200:
                print(f"extension.extensions_api_client: /event/next request to ExtensionsAPI failed. Status: {resp.status}, Response: {resp.read()} ")
                # Fail the extension
                sys.exit(1)
            data = resp.read()
            print(f"extension.extensions_api_client:  Received event from ExtensionsAPI: {data}")
            return data
        except Exception as e:
            raise Exception(f"Failed to get /event/next from ExtensionsAPI: {e}") from e


# -*- coding:gbk -*-
# auther : pdm
# email : ppppdm@gmail.com

import socket
import traceback

# self module
import myLog

HOST = socket.gethostbyname(socket.gethostname()) #socket.INADDR_ANY
REMOTE_CONTROL_PORT = 6320

remote_control_client_list = []

def send_to_remote(b_data):
    for conn in remote_control_client_list:
        try:
            conn.send(b_data)
        except:
            print(traceback.format_exc())
            myLog.mylogger.debug(traceback.format_exc())
            remote_control_client_list.remove(conn)
            conn.close()

def Server():
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind((HOST, REMOTE_CONTROL_PORT))
        sock.listen(5)
        print('remote control ready to accept...')
        while True:
            conn, addr = sock.accept()
            print('connected by ', addr)
            remote_control_client_list.append(conn)
    except:
        print(traceback.format_exc())
        myLog.mylogger.debug(traceback.format_exc())
    return


#!/usr/bin/env python3
from collections import defaultdict
from itertools import permutations

def main():
    matrix = load_matrix()
    print(max(
        total_happiness(arrangement, matrix)
        for arrangement in permutations(list(matrix.keys()))
    ))

def load_matrix():
    matrix = defaultdict(lambda: defaultdict(int))
    with open('13.txt', 'r', encoding='utf-8') as f:
        for line in f:
            source, _, sign, n, _, _, _, _, _, _, destination = line.split()
            amount = (1 if sign == 'gain' else -1) * int(n)
            destination = destination[:-1]  # remove .
            matrix[source][destination] = amount
    return matrix

def total_happiness(arrangement, matrix):
    happiness = 0
    for i, name in enumerate(arrangement):
        right = arrangement[(i + 1) % len(arrangement)]
        happiness += matrix[name][right]
        left = arrangement[(i - 1) % len(arrangement)]
        happiness += matrix[name][left]
    return happiness

if __name__ == '__main__':
    main()


#!/usr/bin/python

from __future__ import division

import numpy as np
import matplotlib

matplotlib.use('Agg')
import xgboost as xgb
import matplotlib.pyplot as plt
from itertools import cycle
from sklearn.preprocessing import normalize

from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
from scipy import interp

def addFea(train_Xn, train_X, num1, num2):
    train_var = tran(train_X[:, 1:], np.var, axis=1)
    train_zero = tran(train_X, np.count_nonzero, axis=1)
    train_zero.shape = 1, -1
    train_zero = map(lambda x: 94 - x, train_zero)
    train_zero = np.transpose(train_zero)
    train_add = np.add(train_X[:, num1], train_X[:, num2])
    train_mul = train_X[:, num1] * train_X[:, num2]
    train_sub = np.subtract(train_X[:, num1], train_X[:, num2])

    with np.errstate(divide='ignore', invalid='ignore'):
        train_div = np.true_divide(train_X[:, 25], train_X[:, 67])
        train_div[train_div == np.inf] = 0
        train_div = np.nan_to_num(train_div)

    train_Xn = np.c_[train_Xn, train_var, train_zero, train_add, train_sub, train_mul, train_div]
    return train_Xn

def tran(array, func, *args, **kwargs):
    res = func(array, *args, **kwargs)
    res.shape = (res.shape[0], 1)
    np.transpose(res)
    return res

def normalizer(lst):
    norm = lst
    for i in range(lst.shape[0]):
        norm[i] = [(float(2 * j) - max(lst[i]) - min(lst[i])) / (max(lst[i]) - min(lst[i])) for j in lst[i]]
        if (i % 500 == 0):
            print(" %.4f done" % (float(i / lst.shape[0])))
    return norm

# label need to be 0 to num_class -1
data = np.loadtxt('../train.csv', skiprows=1, delimiter=',',
                  converters={0: lambda x: int('0'), 94: lambda x: int(x[6:]) - 1})
sz = data.shape

np.random.shuffle(data)
train = data[:int(sz[0] * 0.9), :]
test = data[int(sz[0] * 0.9):, :]

train_X = train[:, :93]
train_Xo = train_X

train_Y = train[:, 94]
train_X = addFea(train_X, train_Xo, 25, 67)
train_X = addFea(train_X, train_Xo, 25, 86)
print(train_X[0, :])

train_X = normalize(train_X, norm='l2')

test_X = test[:, :93]
test_Xo = test_X
test_X = addFea(test_X, test_X, 25, 67)
test_X = addFea(test_X, test_Xo, 25, 86)

test_X = normalize(test_X, norm='l2')

test_Y = test[:, 94]
test_Yb = label_binarize(test_Y, classes=range(0, 9))

xg_train = xgb.DMatrix(train_X, label=train_Y)
xg_test = xgb.DMatrix(test_X, label=test_Y)
# setup parameters for xgboost
param = {}
# use softmax multi-class classification
param['objective'] = 'multi:softmax'
# scale weight of positive examples
param['eta'] = 0.1
# param['max_depth'] = int('6')
param['silent'] = 1
param['nthread'] = 4
param['num_class'] = 9

watchlist = [(xg_train, 'train'), (xg_test, 'test')]
num_round = 5
model = xgb.XGBClassifier(max_depth=10, subsample=0.70, colsample_bytree=0.7, objective='multi:softmax', learning_rate=0.05,
                          gamma=5, silent=0,
                          # n_jobs=40, num_class=9
                          )
model.fit(train_X, train_Y)

# bst = xgb.train(param, xg_train, num_round, watchlist)
# get prediction_cascaded
# pred = bst.predict(xg_test)

res = model.predict(test_X)
pred = model.predict_proba(test_X)

# print(model.booster().get_score(importance_type='weight'))
# print(model.booster().plot_importance(model))

'''
for i in range(test_X.shape[0]):
    if res[i] == test_Y[i]:
        print(pred[i])
        print(test_Y[i])
'''

# pred_b = label_binarize(pred, classes=range(0,9))
def plot(test_Yb, pred, param, filename="otto"):
    fpr = dict()
    tpr = dict()

    roc_auc = dict()

    for i in range(param['num_class']):
        fpr[i], tpr[i], _ = roc_curve(test_Yb[:, i], pred[:, i])
        roc_auc[i] = auc(fpr[i], tpr[i])

    fpr["micro"], tpr["micro"], _ = roc_curve(test_Yb.ravel(), pred.ravel())
    roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])

    n_classes = param["num_class"]
    # Compute macro-average ROC curve and ROC area

    # First aggregate all false positive rates
    all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))

    # Then interpolate all ROC curves at this points
    mean_tpr = np.zeros_like(all_fpr)
    for i in range(n_classes):
        mean_tpr += interp(all_fpr, fpr[i], tpr[i])

    # Finally average it and compute AUC
    mean_tpr /= n_classes

    fpr["macro"] = all_fpr
    tpr["macro"] = mean_tpr
    roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])

    # Plot all ROC curves
    plt.figure()
    plt.plot(fpr["micro"], tpr["micro"],
             label='micro-average ROC curve (area = {0:0.2f})'
                   ''.format(roc_auc["micro"]),
             color='deeppink', linestyle=':', linewidth=4)

    plt.plot(fpr["macro"], tpr["macro"],
             label='macro-average ROC curve (area = {0:0.2f})'
                   ''.format(roc_auc["macro"]),
             color='navy', linestyle=':', linewidth=4)

    colors = cycle(['aqua', 'darkorange', 'cornflowerblue'])
    for i, color in zip(range(n_classes), colors):
        plt.plot(fpr[i], tpr[i], color=color, lw=2,
                 label='ROC curve of class {0} (area = {1:0.2f})'
                       ''.format(i, roc_auc[i]))

    plt.plot([0, 1], [0, 1], 'k--', lw=2)
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.title('Some extension of Receiver operating characteristic to multi-class')
    plt.legend(loc="lower right")
    plt.savefig(filename)

error_rate = np.sum(res != test_Y) / test_Y.shape[0]
print('Test error using softmax = {}'.format(error_rate))

plt.figure()
xgb.plot_importance(model, max_num_features=20)

plt.savefig("imp.png")

plot(test_Yb, pred, param, "otto")
'''
# do the same thing again, but output probabilities
param['objective'] = 'multi:softprob'
bst = xgb.train(param, xg_train, num_round, watchlist)
#print(xgb.get_score())
# Note: this convention has been changed since xgboost-unity
# get prediction_cascaded, this is in 1D array, need reshape to (ndata, nclass)
pred_prob = bst.predict(xg_test).reshape(test_Y.shape[0], param['num_class'])
pred_label = np.argmax(pred_prob, axis=1)
print(bst.get_score())
#print(xgb.plot_importance(bst))
#error_rate = np.sum(pred != test_Y) / test_Y.shape[0]
#print('Test error using softprob = {}'.format(error_rate))
'''


import matplotlib.pyplot as plt
import numpy as np
import csv

def adjacent_values(vals, q1, q3):
    upper_adjacent_value = q3 + (q3 - q1) * 1.5
    upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])

    lower_adjacent_value = q1 - (q3 - q1) * 1.5
    lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)
    return lower_adjacent_value, upper_adjacent_value

def set_axis_style(ax, labels):
    ax.get_xaxis().set_tick_params(direction='out')
    ax.xaxis.set_ticks_position('bottom')
    ax.set_xticks(np.arange(1, len(labels) + 1))
    ax.set_xticklabels(labels)
    ax.set_xlim(0.25, len(labels) + 0.75)
    ax.set_xlabel('Sample name')

def read_results_csv(file_path, row_id=0):
    dice_values = []
    with open(file_path, 'r') as file:
        reader = csv.reader(file)
        for row in reader:
            dice_values.append(float(row[row_id]))

        return dice_values

# create test data
np.random.seed(19680801)

path_file_1 = '/home/nearlab/Jorge/current_work/lumen_segmentation/data/' \
                  '3x3_grayscale_dataset/results/' \
                  'ResUnet_lr_0.001_bs_16_grayscale_16_11_2020_19_37/' \
                  'results_evaluationtest_01_ResUnet_lr_0.001_bs_16_grayscale_16_11_2020_19_37_new.csv'

path_file_2 = '/home/nearlab/Jorge/current_work/lumen_segmentation/data/' \
              '3x3_grayscale_dataset/results/' \
              'ResUnet_lr_1e-05_bs_16_grayscale_16_11_2020_19_32/' \
              'results_evaluationtest_01_ResUnet_lr_1e-05_bs_16_grayscale_16_11_2020_19_32_new.csv'

path_file_3 = '/home/nearlab/Jorge/current_work/lumen_segmentation/data/' \
              'lumen_data/results/' \
              'ResUnet_lr_0.001_bs_16_hsv_14_11_2020_20_06/' \
              'results_evaluation_test_02_ResUnet_lr_0.001_bs_16_hsv_14_11_2020_20_06_.csv'

path_file_4 = '/home/nearlab/Jorge/current_work/lumen_segmentation/data/' \
              'lumen_data/results/' \
              'ResUnet_lr_0.001_bs_16_rgb_06_11_2020_00_51/' \
              'results_evaluation_test_02_ResUnet_lr_0.001_bs_16_rgb_06_11_2020_00_51_.csv'

path_file_5 = '/home/nearlab/Jorge/current_work/lumen_segmentation/' \
              'data/' \
              '3x3_grayscale_dataset/results/MaskRCNN_2/' \
              'results_evaluationtest_02_MaskRCNN_2_new.csv'

path_file_6 = '/home/nearlab/Jorge/current_work/lumen_segmentation/' \
              'data/3x3_grayscale_dataset/' \
              'results/MaskRCNN_2/' \
              'results_evaluationtest_02_MaskRCNN_2_new.csv'

data_experiment_1 = sorted(read_results_csv(path_file_1, 2))
data_experiment_2 = read_results_csv(path_file_2, 2)
data_experiment_3 = read_results_csv(path_file_3, 2)
data_experiment_4 = sorted(read_results_csv(path_file_4, 2))
data_experiment_5 = sorted(read_results_csv(path_file_5, 2))
data_experiment_6 = sorted(read_results_csv(path_file_6, 2))

#data = [data_experiment_1, data_experiment_4, data_experiment_5, data_experiment_6]
#data = [sorted(np.random.normal(0, std, 100)) for std in range(1, 5)]
data = [data_experiment_1, data_experiment_2,
        data_experiment_3, 0, 0, 0]
data_2 = [0,0,0, data_experiment_4,
        data_experiment_5, data_experiment_6]
print(np.shape(data))

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2,
                               figsize=(9, 5), sharey=True)

ax1.set_title('Default violin plot')
ax1.set_ylabel('Observed values')
ax1.violinplot(data)
ax1.violinplot(data_2)

ax2.set_title('Customized violin plot')
parts = ax2.violinplot(
        data, showmeans=True, showmedians=True,
        showextrema=True)
"""
for pc in parts['bodies']:
    pc.set_facecolor('#D43F3A')
    pc.set_edgecolor('black')
    pc.set_alpha(1)

quartile1, medians, quartile3 = np.percentile(data, [25, 50, 100], axis=1)
print(quartile1, medians, quartile3)
whiskers = np.array([
    adjacent_values(sorted_array, q1, q3)
    for sorted_array, q1, q3 in zip(data, quartile1, quartile3)])
whiskers_min, whiskers_max = whiskers[:, 0], whiskers[:, 1]

inds = np.arange(1, len(medians) + 1)
ax2.scatter(inds, medians, marker='o', color='white', s=30, zorder=3)
ax2.vlines(inds, quartile1, quartile3, color='k', linestyle='-', lw=5)
ax2.vlines(inds, whiskers_min, whiskers_max, color='k', linestyle='-', lw=1)
"""
# set style for the axes
labels = ['A', 'B', 'C', 'D', 'E', 'F']
for ax in [ax1, ax2]:
    set_axis_style(ax, labels)

plt.subplots_adjust(bottom=0.15, wspace=0.05)
plt.show()


"""
2 - Write a function that takes in a user string input and reformats it into A E S T H E T I C text.
Example:
Input > Hello World
Output > H e l l o W o r l d
"""

def reformat(input_string):
    output = ""
    for char in input_string:
        output += char
        # Add a space after every char
        output += " "
    return output

string = reformat(input("String: "))
print(string)


# Copyright 2014 by Ethan Fritz. All Rights Reserved.

import data.contestant
import random
import logging

class Heat(object):
    def __init__(self, racers):
        self.run_complete = False
        self.populate_heat(racers)

    def populate_heat(self, racers):
        self.racers = []
        self.times = []
        self.places = []
        for racer in racers:
            self.racers.append(racer)
            self.times.append(None)
            self.places.append(None)

    def set_time_and_place(self, times):
        logging.info("Race finished. Setting time and placement.")
        logging.debug("Setting Times = %s", times)
        logging.debug("Racers = %s", [x.id for x in self.racers])
        assert(all(isinstance(x, (float)) for x in times))
        assert(len(times) == len(self.racers))
        assert(len(times) == len(self.times))
        assert(len(times) == len(self.places))
        self.run_complete = True

        times_indexed = []
        for index, time in enumerate(times):
            self.times[index] = time
            times_indexed.append((time, index))
        times_indexed.sort(reverse=False)

        for placement, (time, index) in enumerate(times_indexed):
            self.places[index] = placement + 1
        logging.debug("Heat's Times = %s", self.times)
        logging.debug("Heat's Places = %s", self.places)

    def winner(self):
        "Return a list of the winner."
        winner = []
        winners_index = self.places.index(1)
        winner.append(self.racers[winners_index])
        return winner

    def losers(self):
        "Return a list of the losers."
        losers = []
        winners_index = self.places.index(1)
        for index, racer in enumerate(self.racers):
            if index != winners_index:
                losers.append(racer)
        return losers

    def number_of_racers(self):
        return len(self.racers)

class DoubleEliminationHeat(Heat):
    "Adds double elimination state to the Heat class."

    def __init__(self, lanes, entries):
        assert(isinstance(lanes, (int)))
        assert(len(entries) >= 2)

        self.first_elimination_phase = True
        self.final_heat = False
        self.win_bracket = []
        self.loss_bracket = []
        self.noloss_bracket = list(entries)
        random.shuffle(self.noloss_bracket)
        racers = []
        for i in range(lanes):
            if len(self.noloss_bracket) > 0:
                racers.append(self.noloss_bracket.pop(0))
            else:
                break
        assert(len(racers) >= 2)
        Heat.__init__(self, racers)


# ！/usr/bin/env python3
# -*-coding: UTF-8 -*-
# Author Frank

import time
import cv2
import numpy
import pytesseract
import pyautogui as auto

from datetime import datetime
from core import selfcv, debug_mode
from logzero import logger

class Adam:

    def __init__(self):
        self.point = None
        self.offset = (None, None)
        # auto.FAILSAFE = False
        # auto.PAUSE = 0.1

    @property
    def point_offset(self):
        x0, y0 = self.offset
        istuple = isinstance(self.point, tuple)
        res = map(lambda x: (x[0] + x0, x[1] + y0), [self.point] if istuple else self.point)
        return next(res) if istuple else list(res)

    def find_object(self, image, templ, *args, match_rate=0.8, return_center=True):
        """ Find object on screen.

        Args:
            image: 图片地址
            templ: 大图
            match_rate: 匹配率
            return_center: 是否返回图片中心坐标，否为返回左上角

        Returns:

        """
        img_sml = cv2.imread(image)
        if isinstance(templ, str):
            img_big = cv2.imread(templ)
        elif callable(templ):
            img_big = templ(*args)
        else:
            img_big = templ

        r = selfcv.single_match_template(img_sml, img_big, match_rate=match_rate, return_center=return_center)
        if debug_mode:
            # logger.debug("{0}:{1}".format(image, r[3]))
            logger.debug("{0}:{1}".format(image, r))
        if r[0]:
            self.point = (r[1], r[2])
            return True
        else:
            self.point = None
            return False

    def count_object(self, image, templ, match_rate=0.8, return_center=True):
        """
        Count the object on screen.
        :param image: image of object.
        :param templ: 大图
        :param match_rate: 匹配率
        :param return_center: 是否返回中心坐标
        :return:
        """
        # Take a ScreenShot, then convert picture to OpenCV format.
        img_sml = cv2.imread(image)
        img_big = templ
        # img_big = auto.screenshot()
        r = selfcv.multi_match_template(img_sml, img_big, match_rate=match_rate, return_center=return_center)
        if not r[0]:
            self.point = None
            return False
        else:
            self.point = r[1]
            return True

    def wait_for_object(self, image, templ, *args, match_rate=0.8, duration=60):
        """
        Find object on the screen within given times.
        :param image:
        :param templ:
        :param match_rate:
        :param duration:->int seconds
        :return:
        """
        start = datetime.utcnow()
        while True:
            delta = datetime.utcnow() - start
            if delta.seconds < duration:
                if isinstance(templ, str):
                    img_big = cv2.imread(templ)
                elif callable(templ):
                    img_big = templ(*args)
                else:
                    img_big = templ
                if self.find_object(image, img_big, match_rate=match_rate):
                    return True
                else:
                    continue
            else:
                raise Exception("Can't find image")

    def touch_object(self, image, templ):
        if self.find_object(image, templ):
            self.click_object()
        else:
            raise Exception("Can't find image.")

    def click_object(self, left=True, times=1):
        self.clickpoint(self.point, left, times)

    def show_screenshot(self, rgb=True):
        mode = cv2.COLOR_RGB2BGR
        if not rgb:
            mode = cv2.COLOR_BGR2GRAY
        img = cv2.cvtColor(numpy.asarray(self.screenshot()), mode)
        img = cv2.resize(img, (1536, 864))
        cv2.imshow('image', img)
        cv2.waitKey(0)

    @classmethod
    def clickpoint(cls, points, left=True, times=1):
        if isinstance(points, tuple):
            if left:
                if times == 1:
                    auto.click(*points)
                elif times == 2:
                    auto.doubleClick(*points)
                elif times == 3:
                    auto.tripleClick(*points)
                else:
                    raise Exception("times must within 1~3.")
                time.sleep(0.2)
            else:
                auto.rightClick(*points)
        elif isinstance(points, list):
            for point in points:
                auto.click(*point)
                time.sleep(0.2)
        auto.dragTo(1920, 1080)

    @classmethod
    def find_text(cls, message):
        img = cls.screenshot()
        """
        waiting for adding image processing.
        """
        text = cls.do_ocr_on_image(img)
        for word in text:
            if message in word:
                return word
        else:
            return False

    @classmethod
    def key_down(cls, key):
        auto.keyDown(key)

    @classmethod
    def key_up(cls, key):
        auto.keyUp(key)

    @classmethod
    def click_key(cls, key, times=1, interval=0):
        auto.press(key, presses=times, interval=interval)

    @classmethod
    def hot_key(cls, *keys):
        auto.hotkey(*keys)

    @classmethod
    def send_text(cls, message, interval=0.1):
        auto.typewrite(message, interval=interval)

    @classmethod
    def do_ocr_on_image(cls, img, data=False):
        image = cv2.imread(img, cv2.IMREAD_GRAYSCALE)
        if data:
            data = pytesseract.image_to_data(image)
            return data
        string = pytesseract.image_to_string(image, lang='eng')
        return string

    @classmethod
    def screenshot(cls):
        """
        Take a screenshot and save it.
        :return:
        """
        temp_pic = auto.screenshot()
        screen = cv2.cvtColor(numpy.asarray(temp_pic), cv2.COLOR_RGB2BGR)
        cv2.imshow('ts', screen)
        cv2.waitKey(0)
        return screen


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov  8 14:06:56 2018

@author: chenhx1992
"""

import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
import numpy as np
from itertools import combinations
import itertools

lst = np.arange(0, 256, 5)
# for combo in combinations(lst, 3):  # 2 for pairs, 3 for triplets, etc
#     print(combo)

RGBlist = list(itertools.product(lst, lst, lst))

# RGBlist = [(random.randint(0,255), random.randint(0,255), random.randint(0,255)) for i in range(100)]
paleta=list(zip(*RGBlist))
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter([(x-127)/128. for x in paleta[0]],[(x-127)/128. for x in paleta[1]],[(x-127)/128. for x in paleta[2]], c=[(r[0] / 255., r[1] / 255., r[2] / 255.) for r in RGBlist])
ax.grid(False)
ax.set_title('RGB Color Cube')
ax.set_xlabel('Red',fontsize=12)
ax.set_ylabel('Green',fontsize=12)
ax.set_zlabel('Blue',fontsize=12, rotation=90)
# make the panes transparent
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# make the grid lines transparent
ax.xaxis._axinfo["grid"]['color'] =  (1,1,1,0)
ax.yaxis._axinfo["grid"]['color'] =  (1,1,1,0)
ax.zaxis._axinfo["grid"]['color'] =  (1,1,1,0)
# plt.savefig('blah.png')


# -*- coding: utf-8-*-
import random
import re
import json
import httplib
from datetime import datetime
from dateutil import tz
from client import jasperpath

WORDS = ["OCTO", "EVENTS"]

def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, by telling a joke.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    events = "These are the last 5 Octo Events. "
    JasperKey = "API-get your own key"
    connection = httplib.HTTPConnection("kno2-deploy.cloudapp.net", 80)
    connection.connect()
    connection.request('GET', '/api/events', None, {"X-Octopus-ApiKey": JasperKey})
    result = json.loads(connection.getresponse().read())
    index = 0
    for attribute, value in result.iteritems():
        if attribute == "Items":
            for each_dict in value[:5]:
                friendlydate = datetime.strptime(each_dict.get("Occurred"), "%Y-%m-%dT%H:%M:%S.%f+00:00")
                from_zone = tz.tzutc()
                to_zone = tz.tzlocal()
                friendlydate = friendlydate.replace(tzinfo=from_zone)
                central = friendlydate.astimezone(to_zone)
                events += "Event: " + each_dict.get("Message") + " was performed by " + each_dict.get("Username") + " at " + \
                      central.strftime("%m/%d/%Y at %H:%M Local Time.")

    mic.say(events)

def isValid(text):
    """
        Returns True if the input is related to jokes/humor.

        Arguments:
        text -- user-input, typically transcribed speech
    """
    return bool(re.search(r'\bocto events\b', text, re.IGNORECASE))


# -*- coding: utf-8 -*-
"""
Created by Serino at 2017/9/30 17:17
"""

class Cat:
    def __init__(self, color, legs):
        self.color = color
        self.legs = legs

    def bark(self):
        print("Woof!")

felix = Cat("ginger", 4)
rover = Cat("dog-colored", 4)
stumpy = Cat("brown", 3)

print(rover.color)
rover.bark()


# -*- coding: utf-8 -*-
# tensorflow.layers 를 사용하면 신경망 구성을 보다 쉽게 할 수 있다.
# 01_CNN.py 를 재구성한 것이다.
import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./mnist/data", one_hot=True)

# --------------------  신경망 모델 구성  -------------------- #
X = tf.placeholder(tf.float32, [None, 28, 28, 1])
Y = tf.placeholder(tf.float32, [None, 10])
is_training = tf.placeholder(tf.bool)

# inputs, outputs size, kernel size 만 넣어주면
# activation function 적용은 물론 convolutional neural network 를 만들기 위한 나머지 수치들을 알아서 계산해준다.
# 특히 Weights 를 계산하는데 xavier_initializer 를 사용하고 있는 등,
# 크게 신경쓰지 않아도 일반적으로 좋은 성능을 내는 효율적인 신경망을 만들어준다.
L1 = tf.layers.conv2d(X, 32, [3, 3])
L1 = tf.layers.max_pooling2d(L1, [2, 2], [2, 2])
L1 = tf.layers.dropout(L1, rate=0.7, training=is_training)

L2 = tf.layers.conv2d(L1, 64, [3, 3])
L2 = tf.layers.max_pooling2d(L2, [2, 2], [2, 2])
L2 = tf.layers.dropout(L2, rate=0.7, training=is_training)

L3 = tf.contrib.layers.flatten(L2)
L3 = tf.layers.dense(L3, 256, activation=tf.nn.relu)
L3 = tf.layers.dropout(L3, rate=0.5, training=is_training)

model = tf.layers.dense(L3, 10, activation=None)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=model, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

# --------------------  신경망 모델 학습  -------------------- #
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

batch_size = 100
total_batch = int(mnist.train.num_examples / batch_size)

for epoch in range(15):
    total_cost = 0

    for i in range(total_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        batch_xs = batch_xs.reshape(-1, 28, 28, 1)
        _, cost_val = sess.run([optimizer, cost], feed_dict={X: batch_xs, Y: batch_ys, is_training: True})

        total_cost += cost_val

    print('Epoch:', '%04d' % (epoch + 1),
          'Avg. cost =', '{:.4f}'.format(total_cost / total_batch))

print('학습 완료!')

# --------------------  결과 확인  -------------------- #
is_correct = tf.equal(tf.argmax(model, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))
print('정확도:', sess.run(accuracy, feed_dict={X: mnist.test.images.reshape(-1, 28, 28, 1),
                                            Y: mnist.test.labels, is_training: False}))


from random import choice
import sys
sys.path.append("enemys")

import anthropomorph, beast, dragon

def randomEnemy(lvl):
    enemys = [1, 2, 3]
    enemy = choice(enemys)
    if enemy == 1:
        return anthropomorph.anthropomorph(lvl)
    if enemy == 2:
        return beast.beast(lvl)
    if enemy == 3:
        return dragon.dragon(lvl)

def randomSkill(enemy):
    skills = [1, 2, 3]
    skill = choice(skills)
    if skill == 1:
        return enemy.skill1()
    if skill == 2:
        return enemy.skill2()
    if skill == 3:
        return enemy.skill3()

def enemyList(lvl, count):
    enemy = randomEnemy(lvl)
    lst = []
    if enemy.type == "Зверь":
        for i in range(count):
            lst.append(beast.beast(lvl))

    if enemy.type == "Дракон":
        for i in range(count):
            lst.append(dragon.dragon(lvl))

    if enemy.type == "Антропоморф":
        for i in range(count):
            lst.append(anthropomorph.anthropomorph(lvl))

    return lst


# Enter three numbers
# sort them in ascending order

i = 1
flist = []
while i < 4:
    try:
        num = int(input("Enter current number"))
    except ValueError:
        print(" not a valid number")
        continue
    flist.append(num)
    i += 1
flist.sort()
j = 0
while j < 3:
    print(f" {flist[j]}  ", end="")
    j += 1


import cv2
import numpy as np

img=np.zeros((512,512,3),np.int8)

#Function to draw a circle
def draw_circle(event,x,y,flags,param):
    if(event==cv2.EVENT_LBUTTONDOWN):
        cv2.circle(img,(x,y),100,(255,0,255),-1)

cv2.namedWindow('my_drawing')
cv2.setMouseCallback('my_drawing',draw_circle)

#Display the image
while True:
    cv2.imshow('my_drawing',img)
    if cv2.waitKey(20) & 0xFF==27:
        break
cv2.destroyAllWindows()


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 29 23:54:01 2018

@author: paul
"""

import matplotlib.pyplot as plt
import numpy as np
import pickle
from kernel_exp_family.estimators.finite.gaussian import KernelExpFiniteGaussian
from kernel_exp_family.estimators.lite.gaussian import KernelExpLiteGaussian
import seaborn as sns
plt.close('all')
N = 2000
D = 7
f = open('/home/paul/data/eprv01_posteriorsamples.dat')
parnames, samples_kepler = pickle.load(f)
f.close()
Period = samples_kepler[:N,4]
Amplitude = samples_kepler[:N,0]
ecc = samples_kepler[:N,3]**2 + samples_kepler[:N,5]**2
pericenter = np.arctan2(samples_kepler[:N,5], samples_kepler[:N,3])
MeanA = samples_kepler[:N, 6]
sigma_Jitter = samples_kepler[:N,1]
V0 = samples_kepler[:N, 2]

P = (Period - np.mean(Period))/np.std(Period)
K = (Amplitude - np.mean(Amplitude))/np.std(Period)
e = (ecc-np.mean(ecc))/np.std(ecc)
w = (pericenter-np.mean(pericenter))/np.std(pericenter)
M = (MeanA-np.mean(MeanA))/np.std(MeanA)
sigma_J = (sigma_Jitter-np.mean(sigma_Jitter))/np.std(sigma_Jitter)
V = (V0-np.mean(V0))/np.std(V0)

X = np.array([P, K, e, w, M, sigma_J, V]).T
surrogate = KernelExpLiteGaussian(sigma=2., lmbda=0.12, D=D, N=N)

surrogate.fit(X)

gradiente = []

for i in range(N):
        gradiente.append(surrogate.grad(X[i,:]))

g = np.array(gradiente)
Params = ['Periodo', 'Semi-Amplitud', 'Excentricidad', 'Arg. pericentro', 'Anomalia media', 'Sigma_J', 'Offset V' ]

for i in range(1, D):

    fig=plt.figure(i, figsize=(10,4))

    plt.style.use('seaborn-darkgrid')
    plt.subplot(121)
    plt.ylabel('%s' %Params[0])
    plt.xlabel('%s' %Params[i])
    plt.scatter(X[:,i], X[:,0], s=0.5, alpha=0.5)

    plt.subplot(122)
    plt.ylabel('%s' %Params[0])
    plt.xlabel('%s' %Params[i])
    plt.quiver(X[:,i], X[:,0], g[:,i], g[:,0])

    plt.tight_layout()
    fig.savefig('/home/paul/Desktop/quiver_keplerian_static%s.png' %Params[i])


""" Keyboard manager """

__author__ = "Peter Bennett"
__copyright__ = "Copyright 2012, Peter A Bennett"
__license__ = "LGPL"
__version__ = "0.1"
__maintainer__ = "Peter Bennett"
__email__ = "pab850@googlemail.com"
__contact__ = "www.bytebash.com"

from pyglet.window import key, mouse
from pyglet import clock

""" Statename strings """

flight = "Flight Mode"
wireframe = "Wireframe Mode"

class Controller(object):
    def __init__(self, window, player, console):
        self.keys = key.KeyStateHandler()
        self.player = player

        # Console
        self.console = console

        # States
        self.states = {}
        self.states[wireframe] = False
        self.states[flight] = False

        # Key Press Events
        self.keyPressEvents = {}

        clock.schedule(self.update)

        window.push_handlers(self.on_key_press)
        window.push_handlers(self.on_key_release)
        window.push_handlers(self.keys)
        window.push_handlers(self.on_mouse_motion)
        window.push_handlers(self.on_mouse_drag)
        window.push_handlers(self.on_mouse_press)
        window.push_handlers(self.on_mouse_release)

    def on_mouse_motion(self, x, y, dx, dy):
        self.player.orient(-dy*0.08, dx*0.08)

    def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
        self.player.orient(-dy*0.08, dx*0.08)

    def keyPressed(self, symbol):
        if symbol in self.keyPressEvents:
            return self.keyPressEvents[symbol]
        return False

    def update(self, dt):
        # Handle events that must occur while a key is pressed.
        self.player.update(dt,
                           self.keyPressed(key.W),
                           self.keyPressed(key.S),
                           self.keyPressed(key.A),
                           self.keyPressed(key.D))

    def on_mouse_press(self, x, y, button, modifiers):
        if button == mouse.LEFT:
            if not self.keyPressed(mouse.LEFT):
                self.player.fire()

        if button == mouse.RIGHT:
            if not self.keyPressed(mouse.RIGHT):
                self.player.altFire()

    def on_mouse_release(self, x, y, button, modifiers):
        self.keyPressEvents[button] = False

    def on_key_press(self, symbol, modifiers):
        # Handle events that only require one action per keypress here.

        # Player jump
        if symbol == key.SPACE:
            if not self.keyPressed(key.SPACE):
                self.player.jump()

        # Player jump
        if symbol == key.R:
            if not self.keyPressed(key.R):
                self.player.fire()

        # Enable or disable flight mode.
        if symbol == key.F:
            if not self.keyPressed(key.F):
                self.states[flight] = not self.states[flight]
                self.console.updateConsole(flight + ": " +
                                           str(self.states[flight]))
                self.player.toggleFlightMode(self.states[flight])
        # Enable or disable wireframe mode.
        if symbol == key.T:
            if not self.keyPressed(key.T):
                self.states[wireframe] = not self.states[wireframe]
                self.console.updateConsole(wireframe + ": " +
                                           str(self.states[wireframe]))

        self.keyPressEvents[symbol] = True

    def on_key_release(self, symbol, modifiers):
        self.keyPressEvents[symbol] = False


#GlobalAIHub HM4
#Defining animals and defining functions inherit
class Animals():
    def __init__(self,name,familia,rep_type):
        self.name=name
        self.familia=familia
        self.rep_type=rep_type
    def define_animal(self):
        print(self.name+" belongs to "+self.familia+" family.")
    def reproductiontype (self):
        print(self.name+"'s reproduction type is "+self.rep_type)
animal=Animals("Snakes","Typhlopidae","Eggs")
animal.define_animal()

class Dogs():
    def __init__(self,name,typeof,color,lifetime):
        self.name=name
        self.typeof=typeof
        self.color=color
        self.lifetime=lifetime
    def infodog(self):
     print(self.name+"''s color:  "+self.color)
     print(self.name+"'s lifetime:  "+self.lifetime)
     print(self.name+"''s type is:  "+self.typeof)

dogs=Dogs("Palpatine","Siberian Husky","Black and White","11 Year")
dogs.infodog()

class Cats():
    def __init__(self,name,typeof,color,lifetime):
        self.name=name
        self.typeof=typeof
        self.color=color
        self.lifetime=lifetime
    def infocat(self):
     print(self.name+"''s color:  "+self.color)
     print(self.name+"'s lifetime:  "+self.lifetime)
     print(self.name+"''s type is:  "+self.typeof)

cats=Cats("Nisan","Turkish Agnora","White","5 Year")
cats.infocat()


"""
@Time:2018/1/11 15:36
@Author:xuzhongyou
"""
#写个算法，对2个小于1000000000的输入，求结果
#特殊乘法举例：123*45=1*4+1*5+2*4+2*5+3*4+3*5
#输入：两个小于1000000000的数
#输出可能有多组数据，对于每一组数据，输出input中的两个数按照题目要求的方法进行运算后得到结果
#123 45
#54
# a = 123
# result = []
# while(a!=0):
#     # result.append(a%10)
#     result.insert(0,a%10)
#     a = int(a/10)
# print(result)
str_1 = '123 45'
print(str_1)
str_list = str_1.split(" ")
num1 = str_list[0]
num2 = str_list[1]
result = 0
for i in list(num1):
    for j in list(num2):
        result += int(i)*int(j)
print(result)


class CasillaDeVotacion:
	def __init__(self, identificador, pais):
		self._identificador = identificador
		self._pais = pais
		self._region = None

	@property
	def region(self):
		return self._region

	@region.setter
	def region(self, region):
		if region in self._pais:
			self._region = region
		else:
			raise ValueError(f'La region {region} no es valida en {self._pais}')

casilla = CasillaDeVotacion(1999, ['México', 'Estado de México'])
casilla.region = 'Puebla'
print(casilla.region)

2. POO y algoritmos con Python/Programación Orientada a Objetos/encapsulacion_getters_setters.py


#!/usr/bin/env python

'''
Translates X11 colors (rgb.txt) to Apple color palette (*.clr).

Read the RGB file from the standard input and then write the colors
to the standard output (works as a filter), use shell
redirection to write to a file.
'''

def parse_rgb(rgb_txt_stream):
    'Parse rgb.txt file (the input is a stream).'
    rgb = []
    while True:
        info = rgb_txt_stream.readline()
        if not info:
            break
        if info == '\n':
            continue
        colors, name = info.strip().split('\t\t')
        r, g, b = colors.split()
        rgb.append((int(r), int(g), int(b), name))
    return rgb

def rgb2clr(rgb):
    'Convert RGB colors to Apple colors.'
    clr = []
    for val in rgb:
        r, g, b, name = val[0], val[1], val[2], val[3]
        new = 0.0, float(r)/255.0, float(g)/255.0, float(b)/255.0, 1.0, name
        clr.append(new)
    return clr

def display_pallete(clr):
    'Display textual Apple colors.'
    print(len(clr))
    for val in clr:
        print('%d %1.4f %1.4f %1.4f %1.4f %s' % val)

if __name__ == '__main__':
    import sys
    display_pallete(rgb2clr(parse_rgb(sys.stdin)))

# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4


import sys
sys.stdin = open('sample_input.txt','r')

def dfs(value, location, visit):
   global N, std
   if value <= std:
       return
   if location == N:
       if value > std:
           std = value
   else:
       for i in range(N):
           if visit[i] == 0:
               visit[i] = 1
               dfs(value * work[location][i] / 100, location+1, visit)
               visit[i] = 0

for tc in range(int(input())):
   N = int(input())
   work = [ list(map(int, input().split())) for _ in range(N) ]
   std = 0
   dfs(1, 0, [0]*N)
   print("#{} {}".format(tc+1, format(std * 100, '.6f')))


# built-in
from ssl import create_default_context

# external
import certifi
from aiohttp import ClientSession, TCPConnector

def aiohttp_session(*, auth=None, **kwargs):
    headers = dict()
    if auth:
        headers['Authorization'] = auth.encode()
    ssl_context = create_default_context(cafile=certifi.where())
    try:
        connector = TCPConnector(ssl=ssl_context)
    except TypeError:
        connector = TCPConnector(ssl_context=ssl_context)
    return ClientSession(headers=headers, connector=connector, **kwargs)


from ..token import Token
from .node import Node
from .identifier_list import IdentifierList

class WriteStatement(Node):
    """
    A write statement.
    """

    def __init__(self):
        """
        Create the write statement.
        """

        self.identifiers = IdentifierList()

    @classmethod
    def parse(cls, tokenizer, identifiers):
        """
        Parse the write statement.
        """

        statement = WriteStatement()
        cls.extract_token(tokenizer, Token.WRITE)
        statement.identifiers = IdentifierList.parse(tokenizer, identifiers)
        cls.extract_token(tokenizer, Token.SEMICOLON)
        return statement

    def execute(self, identifiers, data):
        """
        Execute the statement.
        """

        for identifier in self.identifiers:
            print("{0} = {1}".format(
                identifier.name,
                identifiers.get_value(identifier.name)))

    def __str__(self):
        """
        Human-readable string representation.
        """

        return "{0} {1}{2}".format(
            Token.WRITE.value[1],
            self.identifiers,
            Token.SEMICOLON.value[1])


import unittest
from collections import deque
from typing import List

from hypothesis import given
from hypothesis import strategies as st

from convex_hull import Point
from convex_hull import clockwise_sort
from convex_hull import compute_hull
from convex_hull import is_clockwise
from convex_hull import is_counter_clockwise
from convex_hull import y_intercept

class TestGivenFunctions(unittest.TestCase):
    """ This class checks simple cases for the given functions.
    """
    def test_y_intercept(self):
        p1 = (0, 0)
        p2 = (20, 40)
        xs = [i for i in range(41)]
        for x in xs:
            y_int = y_intercept(p1, p2, x)
            self.assertAlmostEqual(2 * x, y_int, places=5)
        return

    def test_clockwise(self):
        p1 = (0, 0)
        p2 = (1, 0)
        p3 = (1, 1)

        self.assertTrue(is_clockwise(p1, p2, p3))
        self.assertFalse(is_clockwise(p1, p3, p2))
        return

    def test_counter_clockwise(self):
        p1 = (0, 0)
        p2 = (1, 0)
        p3 = (1, 1)

        self.assertTrue(is_counter_clockwise(p1, p3, p2))
        self.assertFalse(is_counter_clockwise(p1, p2, p3))
        return

    def test_clockwise_sort(self):
        p1 = (0, 0)
        p2 = (1, 0)
        p3 = (1, 1)
        p4 = (0, 1)
        points = [p2, p4, p1, p3]
        clockwise_sort(points)

        test_points = points + points[:2]
        for i in range(len(points)):
            a = test_points[i]
            b = test_points[i + 1]
            c = test_points[i + 2]
            self.assertTrue(is_clockwise(a, b, c))
        return

def is_convex_hull(hull: List[Point], points: List[Point]):
    vertices = hull + [hull[0]]
    prev_two = deque(maxlen=2)
    for vertex in vertices:
        prev_two.append(vertex)
        if len(prev_two) == 2:
            for point in points:
                assert not is_counter_clockwise(*prev_two, point)
    return True

class TestComputeHull(unittest.TestCase):
    """
    We provide one simple test here.
    You should write several specific tests for yourself.
    """

    @given(st.lists(  # generate a list
        st.tuples(  # of 2-tuples
            st.integers(min_value=0, max_value=100_000),  # of integers in the interval [0, 100_000]
            st.integers(min_value=0, max_value=100_000),
        ),
        min_size=3,  # minimum length of list
        max_size=100_000,  # maximum length of list
        unique=True,  # list will contain unique elements
    ))
    def test_compute_hull(self, points):
        points = list(points)
        clockwise_sort(points)

        hull = compute_hull(points)
        self.assertTrue(is_convex_hull(hull, points))
        return