# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: e:\jenkins\workspace\client_SERENITY\branches\release\SERENITY\eve\devtools\script\menu_charge.py
import operator
import evetypes
import uthread
import blue
import uix
import carbonui.const as uiconst
import util
from service import *

class ChargeService(Service):
    """Insider Charge"""
    __module__ = __name__
    __exportedcalls__ = {}
    __guid__ = 'svc.charge'
    __servicename__ = 'charge'
    __displayname__ = 'Insider Charges and Drone Service'
    __dependencies__ = ['invCache']

    def NA(self, name):
        return '<color=0x60ffffff>' + name + ' <color=0xffff8080>[N/A]'

    def Name(self, rec):
        if rec.published:
            return evetypes.GetName(rec.typeID)
        else:
            return self.NA(evetypes.GetName(rec.typeID))

    def FormattedName(self, name, published):
        if published:
            return name
        else:
            return self.NA(name)

    def FitDrone(self, drone):
        if uicore.uilib.Key(uiconst.VK_SHIFT):
            result = uix.QtyPopup(maxvalue=100, minvalue=1, caption=drone.name, label=u'Quantity', hint='')
            if result:
                qty = result['qty']
            else:
                return
        else:
            qty = 1
        sm.RemoteSvc('slash').SlashCmd('/fit me %d %d' % (drone.typeID, qty))

    def Fit(self, charges):
        dogmaLocation = sm.GetService('clientDogmaIM').GetDogmaLocation()
        chargeByFlag = {}
        shipID = util.GetActiveShip()
        shipInv = self.invCache.GetInventoryFromId(shipID)
        for dogmaItem in dogmaLocation.GetDogmaItem(shipID).GetFittedItems().itervalues():
            desiredSize = dogmaLocation.dogmaStaticMgr.GetTypeAttribute(dogmaItem.typeID, const.attributeChargeSize)
            capacity = dogmaLocation.GetAttributeValue(dogmaItem.itemID, const.attributeCapacity)
            for chargeGroupAttributeID in dogmaLocation.dogmaStaticMgr.chargeGroupAttributes:
                if not dogmaLocation.dogmaStaticMgr.TypeHasAttribute(dogmaItem.typeID, chargeGroupAttributeID):
                    continue
                chargeGroup = dogmaLocation.GetAttributeValue(dogmaItem.itemID, chargeGroupAttributeID)
                for a in charges:
                    if a.groupID != chargeGroup:
                        continue
                    if a.volume > capacity:
                        continue
                    if desiredSize is not None and getattr(a, 'chargeSize', -1) != desiredSize:
                        continue
                    chargeByFlag[dogmaItem.flagID] = [a, int(capacity / a.volume)]
                    break
                else:
                    continue

                break

        tasks = {flagID:(
         None,
         '/fit me %d %d flag=%d' % (typeObj.typeID,
          qtyNeeded, flagID)) for flagID, (typeObj, qtyNeeded) in chargeByFlag.iteritems()}
        for dogmaItem in dogmaLocation.GetDogmaItem(shipID).GetFittedItems().itervalues():
            flagID = dogmaItem.flagID
            if flagID not in chargeByFlag:
                continue
            if dogmaItem.categoryID != const.categoryCharge:
                continue
            a, quantityNeeded = chargeByFlag[flagID]
            if isinstance(dogmaItem.itemID, tuple):
                if dogmaItem.typeID != a.typeID:
                    tasks[flagID] = [flagID]
                else:
                    quantityNeeded -= dogmaLocation.GetAttributeValue(dogmaItem.itemID, const.attributeQuantity)
                    tasks[flagID] = [None]
            else:
                tasks[flagID] = [flagID]
            if quantityNeeded > 0:
                tasks[flagID].append('/fit me %d %d flag=%d' % (a.typeID, quantityNeeded, flagID))
            else:
                tasks[flagID].append(None)

        def _change(removeFlag, addCmd):
            if removeFlag:
                shipInv.ReplaceCharges(removeFlag, None, forceRemove=True)
                count = 100
                while dogmaLocation.GetSubLocation(util.GetActiveShip(), removeFlag):
                    blue.pyos.synchro.SleepSim(50)
                    count -= 1
                    if not count:
                        raise RuntimeError('Dogma is sleeping on the job, or something worse happened!')

            if addCmd:
                sm.RemoteSvc('slash').SlashCmd(addCmd)
            return

        uthread.parallel([ (_change, (flag, cmd)) for flag, cmd in tasks.itervalues() ])
        return

    def Entry(self, a):
        return (
         self.Name(a),
         self.Fit, ([a],))

    def DroneMenu(self, *args, **kw):
        return self._Menu(drones=True)

    def ChargeMenu(self, *args, **kw):
        return self._Menu()

    def _Menu(self, drones=False):
        dgm = sm.GetService('godma').GetStateManager()
        chargesByChargeGroup = {}
        chargesByLauncherGroup = {}
        missileLauncherGroups = {}
        damageTypes = {'1000': ('EM', 'ui_22_32_12', 0.125),'0100': ('Explosive', 'ui_22_32_11', 0.125),'0010': ('Kinetic', 'ui_22_32_9', 0.125),'0001': ('Thermal', 'ui_22_32_10', 0.125),-1: ('Other', 'ui_7_64_15')}
        for groupID in evetypes.GetGroupIDsByCategories([const.categoryCharge, const.categoryDrone]):
            chargesByChargeGroup[groupID] = []

        for typeID in evetypes.GetTypeIDsByGroups(chargesByChargeGroup.keys()):
            chargesByChargeGroup[evetypes.GetGroupID(typeID)].append(typeID)

        for items in chargesByChargeGroup.itervalues():
            if items:
                typeID = items[0]
                a = dgm.GetType(typeID)
                if a.launcherGroup > 1:
                    chargesByLauncherGroup[a.launcherGroup] = items
                    if a.launcherGroup == const.groupMissileLauncherStandard:
                        chargesByLauncherGroup[const.groupMissileLauncherAssault] = items
                        missileLauncherGroups[const.groupMissileLauncherAssault] = True
                    if const.typeMissileLauncherOperation in (getattr(a, 'requiredSkill1', False), getattr(a, 'requiredSkill2', False)):
                        missileLauncherGroups[a.launcherGroup] = True

        def TurretSubMenu(baseName, charges):
            m = []
            ammo = {}
            damage = {}
            for a in charges:
                ammoType = ' '.join(self.Name(a).replace(baseName + ' ', '').split(' ')[:-1]).strip() or 'Standard'
                if ammoType in ammo:
                    ammo[ammoType].append(a)
                else:
                    ammo[ammoType] = [a]
                    damage[ammoType] = (a.emDamage + a.explosiveDamage + a.kineticDamage + a.thermalDamage) / (1 << a.chargeSize - 1)

            ammo = [ (damage[key], key, charges) for key, charges in ammo.iteritems() ]
            ammo.sort()
            m.append(('<color=0xff708090>Base', None))
            m.append(None)
            lastDamage = baseDamage = ammo[0][0]
            for damage, ammoType, charges in ammo:
                if damage != lastDamage:
                    m.append(None)
                    m.append(('<color=0xff708090>Base +%d%%' % int((damage / baseDamage - 1) * 100 + 0.5), None))
                    m.append(None)
                    lastDamage = damage
                m.append((ammoType, self.Fit, (charges,)))

            return m

        def TurretMenu(chargeGroups):
            m = []
            chargeGroups = [ (evetypes.GetGroupNameByGroup(x), x) for x in chargeGroups ]
            chargeGroups.sort()
            for name, groupID in chargeGroups:
                filtered = {}
                rangeMod = {}
                for typeID in chargesByChargeGroup[groupID]:
                    a = dgm.GetType(typeID)
                    if a.iconID in filtered:
                        filtered[a.iconID].append(a)
                    else:
                        filtered[a.iconID] = [a]
                        rangeMod[a.iconID] = getattr(a, 'weaponRangeMultiplier', 0.0)

                grouped = {}
                inconsistent = []
                while filtered:
                    iconID, items = filtered.popitem()
                    base = items[0].name.split(' ')
                    base.pop()
                    inconsistent = []
                    for a in items[:]:
                        words = a.name.split(' ')
                        newbase = base[:]
                        for word in base:
                            if word not in words:
                                newbase.remove(word)

                        if newbase:
                            base = newbase
                        else:
                            inconsistent.append(a)
                            items.remove(a)

                    baseName = ' '.join(base)
                    if baseName in grouped:
                        g = grouped[baseName]
                    else:
                        g = grouped[baseName] = []
                    g.extend(items)

                processed = []
                while grouped:
                    baseName, items = grouped.popitem()
                    for a in inconsistent:
                        if baseName in a.name:
                            items.append(a)

                    items.sort()
                    for a in items:
                        if a.chargeSize == 2:
                            break
                    else:
                        for a in items:
                            if a.chargeSize == 1:
                                break
                        else:
                            a = items[0]

                        if not a.published:
                            baseName = self.NA(baseName)
                        if len(items) <= 4:
                            processed.append((rangeMod[a.iconID], (baseName, self.Fit, (items,))))
                        else:
                            processed.append((rangeMod[a.iconID], (baseName, ('isDynamic', TurretSubMenu, (baseName, items)))))

                processed.sort()
                processed.reverse()
                if len(processed) < 5:
                    m.append(('<color=0xff708090>%s' % evetypes.GetGroupNameByGroup(groupID), None))
                    m.append(None)
                    m += zip(*processed)[1]
                else:
                    m.append(('<color=0xff708090>Long Range', None))
                    m.append(None)
                    m += zip(*processed)[1]
                    m.append(None)
                    m.append(('<color=0xff708090>High Damage', None))
                m.append(None)

            return m

        def MissileSubMenu(charges):
            m = []
            charges.sort()
            missiles = {}
            for damage, a in charges:
                if a.launcherGroup in missiles:
                    missiles[a.launcherGroup].append(a)
                else:
                    missiles[a.launcherGroup] = [a]

            for launcherGroup, items in missiles.iteritems():
                fitted = []
                label = '<color=0xff708090>%s' % evetypes.GetGroupNameByGroup(launcherGroup)
                if launcherGroup == const.groupMissileLauncherStandard:
                    for row in self.invCache.GetInventoryFromId(util.GetActiveShip()).ListHardwareModules():
                        if row.groupID in (const.groupMissileLauncherStandard, const.groupMissileLauncherAssault):
                            fitted.append(row.groupID)

                    if len(fitted) > 1:
                        label = '<color=0xff708090>%s / %s' % (evetypes.GetGroupNameByGroup(const.groupMissileLauncherStandard), evetypes.GetGroupNameByGroup(const.groupMissileLauncherAssault))
                    else:
                        label = '<color=0xff708090>%s' % evetypes.GetGroupNameByGroup(fitted[0])
                m.append((label, None))
                m.append(None)
                for a in items:
                    m.append(self.Entry(a))

                m.append(None)

            return m

        def MissileMenu(chargeGroups):
            missiles = {}
            for groupID in chargeGroups:
                for typeID in chargesByChargeGroup[groupID]:
                    a = dgm.GetType(typeID)
                    if a.launcherGroup == const.groupMissileLauncher:
                        damageSpec = '0000'
                    else:
                        damageSpec = (a.emDamage, a.explosiveDamage, a.kineticDamage, a.thermalDamage)
                    label = damageTypes.get(''.join(map(lambda x: str(int(not not x)), damageSpec)), None)
                    if label in missiles:
                        missiles[label].append((reduce(operator.__add__, damageSpec), a))
                    else:
                        missiles[label] = [(reduce(operator.__add__, damageSpec), a)]

            missiles = missiles.items()
            missiles.sort()
            multi = False
            for label, items in missiles:
                if label and len(items) > 1:
                    multi = True

            m = []
            m.append(None)
            entry = None
            for label, items in missiles:
                if label is None:
                    if len(items) == 1:
                        entry = self.Entry(items[0][1])
                    else:
                        entry = (damageTypes[-1][0], ('isDynamic', MissileSubMenu, (items,)))
                elif multi:
                    m.append((label[0], ('isDynamic', MissileSubMenu, (items,))))
                else:
                    m.append(self.Entry(items[0][1]))

            if entry:
                m.insert(0, None)
                m.insert(0, entry)
            return m

        def NotSoGenericMenu(groupID, items):
            m = []
            if groupID == const.groupScannerProbe:
                sub = {True: [],False: [],2: []}
                for a in items:
                    if a.marketGroupID:
                        x = a.name.endswith('Probe I')
                        sub[x].append(self.Entry(a))
                    else:
                        sub[2].append(self.Entry(a))

                m = sub[True]
                m.append(None)
                m.append(('<color=0xff708090>%s' % evetypes.GetGroupNameByGroup(groupID), None))
                m.append(None)
                if sub[False]:
                    templist = sub[False]
                    grav = []
                    ladar = []
                    mag = []
                    multi = []
                    radar = []
                    templists = [grav, ladar, mag, multi, radar]
                    for val in templist:
                        try:
                            if val[0][:5] == 'Gravi':
                                grav.append(val)
                            elif val[0][:5] == 'Ladar':
                                ladar.append(val)
                            elif val[0][:5] == 'Magne':
                                mag.append(val)
                            elif val[0][:5] == 'Multi':
                                multi.append(val)
                            elif val[0][:5] == 'Radar':
                                radar.append(val)
                        except:
                            None

                    for list in templists:
                        list.sort()

                    if grav:
                        templist = grav
                    if ladar:
                        templist.append(None)
                        templist += ladar
                    if mag:
                        templist.append(None)
                        templist += mag
                    if multi:
                        templist.append(None)
                        templist += multi
                    if radar:
                        templist.append(None)
                        templist += radar
                    m.append(('Lith Probes', templist))
                m.append(('Unknown / Test', sub[2]))
            else:
                m = [ self.Entry(a) for a in items ]
            return m

        def GenericMenu(chargeGroups, maxVolumeByCG):
            processed = []
            processedLength = 0
            for groupID in chargeGroups:
                maxVolume = maxVolumeByCG[groupID]
                items = [ a for a in map(dgm.GetType, chargesByChargeGroup[groupID]) if a.volume <= maxVolume ]
                items = NotSoGenericMenu(groupID, items)
                processed.append((groupID, items))
                processedLength += len(items)

            m = []
            for groupID, items in processed:
                m.append(('<color=0xff708090>%s' % evetypes.GetGroupNameByGroup(groupID), None))
                m.append(None)
                m.extend(items)
                m.append(None)

            return m

        def GetDroneDmgType(a):
            damageSpec = (
             a.emDamage, a.explosiveDamage,
             a.kineticDamage, a.thermalDamage)
            return damageTypes.get(''.join(map(lambda x: str(int(not not x)), damageSpec)), None)

        def DroneSubMenu(groupID):
            m = []
            if len(chargesByChargeGroup[groupID]) > 16:
                grouped = {}
                for typeID in chargesByChargeGroup[groupID]:
                    a = dgm.GetType(typeID)
                    typ = GetDroneDmgType(a)
                    if typ in grouped:
                        grouped[typ].append(a)
                    else:
                        grouped[typ] = [a]

                for label, items in grouped.items():
                    d = {}
                    for a in items:
                        if a.marketGroupID in d:
                            d[a.marketGroupID].append(a)
                        else:
                            d[a.marketGroupID] = [a]

                    grouped[label] = mm = []
                    if not label:
                        label = damageTypes[-1]
                    for name, id in [('Light Scout Drones', 837), ('Medium Scout Drones', 838), ('Heavy Attack Drones', 839), ('Sentry Drones', 911)]:
                        if id in d:
                            mm.append(None)
                            for a in d[id]:
                                mm.append((self.Name(a), self.FitDrone, (a,)))

                            del d[id]

                    if d:
                        mm.append(None)
                        for id, items in d.iteritems():
                            for a in items:
                                mm.append((self.Name(a), self.FitDrone, (a,)))

                if None in grouped:
                    weird = grouped[None]
                    del grouped[None]
                else:
                    weird = None
                for label, items in grouped.items():
                    m.append((label[0], items))

                m.sort()
                m.append(None)
                m.sort()
                if weird:
                    m.append(None)
                    m.append((damageTypes[-1][0], weird))
            else:
                for typeID in chargesByChargeGroup[groupID]:
                    a = dgm.GetType(typeID)
                    m.append((self.Name(a), self.FitDrone, (a,)))
                    m.sort()

            ew300 = []
            ew600 = []
            ew900 = []
            light = []
            medium = []
            heavy = []
            lists = [ew300, ew600, ew900, light, medium, heavy]
            for entry in m:
                try:
                    if entry[0][-3:] == '300':
                        ew300.append(entry)
                    elif entry[0][-3:] == '600':
                        ew600.append(entry)
                    elif entry[0][-3:] == '900':
                        if entry[0][-6:] != 'SW-900':
                            ew900.append(entry)
                    elif entry[0][:5] == 'Light':
                        light.append(entry)
                    elif entry[0][:6] == 'Medium':
                        medium.append(entry)
                    elif entry[0][:5] == 'Heavy':
                        heavy.append(entry)
                except:
                    None

            for val in lists:
                val.sort()

            if ew300:
                m = ew300
            if ew600:
                m.append(None)
                m += ew600
            if ew900:
                m.append(None)
                m += ew900
            if light:
                m = light
            if medium:
                m.append(None)
                m += medium
            if heavy:
                m.append(None)
                m += heavy
            return m

        def DroneMenu():
            m = []
            for groupID in chargesByChargeGroup:
                if evetypes.GetCategoryIDByGroup(groupID) == const.categoryDrone:
                    m.append((self.FormattedName(evetypes.GetGroupNameByGroup(groupID), evetypes.IsGroupPublishedByGroup(groupID)), ('isDynamic', DroneSubMenu, (groupID,))))

            m.sort()
            return m

        def GetMenu():
            m = []
            missileCG = {}
            turretCGbyLG = {const.groupEnergyWeapon: {},const.groupHybridWeapon: {},const.groupProjectileWeapon: {}}
            otherCGbyLG = {}
            maxVolumeByCG = {}
            iconIDs = {}
            for row in self.invCache.GetInventoryFromId(util.GetActiveShip()).ListHardwareModules():
                groupID = row.groupID
                if groupID in chargesByLauncherGroup:
                    a = dgm.GetType(row.typeID)
                    iconIDs[groupID] = a.iconID
                    chargeGroups = []
                    for x in range(4):
                        chargeGroup = getattr(a, 'chargeGroup%d' % (x + 1), False)
                        if chargeGroup:
                            chargeGroups.append(chargeGroup)

                    if groupID in missileLauncherGroups:
                        iconIDs[const.groupMissileLauncher] = a.iconID
                        for cg in chargeGroups:
                            missileCG[cg] = True

                    elif groupID in turretCGbyLG:
                        for cg in chargeGroups:
                            turretCGbyLG[groupID][cg] = True

                    else:
                        if groupID not in otherCGbyLG:
                            otherCGbyLG[groupID] = {}
                        for cg in chargeGroups:
                            otherCGbyLG[groupID][cg] = True
                            maxVolumeByCG[cg] = max(maxVolumeByCG.get(cg, 0), a.capacity)

            if missileCG:
                m.append((evetypes.GetGroupNameByGroup(const.groupMissileLauncher), ('isDynamic', MissileMenu, (missileCG,))))
            for groupID in (const.groupEnergyWeapon, const.groupHybridWeapon, const.groupProjectileWeapon):
                if turretCGbyLG[groupID]:
                    m.append((evetypes.GetGroupNameByGroup(groupID), ('isDynamic', TurretMenu, (turretCGbyLG[groupID],))))

            for groupID in otherCGbyLG:
                if otherCGbyLG[groupID]:
                    m.append((evetypes.GetGroupNameByGroup(groupID), ('isDynamic', GenericMenu, (otherCGbyLG[groupID], maxVolumeByCG))))

            if m:
                m.insert(0, None)
                m.insert(0, ('<color=0xff708090>Module groups accepting charges', None))
            else:
                m.insert(0, ('<color=0xff708090>No modules accepting charges', None))
            return m

        if drones:
            return DroneMenu()
        else:
            return GetMenu()

    exports = {'insider.ChargeMenu': ChargeMenu,'insider.DroneMenu': DroneMenu}


