import Class_BWTS
import time
import warnings
import sys
import os
import re
import lib_Log
import lib_Modbus

class BioSea_150(Class_BWTS.BWTS):

    def __init__(self, INI, deviceDescr, devNumber):
            self.Error = False
            self.log = lib_Log.Log(PrintToConsole=True)

            #for inhiretance from device class
            self.INI = INI
            self.deviceDescr = deviceDescr
            self.devNumber = devNumber
            self.log.increaseLevel()

            #connection information
            self.IP = None
            self.modBusPort = None
            self.slaveID = None
            self.dictID = 1000

    def Connect(self):
            """
                    Called from device class
                    returns True if failed
            """
            #get vars out of INI
            self.IP = self.INI.getOption(self.deviceDescr, self.devNumber, "IP")
            self.modBusPort = self.INI.getOption(self.deviceDescr, self.devNumber, "MODBUSPORT")
            self.slaveID = self.INI.getOption(self.deviceDescr, self.devNumber, "SLAVEID")

            #check ini vars
            if None in (self.IP, self.modBusPort, self.slaveID):
                self.Error = True
                self.log.printError("Error: IP (= %s), ModbusPort (= %s) or SlaveID (= %s) is missing in INI-Files" % (self.IP, self.modBusPort, self.slaveID))
            else:
                #ModBusPort
                if not self.modBusPort.isdigit():
                        self.Error = True
                        self.log.printError("Error: ModbusPort should be numeric (%s given)" % self.modBusPort)
                else:
                        self.modBusPort = int(self.modBusPort)
                #slaveID
                if not self.slaveID.isdigit():
                        self.Error = True
                        self.log.printError("Error: SlaveID should be numeric (%s given)" % self.slaveID)
                else:
                        self.slaveID = int(self.slaveID)

            #connect
            if self.Error == False:
                pass
                try:
                    self.modbusSocket = lib_Modbus.ModBusRTU(self.IP, self.modBusPort, slaveID = [self.slaveID])
                except Exception as e:
                    self.log.printError("ERROR in connecting ModBusRTU - BWTS%s" % self.devNumber)
                    return None

            #return
            return self.Error

    def GetData(self):
            """
                Called from device-class
            """
            if self.Error == False:
                returnValue = {}
                returnValue["ReadError"] = True
                try:
                    self.electricalCabinets = [] #list with available cabinets

                    self.dictID = 1000
                    #general data
                    self.log.printInfo("Get general data")
                    returnValue.update(self.GetGeneralData())
                    #ELC (UVx.x)
                    self.log.printInfo("Get ELC data")
                    returnValue.update(self.GetUVData())
                    #valves
                    self.log.printInfo("Get valve data")
                    returnValue.update(self.GetValveData())
                    #motors
                    self.log.printInfo("Get motor data")
                    returnValue.update(self.GetMotorData())
                    #pumps
                    self.log.printInfo("Get pump data")
                    returnValue.update(self.GetPumpData())
                    #flow measurement
                    self.log.printInfo("Get flow measurement data")
                    returnValue.update(self.GetFlowMeasurementData())
                    #temperature Measurement
                    self.log.printInfo("Get temperature measurement data")
                    returnValue.update(self.GetTemperatureMeasurementData())
                    #UVirradiance measurement
                    self.log.printInfo("Get UV irradiance measurement data")
                    returnValue.update(self.GetUVirradianceMeasurementData())
                    #Get level transmitter data
                    self.log.printInfo("Get level transmitter data")
                    returnValue.update(self.GetLevelTransmitterData())
                    #Thermostats
                    self.log.printInfo("Get thermostats data")
                    returnValue.update(self.GetThermostatData())
                    #Alarms and warnings
                    self.log.printInfo("Get alarms and warnings")
                    returnValue.update(self.GetAlarmsAndWarnings())
                    #Events
                    self.log.printInfo("Get events")
                    returnValue.update(self.GetEvents())

                    #readError
                    returnValue["ReadError"] =False

                    #return
                    return returnValue

                except Exception as e:
                    self.log.printError("ERROR in retreiving BWTS%s data, %s Module Error" % (self.devNumber, sys._getframe().f_code.co_name))
                    self.log.printError(str(e))
                    self.Error = True
                    returnValue["ReadError"] = True
                    return returnValue

            else:
                self.log.printWarning("%s skipped due to previous failure" % sys._getframe().f_code.co_name)
                return None

    def GetUVData(self):
            #init vars
            returnValue = {}
            serialNumberReg = 0x0000 #v2.02.00
            softwareVersReg = 0x00FA #v2.02.00
            currentPowerReg = 0x0064 #v2.02.00
            currentVltgeReg = 0x0082 #v2.02.00
            currentAmpreReg = 0x00A0 #v2.02.00
            powerSetVlueReg = 0x00BE #v2.02.00
            instldLmpPwrReg = 0x00DC #v2.02.00
            lmpOprtngTmeReg = 0x0118 #v2.02.00
            elcStartNmbrReg = 0x0136 #v2.02.00
            defaultNmberReg = 0X0154 #v2.02.00
            uvElcAlarmReg   = 0x0400 #v2.02.00
            orderStatusReg  = 0x0190 #v2.02.00

            defaultStatusBitCounter = 0x01
            defaultStatusResult = 0

            sys.stdout.write('      (* = Skipped)\n')
            sys.stdout.flush()
            sys.stdout.write('      ')
            sys.stdout.flush()

            for major in range(1, 10 + 1): #run from 1-10
                for minor in range(1,2+1): #run from 1-2
                    sys.stdout.write("ELC%s.%s" % (major, minor))
                    sys.stdout.flush()

                    #increase register pointer (but not for first loop)
                    if not (major == 1 and minor == 1):
                        serialNumberReg += 0x02 #v2.02.00
                        softwareVersReg += 0x01 #v2.02.00
                        currentPowerReg += 0x01 #v2.02.00
                        currentVltgeReg += 0x01 #v2.02.00
                        currentAmpreReg += 0x01 #v2.02.00
                        powerSetVlueReg += 0x01 #v2.02.00
                        instldLmpPwrReg += 0x01 #v2.02.00
                        lmpOprtngTmeReg += 0x01 #v2.02.00
                        elcStartNmbrReg += 0x01 #v2.02.00
                        defaultNmberReg += 0X01 #v2.02.00
                        uvElcAlarmReg   += 0x01 #v2.02.00
                        orderStatusReg  += 0x01 #v2.02.00

                        defaultStatusBitCounter += 0x01

                    #get serialNumber
                    receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [(serialNumberReg >> 8), (serialNumberReg & 0xff)])
                    dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                    snYear   = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,6 )['dec']
                    snMonth  = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,7 ,10)['dec']
                    snNumber = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,11,23)['dec']

                    if ((snNumber is None) or (snNumber == 0)):
                        #no serial number found tso do nothing
                        sys.stdout.write("* ")
                        sys.stdout.flush()
                    else:
                        #serial number found, print space
                        sys.stdout.write(" ")
                        sys.stdout.flush()

                        #update available cabinets
                        if (major not in self.electricalCabinets):
                            self.electricalCabinets.append(major)

                        #get firmware
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(softwareVersReg >> 8), (softwareVersReg & 0xff)])
                        result = self.modbusSocket.ExtractData(receivedData)
                        dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                        minorVersion  = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,3 )['dec']
                        majorVersion  = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,4 ,7 )['dec']

                        #current power
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(currentPowerReg >> 8), (currentPowerReg & 0xff)])
                        currentPower = self.modbusSocket.ExtractData(receivedData)['dataLong']

                        #current Voltage
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(currentVltgeReg >> 8), (currentVltgeReg & 0xff)])
                        currentVoltage = self.modbusSocket.ExtractData(receivedData)['dataLong']

                        #current Amperage
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(currentAmpreReg >> 8), (currentAmpreReg & 0xff)])
                        currentAmperage = float(self.modbusSocket.ExtractData(receivedData)['dataLong']) / 10 #modbus returns in units of 100mA - 12 = 1.2A, so divide by 10

                        #power set value
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(powerSetVlueReg >> 8), (powerSetVlueReg & 0xff)])
                        powerSetValue = self.modbusSocket.ExtractData(receivedData)['dataLong']

                        #installed lamp power
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(instldLmpPwrReg >> 8), (instldLmpPwrReg & 0xff)])
                        installedLampPower = self.modbusSocket.ExtractData(receivedData)['dataLong']

                        #lamp operating time
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(lmpOprtngTmeReg >> 8), (lmpOprtngTmeReg & 0xff)])
                        lampOperatingTime = self.modbusSocket.ExtractData(receivedData)['dataLong']

                        #start number
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(elcStartNmbrReg >> 8), (elcStartNmbrReg & 0xff)])
                        startNumber = self.modbusSocket.ExtractData(receivedData)['dataLong']

                        #default number
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(defaultNmberReg >> 8), (defaultNmberReg & 0xff)])
                        defaultNumber = self.modbusSocket.ExtractData(receivedData)['dataLong']

                        #UV/ELC Alarm registers
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [(uvElcAlarmReg   >> 8), (uvElcAlarmReg   & 0xff)])
                        dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                        alarm = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,2 )['dec']  #bit 0 = Discordance PLC/ELC defect
                                                                                #bit 1 = Internal defect ELC
                                                                                #bit 2 = Defect of lack of safety

                        #get order status
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(orderStatusReg >> 8), (orderStatusReg & 0xff)])
                        result = self.modbusSocket.ExtractData(receivedData)
                        dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                        orderStatus  = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,2 )['dec']   #bit 0 = Order of starting ON
                                                                                #bit 1 = Order in standby
                                                                                #bit 2 = Default

                        #default status bit
                        if (major == 1 and minor == 1):
                                receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x02, 0x08])
                                defaultStatusResult = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                                defaultStatusBitCounter = 0x00

                        if (major == 9 and minor == 1):
                                receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x02, 0x09])
                                defaultStatusResult = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                                defaultStatusBitCounter = 0x00

                        defaultStatusBit = self.modbusSocket.GetPartOfBitArray(defaultStatusResult,defaultStatusBitCounter ,defaultStatusBitCounter )['dec']

                        #build returnValue
                        returnValue[self.dictID] = {}
                        returnValue[self.dictID]["moduleName"] = "UV%s.%s" % (major, minor)
                        returnValue[self.dictID]["snYear"] = snYear
                        returnValue[self.dictID]["snMonth"] = snMonth
                        returnValue[self.dictID]["snNumber"] = snNumber
                        returnValue[self.dictID]["firmware"] = str(majorVersion) + "." + str(minorVersion)
                        returnValue[self.dictID]["currentPower"] = currentPower
                        returnValue[self.dictID]["currentVoltage"] = currentVoltage
                        returnValue[self.dictID]["currentAmperage"] = currentAmperage
                        returnValue[self.dictID]["powerSetValue"] = powerSetValue
                        returnValue[self.dictID]["installedLampPower"] = installedLampPower
                        returnValue[self.dictID]["lampOperatingTime"] = lampOperatingTime
                        returnValue[self.dictID]["startNumber"] = startNumber
                        returnValue[self.dictID]["defaultNumber"] = defaultNumber
                        returnValue[self.dictID]["uvElcAlarm"] = alarm
                        returnValue[self.dictID]["uvStatus"] = orderStatus
                        returnValue[self.dictID]["defaultStatusBit"] = defaultStatusBit
                        self.dictID += 1

            sys.stdout.write("\n")
            sys.stdout.flush()

            #return
            return returnValue

    def GetGeneralData(self):
            #init vars
            returnValue = {}
            returnValue[1] = {} #choose 1 for general, is not needed but makes it easier to remember
            returnValue[1]["moduleName"] = "General"

            #v2.02.00 - get mode status 1
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [0x05, 0x00])
            result = self.modbusSocket.ExtractData(receivedData)
            dataLongBitArray = self.modbusSocket.ConvertToBitArray(result['dataLong'])
            modeStatus1 = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,16 )['dec']

            #v2.02.00 - get mode status 2
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [0x05, 0x46])
            result = self.modbusSocket.ExtractData(receivedData)
            dataLongBitArray = self.modbusSocket.ConvertToBitArray(result['dataLong'])
            modeStatus2 = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,16 )['dec']

            modeStatus = modeStatus1 * 1 + modeStatus2 * 256

            #v2.02.00 - volume measurement - m^3
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x00, 0x32])
            volumeMeasurement = self.modbusSocket.ExtractData(receivedData)['dataLong']
            volumeMeasurement = round(lib_Modbus.IEEE_32Bit_to_float(volumeMeasurement),2)

            #v2.02.00 - consumption measurement - kW/h
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x00, 0x46])
            consumption = self.modbusSocket.ExtractData(receivedData)['dataLong']
            consumption = round(lib_Modbus.IEEE_32Bit_to_float(consumption),2)

            #build return value
            returnValue[1]["modeStatus"] = modeStatus
            returnValue[1]["volumeMeasurement"] = volumeMeasurement
            returnValue[1]["consumption"] = consumption

            #returnValue
            return returnValue

    def GetValveData(self):
            #init vars
            returnValue = {}
            number = 0
            alarmReg = 0x00

            #start and end address
            for i in range(0xC2, 0xD4 + 1):
                    number += 1
                    #custom numbers
                    if i == 0xC2: #v2.02.00
                        number = 5
                        alarmReg = 0x047E - 0x01
                    if i == 0xC7: #v2.02.00
                        number = 101
                        alarmReg = 0x0483 - 0x01
                    if i == 0xCE: #v2.02.00
                        number = 201
                        alarmReg = 0x048A - 0x01

                    #get data
                    receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [0x01, i])
                    result = self.modbusSocket.ExtractData(receivedData)

                    if str(result['dataLong']) is not "0":
                        #alarm
                        alarmReg += 0x01
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(alarmReg   >> 8), (alarmReg   & 0xff)])
                        dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                        alarm = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,1 )['dec']      #bit 0 = Defect opening sensor
                                                                                #bit 1 = Defect closing sensor
                        #build returnValue
                        returnValue[self.dictID] = {}
                        returnValue[self.dictID]["valveStatus"] = str(result['dataLong'])
                        returnValue[self.dictID]["valveAlarm"] = alarm
                        returnValue[self.dictID]["moduleName"] = "Y%03d" % number
                        self.dictID = self.dictID + 1

            #returnValue
            return returnValue

    def GetMotorData(self):
            #init vars
            returnValue = {}
            number = 0
            alarmReg = 0x00

            #start and end address
            for i in range(0xD6, 0xDB + 1):
                    number += 1
                    alarmType = "motorAlarmType1"
                    #custom numbers
                    if i == 0xD6: #v2.02.00
                        number = 101
                        alarmReg = 0x044C - 0x01
                    if i == 0xD7: #v2.02.00
                        number = 103
                        alarmReg = 0x044E - 0x01
                    if i == 0xD8: #v2.02.00
                        number = 104
                        alarmReg = 0x044F - 0x01
                    if i == 0xD9: #v2.02.00
                        number = 111
                        alarmReg = 0x0450 - 0x01
                        alarmType = "motorAlarmType2"
                    if i == 0xDA: #v2.02.00
                        number = 102
                        alarmReg = 0x044D - 0x01
                    if i == 0xDB: #v2.02.00
                        number = 211
                        alarmReg = 0x0451 - 0x01
                        alarmType = "motorAlarmType2"

                    #get data
                    receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [0x01, i])
                    result = self.modbusSocket.ExtractData(receivedData)    #bit 1 = move forward or motor running
                                                                            #bit 2 = default motor (1 way motor)
                                                                            #bit 3 = move backward  (2 way motor)
                                                                            #bit 4 = default motor (2 way motor)

                    #alarm
                    alarmReg += 0x01
                    receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(alarmReg   >> 8), (alarmReg   & 0xff)])
                    dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                    alarm = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,16 )['dec']

                    #build returnValue
                    returnValue[self.dictID] = {}
                    returnValue[self.dictID]["motorStatus"] = str(result['dataLong'])
                    returnValue[self.dictID][alarmType] = alarm
                    returnValue[self.dictID]["moduleName"] = "M%03d" % number
                    self.dictID = self.dictID + 1

            #returnValue
            return returnValue

    def GetPumpData(self):
            #init vars
            returnValue = {}

            number = 0
            #start and end address
            for i in range(0xE0, 0xE2 + 1):
                number += 1
                #custom numbers
                if i == 0xE0: #v2.02.00
                    number = 1
                    alarmReg = 0x04B0
                if i == 0xE1: #v2.02.00
                    number = 101
                    alarmReg = 0x04B1
                if i == 0xE2: #v2.02.00
                    number = 201
                    alarmReg = 0x04B2

                #get data
                receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [0x01, i])
                result = self.modbusSocket.ExtractData(receivedData)

                #Alarm registers
                receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(alarmReg   >> 8), (alarmReg   & 0xff)])
                dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                alarm = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,16 )['dec']

                #build returnValue
                returnValue[self.dictID] = {}
                returnValue[self.dictID]["pumpStatus"] = str(result['dataLong'])
                returnValue[self.dictID]["pumpAlarmType1"] = alarm
                returnValue[self.dictID]["moduleName"] = "P%03d" % number
                self.dictID = self.dictID + 1

            #returnValue
            return returnValue

    def GetFlowMeasurementData(self):
            #init vars
            returnValue = {}

            #flowMeasurement
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x00, 0x36]) #v2.02.00
            result = self.modbusSocket.ExtractData(receivedData)['dataLong']
            result = round(lib_Modbus.IEEE_32Bit_to_float(result),2)

            #v2.02.00 - FT001 - defect sensor or cable break
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x05, 0x32]) #v2.02.00
            dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
            defect = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,0 )['dec']      #bit 0 = defect thermostat electrical equipment box

            #build returnValue
            returnValue[self.dictID] = {}
            returnValue[self.dictID]["flowMeasurement"] = result
            returnValue[self.dictID]["FMdefect"] = defect
            returnValue[self.dictID]["moduleName"] = "FT001"
            self.dictID = self.dictID + 1

            #returnValue
            return returnValue

    def GetUVirradianceMeasurementData(self):
            #init vars
            returnValue = {}

            #UV irradiance Measurement
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x00, 0x34]) #v2.02.00
            result = self.modbusSocket.ExtractData(receivedData)['dataLong']
            result = round(lib_Modbus.IEEE_32Bit_to_float(result),2)

            #v2.02.00 - UV001 - defect sensor or cable break
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x05, 0x33]) #v2.02.00
            dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
            defect = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,0 )['dec']      #bit 0 = defect thermostat electrical equipment box

            #build returnValue
            returnValue[self.dictID] = {}
            returnValue[self.dictID]["uvIrradiance"] = result
            returnValue[self.dictID]["UVdefect"] = defect
            returnValue[self.dictID]["moduleName"] = "UV001"
            self.dictID = self.dictID + 1

            #returnValue
            return returnValue

    def GetTemperatureMeasurementData(self):
            #init vars
            returnValue = {}

            #v2.02.00 - temperature measurement - degrees celcius
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x00, 0x38]) #v2.02.00
            result = self.modbusSocket.ExtractData(receivedData)['dataLong']
            result = round(lib_Modbus.IEEE_32Bit_to_float(result),2)

            #v2.02.00 - TT001 - defect sensor or cable break
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x05, 0x30]) #v2.02.00
            dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
            defect = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,0 )['dec']      #bit 0 = defect thermostat electrical equipment box

            #build returnValue
            returnValue[self.dictID] = {}
            returnValue[self.dictID]["temperature"] = result
            returnValue[self.dictID]["TTdefect"] = defect
            returnValue[self.dictID]["moduleName"] = "TT001"
            self.dictID = self.dictID + 1

            #returnValue
            return returnValue

    def GetThermostatData(self):
            #init vars
            returnValue = {}

            number = 0
            #start and end address
            for i in range(0xC4, 0xCD + 1): #v2.02.00
                    number += 1
                    #custom numbers
                    if i == 0xC4:
                        number = 1

                    #see if cabinet exists in real
                    if number in self.electricalCabinets:
                        #get data
                        receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [0x04, i]) #v2.02.00
                        dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                        defectThermostat = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,0 )['dec']      #bit 0 = defect thermostat electrical equipment box

                        #build returnValue
                        returnValue[self.dictID] = {}
                        returnValue[self.dictID]["TSdefect"] = defectThermostat
                        returnValue[self.dictID]["moduleName"] = "Electrical Cabinet %02d" % number
                        self.dictID = self.dictID + 1

            #returnValue
            return returnValue

    def GetLevelTransmitterData(self):
            #init vars
            returnValue = {}

            #v2.02.00 - LT01 - CIP tank level low
            receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x02], startAddress = [0x05, 0x31]) #v2.02.00
            dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
            defect = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,0 ,0 )['dec']      #bit 0 = defect thermostat electrical equipment box

            #build returnValue
            returnValue[self.dictID] = {}
            returnValue[self.dictID]["LTdefect"] = defect
            returnValue[self.dictID]["moduleName"] = "LT01"
            self.dictID = self.dictID + 1

            #returnValue
            return returnValue

    def GetAlarmsAndWarnings(self):
            #init vars
            returnValue = {}
            returnValue[self.dictID] = {}

            maxBit = 0
            name = ""
            #start and end address
            for i in range(0x0512, 0x0545 + 1):
                    minBit = 0
                    maxBit = 12
                    if i == 0x0512:
                            name = "alarmReg0512"
                    if i == 0x0513:
                            name = "alarmReg0513"
                    if i == 0x0514:
                            name = "alarmReg0514"
                    if i == 0x0515:
                            name = "alarmReg0515"
                    if i == 0x0516:
                            name = "alarmReg0516"
                    if i == 0x0517:
                            name = "alarmReg0517"
                    if i == 0x0518:
                            name = "alarmReg0518"
                    if i > 0x0518 and i < 0x051A: #skip numbers in between
                            continue
                    if i == 0x051A:
                            name = "alarmReg051A"
                    if i > 0x051A and i < 0x051D: #skip numbers in between
                            continue
                    if i == 0x051D:
                            name = "alarmReg051D"
                    if i == 0x051E:
                            name = "alarmReg051E"
                    if i == 0x051F:
                            name = "alarmReg051F"
                    if i == 0x0520:
                            name = "alarmReg0520"
                    if i > 0x0520 and i < 0x0545: #skip numbers in between
                            continue
                    if i == 0x0545:
                            name = "alarmReg0545"

                    #get data
                    receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(i >> 8), (i & 0xff)])
                    dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                    value = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,minBit,maxBit)['dec']      #bit 0 = defect thermostat electrical equipment box

                    #build returnValue
                    returnValue[self.dictID][name] = value

            returnValue[self.dictID]["moduleName"] = "General alarms and warnings"
            self.dictID = self.dictID + 1

            return returnValue

    def GetEvents(self):
            #init vars
            returnValue = {}
            returnValue[self.dictID] = {}

            maxBit = 0
            name = ""
            #start and end address
            for i in range(0x04D8, 0x0546 + 1):
                    minBit = 0
                    maxBit = 0
                    if i == 0x04D8:
                            name = "eventReg04D8"
                    if i == 0x04D9:
                            name = "eventReg04D9"
                    if i == 0x04DA:
                            name = "eventReg04DA"
                    if i == 0x04DB:
                            name = "eventReg04DB"
                    if i > 0x04DB and i < 0x0500: #skip numbers in between
                            continue
                    if i == 0x0500:
                            name = "eventReg0500"
                            maxBit = 5
                    if i == 0x0501:
                            name = "eventReg0501"
                            maxBit = 2
                    if i == 0x0502:
                            name = "eventReg0502"
                    if i == 0x0503:
                            name = "eventReg0503"
                    if i == 0x0504:
                            name = "eventReg0504"
                    if i == 0x0505:
                            name = "eventReg0505"
                    if i > 0x0505 and i < 0x0546: #skip numbers in between
                            continue
                    if i == 0x0546:
                            name = "eventReg0546"
                            maxBit = 10
                    #get data
                    receivedData = self.modbusSocket.SendAndReceive(functionCode = [0x03], requestQuantity = [0x00, 0x01], startAddress = [(i >> 8), (i & 0xff)])
                    dataLongBitArray = self.modbusSocket.ConvertToBitArray(self.modbusSocket.ExtractData(receivedData)['dataLong'])
                    value = self.modbusSocket.GetPartOfBitArray(dataLongBitArray,minBit,maxBit)['dec']      #bit 0 = defect thermostat electrical equipment box

                    #build returnValue
                    returnValue[self.dictID][name] = value

            returnValue[self.dictID]["moduleName"] = "Events"
            self.dictID = self.dictID + 1

            return returnValue


