Beispiel #1
0
def main():
    asyncio.set_event_loop(None)
    if args.iocp:
        from trollius.windows_events import ProactorEventLoop
        loop = ProactorEventLoop()
    else:
        loop = asyncio.new_event_loop()
    sslctx = None
    if args.tls:
        import ssl
        # TODO: take cert/key from args as well.
        here = os.path.join(os.path.dirname(__file__), '..', 'tests')
        sslctx = asyncio.SSLContext(ssl.PROTOCOL_SSLv23)
        sslctx.options |= ssl.OP_NO_SSLv2
        sslctx.load_cert_chain(certfile=os.path.join(here, 'ssl_cert.pem'),
                               keyfile=os.path.join(here, 'ssl_key.pem'))
    cache = Cache(loop)
    task = asyncio.streams.start_server(cache.handle_client,
                                        args.host,
                                        args.port,
                                        ssl=sslctx,
                                        loop=loop)
    svr = loop.run_until_complete(task)
    for sock in svr.sockets:
        logging.info('socket %s', sock.getsockname())
    try:
        loop.run_forever()
    finally:
        loop.close()
def handler(event, contest):
    logger.info("Start!")

    executor = ThreadPoolExecutor(max_workers=1000)
    main_loop = asyncio.new_event_loop()
    main_loop.set_default_executor(executor)
    asyncio.set_event_loop(main_loop)

    poll = Poll(main_loop)
    cal = poll.cal
    update_and_delete = UpdateAndDelete(main_loop, executor)

    table = event['table']
    queue_url = event['queueUrl']
    message_count = event['messageCount']

    poll.messages(sqs, queue_url, message_count)

    logger.info("Receive API count: {}".format(poll.fetch_count))
    logger.info("Fetched messages: {}".format(poll.message_count))

    update_and_delete.execute(sqs_client, db, queue_url, table, cal.stats)

    logger.info("Update API count: {}".format(update_and_delete.update_count))
    logger.info("Delete API count: {}".format(update_and_delete.delete_count))
    logger.info("Delete Message count: {}".format(
        update_and_delete.deleted_message_count))

    main_loop.close()
    executor.shutdown()

    return "Lambda job finished successfully."
Beispiel #3
0
 def __init__(self, topic_name, message_type):
     # The message type used for this gazebo topic
     self.default_message_contents = None
     self.connected = False
     self.topic_name = topic_name
     self.message_type = message_type
     self.loop = trollius.new_event_loop()
Beispiel #4
0
 def setUp(self):
     trollius.set_event_loop(None)
     self.loop = trollius.new_event_loop()
     self.loop.set_debug(True)
     self.cluster = Cluster()
     self.session = self.cluster.connect()
     aiosession(self.session, loop=self.loop)
 def run(self, driver, time_out):
     self.loop = new_event_loop()
     set_event_loop(self.loop)
     ensure_future(self.control_loop(driver, time_out))
     self.loop.run_forever()
     self.loop.close()
     return (self.distance_to_goal, self.left_velocity, self.right_velocity)
Beispiel #6
0
def main():
    asyncio.set_event_loop(None)
    if args.iocp:
        from trollius.windows_events import ProactorEventLoop
        loop = ProactorEventLoop()
    else:
        loop = asyncio.new_event_loop()
    sslctx = None
    if args.tls:
        import ssl
        # TODO: take cert/key from args as well.
        here = os.path.join(os.path.dirname(__file__), '..', 'tests')
        sslctx = asyncio.SSLContext(ssl.PROTOCOL_SSLv23)
        sslctx.options |= ssl.OP_NO_SSLv2
        sslctx.load_cert_chain(
            certfile=os.path.join(here, 'ssl_cert.pem'),
            keyfile=os.path.join(here, 'ssl_key.pem'))
    cache = Cache(loop)
    task = asyncio.streams.start_server(cache.handle_client,
                                        args.host, args.port,
                                        ssl=sslctx, loop=loop)
    svr = loop.run_until_complete(task)
    for sock in svr.sockets:
        logging.info('socket %s', sock.getsockname())
    try:
        loop.run_forever()
    finally:
        loop.close()
 def handler(self):
     while self._active:
         loop = trollius.new_event_loop()
         t = threading.Thread(
             target=functools.partial(self.thread_target, loop))
         t.start()
         time.sleep(1)
Beispiel #8
0
def run(driver, time_out):
    loop = new_event_loop()
    set_event_loop(loop)
    ensure_future(control_loop(driver, time_out, loop))
    loop.run_forever()
    loop.close()
    return (distance_to_goal, left_velocity, right_velocity)
Beispiel #9
0
def handler(event, contest):
    logger.info("Start!")

    executor = ThreadPoolExecutor(max_workers=1000)
    main_loop = asyncio.new_event_loop()
    main_loop.set_default_executor(executor)
    asyncio.set_event_loop(main_loop)

    poll = Poll(main_loop)
    cal = poll.cal
    update_and_delete = UpdateAndDelete(main_loop, executor)

    table = event['table']
    queue_url = event['queueUrl']
    message_count = event['messageCount']

    poll.messages(sqs, queue_url, message_count)

    logger.info("Receive API count: {}".format(poll.fetch_count))
    logger.info("Fetched messages: {}".format(poll.message_count))

    update_and_delete.execute(sqs_client, db, queue_url, table, cal.stats)

    logger.info("Update API count: {}".format(update_and_delete.update_count))
    logger.info("Delete API count: {}".format(update_and_delete.delete_count))
    logger.info("Delete Message count: {}".format(
        update_and_delete.deleted_message_count))

    main_loop.close()
    executor.shutdown()

    return "Lambda job finished successfully."
def run(driver, time_out):
    loop = new_event_loop()
    set_event_loop(loop)
    ensure_future(control_loop(driver, time_out, loop))
    loop.run_forever()
    loop.close()
    return (distance_to_goal, left_velocity, right_velocity)
 def run(self, driver, time_out):
     self.loop = new_event_loop()
     set_event_loop(self.loop)
     ensure_future(self.control_loop(driver, time_out))
     self.loop.run_forever()
     self.loop.close()
     return (self.distance_to_goal, self.left_velocity, self.right_velocity)
Beispiel #12
0
    def extract_data_as_list_of_object(self):
        @trollius.coroutine
        def extract_data(sorted_names,tmp_data,rows,row_index):
            import copy
            data_item = copy.copy(tmp_data)
            for name_item in sorted_names:

                tmp = data_item
                j=0
                for x in range(0,name_item["n_count"]):
                    tmp =getattr(tmp,name_item["names"][x])
                setattr(tmp,name_item["names"][name_item["n_count"]],rows[row_index][name_item["idx"]].value)
            return data_item

        sorted_names= sorted(self.names,key = lambda x:x.col)
        sorted_names = [{"names":x.name.split('.'),"n_count":x.name.split('.').__len__()-1,"idx":x.col} for x in sorted_names]
        rows = list(self.data_sheet.rows)
        rows_count =rows.__len__()
        ret_data=[]
        tmp_data=self.get_oject_template()
        loop = trollius.new_event_loop()

        @trollius.coroutine
        def get_result():
            for i in range(1,rows_count):
                yield extract_data(sorted_names,tmp_data,rows,i)
Beispiel #13
0
def run_main_loop(G):
    '''
    This runs the stopingibition/visual/audio part of the paradigm using
    asyncio-replacement trollius. Before and after, we can still present
    other stimuli.
    '''

    # something like this:
    # mainClock=clock.Clock()
    # mainClockContainer[0]=mainClock # put it into my list, that double-serves
    # as a pointer

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    #tasks = [
    #    asyncio.async(handleVisual()),
    #    asyncio.async(handleGonogo()),
    #    asyncio.async(handleEscape()),
    #    ]
    tasks_dbg = [
        # asyncio.async(handle_exception(test_it,G,loop)),
        asyncio. async (handle_exception(handle_audio, G, loop)),
        asyncio. async (handle_exception(handle_visual, G, loop)),
        asyncio. async (handle_exception(handle_gonogo, G, loop)),
        #asyncio.async(handle_exception(handle_visual,loop)),
    ]

    tasks = [
        # asyncio.async(test_it(G)),
        # asyncio.async(handle_audio(G))
    ]

    # so to debug, just run tasks_dbg instead of tasks.
    loop.run_until_complete(asyncio.wait(tasks_dbg))
    loop.close()