from crawler import Crawler
from dispatcher import Dispatcher

# 리뷰 크롤링 & 로컬 DB 저장
crawler = Crawler()
crawler.pull_product_list()
crawler.pull_product_review()
del crawler

# DB에 저장된 리뷰를 API로 밀어넣기
dispatcher = Dispatcher()
dispatcher.match_product()
dispatcher.push_review()
del dispatcher


from flask import Flask, render_template, redirect, request

app = Flask(__name__)

distance = 0.1

@app.route("/")
def home():
    global distance
    return render_template('test8/page.html', distance=distance)

@app.route("/setdistance", methods=["POST"])
def setdistance():
    global distance
    distance = float(request.form["distance"])
    print("set distance to", distance)
    return redirect(request.referrer)

app.run(debug = True)

Python/Get started with flask/8 request form.py


import cv2
import numpy
import time
import filters
from HD import HD

class CaptureManager(object):
    def __init__(self,capture,previewWindowManager = None,shouldMirrorPreview = False):
        self.previewWindowManager = previewWindowManager
        self.shouldMirrorPreview  = shouldMirrorPreview
        self._capture = capture
        self._channel = 0
        self._enteredFrame = False
        self._frame = None
        self._imageFilename = None
        self._BlurimageFilname = None
        self._videoFilename = None
        self._videoEncoding = None
        self._videoWriter = None
        self._startTime = 0.0
        self._fpsEstimate = 0.0
        self._framesElapse = 0.0
        self._curvefilter = None
        self._IfHD = True
        self._HD = HD()
        self.num_head = 0
        # print 'sss'
    @property
    def channel(self):
        return self._channel
    @channel.setter
    def channel(self,value):
        if self._channel != value:
            self._channel = value
            self._frame = None
    @property
    def isWritingImage(self):
        return self._imageFilename is not None #bool
    @property
    def isBlurWritingImage(self):
        return self._BlurimageFilname is not None and self._curvefilter is not None
    @property
    def iswritingVideo(self):
        return self._videoFilename is not None #bool
    @property
    def isdetectinghead(self):
        return self._IfHD is not False #bool

    def enteredFrame(self):
        # print 'sss2'
        assert not self._enteredFrame,'previous enterFrame() had no matching exitFrame()'
        if self._capture is not None:
            aaa,self._frame = self._capture.read() #read,grab,retval
            while aaa is False:
                print("frame error!")
                aaa,self._frame = self._capture.read() #read,grab,retval
            # cv2.imshow("test",self._frame)
            # cv2.waitKey(0)
        if self._IfHD:
            self.predict_Frame()
    def predict_Frame(self):
        # frame = self._frame
        # print(frame.shape)
        self._frame ,self.num_head= self._HD.HD_predict(self._frame,self._fpsEstimate)
    def exitFrame(self):
        # print 'sss3'
        if self._frame is None:
            self._enteredFrame = False
            return
        # print 'test\n'
        if self._framesElapse == 0:
            self._startTime = time.time()

        else:
            timeElapse = time.time() - self._startTime

            self._fpsEstimate = self._framesElapse / timeElapse
        self._framesElapse += 1
        if self.previewWindowManager is not None:
            if self.shouldMirrorPreview:
                #mirroredFrame = numpy.fliplr(self._frame).copy()
                self.previewWindowManager.show(self._frame)
            else:
                self.previewWindowManager.show(self._frame)
        if self.isWritingImage:
            cv2.imwrite(self._imageFilename,self._frame)
            self._imageFilename = None
        if self.isBlurWritingImage:
            Blurframe = self._frame
            filters.strokeEdges(Blurframe,Blurframe)
            self._curvefilter.apply(Blurframe,Blurframe)
            cv2.imwrite(self._BlurimageFilname,Blurframe)
            self._BlurimageFilname = None
            # print 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
        self._writeVideoFrame()
        self._frame = None
        self._enteredFrame = False
    def writeImage(self,imageFilename):
        # print 'sss4'
        self._imageFilename = imageFilename
    def BlurwriteImage(self,BlurimageFilname,Filtertype):
        self._BlurimageFilname = BlurimageFilname
        # print 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
        self._curvefilter = Filtertype
    # def startWritingVideo(self,filename,encoding = cv2.VideoWriter_fourcc('I','4','2','0')):
    def startWritingVideo(self,filename,encoding = cv2.VideoWriter_fourcc('M','J','P','G')):
        # print 'sss5'
        self._videoFilename = filename
        self._videoEncoding = encoding
    def stopWritingVideo(self):
        self._videoEncoding = None
        self._videoFilename = None
        self._videoWriter = None
    def _writeVideoFrame(self):
        if not self.iswritingVideo:
            return
        if self._videoWriter is None:
            fps = self._capture.get(cv2.CAP_PROP_FPS)
            if fps == 0.0:
                if self._framesElapse < 20:
                    return
                else:
                    fps = self._fpsEstimate
            # size = (int(self._capture.get(cv2.CAP_PROP_FRAME_WIDTH)),int(self._capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
            size = (600,600)
            self._videoWriter = cv2.VideoWriter(self._videoFilename,self._videoEncoding,fps,size)
        self._videoWriter.write(self._frame)
        print("Writing Video！")

