import datetime
import time
import logging
# logging.basicConfig(level=logging.ERROR,
#                     format='\r\n%(asctime)s %(filename)s [line:%(lineno)d]  %(levelname)s  %(funcName)s %(message)s',
#                     datefmt='%a,%d %b %Y %H:%M:%S',
#                     filename='CamShots.log',
#                     filemode='a')
import random
# import Autel_Explorer.Camera.uiautomator2_cam_shots as uiauto
# import Autel_Explorer.Camera.uiautomator2_cam_shots_filter as uiauto
import Cam.nexus5x.uiautomator2_cam_shots_filter as uiauto
# import Autel_Explorer.Camera.uiautomator2_cam_shots_test as uiauto
import uiautomator2 as u2

d = uiauto.d
# d.implicitly_wait(60)
# d.wait_timeout = 60
test=uiauto.Camera()
# time.sleep(1)

# 1-1 app断开连接时相机功能是否可用 "1.app未连接飞行器时，点击首页“GO FLY”按钮，进入模块选择界面
# 2.点击相机模块 ，进入相机界面"
def camtohometocam():
    d(resourceId="com.autel.explorer:id/rl_left").click()
    time.sleep(1)
    d(resourceId="com.autel.explorer:id/tv_autel_home_start").click()

'''1-1, 1-2 app连上或断开飞行器，首页 --> 相机界面 '''
def homeTocam():
    d(resourceId="com.autel.explorer:id/tv_autel_home_start").click()

''' 1-3退出相机功能界面 '''
def home():
    time.sleep(1)
    d(resourceId="com.autel.explorer:id/rl_left").click()

'''2-1 拍照模式：单拍（默认拍照模式是单拍）'''
def singleShot2_1():
    test.SetPictureMode('SINGLE')
    test.shot()
    time.sleep(3)

''' 2-2 拍照模式：Burst连拍  3,5,7,10,14,'''
def burstShot2_2():
    listPara = ["3", "5", "7", "10", "14"]
    random.shuffle(listPara)
    for num in listPara:

        test.SetPictureMode('BURST',num)
        # num=int(num)+5
        test.shot()
        time.sleep(5)
        # time.sleep(num)

    test.SetPictureMode('SINGLE')
    time.sleep(3)

'''2-3 拍照模式：AEB连拍 3,5 '''
def AEBshot2_3():
    test.SetPictureMode('AEB','3')
    test.shot()
    time.sleep(5)

    test.SetPictureMode('AEB','5')
    test.shot()
    time.sleep(5)

    test.SetPictureMode('SINGLE')
    time.sleep(3)

'''2-4 拍照模式：定时拍 Auto'''

def auto_timmelapse2_4():
    test.SetPictureExpo('AUTO')
    test.scrollToFunc('FORMAT')
    listPara = ["5s", "7s", "10s", "20s", "30s", "60s"]
    # if d(resourceId="com.autel.explorer:id/tv_first_para", text=u"RAW+JPG").exists() or  d(resourceId=
    #      "com.autel.explorer:id/tv_first_para", text=u"RAW").exists():
    #
    #     listPara = ["5s", "7s", "10s", "20s","30s","60s"]
    # a =random.randint(len(listPara))
    # random.shuffle(listPara)        #打乱列表顺序
    print(listPara)
    for num in listPara:
        test.SetPictureMode('TIMELAPSE',num)
        print('timelapse',num)
        delay = int(num[:-1])
        # d(resourceId="com.autel.explorer:id/iv_camera_outer").click()
        # if d(resourceId="com.autel.explorer:id/toast_msg_tv", text='SD card is full').exists():
        #     test.camSetFormatsdcard('yes')
        #     time.sleep(8)
        #     print("reshot()")
        test.shot()
        time.sleep(delay+3)
        # d(resourceId="com.autel.explorer:id/iv_camera_outer").click()
        test.shot()
        time.sleep(5)

        # time.sleep(delay+2)
        # test.shot()
        # time.sleep(5)

    test.SetPictureMode('SINGLE')
    time.sleep(5)

'''2-5 拍照模式：定时拍 MANUAL'''
def manual_Timelapse2_5():
    test.SetPictureExpo('MANUAL')
    test.scrollToFunc('FORMAT')
    listPara = ["2s", "5s", "7s", "10s", "20s", "30s", "60s"]
    # if d(resourceId="com.autel.explorer:id/tv_first_para", text=u"RAW+JPG").exists() or d(resourceId=
    #                                                                                "com.autel.explorer:id/tv_first_para",
    #                                                                                text=u"RAW").exists():
    #     listPara = ["5s", "7s", "10s", "20s", "30s", "60s"]
    listPara = ["5s", "7s", "10s", "20s", "30s", "60s"]
    random.shuffle(listPara)  #打乱列表顺序
    for num in listPara:
        test.SetPictureMode('TIMELAPSE', num)
        print('timelapse', num)
        delay = int(num[:-1])
        test.shot()
        time.sleep(delay + 3)
        test.shot()
        time.sleep(5)

'''2-6 照片格式：JPG '''
def JPG2_6():
    #jpg 单拍
    test.SetPictureFomat('JPG')
    test.SetPictureMode('SINGLE')
    test.shot()

    '''
    time.sleep(2)

    #jpg BURST 连拍
    test.SetPictureFomat('JPG')

    for num in ['3','5','7','10','14',]:
        test.SetPictureMode('BURST',num)
        test.shot()
        time.sleep(5)

    #jpg TIMELAPSE 延时拍
    test.SetPictureFomat('JPG')
    for num in ['5s','7s','10s','20s','30s','60s']:
        test.SetPictureMode('TIMELAPSE',num)
        test.shot()
        time.sleep(61)
        test.shot()

    #jpg AEB
    test.SetPictureFomat('JPG')
    for num in ['3','5']:
        test.SetPictureMode('AEB',num)
        test.shot()
        time.sleep(5)
        test.shot()

    test.SetPictureFomat('JPG')
    test.SetPictureMode('SINGLE')
    test.shot()
    time.sleep(3)
    '''

'''2-7 照片格式：RAW '''
def RAW2_7():
    #RAW 单拍
    test.SetPictureFomat('RAW')
    test.SetPictureMode('SINGLE')
    test.shot()

    time.sleep(2)
    '''

    #RAW BURST
    test.SetPictureFomat('RAW')

    for num in ['3','5','7','10','14',]:
        test.SetPictureMode('BURST',num)
        test.shot()
        time.sleep(2)

    #RAW TIMELAPSE
    test.SetPictureFomat('RAW')
    for num in ['5s','7s','10s','20s','30s','60s']:
        test.SetPictureMode('TIMELAPSE',num)
        test.shot()
        time.sleep(61)
        test.shot()

    #RAW AEB
    test.SetPictureFomat('RAW')
    for num in ['3','5']:
        test.SetPictureMode('AEB',num)
        test.shot()
        time.sleep(5)
        test.shot()

    test.SetPictureFomat('JPG')
    test.SetPictureMode('SINGLE')
    test.shot()
    time.sleep(3)
    '''

'''2-8 照片格式：JPG+RAW  '''
def RAWJPG2_8():
    # RAW 单拍
    test.SetPictureFomat('RAW')
    test.SetPictureMode('SINGLE')
    test.shot()
    time.sleep(2)

    '''
    # RAW+JPG BURST
    test.SetPictureFomat('RAW+JPG')

    for num in ['3','5','7','10','14']:
        test.SetPictureMode('BURST',num)
        test.shot()
        time.sleep(2)

    #RAW+jpg TIMELAPSE

    test.SetPictureFomat('RAW+JPG')
    for num in ['5s','7s','10s','20s','30s','60s']:
        test.SetPictureMode('TIMELAPSE',num)
        test.shot()
        time.sleep(61)
        test.shot()

    #RAW+JPG AEB
    test.SetPictureFomat('RAW+JPG')
    for num in ['3','5']:
        test.SetPictureMode('AEB',num)
        test.shot()
        time.sleep(5)

    test.SetPictureFomat('JPG')
    test.SetPictureMode('SINGLE')
    test.shot()
    time.sleep(3)
    '''

'''2-9 照片大小：4：3（4000x3000）'''
def size43_2_9():
    test.SetPictureSize('4000x3000')
    test.shot()

    '''
    for i in [JPG2_6(),RAWJPG2_8()]:
        i
    print('\napp重置')
    camSetFormatReset3_24()
    '''

    time.sleep(2)

'''2-10 照片大小：16：9（4000x2250）'''
def size169_2_10():
    test.SetPictureSize('4000x2250')
    '''
    for i in [RAW2_7(),RAWJPG2_8()]:
        i
    '''
    test.shot()
    time.sleep(2)

##------------------------录相--------------------------###

# 2-1 NTSC:视频尺寸
''' 2-1 NTSC:视频尺寸

"1.点击NTSC/PAL，选择NTSC(默认值)
2.点击视频大小，选择4K+（4096x2160）
或选择4K（3840x2160）
或选择2.7K（2704x1520）
或选择1080P（1920x1080）
或选择720P（1280x720）
3.其他参数为默认参数
4.点击录像按钮，进行录像"
'''
''' 2-1 NTSC:视频尺寸'''
def NTSC2_1():
    test.setVedioStandard('NTSC')
    for res in ['4K+',"4K",'2.7K','1080P','720P']:
        test.setVideoReso(res)
        test.fast_record() #开始录
        time.sleep(5)
        #录相中返回首页,再返回,还在继续录相
        try:
            d(resourceId="com.autel.explorer:id/rl_left").click()
            time.sleep(1)
            d(resourceId="com.autel.explorer:id/tv_autel_home_start").click()
        except:
            pass
        time.sleep(10)
        test.stop_record() #停止录
    time.sleep(2)
    test.setVideoReso('4K')

# '''2-2 PAL:视频尺寸 '''
def PAL2_2():
    test.setVedioStandard('PAL')
    for res in ["4K+","4K","2.7K","1080P",'720P']:
        test.setVideoReso(res)
        time.sleep(3)
        test.fast_record() #开始录
        time.sleep(5)
        # 录相中返回首页,再返回,还在继续录相
        d(resourceId="com.autel.explorer:id/rl_left").click()
        time.sleep(1)
        d(resourceId="com.autel.explorer:id/tv_autel_home_start").click()
        time.sleep(5)
        test.stop_record()#停止录
        time.sleep(2)
    time.sleep(2)
    test.setVideoReso('4K')

'''2-3 视频格式：MOV'''
def mov2_3():
    test.setVedioFormat('MOV')
    time.sleep(3)
    test.fast_record()
    time.sleep(5)
    test.stop_record()

''' 2-4 视频格式：MP4'''
def mp4_2_4():
    test.setVedioFormat('MP4')
    time.sleep(3)
    test.fast_record()
    time.sleep(5)
    test.stop_record()
    time.sleep(2)

''' 2-6 视频编码格式'''
def H264_2_6():
    test.camSetVideoEncoding('H.264')
    time.sleep(3)
    test.fast_record()
    time.sleep(5)
    test.stop_record()
    time.sleep(5)

''' 2-7 视频编码格式'''
def H265_2_7():
    test.camSetVideoEncoding('H.265')
    time.sleep(3)
    test.fast_record()
    time.sleep(5)
    test.stop_record()
    time.sleep(5)

''' 2-8 PIV功能 '''
def PIV2_8():
    # for num in ['5S','10S','30S','60S','MANUAL']:
    for num in ['5S','10S','30S','MANUAL']:

        test.setVideoPIV(num)
        if num =='MANUAL':
            print('PIV MANUAL set.')
            time.sleep(3)
            test.fast_record()
            time.sleep(5)
            test.stop_record()
            time.sleep(5)
        else:
            num =int(num[:-1])+2
            print(num)
            time.sleep(3)

            test.fast_record()
            time.sleep(num)
            test.stop_record()
            time.sleep(5)

    time.sleep(2)

'''3-1 3-2 3-3风格：标准 风格：柔和 风格：风光 '''
def stytlePreset3_1():
    for num in  ['STD.','NEUT.','LAND.']:
        test.setVedioStyle(num)
        time.sleep(3)
        test.fast_record()
        time.sleep(5)
        test.stop_record()
        time.sleep(2)

'''3-4 风格：自定义 '''
def styleSelfDef3_4():

    for num in ["-3 ±0 ±0","-2 ±0 ±0","±0 +1 ±0","±0 +2 ±0",'±0 ±0 +2']:
        test.setVedioStyle(num) #注意 "." 不要忘了.
        time.sleep(3)
        test.record()
        time.sleep(5)
        test.stop_record()
        time.sleep(2)