Beispiel #14
0
 def set_event_loop(self):
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     self.events = asyncio.Queue(loop=self.loop)
     self.set_exception_handler()
     if self.loglevel is not None and self.loglevel <= logging.DEBUG:
         self.loop.set_debug(True)
     return self.loop
Beispiel #15
0
 def set_event_loop(self):
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     self.events = asyncio.Queue(loop=self.loop)
     self.set_exception_handler()
     if self.loglevel is not None and self.loglevel <= logging.DEBUG:
         self.loop.set_debug(True)
     return self.loop
    def execute(self, sqs, queue_url, ids):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.set_default_executor(self.executor)

        id_groups = group_by_10(ids)
        tasks = []
        for id_group in id_groups:
            tasks.append(self._one_request(loop, sqs, queue_url, id_group))
        loop.run_until_complete(asyncio.wait(tasks))
    def execute(self, sqs, queue_url, ids):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.set_default_executor(self.executor)

        id_groups = group_by_10(ids)
        tasks = []
        for id_group in id_groups:
            tasks.append(self._one_request(loop, sqs, queue_url, id_group))
        loop.run_until_complete(asyncio.wait(tasks))
Beispiel #18
0
 def start(self):
     self.isStopped = False
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     self.face = ThreadsafeFace(self.loop, '')
     k = KeyChain()
     self.face.setCommandSigningInfo(k, k.getDefaultCertificateName())
     self.face.stopWhen(lambda:self.isStopped)
     try:
         self.loop.run_until_complete(self.sendNextInsertRequest())
     finally:
         self.face.shutdown()
Beispiel #19
0
            def run_executor(executor):
                # create an event loop in the executor thread
                loop = trollius.new_event_loop()
                trollius.set_event_loop(loop)
                eventlet.spawn(run_loop, loop)

                # run the executor
                executor.start()
                executor.wait()

                # stop the event loop: run_loop() will close it
                loop.stop()
Beispiel #20
0
            def run_executor(executor):
                # create an event loop in the executor thread
                loop = trollius.new_event_loop()
                trollius.set_event_loop(loop)
                eventlet.spawn(run_loop, loop)

                # run the executor
                executor.start()
                executor.wait()

                # stop the event loop: run_loop() will close it
                loop.stop()
Beispiel #21
0
 def get_stock_data(self):
     threads = []
     for index in range(self.request_num):
         threads.append(self.get_stocks_by_range(index))
         log.debug("url:%s  len:%s" % (self.sina_stock_api, len(self.stock_list[index])))
     try:
         loop = asyncio.get_event_loop()
     except RuntimeError:
         loop = asyncio.new_event_loop()
         asyncio.set_event_loop(loop)
     loop.run_until_complete(asyncio.wait(threads))
     log.debug("get_stock_data_loop")
     return self.format_response_data()
Beispiel #22
0
 def setup_eventloop(self):
     """
     Sets up a new eventloop as the current one according to the OS.
     """
     if os.name == 'nt':
         self.eventloop = asyncio.ProactorEventLoop()
         if sys.version_info <= (3, 0):
             # FIXME: There appears to be a bug in the 2.7 version of trollius, wherein the selector retrieves an
             # object of value 0 and attempts to look for it in the weakref set, which raises an exception.
             # This hack sidesteps this issue, but does not solve it. If a proper fix is found, apply it!
             self.eventloop._selector._stopped_serving = set()
     else:
         self.eventloop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.eventloop)
Beispiel #23
0
 def setup_eventloop(self):
     """
     Sets up a new eventloop as the current one according to the OS.
     """
     if os.name == 'nt':
         self.eventloop = asyncio.ProactorEventLoop()
         if sys.version_info <= (3, 0):
             # FIXME: There appears to be a bug in the 2.7 version of trollius, wherein the selector retrieves an
             # object of value 0 and attempts to look for it in the weakref set, which raises an exception.
             # This hack sidesteps this issue, but does not solve it. If a proper fix is found, apply it!
             self.eventloop._selector._stopped_serving = set()
     else:
         self.eventloop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.eventloop)
    def token_renewer(self):
        while True:
            loop = trollius.new_event_loop()
            trollius.set_event_loop(loop)
            tasks = list()
            for symbol in self.websockets.keys():
                ws = self.websockets[symbol]["ws"]
                if ws.open:
                    if (datetime.now() - self.websockets[symbol]["renewed"]
                        ).total_seconds() > 180:
                        tasks.append(self.renew_token(symbol))

            if len(tasks) > 0:
                loop.run_until_complete(trollius.wait(tasks))
                loop.close()
            time.sleep(1)
Beispiel #25
0
def main():
    asyncio.set_event_loop(None)
    if args.iocp:
        from trollius.windows_events import ProactorEventLoop
        loop = ProactorEventLoop()
    else:
        loop = asyncio.new_event_loop()
    sslctx = None
    if args.tls:
        sslctx = test_utils.dummy_ssl_context()
    cache = CacheClient(args.host, args.port, sslctx=sslctx, loop=loop)
    try:
        loop.run_until_complete(
            asyncio.gather(
                *[testing(i, cache, loop) for i in range(args.ntasks)],
                loop=loop))
    finally:
        loop.close()
Beispiel #26
0
    def run(self):
        try:
            asyncio.set_event_loop(asyncio.new_event_loop())

            indexPath = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), 'templates')
            app = tornado.web.Application([
                (r"/stream", ImageStreamHandler, {}),
                (r"/(.*)", tornado.web.StaticFileHandler, {
                    'path': indexPath,
                    'default_filename': 'index.html'
                })
            ])
            app.listen(self.port)
            print('ImageServer::Started.')
            tornado.ioloop.IOLoop.instance().start()
        except Exception as e:
            print('ImageServer::exited run loop. Exception - ' + str(e))
Beispiel #27
0
    def get_stock_data(self, retry_count=3, pause=0.01):
        threads = []
        for index in range(self.request_num):
            threads.append(self.get_stocks_by_range(index))
            log.debug("url len:%s" % (len(self.stock_list[index])))
        if self.request_num == 0:
            threads.append(self.get_stocks_by_range(0))
        for _ in range(retry_count):
            time.sleep(pause)
            try:
                loop = asyncio.get_event_loop()
            except RuntimeError:
                loop = asyncio.new_event_loop()
                asyncio.set_event_loop(loop)
            loop.run_until_complete(asyncio.wait(threads))
            log.debug('get_stock_data_loop')
            return self.format_response_data()

        raise IOError(ct.NETWORK_URL_ERROR_MSG)
def handler(event, contest):
    logger.info("Start!")

    executor = ThreadPoolExecutor(max_workers=1000)
    main_loop = asyncio.new_event_loop()
    main_loop.set_default_executor(executor)
    asyncio.set_event_loop(main_loop)

    poll = Poll(main_loop)

    queue_url = event['queueUrl']
    message_count = event['messageCount']

    poll.messages(sqs, queue_url, message_count)

    logger.info("Receive API count: {}".format(poll.fetch_count))
    logger.info("Fetched messages: {}".format(poll.message_count))

    main_loop.close()
    executor.shutdown()
Beispiel #29
0
def to_asyncio_run(urllist, cmd):
    results = []

    # print "asyncio",
    @asyncio.coroutine
    def get_loop_cmd(cmd, url_s):
        loop = asyncio.get_event_loop()
        result = yield From(loop.run_in_executor(None, cmd, url_s))
        results.append(result)

    threads = []
    for url_s in urllist:
        threads.append(get_loop_cmd(cmd, url_s))
    try:
        loop = asyncio.get_event_loop()
    except RuntimeError:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
    loop.run_until_complete(asyncio.wait(threads))
    return results