class WindowManager(object):
    def __init__(self,windowName,keypressCallback = None):
        self.keypressCallback = keypressCallback
        self._windowName = windowName
        self._isWindowCreated = False

    @property
    def isWindowCreated(self):
        return self._isWindowCreated
    def createWindow(self):
        cv2.namedWindow(self._windowName)
        self._isWindowCreated = True
    def show(self,frame):
        cv2.imshow(self._windowName,frame)
    def destroyWindow(self):
        cv2.destroyWindow(self._windowName)
        self._isWindowCreated = False
    def processEvents(self):
        keycode = cv2.waitKey(1)
        if self.keypressCallback is not None and keycode != -1:
            keycode &= 0xFF # discard GTK info
            self.keypressCallback(keycode)


import argparse

import tensorflow as tf

from model import UGATIT
from utils import *

def parse_args() -> argparse.Namespace:
    desc = 'Tensorflow implementation of U-GAT-IT'
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument('--phase', type=str, default='train', help='[train / test]')
    parser.add_argument('--light', type=str2bool, default=False, help='[U-GAT-IT full version / U-GAT-IT light version')
    parser.add_argument('--dataset', type=str, default='selfie2anime', help='dataset_name')

    parser.add_argument('--epoch', type=int, default=100, help='The number of epochs to run')
    parser.add_argument('--iteration', type=int, default=10000, help='The number of training iterations')
    parser.add_argument('--batch_size', type=int, default=1, help='The size of batches')
    parser.add_argument('--print_freq', type=int, default=1000, help='The frequency of print')
    parser.add_argument('--decay_flag', type=str2bool, default=True, help='The decay flag')
    parser.add_argument('--decay_epoch', type=int, default=50, help='Decay epoch')

    parser.add_argument('--lr', type=float, default=0.0001, help='The learning rate')
    parser.add_argument('--GP_ld', type=int, default=10, help='The gradient penalty lambda')
    parser.add_argument('--adv_weight', type=int, default=1, help='Weight about GAN')
    parser.add_argument('--cycle_weight', type=int, default=10, help='Weight about Cycle')
    parser.add_argument('--identity_weight', type=int, default=10, help='Weight about Identity')
    parser.add_argument('--cam_weight', type=int, default=1000, help='Weight about CAM')
    parser.add_argument('--gan_type', type=str, default='lsgan', help='[gan / lsgan / wgan-up / dragan / hinge]')

    parser.add_argument('--smoothing', type=str2bool, default=False, help='AdaLIN smoothing effect')

    parser.add_argument('--ch', type=int, default=64, help='Base channel number per layer')
    parser.add_argument('--n_res', type=int, default=4, help='The number of resblocks')
    parser.add_argument('--n_dis', type=int, default=6, help='The number of discriminator layers')
    parser.add_argument('--n_critic', type=int, default=1, help='The number of critic')
    parser.add_argument('--sn', type=str2bool, default=True, help='Whether to use Spectral Norm')

    parser.add_argument('--image_size', type=int, default=256, help='The size of the image')
    parser.add_argument('--image_ch', type=int, default=3, help='The size of image channel')
    parser.add_argument('--augment_flag', type=str2bool, default=True, help='Whether to perform Image augmentation')

    parser.add_argument('--checkpoint_dir', type=str, default='checkpoint', help='Directoty for checkpoints')
    parser.add_argument('--result_dir', type=str, default='results', help='Directory to save generated images')
    parser.add_argument('--log_dir', type=str, default='logs', help='Directory to save training logs')
    parser.add_argument('--sample_dir', type=str, default='samples', help='Directory name to save the samples on training')

    return check_args(parser.parse_args())

def check_args(arguments: argparse.Namespace) -> argparse.Namespace:
    check_folder(arguments.checkpoint_dir)
    check_folder(arguments.result_dir)
    check_folder(arguments.log_dir)
    check_folder(arguments.sample_dir)

    try:
        assert arguments.epoch >= 1
    except ValueError:
        print('Number of epochs must be >= 1')

    try:
        assert arguments.batch_size >= 1
    except ValueError:
        print('Batch size must be >= 1')

    return arguments

def main():
    arguments = parse_args()
    if arguments is None:
        exit()

    with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:
        model = UGATIT(sess, args=arguments)
        model.build_model()

        show_all_variables()

        if arguments.phase == 'train':
            # model.train()
            print('[*] Training finished')

        if arguments.phase == 'test':
            # model.test()
            print('[+] Test finished')

if __name__ == '__main__':
    main()


from bs4 import BeautifulSoup
from models.wind import Wind
from models.weather import Weather
from models.tideTime import TideTime
from models.tides import Tides
from datetime import datetime as dt
from datetime import timedelta as td
import numpy as np
import calendar
import re

def prettify(html):
    soup = BeautifulSoup(html, 'html.parser')
    return soup.prettify

# region Weather Extraction

def extractWeather(weatherHtml):
    currentTemperature = __extractCurrentTemperature(weatherHtml)
    humidity = __extractHumidity(weatherHtml)
    wind = __extractWind(weatherHtml)

    return Weather(currentTemperature, humidity, wind)

def __extractCurrentTemperature(html) -> str:
    soup = BeautifulSoup(html, 'html.parser')
    h1 = soup.find('h1')

    return h1.text.strip()[:4]

def __extractHumidity(html) -> str:
    soup = BeautifulSoup(html, 'html.parser')
    humidity = soup.find('li', {'class': 'humidity'})
    spans = humidity.find_all('span')

    return spans[0].text[:-1]

def __extractWind(html) -> Wind:
    soup = BeautifulSoup(html, 'html.parser')
    wind = soup.find('li', {'class': 'wind'})

    direction = wind.find('strong').text

    windAndGustSpeedKmHr = wind.findAll(
        'span')[0].text.strip().replace(' ', '')

    windSpeed = re.search(r'(\d+\.\d)', windAndGustSpeedKmHr).group(0)

    gusts = windAndGustSpeedKmHr.find('(')
    gustSpeed = re.search(r'(\d+\.\d)', windAndGustSpeedKmHr[gusts:]).group(0)

    return Wind(direction, windSpeed, gustSpeed)

# endregion

# region Tide Extraction

def extractTides(tideHtml):
    tideTimes = __extractTideTimes(tideHtml)
    currentTide = __computeCurrentTide(tideTimes)
    direction = __getTideMovementDirection(tideTimes)
    return Tides(currentTide, direction, tideTimes)

def __extractTideTimes(tideHtml):
    soup = BeautifulSoup(tideHtml, 'html.parser')
    list_items = soup.find_all('li', {'class': ['day', 'current']})
    inner_list_items = []
    for item in list_items:
        if 'Today' in item.text:
            inner_list_items = item.find('ul').find_all('li')

    date = dt.now().date()
    format = '%Y-%m-%d %I:%M %p'

    tideTimes = []
    for item in inner_list_items:
        tideTimes.append(
            TideTime(dt.strptime(str(date) + ' ' + item.find('h3').text, format), float(item.find('span').text[:3])))

    return tideTimes

def __computeCurrentTide(tideTimes):
    xp = []
    fp = []

    for tide in tideTimes:
        xp.append(toTimestamp(tide.time))
        fp.append(tide.height)

    today = toTimestamp(dt.now())
    return np.interp(today, xp, fp)

def toTimestamp(d):
    return calendar.timegm(d.timetuple())

def __getTideMovementDirection(tideTimes):
    xp = []
    fp = []

    for tide in tideTimes:
        xp.append(toTimestamp(tide.time))
        fp.append(tide.height)

    tenMinutesAgo = toTimestamp(dt.now() - td(minutes=10))
    now = toTimestamp(dt.now())
    tenMinutesFromNow = toTimestamp(dt.now() + td(minutes=10))

    heightTenMinutesAgo = np.interp(tenMinutesAgo, xp, fp)
    heightNow = np.interp(now, xp, fp)
    heightTenMinutesFromNow = np.interp(tenMinutesFromNow, xp, fp)

    if heightNow > heightTenMinutesAgo and heightNow < heightTenMinutesFromNow:
        return 'Incoming'

    if heightNow < heightTenMinutesAgo and heightNow > heightTenMinutesFromNow:
        return 'Outgoing'

    if heightNow < heightTenMinutesAgo and heightNow > heightTenMinutesFromNow:
        return 'Peaking'