import glob
import os
import jieba
import snownlp
import thulac
from tqdm import tqdm
thu = thulac.thulac(seg_only=True)

jieba.initialize()

file_list = glob.glob("testing/*.utf8")

# perl scripts/score gold/pku_training_words.utf8 gold/pku_test_gold.utf8 results/pku_test_jieba.utf8 > score_jieba.utf8

def gen_score(file_name, res_path, method):
    final_path = "scores/score_dataset_method.utf8"
    if "pku" in file_name:
        os.system("perl {} {} {} {} > {}".format("scripts/score", "gold/pku_training_words.utf8", "gold/pku_test_gold.utf8", res_path, final_path.replace("dataset", "pku").replace("method", method)))
    elif "as" in file_name:
        os.system("perl {} {} {} {} > {}".format("scripts/score", "gold/as_training_words.utf8", "gold/as_testing_gold.utf8", res_path, final_path.replace("dataset", "as").replace("method", method)))
    elif "cityu" in file_name:
        os.system("perl {} {} {} {} > {}".format("scripts/score", "gold/cityu_training_words.utf8", "gold/cityu_test_gold.utf8", res_path, final_path.replace("dataset", "cityu").replace("method", method)))
    elif "msr" in file_name:
        os.system("perl {} {} {} {} > {}".format("scripts/score", "gold/msr_training_words.utf8", "gold/msr_test_gold.utf8", res_path, final_path.replace("dataset", "msr").replace("method", method)))

