コード例 #1
0
    def test_1_status_handle(self):
        with patch.dict('main._CONF', self.conf):
            with patch('main.get_buy_signal', side_effect=lambda _: True):
                msg_mock = MagicMock()
                with patch.multiple('main.telegram',
                                    _CONF=self.conf,
                                    init=MagicMock(),
                                    send_msg=msg_mock):
                    with patch.multiple(
                            'main.exchange',
                            get_ticker=MagicMock(return_value={
                                'bid': 0.07256061,
                                'ask': 0.072661,
                                'last': 0.07256061
                            }),
                            buy=MagicMock(return_value='mocked_order_id')):
                        init(self.conf, 'sqlite://')

                        # Create some test data
                        trade = create_trade(15.0, exchange.Exchange.BITTREX)
                        self.assertTrue(trade)
                        Trade.session.add(trade)
                        Trade.session.flush()

                        _status(bot=MagicBot(), update=self.update)
                        self.assertEqual(msg_mock.call_count, 2)
                        self.assertIn('[BTC_ETH]',
                                      msg_mock.call_args_list[-1][0][0])
コード例 #2
0
    def test_2_profit_handle(self):
        with patch.dict('main._CONF', self.conf):
            with patch('main.get_buy_signal', side_effect=lambda _: True):
                msg_mock = MagicMock()
                with patch.multiple('main.telegram',
                                    _CONF=self.conf,
                                    init=MagicMock(),
                                    send_msg=msg_mock):
                    with patch.multiple(
                            'main.exchange',
                            get_ticker=MagicMock(return_value={
                                'bid': 0.07256061,
                                'ask': 0.072661,
                                'last': 0.07256061
                            }),
                            buy=MagicMock(return_value='mocked_order_id')):
                        init(self.conf, 'sqlite://')

                        # Create some test data
                        trade = create_trade(15.0, exchange.Exchange.BITTREX)
                        self.assertTrue(trade)
                        trade.close_rate = 0.07256061
                        trade.close_profit = 100.00
                        trade.close_date = datetime.utcnow()
                        trade.open_order_id = None
                        trade.is_open = False
                        Trade.session.add(trade)
                        Trade.session.flush()

                        _profit(bot=MagicBot(), update=self.update)
                        self.assertEqual(msg_mock.call_count, 2)
                        self.assertIn('(100.00%)',
                                      msg_mock.call_args_list[-1][0][0])
コード例 #3
0
ファイル: run.py プロジェクト: 6QHTSK/paper-database
def config():
    conf = configparser.ConfigParser()
    if os.path.exists("setting.ini"):  # 如果存在config文件,则调用设置
        conf.read("setting.ini")
        host = conf.get("API", "host", fallback='0.0.0.0')
        port = conf.getint("API", "port", fallback=10501)
        update_interval = conf.getint("UPDATE",
                                      "update_interval",
                                      fallback=86400)
        main.init(host, port, update_interval)

        cool_down = conf.getint("UPDATE", "cool_down", fallback=10800)
        request_max_result = conf.getint("UPDATE",
                                         "request_max_result",
                                         fallback=1000)
        pdf_fetch_start_time = conf.getint("UPDATE",
                                           "pdf_fetch_start_time",
                                           fallback=1601481600)
        pdf_fetch_end_time = conf.getint("UPDATE",
                                         "pdf_fetch_end_time",
                                         fallback=1609430400)
        update.init(cool_down, request_max_result, pdf_fetch_start_time,
                    pdf_fetch_end_time)
    else:  # 否则生成设置
        generate_config()
        main.init()
        update.init()
コード例 #4
0
def test_init(mocker):
    # run wrapper validity: https://medium.com/opsops/how-to-test-if-name-main-1928367290cb
    mocker.patch.object(main, "main", return_value=42)
    mocker.patch.object(main, "__name__", "__main__")
    mocker.patch.object(main.sys, 'exit')
    main.init()
    assert main.sys.exit.call_args[0][0] == 42