# endregion


import sys
import unittest
from unittest.mock import patch

sys.path.insert(0, '..')

from androidtv.adb_manager.adb_manager_async import ClientAsync

from .async_wrapper import awaiter
from . import patchers

class TestAsyncClientDevice(unittest.TestCase):
    """Test the ``ClientAsync`` and ``DeviceAsync`` classes defined in ``adb_manager_async.py``.

    This file can be removed once true async support for using an ADB server is available.

    """

    @awaiter
    async def test_async_client_device(self):
        with patch("androidtv.adb_manager.adb_manager_async.Client", patchers.ClientFakeSuccess):
            client = ClientAsync("host", "port")

            device = await client.device("serial")

            with patch("{}.DeviceFake.shell".format(patchers.__name__)):
                await device.shell("test")

            with patch("{}.DeviceFake.push".format(patchers.__name__)):
                await device.push("local_path", "device_path")

            with patch("{}.DeviceFake.pull".format(patchers.__name__)):
                await device.pull("device_path", "local_path")

            with patch("{}.DeviceFake.screencap".format(patchers.__name__)):
                await device.screencap()

    @awaiter
    async def test_async_client_device_fail(self):
        with patch("androidtv.adb_manager.adb_manager_async.Client", patchers.ClientFakeFail):
            client = ClientAsync("host", "port")

            device = await client.device("serial")

            self.assertFalse(device)


# -*- coding: utf-8 -*-
"""
A backend for packet.net.

"""

import os
import os.path
import time
import sys
import nixops.resources
from nixops.resources import ResourceOptions
from nixops.backends import MachineDefinition, MachineState, MachineOptions
from nixops.nix_expr import Function, RawValue, nix2py
import nixops.util
import nixops.known_hosts
import nixops_packet.utils as packet_utils
import nixops_packet.resources
import socket
import packet
import json
import getpass
from typing import cast, Dict, List, Optional, Any

class PacketMachineOptions(ResourceOptions):
    accessKeyId: Optional[str]
    keyPair: str
    # tags: List[str]
    facility: str
    plan: str
    project: str
    nixosVersion: str
    ipxeScriptUrl: Optional[str]
    customData: Any
    storage: Any
    alwaysPxe: Optional[bool]
    spotInstance: bool
    spotPriceMax: str
    reservationId: Optional[str]

class MyMachineOptions(MachineOptions):
    packet: PacketMachineOptions

class PacketDefinition(MachineDefinition):
    @classmethod
    def get_type(cls):
        return "packet"

    config: MyMachineOptions

    def __init__(self, name: str, config):
        super().__init__(name, config)
        if self.config.packet.accessKeyId is None:
            self.access_key_id = os.environ["PACKET_ACCESS_KEY"]
        else:
            self.access_key_id = self.config.packet.accessKeyId

        self.key_pair = self.config.packet.keyPair
        self.tags = self.config.packet.tags
        self.facility = self.config.packet.facility
        self.plan = self.config.packet.plan
        self.project = self.config.packet.project
        self.nixosVersion = self.config.packet.nixosVersion
        self.ipxe_script_url = self.config.packet.ipxeScriptUrl
        self.customData = self.config.packet.customData
        self.storage = self.config.packet.storage
        self.always_pxe = self.config.packet.alwaysPxe
        self.spotInstance = self.config.packet.spotInstance
        self.spotPriceMax = self.config.packet.spotPriceMax
        self.reservationId = self.config.packet.reservationId

        if self.ipxe_script_url != "":
            self.operating_system = "custom_ipxe"
        else:
            self.operating_system = self.nixosVersion

    def show_type(self):
        return "packet [something]"

class PacketState(MachineState[PacketDefinition]):
    @classmethod
    def get_type(cls):
        return "packet"

    state = nixops.util.attr_property("state", MachineState.MISSING, int)  # override
    accessKeyId: Optional[str] = nixops.util.attr_property("packet.accessKeyId", None)
    key_pair: Optional[str] = nixops.util.attr_property("packet.keyPair", None)
    nixos_version: Optional[str] = nixops.util.attr_property(
        "packet.nixosVersion", None
    )
    ipxe_script_url: Optional[str] = nixops.util.attr_property(
        "packet.ipxeScriptUrl", None
    )
    plan: Optional[str] = nixops.util.attr_property("packet.plan", None)
    provSystem: Optional[str] = nixops.util.attr_property("packet.provSystem", None)
    metadata: Optional[str] = nixops.util.attr_property("packet.metadata", None)
    public_ipv4: str = nixops.util.attr_property("publicIpv4", None)
    public_ipv6: Optional[str] = nixops.util.attr_property("publicIpv6", None)
    private_ipv4: Optional[str] = nixops.util.attr_property("privateIpv4", None)
    default_gateway: Optional[str] = nixops.util.attr_property("defaultGateway", None)
    private_gateway: Optional[str] = nixops.util.attr_property("privateGateway", None)
    default_gatewayv6: Optional[str] = nixops.util.attr_property(
        "defaultGatewayv6", None
    )
    public_cidr: Optional[str] = nixops.util.attr_property("publicCidr", None, int)
    public_cidrv6: Optional[str] = nixops.util.attr_property("publicCidrv6", None, int)
    private_cidr: Optional[str] = nixops.util.attr_property("privateCidr", None, int)

    def __init__(self, depl: nixops.deployment.Deployment, name: str, id):
        MachineState.__init__(self, depl, name, id)
        self.name = name
        self._conn = None
        # print(self.provSystem)

    def get_ssh_name(self) -> str:
        if not self.public_ipv4:
            raise Exception(
                "Packet machine ‘{0}’ does not have a public IPv4 address (yet)".format(
                    self.name
                )
            )
        return self.public_ipv4

    @property
    def resource_id(self) -> Optional[str]:
        return self.vm_id

    def connect(self):
        if self._conn:
            return self._conn
        if not self.accessKeyId:
            raise Exception("No API token is set, ensure packet.accessKeyId is set!")
        self._conn = packet_utils.connect(self.accessKeyId)
        return self._conn

    def get_ssh_private_key_file(self) -> Optional[str]:
        if self._ssh_private_key_file:
            return self._ssh_private_key_file
        kp = self.findKeypairResource(self.key_pair)
        if kp:
            return self.write_ssh_private_key(kp.private_key)
        else:
            return None

    def get_ssh_flags(self, *args, **kwargs):
        file = self.get_ssh_private_key_file()
        super_flags = super(PacketState, self).get_ssh_flags(*args, **kwargs)
        return (
            super_flags
            + (["-i", file] if file else [])
            + ["-o", "StrictHostKeyChecking=accept-new"]
        )

    def get_sos_ssh_name(self) -> str:
        instance = self.connect().get_device(self.vm_id)
        return "sos.{}.packet.net".format(instance.facility["code"])

    def op_sos_console(self) -> None:
        ssh = nixops.ssh_util.SSH(self.logger)
        ssh.register_flag_fun(self.get_ssh_flags)
        ssh.register_host_fun(self.get_sos_ssh_name)
        flags, command = ssh.split_openssh_args([])
        assert self.vm_id is not None
        sys.exit(
            ssh.run_command(
                command, user=self.vm_id, check=False, logged=False, allow_ssh_args=True
            )
        )

    def get_physical_spec_from_plan(self, public_key):
        return {
            "config": {
                ("users", "extraUsers", "root", "openssh", "authorizedKeys", "keys"): [
                    public_key
                ]
            },
            "imports": [nix2py(self.provSystem if self.provSystem else "{}")],
        }

    def get_physical_spec(self):
        if self.key_pair == None and self.plan != None:
            raise Exception("Key Pair is not set")
        kp = self.findKeypairResource(self.key_pair)
        if kp:
            public_key = kp.public_key
        else:
            public_key = "not set"
        return self.get_physical_spec_from_plan(public_key)

    def create_after(self, resources, defn):
        # make sure the ssh key exists before we do anything else
        return {
            r
            for r in resources
            if isinstance(r, nixops_packet.resources.keypair.PacketKeyPairState)
        }

    def get_common_tags(self):
        tags: Dict[str, str] = {
            "uuid": self.depl.uuid,
            "name": self.name,
            "ssh_url": "{0}@{1}:{2}".format(
                getpass.getuser(), socket.gethostname(), self.depl._db.db_file
            ),
        }
        if self.depl.name:
            tags.update({"deployment_name": self.depl.name})
        return tags

    def destroy(self, wipe=False):
        if self.plan != None:
            self.connect()
        if not self.depl.logger.confirm(
            "are you sure you want to destroy Packet.Net machine ‘{0}’?".format(
                self.name
            )
        ):
            return False
        self.log("destroying instance {}".format(self.vm_id))
        try:
            if self.vm_id != None:
                instance = self.connect().get_device(self.vm_id)
                instance.delete()
        except packet.baseapi.Error as e:
            if (
                e.args[0]
                == "Error 422: Cannot delete a device while it is provisioning"
            ):
                self.state = self.packetstate2state(instance.state)
                raise e
            else:
                print(e)
                self.log(
                    "An error occurred destroying instance. Assuming it's been destroyed already."
                )
        return True

    def create(self, defn, check, allow_reboot, allow_recreate):
        assert isinstance(defn, PacketDefinition)
        self.accessKeyId = defn.access_key_id
        self.connect()

        if self.state != self.UP:
            check = True

        self.set_common_state(defn)

        if self.vm_id and check:
            try:
                instance = self.connect().get_device(self.vm_id)
            except packet.baseapi.Error as e:
                if e.args[0] == "Error 404: Not found":
                    instance = None
                    self.vm_id = None
                    self.state = MachineState.MISSING
                    self.provSystem = None
                    self.metadata = None
                else:
                    raise e

            if instance is None:
                if not allow_recreate:
                    raise Exception(
                        "Packet.net instance ‘{0}’ went away; use ‘--allow-recreate’ to create a new one".format(
                            self.name
                        )
                    )

            if instance:
                self.update_state(instance)

        if not self.vm_id:
            self.create_device(defn, check, allow_reboot, allow_recreate)

        self.wait_for_ssh()

        if self.provSystem is None:
            self.update_provSystem()
        if self.metadata is None:
            self.update_metadata()

    def op_update_provSystem(self) -> None:
        self.update_provSystem()

    def update_provSystem(self) -> None:
        self.wait_for_ssh()

        provSystem = self.run_command(
            "cat /etc/nixos/packet/system.nix",
            check=True,
            logged=True,
            allow_ssh_args=True,
            capture_stdout=True,
        )
        self.provSystem = "\n".join(
            [
                line
                for line in provSystem.splitlines()
                if not line.lstrip().startswith("#")
            ]
        )
        self.log("System provisioning file captured: {}".format(self.provSystem))

    def op_reinstall(self):
        """Instruct Packet to deprovision and reinstall NixOS."""
        self.connect()

        if self.vm_id is not None:
            instance = self.connect().get_device(self.vm_id)
            instance.reinstall()

        self.log_start("waiting for the machine to go down ...")
        self.wait_for_ssh()
        self.log_end("[down]")
        self._ssh_pinged_this_time = False
        self.ssh_pinged = False
        self.ssh.reset()
        # !!! nixops.known_hosts.remove(self.public_ipv4, None)

        self.wait_for_state("provisioning")
        self.wait_for_state("active")

        self.wait_for_ssh()
        self.log_end("[up]")

        self.update_state(instance)

        self.log("{}".format(self.public_ipv4))
        self.wait_for_ssh()

        self.update_provSystem()
        self.update_metadata()
        self.update_state(instance)

    def update_metadata(self) -> None:
        metadata: str = self.run_command(
            "curl -Ls https://metadata.packet.net/metadata",
            check=True,
            logged=True,
            allow_ssh_args=True,
            capture_stdout=True,
        )
        self.metadata = json.dumps(metadata)

    def update_state(self, instance):
        self.state = self.packetstate2state(instance.state)
        addresses = instance.ip_addresses
        for address in addresses:
            if address["public"] and address["address_family"] == 4:
                self.public_ipv4 = address["address"]
                self.default_gateway = address["gateway"]
                self.public_cidr = address["cidr"]
            if address["public"] and address["address_family"] == 6:
                self.public_ipv6 = address["address"]
                self.default_gatewayv6 = address["gateway"]
                self.public_cidrv6 = address["cidr"]
            if not address["public"] and address["address_family"] == 4:
                self.private_ipv4 = address["address"]
                self.private_gateway = address["gateway"]
                self.private_cidr = address["cidr"]

    def packetstate2state(self, packetstate):
        states = {
            "queued": MachineState.STARTING,
            "provisioning": MachineState.STARTING,
            "active": MachineState.UP,
            "powering_off": MachineState.STOPPING,
            "powering_on": MachineState.STARTING,
            "inactive": MachineState.STOPPED,
        }
        return states.get(packetstate)

    def findKeypairResource(
        self, key_pair_name
    ) -> Optional[nixops_packet.resources.keypair.PacketKeyPairState]:
        for r in self.depl.active_resources.values():
            if isinstance(r, nixops_packet.resources.keypair.PacketKeyPairState):
                key = cast(nixops_packet.resources.keypair.PacketKeyPairState, r)
                if (
                    key.keypair_name == key_pair_name
                    and key.state
                    == nixops_packet.resources.keypair.PacketKeyPairState.UP
                ):
                    return key

        return None

    def create_device(self, defn, check, allow_reboot, allow_recreate):
        self.connect()
        kp = self.findKeypairResource(defn.key_pair)
        assert kp is not None
        common_tags = self.get_common_tags()
        tags: Dict[str, str] = {}
        tags.update(defn.tags)
        tags.update(common_tags)
        self.log_start("creating packet device ...")
        self.log("project: '{0}'".format(defn.project))
        self.log("facility: {0}".format(defn.facility))
        self.log("keyid: {0}".format(kp.keypair_id))
        instance = self.connect().create_device(
            project_id=defn.project,
            hostname="{0}".format(self.name),
            plan=defn.plan,
            facility=[defn.facility],
            operating_system=defn.operating_system,
            user_ssh_keys=[],
            project_ssh_keys=[kp.keypair_id],
            hardware_reservation_id=defn.reservationId,
            spot_instance=defn.spotInstance,
            storage=defn.storage,
            customdata=defn.customData,
            spot_price_max=defn.spotPriceMax,
            tags=packet_utils.dict2tags(tags),
            ipxe_script_url=defn.ipxe_script_url,
            always_pxe=defn.always_pxe,
        )

        self.vm_id = instance.id
        assert self.vm_id is not None
        self.key_pair = defn.key_pair
        self.plan = defn.plan
        self.accessKeyId = defn.access_key_id
        self.log("instance id: " + self.vm_id)
        self.update_state(instance)

        self.log("instance is in {} state".format(instance.state))

        self.wait_for_state("active")

        self.update_state(instance)
        # !!! nixops.known_hosts.remove(self.public_ipv4, None)

        self.log("{}".format(self.public_ipv4))

        self._ssh_pinged_this_time = False
        self.ssh_pinged = False
        self.wait_for_ssh()
        self.update_provSystem()
        self.update_metadata()
        self.update_state(instance)

    def wait_for_state(self, target_state: str) -> None:
        self.log_start(
            "waiting for the machine to enter the state '{}'  ...".format(target_state)
        )
        while True:
            instance = self.connect().get_device(self.vm_id)
            self.update_state(instance)
            if (
                instance.state == "provisioning"
                and hasattr(instance, "provisioning_percentage")
                and instance.provisioning_percentage
            ):
                self.log(
                    "instance is in {}, {}% done".format(
                        instance.state, int(instance.provisioning_percentage)
                    )
                )
            else:
                self.log("instance is in {} state".format(instance.state))

            if instance.state == target_state:
                break
            else:
                time.sleep(10)