''' 3-5 白平衡：自动  3-6 白平衡：晴天 3-7 白平衡：阴天 3-8 白平衡：白炽灯 '''
def WBPreSet3_5():
    test.SetPictureMode('SINGLE')
    for num in ['AUTO','SUNNY','CLOUDY','INCAN','NEON']:
        test.SetPictureWB(num)
        test.shot()
        time.sleep(2)

'''3-10 白平衡：自定义'''
def WBSelfDef3_10():
    test.SetPictureMode('SINGLE')
    for num in ['2000K','3000K','2900K','4200K','10000K','8000K','2100K','5600K','2300K']:
        test.SetPictureWB(num)
        test.shot()
        time.sleep(2)

'''3-11 色彩 '''
def color3_11():
    listPara = ["NONE", "LOG", "VIVID", "B&W", "ART", "FILM","BEACH","DREAM","CLASSIC","NOSTALGIC"]
    random.shuffle(listPara)
    for num in  listPara:
        test.SetPictureColor(num)
        test.shot()
        time.sleep(2)

'''3-12 拍摄模式：自动模式（A档）'''
def expoatuoshot3_12():
    test.SetPictureExpo('AUTO')
    test.shot()
    time.sleep(3)

''' 3-13  拍摄模式：手动模式（M档）'''
def expomanualshot():
    test.SetPictureExpo('MANUAL')
    test.shot()
    time.sleep(3)

'''3-14 A档：EV '''
def autoEV3_14():
    listPara = ["-3.0", "-2.7", "-2.3", "-2.0",
                                               # "-1.7", "-1.3", "-1.0",
                #"-0.7", "-0.3", "0","+0.3","+0.7",
                        "+1.0","+1.3","+1.7","+2.0","+2.3","+2.7","+3.0"]
    random.shuffle(listPara)
    print(listPara)
    for num in listPara:
        test.SetpictureEv(num)
        # test.shot()
        test.fast_shot()
        time.sleep(2)

    time.sleep(2)

'''3-15 M档：ISO '''
def manualISO3_15():

    listPara = ["100","200", "400", "800", "1600", "3200"]
    random.shuffle(listPara)
    print(listPara)
    for num in listPara:
        test.SetPictureIso(num)
        test.shot()
        time.sleep(2)

'''3-16 M档：快门 '''
def manualShutter3_16():
    listPara = ["1/8000", "1/6000", "1/5000",
                "1/4000", "1/3200", "1/2500", "1/2000", "1/1600", "1/1250", "1/1000",
                           "1/800", "1/640", "1/500",
                           "1/400", "1/320", "1/240", "1/200", "1/160", "1/120", "1/100", "1/80", "1/60", "1/50", "1/40",
                           "1/30", "1/25", "1/20", "1/15", "1/12.5",
                            "1/10", "1/8", "1/6.25", "1/5", "1/4", "1/3", "1/2.5", "1/2", "1/1.67", "1/1.25",
                            "1\"", "1.3\"",
                           "1.6\"", "2\"", "2.5\"", "3\"", "3.2\"",
                            "4\"", "5\"", "6\"", "8\""
                            ]
    random.shuffle(listPara)
    print(listPara)
    for num in listPara:
        print(num)
        test.SetPictureShutterOP(num)
        test.shot()
        if num.endswith("\""):
            num = int(float(num[0:-1]))
            time.sleep(num+5)
        else:
            time.sleep(5)

'''3-17 AE点测光模式 '''
def AE3_17():

    test.SetPictureExpo("AUTO")
    time.sleep(2)
    d.click(0.5, 0.5)
    time.sleep(5)
    d.click(0.6,0.3)

    test.SetPictureExpo("MANUAL") #manual 模式下不不能AE测光
    time.sleep(2)
    d.click(0.6,0.6)
    time.sleep(2)

'''3-18 数码变焦 '''
def digitalzoomshot3_18():

    listPara = ["1.0X", "2.0X", "3.0X", "4.0X","5.0X","6.0X","7.0X","8.0X"]
    random.shuffle(listPara)
    print(listPara)
    for num in listPara:
        test.SetPictureDigizoom(num)
        time.sleep(1)
        test.shot()
        time.sleep(5)
        try:
            d(resourceId="com.autel.explorer:id/rl_left").click()
            time.sleep(3)
            d(resourceId="com.autel.explorer:id/tv_autel_home_start").click()
            time.sleep(8)
        except:
            pass

    test.SetPictureDigizoom('1.0X')

'''3-19 云台角度调节 '''

def gimbal3_19():

    listPara = ['0°','30°','45°','50°','60°','90°']
    for num in listPara:
        test.GimbalAngle(num)
        time.sleep(2)
    test.GimbalAngle('0°')

''' 3-20  直方图 '''
def camsetHis3_20():
    test.camSetHis('on')
    try:
        d(resourceId="com.autel.explorer:id/rl_left").click()
    except:
        print('could not find the button for back to start page!')
    time.sleep(5)

    try:
        d(resourceId="com.autel.explorer:id/tv_autel_home_start").click()
    except:
        print('Could not find start button')
    time.sleep(8)
    test.fast_record()
    time.sleep(5)
    test.stop_record()
    time.sleep(2)
    test.camSetHis('off')

''' 3-21  过曝警告 '''
def camsetOverExp3_21():
    test.camSetOverExp('on')
    time.sleep(1)
    try:
        d(resourceId="com.autel.explorer:id/rl_left").click()
    except:
        pass
    time.sleep(3)
    try:
        d(resourceId="com.autel.explorer:id/tv_autel_home_start").click()
    except:
        pass
    time.sleep(3)
    test.camSetOverExp('off')
    time.sleep(1)
    d.click(0.47, 0.47)
    time.sleep(2)

''' 3-22  抗闪烁  '''
def camSetAntiFlicker3_22():
    listPara = ['Auto','50Hz','60Hz']
    for num in listPara:
        test.camSetAntiFlicker(num)
        time.sleep(2)
        # d.click(0.47, 0.47)
        test.fast_record()
        time.sleep(5)
        test.stop_record()
        time.sleep(2)

    time.sleep(2)

''' 3-23  网格  '''
def camSetGrid3_23():
    listPara = ['None','Grid','Grid + Line']
    for num in listPara:
        test.camSetGrid(num)
        # time.sleep(1)
        # test.shot() #  有问题，拍照后，录相延时不会停。
        time.sleep(5)
        test.fast_record()
        time.sleep(5)
        test.stop_record()
        time.sleep(5)
    test.camSetGrid('None')
    # d.click(0.47, 0.47)
    time.sleep(2)

''' 3-24  重置  '''
def camSetFormatReset3_24():

        test.camSettingsReset()
        time.sleep(20)

''' 3-25  格式化SD卡  '''
def camSetFormatsdcard3_25():
    for num in ['yes','no']:
        test.camSetFormatsdcard(num)
        time.sleep(5)

''' 3-26  相机版本号  '''
def camSetVersion3_26():

        try:
            d.implicitly_wait(5.0)
            d(resourceId="com.autel.explorer:id/rl_camera_setting").click()
        except:
            print('进入相机通用设置失败！')
            test.catchError()
        time.sleep(1)
        d.swipe(0.77, 0.8, 0.77, 0.4)
        time.sleep(1)
        d.swipe(0.77, 0.8, 0.77, 0.35)
        time.sleep(1)

        try:
            d.implicitly_wait(5.0)
            i=d(resourceId="com.autel.explorer:id/item_general_setting_value_tv", textStartsWith='V').get_text()
            print(i)
            d.click(0.3,0.5)

        except:
            print('获取相机版本失败!')
            d.click(0.3,0.5)

''' 3-27  全屏/退出全屏  '''
def camSetFullScreen3_27():
    d.swipe(0.475, 0.241,0.472, 0.696)
    time.sleep(1)
    d.click(0.47, 0.47)
    time.sleep(1)

timestamp = datetime.datetime.now()
i=0

while True:
    i+=1

    print('___________________________第 %d 轮开始____________________________'%i)
    print(datetime.datetime.now())

    singleShot2_1()
    time.sleep(3)

    print('\nBURST 延时拍照')
    burstShot2_2()
    time.sleep(3)

    print('\nAEB拍照')
    AEBshot2_3()
    time.sleep(3)

    print('\nTimelapse')
    auto_timmelapse2_4()
    time.sleep(3)

    print("\nJPG格式拍照")
    JPG2_6()
    time.sleep(3)

    print("\nRAW格式拍照")
    RAW2_7()
    time.sleep(3)

    print("\nRAW + JPG格式拍照")
    RAWJPG2_8()
    time.sleep(3)

    print('\照片大小4:3拍照')
    size43_2_9()
    time.sleep(3)

    print('\照片大小16:9拍照')
    size169_2_10()
    time.sleep(3)

    print('\n视频格式mov录相')
    mov2_3()
    time.sleep(3)

    print("\n视频格式mp4 录相")
    mp4_2_4()
    time.sleep(3)

    print('\n预设风格')
    stytlePreset3_1()
    time.sleep(5)

    '''
    print('\n自定义风格')
    styleSelfDef3_4()
    time.sleep(5)  #  停在这里！
    '''

    print('\n白平衡预设')
    WBPreSet3_5()
    time.sleep(5)   #pass

    print('\n自定义白平衡')
    WBSelfDef3_10()
    time.sleep(5)     #pass

    print('\n色彩')
    color3_11()
    time.sleep(5)  #pass

    print('\n自动曝光')
    expoatuoshot3_12()
    time.sleep(5)

    print('\n手动曝光')
    expomanualshot()
    time.sleep(5) #pass

    print('\nEV')
    autoEV3_14()
    time.sleep(5)  #pass

    print('\nISO')
    manualISO3_15()
    time.sleep(5) #pass

    print('\n快门')
    manualShutter3_16()
    time.sleep(3)   #pass

    print('\nAE')
    AE3_17()
    time.sleep(3)  #pass

    print('\n数码变焦')
    digitalzoomshot3_18()
    time.sleep(3)  #pass

    print('\n云台角度')
    gimbal3_19()
    time.sleep(10)  #pass

    print('\n抗闪烁')
    camSetAntiFlicker3_22()
    time.sleep(5)  #pass

    print('\nH264')
    H264_2_6()
    time.sleep(5)   #pass

    print('\nH265')
    H265_2_7()
    time.sleep(5)   #pass

    print('\napp重置')
    camSetFormatReset3_24()
    time.sleep(120)

    print('\nPIV视频录制')
    PIV2_8()
    time.sleep(5)  #pass

    print('\n显示柱状图')
    camsetHis3_20()
    time.sleep(5)   #pass

    print('\n网格设置')
    camSetGrid3_23()
    time.sleep(5)   #pass

    print('\n过曝')
    camsetOverExp3_21()
    time.sleep(5)     #pass

    print('\n相机版本')
    camSetVersion3_26()
    time.sleep(5)    #pass

    print('\n格式化sd卡')
    camSetFormatsdcard3_25()
    time.sleep(20)

    # print('\napp重置')
    # camSetFormatReset3_24()
    # time.sleep(120)

    time.sleep(30)
    print('___________________________第 %d 轮结束____________________________' % i)
    print(datetime.datetime.now())


import hermes_common
import hermes2d

mesh=hermes2d.PyMesh()
reader=hermes2d.PyMeshReaderH2DXML()
viewer=hermes2d.PyMeshView()

# Test of save / load of one mesh.
reader.load("domain.xml",mesh)
reader.save("domain2.xml",mesh)
reader.load("domain2.xml",mesh)

# Test of save / load of a mesh with multiple subdomains.
meshes = list()
mesh_whole_domain=hermes2d.PyMesh()
meshes.append(mesh_whole_domain)
mesh_bottom_left_corner=hermes2d.PyMesh()
meshes.append(mesh_bottom_left_corner)
mesh_complement=hermes2d.PyMesh()
meshes.append(mesh_complement)

reader.load("subdomains.xml", meshes)

for i in range(0,2):
  meshes[i].refine_all_elements()

reader.save("subdomains2.xml", meshes)
reader.load("subdomains2.xml", meshes)

# Test of MeshView
viewer.show(mesh)
viewer.wait_for_close()

viewer.show(mesh_whole_domain)
viewer.wait_for_close()
viewer.show(mesh_bottom_left_corner)
viewer.wait_for_close()
viewer.show(mesh_complement)
viewer.wait_for_close()


_author_ = 'Chris Donahue, ceuhanod@live.unc.edu, Onyen = ceuhanod'

