Esempio n. 1
0
class SchedulingService(Service):
    """
    Simple L{IService} implementation.
    """
    def __init__(self):
        self.coop = Cooperator(started=False)

    def addIterator(self, iterator):
        return self.coop.coiterate(iterator)

    def startService(self):
        self.coop.start()

    def stopService(self):
        self.coop.stop()
Esempio n. 2
0
def parallel(iterable, count, callable, *a, **kw):
    """
    Concurrently fire C{callable} for each element in C{iterable}.

    Any additional arguments or keyword-arguments are passed to C{callable}.

    @type  iterable: C{iterable}
    @param iterable: Values to pass to C{callable}.

    @type  count: C{int}
    @param count: Limit of the number of concurrent tasks.

    @type  callable: C{callable}
    @param callable: Callable to fire concurrently.

    @rtype:  L{twisted.internet.defer.Deferred}
    """
    coop = Cooperator()
    work = (callable(elem, *a, **kw) for elem in iterable)
    return DeferredList([coop.coiterate(work) for i in xrange(count)])
Esempio n. 3
0
class TestOwnCooperator(unittest.TestCase):
    def setUp(self):
        """
        Create a reactor and Cooperator that can be controlled.

        Instantiate a Doer with the reactor and cooperator.

        Create a Looping Call and set it's clock to the reactor.

        :return:
        """
        self.reactor = Clock()
        self.cooperator = Cooperator()
        self.doer = Doer(self.reactor, self.cooperator)
        self.loop = LoopingCall(self.doer.run)
        self.loop.clock = self.reactor

    def test_control_coop(self):
        """
        Ensure control of own cooperator.

        :return:
        """
        def tick():
            self.reactor.advance(1)
            self.cooperator._tick()

        self.loop.start(1.0, now=True)
        tick()
        self.assertEqual(1, self.doer.count)
        tick()
        self.assertEqual(2, self.doer.count)
        tick()
        self.assertEqual(3, self.doer.count)

    def tearDown(self):
        self.loop.stop()
Esempio n. 4
0
    def setUp(self):
        """
        Create a reactor and Cooperator that can be controlled.

        Instantiate a Doer with the reactor and cooperator.

        Create a Looping Call and set it's clock to the reactor.

        :return:
        """
        self.reactor = Clock()
        self.cooperator = Cooperator()
        self.doer = Doer(self.reactor, self.cooperator)
        self.loop = LoopingCall(self.doer.run)
        self.loop.clock = self.reactor
    def __init__(self, actr=False):

        self.screen_rect = pygame.Rect(0, 0, 350, 350)
        self.screen = pygame.display.set_mode((self.screen_rect.width, self.screen_rect.height), 0)

        self.grid_color = (128, 128, 128)
        self.max_font_size = int(min([self.screen_rect.width, self.screen_rect.height]) / 4)

        self.font = pygame.font.Font(pygame.font.match_font("Monospace", True), self.max_font_size / 5)
        self.spinner = ['|', '|', '/', '/', '-', '-', '\\', '\\']
        self.spinner_index = 0
        
        self.intro_t = self.font.render("Click the red 'X' to start!", True, (0, 0, 0))
        self.intro_ts = self.intro_t.get_rect()
        self.intro_ts.center = self.screen_rect.center
        self.intro_x = self.font.render("X", True, (255, 0, 0))
        self.intro_xs = self.intro_x.get_rect()
        self.intro_xs.center = (randint(0, self.screen_rect.width), randint(0, self.screen_rect.height))
        while not self.screen_rect.contains(self.intro_xs) or self.intro_ts.colliderect(self.intro_xs):
            self.intro_xs.center = (randint(0, self.screen_rect.width), randint(0, self.screen_rect.height))

        self.snd_correct = pygame.mixer.Sound("beep-3.wav")
        self.snd_incorrect = pygame.mixer.Sound("beep-5.wav")

        self.trial = 0
        self.fake_cursor = self.screen_rect.center

        self.state = self.STATE_INTRO
        self.actr = actr
        self.actr_time_lock = False
        if ACTR6 and self.actr:
            self.state = self.STATE_WAIT_CONNECT
            self.actr = JNI_Server(self, clock=Twisted_MPClock())
            self.actr.addDispatcher(self.d)
            reactor.listenTCP(5555, self.actr)

        self.lc1 = LoopingCall(self.update_env)
        self.lc1.start(1.0 / 30)

        self.coop = Cooperator()
        self.coop.coiterate(self.process_event())