import os
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from quizapp.views import *
from django.contrib import admin
admin.autodiscover()

site_media = os.path.join(os.path.dirname(__file__), 'site_media')

urlpatterns = patterns('',
  url(r'^$','django.contrib.auth.views.login'),
  url(r'^userpage/$', user_page),
  url(r'^logout/$', logout_page),
  url(r'^register/$', register_page),
  url(r'^forbidden/$', forbidden),
  url(r'^avatar/',include('avatar.urls')),
  url(r'register/success/$', registration_success),
  url(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': site_media}),
  url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
  url(r'^admin/', include(admin.site.urls)),

)


import c4d
from c4d import gui
#Welcome to the world of Python

def main():
    null01name = doc.SearchObject("measure 01 y")
    null02name = doc.SearchObject("measure 02 y")

    selection = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_0)

    if null01name == None or null02name == None:

        # Create measure NULLs
        null01 = c4d.BaseObject(c4d.Onull)
        null01[c4d.NULLOBJECT_DISPLAY]=13
        null01[c4d.NULLOBJECT_ORIENTATION]=3
        null01[c4d.ID_BASELIST_NAME] = "measure 01 y"
        null01[c4d.ID_BASEOBJECT_USECOLOR]=2
        null01[c4d.ID_BASEOBJECT_COLOR]=c4d.Vector(0,255,0)

        null02 = c4d.BaseObject(c4d.Onull)
        null02[c4d.NULLOBJECT_DISPLAY]=13
        null02[c4d.NULLOBJECT_ORIENTATION]=3
        null02[c4d.ID_BASELIST_NAME] = "measure 02 y"
        null02[c4d.ID_BASEOBJECT_USECOLOR]=2
        null02[c4d.ID_BASEOBJECT_COLOR]=c4d.Vector(255,0,0)
        null02[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_Y]=50

        doc.StartUndo()

        # Insert NULL objects
        doc.AddUndo(c4d.UNDOTYPE_NEW,null01)
        doc.InsertObject(null01)
        doc.AddUndo(c4d.UNDOTYPE_NEW,null02)
        doc.InsertObject(null02)

        doc.EndUndo()

        # Unfold Hierarchy
        null02.InsertUnder(null01)
        null01.SetBit(c4d.BIT_ACTIVE)
        c4d.CallCommand(100004802) # Unfold Selected

        # Create protection tags
        pronull01 = null01.MakeTag(c4d.Tprotection)
        pronull01[c4d.PROTECTION_P_X]=False
        pronull01[c4d.PROTECTION_P_Y]=False

        pronull02 = null02.MakeTag(c4d.Tprotection)
        pronull02[c4d.PROTECTION_P_Y]=False

    else:
        if len(selection) > 1:
            gui.MessageDialog("Select only the image plane.")

        elif len(selection) == 1:

            if op.GetType() ==  5168:

                doc.StartUndo()
                distance = float(null02name[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_Y])
                distanceinput = float(c4d.gui.InputDialog("Set Distance").replace(',','.'))

                factor = distance/distanceinput
                width = op[c4d.PRIM_PLANE_WIDTH]

                height = op[c4d.PRIM_PLANE_HEIGHT]
                newwidth = width/factor
                newheight = height/factor

                doc.AddUndo(c4d.UNDOTYPE_CHANGE,op)
                op[c4d.PRIM_PLANE_HEIGHT] = newheight
                op[c4d.PRIM_PLANE_WIDTH] = newwidth

                doc.AddUndo(c4d.UNDOTYPE_CHANGE,null01name)
                null01name.SetAbsPos(null01name.GetAbsPos()/factor)
                null01name[c4d.NULLOBJECT_RADIUS] = null01name[c4d.NULLOBJECT_RADIUS]/factor

                doc.AddUndo(c4d.UNDOTYPE_CHANGE,null02name)
                null02name[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_Y] = distance/factor
                null02name[c4d.NULLOBJECT_RADIUS] = null02name[c4d.NULLOBJECT_RADIUS]/factor

                doc.EndUndo()

            else:
                gui.MessageDialog("Select the image plane.")
        else:
            gui.MessageDialog("Select the image plane.")

    c4d.EventAdd()

if __name__=='__main__':
    main()


from setuptools import setup

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

setup(
    name='dirtydf',
    version='0.0.22',
    packages=['ddf'],
    author="Joel Tan, Justin Lo, Vik Gopal",
    author_email="vik.gopal@nus.edu.sg",
    description="A package to dirty datasets",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/joeltanwr/DirtyDF",
    license="MIT",
    platforms="OS Independent",
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires ='>=3.6',
    install_requires=['pandas>=1.2.1', 'statsmodels>=0.12.1',
    'scipy>=1.6.0', 'inflection>=0.5.1', 'numpy>=1.19.5']
    #    'pandas',
    #    'statsmodels >= 0.12.1',
    #    'scipy',
    #    'inflection',
    #    'numpy; python_version >= "3.8"', ],
)


from collections import namedtuple

from direction import Direction
import pos_utils
import snake

Game = namedtuple('Game', 'size snake grow direction food')

class SnakeOutOfGameError(Exception):
    pass

def new():
    size = 15, 15
    snake_ = (
        (1, 0),
        (2, 0),
        (3, 0),
    )
    grow = False
    direction = Direction.RIGHT
    food = pos_utils.rand(*(0,0), *size)
    return Game(size, snake_, grow, direction, food)

def move(game: Game, direction: Direction) -> Game:
    if direction.is_opposit(game.direction):
        direction = game.direction
    snake_ = snake.move(game.snake, direction, game.grow)
    if not pos_utils.within(*snake_[-1], *(0,0), *game.size):
        raise SnakeOutOfGameError()
    food = game.food
    if food in snake_:
        grow = True
        food = pos_utils.rand(*(0,0), *game.size)
    else:
        grow = False
        food = game.food
    return Game(game.size, snake_, grow, direction, food)


from cmssw_info import CmsswInfo
import os