for file_name in file_list:
    with open(file_name, "r") as fr:
        datas = fr.readlines()

    # jieba 结果
    jieba_res_path = file_name.replace("testing", "results").replace(".utf8", "_jieba.utf8")
    with open(jieba_res_path, "w") as fw:
        for data in tqdm(datas):
            data = data.strip()
            if data == "":
                fw.write("\n")
                continue
            wordlist = list(jieba.cut(data))
            res = "  ".join(wordlist)
            fw.write(res+"\n")
    gen_score(file_name, jieba_res_path, "jieba")

    # snownlp 结果
    snownlp_res_path = file_name.replace("testing", "results").replace(".utf8", "_snownlp.utf8")
    with open(snownlp_res_path, "w") as fw:
        for data in tqdm(datas):
            data = data.strip()
            if data == "":
                fw.write("\n")
                continue
            wordlist = snownlp.SnowNLP(data).words
            res = "  ".join(wordlist)
            fw.write(res+"\n")
    gen_score(file_name, snownlp_res_path, "snownlp")

    # thulac 结果
    thulac_res_path = file_name.replace("testing", "results").replace(".utf8", "_thulac.utf8")
    with open(thulac_res_path, "w") as fw:
        for data in tqdm(datas):
            data = data.strip()
            if data == "":
                fw.write("\n")
                continue
            wordlist = thu.cut(data, text=True).split()
            res = "  ".join(wordlist)
            fw.write(res+"\n")
    gen_score(file_name, thulac_res_path, "thulac")


def mastermind(guesses:list, codes:list) -> tuple:
    guessesU = [False for _ in guesses]
    codesU = [False for _ in codes]
    result = [0,0]
    for i in range(len(guesses)):
        if guesses[i] == codes[i]:
            result[0] += 1
            guessesU[i] = codesU[i] = True
    for i in range(len(guesses)):
        for j in range(len(codes)):
            if not guessesU[i] and not codesU[j]:
                if guesses[i] == codes[j]:
                    result[1] += 1
                    guessesU[i] = codesU[j] = True
    return tuple(result)