def handler(event, contest):
    logger.info("Start!")

    executor = ThreadPoolExecutor(max_workers=1000)
    main_loop = asyncio.new_event_loop()
    main_loop.set_default_executor(executor)
    asyncio.set_event_loop(main_loop)

    poll = Poll(main_loop)

    queue_url = event['queueUrl']
    message_count = event['messageCount']

    poll.messages(sqs, queue_url, message_count)

    logger.info("Receive API count: {}".format(poll.fetch_count))
    logger.info("Fetched messages: {}".format(poll.message_count))

    main_loop.close()
    executor.shutdown()
    def token_sender(self):
        while True:
            self.logger.info(u"开启话唠模式每55秒的定时与服务器聊天")
            start = datetime.now()
            tasks = list()
            loop = trollius.new_event_loop()
            trollius.set_event_loop(loop)

            for symbol in self.websockets.keys():
                ws = self.websockets[symbol]["ws"]
                if ws.open:
                    tasks.append(
                        ws.send("*" + self.websockets[symbol]["token"]))

            if len(tasks) > 0:
                loop.run_until_complete(trollius.wait(tasks))
                loop.close()
            self.logger.info(u"消息全部发送完毕. 耗时:%s" %
                             (datetime.now() - start).total_seconds())
            time.sleep(55)
Beispiel #32
0
    def run(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        self.factory = WebSockServerFactory("ws://%s:%d" %
                                            (self.ip, self.port))
        self.factory.protocol = WebSockServer

        loop = asyncio.get_event_loop()
        coro = loop.create_server(self.factory, self.ip, self.port)

        self.server = loop.run_until_complete(coro)
        print("Starting Websocketserver at %s:%d" % (self.ip, self.port))
        try:
            loop.run_forever()
        except KeyboardInterrupt:
            print 'Error while serving websocketserver'
            raise
        finally:
            self.server.close()
            loop.close()
Beispiel #33
0
    def run(self):
        #try:
        #asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())
        loop = asyncio.new_event_loop()
        loop = asyncio.set_event_loop(loop)

        indexPath = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                 'templates')
        print(indexPath)
        app = tornado.web.Application([(r"/stream", ImageStreamHandler, {
            'camera': self.camera
        }),
                                       (r"/(.*)",
                                        tornado.web.StaticFileHandler, {
                                            'path': indexPath,
                                            'default_filename': 'index.html'
                                        })])
        print("created app for server with port:" + str(self.port))
        app.listen(self.port)
        print('ImageServer::Started.')
        tornado.ioloop.IOLoop.current().start()
    def websocket_creator(self):
        loop = trollius.new_event_loop()
        trollius.set_event_loop(loop)
        # 首先从新浪获取股票列表
        symbolList = self.symbols
        # Cut symbolList
        weight = (len(self.query) +
                  1) if ('deal' in self.query) else len(self.query)
        step = int(64 / weight)
        symbolListSlice = [
            symbolList[i:i + step] for i in range(0, len(symbolList), step)
        ]

        tasks = list()
        for symbolList in symbolListSlice:
            qlist = ''
            for symbol in symbolList:
                qlist = self.generate_qlist(qlist=qlist, symbol=symbol)
            qlist = qlist.lower()
            tasks.append(self.create_ws(qlist, symbolList=symbolList))

        loop.run_until_complete(trollius.wait(tasks))
        loop.close()
Beispiel #35
0
 def test_custom_event_loop(self):
     loop = asyncio.new_event_loop()
     loop.set_debug(True)
     self._test_using_event_loop(loop)
Beispiel #36
0
def test_extras():
    if IPY:
        import coconut.highlighter  # type: ignore
    assert consume(range(10), keep_last=1)[0] == 9 == coc_consume(range(10), keep_last=1)[0]
    assert version() == version("num")
    assert version("name")
    assert version("spec")
    assert version("tag")
    assert version("-v")
    assert_raises(lambda _=None: version("other"), CoconutException)
    def _coconut_lambda_0(_=None):
        raise CoconutException("derp").syntax_err()
    assert_raises(_coconut_lambda_0, SyntaxError)
    assert coconut_eval("x -> x + 1")(2) == 3
    assert coconut_eval("addpattern")
    assert parse("abc") == parse("abc", "sys")
    assert parse("abc", "file")
    assert parse("abc", "package")
    assert parse("abc", "block") == "abc\n" == parse("abc", "single")
    assert parse("abc", "eval") == "abc" == parse(" abc", "eval")
    assert parse("abc", "any") == "abc"
    assert parse("x |> map$(f)", "any") == "map(f, x)"
    assert "_coconut" not in parse("a |> .b |> .m() |> f$(x) |> .[0]", "block")
    assert parse("abc # derp", "any") == "abc  # derp"
    assert_raises(lambda _=None: parse(" abc", "file"), CoconutException)
    assert_raises(lambda _=None: parse("'"), CoconutException)
    assert_raises(lambda _=None: parse("("), CoconutException)
    assert_raises(lambda _=None: parse("\\("), CoconutException)
    assert_raises(lambda _=None: parse("if a:\n  b\n c"), CoconutException)
    assert_raises(lambda _=None: parse("$"), CoconutException)
    assert_raises(lambda _=None: parse("_coconut"), CoconutException)
    assert parse("def f(x):\n \t pass")
    assert parse("lambda x: x")
    assert parse("u''")
    assert parse("def f(x):\\\n pass")
    assert parse("abc ")
    assert parse("abc # derp", "any") == "abc  # derp"
    setup(line_numbers=True)
    assert parse("abc", "any") == "abc  # line 1"
    setup(keep_lines=True)
    assert parse("abc", "any") == "abc  # abc"
    setup(line_numbers=True, keep_lines=True)
    assert parse("abc", "any") == "abc  # line 1: abc"
    setup()
    assert "prepattern" in parse("\n", mode="file")
    assert "datamaker" in parse("\n", mode="file")
    setup(strict=True)
    assert "prepattern" not in parse("\n", mode="file")
    assert "datamaker" not in parse("\n", mode="file")
    assert_raises(lambda _=None: parse("def f(x):\n \t pass"), CoconutStyleError)
    assert_raises(lambda _=None: parse("lambda x: x"), CoconutStyleError)
    assert_raises(lambda _=None: parse("u''"), CoconutStyleError)
    assert_raises(lambda _=None: parse("def f(x):\\\n pass"), CoconutStyleError)
    assert_raises(lambda _=None: parse("abc "), CoconutStyleError)
    assert_raises(lambda _=None: parse("abc", "file"), CoconutStyleError)
    assert_raises(lambda _=None: parse("a=1;"), CoconutStyleError)
    assert_raises(lambda _=None: parse("class derp(object)"), CoconutStyleError)
    setup()
    assert_raises(lambda _=None: cmd("-f"), SystemExit)
    assert_raises(lambda _=None: cmd("-pa ."), SystemExit)
    assert_raises(lambda _=None: cmd("-n . ."), SystemExit)
    assert_raises(lambda _=None: parse("f$()"), CoconutSyntaxError)
    assert_raises(lambda _=None: parse("f(*x, y)"), CoconutSyntaxError)
    assert_raises(lambda _=None: parse("def f(x) = return x"), CoconutSyntaxError)
    assert_raises(lambda _=None: parse("def f(x) =\n return x"), CoconutSyntaxError)
    assert_raises(lambda _=None: parse("a := b"), CoconutParseError)
    assert_raises(lambda _=None: parse("(a := b)"), CoconutTargetError)
    setup(target="2.7")
    assert parse("from io import BytesIO", mode="any") == "from io import BytesIO"
    assert_raises(lambda _=None: parse("def f(*, x=None) = x"), CoconutTargetError)
    setup(target="3.6")
    assert parse("def f(*, x=None) = x")
    setup(target="3.8")
    assert parse("(a := b)")
    assert parse("print(a := 1, b := 2)")
    assert parse("def f(a, /, b) = a, b")
    if CoconutKernel is not None:
        if PY35:
            asyncio.set_event_loop(asyncio.new_event_loop())
        k = CoconutKernel()
        exec_result = (unwrap_future)(k.do_execute("derp = pow$(?, 2)", False, True, {"two": "(+)(1, 1)"}, True))
        assert exec_result["status"] == "ok"
        assert exec_result["user_expressions"]["two"]["data"]["text/plain"] == "2"
        assert k.do_is_complete("if abc:")["status"] == "incomplete"
        assert k.do_is_complete("f(")["status"] == "incomplete"
        assert k.do_is_complete("abc")["status"] == "complete"
        inspect_result = k.do_inspect("derp", 4, 0)
        assert inspect_result["status"] == "ok"
        assert inspect_result["found"]
        assert inspect_result["data"]["text/plain"]
        complete_result = k.do_complete("der", 1)
        assert complete_result["status"] == "ok"
        assert "derp" in complete_result["matches"]
        assert complete_result["cursor_start"] == 0
        assert complete_result["cursor_end"] == 1
        keyword_complete_result = k.do_complete("ma", 1)
        assert keyword_complete_result["status"] == "ok"
        assert "match" in keyword_complete_result["matches"]
        assert "map" in keyword_complete_result["matches"]
        assert keyword_complete_result["cursor_start"] == 0
        assert keyword_complete_result["cursor_end"] == 1
    if not PYPY:
        import numpy as np
        assert np.all(fmap(lambda _=None: _ + 1, np.arange(3)) == np.array([1, 2, 3]))
    print("<success>")