class HTCondorJob(object):
    """ Store all the info required to write a HTCondor job file """
    def __init__(self, work_space, gen_frag, lhe_base, model, n_events, year, queue=1, seed=None):
        self.work_space = work_space
        self.gen_frag = gen_frag
        self.lhe_base = lhe_base
        self.model = model
        self.n_events = n_events
        self.year = year
        self.queue = queue
        self.seed = seed

        self.this_dir = os.path.dirname(os.path.realpath(__file__))

        self.disk = 50000 * self.n_events  # kB
        self.runtime = 288 * self.n_events  # seconds. 8 hours/100 events
        self.memory = 5000  # MB

        if 'soolin' in os.environ['HOSTNAME'] or self.lhe_base.startswith('root://'):
            self.grid_proxy = "use_x509userproxy = true"
        else:
            self.grid_proxy = ""

        self.cmssw_info = CmsswInfo(year)
        if self.cmssw_info.gensim['arch'].startswith('slc6'):
            self.job_os = 'SLCern6'
        else:
            self.job_os = 'CentOS7'

        self.write_submission_script()

    def write_submission_script(self):
        """ Write the HTCondor submission script for sample generation """

        body = """# HTCondor submission script
Universe = vanilla
cmd      = {this_dir}/runFullSim_condor_{year}.sh
args     = {work_space} {gen_frag} {lhe_base}_$(Process).lhe {model} {n_events:.0f} $(Process) {cmssw_gensim} {cmssw_aod} {cmssw_mini} {cmssw_nano}
Log      = {work_space}/logs/{model}/condor_job_$(Process).log
Output   = {work_space}/logs/{model}/condor_job_$(Process).out
Error    = {work_space}/logs/{model}/condor_job_$(Process).error
should_transfer_files   = YES
when_to_transfer_output = ON_EXIT_OR_EVICT
{grid_proxy}
# Resource requests (disk storage in kB, memory in MB)
request_cpus = 1
# Disk request size determined by n_events
request_disk = {disk}
request_memory = {memory}
# Max runtime (seconds) determined by n_events
+MaxRuntime = {runtime}
# Require SLC6 machines if needed as CMSSW_7_1_X can't run on SLC7/CentOS7
Requirements = (OpSysAndVer == "{os}")
batch_name = {model}
# Number of instances of job to run
queue {queue}
""".format(this_dir=self.this_dir,
           work_space=self.work_space,
           gen_frag=self.gen_frag,
           lhe_base=self.lhe_base,
           model=self.model,
           n_events=self.n_events,
           disk=self.disk,
           runtime=self.runtime,
           grid_proxy=self.grid_proxy,
           queue=self.queue,
           os=self.job_os,
           year=self.year,
           memory=self.memory,
           cmssw_gensim=self.cmssw_info.gensim['version'],
           cmssw_aod=self.cmssw_info.aod['version'],
           cmssw_mini=self.cmssw_info.mini['version'],
           cmssw_nano=self.cmssw_info.nano['version'])

        self.job_file = os.path.join(self.work_space, 'submission_scripts', self.model, 'condor_submission_all.job')
        # Edit submission script file name and body if writing individual files
        if self.seed is not None:
            self.job_file = self.job_file.replace('all.job', '{}.job'.format(self.seed))
            body = body.replace('$(Process)', str(self.seed))

        with open(self.job_file, 'w') as f:
            f.write(body)


from weather_service.info import info_bp
from flask import request
from flask import Response
from .service import is_temp_cross_zero

@info_bp.route('/temperature', methods=['POST'])
def process_weather_data():
    if request.method == 'POST':
        try:
            data = request.get_json(force=True)
            temperature_list = [t['t_air'] for t in data['data'].values()]
            result = is_temp_cross_zero(temperature_list)
            return Response(str(result), status=200, mimetype='application/json')
        except:
            return Response(None, status=400, mimetype='application/json')


import json
import requests

from tsuruclient.base import Manager as Base

class Manager(Base):
    """
    Manage pool resources.
    """

    def rebalance(self, pool):
        """
        Rebalance a pool.
        """
        data = {"metadataFilter": {"pool": pool}}
        response = requests.post(
            "{}/docker/containers/rebalance".format(self.target),
            data=json.dumps(data),
            headers=self.headers,
            stream=True
        )
        return response


# !/usr/bin/env python
# -*- coding: utf-8 -*-

import wx

"""
创建一个文本编辑器：
    它可以打开给定文件名的文本文件；
    它可以编辑文件文件
    它可以保存文本文件
    它可以正常退出程序
"""

app = wx.App()
win = wx.Frame(None, title="这里输入框体标题", size=(410, 335))

loadButton = wx.Button(win, label="open", pos=(225, 5), size=(80, 25))  # pos屏幕显示位置，sizi窗口初始化大小
saveButton = wx.Button(win, label="save", pos=(315, 5), size=(80, 25))  # style是Frame显示的属性，
filename = wx.TextCtrl(win, pos=(5, 5), size=(210, 25))
contents = wx.TextCtrl(win, pos=(5, 35), size=(390, 260), style=wx.TE_MULTILINE | wx.HSCROLL)

win.Show()
app.MainLoop()

"""
    这里可能需要注意的是，控件（按钮，输入框）的位置和尺寸，位置和尺寸都包括一对数值：
位置包括x 和y坐标，而尺寸包括宽和高。

　　代码比较简单，按钮控件（打开、保存）就不解释了。需要注意的是文本控件，默认的文本框（text.txt field）
就是一行可编译的文本，没有滚动条，为了创建文本区（text.txt area）只要使用style参数调整风格，style 参数
的值实际上是个整数，但不用直接指定，可以使用按位或运算符OR联合了wx.TE_MULTILINE来获取多行文件区，
以及 wx.HSCROLL来获取水平滚动条。

style是Frame显示的属性，常用的style样式说明：

style=wx.CAPTION : 在Frame上增加一个标题栏 ：

style=wx.CLOSE_BOX : 在Frame上显示关闭框：

style=wx.MAXIMIZE_BOX :  　在Frame上显示最大化框

style=wx.MINIMIZE_BOX : 　在Frame上显示最小化框

style=wx.RESIZE_BORDER :　给Frame添加一个用户可以自己改变Frame大小的边框

style=wx.DEFAULT_FRAME_STYLE : 默认的Frame样式：

"""


# Copyright (c) 2018, Palo Alto Networks
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

import json

from django import forms
from django.contrib import messages
from django.shortcuts import render, HttpResponseRedirect

from pan_cnc.lib import cnc_utils
from pan_cnc.lib import pan_utils
from pan_cnc.lib import snippet_utils
from pan_cnc.views import CNCBaseFormView, ProvisionSnippetView, ChooseSnippetView, CNCView
from vistoq.lib import salt_utils

class ViewServicesView(CNCView):
    template_name = "mssp/service_list.html"
    base_html = 'vistoq/base.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        service_list = pan_utils.get_device_groups_from_panorama()
        context['service_list'] = service_list
        return context

class ViewMinionsView(CNCView):
    template_name = "vistoq/minion_list.html"
    base_html = 'vistoq/base.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        salt_util = salt_utils.SaltUtil()
        minion_list = salt_util.get_minion_list()
        context['minion_list'] = minion_list
        return context

class DeployServiceView(CNCBaseFormView):
    # template_name = 'vistoq/deploy_service.html'
    snippet = 'provision_firewall'
    base_html = 'vistoq/base.html'
    app_dir = 'vistoq'

    def get_snippet(self):
        return self.snippet

    def get_context_data(self, **kwargs):
        """
        Override get_context_data so we can modify the context as necessary
        :param kwargs:
        :return:
        """
        print('Getting vm_auth_key')
        vm_auth_key = self.get_value_from_workflow('vm_auth_key', '')
        if vm_auth_key == '':
            vm_auth_key = pan_utils.get_vm_auth_key_from_panorama()
            vakl = vm_auth_key.split(' ')
            if len(vakl) > 2:
                vm_auth_key = vakl[3]

        print(vm_auth_key)
        panorama_ip = cnc_utils.get_config_value('PANORAMA_IP', '0.0.0.0')
        print(panorama_ip)
        self.save_value_to_workflow('vm_auth_key', vm_auth_key)
        self.save_value_to_workflow('panorama_ip', panorama_ip)

        # Ensure we capture FW_NAME in case that has been set previously (easy button case)
        fw_name = self.get_value_from_workflow('FW_NAME', '')
        if fw_name != '':
            self.save_value_to_workflow('vm_name', fw_name)

        context = super().get_context_data(**kwargs)
        form = context['form']

        # load all snippets with a type of 'service'
        salt_util = salt_utils.SaltUtil()
        minion_list = salt_util.get_minion_list()

        # we need to construct a new ChoiceField with the following basic format
        # snippet_name = forms.ChoiceField(choices=(('gold', 'Gold'), ('silver', 'Silver'), ('bronze', 'Bronze')))
        choices_list = list()
        # grab each service and construct a simple tuple with name and label, append to the list
        for minion in minion_list:
            minion_label = minion.split('.')[0]
            choice = (minion, minion_label)
            choices_list.append(choice)

        # let's sort the list by the label attribute (index 1 in the tuple)
        choices_list = sorted(choices_list, key=lambda k: k[1])
        # convert our list of tuples into a tuple itself
        choices_set = tuple(choices_list)
        # make our new field
        new_choices_field = forms.ChoiceField(choices=choices_set)
        # set it on the original form, overwriting the hardcoded GSB version
        form.fields['minion'] = new_choices_field
        # save to kwargs and call parent for additional processing
        context['form'] = form
        return context

    def form_valid(self, form):
        print('Here we go deploying %s' % self.app_dir)
        jinja_context = dict()
        service = snippet_utils.load_snippet_with_name('provision_firewall', self.app_dir)
        for v in service['variables']:
            if self.request.POST.get(v['name']):
                jinja_context[v['name']] = self.request.POST.get(v['name'])

        template = snippet_utils.render_snippet_template(service, self.app_dir, jinja_context)
        print(template)

        salt_util = salt_utils.SaltUtil()
        res = salt_util.deploy_template(template)
        print(res)
        context = dict()
        context['base_html'] = self.base_html
        context['title'] = 'Deploy Next Generation Firewall'
        context['header'] = 'Deployment Results'

        try:
            results_json = json.loads(res)
        except ValueError as ve:
            print('Could not load results from provisioner!')
            print(ve)
            context['results'] = 'Error deploying VM!'
            return render(self.request, 'pan_cnc/results.html', context=context)
        except TypeError as te:
            print('Could not load results from provisioner!')
            print(te)
            context['results'] = 'Error deploying VM!'
            return render(self.request, 'pan_cnc/results.html', context=context)

        if 'minion' not in jinja_context:
            context['results'] = 'Error deploying VM! No compute node found in response'
            return render(self.request, 'pan_cnc/results.html', context=context)

        minion = jinja_context['minion']
        if 'return' in results_json and minion in results_json['return'][0]:
            r = results_json['return'][0][minion]
            steps = r.keys()
            for step in steps:
                step_detail = r[step]
                if step_detail['result'] is not True:
                    context['results'] = 'Error deploying VM! Not all steps completed successfully!\n\n'
                    context['results'] += step_detail['comment']
                    return render(self.request, 'pan_cnc/results.html', context=context)

        context['results'] = 'VM Deployed Successfully on CPE: %s' % minion
        return render(self.request, 'pan_cnc/results.html', context=context)