from flask import (Flask, Response, request, render_template, make_response,
                   redirect)
from flask_restful import Api, Resource, reqparse, abort

import json
import random
import string
from datetime import datetime
from functools import wraps

with open('data.jsonld') as data:
    data = json.load(data)

def generate_id(size=6, chars=string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def error_if_package_not_found(package_id):
    if package_id not in data['packages']:
        message = "No package with ID: {}".format(package_id)
        abort(404, message=message)

def filter_and_sort_packages(query='', sort_by='time_received'):

    def matches_query(item):
        (package_id, package) = item
        text = package['title'] + package['recipient']
        return query.lower() in text

    def get_sort_value(item):
        (package_id, package) = item
        return package[sort_by]

    filtered_packages = filter(matches_query, data['packages'].items())

    return sorted(filtered_packages, key=get_sort_value, reverse=True)

def nonempty_string(x):
    s = str(x)
    if len(x) == 0:
        raise ValueError('string is empty')
    return s

new_package_parser = reqparse.RequestParser()
for arg in ['address', 'title', 'recipient']:
    new_package_parser.add_argument(
        arg, type=nonempty_string, required=True,
        help="'{}' is a required value".format(arg))

update_package_parser = reqparse.RequestParser()
update_package_parser.add_argument(
    'location', type=str, default='')
update_package_parser.add_argument(
    'access_code', type=int, default='')

query_parser = reqparse.RequestParser()
query_parser.add_argument(
    'query', type=str, default='')
query_parser.add_argument(
    'sort_by', type=str, choices=('location', 'time'), default='time')

def render_package_as_html(package):
    return render_template(
        'package+microdata+rdfa.html',
        package=package)

def render_package_inventory_as_html(packages):
    return render_template(
        'packages+microdata+rdfa.html',
        packages=packages)

class Package(Resource):

    def get(self, package_id):
        error_if_package_not_found(package_id)
        return make_response(
            render_package_as_html(
                data['packages'][package_id]), 200)

    def patch(self, package_id):
        error_if_package_not_found(package_id)
        package = data['packages'][package_id]
        update = update_package_parser.parse_args()
        package['location'] = update['location']
        if len(update['access_code'].strip()) > 0:
            package.setdefault('access_code', []).append(update['access_code'])
        return make_response(
            render_package_as_html(package), 200)

class PackageAsJSON(Resource):

      def get(self, package_id):
        error_if_package_not_found(package_id)
        package = data['packages'][package_id]
        package['@context'] = data['@context']
        return package

class PackageInventory(Resource):

    def get(self):
        query = query_parser.parse_args()
        return make_response(
            render_package_inventory_as_html(
                filter_and_sort_packages(**query)), 200)

    def post(self):
        package = new_package_parser.parse_args()
        package_id = generate_id()
        package['@id'] = 'request/' + package_id
        package['@type'] = 'packagecenter_locker_system:Package'

        package['time_received'] = datetime.isoformat(datetime.now())
        data['packages'][package_id] = package
        return make_response(
            render_package_inventory_as_html(
                filter_and_sort_packages()), 201)

class PackageInventoryAsJSON(Resource):
    def get(self):
        return data

app = Flask(__name__)
api = Api(app)
api.add_resource(PackageInventory, '/packages')
api.add_resource(PackageInventoryAsJSON, '/packages.json')
api.add_resource(Package, '/package/<string:package_id>')
api.add_resource(PackageAsJSON, '/package/<string:package_id>.json')

@app.route('/')
def index():
    return redirect(api.url_for(PackageInventory), code=303)

@app.after_request
def after_request(response):
    response.headers.add(
        'Access-Control-Allow-Origin', '*')
    response.headers.add(
        'Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add(
        'Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
    return response

if __name__ == '__main__':
    app.run(
        host='0.0.0.0',
        port=5555,
        debug=True,
        use_debugger=False,
        use_reloader=False)


import mxnet as mx
import model
import numpy as np
from collections import namedtuple
from skimage import io, transform

content_image = 'input/content_img.jpg'
style_image = 'input/style_img.jpg'
stop_stage = 0.0005
max_num_stage = 1000
output = 'output/out.jpg'

def PreContentImage(path, long_edge):
    img = io.imread(path)
    factor = float(long_edge) / max(img.shape[:2])
    new_size = (int(img.shape[0] * factor), int(img.shape[1] * factor))
    resized_img = transform.resize(img, new_size)
    sample = np.asarray(resized_img) * 256

    sample = np.swapaxes(sample, 0, 2)
    sample = np.swapaxes(sample, 1, 2)

    sample[0, :] -= 123.68
    sample[1, :] -= 116.779
    sample[2, :] -= 103.939
    return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2]))

def PreStyleImage(path, shape):
    img = io.imread(path)
    resized_img = transform.resize(img, (shape[2], shape[3]))
    sample = np.asarray(resized_img) * 256
    sample = np.swapaxes(sample, 0, 2)
    sample = np.swapaxes(sample, 1, 2)

    sample[0, :] -= 123.68
    sample[1, :] -= 116.779
    sample[2, :] -= 103.939
    return np.resize(sample, (1, 3, sample.shape[1], sample.shape[2]))

def PostImage(img):
    img = np.resize(img, (3, img.shape[2], img.shape[3]))
    img[0, :] += 123.68
    img[1, :] += 116.779
    img[2, :] += 103.939
    img = np.swapaxes(img, 1, 2)
    img = np.swapaxes(img, 0, 2)
    img = np.clip(img, 0, 255)
    return img.astype('uint8')

def SaveImage(img, filename):
    print('Готово ', filename)
    out = PostImage(img)
    io.imsave(filename, out)

dev = mx.gpu()
content_np = PreContentImage(content_image, 1920)
style_np = PreStyleImage(style_image, shape=content_np.shape)
size = content_np.shape[2:]

Executor = namedtuple('Executor', ['executor', 'data', 'data_grad'])

def get_loss(gram, content):
    gram_loss = []
    for i in range(len(gram.list_outputs())):
        gvar = mx.sym.Variable("target_gram_%d" % i)
        gram_loss.append(mx.sym.sum(mx.sym.square(gvar - gram[i])))
    cvar = mx.sym.Variable("target_content")
    content_loss = mx.sym.sum(mx.sym.square(cvar - content))
    return mx.sym.Group(gram_loss), content_loss

def style_gram_symbol(input_size, style):
    _, output_shapes, _ = style.infer_shape(data=(1, 3, input_size[0], input_size[1]))
    gram_list = []
    grad_scale = []
    for i in range(len(style.list_outputs())):
        shape = output_shapes[i]
        x = mx.sym.Reshape(style[i], target_shape=(int(shape[1]), int(np.prod(shape[2:]))))

        gram = mx.sym.FullyConnected(x, x, no_bias=True, num_hidden=shape[1])
        gram_list.append(gram)
        grad_scale.append(np.prod(shape[1:]) * shape[1])
    return mx.sym.Group(gram_list), grad_scale

model_module =  model
style, content = model_module.get_symbol()
gram, gscale = style_gram_symbol(size, style)
model_executor = model_module.get_executor(gram, content, size, dev)
model_executor.data[:] = style_np
model_executor.executor.forward()
style_array = []
for i in range(len(model_executor.style)):
    style_array.append(model_executor.style[i].copyto(mx.cpu()))

model_executor.data[:] = content_np
model_executor.executor.forward()
content_array = model_executor.content.copyto(mx.cpu())
del model_executor

style_loss, content_loss = get_loss(gram, content)
model_executor = model_module.get_executor(
    style_loss, content_loss, size, dev)

grad_array = []
for i in range(len(style_array)):
    style_array[i].copyto(model_executor.arg_dict["target_gram_%d" % i])
    grad_array.append(mx.nd.ones((1,), dev) * (float(1) / gscale[i]))
grad_array.append(mx.nd.ones((1,), dev) * (float(10)))

print([x.asscalar() for x in grad_array])
content_array.copyto(model_executor.arg_dict["target_content"])

img = mx.nd.zeros(content_np.shape, ctx=dev)
img[:] = mx.rnd.uniform(-0.1, 0.1, img.shape)

lr = mx.lr_scheduler.FactorScheduler(step=80, factor=.9)

optimizer = mx.optimizer.SGD(
    learning_rate = 0.001,
    wd = 0.0005,
    momentum=0.1,
    lr_scheduler = lr)
optim_state = optimizer.create_state(0, img)

old_img = img.copyto(dev)
c_norm = 1 * np.prod(img.shape)

for e in range(max_num_stage):
    img.copyto(model_executor.data)
    model_executor.executor.forward()
    model_executor.executor.backward(grad_array)
    gnorm = mx.nd.norm(model_executor.data_grad).asscalar()
    if gnorm > clip_norm:
        model_executor.data_grad[:] *= c_norm / gnorm

    optimizer.update(0, img, model_executor.data_grad, optim_state)
    new_img = img
    stage = (mx.nd.norm(old_img - new_img) / mx.nd.norm(new_img)).asscalar()

    old_img = new_img.copyto(dev)
    print('этап ' , e , ' коэффициент изменения', stage)
    if stage < stop_stage:
        print('Завершено.')
        break

'''End'''
SaveImage(new_img.asnumpy(), output)


# coding: utf-8

get_ipython().magic('matplotlib')

import sys
import os
import argparse
import glob
import time
import re
import numpy as np
import scipy
import pandas as pd
import pims
from PIL import Image
from skimage import io
from skimage import color as col
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import matplotlib.patches as patches
from matplotlib.animation import FuncAnimation

parser = argparse.ArgumentParser();
parser.add_argument('-i', '--image', help='a directory that contains all the images for processing');
parser.add_argument('-f', '--frames', type=int, default=100, help='number of time frames in image stacks');
parser.add_argument('-t', '--time', type=int, default=20, help='time interval between frames. Default value: 20s')
parser.add_argument('-s', '--stamp', action='store_true', default=False, help='include time stamp on movie.');
parser.add_argument('-b', '--scalebar', type=float, default=0, help='Annotate image with scale bar of user defined length (in um)');

arg = parser.parse_args();

image_dir = arg.image;
num_frames = arg.frames;
time_interval = arg.time;
scalebar = arg.scalebar;
stamp = arg.stamp;

frame_number = 1;
os.chdir(image_dir);
image_list = glob.glob('*.tif');
for i in image_list:
    cur_image = i;
    m = re.search('(Batch\d+_.*_XY\d+_.*\d+).*.tif', cur_image);
    match = m.group(1);

    im = io.imread(cur_image)

    fig = plt.figure(figsize=(5,5), frameon=False);
    ax = fig.add_axes([0,0,1,1], xlim=(0,512), ylim=(512,0), aspect='equal', frameon=False);
    ax.set_axis_off();
    plt.margins(0,0)
    ax.set_frame_on(False);
    ax.set_xlim([0, 512]);
    ax.set_ylim([512, 0]);

    im_now = im[frame_number, :, :, :];
    implt = plt.imshow(im_now);

    if stamp:
        frame_string = "Time: " + str(frame_number * time_interval) + " sec";
        frame_text = ax.text(x=10, y=30, s=frame_string, fontsize=16, weight='bold', color='white', fontname='Helvetica');

    if scalebar != 0:
        pixel_len = (scalebar / 0.091) * sf;
        ax.hlines(10, (500 - pixel_len), 500, color='w')

    def update (frame_number):
        im_now = im[frame_number, :, :, :];
        implt.set_data(im_now);
        if stamp:
            frame_string = "Time: " + str(frame_number * 20) + " sec";
            frame_text.set_text(frame_string);

        return

    m = re.search('(Batch\d+_.*_XY\d+.*).tif', cur_image);
    match = m.group(1);
    animation = FuncAnimation(fig, update, interval=70, repeat=True);
    animation.save(match + '.mp4', writer='ffmpeg', dpi=300, bitrate=15000, fps=14);
    plt.show();


#maximum subarray problem
#max crossing subarray
def max_crossing_subarray(ipArray,low,mid,high):
  left_max_sum = None
  max_sum = 0
  for i in range(mid,low-1,-1):
    max_sum = max_sum + ipArray[i]
    if max_sum > left_max_sum:
      left_max_sum = max_sum
      left_max_low = i

  right_max_sum = None
  max_sum = 0
  for i in range(mid+1,high+1):
    max_sum = max_sum + ipArray[i]
    if max_sum > right_max_sum:
      right_max_sum = max_sum
      right_min_high = i

  return left_max_sum+right_max_sum,left_max_low,right_min_high