import torch

from kornia.filters import sobel
from torch.nn.functional import kl_div
from src.utils.kpt_utils import get_image_patches

from .utils import differentiable_histogram

def kpt_visual_metric(kpt_sequence: torch.Tensor,
                      img_sequence: torch.Tensor,
                      patch_size: tuple,
                      n_bins: int = 30,
                      p: float = float('inf')) -> torch.Tensor:
    """ Evaluates the visual difference between the different objects tracked among key-points.

    :param kpt_sequence:
    :param img_sequence:
    :param patch_size:
    :param n_bins:
    :param p:
    :return:
    """

    N, T, K, D = kpt_sequence.shape
    _, _, C, H, W = img_sequence.shape
    Hp, Wp = patch_size

    patches = get_image_patches(img_sequence, kpt_sequence, patch_size)  # (N, T, K, C, Hp, Wp)

    grads = sobel(patches.view((N * T * K, C, Hp, Wp))).view((N, T, K, C, Hp, Wp))

    color_hists = torch.empty((N, T, K, C, n_bins))
    grad_hists = torch.empty((N, T, K, C, n_bins))

    # Compute histograms
    for n in range(N):
        for t in range(T):
            for k in range(K):
                for c in range(C):
                    color_hists[n, t, k, c] = torch.histc(patches[n, t, k, c], bins=n_bins)
                    color_hists[n, t, k, c] /= torch.sum(color_hists[n, t, k, c], dim=-1)
                    #color_hists[n, t, k, c] = differentiable_histogram(
                    #    patches[n, t, k, c], bins=n_bins, min=0.0, max=1.0
                    #)

                    grad_hists[n, t, k, c] = torch.histc(grads[n, t, k, c], bins=n_bins)
                    grad_hists[n, t, k, c] /= torch.sum(grad_hists[n, t, k, c], dim=-1)
                    #grad_hists[n, t, k, c] = differentiable_histogram(
                    #    grads[n, t, k, c], bins=n_bins, min=0.0, max=1.0
                    #)

    joint_hists = torch.multiply(color_hists, grad_hists)

    """
    #color_dists = torch.norm(color_hists.unsqueeze(2) - color_hists.unsqueeze(3), dim=[-1], p=p)   # (N, T, K, K)
    #grad_dists = torch.norm(grad_hists.unsqueeze(2) - grad_hists.unsqueeze(3), dim=[-1], p=p)  # (N, T, K, K)

    #color_dists = torch.sum(color_dists, dim=[-1, -2])/(K * (K-1))  # (N, T)
    #grad_dists = torch.sum(grad_dists, dim=[-1, -2])/(K * (K-1))  # (N, T)

    if p == 'dkl':
        joint_dists = kl_div(joint_hists.unsqueeze(2), joint_hists.unsqueeze(3))
        print(joint_dists.shape)
    else:
        joint_dists = torch.norm(joint_hists.unsqueeze(2) - joint_hists.unsqueeze(3), dim=[-1], p=p)  # (N, T, K, K)
    joint_dists = torch.sum(joint_dists, dim=[-1, -2])/(K * (K-1))  # (N, T)
    # joint_dists = torch.sum(joint_dists, dim=[-3]) / (K * (K - 1))  # (N, K, K)
    """

    joint_dist = torch.zeros([N, T, K, K])
    color_dist = torch.zeros([N, T, K, K])
    grad_dist = torch.zeros([N, T, K, K])

    for n in range(N):
        for t in range(T):
            for k in range(K):
                for _k in range(K):
                    if p == 'dkl':
                        joint_dist[n, t, k, _k] = kl_div(joint_hists[n, t, k, :], joint_hists[n, t, _k, :],
                                                         reduction='batchmean')
                        color_dist[n, t, k, _k] = kl_div(color_hists[n, t, k, :], color_hists[n, t, _k, :],
                                                         reduction='batchmean')
                        grad_dist[n, t, k, _k] = kl_div(grad_hists[n, t, k, :], grad_hists[n, t, _k, :],
                                                        reduction='batchmean')
                    else:
                        joint_dist[n, t, k, _k] = torch.norm(joint_hists[n, t, k, :] - joint_hists[n, t, _k, :], p=p)
                        color_dist[n, t, k, _k] = torch.norm(color_hists[n, t, k, :] - color_hists[n, t, _k, :], p=p)
                        grad_dist[n, t, k, _k] = torch.norm(grad_hists[n, t, k, :] - grad_hists[n, t, _k, :], p=p)

    joint_dist = torch.sum(joint_dist, dim=[-2, -1]) / (K * (K - 1))
    color_dist = torch.sum(color_dist, dim=[-2, -1]) / (K * (K - 1))
    grad_dist = torch.sum(grad_dist, dim=[-2, -1]) / (K * (K - 1))

    # return color_dists.mean() * grad_dists.mean()
    # return joint_dists.mean(), None, None #, color_dists.mean(), grad_dists.mean()

    return joint_dist.mean(), color_dist.mean(), grad_dist.mean()


import cv2,numpy

v=cv2.VideoCapture(0,cv2.CAP_DSHOW)
while True :
    a=0

    area_of_face=0
    area_of_eye = 0
    area_of_face_minus_eye = 0
    face=cv2.CascadeClassifier("C:\Python\haarcascade_frontalface_alt.xml")
    eyes = cv2.CascadeClassifier("C:\Python\haarcascade_eye.xml")

    check,frame=v.read()
    gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    f=face.detectMultiScale(gray,1.3,5)
    for x,y,w,h in f:
        area_of_face =w*h
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

        roi_gray=gray[y:y+h,x:x+w]
        roi_color = frame[y:y + h, x:x + w]
        eye=eyes.detectMultiScale(roi_gray)
        a=len(eye)

        for ex,ey,ew,eh in eye:
            area_of_eye = ew*eh
            cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (255, 0, 0), 2)
    area_of_face_minus_eyes =area_of_face-area_of_eye

    if area_of_face==area_of_face_minus_eye or a==0:
        print('drowsy')
    else:
        print('ok')

    cv2.imshow("Drowsiness Detection",frame)
    c=cv2.waitKey(1)
    if c==ord('q'):
        break
v.release()
cv2.destroyAllWindows()


import math
import numpy
import random
from parameters import *

def path_loss(distance):
    path_loss_matrix=numpy.zeros((len(distance),len(distance[0])),float)
    path_loss_ideal_matrix =numpy.zeros((len(distance),len(distance[0])),float)
    for i in range(len(path_loss_matrix)):
        for j in range(len(path_loss_matrix[0])):
            x=math.log10((distance[i][j])/d0)
            path_loss_matrix[i][j]=pl_d0 + 10*gamma*x + random.gauss(mu, sigma)
            path_loss_ideal_matrix[i][j]=pl_d0 + 10*gamma*x

    return path_loss_matrix,path_loss_ideal_matrix

def path_loss_train(distance):
    path_loss_matrix=numpy.zeros((len(distance),len(distance[0])),float)

    for i in range(len(path_loss_matrix)):
        for j in range(len(path_loss_matrix[0])):
            x=math.log10((distance[i][j])/d0_train)
            path_loss_matrix[i][j]=pl_d0_train + 10*gamma_train*x + random.gauss(mu_train, sigma_train)

    return path_loss_matrix

def received_power(path_loss):
    received_power_matrix_t=numpy.zeros((len(path_loss),len(path_loss[0])),float)

    for i in range(len(received_power_matrix_t)):
        for j in range(len(received_power_matrix_t[0])):
            received_power_matrix_t[i][j]=P_t + G_t + G_r - L_t - L_r - L_add - path_loss[i][j]

    return received_power_matrix_t

def received_power_train(path_loss):
    received_power_matrix=numpy.zeros((len(path_loss),len(path_loss[0])),float)

    for i in range(len(received_power_matrix)):
        for j in range(len(received_power_matrix[0])):
            received_power_matrix[i][j]=P_t_train + G_t_train + G_r_train - L_t_train - L_r_train - L_add_train - path_loss[i][j]

    return received_power_matrix

def BLER_func(received_power,sensitivity,tech):
    BLER_matrix=numpy.zeros((len(received_power),len(received_power[0])),float)
    for i in range(len(BLER_matrix)):
        for j in range(len(BLER_matrix[0])):
            if received_power[i][j] >= sensitivity:
                BLER_matrix[i][j]=1
                bler=1
            else:
                BLER_matrix[i][j]=0
                bler=0
            #if tech == "802.15.4" and flag==3.1:
            #    print("BLER on the main node for the packet sent from node {} for transmission period {}: {}".format(j+1,i+1,bler))
            #elif tech == "802.15.4" and flag==3.2:
            #    print("BLER on the main node for the packet sent from node {} for transmission period {}: {}".format(j+1,i+1,bler))
            #elif tech == "LoRa":
            #    print("BLER on the {}.masts for the packet sent from {}.position of the train: {}".format(j+1,i+1,bler))

    return BLER_matrix


from django.db import models
from django.utils.translation import gettext_lazy as _
from common.models import AbstractCreatedByModel

