def test_numbering_latex():
    init()

    src = Para(createListStr(u'Exercise #'))
    dest = Para([
        RawInline(u'tex', u'\\phantomsection\\addcontentsline{exercise}{exercise}{\\protect\\numberline {1}{\\ignorespaces Exercise}}'),
        Span(
            [u'exercise:1', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], 'latex', {}) == dest

    init()

    src = Para(createListStr(u'Exercise (The title) #'))
    dest = Para([
        RawInline(u'tex', u'\\phantomsection\\addcontentsline{exercise}{exercise}{\\protect\\numberline {1}{\\ignorespaces The title}}'),
        Span(
            [u'exercise:1', ['pandoc-numbering-text', 'exercise'], []],
            [
                Strong(createListStr(u'Exercise 1')),
                Space(),
                Emph(createListStr(u'(') + createListStr(u'The title') + createListStr(u')'))
            ]
       )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], 'latex', {}) == dest
def test_numbering_hidden():
    init()

    src = Header(1, [u'first-chapter', [], []], createListStr(u'First chapter'))
    pandoc_numbering.numbering(src['t'], src['c'], '', {})

    src = Para(createListStr(u'Exercise -.#exercise:one'))
    dest = Para([
        Span(
            [u'exercise:one', ['pandoc-numbering-text', 'exercise'], []],
            [
                Strong(createListStr(u'Exercise 1'))
            ]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest

    src = Para(createListStr(u'Exercise -.#'))
    dest = Para([
        Span(
            [u'exercise:1.2', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 2'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest

    src = Header(1, [u'second-chapter', [], []], createListStr(u'Second chapter'))
    pandoc_numbering.numbering(src['t'], src['c'], '', {})

    src = Para(createListStr(u'Exercise -.#'))
    dest = Para([
        Span(
            [u'exercise:2.1', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest

    src = Para(createListStr(u'Exercise +.#'))
    dest = Para([
        Span(
            [u'exercise:2.2', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 2.2'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest

    src = Para([Str(u'Exercise'), Space(), Str(u'#')])
    dest = Para([
        Span(
            [u'exercise:1', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest
def listing_latex(meta, color, tab, space):
    init()

    src = Para(createListStr(u'Exercise #'))
    pandoc_numbering.numbering(src['t'], src['c'], 'latex', meta)
    src = Para(createListStr(u'Exercise (test) #'))
    pandoc_numbering.numbering(src['t'], src['c'], 'latex', meta)

    doc = [[{'unMeta': meta}], []]
    pandoc_numbering.addListings(doc, 'latex', meta)

    dest = [
        Header(1, ['', ['unnumbered'], []], createListStr(u'Listings of exercises')),
        RawBlock(
            'tex',
            ''.join([
                '\\hypersetup{linkcolor=' + color + '}',
                '\\makeatletter',
                '\\newcommand*\\l@exercise{\\@dottedtocline{1}{' + tab + 'em}{' + space + 'em}}',
                '\\@starttoc{exercise}',
                '\\makeatother'
            ])
        )
    ]

    assert json.loads(json.dumps(doc[1])) == json.loads(json.dumps(dest))
def test_numbering_sharp_sharp():
    init()

    src = Para(createListStr(u'Exercise ##'))
    dest = Para(createListStr(u'Exercise #'))
    pandoc_numbering.numbering(src['t'], src['c'], '', {})

    assert src == dest
Example #5
0
def main():
    helper.init('chrome_option_temp')

    # helper.logout()
    helper.auto_login()

    loop = asyncio.get_event_loop()
    loop.run_until_complete(async_export())

    helper.dispose()
Example #6
0
def test():
    try:
        # print(helper.check_download_limit(45671948, 623597263))
        helper.init()
        # print(helper.get_user_info())
        print(
            helper.auto_download(
                'https://download.csdn.net/download/hfstray/11103359'))
    finally:
        helper.dispose()
def test_numbering():
    init()

    src = Para(createListStr(u'Exercise #'))
    dest = Para([
        Span(
            [u'exercise:1', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest
def test_numbering_level():
    init()

    src = Para(createListStr(u'Exercise +.+.#'))
    dest = Para([
        Span(
            [u'exercise:0.0.1', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 0.0.1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest

    src = Header(1, [u'first-chapter', [], []], createListStr(u'First chapter'))
    pandoc_numbering.numbering(src['t'], src['c'], '', {})

    src = Header(2, [u'first-section', [], []], createListStr(u'First section'))
    pandoc_numbering.numbering(src['t'], src['c'], '', {})

    src = Para(createListStr(u'Exercise +.+.#'))
    dest = Para([
        Span(
            [u'exercise:1.1.1', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 1.1.1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest

    src = Para(createListStr(u'Exercise +.+.#'))
    dest = Para([
        Span(
            [u'exercise:1.1.2', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 1.1.2'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest

    src = Header(2, [u'second-section', [], []], createListStr(u'Second section'))
    pandoc_numbering.numbering(src['t'], src['c'], '', {})

    src = Para(createListStr(u'Exercise +.+.#'))
    dest = Para([
        Span(
            [u'exercise:1.2.1', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 1.2.1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest
def test_classes():
    init()

    meta = getMeta4()

    src = Para(createListStr(u'Exercise #'))
    dest = Para([
        Span(
            [u'exercise:1', ['pandoc-numbering-text', 'my-class'], []],
            [Strong(createListStr(u'Exercise 1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', meta) == dest
def test_numbering_unnumbered():
    init()

    src = Header(1, [u'unnumbered-chapter', [u'unnumbered'], []], createListStr(u'Unnumbered chapter'))
    pandoc_numbering.numbering(src['t'], src['c'], '', {})

    src = Para(createListStr(u'Exercise +.#'))
    dest = Para([
        Span(
            [u'exercise:0.1', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 0.1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest
def test_numbering_title():
    init()

    src = Para(createListStr(u'Exercise (The title) #'))
    dest = Para([
        Span(
            [u'exercise:1', ['pandoc-numbering-text', 'exercise'], []],
            [
                Strong(createListStr(u'Exercise 1')),
                Space(),
                Emph(createListStr(u'(') + createListStr(u'The title') + createListStr(u')'))
            ]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', {}) == dest
def test_numbering_sectioning_map():
    init()

    meta = getMeta2()

    sectioning(meta)

    src = Para([Str(u'Exercise'), Space(), Str(u'#')])
    dest = Para([
        Span(
            [u'exercise:2.2.1', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 2.1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', meta) == dest
def test_numbering_sectioning_map_error():
    init()

    meta = getMeta3()

    sectioning(meta)

    src = Para(createListStr(u'Exercise #'))
    dest = Para([
        Span(
            [u'exercise:1', ['pandoc-numbering-text', 'exercise'], []],
            [Strong(createListStr(u'Exercise 1'))]
        )
    ])

    assert pandoc_numbering.numbering(src['t'], src['c'], '', meta) == dest
Example #14
0
def test():
    try:
        helper.init()
        print(helper.get_user_info())
        print(
            helper.auto_download(
                'https://download.csdn.net/download/ozhy111/10880596'))
        print(
            helper.auto_download(
                'https://download.csdn.net/download/wjf8882300/10879204'))
        print(
            helper.auto_download(
                'https://download.csdn.net/download/yeyuxingyun/3455948'))
        print(
            helper.auto_download(
                'https://download.csdn.net/download/u013363856/9783561'))
    finally:
        helper.dispose()
def test_format():
    init()

    meta = getMeta5()

    src = Para(createListStr(u'Exercise #'))
    dest = json.loads(json.dumps(Para([
        Span(
            [u'exercise:1', ['pandoc-numbering-text', 'exercice'], []],
            [
                Span(['', ['description'], []], createListStr(u'Exercise')),
                Span(['', ['number'], []], createListStr(u'1')),
                Span(['', ['title'], []], [])
            ]
        )
    ])))

    json.loads(json.dumps(pandoc_numbering.numbering(src['t'], src['c'], '', meta))) == dest
Example #16
0
 def start(self):
     self.harvesters, self.hunters, self.storages, self.supplies = helper.init(
     )
     while (True):
         for j in range(100):
             self.show_all_elements()
             for i in range(len(self.harvesters)):
                 self.harvesters[i].update()
                 self.harvesters[i].set_score()
         self.harvesters = helper.get_fitness(self.harvesters)
         self.harvesters = helper.generate_harvesters_population(
             self.harvesters)
Example #17
0
def test_listing_classic():
    init()

    meta = getMeta1()

    src = Para(createListStr(u'Exercise #'))
    pandoc_numbering.numbering(src['t'], src['c'], '', meta)
    src = Para(createListStr(u'Exercise (test) #'))
    pandoc_numbering.numbering(src['t'], src['c'], '', meta)

    doc = [[{'unMeta': meta}], []]
    pandoc_numbering.addListings(doc, '', meta)

    dest = [
        Header(1, ['', ['unnumbered'], []], createListStr(u'Listings of exercises')),
	    BulletList([
	    	[Plain([createLink(['', [], []], createListStr(u'0.0.1 Exercise'), ['#exercise:0.0.1', ''])])],
	    	[Plain([createLink(['', [], []], createListStr(u'0.0.2 test'), ['#exercise:0.0.2', ''])])]
	    ])
	]

    assert json.loads(json.dumps(doc[1])) == json.loads(json.dumps(dest))
Example #18
0
def bgoa():
    agents = helper.init()
    fitness = helper.fitness(agents)
    inds = fitness.argsort()
    agents = agents[inds]
    target = agents[0]
    maxscore = helper.fitness(np.asarray([target]))
    dist = np.zeros((meta.ns,meta.ns))
    for l in range(meta.L):
        print("Iteration : ",l+1)
        c = meta.cmax - l * (meta.cmax-meta.cmin)/meta.L
        dmin = sys.float_info.max    
        dmax = 0
        for i in range(meta.ns):
            for j in range(meta.ns):
                if j==i:
                    continue
                dist[i][j] = dist[j][i] = np.linalg.norm(agents[i]-agents[j])
                dmax = max(dist[i][j],dmax)
                dmin = min(dist[i][j],dmin)
        dist = np.interp(dist,(dmin,dmax),(1,4))
        dT = np.zeros((meta.ns,meta.dim))
        for i in range(meta.ns):
            upd = np.zeros(meta.dim)
            for d in range(meta.dim):
                for j in range(meta.ns):
                    if(i==j):
                        continue
                    upd[d] += social(math.fabs(agents[j][d] - agents[i][d])) * (agents[j][d] - agents[i][d]) / dist[i][j]
            upd = upd * (c*c*0.5)
            T = np.array([sigmoid(x) for x in upd])
            dT[i] = T
        # print("Updating Vectors")
        for i in range(meta.ns):
            for j in range(meta.dim):
                r = np.random.rand(1)
                if(r>=dT[i][j]):
                    agents[i][j] = 0
                else:
                    agents[i][j] = 1
        fitness = helper.fitness(agents)
        inds = fitness.argsort()
        score = helper.fitness(np.asarray([agents[inds[0]]]))
        if(score > maxscore):
            target = agents[inds[0]]
            maxscore = score
        print(maxscore)
    return target
Example #19
0
scanner = Scanner()
devices = scanner.scan(2.0)

# 2. Connect to them
for dev in devices:
    print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
    for (adtype, desc, value) in dev.getScanData():
        print("  %s = %s" % (desc, value))
        if dev.addr not in connected_ble_devices:
            if desc == "Complete Local Name" and "CIRCUITPY" in value:
                create_ble(dev.addr, dev.addrType)
            # if dev.addr == "e5:59:80:c5:bc:4d":
            #     create_ble(dev.addr, dev.addrType)

# 3. Init connection to room
init(__file__, skipListening=True)
# # Cleanup old claims and subscriptions
batch([{"type": "death", "fact": [["id", get_my_id_str()]]}])

# 4. Listen for updates from room and BLE devices
while True:
    listen(blocking=False)
    for addr, data in list(connected_ble_devices.items()):
        room_batch_queue, room_sub_update_queue, device = data
        if not device.is_alive():
            print("Device died: {}".format(addr))
            del connected_ble_devices[addr]
        else:
            try:
                batch_update_from_ble_device = room_batch_queue.get(
                    block=False, timeout=None)
Example #20
0
        data = ring_buffer.get()
        if len(data) == 0:
            continue

        ans = detector.RunDetection(data)
        if ans == -1:
            print("Error initializing streams or reading audio data")
        elif ans > 0:
            message = "Keyword " + str(ans) + " detected at time: "
            message += time.strftime("%Y-%m-%d %H:%M:%S",
                                     time.localtime(time.time()))
            print message
            delay_time = time.time() + 3  # give at-least a 3 second delay
            os.system('aplay -q {}'.format(DETECT_DING))
            record()


if __name__ == "__main__":  # Run when program is called (won't run if you decide to import this program)
    while helper.internet_on() == False:
        print "."
    helper.init()
    path = os.path.realpath(__file__).rstrip(os.path.basename(__file__))
    # before doing anything else, just caliberate the threshold
    setup_snowboy(sensitivity=0.5)
    setup_microphone()
    set_threshold()
    os.system('mpg123 -q {}hello.mp3'.format(path, path))  # Say hello!
    print('Listening... Press Ctrl+C to exit')
    start_detect(sleep_time=0.03)
    print "\nYou have exited JarvisBot. I hope that I was useful. To talk to me again just type: python main.py"
Example #21
0
    claims = []
    claims.append({
        "type":
        "retract",
        "fact": [
            ["id", get_my_id_str()],
            ["id", "1"],
            ["postfix", ""],
        ]
    })
    for result in results:
        claims.append({
            "type":
            "claim",
            "fact": [
                ["id", get_my_id_str()],
                ["id", "1"],
                ["text", "draw"],
                ["text", "graphics"],
                ["text", str(result["graphics"])],
                ["text", "on"],
                ["text", "miniprojector"],
            ]
        })
    proxy_client.send_multipart(
        ["....BATCH{}{}".format(get_my_id_str(), json.dumps(claims)).encode()],
        zmq.NOBLOCK)


init(__file__)
Example #22
0
async def handle_msg_group(context):
    global last_cmd
    global last_arg_str
    global last_arg_int
    message = context['message']

    if config.need_at_me:
        if not is_at_me(message):
            return
    if is_at_me(message):
        message = rm_at_me(message)

    message = message.strip()
    cmd_args = message.split(' ')
    cmd = cmd_args[0]
    args = cmd_args[1:] if len(cmd_args) > 1 else []

    def is_all_number(_str: str):
        if _str is None or _str == '':
            return False
        for a in _str:
            if not '0' <= a <= '9':
                return False
        return True

    arg_int = int(args[0]) if len(args) > 0 and is_all_number(args[0]) else 0
    arg_int_2 = int(args[1]) if len(args) > 1 and is_all_number(args[1]) else 0
    arg_str = args[0] if len(args) > 0 else ''

    qq_num = str(context['sender']['user_id'])
    qq_name = context['sender']['nickname']
    if 'card' in context['sender'] and context['sender']['card'] != '':
        qq_name = context['sender']['card']
    qq_group = '-1'
    if 'group_id' in context:
        qq_group = str(context['group_id'])

    if cmd == '-help' or cmd == '-?':
        msg = '● 个人信息 -personal'
        msg += '\n● 排行榜  -rank [index]'
        msg += '\n● 查询文件 -find [keyword]'
        msg += '\n● 文件信息 -info [id]'
        msg += '\n● 更多信息 -more'
        msg += sep_s()
        msg += '\n* 输入CSDN下载页链接下载'
        msg += source_code_tail()
        msg += donate_tail()
        msg += export_tail()
        last_cmd = cmd
        await bot.send(context, msg)

    if cmd == '-user':
        await bot.send(context, '查询用户信息中...')
        helper.init()
        info = helper.get_user_info()
        helper.dispose()
        if info is None:
            msg = '获取用户信息失败!'
        else:
            msg = '{}'.format(info['name'])
            if info['vip']:
                msg += '【VIP】'
                msg += '\n剩余次数:{}次'.format(info['remain'])
                msg += '\n有效期至:{}'.format(info['date'][:10])
            else:
                msg += '\n剩余积分:{}积分'.format(info['remain'])
        await bot.send(context, msg)

    if cmd == '-rank':
        result = db_helper.rank_qq(arg_int)
        msg = build_rank_msg(result, arg_int)
        last_cmd = cmd
        last_arg_int = arg_int
        await bot.send(context, msg)

    if cmd == '-find':
        result = db_helper.find_all(arg_str, arg_int_2)
        count = db_helper.count_all(arg_str)
        msg = build_find_msg(result, count, arg_int_2)
        last_cmd = cmd
        last_arg_str = arg_str
        last_arg_int = arg_int_2
        await bot.send(context, msg)

    if cmd == '-info':
        result = db_helper.get_download(arg_int)
        if result is not None:
            msg = build_download_info(result)
            last_cmd = cmd
            last_arg_str = arg_str
            last_arg_int = arg_int
            await bot.send(context, msg)
        else:
            await bot.send(context, '文件不存在。')

    if cmd == '-donors':
        msg = build_donors(arg_int)
        last_cmd = cmd
        last_arg_int = arg_int
        await bot.send(context, msg)

    if cmd == '-personal':
        msg = build_personal(qq_num, qq_group, qq_name)
        await bot.send(context, msg)

    if cmd == '-more':
        if last_cmd == '-find':
            last_arg_int += 10
            result = db_helper.find_all(last_arg_str, last_arg_int)
            count = db_helper.count_all(last_arg_str)
            msg = build_find_msg(result, count, last_arg_int)
            await bot.send(context, msg)
        if last_cmd == '-rank':
            last_arg_int += 10
            result = db_helper.rank_qq(last_arg_int)
            msg = build_rank_msg(result, last_arg_int)
            await bot.send(context, msg)
        if last_cmd == '-info':
            result = db_helper.get_download(last_arg_int)
            if result is not None:
                msg = build_download_detail_info(result)
                await bot.send(context, msg)
        if last_cmd == '-donors':
            last_arg_int += 10
            msg = build_donors(last_arg_int)
            await bot.send(context, msg)
        if last_cmd == '-help' or last_cmd == '-?':
            msg = '● 用户信息 -user'
            msg += '\n● 捐赠名单 -donors'
            msg += sep_s()
            msg += '\n* 输入CSDN下载页链接下载'
            msg += source_code_tail()
            msg += donate_tail()
            msg += export_tail()
            await bot.send(context, msg)

    download_id = find_csdn_download_id(context['message'])
    if download_id is not None:
        if helper.__already_download(download_id) and db_helper.exist_download(
                download_id):
            msg = build_download_info(db_helper.get_download(download_id))
            await bot.send(context, msg)
            return

    download_url = find_csdn_download_url(context['message'])
    if download_url is not None:
        can_download, msg = helper.check_download_limit(qq_num, qq_group)
        if not can_download:
            await bot.send(context, msg)
            return

        if helper.is_busy():
            await bot.send(context, '资源正在下载中,请稍后...')
            return
        await bot.send(context, '开始下载...')
        try:
            helper.init()
            download_info = helper.auto_download(download_url, qq_num, qq_name,
                                                 qq_group)
            msg = download_info['message']
            if download_info['success']:
                result = db_helper.get_download(download_info['info']['id'])
                msg = build_download_info(result)
                last_cmd = '-info'
                last_arg_int = int(result.id)
            elif donate_tail() != '':
                msg += sep_s()
                msg += donate_tail()
            await bot.send(context, msg)
        finally:
            helper.dispose()
Example #23
0
def main(configfile):
  print('smartCam-start -----------------------------')

  # Loading config file,
  # Default values
  cfg_log_traces="smartCam.log"
  cfg_log_exceptions="smartCame.log"


  global GLB_configuration


  # Let's fetch data
  GLB_configuration={}
  with open(configfile) as json_data:
      GLB_configuration = json.load(json_data)
  #Get log names
  if "log" in GLB_configuration:
      if "logTraces" in GLB_configuration["log"]:
        cfg_log_traces = GLB_configuration["log"]["logTraces"]
      if "logExceptions" in GLB_configuration["log"]:
        cfg_log_exceptions = GLB_configuration["log"]["logExceptions"]
  helper.init(cfg_log_traces,cfg_log_exceptions)
  print('See logs traces in: {0} and exeptions in: {1}-----------'.format(cfg_log_traces,cfg_log_exceptions))  
  helper.internalLogger.critical('smartCam-start -------------------------------')  
  helper.einternalLogger.critical('smartCam-start -------------------------------')

  try:
        os.makedirs(GLB_configuration["mediaPath"])
  except FileExistsError:
        # directory already exists
        pass
  
  mountBindMediaPath(False)
  mountBindMediaPath(True)
 
  try:
    apiRestTask=threading.Thread(target=apirest_task,name="restapi")
    apiRestTask.daemon = True
    apiRestTask.start()

  except Exception as e:
    helper.internalLogger.critical("Error processing GLB_configuration json {0} file. Exiting".format(configfile))
    helper.einternalLogger.exception(e)
    loggingEnd()
    return  

  try:    

     while True:
       #helper.internalLogger.critical("Polling, nothing to poll yet")
       time.sleep(1)


  except Exception as e:
    e = sys.exc_info()[0]
    helper.internalLogger.critical('Error: Exception unprocessed properly. Exiting')
    helper.einternalLogger.exception(e)  
    print('smartCam-General exeception captured. See log:{0}',format(cfg_log_exceptions))        
    mountBindMediaPath(False)
    loggingEnd()
Example #24
0
    # If you need to invert the black/white data image
    # im_blur = np.invert(im_blur)
    #Convert back to BGR for cv2
    #im_cloud_blur = cv2.cvtColor(im_cloud_blur,cv2.COLOR_GRAY2BGR)

    # Apply colormap
    im_cloud_clr = cv2.applyColorMap(im_cloud_blur, colormap)

    # blend images 50/50
    return (a1 * im_map + a2 * im_cloud_clr).astype(np.uint8)


if __name__ == "__main__":
    seqname = sys.argv[1]
    helper.init(seqname)

    # Test model
    model = mod_vgg16.create_my_model_without_dropout()
    model.load_weights('./trained_weights.h5')
    adam = Adam(lr=0.001)
    model.compile(loss='sparse_categorical_crossentropy',
                  optimizer=adam,
                  metrics=['accuracy'])

    for layer in model.layers:
        layer.trainable = False

    dataset_train, dataset_test = helper.getKings()

    X_test = np.squeeze(np.array(dataset_test.images))
def room_thread():
    global room_ui_requests

    @prehook
    def room_prehook_callback():
        batch([{"type": "death", "fact": [["id", get_my_id_str()]]}])

    @subscription([
        "$ $ paper $targetId has RFID $rfid",
        "$ $ $targetName has paper ID $targetId",
        "$ $ $targetName has source code $sourceCode"
    ])
    def rfid_source_code_callback(results):
        rfid_to_source_code = {}
        if results:
            for result in results:
                source_code = result["sourceCode"].replace(chr(9787), '"')
                rfid_to_source_code[result["rfid"]] = (result["targetName"],
                                                       source_code)
        room_rfid_code_updates.put(rfid_to_source_code)
        print("updated RFID to source code map")

    init(__file__, skipListening=True)

    while True:
        listen(blocking=False)
        try:
            message = room_ui_requests.get(block=False)
            if message is None:
                print("received none message in room thread, exiting")
                return
            req_type = message[0]
            active_rfid = message[1]
            active_program_name = message[2]
            source_code = message[3]
            clean_source_code = source_code.replace('"', chr(9787))
            if req_type == ROOM_REQUEST_SAVE:
                batch([{
                    "type":
                    "claim",
                    "fact": [
                        ["id", get_my_id_str()],
                        ["id", "0"],
                        ["text", "wish"],
                        ["text", active_program_name],
                        ["text", "has"],
                        ["text", "source"],
                        ["text", "code"],
                        ["text", clean_source_code],
                    ]
                }])
            elif req_type == ROOM_REQUEST_PRINT:
                generate_and_upload_code_image("Code for {}\n\n{}".format(
                    active_program_name, clean_source_code))
                batch([{
                    "type":
                    "claim",
                    "fact": [
                        ["id", get_my_id_str()],
                        ["id", "0"],
                        ["text", "wish"],
                        ["text", "1854-code.png"],
                        ["text", "would"],
                        ["text", "be"],
                        ["text", "thermal"],
                        ["text", "printed"],
                        ["text", "on"],
                        ["text", "epson"],
                    ]
                }])
            elif req_type == ROOM_REQUEST_PRINT_FRONT:
                generate_and_upload_code_front_image(active_program_name)
                batch([{
                    "type":
                    "claim",
                    "fact": [
                        ["id", get_my_id_str()],
                        ["id", "0"],
                        ["text", "wish"],
                        ["text", "1854-front.png"],
                        ["text", "would"],
                        ["text", "be"],
                        ["text", "thermal"],
                        ["text", "printed"],
                        ["text", "on"],
                        ["text", "epson"],
                    ]
                }])
        except queue.Empty:
            pass
        time.sleep(0.1)
Example #26
0
def main(host, port, lc, configfile):
    print('SCSEM-start -----------------------------')

    # Loading config file,
    # Default values
    cfg_log_traces = "scsem.log"
    cfg_log_exceptions = "scseme.log"
    cfg_SensorsDirectory = {}
    cfg_lc = lc
    cfg_database_dbhost = host
    cfg_database_dbport = port
    cfg_bt_enable = True
    cfg_bt_retryTimeSeconds = 20
    # Let's fetch data
    with open(configfile) as json_data:
        configuration = json.load(json_data)
    #Get log names
    if "log" in configuration:
        if "logTraces" in configuration["log"]:
            cfg_log_traces = configuration["log"]["logTraces"]
        if "logExceptions" in configuration["log"]:
            cfg_log_exceptions = configuration["log"]["logExceptions"]
    helper.init(cfg_log_traces, cfg_log_exceptions)
    print('See logs traces in: {0} and exeptions in: {1}-----------'.format(
        cfg_log_traces, cfg_log_exceptions))
    helper.internalLogger.critical(
        'SCSEM-start -------------------------------')
    helper.einternalLogger.critical(
        'SCSEM-start -------------------------------')
    try:
        #Get sensors list
        cfg_SensorsDirectory = configuration["Sensors"]
        #Override args if available in config file
        if "launchContainers" in configuration:
            cfg_lc = configuration["launchContainers"]
        if "DataBase" in configuration:
            if "dbhost" in configuration["DataBase"]:
                cfg_database_host = configuration["DataBase"]["dbhost"]
            if "dbport" in configuration["DataBase"]:
                cfg_database_port = configuration["DataBase"]["dbport"]
        if "BluetoothSettings" in configuration:
            if "isBtEnabled" in configuration["BluetoothSettings"]:
                cfg_bt_enabled = configuration["BluetoothSettings"][
                    "isBtEnabled"]
                if not cfg_bt_enabled:
                    helper.internalLogger.warning(
                        "Bluetooth devices are not enabled this time in config."
                    )
            if "retryTimeSeconds" in configuration["BluetoothSettings"]:
                cfg_bt_retryTimeSeconds = configuration["BluetoothSettings"][
                    "retryTimeSeconds"]

    except Exception as e:
        helper.internalLogger.critical(
            "Error processing configuration json {0} file. Exiting".format(
                configfile))
        helper.einternalLogger.exception(e)
        loggingEnd()
        return

    if cfg_lc == True:
        launchContainers()

    try:
        hdlDB = dbWrapper(cfg_database_host,
                          cfg_database_port,
                          user='******',
                          password='******',
                          dbname='db_emem',
                          dbuser='******',
                          dbpss='emem')

        for key, item in cfg_SensorsDirectory.items():
            if item['devType'] == "BT":
                if not cfg_bt_enabled:
                    helper.internalLogger.debug(
                        "Skipping creating BT object handler, bluethooth devices are disabled."
                    )
                    continue
                helper.internalLogger.debug("Creating BT object handler...")
                x = btWrapper(key,
                              item,
                              speed=9600,
                              timeout=cfg_bt_retryTimeSeconds)
                x.tryReconnect()
            elif item['devType'] == "LOCAL":
                helper.internalLogger.debug(
                    "Creating local DHT object handler...")
                x = localDhtWrapper(key, item)
            else:
                helper.internalLogger.error(
                    "Unknown sensor device type, ignoring it")
                continue
            item['handler'] = x
            sensorTask = threading.Thread(target=sensor_task,
                                          args=(
                                              key,
                                              item,
                                              hdlDB,
                                          ),
                                          name=key)
            sensorTask.daemon = True
            sensorTask.start()

        while True:
            time.sleep(1)

    except Exception as e:
        e = sys.exc_info()[0]
        helper.internalLogger.critical(
            'Error: Exception unprocessed properly. Exiting')
        helper.einternalLogger.exception(e)
        print('SCSEM-General exeception captured. See ssms.log:{0}',
              format(cfg_log_exceptions))
        loggingEnd()
Example #27
0

if __name__ == '__main__':
    import argparse
    # ----#-   Main
    parser = argparse.ArgumentParser(
        description="D&D web server",
        epilog="The server runs locally on port 5000 if PORT is not specified."
    )
    parser.add_argument("-f",
                        dest="file",
                        help="The location of the database file")
    parser.add_argument("-p",
                        dest="port",
                        help="The port where the server will run")
    args = parser.parse_args()
    helper.init(args.file)

    if args.port is not None:  # Public System
        port = int(args.port)
        host = '0.0.0.0'
        debug = False
    else:  # Private System
        port = 5000
        host = '127.0.0.1'
        debug = False

        print('safari-http://%s:%d/' % (host, port))

    app.run(host=host, port=port, debug=debug, use_reloader=False)
Example #28
0
import helper as app

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

    app.process()
    
    app.end()
Example #29
0
from helper import init, moveDisk


def towers(nd, source, dest):
    if nd > 0:
        temp = 3 - source - dest
        towers(nd - 1, source, temp)
        moveDisk(source, dest)
        towers(nd - 1, temp, dest)


n = 3
init(n)
towers(n, 0, 2)
Example #30
0
#change those depending on sideLength
flt_bridgeLayerOneExtrude = 1.5#1#
flt_bridgeLayerOneFeed = 1000#50#
flt_bridgeLayerTwoExtrude = 3
flt_bridgeLayerTwoFeed = 500#40#
int_bridgePause = 1000

#roof only
rExtrude = 1.5#0.8
rFeed = 4000
rShiftValue = 0.5
rWait = 200
#########
str_targetFile = "fast_cube_%dmm.gcode" % int_sideLength

str_gcode = helper.init()

str_gcode += """
;init
G1 X30 E20
"""

str_gcode += helper.print_square(int_sideLength, flt_squareExtrude)

str_gcode += """
"""

str_gcode += """
;first pillar
"""
Example #31
0
        )

    if not html:
        return abort(404)

    return final_pass(html)

if __name__ == '__main__':
    import argparse
    # ----#-   Main
    parser = argparse.ArgumentParser(description="D&D web server", epilog="The server runs locally on port 5000 if PORT is not specified.")
    parser.add_argument("-f", dest="file", help="The location of the database file")
    parser.add_argument("-p", dest="port", help="The port where the server will run")
    parser.add_argument("-m", dest="message", help="A message to display on the site")
    args = parser.parse_args()
    helper.init(args.file)

    if args.port is not None: # Public System
        port = int(args.port)
        host = '0.0.0.0'
        debug = False
    else: # Private System
        port = 5000
        host = '127.0.0.1'
        debug = False

        print('safari-http://%s:%d/' % (host, port))
    
    app.config['message'] = args.message

    app.run(host=host, port=port, debug=debug, use_reloader=False)
Example #32
0
    framerate = 0
    frametimer = time.time()
    while True:
        stepr += 1
        threading.Thread(
            target=glb.allstep,
            daemon=True,
        ).start()
        #glb.allstep()
        glb.canvas.step()

        st = time.time()

        if stepr % 250 == 0:
            for i in range(2):
                helper.makenewenemy()

        while time.time() - st <= 1 / frametarget:
            pass
        framerate += 1
        if time.time() - frametimer >= 1:
            print("FR: ", framerate)
            frametimer = time.time()
            framerate = 0


if __name__ == "__main__":
    print("\033[1;37;40mStarting Program...")
    glb.init()
    start()
Example #33
0
async def handle_msg(context):
    # 下面这句等价于 bot.send_private_msg(user_id=context['user_id'], message='你好呀,下面一条是你刚刚发的:')
    """
    try:
         await bot.send(context, '你好呀,下面一条是你刚刚发的:')
     except ApiError:
         pass
    """
    global last_cmd
    global last_arg_str
    global last_arg_int
    message = context['message']
    if message.startswith('@{}'.format(config.default_qq_name)):
        message = message[4:]
    message = message.strip()
    cmd_args = message.split(' ')
    cmd = cmd_args[0]
    args = cmd_args[1:] if len(cmd_args) > 1 else []

    def is_all_number(_str: str):
        if _str is None or _str == '':
            return False
        for a in _str:
            if not '0' <= a <= '9':
                return False
        return True

    arg_int = int(args[0]) if len(args) > 0 and is_all_number(args[0]) else 0
    arg_int_2 = int(args[1]) if len(args) > 1 and is_all_number(args[1]) else 0
    arg_str = args[0] if len(args) > 0 else ''

    if cmd == '-help' or cmd == '-?':
        msg = '● 用户信息 -user'
        msg += '\n● 排行榜  -rank [index]'
        msg += '\n● 查询文件 -find [keyword]'
        msg += '\n● 文件信息 -info [id]'
        msg += '\n● 更多信息 -more'
        msg += '\n' + '-' * 38
        msg += '\n* 直接输入CSDN下载页链接即可下载'
        msg += '\n* 大黄鸭源码 http://t.cn/EK5Q58Y'
        await bot.send(context, msg)

    if cmd == '-user':
        await bot.send(context, '查询用户信息中...')
        helper.init()
        info = helper.get_user_info()
        helper.dispose()
        if info is None:
            msg = '获取用户信息失败!'
        else:
            msg = '{}'.format(info['name'])
            if info['vip']:
                msg += '【VIP】'
                msg += '\n剩余次数:{}次'.format(info['remain'])
                msg += '\n有效期至:{}'.format(info['date'][:10])
            else:
                msg += '\n剩余积分:{}积分'.format(info['remain'])
        await bot.send(context, msg)

    if cmd == '-rank':
        result = db_helper.rank_qq(arg_int)
        msg = build_rank_msg(result, arg_int)
        last_cmd = cmd
        last_arg_int = arg_int
        await bot.send(context, msg)

    if cmd == '-find':
        result = db_helper.find_all(arg_str, arg_int_2)
        count = db_helper.count_all(arg_str)
        msg = build_find_msg(result, count, arg_int_2)
        last_cmd = cmd
        last_arg_str = arg_str
        last_arg_int = arg_int_2
        await bot.send(context, msg)

    if cmd == '-info':
        result = db_helper.get_download(arg_int)
        if result is not None:
            msg = build_download_info(result)
            last_cmd = cmd
            last_arg_str = arg_str
            last_arg_int = arg_int
            await bot.send(context, msg)
        else:
            await bot.send(context, '文件不存在。')

    if cmd == '-more':
        if last_cmd == '-find':
            last_arg_int += 10
            result = db_helper.find_all(last_arg_str, last_arg_int)
            count = db_helper.count_all(arg_str)
            msg = build_find_msg(result, count, last_arg_int)
            await bot.send(context, msg)
        if last_cmd == '-rank':
            last_arg_int += 10
            result = db_helper.rank_qq(last_arg_int)
            msg = build_rank_msg(result, last_arg_int)
            await bot.send(context, msg)
        if last_cmd == '-info':
            result = db_helper.get_download(last_arg_int)
            if result is not None:
                msg = build_download_detail_info(result)
                await bot.send(context, msg)

    download_url = find_csdn_download_url(context['message'])
    if download_url is not None:
        if helper.is_busy():
            await bot.send(context, '资源正在下载中,请稍后...')
            return
        await bot.send(context, '开始下载...')
        try:
            helper.init()
            qq_num = context['sender']['user_id']
            qq_name = context['sender']['nickname']
            if 'card' in context['sender'] and context['sender']['card'] != '':
                qq_name = context['sender']['card']
            download_info = helper.auto_download(download_url, qq_num, qq_name)
            msg = download_info['message']
            if download_info['success']:
                result = db_helper.get_download(download_info['info']['id'])
                msg = build_download_info(result)
                last_cmd = '-info'
                last_arg_int = int(result.id)
            await bot.send(context, msg)
        finally:
            helper.dispose()