Esempio n. 6
0
    def __init__(
        self,
        hs,
        treq_args={},
        ip_whitelist=None,
        ip_blacklist=None,
        http_proxy=None,
        https_proxy=None,
    ):
        """
        Args:
            hs (synapse.server.HomeServer)
            treq_args (dict): Extra keyword arguments to be given to treq.request.
            ip_blacklist (netaddr.IPSet): The IP addresses that are blacklisted that
                we may not request.
            ip_whitelist (netaddr.IPSet): The whitelisted IP addresses, that we can
               request if it were otherwise caught in a blacklist.
            http_proxy (bytes): proxy server to use for http connections. host[:port]
            https_proxy (bytes): proxy server to use for https connections. host[:port]
        """
        self.hs = hs

        self._ip_whitelist = ip_whitelist
        self._ip_blacklist = ip_blacklist
        self._extra_treq_args = treq_args

        self.user_agent = hs.version_string
        self.clock = hs.get_clock()
        if hs.config.user_agent_suffix:
            self.user_agent = "%s %s" % (self.user_agent,
                                         hs.config.user_agent_suffix)

        # We use this for our body producers to ensure that they use the correct
        # reactor.
        self._cooperator = Cooperator(
            scheduler=_make_scheduler(hs.get_reactor()))

        self.user_agent = self.user_agent.encode("ascii")

        if self._ip_blacklist:
            real_reactor = hs.get_reactor()
            # If we have an IP blacklist, we need to use a DNS resolver which
            # filters out blacklisted IP addresses, to prevent DNS rebinding.
            nameResolver = IPBlacklistingResolver(real_reactor,
                                                  self._ip_whitelist,
                                                  self._ip_blacklist)

            @implementer(IReactorPluggableNameResolver)
            class Reactor:
                def __getattr__(_self, attr):
                    if attr == "nameResolver":
                        return nameResolver
                    else:
                        return getattr(real_reactor, attr)

            self.reactor = Reactor()
        else:
            self.reactor = hs.get_reactor()

        # the pusher makes lots of concurrent SSL connections to sygnal, and
        # tends to do so in batches, so we need to allow the pool to keep
        # lots of idle connections around.
        pool = HTTPConnectionPool(self.reactor)
        # XXX: The justification for using the cache factor here is that larger instances
        # will need both more cache and more connections.
        # Still, this should probably be a separate dial
        pool.maxPersistentPerHost = max(
            (100 * hs.config.caches.global_factor, 5))
        pool.cachedConnectionTimeout = 2 * 60

        self.agent = ProxyAgent(
            self.reactor,
            connectTimeout=15,
            contextFactory=self.hs.get_http_client_context_factory(),
            pool=pool,
            http_proxy=http_proxy,
            https_proxy=https_proxy,
        )

        if self._ip_blacklist:
            # If we have an IP blacklist, we then install the blacklisting Agent
            # which prevents direct access to IP addresses, that are not caught
            # by the DNS resolution.
            self.agent = BlacklistingAgentWrapper(
                self.agent,
                self.reactor,
                ip_whitelist=self._ip_whitelist,
                ip_blacklist=self._ip_blacklist,
            )
Esempio n. 7
0
    def __init__(
        self,
        hs: "HomeServer",
        treq_args: Optional[Dict[str, Any]] = None,
        ip_whitelist: Optional[IPSet] = None,
        ip_blacklist: Optional[IPSet] = None,
        use_proxy: bool = False,
    ):
        """
        Args:
            hs
            treq_args: Extra keyword arguments to be given to treq.request.
            ip_blacklist: The IP addresses that are blacklisted that
                we may not request.
            ip_whitelist: The whitelisted IP addresses, that we can
               request if it were otherwise caught in a blacklist.
            use_proxy: Whether proxy settings should be discovered and used
                from conventional environment variables.
        """
        self.hs = hs

        self._ip_whitelist = ip_whitelist
        self._ip_blacklist = ip_blacklist
        self._extra_treq_args = treq_args or {}

        self.user_agent = hs.version_string
        self.clock = hs.get_clock()
        if hs.config.server.user_agent_suffix:
            self.user_agent = "%s %s" % (
                self.user_agent,
                hs.config.server.user_agent_suffix,
            )

        # We use this for our body producers to ensure that they use the correct
        # reactor.
        self._cooperator = Cooperator(
            scheduler=_make_scheduler(hs.get_reactor()))

        self.user_agent = self.user_agent.encode("ascii")

        if self._ip_blacklist:
            # If we have an IP blacklist, we need to use a DNS resolver which
            # filters out blacklisted IP addresses, to prevent DNS rebinding.
            self.reactor: ISynapseReactor = BlacklistingReactorWrapper(
                hs.get_reactor(), self._ip_whitelist, self._ip_blacklist)
        else:
            self.reactor = hs.get_reactor()

        # the pusher makes lots of concurrent SSL connections to sygnal, and
        # tends to do so in batches, so we need to allow the pool to keep
        # lots of idle connections around.
        pool = HTTPConnectionPool(self.reactor)
        # XXX: The justification for using the cache factor here is that larger instances
        # will need both more cache and more connections.
        # Still, this should probably be a separate dial
        pool.maxPersistentPerHost = max(
            (100 * hs.config.caches.global_factor, 5))
        pool.cachedConnectionTimeout = 2 * 60

        self.agent: IAgent = ProxyAgent(
            self.reactor,
            hs.get_reactor(),
            connectTimeout=15,
            contextFactory=self.hs.get_http_client_context_factory(),
            pool=pool,
            use_proxy=use_proxy,
        )

        if self._ip_blacklist:
            # If we have an IP blacklist, we then install the blacklisting Agent
            # which prevents direct access to IP addresses, that are not caught
            # by the DNS resolution.
            self.agent = BlacklistingAgentWrapper(
                self.agent,
                ip_whitelist=self._ip_whitelist,
                ip_blacklist=self._ip_blacklist,
            )