class Note(AbstractCreatedByModel):
    description = models.TextField(
        default='',
        verbose_name=_('Описание'),
    )
    guest = models.ForeignKey(
        'hostelguests.Guest',
        on_delete=models.CASCADE,
        related_name='notes',
        verbose_name=_('Гость'),
    )

    class Meta:
        verbose_name = _('Заметка о госте')
        verbose_name_plural = _('Заметки о госте')

        permissions = [
            ('can_add_note', _('Может добавлять заметку о госте')),
            ('can_change_note', _('Может изменять заметку о госте')),
            ('can_delete_note', _('Может удалять заметку о госте')),
            ('can_view_note', _('Может просматривать заметку о госте')),
        ]


import random

import qailo as q
from pytest import approx

def apply(op, m0, m1, m2, m3, v, seq, pos):
    m0 = q.mps.apply(m0, op, pos)
    m1 = q.mps.apply(m1, op, pos)
    m2 = q.mps.apply(m2, op, pos)
    m3 = q.mps.apply(m3, op, pos)
    v = q.sv.apply(v, op, pos)
    seq.append([op, pos])
    return m0, m1, m2, m3, v, seq

def test_apply():
    n = 8
    p = 64
    nkeep = 2

    m0 = q.mps.zero(n, mps=q.mps.canonical_mps)
    m1 = q.mps.zero(n, mps=q.mps.projector_mps)
    m2 = q.mps.zero(n, nkeep=nkeep, mps=q.mps.canonical_mps)
    m3 = q.mps.zero(n, nkeep=nkeep, mps=q.mps.projector_mps)
    v = q.sv.zero(n)
    seq = []

    i = 4
    j = 0
    print("apply cz on {} and {}".format(i, j))
    m0, m1, m2, m3, v, seq = apply(q.op.cz(), m0, m1, m2, m3, v, seq, [i, j])

    for _ in range(p):
        i = random.randrange(n)
        j = random.randrange(n)
        if i == j:
            t = random.randrange(3)
            if t == 0:
                print("apply h on {}".format(i))
                m0, m1, m2, m3, v, seq = apply(q.op.h(), m0, m1, m2, m3, v, seq, [i])
            elif t == 1:
                print("apply x on {}".format(i))
                m0, m1, m2, m3, v, seq = apply(q.op.s(), m0, m1, m2, m3, v, seq, [i])
            elif t == 2:
                print("apply s on {}".format(i))
                m0, m1, m2, m3, v, seq = apply(q.op.t(), m0, m1, m2, m3, v, seq, [i])
        else:
            t = random.randrange(2)
            if t == 0:
                print("apply cx on {} and {}".format(i, j))
                m0, m1, m2, m3, v, seq = apply(
                    q.op.cx(), m0, m1, m2, m3, v, seq, [i, j]
                )
            elif t == 1:
                print("apply cz on {} and {}".format(i, j))
                m0, m1, m2, m3, v, seq = apply(
                    q.op.cz(), m0, m1, m2, m3, v, seq, [i, j]
                )
        m0._is_canonical()
        m1._is_canonical()
        m2._is_canonical()
        m3._is_canonical()
        f0 = q.sv.fidelity(q.mps.state_vector(m0), v)
        f1 = q.sv.fidelity(q.mps.state_vector(m1), v)
        f2 = q.sv.fidelity(q.mps.state_vector(m2), v)
        f3 = q.sv.fidelity(q.mps.state_vector(m3), v)
        print("fidelity = {} {} {} {}".format(f0, f1, f2, f3))
        assert f0 == approx(1)
        assert f1 == approx(1)

    f0 = q.sv.fidelity(q.mps.state_vector(m0), v)
    f1 = q.sv.fidelity(q.mps.state_vector(m1), v)
    f2 = q.sv.fidelity(q.mps.state_vector(m2), v)
    f3 = q.sv.fidelity(q.mps.state_vector(m3), v)
    print("final fidelity = {} {} {} {}".format(f0, f1, f2, f3))
    assert f0 == approx(1)
    assert f1 == approx(1)

    m4 = q.mps.zero(n, mps=q.mps.projector_mps)
    f4 = q.sv.fidelity(q.mps.state_vector(q.mps.apply_seq(m4, seq)), v)
    assert f4 == approx(1)

if __name__ == "__main__":
    test_apply()


import mint_client
import mintapi
import json
import requests
import re
import os
import logging
import sys

logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")

COINTRACKING_PORTFOLIO_ID = os.environ.get('COINTRACKING_PORTFOLIO_ID')
MINT_CRYPTO_ACCOUNT_PREFIX = os.environ.get('MINT_CRYPTO_ACCOUNT_PREFIX')

def main():
    portfolio = get_cointracking_portfolio_data()

    mint = mint_client.get_mint_client()
    accounts = get_slimmed_accounts(mint)

    for account_name in accounts.keys():
        if MINT_CRYPTO_ACCOUNT_PREFIX in account_name:
            cur_account = accounts[account_name]

            ticker = account_name[account_name.index(' - ') + 3:]
            if ticker in portfolio:
                new_value = float(portfolio[ticker])
                update_account_value(mint, cur_account, new_value)

def get_slimmed_accounts(mint):
    logging.info("Fetching account data")

    providers = mint.get_providers()

    accounts_slimmed = {}

    for provider in providers:
        for account in provider['providerAccounts']:
            for link in account['metaData']['link']:
                if link['operation'] == 'updateAccount':
                    accounts_slimmed[account['name']] = {
                        'id': account['id'],
                        'name': account['name'],
                        'type': account['type'],
                        'updateAccountHref': link['href'],
                        'propertyValue': account.get('propertyValue', None),
                        'otherPropertyType': account.get('otherPropertyType', None)
                    }

    return accounts_slimmed

def update_account_value(mint, account, new_value):
    logging.info(f"Updating balance: {account['name']} was ${account['propertyValue']} is now worth ${new_value}")

    headers = mint._get_api_key_header()
    headers['content-type'] = 'application/json'

    logging.debug(f"PATCH {mintapi.api.MINT_ROOT_URL}/mas{account['updateAccountHref']}")
    response = mint.patch(
        f"{mintapi.api.MINT_ROOT_URL}/mas{account['updateAccountHref']}",
        headers=headers,
        data=json.dumps({
            "name": account['name'],
            "value": new_value,
            "associatedLoanAccounts": [],
            "hasAssociatedLoanAccounts": False,
            "type": account['type']
        })
    )

    if response.status_code != 204:
        logging.error(f"ERROR {response.status_code}: {response.content.decode('utf-8')}")

def map_currency(currency):
    if currency == 'DOT2':
        return 'DOT'

    return currency

def get_cointracking_portfolio_data():
    logging.info("Downloading from CoinTracking")

    url = f"https://cointracking.info/ajax/portfolio_current_balance.php?portfolio={COINTRACKING_PORTFOLIO_ID}&fiat=0"
    coin_data = json.loads(requests.get(url).text)

    portfolio = {}

    for data in coin_data['data']:
        symbol_search = re.search(">([A-Z0-9]*)</a>", data['c'])

        if symbol_search is not None:
            symbol = map_currency(data['c'][symbol_search.start() + 1:symbol_search.end() - 4])

            portfolio[symbol] = data['f']

    return portfolio

if __name__ == '__main__':
    main()


import json
import os

from python_terraform import Terraform

class TerraformService:
    def __init__(self, gcp_service):
        gcp_service.__create_bucket_if_it_doesnt_exist(
            "min-permission-solver-terraform-state"
        )
        service_account = gcp_service.get_service_account()
        self.__write_variable_file(service_account)
        self.terraform = self.__initialize_terraform()
        self.__import_service_account_if_it_isnt_imported(service_account)

    @staticmethod
    def __write_variable_file(service_account):
        variables = {
            "project": service_account["projectId"],
            "service_account_id": service_account["email"].split("@")[0],
        }
        variables_file = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "../terraform/variables.json")
        )
        with open(variables_file, "w") as outfile:
            json.dump(variables, outfile)

    @staticmethod
    def __initialize_terraform():
        terraform_dir = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "../terraform")
        )
        terraform = Terraform(working_dir=terraform_dir)
        return_code, stdout, stderr = terraform.init()

        if return_code != 0:
            raise Exception(f"Failed to initialize terraform: {stderr}")

        return terraform

    def __import_service_account_if_it_isnt_imported(self, service_account):
        return_code, stdout, stderr = self.terraform.cmd(
            "state show", "google_service_account.this"
        )

        if return_code == 0:
            return

        return_code, stdout, stderr = self.terraform.import_cmd(
            "google_service_account.this",
            service_account["name"],
        )

        if return_code != 0:
            raise Exception(f"Failed to import service account: {stderr}")

    def update_permissions_in_service_account(self, permissions):
        permissions_json = {
            "permission_lists": list(self.__divide_into_sized_chunks(permissions, 1000))
        }
        permissions_file = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "../terraform/permissions.json")
        )
        with open(permissions_file, "w") as outfile:
            json.dump(permissions_json, outfile)

        return_code, stdout, stderr = self.terraform.apply(skip_plan=True)

        if return_code != 0:
            raise Exception(f"Failed to update permissions: {stderr}")

    @staticmethod
    def __divide_into_sized_chunks(full_list, size):
        for i in range(0, len(full_list), size):
            yield full_list[i : i + size]


import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline

m,n,k = map(int,input().split())

def func1(x1,y1,x2,y2):
    for i in range(y1,y2):
        for j in range(x1,x2):
            graph[i][j] = 1

def func2(x,y):
    visit[y][x] = 1
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]

        if nx < 0 or ny < 0 or ny >= m or nx >= n:
            continue
        if graph[ny][nx] == 0 and visit[ny][nx] == 0:
            lst.append([ny,nx])
            func2(nx,ny)