#max subarray
def max_subarray(ipArray, low, high):
	if low == high:
		return ipArray[low],low,high
	else:
		#print(ipArray)
		mid = (low + high) // 2
		print("mid pt: " + str(mid))

		left_max, left_max_low, left_min_high = max_subarray(ipArray, low, mid)

		right_max, right_max_low, right_min_high = max_subarray(ipArray, mid + 1, high)

		#max crossing subarray
		crossing_max, crossing_max_low, crossing_min_high = max_crossing_subarray(ipArray,low,mid,high)

		if left_max >= right_max and left_max >= crossing_max:return left_max, left_max_low, left_min_high
		elif right_max >= crossing_max:return right_max, right_max_low, right_min_high
		else:return crossing_max,crossing_max_low, crossing_min_high

A = [-2, -3, 4, -1, -2, 1, 5, -3]
maxVal, maxlow, minhigh = max_subarray(A, 0, len(A)-1)
print("maxVal: " + str(maxVal) + " low: " + str(maxlow) + " high: " +str(minhigh))


from Utils import *
import random
def randomBodies(num_bodies, world_bounds, v_bounds, m_bounds, r_seed=42):

    random.seed(r_seed)
    scaleX = lambda x: (x-0.5)*world_bounds
    scaleV = lambda x: (x-0.5)*v_bounds
    scaleM = lambda x: x*m_bounds

    init_bodies = [Body(
        (scaleX(random.random()), scaleX(random.random()), scaleX(random.random())),
        (scaleV(random.random()), scaleV(random.random()), scaleV(random.random())),
        scaleM(random.random())
        ) for i in range(num_bodies)]

    return init_bodies

def HugeGalaxy():
    snap_shot_t = 0.1
    final_t = 10
    dt = 0.1

    bodies = randomBodies(10000, 10000, 4, 5)
    sim_setup = SimArgs(snap_shot_t, final_t, dt, bodies)

    return {"setup":sim_setup}

HugeGalaxySpeedTest = SpeedTestCase("Galaxy Speed", "Loads of bodies", HugeGalaxy)

def QuickGalaxy():
    snap_shot_t = 0.1
    final_t = 10
    dt = 0.1

    bodies = randomBodies(1000, 10000, 4, 5)
    sim_setup = SimArgs(snap_shot_t, final_t, dt, bodies)

    return {"setup":sim_setup}

QuickGalaxySpeedTest = SpeedTestCase("Quick Galaxy Speed", "Many bodies, few timesteps", QuickGalaxy)

def MediumGalaxy():
    snap_shot_t = 0.1
    final_t = 10
    dt = 0.1

    bodies = randomBodies(3000, 10000, 4, 5)
    sim_setup = SimArgs(snap_shot_t, final_t, dt, bodies)

    return {"setup":sim_setup}

MediumGalaxySpeedTest = SpeedTestCase("Medium", "Many bodies, few timesteps", MediumGalaxy)

def FineGalaxy():
    snap_shot_t = 0.1
    final_t = 10
    dt = 0.0025

    bodies = randomBodies(500, 10000, 4, 5)
    sim_setup = SimArgs(snap_shot_t, final_t, dt, bodies)

    return {"setup":sim_setup}

FineGalaxySpeedTest = SpeedTestCase("Fine grain speed", "Medium bodies at small ts", FineGalaxy)

def UltraFineGalaxy():
    snap_shot_t = 0.1
    final_t = 10
    dt = 0.00001

    bodies = randomBodies(20, 10000, 4, 5)
    sim_setup = SimArgs(snap_shot_t, final_t, dt, bodies)

    return {"setup":sim_setup}

UltraFineGalaxySpeedTest = SpeedTestCase("Ultra Fine grain speed", "Low bodies at small ts", UltraFineGalaxy)

def ClusterF():
    snap_shot_t = 0.1
    final_t = 10
    dt = 0.002

    bodies = randomBodies(500, 60, 4, 5)
    sim_setup = SimArgs(snap_shot_t, final_t, dt, bodies)

    return {"setup":sim_setup, "cluster":True}

ClusterFSpeedTest = SpeedTestCase("Cluster F speed", "Low bodies at small ts", ClusterF)


'''Croc Cloud EC2 Address Pool.'''

from boto.ec2.ec2object import EC2Object, TaggedEC2Object

class AddressPool(TaggedEC2Object):

    def __init__(self, connection=None, id=None):
        super(AddressPool, self).__init__(connection)
        self.connection = connection
        self.id = id
        self.description = None
        self.total_address_count = None
        self.total_available_address_count = None
        self.pool_address_ranges = AddressRangeList()

    def __repr__(self):
        return 'AddressPool:{0}'.format(self.id)

    def startElement(self, name, attrs, connection):
        retval = super(AddressPool, self).startElement(name, attrs, connection)
        if retval is not None:
            return retval
        if name == 'poolAddressRangeSet':
            return self.pool_address_ranges
        else:
            return None

    def endElement(self, name, value, connection):
        if name == 'poolId':
            self.id = value
        elif name == 'description':
            self.description = value
        elif name == 'totalAvailableAddressCount':
            self.total_available_address_count = int(value)
        elif name == 'totalAddressCount':
            self.total_address_count = int(value)
        elif name == 'item':
            pass
        else:
            setattr(self, name, value)

class AddressRangeList(list):

    def startElement(self, name, attrs, connection):
        if name == 'item':
            self.append(AddressRange(self))
            return self[-1]
        return None

    def endElement(self, name, value, connection):
        pass

class AddressRange(object):

    def __init__(self, parent=None):
        self.parent = parent
        self.address_count = None
        self.last_address = None
        self.available_address_count = None
        self.first_address = None

    def __repr__(self):
        return 'AddressRange:{0}-{1}'.format(self.first_address, self.last_address)

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'addressCount':
            self.address_count = int(value)
        elif name == 'lastAddress':
            self.last_address = value
        elif name == 'availableAddressCount':
            self.available_address_count = int(value)
        elif name == 'firstAddress':
            self.first_address = value
        elif name == 'item':
            pass
        else:
            setattr(self, name, value)

class ByoipCidr(EC2Object):

    def __init__(self, connection=None, id=None):
        super(ByoipCidr, self).__init__(connection)
        self.connection = connection
        self.id = id
        self.cidr = None
        self.description = None
        self.status_message = None
        self.state = None

    def __repr__(self):
        return 'ByoipCidr:{0}'.format(self.cidr)

    def startElement(self, name, attrs, connection):
        return super(ByoipCidr, self).startElement(name, attrs, connection)

    def endElement(self, name, value, connection):
        if name == 'cidr':
            self.id = value
            self.cidr = value
        elif name == 'description':
            self.description = value
        elif name == 'statusMessage':
            self.status_message = value
        elif name == 'state':
            self.state = value
        elif name == 'item':
            pass
        else:
            setattr(self, name, value)


'''
Created on Sep 5, 2012

@author: azar
'''
import unittest
from scipy.stats import uniform
from scipy.stats import expon as exponential
from src.Auctions.VirtualValuation import virtualValuation

class Test(unittest.TestCase):
    values = [0,0.5,0.7,1]
    params = [1,2,3,4,5,23.3,0.3]

    def testUniform(self):
        for value in self.values:
            expected = 2 * value -  1
            obtained = virtualValuation(value, uniform)
            self.assertAlmostEqual(expected, obtained, msg="Given value " + str(value) + " and distribution " + str(uniform) + ". Expected " + str(expected) + " but obtained  " + str(obtained) )

    def testExponential(self):
        for value in self.values:
            for parameter in self.params:
                expected = value -  parameter
                obtained = virtualValuation(value, exponential(scale=parameter))
                self.assertAlmostEqual(expected, obtained, msg="Given value " + str(value) + " and exponential distribution with parameter " + str(parameter) + ". Expected " + str(expected) + " but obtained  " + str(obtained) )

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()


#!/usr/bin/python3
import csv, time
from os import system, listdir
from sys import argv

if len(argv) < 2:
	print('Usage: ' + argv[0] + ' keys_mix')
	exit()

EXP_NAME = str(argv[1])

filesToNumOfLines = {}
for file in listdir('build'):
	if file.startswith('memrec') and file.endswith(EXP_NAME + '.csv'):
		with open('./build/'+file) as f:
			r = csv.reader(f, delimiter='\t')
			lines = list(r)
			filesToNumOfLines[file] = len(lines)
maxLines = max(filesToNumOfLines.values())
numOfFiles = len(filesToNumOfLines)
numOfRows = maxLines+1
numOfCols = numOfFiles+1
files = list(filesToNumOfLines.keys())
algs = []
algsToFiles = {}
for i,file in enumerate(files):
	alg = files[i].split('-')[1]
	algs.append(alg)
	algsToFiles[alg] = file
algs.sort()

with open('memrec_temp.tsv','w') as f2:

	# Expand spreadsheet
	w = csv.writer(f2, delimiter='\t')
	emptyLine = [' ']*numOfCols
	for i in range(numOfRows):
		w.writerow(emptyLine.copy())

with open('memrec_temp.tsv','r') as f2:

	# Load empty spreadsheet
	r2 = csv.reader(f2, delimiter='\t')
	lines2 = list(r2)

with open('memrec_temp.tsv','w') as f2:

	# Write title
	w = csv.writer(f2, delimiter='\t')
	lines2[0][0] = '#TIME (sec)'
	for j,alg in enumerate(algs):
		lines2[0][j+1] = alg+' (GB)'

	# Create time column
	for i in range(numOfRows-1):
		lines2[i+1][0] = i

	# Write columns
	for j,alg in enumerate(algs):
		with open('./build/'+algsToFiles[alg]) as f:
			r = csv.reader(f, delimiter='\t')
			lines = list(r)
			outIndex = 1

			for i in range(1,len(lines)):
				# Skip empty lines
				if lines[i][1] == '':
					continue
				# Convert in GB and write memory value
				lines2[outIndex][j+1] = round(int(lines[i][1])/1000000,2)
				outIndex += 1

			# Pad with zeroes
			for i in range(outIndex,numOfRows):
				lines2[outIndex][j+1] = 0
				outIndex += 1
	w.writerows(lines2)

# Archive
DATETIME = time.strftime('%Y-%m-%d-%H..%M')
system('mv memrec_temp.tsv experiments/expmem' + '_' + DATETIME + '_' + EXP_NAME + '.tsv')


## Training a CNN network for audio classification using MFCC features extracted from UrbanSound8K dataset
## Author: leopauly ! leopauly314@gmail.com

import os
import pickle

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
#from sklearn.model_selection import train_test_split

'''
dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension (the depth) is at index 1,
in 'tf' mode is it at index 3. It defaults to the  image_dim_ordering value found in your
Keras config file at ~/.keras/keras.json. If you never set it, then it will be "tf".

print K.image_dim_ordering()
'''

#---------------------------------------------------------------------------------------------------------------#

np.random.seed(1337)  # for reproducibility
# Network parameters
data_w = 40
data_h = 40
n_classes = 10
n_filters_1 = 32
n_filters_2 = 64
d_filter = 3
p_drop_1 = 0.25
p_drop_2 = 0.50

# Traning parameters
p_test = 0.2
p_train = 1-p_test
batch_size = 32
nb_epoch = 50

#---------------------------------------------------------------------------------------------------------------#

def layer_info(model, i):
    print("INPUT # ", i)
    print("at", model.get_input_at(i))
    print("mask_at", model.get_input_mask_at(i))
    print("shape_at", model.get_input_shape_at(i))
    # print("shape_for", model.get_input_shape_for(i))
    print("OUTPUT # ", i)
    print("at", model.get_output_at(i))
    print("mask_at", model.get_output_mask_at(i))
    print("shape_at", model.get_output_shape_at(i))

#---------------------------------------------------------------------------------------------------------------#

## Getting data
print("Start loading data")
fd = open("/nobackup/leopauly/UrabanSound8k_Stored_mfcc/data_x_librosa_train_1.pkl", 'rb')
fd2 = open("/nobackup/leopauly/UrabanSound8k_Stored_mfcc/data_y_librosa_train_1.pkl", 'rb')
features = pickle.load(fd,encoding='bytes')
labels = pickle.load(fd2,encoding='bytes')
print("Data loaded")

#X_train,X_test,Y_train,Y_test=train_test_split(features, label, test_size=p_test)
rnd_indices = np.random.rand(len(labels)) < p_train
X_train = features[rnd_indices]
Y_train = labels[rnd_indices]
X_test = features[~rnd_indices]
Y_test = labels[~rnd_indices]

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255