Esempio n. 8
0
class DistTrialRunnerTestCase(TestCase):
    """
    Tests for L{DistTrialRunner}.
    """
    def setUp(self):
        """
        Create a runner for testing.
        """
        self.runner = DistTrialRunner(TreeReporter,
                                      4, [],
                                      workingDirectory=self.mktemp())
        self.runner._stream = StringIO()

    def test_writeResults(self):
        """
        L{DistTrialRunner.writeResults} writes to the stream specified in the
        init.
        """
        stringIO = StringIO()
        result = DistReporter(Reporter(stringIO))
        self.runner.writeResults(result)
        self.assertTrue(stringIO.tell() > 0)

    def test_createLocalWorkers(self):
        """
        C{createLocalWorkers} iterates the list of protocols and create one
        L{LocalWorker} for each.
        """
        protocols = [object() for x in xrange(4)]
        workers = self.runner.createLocalWorkers(protocols, "path")
        for s in workers:
            self.assertIsInstance(s, LocalWorker)
        self.assertEqual(4, len(workers))

    def test_launchWorkerProcesses(self):
        """
        Given a C{spawnProcess} function, C{launchWorkerProcess} launches a
        python process with a existing path as its argument.
        """
        protocols = [ProcessProtocol() for i in range(4)]
        arguments = []

        def fakeSpawnProcess(processProtocol,
                             executable,
                             args=(),
                             env={},
                             path=None,
                             uid=None,
                             gid=None,
                             usePTY=0,
                             childFDs=None):
            arguments.append(executable)
            arguments.append(args[0])
            arguments.append(args[1])
            arguments.append(args[2])

        self.runner.launchWorkerProcesses(fakeSpawnProcess, protocols, ["foo"])
        self.assertEqual(arguments[0], arguments[1])
        self.assertTrue(os.path.exists(arguments[2]))
        self.assertEqual("foo", arguments[3])

    def test_run(self):
        """
        C{run} starts the reactor exactly once and spawns each of the workers
        exactly once.
        """
        fakeReactor = FakeReactor()
        suite = TrialSuite()
        for i in xrange(10):
            suite.addTest(TestCase())
        self.runner.run(suite, fakeReactor)
        self.assertEqual(fakeReactor.runCount, 1)
        self.assertEqual(fakeReactor.spawnCount, self.runner._workerNumber)

    def test_runUsedDirectory(self):
        """
        L{DistTrialRunner} checks if the test directory is already locked, and
        if it is generates a name based on it.
        """
        class FakeReactorWithLock(FakeReactor):
            def spawnProcess(oself, worker, *args, **kwargs):
                self.assertEqual(
                    os.path.abspath(worker._logDirectory),
                    os.path.abspath(
                        os.path.join(workingDirectory + "-1",
                                     str(oself.spawnCount))))
                localLock = FilesystemLock(workingDirectory + "-1.lock")
                self.assertFalse(localLock.lock())
                oself.spawnCount += 1
                worker.makeConnection(FakeTransport())
                worker._ampProtocol.run = lambda *args: succeed(None)

        newDirectory = self.mktemp()
        os.mkdir(newDirectory)
        workingDirectory = os.path.join(newDirectory, "_trial_temp")
        lock = FilesystemLock(workingDirectory + ".lock")
        lock.lock()
        self.addCleanup(lock.unlock)
        self.runner._workingDirectory = workingDirectory

        fakeReactor = FakeReactorWithLock()
        suite = TrialSuite()
        for i in xrange(10):
            suite.addTest(TestCase())
        self.runner.run(suite, fakeReactor)

    def test_minimalWorker(self):
        """
        L{DistTrialRunner} doesn't try to start more workers than the number of
        tests.
        """
        fakeReactor = FakeReactor()
        self.runner.run(TestCase(), fakeReactor)
        self.assertEqual(fakeReactor.runCount, 1)
        self.assertEqual(fakeReactor.spawnCount, 1)

    def test_runUncleanWarnings(self):
        """
        Running with the C{unclean-warnings} option makes L{DistTrialRunner}
        uses the L{UncleanWarningsReporterWrapper}.
        """
        fakeReactor = FakeReactor()
        self.runner._uncleanWarnings = True
        result = self.runner.run(TestCase(), fakeReactor)
        self.assertIsInstance(result, DistReporter)
        self.assertIsInstance(result.original, UncleanWarningsReporterWrapper)

    def test_runWithoutTest(self):
        """
        When the suite contains no test, L{DistTrialRunner} takes a shortcut
        path without launching any process or starting the reactor.
        """
        fakeReactor = object()
        suite = TrialSuite()
        result = self.runner.run(suite, fakeReactor)
        self.assertIsInstance(result, DistReporter)
        output = self.runner._stream.getvalue()
        self.assertIn("Running 0 test", output)
        self.assertIn("PASSED", output)

    def test_runWithoutTestButWithAnError(self):
        """
        Even if there is no test, the suite can contain an error (most likely,
        an import error): this should make the run fail, and the error should
        be printed.
        """
        fakeReactor = object()
        error = ErrorHolder("an error", Failure(RuntimeError("foo bar")))
        result = self.runner.run(error, fakeReactor)
        self.assertIsInstance(result, DistReporter)
        output = self.runner._stream.getvalue()
        self.assertIn("Running 0 test", output)
        self.assertIn("foo bar", output)
        self.assertIn("an error", output)
        self.assertIn("errors=1", output)
        self.assertIn("FAILED", output)

    def test_runUnexpectedError(self):
        """
        If for some reasons we can't connect to the worker process, the test
        suite catches and fails.
        """
        class FakeReactorWithFail(FakeReactor):
            def spawnProcess(self, worker, *args, **kwargs):
                worker.makeConnection(FakeTransport())
                self.spawnCount += 1
                worker._ampProtocol.run = self.failingRun

            def failingRun(self, case, result):
                return fail(RuntimeError("oops"))

        scheduler = FakeScheduler()
        cooperator = Cooperator(scheduler=scheduler)

        fakeReactor = FakeReactorWithFail()
        result = self.runner.run(TestCase(), fakeReactor, cooperator.cooperate)
        self.assertEqual(fakeReactor.runCount, 1)
        self.assertEqual(fakeReactor.spawnCount, 1)
        scheduler.pump()
        self.assertEqual(1, len(result.original.failures))