コード例 #5
0
ファイル: Menu.py プロジェクト: DaniloGR91/Curso_Python3
    def escolher_opcao(self):
        if self.opcao == 1:
            return self.opcao

        if self.opcao == 2:
            if self.agencia_atual == 1111:

                while True:
                    agencia_nome = input('Digite o nome da agência: ').strip()
                    agencia_numero = input('Digite a agência: ').strip()
                    if self.validar_nova_agencia(agencia_nome, agencia_numero):
                        super().cadastrar_agencia(agencia_nome=agencia_nome,
                                                  agencia_numero=int(agencia_numero))
                        break
            else:
                print(
                    'Apenas a agência 1111 tem autorização para cadastrar uma nova agência')

        if self.opcao == 3:
            return self.opcao

        if self.opcao == 4:
            from main import init
            init()

        if self.opcao == 5:
            print('Obrigado por usar o nosso sistema')
            sys.exit()
            return
コード例 #6
0
ファイル: test.py プロジェクト: youzhonghui/Adence
 def test_login(self):
     with main.app.app_context():
         main.init()
         self.register()
         res = self.login()
         res = json.loads(res.data.decode())
         assert res.get('status') == 'success'
コード例 #7
0
ファイル: test.py プロジェクト: youzhonghui/Adence
    def test_check(self):
        with main.app.app_context():
            main.init()
            self.insert_fake_key_list()
            param = dict(
                verify=main.app.config['verify'],
                time=datetime.datetime.now().strftime('%Y-%m-%d %H.%M.%S'),
                data=dict(id=self.user_id)
            )
            res = self.send_request('check', param)
            res = json.loads(res.data.decode())
            assert res.get('status') == 'not registered'

            self.register()
            res = self.send_request('check', param)
            res = json.loads(res.data.decode())
            assert res.get('status') == 'not logged'

            self.send_request('trigger', param)
            res = self.send_request('check', param)
            res = json.loads(res.data.decode())
            assert res.get('status') == 'logged'

            self.send_request('trigger', param)
            res = self.send_request('check', param)
            res = json.loads(res.data.decode())
            assert res.get('status') == 'not logged'
コード例 #8
0
ファイル: gui.py プロジェクト: MariusDinu/CN
def start_gui():
    global val, w, root
    root = Tk()
    root.resizable(False, False)
    top = CN_gui(root)  # aici sa seteza setarile pt layout
    main.init(root, top)
    root.mainloop()
コード例 #9
0
ファイル: test_main.py プロジェクト: mygirl8893/freqtrade.old
 def test_1_create_trade(self):
     with patch.dict('main._CONF', self.conf):
         with patch('main.get_buy_signal',
                    side_effect=lambda _: True) as buy_signal:
             with patch.multiple('main.telegram',
                                 init=MagicMock(),
                                 send_msg=MagicMock()):
                 with patch.multiple(
                         'main.exchange',
                         get_ticker=MagicMock(return_value={
                             'bid': 0.07256061,
                             'ask': 0.072661,
                             'last': 0.07256061
                         }),
                         buy=MagicMock(return_value='mocked_order_id')):
                     init(self.conf, 'sqlite://')
                     trade = create_trade(15.0, exchange.Exchange.BITTREX)
                     Trade.session.add(trade)
                     Trade.session.flush()
                     self.assertIsNotNone(trade)
                     self.assertEqual(trade.open_rate, 0.072661)
                     self.assertEqual(trade.pair, 'BTC_ETH')
                     self.assertEqual(trade.exchange,
                                      exchange.Exchange.BITTREX)
                     self.assertEqual(trade.amount, 206.43811673387373)
                     self.assertEqual(trade.btc_amount, 15.0)
                     self.assertEqual(trade.is_open, True)
                     self.assertIsNotNone(trade.open_date)
                     buy_signal.assert_called_once_with('BTC_ETH')
コード例 #10
0
    def setUp(self):
        main.init(False)
        main.set_system_state(self.system_state)

        for robot in main.system_state().their_robots:
            robot.set_vis_for_testing(True)

        self.length = constants.Field.Length
        self.width = constants.Field.Width
        self.botRadius = constants.Robot.Radius

        self.center_y = self.length / 2
        self.right_side = self.width / 2
        self.left_side = -self.width / 2

        self.their_robots = main.system_state().their_robots[0:6]
        self.our_robots = main.system_state().our_robots[0:6]
        self.ball = main.system_state().ball
        self.ball.set_pos_for_testing(robocup.Point(0, 0))

        for our_robot, their_robot in zip(self.our_robots, self.their_robots):
            our_robot.set_vis_for_testing(False)
            their_robot.set_vis_for_testing(False)

        main.set_their_robots(main.system_state().their_robots[0:6])
        main.set_our_robots(main.system_state().our_robots[0:6])
        main.set_ball(main.system_state().ball)