graph = [[0]*n for _ in range(m)]

for i in range(k):
    x1,y1,x2,y2 = map(int,input().split())
    func1(x1,y1,x2,y2)

visit = [[0]*n for _ in range(m)]
lst = []
lst1 = []

dx = [0,1,0,-1]
dy = [1,0,-1,0]

for i in range(m):
    for j in range(n):
        if graph[i][j] == 0 and visit[i][j] == 0:
            func2(j,i)
            lst1.append(len(lst)+1)
            lst = []

lst1.sort()
print(len(lst1))
for i in lst1:
    print(i,end=' ')


import random
from utils import *
from proto import *
#from kill_caffe import *
from logger import *
from graph_io import GraphProtoIO

class CreateJson(object):
    """
    create an json str from dict
    """
    def __init__(self, **kwargs):
        self.__dict__ = {}
        self.__dict__ = kwargs

    def __call__(self):
        return self.__dict__

class GraphToJson(object):
    """
    convert GraphProto to json(dict type) which can be used by cytoscape elements
    """
    def __init__(self, graph_io=GraphProtoIO()):
        self.graph_proto = graph_io()
        # decide layout
        #self.get_layout_coordinate()

    def get_edge_nexts(self, node_name, with_info=False):
        """
        get edge's next node_name
        """
        edges_out = self.graph_proto.edges_out
        nexts = list()
        if node_name in edges_out:
            if with_info is False:
                for target in edges_out[node_name].target:
                    nexts.append(target.node)
            else:
                nexts = edges_out[node_name].target[:]
        return nexts

    def get_layout_coordinate(self):
        """
        get layout coordinate of node in graph board
        """
        # map node_name to its coordinate list(x, y)
        self.map_node_to_coordinate = dict()
        start_cord_x = 0
        horizon_step = 500
        vertical_step = 200
        # assign start nodes
        start_nodes = self.graph_proto.ins
        for node in start_nodes:
            self.map_node_to_coordinate[node] = [start_cord_x, 0]
            start_cord_x = start_cord_x + horizon_step
        # assign middle nodes
        nodes = self.graph_proto.nodes
        while len(self.map_node_to_coordinate.keys()) < len(nodes):
            for node_proto in nodes:
                if node_proto.name in self.map_node_to_coordinate.keys():
                    x = self.map_node_to_coordinate[node_proto.name][0]
                    y = self.map_node_to_coordinate[node_proto.name][1]
                    inc_step = 0
                    for next_node_name in self.get_edge_nexts(node_proto.name):
                        self.map_node_to_coordinate[next_node_name] = [0, 0]
                        self.map_node_to_coordinate[next_node_name][0] = x + inc_step
                        inc_step = inc_step + horizon_step
                        self.map_node_to_coordinate[next_node_name][1] = y + vertical_step
                else:
                    break

    def create_nodes(self):
        """
        create graph nodes
        """
        nodes = []
        exec_count = 0
        for node_proto in self.graph_proto.nodes:
            inner_data = CreateJson(id=node_proto.name,
                                                            name=node_proto.Op.name,
                                                            exec_count=exec_count,
                                                            lane=node_proto.lane, # addition for optimization
                                                            need_wait=node_proto.need_wait) # addition for optimization
            exec_count = exec_count + 1
            node = CreateJson(data=inner_data())
            nodes.append(node())
        return nodes

    def create_edges(self):
        """
        create graph edges
        """
        memory_bank_count = 1
        # map : edge name --> hex color of html
        self.edge_color_map = dict()
        # map : edge name --> memory bank id
        self.edge_memory_bank_map = dict()
        r = lambda: random.randint(0, 255)
        new_color = lambda: ("#%02X%02X%02X" % (r(), r(), r()))
        for node_proto in self.graph_proto.nodes:
            if node_proto.name in self.graph_proto.edges_out:
                for node_name in self.get_edge_nexts(node_proto.name):
                    edge_name = node_proto.name + '_' + node_name
                    if edge_name in self.graph_proto.edges_info:
                        tensor_proto = self.graph_proto.edges_info[edge_name]
                        shared = tensor_proto.shared
                        tensor_name = tensor_proto.name
                        if not shared:
                            self.edge_color_map[tensor_name] = new_color()
                            self.edge_memory_bank_map[tensor_name] = memory_bank_count
                            memory_bank_count = memory_bank_count + 1
        edges = []
        for node_proto in self.graph_proto.nodes:
            if node_proto.name in self.graph_proto.edges_out:
                for node_name in self.get_edge_nexts(node_proto.name):
                    edge_name = node_proto.name + '_' + node_name
                    tensor_name = ""
                    shared = ""
                    share_from = ""
                    if edge_name in self.graph_proto.edges_info:
                        tensor_proto = self.graph_proto.edges_info[edge_name]
                        tensor_name = tensor_proto.name
                        shared = tensor_proto.shared
                        share_from = tensor_proto.share_from
                        if shared:
                            self.edge_color_map[tensor_name] = self.edge_color_map[share_from]
                            self.edge_memory_bank_map[tensor_name] = self.edge_memory_bank_map[share_from]
                    if tensor_name == "":
                        inner_data = CreateJson(source=node_proto.name,
                                                                        target=node_name)
                    else:
                        inner_data = CreateJson(source=node_proto.name,
                                                                        target=node_name,
                                                                        edge_name=tensor_name,
                                                                        shared=shared,
                                                                        share_from=share_from,
                                                                        edge_color=self.edge_color_map[tensor_name],
                                                                        memory_id=self.edge_memory_bank_map[tensor_name])
                    edge = CreateJson(data=inner_data())
                    edges.append(edge())
        return edges

    def create_attr(self):
        """
        create graph attrs
        """
        attrs = []
        for node_proto in self.graph_proto.nodes:
            key_id = node_proto.name
            node_attrs = []
            for attr_name in node_proto.attr.keys():
                value_data = node_proto.attr[attr_name]
                name = attr_name
                type_str = ""
                value = ""
                if value_data.type == STR:
                    type_str = "string"
                    value = value_data.s
                elif value_data.type == INT32:
                    type_str = "int"
                    value = value_data.i
                elif value_data.type == FLOAT:
                    type_str = "float"
                    value = value_data.f
                elif value_data.type == BOOLEN:
                    type_str = "bool"
                    value = "true" if value_data.b else "false"
                elif value_data.type == TENSOR:
                    type_str = "tensor"
                    value = list(value_data.tensor.shape.dim.value)
                elif value_data.type == CACHE_LIST:
                    type_str = "list"
                    if value_data.cache_list.type == STR:
                        value = value_data.cache_list.s
                    elif value_data.cache_list.type == INT32:
                        value = value_data.cache_list.i
                    elif value_data.cache_list.type == FLOAT:
                        value = value_data.cache_list.f
                    elif value_data.cache_list.type == BOOLEN:
                        value = value_data.cache_list.b
                    elif value_data.cache_list.type == CACHE_LIST:
                        value = []
                        for list_tmp in value_data.cache_list.l:
                            value.append(list_tmp.i)
                    else:
                        raise NameError('ERROR: UnSupport Recursive list data type(%s) in list ' % (str(value_data.cache_list.type)))
                else:
                    raise NameError('ERROR: Unknown data type (%s) in message valueType' % (str(value_data.type)))
                target_attr = CreateJson(id=name,
                                                                 type=type_str,
                                                                 value=str(value))
                node_attrs.append(target_attr())
            # Quantitative information
            name = 'bit_mode'
            type_str = 'type'
            if node_proto.bit_type == FLOAT:
                value = 'FLOAT32'
            elif node_proto.bit_type == INT8:
                value = 'INT8'
            elif node_proto.bit_type == STR:
                value = 'UNKNOWN'
            else:
                raise NameError('ERROR: Unknown data type (%d) in message valueType' \
                 % (node_proto.bit_type))
            target_attr = CreateJson(id=name,
                                                             type=type_str,
                                                             value=str(value))
            node_attrs.append(target_attr())
            node_map = CreateJson(key_name=key_id,
                                                      key_attrs=node_attrs)
            attrs.append(node_map())
        return attrs

    def create_elements(self):
        """
        create elements of graph for cytoscape
        """
        nodes = self.create_nodes()
        edges = self.create_edges()

        elements = CreateJson(nodes=nodes, edges=edges)
        return elements()

    def create_mem_info(self):
        """
        create memory optimization information
        """
        temp_mem_used = self.graph_proto.summary.temp_mem_used
        system_mem_used = self.graph_proto.summary.system_mem_used
        model_mem_used = self.graph_proto.summary.model_mem_used
        sum_mem = self.graph_proto.summary.temp_mem_used + \
				self.graph_proto.summary.system_mem_used + \
				self.graph_proto.summary.model_mem_used
        mem_info =  CreateJson(temp_mem=temp_mem_used,
							   system_mem=system_mem_used,
							   model_mem=model_mem_used,
							   total_mem=sum_mem)
        return mem_info()

    def __call__(self):
        return self.create_elements(), self.create_attr(), self.create_mem_info()


# for test in range(10):
T = int(input())
pattern = input()
text = list(input())
M = len(pattern)
N = len(text)
cnt = 0

# for i in range(N-1):
#     for j in range(M):
#         if text[i+j] == pattern[j]:
#             cnt +=1
# print(cnt)