# Fix for keras
Y_train = Y_train.reshape((-1, 1))
Y_test = Y_test.reshape((-1, 1))

print('Size of trainning data_x:',X_train.shape)
print('Size of trainning data_y:',Y_train.shape)
print('Size of test data_x:',X_test.shape)
print('Size of test data_y:',Y_test.shape)

#---------------------------------------------------------------------------------------------------------------#

## CNN model
model = Sequential()

# First layer
model.add(Convolution2D(n_filters_1, d_filter, d_filter, border_mode='valid', input_shape=(data_w, data_h, 3)))
model.add(Activation('relu'))

# Second layer
model.add(Convolution2D(n_filters_1, d_filter, d_filter))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# Drop layer
model.add(Dropout(p_drop_1))

# Third layer
model.add(Convolution2D(n_filters_2, d_filter, d_filter, border_mode='valid'))
model.add(Activation('relu'))

# Fouth layer
model.add(Convolution2D(n_filters_2, d_filter, d_filter))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
# Drop layer
model.add(Dropout(p_drop_1))

## Used to flat the input (1, 10, 2, 2) -> (1, 40)
model.add(Flatten())

# Full Connected layer
model.add(Dense(256))
model.add(Activation('relu'))
# Drop layer
model.add(Dropout(p_drop_2))

# Output Full Connected layer
model.add(Dense(n_classes))
model.add(Activation('softmax'))

#---------------------------------------------------------------------------------------------------------------#

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='sparse_categorical_crossentropy',optimizer='adadelta',metrics=['accuracy'])
model.fit(X_train, Y_train,batch_size=batch_size,nb_epoch=nb_epoch,validation_split=0,shuffle=False)

#---------------------------------------------------------------------------------------------------------------#

score = model.evaluate(X_test, Y_test, verbose=1)
print('Test score:', score[0])
print('Test accuracy:', score[1])

#---------------------------------------------------------------------------------------------------------------#

# serialize model to JSON
model_json = model.to_json()
with open("/nobackup/leopauly/S2LStage2/logdir_0/audio_classifier_mfcc_1.json", "w") as json_file:
    json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("/nobackup/leopauly/S2LStage2/logdir_0/audio_classifier_mfcc_1.h5")
print("Saved model to disk")

#---------------------------------------------------------------------------------------------------------------#


from django.test import TestCase
from config import settings
import mock

class DatabaseSettingsTest(TestCase):
  @mock.patch('config.settings.USE_DOCKER', True)
  @mock.patch('config.settings.DATABASES', {
    "default": {
      "ENGINE": "django.db.backends.postgresql",
      "HOST": "db",
    }
  })
  def test_when_use_docker_database_is_postgres(self):
    self.assertEqual(settings.DATABASES['default']['ENGINE'], 'django.db.backends.postgresql')


# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>

"""Integration tests for Assessment action and status change."""
import itertools
import ddt

from ggrc.models import all_models

from integration import ggrc
from integration.ggrc.models import factories
from integration.ggrc_basic_permissions.models \
    import factories as rbac_factories

@ddt.ddt
class TestAssessmentCompleteWithAction(ggrc.TestCase):
  """Test Assessment complete status with action."""
  def setUp(self):
    """Set up audit and cad for test cases."""
    super(TestAssessmentCompleteWithAction, self).setUp()
    self.api = ggrc.api_helper.Api()
    with factories.single_commit():
      self.audit = factories.AuditFactory()
      self.asmt = factories.AssessmentFactory(audit=self.audit,
                                              status="In Progress")
      self.evidence = factories.EvidenceFactory()

  def _prepare_mandatory_evidence_cad(self):
    """Prepare mandatory evidence"""
    cad = factories.CustomAttributeDefinitionFactory(
        attribute_type="Dropdown",
        definition_type="assessment",
        definition_id=self.asmt.id,
        multi_choice_options="value_1,value_2",
        multi_choice_mandatory="0,2",
    )
    factories.CustomAttributeValueFactory(
        custom_attribute=cad,
        attributable=self.asmt,
        attribute_value="value_2",
    )

  @ddt.data(("In Review", "In Review"),
            ("Verified", "Completed"),
            ("Completed", "Completed"),
            ("Deprecated", "Deprecated"))
  @ddt.unpack
  def test_add_evidence_and_status(self, status, result_status):
    """Test add evidence and update {0} status to {1}
    in single PUT."""
    asmt_id = self.asmt.id

    # putting assessment to 'In Progress' state
    self.api.put(self.asmt, {
        "actions": {"add_related": [{"id": self.evidence.id,
                                     "type": "Evidence"}]},
    })
    new_evidence = factories.EvidenceFactory()
    response = self.api.put(self.asmt, {
        "status": status,
        "actions": {"add_related": [{"id": new_evidence.id,
                                     "type": "Evidence"}]},
    })
    self.assertEqual(response.status_code, 200)
    response_asmt = response.json["assessment"]
    self.assertEqual(response_asmt["status"], result_status)

    asmt = all_models.Assessment.query.get(asmt_id)
    self.assertEqual(asmt.status, result_status)

  @ddt.data(("In Review", "In Review"),
            ("Verified", "Completed"),
            ("Completed", "Completed"),
            ("Deprecated", "Deprecated"))
  @ddt.unpack
  def test_remove_evidence_and_status(self, status, result_status):
    """Test remove evidence and update {0} status to {1}
    in single PUT."""
    asmt_id = self.asmt.id

    # putting assessment to 'In Progress' state
    self.api.put(self.asmt, {
        "actions": {"add_related": [{"id": self.evidence.id,
                                     "type": "Evidence"}]},
    })
    response = self.api.put(self.asmt, {
        "status": status,
        "actions": {"remove_related": [{"id": self.evidence.id,
                                        "type": "Evidence"}]},
    })
    self.assertEqual(response.status_code, 200)
    response_asmt = response.json["assessment"]
    self.assertEqual(response_asmt["status"], result_status)

    asmt = all_models.Assessment.query.get(asmt_id)
    self.assertEqual(asmt.status, result_status)

  @ddt.data("In Review", "Verified", "Completed")
  def test_remove_required_evidence(self, status):
    """Test remove mandatory evidence and update
    status to {0} in single PUT. Result status
    should be `In Progress`"""
    asmt_id = self.asmt.id
    self._prepare_mandatory_evidence_cad()
    rel = factories.RelationshipFactory(
        source=self.asmt,
        destination=self.evidence,
    )
    rel_id = rel.id
    response = self.api.put(self.asmt, {
        "status": status,
        "actions": {"remove_related": [{"id": self.evidence.id,
                                        "type": "Evidence"}]},
    })
    self.assertEqual(response.status_code, 400)
    message = response.json["message"]
    self.assertEqual(message, "CA-introduced completion preconditions "
                              "are not satisfied. Check preconditions_failed"
                              " of items of self.custom_attribute_values")
    asmnt = all_models.Assessment.query.filter_by(id=asmt_id).first()
    self.assertEqual(asmnt.status, "In Progress")

    relationship = all_models.Relationship.query.get(rel_id)
    self.assertIsNotNone(relationship)

  def test_remove_req_evid_deprecated(self):
    """Test remove mandatory evidence and update
    status to deprecated in single PUT. Result status
    should be `Deprecated`"""
    asmt_id = self.asmt.id
    self._prepare_mandatory_evidence_cad()
    rel = factories.RelationshipFactory(
        source=self.asmt,
        destination=self.evidence,
    )
    rel_id = rel.id
    response = self.api.put(self.asmt, {
        "status": "Deprecated",
        "actions": {"remove_related": [{"id": self.evidence.id,
                                        "type": "Evidence"}]},
    })
    self.assertEqual(response.status_code, 200)
    asmnt = all_models.Assessment.query.filter_by(id=asmt_id).first()
    self.assertEqual(asmnt.status, "Deprecated")

    relationship = all_models.Relationship.query.get(rel_id)
    self.assertIsNone(relationship)

  def test_remove_req_evid_progress(self):
    """Test remove mandatory evidence and update
    status to deprecated in single PUT. Result status
    should be `In Progress`"""
    asmt_id = self.asmt.id
    self._prepare_mandatory_evidence_cad()
    rel = factories.RelationshipFactory(
        source=self.asmt,
        destination=self.evidence,
    )
    rel_id = rel.id
    response = self.api.put(self.asmt, {
        "status": "In Progress",
        "actions": {"remove_related": [{"id": self.evidence.id,
                                        "type": "Evidence"}]},
    })
    self.assertEqual(response.status_code, 200)
    asmnt = all_models.Assessment.query.filter_by(id=asmt_id).first()
    self.assertEqual(asmnt.status, "In Progress")

    relationship = all_models.Relationship.query.get(rel_id)
    self.assertIsNone(relationship)

  @ddt.data(
      *itertools.product(("Assignees", "Creators", "Verifiers"),
                         ("Creator", "Editor", "Reader"))
  )
  @ddt.unpack
  # pylint: disable=invalid-name
  def test_remove_related_forbidden_for_system_roles(self, role, system_role):
    """Test system roles are not allowed to delete related evidence"""
    asmt_id = self.asmt.id
    with factories.single_commit():
      self._prepare_mandatory_evidence_cad()
      factories.RelationshipFactory(
          source=self.asmt,
          destination=self.evidence,
      )
      person = factories.PersonFactory()
      creator_role = all_models.Role.query.filter(
          all_models.Role.name == system_role
      ).one()
      rbac_factories.UserRoleFactory(role=creator_role, person=person)
      factories.AccessControlPersonFactory(
          ac_list=self.asmt.acr_name_acl_map[role],
          person=person,
      )
    evid_id = self.evidence.id
    self.api.set_user(person)
    response = self.api.put(all_models.Assessment.query.get(asmt_id), {
        "actions": {"remove_related": [{"id": evid_id,
                                        "type": "Evidence"}]},
    })
    self.assert403(response)
    evidence = all_models.Evidence.query.get(evid_id)
    self.assertIsNotNone(evidence)


from .pssdlowrank import PSSDLowRank
from .exceptions import VectorError, NonSquareError

class PSSD(PSSDLowRank):
    def __init__(self, size, triv="expm"):
        r"""
        Manifold of symmetric positive semidefinite matrices

        Args:
            size (torch.size): Size of the tensor to be applied to
            triv (str or callable): Optional.
                A map that maps :math:`\operatorname{Skew}(n)` onto the orthogonal
                matrices surjectively. This is used to optimize the Q in the eigenvalue
                decomposition. It can be one of `["expm", "cayley"]` or a custom
                callable. Default: `"expm"`
        """
        super().__init__(size, PSSD.rank(size), triv)

    @classmethod
    def rank(cls, size):
        if len(size) < 2:
            raise VectorError(cls.__name__, size)
        n, k = size[-2:]
        if n != k:
            raise NonSquareError(cls.__name__, size)
        return n


from utilidades import numeros as nu

def moeda(n):
    return str(f'{n:.2f}').replace('.', ',')

def tit(msg):
    print('- ' * 25)
    print(f'{msg:^46}')
    print('- ' * 25)

def resumo(n, ac, ds):
    nota = {}
    nota['Preço analisado'] = moeda(n)
    nota['Dobro do preço'] = nu.dobro(n, mo=True)
    nota['Metade do preço'] = nu.metade(n, mo=True)
    nota[f'{ac}% acréscimo'] = nu.aumentar(n, ac, mo=True)
    nota[f'{ds}% desconto'] = nu.diminuir(n, ds, mo=True)
    tit('RESUMO DO VALOR')
    for k, v in nota.items():
        print(f'{k:<32}{"R$":>10}{v:>7}')
    print('- ' * 25)

def leiadin(msg):
    while True:
        n = input(msg)
        try:
            return float(n.replace(',', '.'))
        except ValueError:
            print('\033[31mValor inválido!\033[m')


# reads parameters from config.txt and changes .ski file
# begin line with 'SKIRT/' for skirt parameters
# use a unique parent header after the '/' to point to each parameter
# example: SKIRT/GeometricSource/scaleLength "2000 pc"

import xml.etree.ElementTree as ET
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--filename")
parser.add_argument("--projectPath")
args = parser.parse_args()

tree = ET.parse(args.projectPath+'/SKIRT_files/'+args.filename)
root = tree.getroot()

# store config.txt inputs as dictionary
d = {}
with open(args.projectPath+"/config.txt") as f:
	for line in f:
		(key, val) = line.split()
		d[key] = val

print (d)

for name, value in d.items():
	s = name.split('/')
	print('split:', s)
	print('length:', len(s))
	print(s[-1], value)

	if s[0] == 'SKIRT':

		for item in root.iter(s[1]):
			item.set(s[-1], value.replace("_", " "))