コード例 #11
0
def zsy(d, count, answer_delay, delay_max, delay_min):
    unknown = []
    main.init(d)
    d(resourceId="cn.xuexi.android:id/comm_head_xuexi_mine").click()
    time.sleep(5)
    d.xpath(
        '//*[@resource-id="cn.xuexi.android:id/my_recycler_view"]/android.widget.LinearLayout['
        '3]/android.widget.ImageView[1]').click()
    time.sleep(5)
    d.xpath(
        '//*[@resource-id="app"]/android.view.View[1]/android.view.View[3]/android.view.View[9]'
    ).click()
    load_dict = tiaozhandati.loadanswer() + tiaozhandati.loadunknown()
    for i in range(0, count):
        d.xpath('//*[@text="开始比赛"]').click()
        time.sleep(4)
        if d.xpath('//*[@text="知道了"]').exists:
            d.xpath('//*[@text="知道了"]').click()
            return -1
        unknown = zsydati(d, load_dict, answer_delay)
        if len(unknown) > 0:
            print(unknown)
        time.sleep(random.randint(delay_min, delay_max))
        if len(unknown) > 0:
            data = unknown + tiaozhandati.loadunknown()
            with open("unknown.json", 'w', encoding='utf-8') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
            time.sleep(20)
            print("生成题库完成")

    d.xpath('//*[@text=""]').click()
    time.sleep(2)
    return count
コード例 #12
0
	def setUp(self):
		main.init(False)
		main.set_system_state(self.system_state)

		for robot in main.system_state().their_robots:
			robot.set_vis_for_testing(True)

		self.length = constants.Field.Length
		self.width = constants.Field.Width
		self.botRadius = constants.Robot.Radius

		self.center_y = self.length / 2
		self.right_side = self.width / 2
		self.left_side = -self.width / 2

		self.their_robots = main.system_state().their_robots[0:6]
		self.our_robots = main.system_state().our_robots[0:6]
		self.ball = main.system_state().ball
		self.ball.set_pos_for_testing(robocup.Point(0, 0))

		for our_robot, their_robot in zip(self.our_robots, self.their_robots):
			our_robot.set_vis_for_testing(False)
			their_robot.set_vis_for_testing(False)

		main.set_their_robots(main.system_state().their_robots[0:6])
		main.set_our_robots(main.system_state().our_robots[0:6])
		main.set_ball(main.system_state().ball)
コード例 #13
0
def vp_start_gui():
    '''Starting point when module is the main routine.'''
    global val, w, root
    root = tk.Tk()
    main.set_Tk_var()
    top = Toplevel1 (root)
    main.init(root, top)
    root.mainloop()
コード例 #14
0
    def goto_main(self):
        """
        go to main GUI function
        """
        # destroy login GUI
        self.root.destroy()

        # enter main GUI
        main.init()
コード例 #15
0
def create_Toplevel1(root, *args, **kwargs):
    '''Starting point when module is imported by another program.'''
    global w, w_win, rt
    rt = root
    w = tk.Toplevel (root)
    main.set_Tk_var()
    top = Toplevel1 (w)
    main.init(w, top, *args, **kwargs)
    return (w, top)
コード例 #16
0
def make_app():

    import main
    my_app.create_label = main.create_label
    my_app.tts_func = {}
    my_app.tts_func["hecuiru"] = main.init("hecuiru")
    my_app.tts_func["15521387651"] = main.init("15521387651")

    my_app.run(host="0.0.0.0", port=8891, debug=False)
    print("listening %s" % 8891)
コード例 #17
0
def daily_job():
    main.init()
    try:
        main.scrap()
    except Exception as ex:
        traceback.print_exc()
    try:
        main.map(update_prediction=False, any=True)
    except Exception as ex:
        traceback.print_exc()
コード例 #18
0
def weekly_job_2():
    main.init()
    try:
        main.fit(True)
    except Exception as ex:
        traceback.print_exc()
    try:
        main.map(any=True)
    except Exception as ex:
        traceback.print_exc()