i = 0
j = 0
cnt = 0
while j < M and i < N:
    if text[i] != pattern[j]:
        i = i-j
        j = -1
    # elif text[i] == pattern[j]:
    #     cnt +=1
    i = i+1
    j = j+1
if j == M:
    print(i - M)
else:
    print(0)


import discord
import random
import Data
from discord.ext import commands, tasks

intents = discord.Intents.default()
intents.message_content = True

client = commands.Bot(command_prefix='!', intents=intents)

bad_words = ['avazi', 'khafe sho', 'bi tarbiat', 'bi shoor', 'oskol']
reply_choice = ['khodeti!', "bi tarbiat!", 'chendesh', 'dige tekrar nashe']

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')
    set_activity.start()

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    for word in bad_words:
        if word in message.content:
            await message.delete()
            await message.channel.send(f"{message.author.mention}" + " " + random.choice(reply_choice))

    await client.process_commands(message)

@client.command()
async def clear(ctx, arg):
    await ctx.channel.purge(limit=(int(arg) + 1))

@tasks.loop(seconds=10)
async def set_activity():
    guild = client.get_guild(1021834785557073980)
    mc = guild.member_count
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="" + str(mc)),
                                 status=discord.Status.do_not_disturb)

client.run(Data.token)


#!/usr/bin/env python

# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Xinlei Chen, based on code from Ross Girshick
# --------------------------------------------------------

"""
Demo script showing detections in sample images.

See README.md for installation instructions before running.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os

import cv2
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from lib.config import config as cfg
from lib.utils.nms_wrapper import nms
from lib.utils.test import im_detect
#from nets.resnet_v1 import resnetv1
from lib.nets.vgg16 import vgg16
from lib.utils.timer import Timer

CLASSES = ('__background__',
           'chinese')
#40000
NETS = {'vgg16': ('vgg16_faster_rcnn_iter_25000.ckpt',), 'res101': ('res101_faster_rcnn_iter_110000.ckpt',)}
DATASETS = {'pascal_voc': ('GeetCode_2019_train',)}

def getimgth(image):
    height = image.shape[0]
    width = image.shape[1]
    # print(image.shape)
    img = image[int(height / 4):int(height * 3 / 4), int(width / 4):int(width * 3 / 4)]
    ret, th = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

    if  ret < 127:
        if ret - 20 > 0:
            ret = ret - 20
    else:
        if ret + 20 < 255:
            ret = ret + 20

    return ret

def getbboximage(bbox,im,image_name,index,output_path):

     x1 = int(bbox[0]+0.5)
     y1 = int(bbox[1]+0.5)
     x2 = int(bbox[2]+0.5)
     y2 = int(bbox[3]+0.5)

     region = im[y1:y2,x1:x2]
     region =  cv2.cvtColor(region,cv2.COLOR_BGR2GRAY)
     ret =  getimgth(region)
     ret, region = cv2.threshold(region, ret, 255, cv2.THRESH_BINARY)

     out_file = output_path + image_name.split('.')[0] + '_' + str(index) + '.jpg'
     cv2.imwrite(out_file, region)
     return out_file,bbox

def vis_detections(im, class_name, dets,image_name,output_path, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return
    #    # python-opencv 中读取图片默认保存为[w,h,channel](w,h顺序不确定)
    # 其中 channel：BGR 存储，而画图时，需要按RGB格式，因此此处作转换。
    im = im[:, :, (2, 1, 0)]
    chinese_bbox= []

    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]
        chinese_bbox.append(getbboximage(bbox,im,image_name,i,output_path))
    return chinese_bbox

def boxdetect(sess, net,im_file,output_path):
    """Detect object classes in an image using pre-computed object proposals."""

    # Load the image
    im_file = im_file.replace('\\', '/')
    im = cv2.imread(im_file)
    image_name = im_file.split(r'/')[-1]
    # Detect all object classes and regress object bounds
    timer = Timer()
    timer.tic()
    scores, boxes = im_detect(sess, net, im)
    timer.toc()
    print('Detection took {:.3f}s for {:d} object proposals'.format(timer.total_time, boxes.shape[0]))

    # Visualize detections for each class
    CONF_THRESH = 0.1
    NMS_THRESH = 0.1
    geetcode_bbox=[]
    for cls_ind, cls in enumerate(CLASSES[1:]):
        cls_ind += 1  # because we skipped background
        cls_boxes = boxes[:, 4 * cls_ind:4 * (cls_ind + 1)]
        cls_scores = scores[:, cls_ind]
        dets = np.hstack((cls_boxes,
                          cls_scores[:, np.newaxis])).astype(np.float32)
        keep = nms(dets, NMS_THRESH)
        dets = dets[keep, :]
        bbox = vis_detections(im, cls, dets,image_name,output_path, thresh=CONF_THRESH)
        geetcode_bbox.append(bbox)
    return geetcode_bbox

def parse_args():
    """Parse input arguments."""
    parser = argparse.ArgumentParser(description='Tensorflow Faster R-CNN')
    parser.add_argument('--net', dest='detect_net', help='Network to use [vgg16 res101]',
                        choices=NETS.keys(), default='vgg16')
    parser.add_argument('--dataset', dest='dataset', help='Trained dataset [GeetCode_2019_train]',
                        choices=DATASETS.keys(), default='pascal_voc')
    args = parser.parse_args()

    return args

def getimgnamepath(img_path):
    img_name=[]
    for root, sub_folder, name_list in os.walk(img_path):
        img_name += [os.path.join(root, name) for name in name_list]
    return img_name

def load_faster_rcnn_network():
    args = parse_args()
    detect_net = args.detect_net
    dataset = args.dataset
    tfmodel = os.path.join('output', detect_net, DATASETS[dataset][0], 'default', NETS[detect_net][0])
    print(tfmodel)
    if not os.path.isfile(tfmodel + '.meta'):
        print(tfmodel)
        raise IOError(('{:s} not found.\n').format(tfmodel + '.meta'))

    fasterrcnn_graph = tf.Graph()
    with fasterrcnn_graph.as_default():
        # set config
        tfconfig = tf.ConfigProto(allow_soft_placement=True)
        tfconfig.gpu_options.allow_growth = True
        # init session
        sess = tf.Session(graph=fasterrcnn_graph,config=tfconfig)
        # load network
        if detect_net == 'vgg16':
            net = vgg16(batch_size=1)
        # elif demonet == 'res101':
        # net = resnetv1(batch_size=1, num_layers=101)
        else:
            raise NotImplementedError
        net.create_architecture(sess, "TEST", len(CLASSES),
                                tag='default', anchor_scales=[8, 16, 32])
        saver = tf.train.Saver()
        saver.restore(sess, tfmodel)
        print('Loaded network {:s}'.format(tfmodel))

    return sess,net

def run_geetcode_boxdetect(im,output_path, sess, net):
    print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    print('detect_net for data/demo/{}'.format(im))
    geetcode_bbox = boxdetect(sess, net,im,output_path)

    # plt.show()
    return geetcode_bbox

if __name__ == '__main__':
    args = parse_args()


import unittest
import numpy

import lsst.utils.tests
import lsst.shapelet
import lsst.afw.geom
import lsst.geom
import lsst.afw.image
import lsst.log
import lsst.utils.logging
import lsst.meas.modelfit
import lsst.meas.base

#   Set trace to 0-5 to view debug messages.  Level 5 enables all traces.
lsst.utils.logging.trace_set_at("lsst.meas.modelfit.optimizer.Optimizer", -1)
lsst.utils.logging.trace_set_at("lsst.meas.modelfit.optimizer.solveTrustRegion", -1)

def makeMultiShapeletCircularGaussian(sigma):
    s = lsst.shapelet.ShapeletFunction(0, lsst.shapelet.HERMITE, sigma)
    s.getCoefficients()[0] = 1.0 / lsst.shapelet.ShapeletFunction.FLUX_FACTOR
    m = lsst.shapelet.MultiShapeletFunction()
    m.addComponent(s)
    return m

def computePsfFlux(centroid, exposure):
    schema = lsst.afw.table.SourceTable.makeMinimalSchema()
    pointKey = lsst.afw.table.Point2DKey.addFields(schema, "centroid", "known input centroid", "pixel")
    schema.getAliasMap().set("slot_Centroid", "centroid")
    algorithm = lsst.meas.base.PsfFluxAlgorithm(lsst.meas.base.PsfFluxControl(), "base_PsfFlux", schema)
    table = lsst.afw.table.SourceTable.make(schema)
    record = table.makeRecord()
    record.set(pointKey, centroid)
    algorithm.measure(record, exposure)
    return record.get("base_PsfFlux_instFlux"), record.get("base_PsfFlux_instFluxErr")

class CModelTestCase(lsst.utils.tests.TestCase):

    def setUp(self):
        # Setup test data: a single point source, initially with no noise.
        numpy.random.seed(500)
        crval = lsst.geom.SpherePoint(45.0, 45.0, lsst.geom.degrees)
        crpix = lsst.geom.Point2D(0.0, 0.0)
        scale = 0.2 * lsst.geom.arcseconds
        cdMatrix = lsst.afw.geom.makeCdMatrix(scale=scale, flipX=True)
        dataWcs = lsst.afw.geom.makeSkyWcs(crpix=crpix, crval=crval, cdMatrix=cdMatrix)
        photoCalib = lsst.afw.image.PhotoCalib(4.0)
        self.xyPosition = lsst.geom.Point2D(1.1, -0.8)
        bbox = lsst.geom.Box2I(lsst.geom.Point2I(-100, -100), lsst.geom.Point2I(100, 100))
        self.exposure = lsst.afw.image.ExposureF(bbox)
        self.exposure.setWcs(dataWcs)
        self.exposure.setPhotoCalib(photoCalib)
        self.trueFlux = 65.0
        self.psfSigma = 2.0
        psf = lsst.afw.detection.GaussianPsf(25, 25, self.psfSigma)
        self.exposure.setPsf(psf)
        psfImage = psf.computeImage(self.xyPosition)
        psfImage.getArray()[:, :] *= self.trueFlux
        psfBBox = psfImage.getBBox(lsst.afw.image.PARENT)
        subImage = lsst.afw.image.ImageF(self.exposure.getMaskedImage().getImage(), psfBBox,
                                         lsst.afw.image.PARENT)
        subImage.getArray()[:, :] = psfImage.getArray()

    def tearDown(self):
        del self.xyPosition
        del self.exposure
        del self.trueFlux
        del self.psfSigma

    def testNoNoise(self):
        """Test that CModelAlgorithm.apply() works when applied to a postage-stamp
        containing only a point source with no noise.

        We still have to pretend there is noise (i.e. have nonzero values in
        the variance plane) to allow it to compute a likelihood, though.
        """
        ctrl = lsst.meas.modelfit.CModelControl()
        ctrl.initial.usePixelWeights = False
        algorithm = lsst.meas.modelfit.CModelAlgorithm(ctrl)
        var = 1E-16
        self.exposure.getMaskedImage().getVariance().getArray()[:, :] = var
        psfImage = self.exposure.getPsf().computeKernelImage(self.xyPosition).getArray()
        expectedFluxErr = var**0.5 * (psfImage**2).sum()**(-0.5)
        pos = self.exposure.getPsf().getAveragePosition()
        result = algorithm.apply(
            self.exposure, makeMultiShapeletCircularGaussian(self.psfSigma),
            self.xyPosition, self.exposure.getPsf().computeShape(pos)
        )
        self.assertFalse(result.initial.flags[result.FAILED])
        self.assertFloatsAlmostEqual(result.initial.instFlux, self.trueFlux, rtol=0.01)
        self.assertFloatsAlmostEqual(result.initial.instFluxErr, expectedFluxErr, rtol=0.01)
        self.assertLess(result.initial.ellipse.getDeterminantRadius(), 0.2)
        self.assertFalse(result.exp.flags[result.FAILED])
        self.assertFloatsAlmostEqual(result.exp.instFlux, self.trueFlux, rtol=0.01)
        self.assertFloatsAlmostEqual(result.exp.instFluxErr, expectedFluxErr, rtol=0.01)
        self.assertLess(result.exp.ellipse.getDeterminantRadius(), 0.2)
        self.assertFalse(result.dev.flags[result.FAILED])
        self.assertFloatsAlmostEqual(result.dev.instFlux, self.trueFlux, rtol=0.01)
        self.assertFloatsAlmostEqual(result.dev.instFluxErr, expectedFluxErr, rtol=0.01)
        self.assertLess(result.dev.ellipse.getDeterminantRadius(), 0.2)
        self.assertFalse(result.flags[result.FAILED])
        self.assertFloatsAlmostEqual(result.instFlux, self.trueFlux, rtol=0.01)

    def testVsPsfFlux(self):
        """Test that CModel produces results comparable to PsfFlux when run
        on point sources.
        """
        noiseSigma = 1.0
        for fluxFactor in (1.0, 10.0, 100.0):
            exposure = self.exposure.Factory(self.exposure, True)
            exposure.getMaskedImage().getImage().getArray()[:] *= fluxFactor
            exposure.getMaskedImage().getVariance().getArray()[:] = noiseSigma**2
            exposure.getMaskedImage().getImage().getArray()[:] += \
                noiseSigma*numpy.random.randn(exposure.getHeight(), exposure.getWidth())
            ctrl = lsst.meas.modelfit.CModelControl()
            algorithm = lsst.meas.modelfit.CModelAlgorithm(ctrl)
            pos = self.exposure.getPsf().getAveragePosition()
            cmodel = algorithm.apply(
                exposure, makeMultiShapeletCircularGaussian(self.psfSigma),
                self.xyPosition, self.exposure.getPsf().computeShape(pos)
            )
            psfFlux, psfFluxErr = computePsfFlux(self.xyPosition, exposure)
            self.assertFloatsAlmostEqual(psfFlux, cmodel.instFlux, rtol=0.1/fluxFactor**0.5)
            self.assertFloatsAlmostEqual(psfFluxErr, cmodel.instFluxErr, rtol=0.1/fluxFactor**0.5)

class TestMemory(lsst.utils.tests.MemoryTestCase):
    pass

def setup_module(module):
    lsst.utils.tests.init()

if __name__ == "__main__":
    lsst.utils.tests.init()
    unittest.main()


# Step 2 - Climate app

# 1. import libraries
from flask import Flask, jsonify

import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func

import numpy as np

import datetime as dt

# 2. Setup Database
engine = create_engine("sqlite:///hawaii.sqlite")
Base = automap_base()
Base.prepare(engine, reflect=True)
Measurement = Base.classes.measurement
Station = Base.classes.station
session = Session(engine)

# 3. Create an app, being sure to pass __name__
app = Flask(__name__)

# 4. Setup Flask Routes
@app.route("/")
def homepage():
    """List of all returnable API routes."""
    return (
        f"
Climate app

"
        f"Available Routes:
"
        """Precipitations in Hawaii for the last year: /api/v1.0/precipitation