Beispiel #37
0
 def setUp(self):
     self.loop = asyncio.new_event_loop()
     self.set_event_loop(self.loop)
 def test_custom_event_loop(self):
     loop = asyncio.new_event_loop()
     loop.set_debug(True)
     self._test_using_event_loop(loop)
Beispiel #39
0
def main():
    import argparse

    ap = argparse.ArgumentParser()
    ap.add_argument("--remote", type=str, default=None, help="remote destination to exchange ip packets with")
    ap.add_argument("--i2cp", type=str, default="127.0.0.1:7654", help="i2cp interface")
    ap.add_argument("--mtu", type=int, default=4096, help="interface mtu")
    ap.add_argument("--local-addr", type=str, default=None, help="our ip on our interface")
    ap.add_argument("--remote-addr", type=str, default=None, help="remote peer's ip")
    ap.add_argument("--netmask", type=str, default="255.255.255.0", help="interface's network mask")
    ap.add_argument("--iface", type=str, default="i2ptun0", help="what we want to call the new network interface")
    ap.add_argument("--keyfile", type=str, default="i2p.tun.key", help="i2cp destination keys")
    ap.add_argument("--debug", action="store_const", const=True, default=False, help="toggle debug mode")
    ap.add_argument("--tap", action="store_const", const=True, default=False, help="use tap instead of tun")
    args = ap.parse_args()

    log = logging.getLogger("i2p.tun")

    if args.debug:
        lvl = logging.DEBUG
    else:
        lvl = logging.WARN

    i2cp_host = args.i2cp.split(":")[0]
    i2cp_port = int(args.i2cp.split(":")[-1])
        
    logging.basicConfig(level=lvl)
    loop = asyncio.new_event_loop()
    ftr = asyncio.Future(loop=loop)
    tun = None
    # wait sleeptime seconds for our connection to be done or retry
    def _wait_for_done(conn, sleeptime):
        if conn.is_done():
            ftr.set_result(True)
            if tun:
                tun.down()
                tun.close()
        else:
            loop.call_later(sleeptime, _wait_for_done, conn, sleeptime)
            
    
    if args.remote is None:
        handler = i2cp.PrintDestinationHandler()
    else:
        tun = tundev.opentun(args.iface, args.tap)
        if args.local_addr is None:
            log.error("no local ip address specified")
            return
        if args.remote_addr is None:
            log.error("no remote ip address specified")
            return
        tun.addr = args.local_addr
        tun.dstaddr = args.remote_addr
        tun.mtu = args.mtu
        tun.netmask = args.netmask
        # make handler
        handler = Handler(args.remote, tun, lambda x : x, loop)

    conn = i2cp.Connection(handler, i2cp_host=i2cp_host, i2cp_port=i2cp_port, keyfile=args.keyfile, evloop=loop)
    conn.open()
    loop.call_soon(_wait_for_done, conn, 1.0)
    loop.run_until_complete(ftr)
Beispiel #40
0
 def setUp(self):
     policy = greenio.GreenTrolliusEventLoopPolicy()
     asyncio.set_event_loop_policy(policy)
     trollius.set_event_loop_policy(policy)
     self.loop = trollius.new_event_loop()
     policy.set_event_loop(self.loop)