コード例 #19
0
ファイル: test.py プロジェクト: youzhonghui/Adence
    def test_admin_session_authentication(self):
        with main.app.app_context():
            main.init()
            c = main.app.test_client()
            session_id = web_interface.gen_random_string(512)
            main.app.config['SESSIONS'][session_id] = datetime.datetime.now()
            c.set_cookie('localhost', 'session_id', session_id)
            assert c.get('/test_shell/admin').status_code == 200

            # session过期
            main.app.config['session_expire'] = -1
            assert c.get('/test_shell/admin').status_code == 400
コード例 #20
0
ファイル: test.py プロジェクト: youzhonghui/Adence
    def test_delete(self):
        with main.app.app_context():
            main.init()
            self.register()
            param = dict(
                verify=main.app.config['verify'],
                time=datetime.datetime.now().strftime('%Y-%m-%d %H.%M.%S'),
                data=dict(id=self.user_id)
            )

            res = self.send_request('delete', param)
            res = json.loads(res.data.decode())
            assert res.get('status') == 'success'
コード例 #21
0
ファイル: genDatabase.py プロジェクト: Gahon1995/mongo
def main():
    from config import Config
    Config.log_in_file = True
    Config.log_file_name = './genDatabase.log'
    Config.is_import = True

    from main import init
    init()

    reset_db()

    IdsService(is_import=True)

    gen_data()
コード例 #22
0
ファイル: test.py プロジェクト: youzhonghui/Adence
    def setUp(self):
        main.app.config.update(dict(
            DATABASE=main.get_file_path('testing.db.sqlite'),
            SETTINGS_FILE=main.get_file_path('testing.settings.dump')
        ))
        self.app = main.app.test_client()
        with main.app.app_context():
            main.init()
            assert os.path.exists(main.app.config['DATABASE'])
            assert os.path.exists(main.app.config['SETTINGS_FILE'])

        self.user_id = 1234567890111
        self.student_number = 2012060050003
        self.user_name = '奥特曼'
コード例 #23
0
ファイル: test.py プロジェクト: youzhonghui/Adence
 def test_param_decode(self):
     with main.app.app_context():
         main.init()
         self.insert_fake_key_list()
         param = dict(
             verify=main.app.config['verify'],
             time='tmp',
             data={'c': 'Hello'}
         )
         with open('pems/3.pub', 'r') as fp:
             pub_key = fp.read()
         crypto = rsa.encrypt(json.dumps(param).encode(),
                              rsa.PublicKey.load_pkcs1(pub_key.encode()))
         a, b, c = slave_interface.param_decode(crypto)
コード例 #24
0
    def test_5_start_handle(self):
        with patch.dict('main._CONF', self.conf):
            msg_mock = MagicMock()
            with patch.multiple('main.telegram',
                                _CONF=self.conf,
                                init=MagicMock(),
                                send_msg=msg_mock):
                init(self.conf, 'sqlite://')

                update_state(State.STOPPED)
                self.assertEqual(get_state(), State.STOPPED)
                _start(bot=MagicBot(), update=self.update)
                self.assertEqual(get_state(), State.RUNNING)
                self.assertEqual(msg_mock.call_count, 0)
コード例 #25
0
ファイル: DL.py プロジェクト: newdaytrue/DeepLearning
def make_data(num):
    xd=[]
    yd=[]
    for size in range(num):
        main.init()
        number=random.randrange(0,10000)
        main.run(number)
        xd.append(main.photo)
        yd.append(number)
    xd=np.array(xd)
    yd=np.array(yd)
    xd=np.reshape(xd,[-1,16,64,1])
    yd=np.reshape(yd,[-1,1])
    return xd,yd
コード例 #26
0
def test_init(monkeypatch):
    ctx = CtxMock()

    mock_currency = "EUR"

    def getenv_mocked(var):
        if var == "OUTPUT_PRICE_CURRENCY":
            return mock_currency
        else:
            raise Exception("Must get OUTPUT_PRICE_CURRENCY env var")

    monkeypatch.setattr(os, "getenv", getenv_mocked)

    init(ctx)
    ctx.set.assert_called_once_with("currency", mock_currency)
コード例 #27
0
 def post(self):
     filesDict = self.request.files
     for inputname in filesDict:
         http_file = filesDict[inputname]
         for fileObj in http_file:
             if fileObj.filename.endswith('.txt'):
                 filePath = os.path.join(
                     os.path.dirname(__file__) + '/paper/',
                     fileObj.filename)
                 with open(filePath, 'wb') as f:
                     f.write(fileObj.body)
                     main.init()
                     self.write('file upload success')
             else:
                 self.write('file is error')