Esempio n. 9
0
        """
        called = []

        class FakeReactorWithSuccess(FakeReactor):
            def spawnProcess(self, worker, *args, **kwargs):
                worker.makeConnection(FakeTransport())
                self.spawnCount += 1
                worker._ampProtocol.run = self.succeedingRun

            def succeedingRun(self, case, result):
                called.append(None)
                if len(called) == 5:
                    return fail(RuntimeError("oops"))
                return succeed(None)

        fakeReactor = FakeReactorWithSuccess()

        scheduler = FakeScheduler()
        cooperator = Cooperator(scheduler=scheduler)

        result = self.runner.run(TestCase(),
                                 fakeReactor,
                                 cooperate=cooperator.cooperate,
                                 untilFailure=True)
        scheduler.pump()
        self.assertEqual(5, len(called))
        self.assertFalse(result.wasSuccessful())
        output = self.runner._stream.getvalue()
        self.assertIn("PASSED", output)
        self.assertIn("FAIL", output)
Esempio n. 10
0
 def __init__(self):
     self.coop = Cooperator(started=False)
class Environment(object):

    if ACTR6:
        d = Dispatcher()

    STATE_WAIT_CONNECT = -3
    STATE_WAIT_MODEL = -2
    STATE_INTRO = -1
    STATE_RESET = 0
    STATE_FIXATION = 1
    STATE_UPDATE = 2
    STATE_SEARCH = 3
    STATE_DONE = 4

    colors = {':white': (255, 255, 255), ':black': (0, 0, 0)}

    def __init__(self, actr=False):

        self.screen_rect = pygame.Rect(0, 0, 350, 350)
        self.screen = pygame.display.set_mode(
            (self.screen_rect.width, self.screen_rect.height), 0)

        self.grid_color = (128, 128, 128)
        self.max_font_size = int(
            min([self.screen_rect.width, self.screen_rect.height]) / 4)

        self.font = pygame.font.Font(pygame.font.match_font("Monospace", True),
                                     self.max_font_size / 5)
        self.spinner = ['|', '|', '/', '/', '-', '-', '\\', '\\']
        self.spinner_index = 0

        self.intro_t = self.font.render("Click the red 'X' to start!", True,
                                        (0, 0, 0))
        self.intro_ts = self.intro_t.get_rect()
        self.intro_ts.center = self.screen_rect.center
        self.intro_x = self.font.render("X", True, (255, 0, 0))
        self.intro_xs = self.intro_x.get_rect()
        self.intro_xs.center = (randint(0, self.screen_rect.width),
                                randint(0, self.screen_rect.height))
        while not self.screen_rect.contains(
                self.intro_xs) or self.intro_ts.colliderect(self.intro_xs):
            self.intro_xs.center = (randint(0, self.screen_rect.width),
                                    randint(0, self.screen_rect.height))

        self.snd_correct = pygame.mixer.Sound("beep-3.wav")
        self.snd_incorrect = pygame.mixer.Sound("beep-5.wav")

        self.trial = 0
        self.fake_cursor = self.screen_rect.center

        self.state = self.STATE_INTRO
        self.actr = actr
        self.actr_time_lock = False
        if ACTR6 and self.actr:
            self.state = self.STATE_WAIT_CONNECT
            self.actr = JNI_Server(self, clock=Twisted_MPClock())
            self.actr.addDispatcher(self.d)
            reactor.listenTCP(5555, self.actr)

        self.lc1 = LoopingCall(self.update_env)
        self.lc1.start(1.0 / 30)

        self.coop = Cooperator()
        self.coop.coiterate(self.process_event())

    def reset(self):
        self.trial += 1
        self.intro_xs.center = (randint(0, self.screen_rect.width),
                                randint(0, self.screen_rect.height))
        while not self.screen_rect.contains(
                self.intro_xs) or self.intro_ts.colliderect(self.intro_xs):
            self.intro_xs.center = (randint(0, self.screen_rect.width),
                                    randint(0, self.screen_rect.height))
        self.start = sample([1, 0, 0, 0], 4)
        colors = sample([":red", ":blue"], 2)
        self.letters = sample(string.ascii_uppercase, 4)
        self.objects = [
            Letter(self.letters[i], i + 1, self.start[i], colors,
                   self.max_font_size) for i in range(0, len(self.letters))
        ]
        self.clockwise = choice([True, False])
        if self.clockwise:
            self.bgcolorname = ':black'
        else:
            self.bgcolorname = ':white'
        self.bgcolor = self.colors[self.bgcolorname]
        start = self.start.index(True)
        if self.clockwise:
            self.answer = [self.letters[(start + i) % 4] for i in range(0, 4)]
        else:
            self.answer = [self.letters[(start - i) % 4] for i in range(0, 4)]
        self.response = []

    def validate(self):
        if self.answer == self.response:
            self.snd_correct.play()
            if self.actr:
                self.actr.tone_sound(1320, .25)
        else:
            self.snd_incorrect.play()
            if self.actr:
                self.actr.tone_sound(440, .25)
        self.state = self.STATE_DONE

    def update_objects(self):
        for i in range(0, len(self.objects)):
            if self.objects[i].quad == 1 or self.objects[i].quad == 2:
                basey = self.screen_rect.height / 4
            else:
                basey = self.screen_rect.height / 4 * 3
            if self.objects[i].quad == 1 or self.objects[i].quad == 4:
                basex = self.screen_rect.width / 4
            else:
                basex = self.screen_rect.width / 4 * 3
            self.objects[i].rect.centerx = randint(
                basex - self.screen_rect.width / 8,
                basex + self.screen_rect.width / 8)
            self.objects[i].rect.centery = randint(
                basey - self.screen_rect.height / 8,
                basey + self.screen_rect.height / 8)

    def draw_intro(self):
        self.screen.fill((128, 128, 128))
        self.screen.blit(self.intro_t, self.intro_ts)
        self.screen.blit(self.intro_x, self.intro_xs)
        pygame.display.flip()

    def draw_actr_wait_connect(self):
        self.screen.fill((255, 0, 0))
        f = self.font.render("Waiting for ACT-R to connect", True, (0, 0, 0))
        fs = f.get_rect()
        fs.midbottom = self.screen_rect.center
        self.screen.blit(f, fs)
        f = self.font.render(self.spinner[self.spinner_index], True, (0, 0, 0))
        fs = f.get_rect()
        fs.midtop = self.screen_rect.center
        self.screen.blit(f, fs)
        self.spinner_index = (self.spinner_index + 1) % 8
        pygame.display.flip()

    def draw_actr_wait_model(self):
        self.screen.fill((0, 255, 0))
        f = self.font.render("Waiting for ACT-R model", True, (0, 0, 0))
        fs = f.get_rect()
        fs.midbottom = self.screen_rect.center
        self.screen.blit(f, fs)
        f = self.font.render(self.spinner[self.spinner_index], True, (0, 0, 0))
        fs = f.get_rect()
        fs.midtop = self.screen_rect.center
        self.screen.blit(f, fs)
        self.spinner_index = (self.spinner_index + 1) % 8
        pygame.display.flip()

    def draw_fixation(self):
        self.screen.fill(self.bgcolor)
        pygame.draw.line(
            self.screen, self.grid_color,
            (self.screen_rect.centerx - 10, self.screen_rect.centery),
            (self.screen_rect.centerx + 10, self.screen_rect.centery), 1)
        pygame.draw.line(
            self.screen, self.grid_color,
            (self.screen_rect.centerx, self.screen_rect.centery - 10),
            (self.screen_rect.centerx, self.screen_rect.centery + 10), 1)
        pygame.display.flip()

    def draw_search(self):
        self.screen.fill(self.bgcolor)
        pygame.draw.line(self.screen, self.grid_color, self.screen_rect.midtop,
                         self.screen_rect.midbottom, 1)
        pygame.draw.line(self.screen, self.grid_color,
                         self.screen_rect.midleft, self.screen_rect.midright,
                         1)
        for o in self.objects:
            self.screen.blit(o.surf, o.rect)
        pygame.display.flip()

    def update_env(self):
        if self.state == self.STATE_WAIT_CONNECT:
            self.draw_actr_wait_connect()
        if self.state == self.STATE_WAIT_MODEL:
            self.draw_actr_wait_model()
        if self.state == self.STATE_INTRO:
            self.draw_intro()
        if self.state == self.STATE_RESET:
            self.reset()
            self.state = self.STATE_FIXATION
            if self.actr:
                fix = VisualChunk("f%d" % self.trial, "fixation-cross",
                                  self.screen_rect.centerx,
                                  self.screen_rect.centery)
                self.actr.update_display([fix], clear=True)
        if self.state == self.STATE_UPDATE:
            self.update_objects()
            self.state = self.STATE_SEARCH
            if self.actr:
                chunks = [obj.toChunk() for obj in self.objects]
                chunks.append(
                    VisualChunk(None, "background", self.screen_rect.centerx,
                                self.screen_rect.centery,
                                self.screen_rect.width,
                                self.screen_rect.height, self.bgcolorname))
                self.actr.update_display(chunks, clear=True)
        if self.state == self.STATE_FIXATION:
            self.draw_fixation()
        elif self.state == self.STATE_SEARCH:
            self.draw_search()

    def handle_mouse_event(self, pos):
        if self.state == self.STATE_INTRO:
            if self.intro_xs.collidepoint(pos):
                self.state = self.STATE_RESET

    def handle_key_press(self, key, code):
        if key == pygame.K_ESCAPE:
            reactor.stop()
        elif key == pygame.K_SPACE:
            if self.state == self.STATE_FIXATION:
                self.state = self.STATE_UPDATE
            elif self.state == self.STATE_DONE:
                self.state = self.STATE_RESET
        elif key >= pygame.K_a and key <= pygame.K_z:
            if self.state == self.STATE_SEARCH:
                self.response.append(str.upper(str(code)))
                if len(self.response) == 4:
                    self.validate()

    def process_event(self):
        while True:
            for e in pygame.event.get():
                if e.type == pygame.KEYDOWN:
                    self.handle_key_press(e.key, e.unicode)
                elif e.type == pygame.MOUSEBUTTONDOWN:
                    self.handle_mouse_event(e.pos)
            yield

    def setDefaultClock(self):
        self.lc1.stop()
        self.lc1.clock = reactor
        self.lc1.start(1.0 / 30)

    if ACTR6:

        @d.listen('connectionMade')
        def ACTR6_JNI_Event(self, model, params):
            self.state = self.STATE_WAIT_MODEL
            self.actr.setup(self.screen_rect.width, self.screen_rect.height)

        @d.listen('connectionLost')
        def ACTR6_JNI_Event(self, model, params):
            self.setDefaultClock()
            self.state = self.STATE_WAIT_CONNECT

        @d.listen('reset')
        def ACTR6_JNI_Event(self, model, params):
            self.actr_time_lock = params['time-lock']
            self.setDefaultClock()
            self.state = self.STATE_WAIT_MODEL

        @d.listen('model-run')
        def ACTR6_JNI_Event(self, model, params):
            if not params['resume']:
                self.state = self.STATE_INTRO
                X = VisualChunk(None,
                                "letterobj",
                                self.intro_xs.centerx,
                                self.intro_xs.centery,
                                color=":red")
                self.actr.update_display([X], clear=True)
                self.actr_running = True
            if self.actr_time_lock:
                self.lc1.stop()
                self.lc1.clock = self.actr.clock
                self.lc1.start(1.0 / 30)

        @d.listen('model-stop')
        def ACTR6_JNI_Event(self, model, params):
            pass

        @d.listen('keypress')
        def ACTR6_JNI_Event(self, model, params):
            self.handle_key_press(params['keycode'], chr(params['keycode']))

        @d.listen('mousemotion')
        def ACTR6_JNI_Event(self, model, params):
            # Store "ACT-R" cursor in variable since we are
            # not going to move the real mouse
            self.fake_cursor = params['loc']

        @d.listen('mouseclick')
        def ACTR6_JNI_Event(self, model, params):
            # Simulate a button press using the "ACT-R" cursor loc
            self.handle_mouse_event(self.fake_cursor)
Esempio n. 12
0
            timedelta = timestamp - self._timestamp
            if timedelta.total_seconds() >= 1:
                self.websocket.sendMessage(u'Hello, world!'.encode('utf8'))
                self.websocket.sendMessage(b'\x00\x01\x03\x04', isBinary=True)
                self._timestamp = timestamp

    def display_total_msgs(self):
        total_msgs = len(self.msgs)
        msg = 'WebSocket messages received: {}'.format(unicode(total_msgs))
        msg = self.font.render(msg, True, BLACK)
        w, h = self._display_surface.get_size()
        w = w - msg.get_width()
        h = h - msg.get_height()
        self._display_surface.fill(WHITE)
        self._display_surface.blit(msg, (int(w / 2.0), int(h / 2)))
        pygame.display.flip()

    def process_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.close_websocket()


if __name__ == '__main__':
    log.startLogging(sys.stdout)
    app = App()
    # twisted.internet.task.LoopingCall is also possible
    coop = Cooperator()
    coop.coiterate(app.main())
    reactor.run()  # Start the Twisted reactor.
class Environment(object):
    
    if ACTR6:
        d = Dispatcher()

    STATE_WAIT_CONNECT = -3
    STATE_WAIT_MODEL = -2
    STATE_INTRO = -1
    STATE_RESET = 0
    STATE_FIXATION = 1
    STATE_UPDATE = 2
    STATE_SEARCH = 3
    STATE_DONE = 4

    colors = {':white':(255, 255, 255), ':black':(0, 0, 0)}

    def __init__(self, actr=False):

        self.screen_rect = pygame.Rect(0, 0, 350, 350)
        self.screen = pygame.display.set_mode((self.screen_rect.width, self.screen_rect.height), 0)

        self.grid_color = (128, 128, 128)
        self.max_font_size = int(min([self.screen_rect.width, self.screen_rect.height]) / 4)

        self.font = pygame.font.Font(pygame.font.match_font("Monospace", True), self.max_font_size / 5)
        self.spinner = ['|', '|', '/', '/', '-', '-', '\\', '\\']
        self.spinner_index = 0
        
        self.intro_t = self.font.render("Click the red 'X' to start!", True, (0, 0, 0))
        self.intro_ts = self.intro_t.get_rect()
        self.intro_ts.center = self.screen_rect.center
        self.intro_x = self.font.render("X", True, (255, 0, 0))
        self.intro_xs = self.intro_x.get_rect()
        self.intro_xs.center = (randint(0, self.screen_rect.width), randint(0, self.screen_rect.height))
        while not self.screen_rect.contains(self.intro_xs) or self.intro_ts.colliderect(self.intro_xs):
            self.intro_xs.center = (randint(0, self.screen_rect.width), randint(0, self.screen_rect.height))

        self.snd_correct = pygame.mixer.Sound("beep-3.wav")
        self.snd_incorrect = pygame.mixer.Sound("beep-5.wav")

        self.trial = 0
        self.fake_cursor = self.screen_rect.center

        self.state = self.STATE_INTRO
        self.actr = actr
        self.actr_time_lock = False
        if ACTR6 and self.actr:
            self.state = self.STATE_WAIT_CONNECT
            self.actr = JNI_Server(self, clock=Twisted_MPClock())
            self.actr.addDispatcher(self.d)
            reactor.listenTCP(5555, self.actr)

        self.lc1 = LoopingCall(self.update_env)
        self.lc1.start(1.0 / 30)

        self.coop = Cooperator()
        self.coop.coiterate(self.process_event())

    def reset(self):
        self.trial += 1
        self.intro_xs.center = (randint(0, self.screen_rect.width), randint(0, self.screen_rect.height))
        while not self.screen_rect.contains(self.intro_xs) or self.intro_ts.colliderect(self.intro_xs):
            self.intro_xs.center = (randint(0, self.screen_rect.width), randint(0, self.screen_rect.height))
        self.start = sample([1, 0, 0, 0], 4)
        colors = sample([":red", ":blue"], 2)
        self.letters = sample(string.ascii_uppercase, 4)
        self.objects = [Letter(self.letters[i], i + 1, self.start[i], colors, self.max_font_size) for i in range(0, len(self.letters))]
        self.clockwise = choice([True, False])
        if self.clockwise:
            self.bgcolorname = ':black'
        else:
            self.bgcolorname = ':white'
        self.bgcolor = self.colors[self.bgcolorname]
        start = self.start.index(True)
        if self.clockwise:
            self.answer = [self.letters[(start + i) % 4] for i in range(0, 4)]
        else:
            self.answer = [self.letters[(start - i) % 4]  for i in range(0, 4)]
        self.response = []

    def validate(self):
        if self.answer == self.response:
            self.snd_correct.play()
            if self.actr:
                self.actr.tone_sound(1320, .25)
        else:
            self.snd_incorrect.play()
            if self.actr:
                self.actr.tone_sound(440, .25)
        self.state = self.STATE_DONE

    def update_objects(self):
        for i in range(0, len(self.objects)):
            if self.objects[i].quad == 1 or self.objects[i].quad == 2:
                basey = self.screen_rect.height / 4
            else:
                basey = self.screen_rect.height / 4 * 3
            if self.objects[i].quad == 1 or self.objects[i].quad == 4:
                basex = self.screen_rect.width / 4
            else:
                basex = self.screen_rect.width / 4 * 3
            self.objects[i].rect.centerx = randint(basex - self.screen_rect.width / 8, basex + self.screen_rect.width / 8)
            self.objects[i].rect.centery = randint(basey - self.screen_rect.height / 8, basey + self.screen_rect.height / 8)

    def draw_intro(self):
        self.screen.fill((128, 128, 128))
        self.screen.blit(self.intro_t, self.intro_ts)
        self.screen.blit(self.intro_x, self.intro_xs)
        pygame.display.flip()

    def draw_actr_wait_connect(self):
        self.screen.fill((255, 0, 0))
        f = self.font.render("Waiting for ACT-R to connect", True, (0, 0, 0))
        fs = f.get_rect()
        fs.midbottom = self.screen_rect.center
        self.screen.blit(f, fs)
        f = self.font.render(self.spinner[self.spinner_index], True, (0, 0, 0))
        fs = f.get_rect()
        fs.midtop = self.screen_rect.center
        self.screen.blit(f, fs)
        self.spinner_index = (self.spinner_index + 1) % 8
        pygame.display.flip()
        
    def draw_actr_wait_model(self):
        self.screen.fill((0, 255, 0))
        f = self.font.render("Waiting for ACT-R model", True, (0, 0, 0))
        fs = f.get_rect()
        fs.midbottom = self.screen_rect.center
        self.screen.blit(f, fs)
        f = self.font.render(self.spinner[self.spinner_index], True, (0, 0, 0))
        fs = f.get_rect()
        fs.midtop = self.screen_rect.center
        self.screen.blit(f, fs)
        self.spinner_index = (self.spinner_index + 1) % 8
        pygame.display.flip()

    def draw_fixation(self):
        self.screen.fill(self.bgcolor)
        pygame.draw.line(self.screen, self.grid_color, (self.screen_rect.centerx - 10, self.screen_rect.centery), (self.screen_rect.centerx + 10, self.screen_rect.centery), 1)
        pygame.draw.line(self.screen, self.grid_color, (self.screen_rect.centerx, self.screen_rect.centery - 10), (self.screen_rect.centerx, self.screen_rect.centery + 10), 1)
        pygame.display.flip()

    def draw_search(self):
        self.screen.fill(self.bgcolor)
        pygame.draw.line(self.screen, self.grid_color, self.screen_rect.midtop, self.screen_rect.midbottom, 1)
        pygame.draw.line(self.screen, self.grid_color, self.screen_rect.midleft, self.screen_rect.midright, 1)
        for o in self.objects:
            self.screen.blit(o.surf, o.rect)
        pygame.display.flip()

    def update_env(self):
        if self.state == self.STATE_WAIT_CONNECT:
            self.draw_actr_wait_connect()
        if self.state == self.STATE_WAIT_MODEL:
            self.draw_actr_wait_model()
        if self.state == self.STATE_INTRO:
            self.draw_intro()
        if self.state == self.STATE_RESET:
            self.reset()
            self.state = self.STATE_FIXATION
            if self.actr:
                fix = VisualChunk("f%d" % self.trial, "fixation-cross", self.screen_rect.centerx, self.screen_rect.centery)
                self.actr.update_display([fix], clear=True)
        if self.state == self.STATE_UPDATE:
            self.update_objects()
            self.state = self.STATE_SEARCH
            if self.actr:
                chunks = [obj.toChunk() for obj in self.objects]
                chunks.append(VisualChunk(None, "background", self.screen_rect.centerx, self.screen_rect.centery, self.screen_rect.width, self.screen_rect.height, self.bgcolorname))
                self.actr.update_display(chunks, clear=True)
        if self.state == self.STATE_FIXATION:
            self.draw_fixation()
        elif self.state == self.STATE_SEARCH:
            self.draw_search()
            
    def handle_mouse_event(self, pos):
        if self.state == self.STATE_INTRO:
            if self.intro_xs.collidepoint(pos):
                self.state = self.STATE_RESET
                
    def handle_key_press(self, key, code):
        if key == pygame.K_ESCAPE:
            reactor.stop()
        elif key == pygame.K_SPACE:
            if self.state == self.STATE_FIXATION:
                self.state = self.STATE_UPDATE
            elif self.state == self.STATE_DONE:
                self.state = self.STATE_RESET
        elif key >= pygame.K_a and key <= pygame.K_z:
            if self.state == self.STATE_SEARCH:
                self.response.append(str.upper(str(code)))
                if len(self.response) == 4:
                    self.validate()

    def process_event(self):
        while True:
            for e in pygame.event.get():
                if e.type == pygame.KEYDOWN:
                    self.handle_key_press(e.key, e.unicode)
                elif e.type == pygame.MOUSEBUTTONDOWN:
                    self.handle_mouse_event(e.pos)
            yield

    def setDefaultClock(self):
        self.lc1.stop()
        self.lc1.clock = reactor
        self.lc1.start(1.0 / 30)

    if ACTR6:

        @d.listen('connectionMade')
        def ACTR6_JNI_Event(self, model, params):
            self.state = self.STATE_WAIT_MODEL
            self.actr.setup(self.screen_rect.width, self.screen_rect.height)

        @d.listen('connectionLost')
        def ACTR6_JNI_Event(self, model, params):
            self.setDefaultClock()
            self.state = self.STATE_WAIT_CONNECT

        @d.listen('reset')
        def ACTR6_JNI_Event(self, model, params):
            self.actr_time_lock = params['time-lock']
            self.setDefaultClock()
            self.state = self.STATE_WAIT_MODEL
            
        @d.listen('model-run')
        def ACTR6_JNI_Event(self, model, params):
            if not params['resume']:
                self.state = self.STATE_INTRO
                X = VisualChunk(None, "letterobj", self.intro_xs.centerx, self.intro_xs.centery, color=":red")
                self.actr.update_display([X], clear=True)
                self.actr_running = True
            if self.actr_time_lock:
                self.lc1.stop()
                self.lc1.clock = self.actr.clock
                self.lc1.start(1.0 / 30)

        @d.listen('model-stop')
        def ACTR6_JNI_Event(self, model, params):
            pass

        @d.listen('keypress')
        def ACTR6_JNI_Event(self, model, params):
            self.handle_key_press(params['keycode'], chr(params['keycode']))

        @d.listen('mousemotion')
        def ACTR6_JNI_Event(self, model, params):
            # Store "ACT-R" cursor in variable since we are 
            # not going to move the real mouse
            self.fake_cursor = params['loc']

        @d.listen('mouseclick')
        def ACTR6_JNI_Event(self, model, params):
            # Simulate a button press using the "ACT-R" cursor loc
            self.handle_mouse_event(self.fake_cursor)
Esempio n. 14
0
 def __init__(self):
     self.coop = Cooperator(started=False)
Esempio n. 15
0
 def list_files_ok(self, newfiles):
     self.log("Comparing new files (%d) to old files (%d)", len(newfiles), len(self._files))
     processor = self.process_files(self._files, newfiles)
     # process the file comparison one at a time
     cooperator = Cooperator(scheduler=scheduler)
     cooperator.cooperate(processor)