Beispiel #41
0
    def handle_gonogo(GLOBS):
        '''
        This contains the experimenal logic of the Stop Task. A lot of work
        went into constructing the stimuli. Stimuli parameters are loaded
        into variables in the code above. Runs 136 trials of Go-Nogo.
        This function is to be run within the asyncio loop.
        '''
     
        
        # we just need it here...
        STOP=1
        GO=0
        
        tooSoonTime = G['S']['tooSoonTime']  
        
        myMultiStairs = G['S']['myMultiStairs']
    
        # if the time it took tov respond is smaller than this time --> invalid.
        numberOfResponses=0
        
        
        G['S']['nextFLipTasks']=[]  # stuff winflupper needs to do later on..
        G['S']['clock']=[None]

        # set the visual contents here...
        # INITIAL SETTING
        G['S']['goNogoStim']=G['vstims']['S']['fix']

  
    
        # yeah, do all kinds of init here.
        for trialNumber in range(len(G['S']['SSstopgo'])):
    
    
            
            
            thisDirection=random.choice(('al','ar')) # obtain this from the file!!
            LorR = thisDirection[1].upper()

            thisTrialType = G['S']['SSstopgo'][trialNumber] # this is a 0 (GO) or 1 (STOP)
            thisTrialType = [GO, STOP][int(thisTrialType)]  # shady practices indeed -- so later on I cany say 'if this TrialType is GO:, etc'
            GorNG = ['Go', 'Stop'][int(thisTrialType)]


            thisISIWaitTime = G['S']['ISIwaitTime'][trialNumber]
            
            correctResponseSide = G['S']['correctResponseSides'][trialNumber]
            wrongResponseSide = G['S']['wrongResponseSides'][trialNumber]
            

            
            allResponses=[] 
            responded=False # subj responded?
            tooManyResponses=False
            trialHandled=False
            
            
            
            if taskType is STOP:
                # this should be called only 40 times, since there are 40 stop trials...
                thisSSD, thisCondition = myMultiStairs.next() # I defined the myMultiStairs above.
            
    
    
            # this code tells the loop to only continue when continueTroutine is not False
            # otherwise it'll just keep yielding.
            # let winflipper make new clock
            G['S']['continueRoutine']=False
            G['S']['nextFlipTasks'].append([G['S']['makeNewClock'], G]) # the makeNewClock automatically makes things continue
            while G['S']['continueRoutine'] is False:
                yield From(asyncio.sleep(0))
            cl=G['S']['clock'] # obtain the clock that was just made.
    
    
            # ok, we can proceed -- the clock has been set.
            G['S']['goNogoStim']=G['vstims']['S']['pre']
            while cl.getTime() < 0.5:
                yield From(asyncio.sleep(0))
        
        



        
            # obtain our next clock...
            # this code tells the loop to only continue when continueTroutine is not False
            # otherwise it'll just keep yielding.
            # let winflipper make new clock
            G['S']['continueRoutine']=False
            
            # make sure upon next window flow, we have a new clock set, and also - that marker is sent signalling the start of the new go/stop trial.
            G['S']['nextFlipTasks'].append([G['S']['makeNewClock'], G]) # the makeNewClock automatically makes things continue
            # send the trigger regarding the arrow, as soon as the windows flips
            G['S']['nextFlipTasks'].append([G['eh'].send_message, 
                                  ['Begin'+GorNG+LorR])
            while G['S']['continueRoutine'] is False:
                yield From(asyncio.sleep(0))
            cl=G['S']['clock'] # obtain the clock that was just made.
            
    
            # this is where we show the arrow + find out whether a key is pressed:
            G['S']['goNogoStim']=G['vstims']['S'][thisDirection]
            currentTime = 0.0
            while currentTime < 1.0:
                currentTime = cl.getTime()
                
                # set the stimulus to the proper direction (it's a choice, for now... -- but it's much much better to hard-code it)
                # make the arrow (+ circle)
    
                evs=event.getKeys(timeStamped=cl)
                if len(evs)>0:
                    buttonsPressed, timesPressed = zip(*evs)
                    # it's highly unlikely that two buttons are pressed in a signle
                    # frame, but control for that anyway.
                    allResponses.append((buttonsPressed[0], timesPressed[0]))
                    numberOfResponses += 1
                    # LOG this event... (i.e. send trigger)
                    
                    # handle event:


                # once a button is pressed -- display fixation point again.
                if len(allResponses) > 0 and not responded:
                    # 'clear' the visual window --> fixation cross, again:
                    G['S']['goNogoStim']=G['vstims']['S']['fix']
                    responded=True
                    
                    buttonPressed, RTime = allResponses[0]
                    
                    if RTime < tooSoonTime:
                        G['ev'].send_message('PressedTooSoon')
                    else:
                        if buttonsPressed[0] == BUTTONS[0]:
                            G['ev'].send_message('RespL')
                        elif buttonsPressed[0] == BUTTONS[1]:
                            G['ev'].send_message('RespR')


        
        
                # if it's a stop trial, then make arrow red after X time
                if thisTrialType is STOP and not responded:
                    if currentTime > thisSSD:
                        G['S']['goNogoStim']=G['vstims']['S'][thisDirection+'r']
    
            
                # here we wait...
                yield From(asyncio.sleep(0))

            #            # Stop / Inhibit Response Codes
            #            'BeginGoL':1,
            #            'BeginGoR':2,
            #            'BeginStopL':3,
            #            'BeginStopR':4,
            #            
            #            'RespL':5,
            #            'RespR':6,
            #
            #            'CorrectGoL':11,
            #            'CorrectGoR':12,
            #            'CorrectStopL':13,
            #            'CorrectStopR':14,
            #            'ErrorCommission':15,
            #            
            #            # don't expect too many of these:
            #            'ErrorOmission':21,
            #            'PressedTooSoon':22,
            #            'TooManyResponses':23,
            #            'WrongSideErrorCommission':24,
            #            'WrongSideGo':25,

            # so the loop is done -- let's figure out what kind of trial this was.
            # taking care of the button press itself, as soon as button is pressed:
            if not trialHandled and responded:

                trialHandled=True

                if len(allResponses) > 1:
                    trialOutcome = 'TooManyResponses'
                    if trialType is STOP:
                        myMultiStairs.addResponse(0)

                else:
                    if RTime < tooSoonTime:
                        trialOutcome = 'PressedTooSoon'
                        if trialType is STOP:
                            myMultiStairs.addResponse(0)
                    else:
                        if thisTrialType is STOP:
                            
                            if buttonPressed == correctResponseSide:
                                trialOutcome = 'ErrorCommission'
                                myMultiStairs.addResponse(0)
        
                            elif buttonPressed == wrongResponseSide:
                                trialOutcome = 'WrongSideErrorCommission'
                                myMultiStairs.addResponse(0)
                                
                            
                        elif thisTrialType is GO:
                            if buttonPressed == correctResponseSide:
                                trialOutcome = 'CorrectGo'+correctResponseSide

                                # not yet...
                            elif buttonPressed == wrongResponseSide:
                                trialOutcome = 'WrongSideGo'


        
                        # handle the 'response' if the button was NOT pressed:
            if not trialHandled and not responded:
                trialHandled = True

                if trialType is GO:
                    trialOutcome = 'ErrorOmission'
    
                if trialType is STOP:
                    trialOutcome = 'CorrectStop'+LorR
                    myMultiStairs.addResponse(1)
                    
            # so we send it out:
            G['ev'].send_message(trialOutcome)
            

    
            # obtain our next clock...
            # this code tells the loop to only continue when continueTroutine is not False
            # otherwise it'll just keep yielding.
            # let winflipper make new clock
            continueRoutineContainer[0]=False
            nextfliptasks.append([makeNewClock]) # the makeNewClock automatically makes things continue
            while continueRoutineContainer[0] is False:
                yield From(asyncio.sleep(0))
            cl=clockContainer[0] # obtain the clock that was just made.
    
    

            # this is a nice place to save it to logfile: before the 
            # send a report about the STOP trial, write a nice line:
            # logging.data('messa')
            logging.flush()

    
             # ok, we can proceed -- the clock has been set.
            goNogoStimContainer=sstims['fix']
            while cl.getTime() < thisISIWaitTime:
                yield From(asyncio.sleep(0))
            


        # the stop task should be finished now!
        # the visual task should also be finished around the same time.
        # so further stuff, we can do with basic instructions, wait times, etc
            


#%% ASYNC V - Handle the Audio!

# the audio stim list:
# audio_stim_list = [[10.,20.,'audio',['left','40']],[112.5,130.,'audio',['left','40']],[242.5,260.,'audio',['left','40']],[50.,60.,'audio',['left','55']],[195.,205.,'audio',['left','55']],[312.5,330.,'audio',['left','55']],[30.,40.,'audio',['right','40']],[147.5,165.,'audio',['right','40']],[277.5,295.,'audio',['right','40']],[77.5,95.,'audio',['right','55']],[175.,185.,'audio',['right','55']],[215.,225.,'audio',['right','55']]]

# make a more usable stim list:
    audio_stim_list = [
            [10.0, 20.0, 'aud_l40'],
            [112.5, 130.0, 'aud_l40'],
            [242.5, 260.0, 'aud_l40'],
            [50.0, 60.0, 'aud_l55'],
            [195.0, 205.0, 'aud_l55'],
            [312.5, 330.0, 'aud_l55'],
            [30.0, 40.0, 'aud_r40'],
            [147.5, 165.0, 'aud_r40'],
            [277.5, 295.0, 'aud_r40'],
            [77.5, 95.0, 'aud_r55'],
            [175.0, 185.0, 'aud_r55'],
            [215.0, 225.0, 'aud_r55']
            ]
    
    # load in the audio's timings, defined in seconds, so that later on, one could
    # input triggers into the EEG (or optionally -- send out triggers with the event handler)        
    
    # 40 Hz:
    timings40Hz=np.loadtxt('stims/audio_40_ts.txt');
    # 50 Hz:
    timings55Hz=np.loadtxt('stims/audio_55_ts.txt')
    
    # see also the figure_out_audio_timings.m file to further play with the audio's
    # waveforms.
    
    
    snd40hzL = sound.backend_pygame.SoundPygame(value='stims/audio_40Hz_L.wav',loops=0)
    snd40hzR = sound.backend_pygame.SoundPygame(value='stims/audio_40Hz_R.wav',loops=0)
    snd55hzL = sound.backend_pygame.SoundPygame(value='stims/audio_55Hz_L.wav',loops=0)
    snd55hzR = sound.backend_pygame.SoundPygame(value='stims/audio_55Hz_R.wav',loops=0)
    
    
    astims={
            'aud_l40':snd40hzL,
            'aud_r40':snd40hzR,
            'aud_l55':snd55hzL,
            'aud_r55':snd55hzR
            }
    
    
    # put these into the variable, too...
    G['astims']=astims
    G['A']['audio_stim_list']=audio_stim_list
    G['A']['timings40Hz']=timings40Hz
    G['A']['timings55Hz']=timings5Hz
    
    
    @asyncio.coroutine
    def handle_audio(G):
        '''
        this should handle the audio stimuli, using the async programming style.
        it starts a new clock and depending on timings, will start some audio
        samples, L or R, 40 or 55 Hz.
        '''
        
        audioClock=clock.Clock()
        playing=False
        withinAudioBlock=False
        prevWithinAudioBlock=False
        RunAudio=True
        
        
        currentTime=audioClock.getTime()
        while currentTime < 340.: #currentTime < 340.:
            
            # print('hello')
            # print(currentTime)
            
            if not playing:     # I can safely use this since only one audio is playing at a time.
    
                withinAudioBlock=False
                
                for item in audio_stim_list:
                    b, e, stim = item
                    if b < currentTime < e:
                        currentStim = stim
                        withinAudioBlock=True
                        astims[stim].play()
                        playDuration=astims[stim].getDuration()
                        playing=True
                        playClock=clock.Clock()
                        
                        print(stim)
                        logging.data(stim)
                        # eh.send_message(stim)
    
                        
            else:
                if playClock.getTime() > playDuration:  # figure out if something is playing 
                    playing=False
    
                    
            # try dealing with begin and ending markers:                    
            if withinAudioBlock and not prevWithinAudioBlock:
                messg=currentStim.replace('_','_b')
                print(messg)
                logging.data(messg)
                # eh.send_message(stim)
                prevWithinAudioBlock=True
                
            elif prevWithinAudioBlock and not withinAudioBlock:
                messg=currentStim.replace('_','_e')
                print(messg)
                logging.data(messg)
                # eh.send_message(stim)
                prevWithinAudioBlock=False
                
            
            # this will stop this loop, probably:
            currentTime=audioClock.getTime()
            #if currentTime > 340.:
            #    print('Stopping!')
            #    RunAudio=False
            
            yield From(asyncio.sleep(0))  # pass control to someone else, while this guy sleeps a bit.
            



#%% ASYNC II - The Visual handler
## set up the functions to be used in the end for asyncing through the loops:
# load the vis table somewhere here - big mem space (.csv?)
    
    
    # Visual Helpers
    nextfliptasks=[]
    stimulusContents=[]
    
    def makeNewClock():
        clockContainer.append(clock.Clock())
        continueRoutineContainer[0]=True
    


    
    # load in the table that tells me all the stop signal stuff (.csv?)
    #% Frame-by-frame checkerboard List
    # load in the frame-list of the visual stimuli: i.e. saying when things should
    # be used:
    ASYNC_SLEEPTIME = 1/60.*0.75        
    
    
    with open('efl/fd.pkl','rb') as f:
        fd=pickle.load(f)
        
    
    with open('efl/complete_fd_list.pkl','rb') as f:
        complete_fd_list=pickle.load(f)
    
    #    with open('efl/fd_with_markers.pkl','rb') as f:
    #        fd_with_markers=pickle.load(f)
        
    with open('efl/fd_with_markers_II.pkl','rb') as f:
        fd_with_markers=pickle.load(f)
    
    
            
            
     
    
    
    
    @asyncio.coroutine
    def handle_visual():
        '''
        This flips the window, draws the stuff to be drawn, and calls
        functions to be called from the stop task. It is supposed to be
        run in the asyncio loop.
        '''
        
        # logging.console.setLevel(logging.DEBUG)
        mainClock=mainClockContainer[0]
        frameCounter=0
        previousShapes=[]
        mainCurrentTime=0
        totFrames=len(fd_with_markers)
    
        # visualClock=clock.Clock()
        # this will run the entire length of the visual...
        # within this time, the stop signal task will (hopefully) finish.
        # OR... we can also just use a counter.
        while frameCounter < totFrames:
        
        
            # the workflow
            # 1) Prepare everything + draw
            # 2) Prepare markers
            # 3) win.flip() + the callOnFlip routines to be done.
        
            
            # all the visual stuff:
            frameIndex, visContents, markers = fd_with_markers[frameCounter]
            frameCounter += 1
            # deal with the visuals -- using vstims which should be accessible
            # we get the list...
            # create the shapes to be drawn using list comprehension
            if len(visContents) > 0:
                shapes=[stim for stim in vstims[ind] for ind in visContents]
            else:
                shapes=[]
    
            
            
            # add the gonogo stimuli to them:
            if goNogoStimContainer[0] is not None:
                for stim in goNogoStimContainer[0]:
                    shapes.append(goNogoStims)
            
            
            
            # draw them on our little canvas.
            for shape in shapes:
                shape.draw()
            
    
    
            
            # prepare the calls for the next iteration, including marlers;
            # deal with visual markers
            if len(markers) > 0:
                for marker in markers:
                    win.callOnFlip(eventHandler.handle,marker)
            
            
            for task in nextfliptasks:
                if len(task)==1:
                    win.callOnFlip(task)
                elif len(task)==2:
                    win.callOnFlip(task, args)
    
    
    
            # we flip the screen here - this will take ~ 16.66667 msec.
            win.flip()
            
            
            
            
            # sleep for a little while:
            yield From(asyncio.sleep(ASYNC_SLEEPTIME))
                    
            # do for loop for TIME (I suppose)
            
            # check vis table + draw stimuli
            # if there's an event - send to sync
            
            # check stimulus for stop + draw stimuli
            
            # pass on current time for audio presentation (this is another process)
            
            # AWAIT (!) -- to flip the window
        

    

            
            
    

#%% ASYNC III - The Main Event Loop
            
    @asyncio.coroutine
    def test_it():
        cl=clock.Clock()
        # while cl.getTime() < 1: #i in range(1000):e
        runit=True
        while runit:
            print cl.getTime()
            yield From(asyncio.sleep(0))
        
            if cl.getTime() > 1:
                runit=False
            if cl.getTime() > 0.5:
                #pass
                print(1/0)
        
    
    @asyncio.coroutine
    def handle_exception(f, G, loop):
        print f
        print loop
        try:
            yield From(f(G))
        except Exception:
            # print debug information
            print('---------------')
            print('---------------')
            print('ERROR OCCURRED:')
            print(sys.exc_info()[1])
            traceback.print_tb(sys.exc_info()[2])
    
            pending = asyncio.Task.all_tasks()
            for task in pending:
                task.cancel()
                # Now we should await task to execute it's cancellation.
                # Cancelled task raises asyncio.CancelledError that we can suppress:
                #with suppress(asyncio.CancelledError):
                #    loop.run_until_complete(task)        
            loop.stop()  # stops the loop, gives an error for that, too.
    
    
    
    def run_main_loop(G):    
        '''
        This runs the stopingibition/visual/audio part of the paradigm using
        asyncio-replacement trollius. Before and after, we can still present
        other stimuli.
        '''
        
        
        # something like this:
        mainClock=clock.Clock()
        mainClockContainer[0]=mainClock # put it into my list, that double-serves
                                        # as a pointer
        
        
        
        loop=asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        #tasks = [
        #    asyncio.async(handleVisual()),
        #    asyncio.async(handleGonogo()),
        #    asyncio.async(handleEscape()),
        #    ]
        tasks_dbg = [
                asyncio.async(handle_exception(test_it,G,loop)),
                asyncio.async(handle_exception(handle_audio,G,loop)),
                asyncio.async(handle_exception(handle_visual,G,loop))
                #asyncio.async(handle_exception(handle_visual,loop)),
                #asyncio.async(handle_exception(handle_gonogo,loop))
                ]
        
        
        tasks = [
                asyncio.async(test_it(G)),
                asyncio.async(handle_audio(G))
                ]
        
        # so to debug, just run tasks_dbg instead of tasks.
        loop.run_until_complete(asyncio.wait(tasks_dbg))   
        loop.close()

    




#%% MAIN -- hope things work
    if __name__=="__main__":
        # do the stuff.
        run_main_loop()
    
        
        
        
        





#%% The Rest
#    @asyncio.coroutine
#    def handle_exception_test_it():
#        try:
#            yield From(test_it())
#        except Exception:
#            
#            #print(sys.last_type)
#            #traceback.print_tb(sys.last_traceback)
#            #print("exception consumed")
#            # print('hallo!')
#            # print(traceback)
#            print(sys.exc_info()[1])
#            traceback.print_tb(sys.exc_info()[2])
#            # etype, evalue, etraceback = sys.exec_info()
#            # traceback.format_exc()
#            # print(traceback.fortmat_exec(etraceback))
#            
#    @asyncio.coroutine
#    def handle_exception_handle_audio():
#        try:
#            yield From(handle_audio())
#        except Exception:
#            
#            #print(sys.last_type)
#            #traceback.print_tb(sys.last_traceback)
#            #print("exception consumed")
#            # print('hallo!')
#            # print(traceback)
#            print(sys.exc_info()[1])
#            traceback.print_tb(sys.exc_info()[2])
#            
#            # etype, evalue, etraceback = sys.exec_info()
#            # traceback.format_exc()
#            # print(traceback.fortmat_exec(etraceback))
#            
#            
#    # we debug by CHAINING coroutines. Very very clear, yes. But it's necessity for now.
#    # would be nice to enable this feature in a nicer way for someone like me.
        
        
        

#%% Getting Input

# see: http://easygui.sourceforge.net/tutorial.html#enterbox
# variable = easygui.enterbox('hello','title','text')



# OR -- use psychopy's functions:
# expName = 'loc_v1'  # from the Builder filename that created this script
# expInfo = {'participant':'', 'session':'001'}
# dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
#
# access via expInfo['participant'], etc.


#%% Gonogo Thoughts
# vis contents is a list that's accessible by the function
# if the function changes its contents, then other functions will be able to
# read in those contents, too.
# I let the functions talk to each other using ... what?

# visContents is a list from handleGoNogo that contains the stuff to be drawn 
# GoNogo's end
# nexFlipTasks is a list/.. or a dict of stuff with function names and arguments
# that handleVisual should call using win.
    
#
#class GoNogo(object):
#    def __init__(self, SSnumber, SSstopgo, myMultiStairs, myVisualContents,nextFlipTasks, newClock, continueRoutine):
#        self.SSnumber=SSnumber
#        self.SSstopgo=SSstopgo
#        self.myMultiStairs=myMultiStairs
#        self.myVisualContents=myVisualContents
#        self.nextFlipTasks=nextFlipTasks
#        self.newClock=newClock
#        self.continueRoutine=continueRoutine
#        
# after some sleep, my brain might be able to conceive of how I could make this with a Object Oriented programming
# in the event loop in any case I should definitely use some kind of function that yields.
# or can I also make coroutine objects?
# and.. how to implement this, then?    
        
        
#%% Starcase usage -- use the starcase to loop over the stop trials:
# myMultiStair.next()
# myMultiStair.addResponse(1)
#
# getting intensities (for later to average over):
#
# myMultiStair.staircases[3].intensities
#    for thisIntensity, thisCondition in myMultiStairs:
#        print(thisIntensity)
#        print(thisCondition)
#        myMultiStairs.addResponse(random.choice([0,1]))
        
        
#%%

#    visual_evt_codes={'left':{'8':87,'13':137},'right':{'8':88,'13':138}}
#    
#    # these are markers for the frequency analysis
#    visual_evt_codes_begin={'left':{'8':83,'13':133},'right':{'8':84,'13':134}}
#    visual_evt_codes_end={'left':{'8':85,'13':135},'right':{'8':86,'13':136}}
#    
#    # these are the thread starts - which conveniently also denotify what your visual segments
#    # should BE - in case you wish to reconstruct the visual ERP
#    global visual_evt_codes_beginvisthread
#    visual_evt_codes_beginvisthread={'left':{'8':81,'13':131},'right':{'8':82,'13':132}}
#    
#    
#    
#    
#    
#    
#    audio_evt_codes={'left':{'40':41,'55':51},'right':{'40':42,'55':52}}
#    audio_evt_codes_begin={'left':{'40':43,'55':53},'right':{'40':44,'55':54}}
#    audio_evt_codes_end={'left':{'40':45,'55':55},'right':{'40':46,'55':56}}
#    
#    
#    txt_evt_codes = {'normal':100, 'oddball':101}
        
        
#
Beispiel #42
0
 def run(self):
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     self.thread_id = threading.current_thread()
     self.loop.call_soon(self.ready_event.set)
     self.loop.run_forever()
Beispiel #43
0
 def setUp(self):
     self.event_loop = trollius.new_event_loop()
     self.event_loop.set_debug(True)
     trollius.set_event_loop(self.event_loop)
 def setUp(self):
     self.loop = asyncio.new_event_loop()
     self.set_event_loop(self.loop)
Beispiel #45
0
import logging
import queue
import threading

import trollius as asyncio
from trollius import Return, From

from . import firewall


SOCK_STREAM = datatypes.i2cp_protocol.STREAMING
SOCK_DGRAM = datatypes.i2cp_protocol.DGRAM
SOCK_RAW = datatypes.i2cp_protocol.RAW

_ev_loop = asyncio.new_event_loop()


class SocketEndpoint(client.I2CPHandler):

    _log = logging.getLogger("i2p.socket.SocketEndpoint")
    
    def __init__(self, rules, connection_handler_class):
        """
        :param rules: firewall rules
        :param connection_handler_class: class to use for handling connections
        """
        self._handlers = dict()
        self._rules = rules
        self._handler_class = connection_handler_class
        self._remote_connected = False
Beispiel #46
0
 def __init__(self):
     super(WebSocketClient, self).__init__()
     self.__session = None
     self.__mainLoop = asyncio.get_event_loop()
     self.__loop = asyncio.new_event_loop()
 def transmit_item_group(self, item_group, memcpy, allocator):
     self.loop = trollius.new_event_loop()
     ret = self.loop.run_until_complete(
         self.transmit_item_group_async(item_group, memcpy, allocator))
     self.loop.close()
     return ret
 def transmit_item_group(self, item_group, memcpy, allocator):
     self.loop = trollius.new_event_loop()
     ret = self.loop.run_until_complete(
         self.transmit_item_group_async(item_group, memcpy, allocator))
     self.loop.close()
     return ret
Beispiel #49
0
    def pre_mainloop(self):

        MostBasicPsychopyFeedback.pre_mainloop(self)

        # do the trick -- SAVE all of those things! --> and put it in settings.pkl.
        v = dict()

        v['caption'] = self.caption
        v['color'] = self.color
        v['fontheight'] = self.fontheight

        v['STARTKEYS'] = self.STARTKEYS

        v['EX_THRLINEWIDTH'] = self.EX_THRLINEWIDTH
        v['EX_COLORGAP'] = self.EX_COLORGAP
        v['EX_TVSP'] = self.EX_TVSP
        v['EX_TPAUSE'] = self.EX_TPAUSE
        v['EX_NREGULATE'] = self.EX_NREGULATE
        v['EX_NTRANSFER'] = self.EX_NTRANSFER

        v['EX_SHOWCHECKORCROSS'] = self.EX_SHOWCHECKORCROSS
        v['EX_SHOWCHECKORCROSSTRANSFER'] = self.EX_SHOWCHECKORCROSSTRANSFER
        v['EX_SHOWPOINTS'] = self.EX_SHOWPOINTS

        v['EX_SQUARESIZE'] = self.EX_SQUARESIZE
        v['EX_UPREGTEXT'] = self.EX_UPREGTEXT
        v['EX_TESTSIGNALUPDATEINTERVAL'] = self.EX_TESTSIGNALUPDATEINTERVAL
        v['EX_NREST'] = self.EX_NREST
        v['EX_SCALING'] = self.EX_SCALING
        v['EX_INTERACTIONMODE'] = self.EX_INTERACTIONMODE
        v['EX_NOBSERVE'] = self.EX_NOBSERVE
        v['EX_NOREGTEXT'] = self.EX_NOREGTEXT
        v['EX_TINSTR'] = self.EX_TINSTR
        v['EX_THERMOCLIMS'] = self.EX_THERMOCLIMS
        v['EX_GRAPHICSMODE'] = self.EX_GRAPHICSMODE

        v['EX_STAIRCASEMANIPULATION'] = self.EX_STAIRCASEMANIPULATION
        v['EX_POINTS_PENALTY'] = self.EX_POINTS_PENALTY
        v['EX_TESTSIGNALPERIOD'] = self.EX_TESTSIGNALPERIOD
        v['EX_TMARK'] = self.EX_TMARK
        v['EX_TESTNFNOISE'] = self.EX_TESTNFNOISE
        v['EX_PATCHCOLOR'] = self.EX_PATCHCOLOR
        v['EX_TJITT'] = self.EX_TJITT
        v['EX_TFB'] = self.EX_TFB
        v['EX_POINTS_REWARD'] = self.EX_POINTS_REWARD
        v['EX_PR_SLEEPTIME'] = self.EX_PR_SLEEPTIME
        v['EX_TESTSIGNALTYPE'] = self.EX_TESTSIGNALTYPE
        v['EX_BUTTONS'] = self.EX_BUTTONS
        v['EX_INSTR'] = self.EX_INSTR
        v['EX_RUNS'] = self.EX_RUNS

        v['EX_SND_LOWESTTONE'] = self.EX_SND_LOWESTTONE
        v['EX_SND_HIGHESTTONE'] = self.EX_SND_HIGHESTTONE

        v['EX_EMG_THERMOWIDTH'] = self.EX_EMG_THERMOWIDTH
        v['EX_EMG_THERMOHEIGHT'] = self.EX_EMG_THERMOHEIGHT
        v['EX_EMG_THERMOEDGE'] = self.EX_EMG_THERMOEDGE

        v['EX_TXT_COUNTER'] = self.EX_TXT_COUNTER

        v['MONITOR_PIXWIDTH'] = self.MONITOR_PIXWIDTH
        v['MONITOR_PIXHEIGHT'] = self.MONITOR_PIXHEIGHT
        v['MONITOR_WIDTH'] = self.MONITOR_WIDTH
        v['MONITOR_HEIGHT'] = self.MONITOR_HEIGHT
        v['MONITOR_DISTANCE'] = self.MONITOR_DISTANCE
        v['MONITOR_GAMMA'] = self.MONITOR_GAMMA
        v['MONITOR_FPS'] = self.MONITOR_FPS
        v['MONITOR_USEDEGS'] = self.MONITOR_USEDEGS
        v['MONITOR_DEGS_WIDTHBASE'] = self.MONITOR_DEGS_WIDTHBASE
        v['MONITOR_DEGS_HEIGHTBASE'] = self.MONITOR_DEGS_HEIGHTBASE
        v['MONITOR_FLIPHORIZONTAL'] = self.MONITOR_FLIPHORIZONTAL
        v['MONITOR_FLIPVERTICAL'] = self.MONITOR_FLIPVERTICAL
        v['MONITOR_RECORDFRAMEINTERVALS'] = self.MONITOR_RECORDFRAMEINTERVALS
        v['MONITOR_NSCREENS'] = self.MONITOR_NSCREENS
        v['MONITOR_DISPLAYONSCREEN'] = self.MONITOR_DISPLAYONSCREEN
        v['MONITOR_FULLSCR'] = self.MONITOR_FULLSCR
        v['MONITOR_ALLOWGUI'] = self.MONITOR_ALLOWGUI

        v['LOG_PATHFILE'] = self.LOG_PATHFILE
        v['LOG_PATHFILE_EVENT'] = self.LOG_PATHFILE_EVENT

        v['EVENT_LPT_TRIGGER_WAIT'] = self.EVENT_LPT_TRIGGER_WAIT
        v['EVENT_destip'] = self.EVENT_destip
        v['EVENT_destport'] = self.EVENT_destport
        v['EVENT_LPTAddress'] = self.EVENT_LPTAddress
        v['EVENT_LPTTrigWaitTime'] = self.EVENT_LPTTrigWaitTime
        v['EVENT_TRIGLOG'] = self.EVENT_TRIGLOG
        v['EVENT_sendParallel'] = self.EVENT_sendParallel
        v['EVENT_sendTcpIp'] = self.EVENT_sendTcpIp
        v['EVENT_sendLogFile'] = self.EVENT_sendLogFile
        v['EVENT_printToTerminal'] = self.EVENT_printToTerminal
        v['EVENT_printToTerminalAllowed'] = self.EVENT_printToTerminalAllowed

        # so these are NOW control parameters:
        v['EX_TUNING_TYPE'] = self.EX_TUNING_TYPE  # = 'thr'  # alternatives are 'linear', and maybe 'fancy'
        v['EX_TUNING_PARAMS'] = self.EX_TUNING_PARAMS  # = [1.0, 0.0]  # linear requires a slope and offset. - eill not be used if it's not 'linear'
        v['EX_WIN_CONDITION'] = self.EX_WIN_CONDITION  # = 'time_above_thr'
        v['EX_WIN_PARAMS'] = self.EX_WIN_PARAMS  # = [0.25]  # 25 % of the time, it needs to be above the threshold...
        v['EX_NUMBEROFSETS'] = self.EX_NUMBEROFSETS  # = 6  # how long (sets of 6) do we wish our experiment to have?? Determines also our staircases.
        v['EX_MIXOFSETS'] = self.EX_MIXOFSETS  # = {'train':3, 'transfer':1, 'observe':1, 'rest':1}
        v['EX_STAIRIDENTIFIER'] = self.EX_STAIRIDENTIFIER  # = '0001'  # needed to keep track of the staircases.
        v['EX_XorV_RESET_POINTS'] = self.EX_XorV_RESET_POINTS  # = False  # at the start of the day --> this should be True.

        # use the Cpntrol Parameters:
        CP = self.CP  # control parameters...

        # create G, put it into self too..
        G = dict()
        G['v'] = v
        self.G = G

        # we need this in order to continue working as if we're doing it using the normal (test) script...
        for key in G['v']:
            G[key] = G['v'][
                key]  # this is actually superfluous. But removing it might possibly break things.

        # the main clock
        mainClock = clock.Clock()
        G['mainClock'] = mainClock

        # screen/monitor...
        G = init_screen(G)  # we need to do this

        # logging...
        logging.setDefaultClock(G['mainClock'])
        newLogFile = create_incremental_filename(G['v']['LOG_PATHFILE'])
        expLogger = logging.LogFile(
            newLogFile, logging.EXP)  # the correct loglevel should be EXP!
        print(expLogger)
        logging.LogFile(newLogFile,
                        logging.EXP)  # the correct loglevel should be EXP!
        print('made new logfile: ' + newLogFile)
        for key in G['v'].keys():
            logging.data("{key}: {value}".format(key=key, value=G['v'][key]))
        logging.flush()
        G['logging'] = logging  # put into the G, which is in self

        # event handler...
        G = init_eventcodes(G)  # and this??
        G = start_eh(G)

        init_staircases_quest(G)
        st = make_stimuli(G, CP)
        pr = init_programs(G, st, CP)

        ex = define_experiment(
            G, st, pr,
            CP)  # pr is passed to define_experiment, but then we won't need...

        self.st = st
        self.ex = ex

        # take care of the randomization(s)...
        trialopts = []

        trialopts.append([1, 1, 2, 1, 3, 4])
        trialopts.append([1, 1, 2, 1, 4, 3])
        trialopts.append([1, 1, 2, 3, 1, 4])
        trialopts.append([1, 1, 2, 4, 1, 3])
        trialopts.append([1, 1, 3, 1, 2, 4])
        trialopts.append([1, 1, 3, 1, 4, 2])
        trialopts.append([1, 1, 3, 2, 1, 4])
        trialopts.append([1, 1, 3, 4, 1, 2])
        trialopts.append([1, 1, 4, 1, 3, 2])
        trialopts.append([1, 1, 4, 1, 2, 3])
        trialopts.append([1, 1, 4, 3, 1, 2])
        trialopts.append([1, 1, 4, 2, 1, 3])
        trialopts.append([1, 2, 1, 4, 1, 3])
        trialopts.append([1, 2, 1, 3, 1, 4])
        trialopts.append([1, 3, 1, 4, 1, 2])
        trialopts.append([1, 3, 1, 2, 1, 4])
        trialopts.append([1, 4, 1, 2, 1, 3])
        trialopts.append([1, 4, 1, 3, 1, 2])

        random.shuffle(trialopts)
        random.shuffle(trialopts)
        random.shuffle(trialopts)  # 3 time shuffle, for good luck :-)
        # computational anathema and heretic!

        my_trial_sequence = flatten(
            trialopts[0:G['v']['EX_RUNS']])  # we do 5 of them.
        my_trial_definitions = {
            1: 'train',
            2: 'transfer',
            3: 'observe',
            4: 'rest'
        }

        # so to debug, just run tasks_dbg instead of tasks.
        for t_i in my_trial_sequence:
            self.runlist = iter(
                [my_trial_definitions[i] for i in my_trial_sequence])

        # the ev loop we're going to be using..
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        self.loop = loop

        if G['EX_TESTNFNOISE'] is True:
            self.loop.create_task(pr['GenTestSignal'](G, st, CP))

        logging.flush()
        G['logging'] = logging

        G['cl'] = clock.Clock(
        )  # init the trial-by-trial clock here and put into G...