class ViewDeployedVmsView(CNCBaseFormView):
    """
    Show all the VMs currently deployed on the compute node

    GET will show the dynamic form based on the 'show_deployed_vms_on_node' snippet

    POST will load the snippet and execute it against
    """
    snippet = 'show_deployed_vms_on_node'
    header = 'Vistoq MSSP'
    title = 'Show Deployed VMs on Node'
    action = '/vistoq/vms'
    base_html = 'vistoq/base.html'
    app_dir = 'vistoq'

    def get_snippet(self):
        return self.snippet

    def get_context_data(self, **kwargs):
        """
        Override get_context_data so we can modify the SimpleDemoForm as necessary.
        We want to dynamically add all the snippets in the snippets dir as choice fields on the form
        :param kwargs:
        :return:
        """

        context = super().get_context_data(**kwargs)
        form = context['form']

        # load all snippets with a type of 'service'
        salt_util = salt_utils.SaltUtil()
        minion_list = salt_util.get_minion_list()

        # we need to construct a new ChoiceField with the following basic format
        # snippet_name = forms.ChoiceField(choices=(('gold', 'Gold'), ('silver', 'Silver'), ('bronze', 'Bronze')))
        choices_list = list()
        # grab each service and construct a simple tuple with name and label, append to the list
        for minion in minion_list:
            minion_label = minion.split('.')[0]
            choice = (minion, minion_label)
            choices_list.append(choice)

        # let's sort the list by the label attribute (index 1 in the tuple)
        choices_list = sorted(choices_list, key=lambda k: k[1])
        # convert our list of tuples into a tuple itself
        choices_set = tuple(choices_list)
        # make our new field
        new_choices_field = forms.ChoiceField(choices=choices_set)
        # set it on the original form, overwriting the hardcoded GSB version
        form.fields['minion'] = new_choices_field
        # save to kwargs and call parent for additional processing
        context['form'] = form
        return context

    def form_valid(self, form):
        print('Here we go deploying')
        minion = self.get_value_from_workflow('minion', '')
        salt_util = salt_utils.SaltUtil()

        template = snippet_utils.render_snippet_template(self.service, self.app_dir, self.get_workflow())

        res = salt_util.deploy_template(template)
        context = dict()
        context['base_html'] = self.base_html

        try:
            if res is None:
                context['results'] = 'Could not get deployed VM list, no valid return from CPE'
                return render(self.request, 'pan_cnc/results.html', context=context)

            response_obj = json.loads(res)
            # {"return": [{"compute-01.c.vistoq-demo.internal": {"shoaf1": "shutdown", "stuart1": "shutdown"}}]}
            fm = response_obj['return'][0]
            vms = list()
            if minion in fm:
                minion_dict = response_obj['return'][0][minion]
                for m in minion_dict:
                    vm_detail = dict()
                    vm_detail['hostname'] = m
                    vm_detail['status'] = minion_dict[m]
                    vms.append(vm_detail)

                context['vms'] = vms
                context['minion'] = minion
                return render(self.request, 'vistoq/deployed_vms.html', context=context)
            else:
                context['results'] = response_obj['return'][0]
                return render(self.request, 'pan_cnc/results.html', context=context)
        except ValueError as ve:
            print('Could not parse json')
            print(ve)
            context['results'] = {'Error': 'Could not get deployed VMs list!'}
            return render(self.request, 'pan_cnc/results.html', context=context)

class DeleteVMView(CNCView):
    template_name = 'pan_cnc/results.html'
    base_html = 'vistoq/base.html'
    app_dir = 'vistoq'

    def get_context_data(self, **kwargs):
        hostname = self.kwargs['hostname']
        minion = self.kwargs['minion']

        service = snippet_utils.load_snippet_with_name('delete_single_vm', self.app_dir)
        jinja_context = dict()
        for v in service['variables']:
            if kwargs.get(v['name']):
                jinja_context[v['name']] = kwargs.get(v['name'])

        template = snippet_utils.render_snippet_template(service, self.app_dir, jinja_context)
        salt_util = salt_utils.SaltUtil()
        res = salt_util.deploy_template(template)
        print(res)
        print('deleting hostname %s' % hostname)
        context = dict()
        context['base_html'] = self.base_html
        context['results'] = res

        return context

class GPCSView(CNCBaseFormView):
    """
    /vistoq/configure

    This will instantiate the SimpleDemoForm from forms.py

    Allows the user to choose which snippet to load

    """
    snippet = 'cnc-conf-gpcs'
    header = 'Provision Service: GPCS'
    title = 'Configure Service Sales information: GPCS'
    app_dir = 'vistoq'

    def get_context_data(self, **kwargs):
        """
        Override get_context_data so we can modify the SimpleDemoForm as necessary.
        We want to dynamically add all the snippets in the snippets dir as choice fields on the form
        :param kwargs:
        :return:
        """

        context = super().get_context_data(**kwargs)

        form = context['form']
        # load all snippets with a type of 'service'
        services = snippet_utils.load_snippets_of_type('gpcs')

        # we need to construct a new ChoiceField with the following basic format
        # snippet_name = forms.ChoiceField(choices=(('gold', 'Gold'), ('silver', 'Silver'), ('bronze', 'Bronze')))
        choices_list = list()
        # grab each service and construct a simple tuple with name and label, append to the list
        for service in services:
            choice = (service['name'], service['label'])
            choices_list.append(choice)

        # let's sort the list by the label attribute (index 1 in the tuple)
        choices_list = sorted(choices_list, key=lambda k: k[1])
        # convert our list of tuples into a tuple itself
        choices_set = tuple(choices_list)
        # make our new field
        new_choices_field = forms.ChoiceField(choices=choices_set)
        # set it on the original form, overwriting the hardcoded GSB version

        form.fields['snippet_name'] = new_choices_field

        context['form'] = form
        return context

    def form_valid(self, form):
        """
        Called when the simple demo form is submitted
        :param form: SimpleDemoForm
        :return: rendered html response
        """
        return HttpResponseRedirect('provision')

class GsbProvisionView(ProvisionSnippetView):
    base_html = 'vistoq/base.html'

    def generate_dynamic_form(self):
        simple_service = self.get_value_from_workflow('simple_service', '')
        print('simple service is ' + simple_service)
        if simple_service == 'on':
            print('only showing device name field')
            self.fields_to_render += ['FW_NAME']

        # save local workflow data to jinja context for template render
        self.save_workflow_to_session()

        return super().generate_dynamic_form()

class GsbWorkflow02(ProvisionSnippetView):
    base_html = 'vistoq/base.html'

    def create_sku(self):
        # decoder ring to map menu values to SKU elements
        sku_tier = {'gold': 'BND2', 'silver': 'BND1', 'bronze': 'BASIC'}
        sku_size = {'small': 'VM-50', 'medium': 'VM-300', 'large': 'VM-500'}
        sku_term = {'M': 'MU', '1': 'YU', '3': '3YU'}

        user_tier = self.get_value_from_workflow('snippet_name', '').split('_')[0]
        user_size = self.get_value_from_workflow('service_size', '')
        user_term = self.get_value_from_workflow('service_term', '')

        sku = 'PAN-{0}-SP-BKLN-{1}-{2}'.format(sku_size[user_size],
                                               sku_tier[user_tier],
                                               sku_term[user_term])

        self.save_value_to_workflow('sku', sku)
        print('sku is {0}'.format(sku))

    def generate_dynamic_form(self):
        # get customer name and use for fw name
        customer_name = self.get_value_from_workflow('customer_name', '')
        self.save_value_to_workflow('FW_NAME', customer_name)

        # only show the FW_NAME field to validate name used
        self.fields_to_render = ['FW_NAME']

        # create a sku value based on form input data
        self.create_sku()
        # save local workflow data to jinja context for template render
        self.save_workflow_to_session()

        return super().generate_dynamic_form()

    def form_valid(self, form):
        """
        Called when the simple demo form is submitted
        :param form: SimpleDemoForm
        :return: rendered html response
        """

        # get FW_NAME value from form submit
        fw_name = self.get_value_from_workflow('FW_NAME', '')

        # set stack and device-group names to fw_name
        self.save_value_to_workflow('STACK', fw_name)
        self.save_value_to_workflow('DEVICE_GROUP', fw_name)
        # Force Gold and Silver to NOT include EDL rules
        self.save_value_to_workflow('INCLUDE_PAN_EDL', 'False')

        print('set device-group and stack to firewall name')

        return super().form_valid(form)

class VistoqChooseSnippetView(ChooseSnippetView):
    base_html = 'vistoq/base.html'

class VistoqRedirectView(CNCView):
    template_name = 'vistoq/redirect.html'

    def get_context_data(self, **kwargs):
        context = dict()
        panorama_ip = cnc_utils.get_config_value('PANORAMA_IP', '0.0.0.0')
        if panorama_ip == '0.0.0.0':
            panorama_ip = self.get_value_from_workflow('TARGET_IP', '0.0.0.0')
            if panorama_ip == '0.0.0.0':
                print('Could not load panorama ip')
                messages.add_message(self.request, messages.ERROR, 'Could not locate Panorama Configuration')
                context['redirect_link'] = '/'
                return context

            context['redirect_link'] = f'https://{panorama_ip}'
        else:
            context['redirect_link'] = f'https://{panorama_ip}'

        return context


# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
    def __repr__(self):
        if self:
            return "{} -> {}".format(self.val, self.next)

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        result = ListNode(0)
        tmp = result
        flag =0
        p = l1
        q = l2
        while (p != None or q != None):
            x = p.val if p!=None else 0
            y = q.val if q!=None else 0
            sum = x+y+flag
            flag=int(sum/10)
            tmp.next = ListNode(sum%10)
            tmp = tmp.next
            if p!=None:
                p = p.next
            if q!=None:
                q = q.next

        if flag == 1:
            tmp.next = ListNode(1)
            tmp = tmp.next

        return result.next

class Solution2:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        result = ListNode(0)
        tmp = result
        carry = 0
        while l1 or l2 or carry:
            val1 = val2 = 0
            if l1:
                val1 = l1.val
                l1 = l1.next
            if l2:
                val2 = l2.val
                l2 = l2.next

            carry,mod = divmod(val1+val2+carry,10)
            tmp.next = ListNode(mod)
            tmp = tmp.next

        return result.next

l1 = ListNode(9)
l1.next = ListNode(9)
l1.next.next = ListNode(9)
l2 = ListNode(9)
l2.next = ListNode(9)

print(Solution2().addTwoNumbers(l1,l2))


ng=input() # whether the number is ‘ajs’ or not.An ‘ajs’ number is a number whose sum of first two digits is present in given number ‘n’
ngk=list(ng)
s,c=0,0
for i in range(0,2):
  s=s+int(ngk[i])
for i in range(0,len(ng)-1):
  if(int(ng[i]+ng[i+1])==s or int(ng[i])==s or int(ng[i+1])==s):
    c=c+1
if(c>0):
  print("1")
else:
  print("0")