tree.write(args.projectPath+'/SKIRT_files/'+args.filename, encoding='UTF-8', xml_declaration=True)

"""

tree = ET.parse('built-ins.ski')
root = tree.getroot()

for item in root.iter('MonteCarloSimulation'):
	item.set('numPackets', "1e6")

# Wavelength grids:
for item in root.iter('sourceSystem'):
	item.set('minWavelength', "0.1 micron")
	item.set('maxWavelength', "100 micron")
	item.set('sourceBias', "0.5")
for item in root.iter('IntegratedLuminosityNormalization'):
	item.set('integratedLuminosity', '1e9 Lsun') # controls total stellar mass
	item.set('minWavelength', '0.1 micron')
	item.set('maxWavelength', '100 micron')
for child in root.iter('GeometricSource'):
	for item in child.iter('LogWavelengthDistribution'):
		item.set('minWavelength', '0.1 micron')
		item.set('maxWavelength', '100 micron')
for child in root.iter('DustEmissionOptions'):
	for item in child.iter('LogWavelengthDistribution'):
		item.set('minWavelength', '0.1 micron')
		item.set('maxWavelength', '100 micron')
for child in root.iter('wavelengthBiasDistribution'):
	for item in child.iter('LogWavelengthDistribution'):
		item.set('minWavelength', '0.1 micron')
		item.set('maxWavelength', '100 micron')
for child in root.iter('InstrumentSystem'):
	for item in child.iter('LogWavelengthGrid'):
		item.set('minWavelength', '0.1 micron')
		item.set('maxWavelength', '100 micron')
		item.set('numWavelengths', '1000')

for child in root.iter('GeometricSource'):
	for item in child.iter('ExpDiskGeometry'):
		item.set('scaleLength', '2000 pc')
		item.set('scaleHeight', '300 pc')

for child in root.iter('GeometricMedium'):
	for item in child.iter('ExpDiskGeometry'):
		item.set('scaleLength', '2000 pc')
		item.set('scaleHeight', '300 pc')

for child in root.iter('GeometricMedium'):
	for item in child.iter('MassMaterialNormalization'):
		item.set('mass', '1e7 Msun')

for item in root.iter('FSPSSED'):
	item.set('imf', 'Chabrier')
	item.set('metallicity', '0.02')
	item.set('age', '5 Gyr')

for child in root.iter('InstrumentSystem'):
	for item in child.iter('FullInstrument'):
		item.set('instrumentName', 'i00')
		item.set('distance', '100 Mpc')
		item.set('inclination', '0 deg')
		item.set('azimuth', '0 deg')
		item.set('fieldOfViewX', '2e4 pc')
		item.set('numPixelsX', '250')
		item.set('centerX', '0 pc')
		item.set('fieldOfViewY', '2e4 pc')
		item.set('numPixelsY', '250')
		item.set('centerY', '0 pc')

tree.write('built-ins_2.ski', encoding='UTF-8', xml_declaration=True)

"""


'''
Created on May 28, 2016

@author: Tania
'''

import os
import sys
from wikitools import wiki, api
import wikipedia
import csv

def wiki_search(keyword):
    title=""
    site = wiki.Wiki("https://en.wikipedia.org/w/api.php")
    # get the title of the article
    params = {'action':'query',  'list':'search', 'srsearch':keyword, 'srnamespace':0, 'srwhat':'nearmatch', 'srlimit':1, 'srprop':'titlesnippet', 'srenablerewrites':1}
    req = api.APIRequest(site, params)
    result = req.query()
    if result['query']['search']:
        for key, value in result['query']['search'][0].iteritems():
            if key=='title':
                title=value
        # get the URL of the article
        params = {'action':'query',  'prop':'info', 'titles':title, 'inprop':'url'}
        req = api.APIRequest(site, params)
        result = req.query()
        for pidkey in result['query']['pages']:
            for key, value in result['query']['pages'][pidkey].iteritems():
                if key=='fullurl':
                    url=value
        return url

base_dir = os.path.dirname(os.path.dirname(__file__))
data_dir = os.path.join(base_dir, 'data')
baseline_dir = os.path.join(data_dir, 'baseline')

csv_path =os.path.join(baseline_dir, 'prominent_scientists_(mearged_2001,2014,2015_TR).csv')
csvfile = open(csv_path , 'r')
reader = csv.reader(csvfile)
data=[]
for row in reader:
    keyword =  row[0]+" "+row[1]
    url=wiki_search(keyword)
    if url is not None:
        csv_row = [keyword, url, row[3]]
        data.append(csv_row)
csvfile.close()

output_path =  os.path.join(baseline_dir, 'baseline.csv')

with open(output_path, 'w') as fp:
    a = csv.writer(fp, delimiter=',')
    a.writerows(data)


#!/usr/bin/env python3

import numpy as np

def semivariogram(x, y, z, s=1):
    '''Calaculate the semivariance as:

    ..math: \gamma_i (h) = \frac{1}{2} \left( z_{x_i} -  z_{x_i+h} \right)^2

    Parameters:
    ----------
        x : array_like
            x-coordinate vector
        y : array_like
            y-coordinate array
        z : array_like
            z-vector at point(x,y) to calculate the semivariance of
        s : int or float
            scale factor in computing the lag distance between bins
    Reutrns:
    -------
        mean_lag : array_like
            lag distance bins
        vario :
            semivariance within the corresponding bin
        varz :
            variance of the the full dataset z
    '''

    # Grid the input data in it's observed grid
    X1, X2 = np.meshgrid(x,x)
    Y1, Y2 = np.meshgrid(y,y)
    Z1, Z2 = np.meshgrid(z,z)

    # Compute distance matrix and replace zeros along the diagonal with NaNs
    D  = np.sqrt((X1-X2)**2 + (Y1-Y2)**2)
    D += D*np.diag((x*np.nan))

    # Compute the semivariance between points
    G = (1/2)*(Z1 - Z2)**2

    lag      = s*0.5*np.mean(np.nanmin(D, axis=0)) # compute lag distance
    hmd      = np.nanmax(D)/2                      # Find max distance between points/2
    num_lags = np.floor(hmd/lag)                   # compute number of lags

    # Bin the data with the calculate lag length
    all_lags = np.ceil(D/lag)

    # Initalize empty vectors to be populated in for loop below
    mean_lag  = np.zeros(int(num_lags))            # Lag vector
    num_pairs = np.zeros(int(num_lags))            # Pair counts
    vario     = np.zeros(int(num_lags))            # Variance at lag

    # iterate over the lags
    for i in range(int(num_lags)):
        selection    = all_lags == (i+1)                 # select points in bin (1 = true)
        mean_lag[i]  = np.mean(D[selection])             # compute mean lag distance
        num_pairs[i] = np.sum(selection.astype(int))/ 2  # count pairs
        vario[i]     = np.mean(G[selection])             # populate variogram

    # Compute variance of original data
    varz = np.var(z)

    return mean_lag, vario, varz

def ordinary_krig(x, y, z, model = 'linear', nugget=0.0, sill=None, slope=0.9, range=50):
    '''Function to compute Ordinary Kirging

    Parameters:
    ----------
        x : array_like
            x-coordinate vector
        y : array_like
            y-coordinate array
        z : array_like
            z-vector at point(x,y) to be kriged
        model : string
                Type of model used to compute the semivariance matrix (W)
        nugget : float, optional
                 Offset to force semivariogram through origin
        sill : float
               default value np.var(z, ddof=1)
        range : int, optional (required for "exponential" and "spherical" models)
                Lag (distance) at which semivariance=> variance, measure of correlation distance

    Reutrns:
    -------
        Z : array_like (2D)
            predicted value on a regularly spaced grid
        S2 : array_like (2D)
            Kriging variance on our regularly spaced grid
        X : array_like (2D)
            X grid of kriged points
        Y : array_like (2D)
            Y grid of kriged points
    '''
    models = ['linear', 'exponential', 'spherical']

    if model not in models:
        raise ValueError('Invalid model specified. Model must be "{}", "{}" or "{}"'.format(*models))

    X1, X2 = np.meshgrid(x,x)
    Y1, Y2 = np.meshgrid(y,y)
    Z1, Z2 = np.meshgrid(z,z)

    # Calculate the distance between points
    D = np.sqrt((X1-X2)**2 + (Y1-Y2)**2)

    if sill == None:
        # Compute variance of original data
        sill = np.var(z)

    # Populate semivariance matrix W
    if model == 'linear':
        W = nugget + slope*D
    else:
        raise NotImplementedError('Model not supported yet. Add functionality yourself!!')

    # Add extra row and column to W for Lagrange multiplier
    m, n     = W.shape
    W        = np.append(W,np.ones((1,m)),  axis=0)  # Add final column of ones
    W        = np.append(W,np.ones((n+1,1)),axis=1)  # Add final row of ones
    W[-1,-1] = 0

    # Invert W for later, this is ill-conditioned but oh-well
    # this can be very computationally expensive so only want to do it once
    Winv = np.linalg.inv(W)

    #  Construct regular grid over which interpolated values are required
    xgrid = np.linspace(x.min(),x.max(),len(x))
    ygrid = np.linspace(y.min(),y.max(),len(y))
    X, Y  = np.meshgrid(xgrid,ygrid)

    # Convert arrays to single vectors:
    Xvec = X.flatten()
    Yvec = Y.flatten()

    # Initalize vairable solved for
    Zvec  = 99999.*np.ones((Xvec.shape[0],1))
    S2vec = 99999.*np.ones((Xvec.shape[0],1))

    # Compute the Kriged estimate at each point
    for i in np.arange(Xvec.shape[0]):
        # calculate distances between point of interest and all observations:
        D0 = np.sqrt( (x - Xvec[i])**2 + (y - Yvec[i])**2 )

        # calculate B (RHS) based on distances above and variogram model
        if model == 'linear':
            B = nugget + slope*D0

        # Add final element for Lagrange multiplier
        B = np.append(B,1)

        # Compute kriging weights and lagrange multiplier with matrix multiplication
        Lambda   = np.dot(Winv,B)

        # Compute kriging estimate at point of interest as weighted sum of obs
        Zvec[i]  = np.dot(z.T,Lambda[:n])

        # Compute kriging variance at point of interest
        S2vec[i] = np.dot(B.T,Lambda)

    # Reshape from flattened vectors to MxM matrix
    M  = xgrid.shape[0]
    Z  = Zvec.reshape(M,M)
    S2 = S2vec.reshape(M,M)

    return Z, S2, xgrid, ygrid


from django.contrib import admin
from django.conf.urls import include, url
from courses import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register(r'branch', views.BranchViewSet)
router.register(r'contact', views.ContactViewSet)
router.register(r'course', views.CourseViewSet)

urlpatterns = [
    url('^', include(router.urls)),
    url(r'^admin/', admin.site.urls),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^course/', views.CourseViewSet),
    url(r'^course/(?P<pk>[0-9]+)/$', views.CourseDetailView.as_view()),
]