コード例 #28
0
ファイル: eval.py プロジェクト: aobo-y/multitask-rank
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-m',
                        '--model',
                        help='model name to save/load checkpoints')
    parser.add_argument('-c', '--checkpoint')
    parser.add_argument('evals', nargs='+')
    args = parser.parse_args()

    torch.no_grad()

    model, misc = init(args.model, args.checkpoint)
    model.eval()

    test_dataset = load_test_dataset()

    for ev in args.evals:
        if ev == 'rmse':
            mse = test_rate_mse(test_dataset, model)
            print('Rate RMSE: ', mse)

        elif ev == 'ndcg':
            ndcg_path = os.path.join(DIR_PATH, 'data/ndcg_150.ls')
            ndcg_user_items = load_ndcg(ndcg_path)

            print('User size:', len(ndcg_user_items))

            vals = next(iter(ndcg_user_items.values()))
            size = len(vals)

            avg_ndcg, ndcg = test_rate_ndcg(model, test_dataset,
                                            ndcg_user_items)
            print(f'Rate NDCG({size}):', avg_ndcg, ndcg)
コード例 #29
0
ファイル: test.py プロジェクト: youzhonghui/Adence
 def test_register(self):
     with main.app.app_context():
         main.init()
         assert self.register() == 'success'
         param = dict(
             verify=main.app.config['verify'],
             time=datetime.datetime.now().strftime('%Y-%m-%d %H.%M.%S'),
             data=dict(
                 id=self.user_id,
                 name=self.user_name,
                 student_number=self.student_number
             )
         )
         res = self.send_request('/register', param)
         res = json.loads(res.data.decode())
         assert res.get('status') == 'failed'
コード例 #30
0
ファイル: test_drivers.py プロジェクト: hpagseddy/ZPUI
 def test_pygame_driver(self):
     input_config = {"driver": "pygame_input"}
     config = deepcopy(base_config)
     config["input"][0] = input_config
     assert (config["output"][0]["driver"] == "test_output")
     module_patch = patch.dict('sys.modules', {"luma.emulator.device":Mock(), \
                                               "luma.emulator":Mock()})
     module_patch.start()
     import sys
     print([(key, sys.modules[key]) for key in sys.modules.keys()
            if key.startswith('luma.emulator')])
     sys.modules['luma.emulator'].configure_mock(device2=Mock())
     print(sys.modules['luma.emulator'])
     print(sys.modules['luma.emulator.device'])
     import emulator as emulator_py
     with patch.object(emulator_py.Emulator, 'init_hw') as init_hw, \
       patch.object(emulator_py.Emulator, 'runner') as runner, \
       patch.object(emulator_py.EmulatorProxy, 'start_process'):
         with patch.object(main_py, 'load_config') as mocked:
             mocked.return_value = (config, "test_config.json")
             i, o = main_py.init()
     assert (isinstance(i, main_py.input.InputProxy))
     assert (isinstance(o, main_py.output.OutputProxy))
     module_patch.stop()
     print([(key, sys.modules[key]) for key in sys.modules.keys()
            if key.startswith('luma.emulator')])
     # so that no ugly exception is raised when the test finishes
     main_py.input_processor.atexit()
コード例 #31
0
    def setup_class(cls) -> None:
        print("=" * 50 + "INIT" + "=" * 50)
        # print("连接数据库")
        Config.redis_enable = False
        Config.log_in_file = False
        # DBMS().db_name = 'test'
        init()

        # app.testing = True
        # cls.client = app.test_client()
        Web().session.testing = True
        # Web().run()
        cls.client = Web().session.test_client()
        cls.header = {'Content-Type': 'application/json'}
        # api_rules()
        print("=" * 50 + "INIT FINISH" + "=" * 50)
コード例 #32
0
    def test_6_stop_handle(self):
        with patch.dict('main._CONF', self.conf):
            msg_mock = MagicMock()
            with patch.multiple('main.telegram',
                                _CONF=self.conf,
                                init=MagicMock(),
                                send_msg=msg_mock):
                init(self.conf, 'sqlite://')

                update_state(State.RUNNING)
                self.assertEqual(get_state(), State.RUNNING)
                _stop(bot=MagicBot(), update=self.update)
                self.assertEqual(get_state(), State.STOPPED)
                self.assertEqual(msg_mock.call_count, 1)
                self.assertIn('Stopping trader',
                              msg_mock.call_args_list[0][0][0])