def predict(model, struct_array, test_inds, norm_inputs, norm_outputs, num_rdf, num_adf, dump_folder_path, H_bar, output_stdev, mol_type):

    from numpy import mean, abs, subtract, array, std
    from pandas import DataFrame
    struct_array = struct_array[test_inds]
    pred = []
    target = []
    all_info = []
    for num_atoms, category_ind, internal_ind in struct_array:
        # try:
        pred.append(float(model[num_atoms].predict(x=[atom_i[internal_ind].reshape(1,num_rdf+num_adf+len(mol_type),)
                                         for atom_i in norm_inputs[category_ind]], batch_size=1, verbose=0))*output_stdev + H_bar)
        if len(norm_outputs) == 1:
            target.append(norm_outputs[0][category_ind][internal_ind]*output_stdev + H_bar)
        else:
            target.append(norm_outputs[category_ind][internal_ind]*output_stdev + H_bar)
        all_info.append([num_atoms, target[-1], pred[-1], abs(target[-1] - pred[-1])])
        # except:
        #     print("No models with "+str(num_atoms)+" atoms")
    print("\nAll info (num atoms, target, pred, diff):", all_info)
    mae = mean(array([entry[3] for entry in all_info]))

    if dump_folder_path != None:
        df = DataFrame(data=all_info, columns=("num atoms", "target", "prediction", "difference"))
        df.to_csv(dump_folder_path+'all_info.csv', sep='\t')

    return pred, target, mae


"""
Handlers for executing requests and forwarding responses.

A Requester receives request tasks from the Scraper and executes them a
callback on their resultant Response object.
"""

__author__ = 'bshillingford'

try:
    import queue
except ImportError:
    import Queue as queue
from threading import Thread

class BaseRequester(object):

    """
    Base class for Requesters.

    Initiate the tasks given by the `Scraper` and on completion, call call
    the `Scraper`'s response handler.
    """

    def __init__(self):
        super(BaseRequester, self).__init__()

    def enqueue(self, fn, *args, **kwargs):
        """
        Add a task to the queue.

        May be called on a separate thread if desired.

        :param fn: function to call
        :param args: arguments for fn
        :param kwargs: keyword arguments for fn
        :raise NotImplementedError: this function is abstract
        """
        raise NotImplementedError()

    def mainloop(self, response_handler):
        """
        Called by the scraper's main run function.

        This loop should initiate queued tasks and on completion call the
        `response_handler`.

        :param response_handler: function to call with one argument, the
                                 response
        """
        raise NotImplementedError()

# NOTE: we can't use concurrent.future's ThreadPoolExecutor since we cant
# enqueue from within the callable, as this causes deadlock
class ThreadPoolRequester(BaseRequester):

    """
    Threaded implementation for Requester.

    Sends requests from a thread pool, and calls the `Scraper`'s response
    handler from the main thread.
    """

    def __init__(self, workers=4):
        super(ThreadPoolRequester, self).__init__()
        self.workers = workers
        self._http_queue = queue.Queue()  # tasks for worker threads
        self._main_queue = queue.Queue()  # tasks for main thread

    def enqueue(self, fn, *args, **kwargs):
        """
        Add a request/function to the queue.

        Will be called on a separate thread.

        :param fn: function to call
        :param args: arguments for fn
        :param kwargs: keyword arguments for fn
        """
        self._http_queue.put((fn, args, kwargs))

    def mainloop(self, response_handler):
        """
        Called by the scraper's main run function.

        This loop should initiate queued tasks and on completion call the
        `response_handler`.

        This function creates a thread pool for sending requests, with as many
        workers as specified in the constructor.

        :param response_handler: function to call with one argument, the
                                 response
        """
        # handle requests on worker thread
        def worker():
            while True:
                fn, args, kwargs = self._http_queue.get()
                response = fn(*args, **kwargs)
                self._main_queue.put(response)
                self._http_queue.task_done()

        # create workers
        for _ in xrange(self.workers):
            th = Thread(target=worker)
            th.daemon = True
            th.start()

        # on main thread, call handlers
        # we are completely done <=> all handlers are finished AND all
        # workers are done their tasks
        while True:
            response = self._main_queue.get()
            response_handler(response)
            self._main_queue.task_done()

            # if we're done, check if it's just for now...
            if self._main_queue.empty():
                self._http_queue.join()  # wait for workers to give us
                # responses
                # if no more responses created by workers => completely done
                if self._main_queue.empty():
                    break

class SerialRequester(BaseRequester):

    """
    Fully sequential implementation for Requester.

    Sends requests and calls the `Scraper`'s response handler all from the
    main thread.
    """

    def __init__(self):
        super(SerialRequester, self).__init__()
        self._queue = []

    def enqueue(self, fn, *args, **kwargs):
        """
        Add a request/function to the queue.

        Will be called on a separate thread.

        :param fn: function to call
        :param args: arguments for fn
        :param kwargs: keyword arguments for fn
        """
        self._queue.append((fn, args, kwargs))

    def mainloop(self, response_handler):
        """
        Called by the scraper's main run function.

        This loop should initiate queued tasks and on completion call the
        `response_handler`.

        No threads are created.

        :param response_handler: function to call with one argument, the
                                 response
        """
        # since this is sequential and blocking, when nothing is left in the
        # queue we're done
        while len(self._queue) > 0:
            fn, args, kwargs = self._queue.pop(0)
            response = fn(*args, **kwargs)
            response_handler(response)


"""
Final Project code
Amir Rahimov
Comp525
Dec 21, 2020
"""
import csv
import datetime
from collections import Counter
time_now = datetime.datetime.now()

class DevStats():
    """
    Find the requested information based on the functions from the TMDB
        database. It's purpose is to refer to the functions from the testing
        modules
    """
    @staticmethod
    def top_five_movies(filename):
        """
        Finds the top 5 popular movies for the past 10 years
        by popularity rating.
        Input: location of the csv file containing the dataset.
        Return: Dictionary histogram
        Keys: movie names
        Values:  popularity ratings.
        """
        data_structure = {}
        top_popularity = [0.0, 0.0, 0.0, 0.0, 0.0]
        top_title = ['', '', '', '', '']
        idx = 0
        date_rel_year = 0
        with open(filename, 'r', encoding='utf-8') as csvfile:
            # creating a csv reader object
            reader = csv.reader(csvfile)
            for aline in reader:
                title = aline[2]
                popularity = aline[15]
                if aline[9] != '' and aline[9] != 'Release_Date':
                    if '-' in aline[9][-4:]:
                        date_rel_year = int(aline[9][-2:]) + 2000
                    else:
                        date_rel_year = int(aline[9][-4:])
                if title != 'Title' and date_rel_year >= time_now.year - 10:
                    # Check if the new popularity is greater than the
                    # 1st top so far
                    if float(popularity) > top_popularity[0]:
                        # Move the top 4 down one position so we
                        # can insert the new top popularity
                        top_popularity[4] = top_popularity[3]
                        top_title[4] = top_title[3]
                        top_popularity[3] = top_popularity[2]
                        top_title[3] = top_title[2]
                        top_popularity[2] = top_popularity[1]
                        top_title[2] = top_title[1]
                        top_popularity[1] = top_popularity[0]
                        top_title[1] = top_title[0]
                        # Insert the new top popularity
                        top_popularity[0] = float(popularity)
                        top_title[0] = title
                    # Otherwise, check if the new popularity is greater
                    # than the 2nd top one
                    elif float(popularity) > top_popularity[1]:
                        # Move the top 3 down one position
                        top_popularity[4] = top_popularity[3]
                        top_title[4] = top_title[3]
                        top_popularity[3] = top_popularity[2]
                        top_title[3] = top_title[2]
                        top_popularity[2] = top_popularity[1]
                        top_title[2] = top_title[1]
                        # Insert the new 2nd popularity
                        top_popularity[1] = float(popularity)
                        top_title[1] = title
                    elif float(popularity) > top_popularity[2]:
                        top_popularity[4] = top_popularity[3]
                        top_title[4] = top_title[3]
                        top_popularity[3] = top_popularity[2]
                        top_title[3] = top_title[2]
                        top_popularity[2] = float(popularity)
                        top_title[2] = title
                    elif float(popularity) > top_popularity[3]:
                        top_popularity[4] = top_popularity[3]
                        top_title[4] = top_title[3]
                        top_popularity[3] = float(popularity)
                        top_title[3] = title
                    elif float(popularity) > top_popularity[4]:
                        top_popularity[4] = float(popularity)
                        top_title[4] = title
                    # construct a data_structure with top 5 titles
                    # and popularity
            for title in top_title:
                data_structure[title] = top_popularity[idx]
                idx += 1
        csvfile.close()
        return data_structure

    @staticmethod
    def get_top_budget(filename):
        """
        Finds the top 5  movies of all time by budget
        Input: would be a location and the name of the csv file containing the
            dataset.
        Return: List of tuples. Each tuple has the title and the revenue value
        """
        all_movie_budgets = {}
        with open(filename, 'r', encoding='utf-8') as csvfile:
            # creating a csv reader object
            reader = csv.reader(csvfile)
            for aline in reader:
                title = aline[2]
                budget = aline[-2]
                if title != 'Title' and budget != 'Budget' and budget != '':
                    all_movie_budgets[title] = int(budget)
            sorted_dict = Counter(all_movie_budgets)
            top_movie_budgets = sorted_dict.most_common(5)
            return top_movie_budgets

    @staticmethod
    def get_top_revenues(filename):
        """
        Finds the top 5  movies of all time by revenue.
        Input: would be a location and the name of the csv file containing the
            dataset.
        Return: List of tuples. Each tuple has the title and the revenue value
        """
        all_movie_revenues = {}
        with open(filename, 'r', encoding='utf-8') as csvfile:
            # creating a csv reader object
            reader = csv.reader(csvfile)
            for aline in reader:
                title = aline[2]
                revenue = aline[-1]
                if title != 'Title' and revenue != 'Revenue' and revenue != '':
                    all_movie_revenues[title] = int(revenue)
            sorted_dict = Counter(all_movie_revenues)
            top_movie_revenues = sorted_dict.most_common(5)
            return top_movie_revenues

    @staticmethod
    def get_top_genre(genre_submitted, filename):
        """
        Finds the top movie of the genre of all time by popularity.
        Input: The string containing the genre wanted and the location with the
            name of the csv file containing the
                dataset.
        Return: List of tuples. Each tuple has the title and the revenue value
        """
        try:
            genre_d = {}
            with open(filename, 'r', encoding='utf-8') as csvfile:
                # creating a csv reader object
                reader = csv.reader(csvfile)
                for aline in reader:
                    title = aline[2]
                    genre = aline[5]
                    popularity = aline[15]
                    if genre != 'Genres' and genre_submitted in genre:
                        genre_d[title] = float(popularity)
                top_genre = max(genre_d, key=genre_d.get)
            return top_genre
        except:
            None


import numpy as np
import pickle
import h5py
name = np.loadtxt('a.txt',dtype = 'S')

a = {}
for i in range(name.shape[0]):
    f =  open(name[i],'rb')
    a[i] = pickle.load(f)

b = np.array([val for (key,val) in a.items()])
with h5py.File('image_posi','w') as t:
    t.create_dataset('image',data = b)