"""
        """Names of stations in Hawaii for weather metrology: /api/v1.0/stations
"""
        """Temperature observations in Hawaii for the previous year: /api/v1.0/tobs
"""
        """Temperature statistics in Hawaii from a given date: /api/v1.0/start
"""
        """Temperature statistics within a start-end range of dates: /api/v1.0/start/end
"""
)

# 5. Flask Route for precipitations
@app.route("/api/v1.0/precipitation")
def precipitation():

    # Get date with last measurement data
    measure_dates = session.query(Measurement).order_by(Measurement.date.desc()).limit(1)
    for date in measure_dates:
        last_measure_date = date.date

    # Calculate the date 1 year ago from today
    last_measure_date = dt.datetime.strptime(last_measure_date, "%Y-%m-%d") # Date convertion
    one_year_ago_date = last_measure_date - dt.timedelta(days=365)
    start = one_year_ago_date
    end = last_measure_date

    # Query the dates and the precipitations from the last year
    prcp_data = session.query(Measurement.date, Measurement.prcp).\
            filter(Measurement.date >= one_year_ago_date).\
            all()

    # Create a list of dictionaries
    dicts_prcp = []
    for data in prcp_data:
        dict_prcp = {}
        dict_prcp["date"] = data.date
        dict_prcp["prcp"] = data.prcp
        dicts_prcp.append(dict_prcp)

    # Return a JSON of the dates and precipitations
    return jsonify(dicts_prcp)

# 6. Flask Route for stations
@app.route("/api/v1.0/stations")
def stations():

   # Query for the stations from the dataset
    station_data = session.query(Station.name).all()

    # Convert list of tuples into a normal list
    stations_list = list(np.ravel(station_data))

    # Return a JSON of the stations
    return jsonify(stations_list)

# 7. Flask Route for temperature observations
@app.route("/api/v1.0/tobs")
def tobs():

    # Query for the temperature observations for the previous year
    tobs_data = session.query(Measurement.tobs).all()

    # Convert list of tuples into a normal list
    tobs_list = list(np.ravel(tobs_data))

    # Return a JSON of the temperature observations
    return jsonify(tobs_data)

# 8. Flask Route for temperature statistics from a given start
@app.route("/api/v1.0/<start>")
def temps_start(start):

    # Query for calculating temperature statistics for a given start
    temps_start = session.query(func.min(Measurement.tobs),\
                    func.avg(Measurement.tobs),\
                    func.max(Measurement.tobs)).\
                    filter(Measurement.date >= start).\
                    all()

    # Convert list of tuples into normal list
    start_list = list(np.ravel(temps_start))

    # Create a dictionary using TMIN, TAVG, and TMAX as keys and temperature calculations as the respecive values.
    for temp in start_list:
        start_dict = {}
        start_dict["TMIN"] = start_list[0]
        start_dict["TAVG"] = start_list[1]
        start_dict["TMAX"] = start_list[2]

    # Return a JSON of the temperature statistics
    return jsonify(start_dict)

# 9. Flask Route for temperature statistics from a start-end range
@app.route("/api/v1.0/<start>/<end>")
def temps_range(start, end):

    # Query for calculating temperature statistics within a start-end range
    temps_start_end = session.query(func.min(Measurement.tobs), \
                         func.avg(Measurement.tobs), \
                         func.max(Measurement.tobs)).\
                            filter(Measurement.date >= start).\
                            filter(Measurement.date <= end).\
                            all()

    # Convert list of tuples into normal list
    start_end_list = list(np.ravel(temps_start_end))

    # Create a dictionary using TMIN, TAVG, and TMAX as keys and temperature calculations as the respecive values.
    for temp in start_end_list:
        start_end_dict = {}
        start_end_dict["TMIN"] = start_end_list[0]
        start_end_dict["TAVG"] = start_end_list[1]
        start_end_dict["TMAX"] = start_end_list[2]

    # Return a JSON of the temperature statistics
    return jsonify(start_end_dict)

# 10. Run app
if __name__ == "__main__":
    app.run(debug=True)