コード例 #33
0
ファイル: test_base.py プロジェクト: Gahon1995/mongo
    def setup_class(cls) -> None:
        print("=" * 50 + "INIT" + "=" * 50)
        # print("连接数据库")
        Config.redis_enable = False
        Config.log_in_file = False
        DBMS.db_name = 'test'

        init()

        Gen.USERS_NUM = 100
        Gen.ARTICLES_NUM = 100
        Gen.READS_NUM = 100

        Gen.gen_data()
        print()
        print("=" * 50 + "INIT FINISH" + "=" * 50)
        pass
コード例 #34
0
ファイル: test.py プロジェクト: youzhonghui/Adence
 def test_register_with_student_number(self):
     with main.app.app_context():
         main.init()
         self.insert_fake_key_list()
         param = dict(
             verify=main.app.config['verify'],
             time=datetime.datetime.now().strftime('%Y-%m-%d %H.%M.%S'),
             data=dict(
                 id=self.user_id,
                 name=self.user_name,
                 student_number=self.student_number
             )
         )
         # note: This will failed
         # import time
         res = self.send_request('/register', param)
         res = json.loads(res.data.decode())
         assert res['status'] == 'success'
コード例 #35
0
def show_animation(swing, orphan):
    t = 3
    empty_space = 10 * "\n"

    for i in range(3):
        show_intro(swing)
    os.system('clear')
    ui.show_story()
    os.system('clear')

    for picture in orphan:
        os.system('clear')
        print(empty_space)
        for pictureLine in picture.splitlines():
            print(pictureLine.center(shutil.get_terminal_size().columns))
        time.sleep(t)

    main.init()
コード例 #36
0
ファイル: test.py プロジェクト: youzhonghui/Adence
    def test_csv(self):
        with main.app.app_context():
            main.init()
            self.register()
            param = dict(
                verify=main.app.config['verify'],
                time=datetime.datetime.now().strftime('%Y-%m-%d %H.%M.%S'),
                data=dict(id=self.user_id)
            )
            self.send_request('trigger', param)
            self.send_request('trigger', param)

            ra = self.app.get('/get_csv/2014-01-12 12.12.12/2014-12-12 12.12.12')
            rb = self.app.get('/get_csv')
            # assert ra.data == rb.data

            ra = self.app.get('/get_csv/2014-01-12 12.12.12/2014-01-12 12.12.12')
            assert ra.data != rb.data
コード例 #37
0
def run_server(app, port=8080):
    from tornado.wsgi import WSGIContainer
    from tornado.httpserver import HTTPServer
    from tornado.ioloop import IOLoop
    import main

    # Initialize app and serve.
    http_server = HTTPServer(WSGIContainer(main.init()))
    http_server.listen(port)
    IOLoop.instance().start()
コード例 #38
0
def handle_data():
    nickname = request.form['nickname']
    limit = request.form['limit']
    msg = main.init(nickname, limit)

    # this mean that there is no user with given nickname
    if msg:
        return render_template("unknown.html", nickname=nickname)

    return render_template("Map.html")
コード例 #39
0
ファイル: test_drivers.py プロジェクト: hpagseddy/ZPUI
 def test_st7735(self):
     output_config = {"driver": "st7735", "kwargs": {"hw": "dummy"}}
     config = deepcopy(base_config)
     config["output"][0] = output_config
     assert (config["input"][0]["driver"] == "test_input")
     with patch.object(main_py, 'load_config') as mocked:
         mocked.return_value = (config, "test_config.json")
         i, o = main_py.init()
     assert (isinstance(i, main_py.input.InputProxy))
     assert (isinstance(o, main_py.output.OutputProxy))
コード例 #40
0
ファイル: metrics.py プロジェクト: 419eaterbot/bot
def show(thread=28):
	a,b = init()
	for m in b[thread]['Messages']:
		print "Sender:", b[thread]['Messages'][m]['Sender']
		print "Receiver:", b[thread]['Messages'][m]['Receiver']
		print "Origin:", b[thread]['Messages'][m]['Origin']
		print "Subject:", b[thread]['Messages'][m]['Subject']
		print "\n"
		print "Body:\n", b[thread]['Messages'][m]['Body']
		a = raw_input()
	return