"""GeneJson URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from mysite import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index', views.html_index),
    # path('upload', views.html_upload),
    # path('about', views.html_about),
    # path('browse', views.html_browse),
    path('contact', views.html_contact),
    path('download', views.html_download),
    path('upload/doupload', views.doupload),
    path('upload/uploadcomplete', views.uploadcomplete),
    path('upload/uploadcheckchunk', views.uploadcheckchunk),
    path('upload/uploadcheckfile', views.uploadcheckfile),
    path('upload/convert', views.uploadconvert),
    path('upload/importDB', views.uploadimportDB),
    path('search', views.html_search),
    path('search/doDiseaseSearch', views.DiseaseSearch),
    path('search/doVCFSearch/', views.doVCFSearch),
    path('search/doexactSearch/', views.doexactSearch),
    path('search/doGeneDiseaseSearch/', views.doGeneDiseaseSearch),
    path('search/doGeneInfoSearch/', views.doGeneInfoSearch),
    path('search/doGFF3Search/', views.doGFF3Search),
    path('download/showfiellist', views.GetDownloadfileList),
    path('download/dodownload/', views.DownloadFile),
    path('download/dodownloadOntoAnnotation/', views.DownloadOntoAnnotation),
    path('download/dodownloadDBdump/', views.DownloadDBdump),
    path('search/getkeyfield', views.GetKeyField),
    path('search/doSOInfoSearch/', views.doSOInfoSearch),
    path('search/doVCFSearchWithOntology/', views.doVCFSearchWithOntology),
    path('search/DoVariantIDSearch/', views.doVariantIDSearch),
    path('search/DoRegionSearch/', views.doRegionSearch),
    path('search/DoOntologySearch/', views.doOntologySearch),
    path('search/DoGetInfoFields/', views.doGetInfoFields),
    path('search/GetDataLabel/', views.doGetInputDataLabel),
]

import configparser
cf = configparser.ConfigParser()
cf.read("project.config")
HASKBQA = cf.get("backend", "HASKBQA")=="True"
if HASKBQA:
    from mysite import KBQA
    urlpatterns.append(path('KBQA/domainsearch', KBQA.domainsearch))


from os.path import dirname
import pandas as pd
from utils import *
from classes import *

def readingData(country):

    current_dir = dirname(__file__)
    file_path = current_dir + "/InstancesV1/Instance" + country + "V1.xlsx"
    xls = pd.ExcelFile(file_path)

    #employees
    employees_sheet = pd.read_excel(xls, 'Employees')
    skillToRank = {skill : i for i,skill in enumerate( set(employees_sheet["Skill"]) )}
    skillToRank['other'] = len(skillToRank)
    employees = []

    for index, row in employees_sheet.iterrows():
        print(index,row)
        workingStartTime = dateToMinute( row["WorkingStartTime"] )
        workingEndTime = dateToMinute( row["WorkingEndTime"] )
        skill = skillToRank[ row["Skill"] ]
        employees.append( TEmployee(row["EmployeeName"], row["Latitude"], row["Longitude"], skill, row["Level"], workingStartTime, workingEndTime) )

    #tasks
    task_sheet = pd.read_excel(xls, 'Tasks')
    tasks = []
    for index, row in task_sheet.iterrows():
        openingTime = dateToMinute( row["OpeningTime"] )
        closingTime = dateToMinute( row["ClosingTime"] )
        if row["Skill"] in skillToRank.keys():
            skill = skillToRank[ row["Skill"] ]
        else: skill = skillToRank["other"]
        tasks.append( TTask(row["TaskId"], row["Latitude"], row["Longitude"], row["TaskDuration"], skill, row["Level"], openingTime, closingTime) )

    return employees, tasks


import time
import pickle

class DataTwitter(object):

	def __init__(self):
		self.tweet_file_name = 'data/tweet_stocks.txt'
		self.lock =  False

	def get_tweets_list(self):
		'''Return a list of Simpletweet object'''
		if(self.lock):
			time.sleep(1)
			self.get_tweets_list()
		else:
			self.lock = True
			self.tweet_file = open(self.tweet_file_name,'r+b')
			tweet_file_unpickel = pickle.Unpickler(self.tweet_file)
			list_of_tweet = []
			while True:
				try:
					tweet = tweet_file_unpickel.load()
					list_of_tweet.append(tweet)
				except EOFError:
					self.tweet_file.close()
					self.lock =  False
					return list_of_tweet

	def write_tweet(self, SimpleTweet):
		'''Write a simple tweet object '''

		if(self.lock):
			time.sleep(1)
			self.get_tweets_list()
		else:
			self.lock = True
			self.tweet_file = open(self.tweet_file_name,'a+b')
			tweet_file_pickle = pickle.Pickler(self.tweet_file)
			tweet_file_pickle.dump(SimpleTweet)
			self.tweet_file.close()
			self.lock =  False

	def create_author_nb_tweet_list(self):

		if(self.lock):
			time.sleep(1)
			self.get_tweets_list()
		else:
			self.lock = True
			tweet_file = open(tweet_file_name,'rb')
			tweet_file_unpickel = pickle.Unpickler(tweet_file)
			dict_author_nb_tweet = {}

			while True:
				try:
					tweet = tweet_file_unpickel.load()
					if(dict_author_nb_tweet.has_key(int(tweet.author))):
						dict_author_nb_tweet[int(tweet.author)] = int(dict_author_nb_tweet[int(tweet.author)]) +1
					else:
						dict_author_nb_tweet[int(tweet.author)] = 1
				except EOFError:
					self.lock =  True
					self.tweet_file.close()
					break

		return dict_author_nb_tweet


# Ignore user warnings to keep the terminal clean
import warnings
warnings.simplefilter("ignore", UserWarning)

# Import the necessary python library modules
import numpy as np
from control import matlab
import os
import sys
import pdb

# Add my local path to the relevant modules list
sys.path.append('/Users/Daniel/Github/Crawlab-Student-Code/Daniel Newman/Python Modules')

# Import my python modules
import InputShaping as shaping
import ic_linear as ic
import Generate_Plots as genplt

folder = 'Figures/{}/'.format(
												sys.argv[0],
												)

sens_3d = np.genfromtxt('3D Sens/amp_freq_data.txt',skip_header=1,delimiter=',')
Amplitude = np.round(sens_3d[:,2],3)

freq = np.round(sens_3d[:,0],3)
amp = np.round(sens_3d[:,1],3)

genplt.plot_3d(freq,amp,Amplitude,
		r'Normalized Freq. $\frac{\omega_n}{\omega_m}$',
		r'Amplitude Error, $A_e$',
		'Percent Vibration',azimuth=-20,elevation=40,
		folder=folder,name_append='3D_Amp_Freq_Sens')

sens_3d = np.genfromtxt('3D Sens/phase_amp_data.txt',skip_header=1,delimiter=',')
Amp = sens_3d[:,2]

Amp = np.clip(Amp,0,200)

norm_amp = sens_3d[:,0]
phase = sens_3d[:,1]

genplt.plot_3d(norm_amp,phase,Amp,
		r'Amplitude Error, $A_e$',
		r'Phase Error, $\theta_e$ (deg)',
		'Percent Vibration',azimuth=-20,elevation=40,
		folder=folder,name_append='3D_Phase_Amp_Sens')

sens_3d = np.genfromtxt('3D Sens/phase_freq_data.txt',skip_header=1,delimiter=',')
Amp = np.round(sens_3d[:,2],3)

Amp = np.clip(Amp,0,200)
freq = np.round(sens_3d[:,0],3)
phase = sens_3d[:,1]

genplt.plot_3d(freq,phase,Amp,
		r'Normalized Freq. $\frac{\omega_n}{\omega_m}$',
		r'Phase Error, $\theta_e$ (deg)',
		'Percent Vibration',azimuth=-20,elevation=40,
		folder=folder,name_append='3D_Phase_Freq_Sens')


# import string
import secrets
import base58
from blake3 import blake3

import time
from typing import Optional

# totp time window in seconds
# would go to a config in a real microservice

time_window = 15

def generate_secret() -> str:
    """Returns a random 20-symbol base58 string"""
    # alphabet = (string.ascii_letters + string.digits).translate({ord(c): '' for c in "0OlI"})
    # secret = ''.join(secrets.choice(alphabet) for i in range(20))

    alphabet = secrets.token_bytes(15)
    secret = base58.b58encode(alphabet).decode('utf-8')[:20]

    return secret

# def generate_secret() -> str:
#     """Returns a random 20-symbol base58 string"""
#     return "abcdeabcdeabcdeabcd" + str(int(time.time_ns()) % 9)

def generate_code(secret: str,
                  seconds_since_the_epoch: Optional[int] = None) -> str:
    """Generates a TOTP code.
    Arguments:
    secret -- 20-symbol base58 string to act as a secret key to make TOTP code
    seconds_since_the_epoch -- second for which to generate. Current moment if None

    Returns 4-digit string that changes every window"""

    if len(secret) > 20:
        raise ValueError("Secret must be 20-symbol base58 string, is '{}' instead".format(secret))

    if seconds_since_the_epoch is None:
        seconds_since_the_epoch = int(time.time())

    seconds_since_the_epoch = int(seconds_since_the_epoch // time_window)
    hash_blk = blake3((secret + str(seconds_since_the_epoch)).encode('utf-8')).hexdigest()
    code = str(int(hash_blk, 16))[-4:]

    return code

def check_code(secret: str, code: str,
               seconds_since_the_epoch: Optional[int] = None) -> bool:
    """Checks if the code is correct for the current moment.
    Arguments:
    secret -- 20-symbol base58 string to act as a secret key to generate TOTP code
    code -- 4-digit string TOTP code.
    seconds_since_the_epoch -- moment at which code should be correct

    Returns True if the code is valid for the provided moment
    """
    if len(code) != 4:
        raise ValueError("TOTP code must be 4 digits string, is '{}' instead".format(code))

    return generate_code(secret, seconds_since_the_epoch) == code


#!/usr/bin/env python

# Exercise10 (optional)
# Read the 'show_ip_bgp.txt' file.
# Strip out the header information so you are just left with the routes
# Parse each BGP line such that you retrieve the prefix and the as_path.
# Save the prefix and as_path to a file.

with open('show_ip_bgp.txt','r') as f:
    output = f.read().splitlines()

with open('bgp_out.txt','w') as f:
    for line in output:
        if '4.69.184.193' in line:
            list = line.split()
            prefix = list[1]
            as_path = list[5:-1]
            as_path = " ".join(as_path)
            output_str = "Prefix: {}     as_path: {}\n".format(prefix, as_path)
            f.write(output_str)


from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from django.template import loader

import json
import logging
from django.core.paginator import  Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Max
from django.db import transaction

from website.models import Browser_setting

logger = logging.getLogger('mylogger')

# 系统配置-浏览器设置
def browser_setting(request):
    template = loader.get_template('website/pages/browserSetting.html')
    return HttpResponse(template.render({}, request))

# 获取系统配置-浏览器配置表，列表数据
def get_browser_settings(request):
    griddata = {"total": 0, "rows": []}
    rows = [] # 用于存储记录行

    # 获取总记录数
    envs = Browser_setting.objects.all().order_by('-order').values()
    griddata["total"] = len(envs)

    page_num = request.GET.get('page') # 记录请求的是第几页数据
    rows_num = request.GET.get('rows') # 记录请求每页的记录数

    paginator = Paginator(envs, rows_num) # 设置每页展示的数据

    try:
        page = paginator.page(page_num)
    except PageNotAnInteger as e: # 如果请求的页面编号不存在，返回第一页数据
        logger.warn('%s' % e)
        page = paginator.page(1)
    except EmptyPage as e: # 如果请求页面，超出页面范围，返回最后一页数据
        logger.warn('%s' % e)
        page = paginator.page(paginator.num_pages)

    objs = page.object_list
    for obj in objs:
        rows.append(obj)
    griddata["rows"] =  rows
    griddata = json.dumps(griddata)
    return HttpResponse(griddata)

# 新增浏览器配置
def add_browser_setting(request):
    try:
        params = request.POST

        browser_name = params['browser']
        order = params['order']
        if not browser_name:
            return HttpResponse('浏览器名称不能为空')

        if_name_exists = Browser_setting.objects.filter(browser=browser_name).exists()
        if if_name_exists:
            # logger.error('error, 环境名称(%s)已存在' % browser_name)
            return HttpResponse('环境名称(%s)已存在' % browser_name)

        if order == '': # 如果顺序为空，表明是新增
            all_objects = Browser_setting.objects.all()
            if all_objects.exists():
                max_order = all_objects.aggregate(Max('order'))['order__max']
                order = max_order + 1
            else:
                order = 1
            obj = Browser_setting(browser = browser_name, order=order)
            obj.save()
        else: #表明是插入
            logger.info('即将插入新记录，正在调整记录的顺序') # 插入记录所在行上方的记录都+1
            all_objects = Browser_setting.objects.filter(order__gte=order)
            try:
                with transaction.atomic():
                    for item in all_objects:
                        item.order = item.order + 1
                        item.save()
                    obj = Browser_setting(browser = browser_name, order=order)
                    obj.save()
            except Exception as e:
                logger.error('%s' % e)
                return HttpResponse('%s' % e)
        return  HttpResponse('success')
    except Exception as e:
        return HttpResponse('%s' % e)

# 系统设置-浏览器配置，修改浏览器名称
def edit_browser_setting(request):
    try:
        params = request.POST

        id = params['id']
        name = params['browser']
        if not name:
            return HttpResponse('浏览器名称不能为空')

        if_name_exists = Browser_setting.objects.filter(browser=name).exclude(id=id).exists()
        if if_name_exists:
            # logger.error('error, 浏览器名称(%s)已存在' % name)
            return HttpResponse('浏览器名称(%s)已存在' % name)

        obj = Browser_setting.objects.get(id=id)
        obj.browser = name
        obj.save()
        return  HttpResponse('success')
    except Exception as e:
        logger.error('%s' % e)
        return HttpResponse('%s' % e)


from clases.Consulta import *

class G3(Consulta):
    def __init__(self, nombre, busqueda=None, ruta="/text-search"):
        Consulta.__init__(self, ruta)
        #if id is None:
        #    self.esperar = Truye
        self.busqueda = busqueda
        self.done = False
        self.nombre = nombre
        self.json_api = None
        self.json_grupo_original = None
        self.json_grupo_adaptado = None
        self.json_api_mayus = None
        self.json_api_tilde = None
        self.json_api_mayus_tilde = None
        self.filtros_busqueda = []
        self.completo = True
        if nombre == "G3.11":
            self._puntos = 4
        else:
            self._puntos = 2

    def puntos(self):
        if self.respuesta:
            if self.completo:
                return self._puntos
            else:
                return self._puntos / 2
        return 0 # "mid" in i and str(i["mid"]

    def mensaje(self):
        if not self.atributos:
            self._mensaje = "Faltan atributos por mostrar."
        if not self.completo:
            self._mensaje += " No se considera el caso de no agregar todos los parámetros. "
        if self.respuesta:
            return f"{self.nombre}: {self.respuesta} [{self.puntos()} puntos] ({self._mensaje}) pruebas_aceptadas = {' - '.join(self.filtros_busqueda)}"
        else:
            return f"{self.nombre}: {self.respuesta} [{self.puntos()} puntos] ({self._mensaje})"#"

    def escribir(self, nombre_archivo="G3.py"):
        if Consulta.guarda:
            nombre_carpeta = Consulta.nombre_archivo
            with open(nombre_carpeta + f"/{nombre_archivo}", "a") as archivo:# + datetime.now().strftime('%d-%m-%y_%H-%M-%S'))
                #""#bcb
                string = f'''
{"#"*((80-len(self.nombre) - 2)//2)} {self.nombre} {"#"*(80 - len(self.nombre) - 2 - ((80-len(self.nombre) - 2)//2))}
"{self.nombre}": {'{'}
    "busqueda": {self.busqueda},
    "respuesta": {self.respuesta},
    "acepta_no_incluir_parametros": {self.completo},
    "puntos": {self.puntos()},
    "todos_los_atributos": {self.atributos},
    "atributos_encontrados": {self.atributos_encontrados},
    "json_grupo_adaptado": {self.json_grupo_adaptado if self.json_grupo_adaptado in [None, False] else [int(float(i["mid"])) for i in self.json_grupo_adaptado if "mid" in i and str(i["mid"]).isnumeric() or "mid" in i and str(i["mid"]).replace(".", "").isnumeric()]},
    "json_api": {self.json_api if self.json_api in [None, False] else [int(float(i["mid"])) for i in self.json_api if "mid" in i and str(i["mid"]).isnumeric() or "mid" in i and str(i["mid"]).replace(".", "").isnumeric()]},
    "json_api_mayusculas": {self.json_api_mayus if self.json_api_mayus in [None, False] else [int(float(i["mid"])) for i in self.json_api_mayus if "mid" in i and str(i["mid"]).isnumeric() or "mid" in i and str(i["mid"]).replace(".", "").isnumeric()]},
    "json_api_tildes": {self.json_api_tilde if self.json_api_tilde in [None, False] else [int(float(i["mid"])) for i in self.json_api_tilde if "mid" in i and str(i["mid"]).isnumeric() or "mid" in i and str(i["mid"]).replace(".", "").isnumeric()]},
    "json_api_mayus_tildes": {self.json_api_mayus_tilde if self.json_api_mayus_tilde in [None, False] else [int(float(i["mid"])) for i in self.json_api_mayus_tilde if "mid" in i and str(i["mid"]).isnumeric() or "mid" in i and str(i["mid"]).replace(".", "").isnumeric()]},

    "json_grupo_original": {self.json_grupo_original},

{'},'}
                '''
                archivo.write(string)#r

    def correr(self):
        try:

            cargando = threading.Thread(target=self.animate)
            cargando.start()

            resultado = self._correr()
            self.respuesta = resultado
            if not self.respuesta:
                resultado = self._correr(de_nuevo=True)
                if resultado:
                    self.respuesta = resultado
                    self.completo = False
            self.done = True#jiib.strip()
            sys.stdout.write(f"\r¡Listo! {self.nombre}: {resultado} [{', '.join([i for i in self.busqueda]) if self.busqueda else self.busqueda}]   ")
            print()
        except SeDemora:
            #print("hola")
            self.done = True
            resultado = False
            sys.stdout.write(f"\r¡Listo! {self.nombre}: {resultado} [{self.busqueda}]   ")
            print()
        except (KeyboardInterrupt, SystemExit):
            self.done = True
            cargando.clear()

        return resultado

    def _correr(self, de_nuevo=False):
        try:
            if de_nuevo:
                for i in ["desired", "forbidden", "required"]:
                    if i not in self.busqueda:
                        self.busqueda[i] = []
        except:
            return False
        try:
            #https://stackoverflow.com/questions/22029562/python-how-to-make-simple-animated-loading-while-process-is-runningd
            if self.busqueda == None or self.busqueda == {}:
                consulta = f"{self.ruta}"
                if self.busqueda is None:
                    uno = Consulta.requests_get(self.api + consulta, timeout=10)
                else:
                    uno = Consulta.requests_get(self.api + consulta, json=self.busqueda, timeout=10)

                respuesta_api = Consulta.encontrar(uno.json())

                if self.busqueda is None:
                    dos = Consulta.requests_get(self.grupo + consulta, timeout=10)
                else:
                    dos = Consulta.requests_get(self.grupo + consulta, json=self.busqueda, timeout=10)
                self.json_grupo_original = dos.json()
                respuesta_grupo = Consulta.encontrar(self.json_grupo_original)
                self.json_grupo_adaptado = respuesta_grupo
                if not respuesta_api and not respuesta_grupo:
                    return True
                elif respuesta_api and not respuesta_grupo:
                    return False
                elif not respuesta_api and respuesta_grupo:
                    return False
                else:
                    self.todos_atributos(respuesta_grupo)
                    largo = len(respuesta_grupo)
                    contador = 0
                    for i in range(len(respuesta_grupo)):
                        if "mid" in respuesta_grupo[i]:
                            if str(respuesta_grupo[i]["mid"]).replace(".", "").isnumeric() and 1 <= int(str(respuesta_grupo[i]["mid"]).replace(".", "")) <= 220:
                                contador += 1
                    if contador >= 100:
                        return True
                    if largo >= 2:
                        return True
                    return False

            else:
                consulta = f"{self.ruta}"
                uno = Consulta.requests_get(self.api + consulta, json=self.busqueda)
                tres_mayus = Consulta.requests_get(self.api + consulta + "-2/True/False", json=self.busqueda, timeout=10)
                tres_tilde = Consulta.requests_get(self.api + consulta + "-2/False/True", json=self.busqueda, timeout=10)
                tres_mayus_tilde = Consulta.requests_get(self.api + consulta + "-2/True/True", json=self.busqueda, timeout=10)
                respuesta_api = Consulta.encontrar(uno.json())
                self.json_api = respuesta_api
                dos = Consulta.requests_get(self.grupo + consulta, json=self.busqueda)
                # print("grupo", self.grupo + consulta, "grupo")
                respuesta_api_mayus = Consulta.encontrar(tres_mayus.json())
                respuesta_api_tilde = Consulta.encontrar(tres_tilde.json())
                respuesta_api_mayus_tilde = Consulta.encontrar(tres_mayus_tilde.json())
                self.json_api = respuesta_api
                self.json_api_mayus = respuesta_api_mayus
                self.json_api_tilde = respuesta_api_tilde
                self.json_api_mayus_tilde = respuesta_api_mayus_tilde
                '''
                print(self.busqueda)
                print(dos.status_code)
                '''
                print()
                self.json_grupo_original = dos.json()

                respuesta_grupo = Consulta.encontrar(self.json_grupo_original)
                self.json_grupo_adaptado = respuesta_grupo
                if not respuesta_api and not respuesta_grupo:
                    return True
                elif respuesta_api and not respuesta_grupo:
                    return False
                elif not respuesta_api and respuesta_grupo:
                    return False
                else:
                    ids_encontrados = set([int(i["mid"]) for i in respuesta_api])
                    ids_encontrados_mayus = set([int(i["mid"]) for i in respuesta_api_mayus] if respuesta_api_mayus not in [None, False] else [])
                    ids_encontrados_tilde = set([int(i["mid"]) for i in respuesta_api_tilde] if respuesta_api_tilde not in [None, False] else [])
                    ids_encontrados_mayus_tilde = set([int(i["mid"]) for i in respuesta_api_mayus_tilde ] if respuesta_api_mayus_tilde not in [None, False] else [])
                    self.todos_atributos(respuesta_grupo)
                    ids = set()
                    for elemento in respuesta_grupo:
                        mid = elemento.get("mid")
                        if str(mid).replace(".", "").isnumeric():
                            mid = int(float(str(mid)))
                            if mid in Consulta.ids:
                                if mid not in ids_encontrados:
                                    return False
                                else:
                                    ids.add(mid)
                    largo = len((ids_encontrados - ids).union(ids - ids_encontrados).intersection(Consulta.ids))
                    largo_mayus = len((ids_encontrados_mayus - ids).union(ids - ids_encontrados_mayus).intersection(Consulta.ids))
                    largo_tilde = len((ids_encontrados_tilde - ids).union(ids - ids_encontrados_tilde).intersection(Consulta.ids))
                    largo_mayus_tilde = len((ids_encontrados_mayus_tilde - ids).union(ids - ids_encontrados_mayus_tilde).intersection(Consulta.ids))
                    #print(largo)
                    if largo >= 1 and largo_mayus >= 1 and largo_tilde >= 1 and largo_mayus_tilde >= 1:
                        return False #if i in
                    lista = []
                    if largo == 0:
                        lista.append("regular")
                    if largo_mayus == 0:
                        lista.append("case_sensitive")
                    if largo_mayus_tilde == 0:
                        lista.append("case_and_diacritic_sensitive")
                    if largo_tilde == 0:
                        lista.append("diacritic_sensitive")
                    self.filtros_busqueda = lista
                    return True#tYu#tRUE#FalsetRUE
        except requests.exceptions.ReadTimeout:
            self.done = True
            sys.stdout.write(f"\r¿Listo? {self.nombre}")
            print()
            print("    " + "_"*48)
            print("    Al parecer algo sucede Con las consultas que ")
            print("    entregan todos los mensajes                  ")
            print("    A continuación se dan distintas opciones     ")
            print("    para resolver, resolverlo ahora o más tarde: ")
            print('''
    [0] Revisar código ahora -> Está correcto
    [1] Revisar código ahora -> Está incorrecto
    [2] Revisar código más tarde
            ''')
            entrada = input("    >> ")
            while entrada.strip() not in ["0", "1", "2"]:
                print("    No se reconoció la entrada")
                entrada = input("    >> ")
            print("    " + "_"*48)
            if entrada.strip() == "0":
                resultado = True#ye#TTTT
                return True
            elif entrada.strip() == "1":
                resultado = False
                return False
            else:
                resultado = None
                return None

        except Exception as e:
            print(e)
            self.done = True
            return False


#coding=utf-8
'''
Created on 2016年3月1日

@author: cero
'''
from django.conf.urls import url
from login.views import requires_login
from .views import to_SubScale,getData_RecenetOneYearSubScale,getData_SubScale,to_allscale,getData_allscale,to_alllevel,getData_alllevel
from .views import to_subLevel,getData_subLevel,to_activeyear,getData_activeyear,to_activemonth,getData_activemonth
urlpatterns = [
    url(r'^tosublevel$', requires_login(to_subLevel)),
    url(r'^getsubleveldata$', requires_login(getData_subLevel)),
    url(r'^tosubscale$', requires_login(to_SubScale)),
    url(r'^getsubscaledataReceOneYear$', requires_login(getData_RecenetOneYearSubScale)),
    url(r'^getsubscaledata$', requires_login(getData_SubScale)),
    url(r'^toallscale$', requires_login(to_allscale)),
    url(r'^getallscaledata$', requires_login(getData_allscale)),
    url(r'^toalllevel$', requires_login(to_alllevel)),
    url(r'^getallleveldata$', requires_login(getData_alllevel)),
    url(r'^toactiveyear$', requires_login(to_activeyear)),
    url(r'^getYearActiveData$', requires_login(getData_activeyear)),
    url(r'^toactivemonth$', requires_login(to_activemonth)),
    url(r'^getMonthActiveData$', requires_login(getData_activemonth)),
]