コード例 #41
0
ファイル: test.py プロジェクト: youzhonghui/Adence
    def test_attendance_list(self):
        with main.app.app_context():
            main.init()
            self.register()
            param = dict(
                verify=main.app.config['verify'],
                time=datetime.datetime.now().strftime('%Y-%m-%d %H.%M.%S'),
                data=dict(id=self.user_id)
            )
            self.send_request('trigger', param)

            res = self.app.get('/attendance')
            res = json.loads(res.data.decode())
            assert len(res['data']) == 1
            assert res['data'][0]['name'] == self.user_name

            self.send_request('trigger', param)
            res = self.app.get('/attendance')
            res = json.loads(res.data.decode())
            assert len(res['data']) == 0
コード例 #42
0
ファイル: test.py プロジェクト: youzhonghui/Adence
    def test_query_student_attendance(self):
        with main.app.app_context():
            main.init()
            self.register()
            param = dict(
                verify=main.app.config['verify'],
                time=datetime.datetime.now().strftime('%Y-%m-%d %H.%M.%S'),
                data=dict(id=self.user_id)
            )
            self.send_request('trigger', param)
            self.send_request('trigger', param)
            self.send_request('trigger', param)
            res = self.send_request('trigger', param)
            res = json.loads(res.data.decode())
            assert res.get('status') == 'success'

            res = self.app.get('/student/%s' % self.student_number)
            res = json.loads(res.data.decode())
            assert res['status'] == 'success'
            assert len(res['data']) == 2
コード例 #43
0
def show(thread=28):
    a, b = init()
    for m in b[thread]['Messages']:
        print "Sender:", b[thread]['Messages'][m]['Sender']
        print "Receiver:", b[thread]['Messages'][m]['Receiver']
        print "Origin:", b[thread]['Messages'][m]['Origin']
        print "Subject:", b[thread]['Messages'][m]['Subject']
        print "\n"
        print "Body:\n", b[thread]['Messages'][m]['Body']
        a = raw_input()
    return
コード例 #44
0
ファイル: train.py プロジェクト: aobo-y/multitask-rank
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-m',
                        '--model',
                        help='model name to save/load checkpoints')
    parser.add_argument('-c', '--checkpoint')
    args = parser.parse_args()

    model, misc = init(args.model, args.checkpoint)
    checkpoint, ckpt_mng, model_config = (
        misc[k] for k in ['checkpoint', 'ckpt_mng', 'model_config'])

    kargs = dict(
        batch_size=model_config.BATCH_SIZE,
        lr=model_config.LR,
        l2=model_config.L2_PENALTY,
        clip=model_config.CLIP,
        patience=config.PATIENCE,
        max_iters=model_config.MAX_ITERS,
        save_every=config.SAVE_EVERY,
        loss_type=model_config.LOSS_TYPE,
        grp_config=config.LOSS_TYPE_GRP_CONFIG[model_config.LOSS_TYPE])

    print(f'Training config:',
          {k: v
           for k, v in kargs.items() if k in KARGS_LOG_KEYS})

    trainer = RankerTrainer(model, ckpt_mng, **kargs)

    if checkpoint:
        trainer.resume(checkpoint)
    else:
        ckpt_mng.save_meta()

    trainfile = os.path.join(DIR_PATH, config.TRAIN_CORPUS)
    devfile = os.path.join(DIR_PATH, config.DEV_CORPUS)

    print('Reading training data from %s...' % trainfile)

    train_datasets = ReviewDataset(trainfile)

    print(f'Read {len(train_datasets)} training reviews')

    print("Reading development data from %s..." % devfile)

    dev_datasets = ReviewDataset(devfile)

    print(f'Read {len(dev_datasets)} development reviews')

    # Ensure dropout layers are in train mode
    model.train()

    trainer.train(train_datasets, dev_datasets)
コード例 #45
0
ファイル: test.py プロジェクト: youzhonghui/Adence
    def test_extends(self):
        with main.app.app_context():
            main.init()
            self.insert_fake_key_list()
            web_interface._add_extend('文档', 'http://www.baidu.com')
            web_interface._add_extend('ss', 'http://www.ee.com')
            c = main.app.test_client()

            res = c.get('/extend')
            res = json.loads(res.data.decode())
            assert len(res['extend']) == 2

            web_interface._delete_extend(1)
            res = c.get('/extend')
            res = json.loads(res.data.decode())
            assert len(res['extend']) == 1

            web_interface._delete_extend(2)
            res = c.get('/extend')
            res = json.loads(res.data.decode())
            assert len(res['extend']) == 0

            web_interface._add_extend('second', 'http://localhost:9001/action')
            res = c.get('/extend')
            res = json.loads(res.data.decode())
            param = dict(
                verify=main.app.config['verify'],
                time=datetime.datetime.now().strftime('%Y-%m-%d %H.%M.%S'),
                data=dict(
                    id=res['extend'][0]['passName'],
                    param='msg=hello'
                )
            )
            res = self.send_request('send_extend', param)
            res = json.loads(res.data.decode())
            assert res.get('status') == 'success'
コード例 #46
0
from engine.itemManager import getNonAggregatorItem
from engine.userManager import getUser
from main import init

init()

user = getUser('Toby')
votes = user.getVotes()

for i, v in enumerate(votes):
    if not v.item.source.isAggregator():
        continue

    new_items = getNonAggregatorItem(v.item, silent=True)
    if new_items != v.item and new_items is not None and not new_items.source.isAggregator():
        print("update ignore votes set id = %s where id = %s;" % (new_items.id, v.item.id))
コード例 #47
0
ファイル: test.py プロジェクト: youzhonghui/Adence
 def test_add_extend(self):
     with main.app.app_context():
         main.init()
         web_interface._add_extend('你好', 'http://www.baidu.com')
         assert db.get_db().execute('select * from Extend').fetchone()['name'] == '你好'
コード例 #48
0

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as e:
        if e.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise


logging.getLogger().setLevel(logging.INFO)

import main
main.init()

for behavior_type in ['skills', 'tactics', 'plays']:
    entries = class_import.recursive_import_classes('.', [behavior_type], fsm.StateMachine)

    for entry in entries:
        try:
            klass = entry[1]
            module_path = entry[0]
            dirpath = 'diagrams/' + '/'.join(module_path[:-1])
            mkdir_p(dirpath)
            filepath = dirpath + "/" + klass.__name__ + ".png"
            klass().write_diagram_png(filepath)
            print("generated " + filepath)
        except Exception as e:
            logging.error("Error generating fsm diagram for behavior '" + klass.__name__ + "':" + str(e))
コード例 #49
0
	def setUp(self):
		main.init(False)
		self.robots = [Moc_Robot(0, 0), Moc_Robot(0, 0), Moc_Robot(0, 0), 
				Moc_Robot(0, 0), Moc_Robot(0, 0), Moc_Robot(0, 0)]
		main.set_their_robots(self.robots)
コード例 #50
0
ファイル: driver.py プロジェクト: CallanIwan/Aranha
 def __init__(self):
     super(Driver, self).__init__()
     self.daemon = True
     main.init()
     atexit.register(self.dispose)
コード例 #51
0
ファイル: baseline.py プロジェクト: 419eaterbot/bot
		bucket = conv_store[key]['Bucket']
		mime_msg = MIMEText(message, 'plain')
		mime_msg['From'] = own_name + ' <' + own_addr + '>'
		if not bucket:
			continue
		else:
			destination_addr = bucket[0]
		for email_addr in bucket:
			if email_addr not in getIdentityEmails():
				mime_msg['To'] = email_addr
		if conv_store[key]['Messages'][0]['Subject']:
			mime_msg['Subject'] = "Re: " + conv_store[key]['Messages'][0]['Subject']
		else:
			mime_msg['Subject'] = "Re: "
		server_addr = 'smtp.mail.yahoo.com'
		conn = SMTP_SSL(server_addr)
		conn.set_debuglevel(True)
		conn.login(own_addr, 'test123')
		try:
			print "Preview:\n"
			print mime_msg.as_string()
			conn.sendmail(own_addr, destination_addr, mime_msg.as_string())
		finally:
			print "Send email!"
			conn.close()
			time.sleep(10)	

if __name__ == "__main__":
	a, b = init()
	sendRequest(b)
コード例 #52
0
from gevent.monkey import patch_all

patch_all()


def run_server(app, port=8080):
    from gevent.pywsgi import WSGIServer

    http_server = WSGIServer(("", port), app)
    http_server.serve_forever()


if __name__ == "__main__":
    import main

    run_server(main.init())