当前位置: 首页>>代码示例>>Python>>正文


Python event_manager.EventManager类代码示例

本文整理汇总了Python中event_manager.EventManager的典型用法代码示例。如果您正苦于以下问题:Python EventManager类的具体用法?Python EventManager怎么用?Python EventManager使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了EventManager类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _setup_event_system

    def _setup_event_system(self):
        handlers = []

        if self.config.logging and 'color' in self.config.logging and self.config.logging['color']:
            handlers.append(ColoredLoggingHandler(self))
        else:
            handlers.append(LoggingHandler(self))

        if self.config.enable_social:
            handlers.append(SocialHandler(self))

        if self.config.websocket_server_url:
            if self.config.websocket_start_embedded_server:
                self.sio_runner = SocketIoRunner(self.config.websocket_server_url)
                self.sio_runner.start_listening_async()

            websocket_handler = SocketIoHandler(
                self,
                self.config.websocket_server_url
            )
            handlers.append(websocket_handler)

            if self.config.websocket_remote_control:
                remote_control = WebsocketRemoteControl(self).start()

        # @var EventManager
        self.event_manager = EventManager(self.config.walker_limit_output, *handlers)
        self._register_events()
        if self.config.show_events:
            self.event_manager.event_report()
            sys.exit(1)
开发者ID:cbogithub,项目名称:PokemonGo-Bot,代码行数:31,代码来源:__init__.py

示例2: _setup_event_system

    def _setup_event_system(self):
        handlers = []
        if self.config.logging_color:
            handlers.append(ColoredLoggingHandler())
        else:
            handlers.append(LoggingHandler())

        if self.config.websocket_server_url:
            if self.config.websocket_start_embedded_server:
                self.sio_runner = SocketIoRunner(self.config.websocket_server_url)
                self.sio_runner.start_listening_async()

            websocket_handler = SocketIoHandler(
                self,
                self.config.websocket_server_url
            )
            handlers.append(websocket_handler)

            if self.config.websocket_remote_control:
                remote_control = WebsocketRemoteControl(self).start()

        self.event_manager = EventManager(*handlers)
        self._register_events()
        if self.config.show_events:
            self.event_manager.event_report()
            sys.exit(1)
开发者ID:Calcyfer,项目名称:PokemonGo-Bot,代码行数:26,代码来源:__init__.py

示例3: __init__

    def __init__(self, background=None):
        
        if background!=None:
            self.set_background(background)

        self.event_manager = EventManager()
        self.subscribe(pygame.QUIT, "quit", self)

        self.items = pygame.sprite.Group()
开发者ID:Dkazarian,项目名称:Cockroach-and-lamp,代码行数:9,代码来源:scenario.py

示例4: __init__

 def __init__(self,):
     """
     Définit une Window et un screen qui y est dessiné
     """
     self.surface = pygame.display.set_mode((1024, 574), pg.DOUBLEBUF)
     pygame.display.set_caption("Dunwall's Gate")
     self.eventmanager = EventManager(self)
     self._screen = None
     self.game = None
     self.set_screen(HomeScreen())
     self.fpsClock = pygame.time.Clock()
     self.do_run = True
开发者ID:PaulEcoffet,项目名称:stonewallsgate,代码行数:12,代码来源:window.py

示例5: __init__

    def __init__(self, node, southwest, northeast, extras):

        logging.info("Beginning TwitterStreamer init")

        StreamListener.__init__(self)

        # Lock and target location
        self.lock = threading.Lock()
        self.buckets = {}
        self.deltas = {}
        self.uploaders = {}
        self.location = [southwest[LONG],southwest[LAT],northeast[LONG],northeast[LAT]]
        self.event_manager = EventManager()


        # Upload handler
        self.node = node

        logging.info("TwitterStreamer init successful")
开发者ID:andrewsosa001,项目名称:TweetEngine,代码行数:19,代码来源:twitter_streamer.py

示例6: Window

class Window():
    def __init__(self,):
        """
        Définit une Window et un screen qui y est dessiné
        """
        self.surface = pygame.display.set_mode((1024, 574), pg.DOUBLEBUF)
        pygame.display.set_caption("Dunwall's Gate")
        self.eventmanager = EventManager(self)
        self._screen = None
        self.game = None
        self.set_screen(HomeScreen())
        self.fpsClock = pygame.time.Clock()
        self.do_run = True

    def set_screen(self, screen):
        """
        Définit l'écran affiché dans la Window
        """
        if self._screen is not None:
            self._screen.surface.fill(0)
            self._screen.shutdown()
            self.eventmanager.purge_callbacks(self._screen)
        self._screen = screen
        self._screen.start(self, self.eventmanager)

    def set_do_run(self, value=True):
        self.do_run = value

    def start_game(self, game):
        self.game = game
        game.start(self)

    def run(self):
        """
        Lance le jeu
        """
        self.eventmanager.on_quit(lambda x: self.set_do_run(False), "global")
        while self.do_run:
            self._screen.update()
            self._screen.draw()
            if self.game:
                self.game.game_event.update()
            self.eventmanager.run(pygame.event.get())
            pygame.display.flip()
            self.fpsClock.tick(FPS)
        pygame.quit()
开发者ID:PaulEcoffet,项目名称:stonewallsgate,代码行数:46,代码来源:window.py

示例7: PokemonGoBot

class PokemonGoBot(object):
    @property
    def position(self):
        return self.api._position_lat, self.api._position_lng, 0

    @position.setter
    def position(self, position_tuple):
        self.api._position_lat, self.api._position_lng, self.api._position_alt = position_tuple

    @property
    def player_data(self):
        """
        Returns the player data as received from the API.
        :return: The player data.
        :rtype: dict
        """
        return self._player

    def __init__(self, config):
        self.config = config
        self.fort_timeouts = dict()
        self.pokemon_list = json.load(
            open(os.path.join('data', 'pokemon.json'))
        )
        self.item_list = json.load(open(os.path.join('data', 'items.json')))
        self.metrics = Metrics(self)
        self.latest_inventory = None
        self.cell = None
        self.recent_forts = [None] * config.forts_max_circle_size
        self.tick_count = 0
        self.softban = False
        self.start_position = None
        self.last_map_object = None
        self.last_time_map_object = 0
        self.logger = logging.getLogger(type(self).__name__)

        # Make our own copy of the workers for this instance
        self.workers = []

    def start(self):
        self._setup_event_system()
        self._setup_logging()
        self._setup_api()

        random.seed()

    def _setup_event_system(self):
        handlers = [LoggingHandler()]
        if self.config.websocket_server_url:
            if self.config.websocket_start_embedded_server:
                self.sio_runner = SocketIoRunner(self.config.websocket_server_url)
                self.sio_runner.start_listening_async()

            websocket_handler = SocketIoHandler(
                self,
                self.config.websocket_server_url
            )
            handlers.append(websocket_handler)

            if self.config.websocket_remote_control:
                remote_control = WebsocketRemoteControl(self).start()


        self.event_manager = EventManager(*handlers)
        self._register_events()
        if self.config.show_events:
            self.event_manager.event_report()
            sys.exit(1)

        # Registering event:
        # self.event_manager.register_event("location", parameters=['lat', 'lng'])
        #
        # Emitting event should be enough to add logging and send websocket
        # message: :
        # self.event_manager.emit('location', 'level'='info', data={'lat': 1, 'lng':1}),

    def _register_events(self):
        self.event_manager.register_event(
            'location_found',
            parameters=('position', 'location')
        )
        self.event_manager.register_event('api_error')
        self.event_manager.register_event('config_error')

        self.event_manager.register_event('login_started')
        self.event_manager.register_event('login_failed')
        self.event_manager.register_event('login_successful')

        self.event_manager.register_event('set_start_location')
        self.event_manager.register_event('load_cached_location')
        self.event_manager.register_event('location_cache_ignored')
        self.event_manager.register_event(
            'position_update',
            parameters=(
                'current_position',
                'last_position',
                'distance', # optional
                'distance_unit' # optional
            )
        )
#.........这里部分代码省略.........
开发者ID:lyriccoder,项目名称:PokemonGo-Bot,代码行数:101,代码来源:__init__.py

示例8: PokemonGoBot

class PokemonGoBot(Datastore):
    @property
    def position(self):
        return self.api.actual_lat, self.api.actual_lng, self.api.actual_alt

    @property
    def noised_position(self):
        return self.api.noised_lat, self.api.noised_lng, self.api.noised_alt

    #@position.setter # these should be called through api now that gps replication is there...
    #def position(self, position_tuple):
    #    self.api._position_lat, self.api._position_lng, self.api._position_alt = position_tuple

    @property
    def player_data(self):
        """
        Returns the player data as received from the API.
        :return: The player data.
        :rtype: dict
        """
        return self._player

    def __init__(self, config):

        # Database connection MUST be setup before migrations will work
        self.database = _init_database('/data/{}.db'.format(config.username))

        self.config = config
        super(PokemonGoBot, self).__init__()

        self.fort_timeouts = dict()
        self.pokemon_list = json.load(
            open(os.path.join(_base_dir, 'data', 'pokemon.json'))
        )
        self.item_list = json.load(open(os.path.join(_base_dir, 'data', 'items.json')))
        self.metrics = Metrics(self)
        self.latest_inventory = None
        self.cell = None
        self.recent_forts = [None] * config.forts_max_circle_size
        self.tick_count = 0
        self.softban = False
        self.start_position = None
        self.last_map_object = None
        self.last_time_map_object = 0
        self.logger = logging.getLogger(type(self).__name__)
        self.alt = self.config.gps_default_altitude

        # Make our own copy of the workers for this instance
        self.workers = []

        # Theading setup for file writing
        self.web_update_queue = Queue.Queue(maxsize=1)
        self.web_update_thread = threading.Thread(target=self.update_web_location_worker)
        self.web_update_thread.start()

        # Heartbeat limiting
        self.heartbeat_threshold = self.config.heartbeat_threshold
        self.heartbeat_counter = 0
        self.last_heartbeat = time.time()


    def start(self):
        self._setup_event_system()
        self._setup_logging()
        self._setup_api()
        self._load_recent_forts()
        init_inventory(self)
        self.display_player_info()
        self._print_character_info()
        if self.config.pokemon_bag_show_at_start and self.config.pokemon_bag_pokemon_info:
            self._print_list_pokemon()

        random.seed()

    def _setup_event_system(self):
        handlers = []
        if self.config.logging_color:
            handlers.append(ColoredLoggingHandler())
        else:
            handlers.append(LoggingHandler())
        if self.config.enable_social:
            handlers.append(SocialHandler(self))
        if self.config.websocket_server_url:
            if self.config.websocket_start_embedded_server:
                self.sio_runner = SocketIoRunner(self.config.websocket_server_url)
                self.sio_runner.start_listening_async()

            websocket_handler = SocketIoHandler(
                self,
                self.config.websocket_server_url
            )
            handlers.append(websocket_handler)

            if self.config.websocket_remote_control:
                remote_control = WebsocketRemoteControl(self).start()

        self.event_manager = EventManager(*handlers)
        self._register_events()
        if self.config.show_events:
            self.event_manager.event_report()
#.........这里部分代码省略.........
开发者ID:dhluong90,项目名称:PokemonGo-Bot,代码行数:101,代码来源:__init__.py

示例9: TwitterStreamer

class TwitterStreamer(StreamListener):

    def __init__(self, node, southwest, northeast, extras):

        logging.info("Beginning TwitterStreamer init")

        StreamListener.__init__(self)

        # Lock and target location
        self.lock = threading.Lock()
        self.buckets = {}
        self.deltas = {}
        self.uploaders = {}
        self.location = [southwest[LONG],southwest[LAT],northeast[LONG],northeast[LAT]]
        self.event_manager = EventManager()


        # Upload handler
        self.node = node

        logging.info("TwitterStreamer init successful")

    #
    #   Threading Functiosn
    #

    # Start node
    def start(self):

        logging.info("Starting TwitterStreamer")

        # This handles Twitter authetification and the connection to Twitter Streaming API
        auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
        auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

        # 2nd parameter self serves as the StreamListener object
        self.stream = Stream(auth, self)

        logging.debug("Created Stream object")

        # Start streaming with right parameters
        #self.stream.filter(locations=self.location, async=True)
        t = threading.Thread(target=self.stream.filter, kwargs={'locations':self.location, 'async':False})
        t.daemon = True
        t.start()

        logging.info("TwitterStreamer started successfully")

        return t


    def stop(self):

        logging.info("Stopping TwitterStreamer")

        # Disconnect the stream
        self.stream.disconnect()

        # Cancel our uploading threads
        for t in self.uploaders:
            self.uploaders[t].cancel()

        logging.info("TwitterStreamer stopped")


    #
    #   Data Management
    #

    def find_location(self, json):
        # Primary check
        coordinates = json['place']['bounding_box']['coordinates'][0]
        return coordinates

    def record_event(self,long,lat):

        key = str(long) + "," + str(lat)

        # If this is the first time recording for bucket, launch updater
        if key not in self.buckets:
            self.buckets[key] = self.buckets.get(key,0) + 1
            self.deltas[key] = datetime.datetime.now()
            self.post_bucket(key)
        else:
            self.buckets[key] += 1


    def post_bucket(self, key):

        #now = datetime.datetime.now()
        #period = (now - self.deltas[key]).total_seconds()
        #self.deltas[key] = now
        period = 10

        velocity = float(self.buckets[key]) / float(period)

        accel, torque = self.event_manager.record(velocity)

        x, y = [int(i) for i in key.split(',')]

#.........这里部分代码省略.........
开发者ID:andrewsosa001,项目名称:TweetEngine,代码行数:101,代码来源:twitter_streamer.py

示例10: setUp

 def setUp(self):
     self.event_manager = EventManager()
     self.client = MockClient(user_id='60')
     self.client2 = MockClient(user_id='50')
开发者ID:ashkan18,项目名称:sc,代码行数:4,代码来源:test-event-manager.py

示例11: TestEventManager

class TestEventManager(unittest.TestCase):
    def setUp(self):
        self.event_manager = EventManager()
        self.client = MockClient(user_id='60')
        self.client2 = MockClient(user_id='50')

    def test_add_client(self):
        self.assertEqual(len(self.event_manager.clients), 0)

        self.event_manager.add_client(self.client)
        self.assertEqual(len(self.event_manager.clients), 1)
        self.assertEqual(self.event_manager.clients[self.client.user_id].user_id, self.client.user_id)

    def test_remove_client(self):
        self.event_manager.clients[self.client.user_id] = self.client
        self.assertEqual(len(self.event_manager.clients), 1)
        self.assertEqual(self.event_manager.clients[self.client.user_id].user_id, self.client.user_id)

        self.event_manager.remove_client(self.client.user_id)
        self.assertEqual(len(self.event_manager.clients), 0)

    def test_wrong_event(self):
        bogus_event = '666\F/60D50'
        with self.assertRaises(AssertionError):
            self.event_manager.receive_event(bogus_event)

    def test_follow_event_no_user(self):
        follow_event = '666|F|60|50'
        self.assertEqual(len(self.event_manager.clients), 0)
        self.assertEqual(len(self.event_manager.followers), 0)
        self.event_manager.receive_event(follow_event)
        self.assertEqual(len(self.event_manager.clients), 0)
        self.assertEqual(len(self.event_manager.followers), 1)
        self.assertIn('50', self.event_manager.followers)
        self.assertIn('60', self.event_manager.followers['50'])

    def test_follow_event_with_user(self):
        follow_event = '666|F|60|50'
        self.event_manager.add_client(self.client)
        self.event_manager.add_client(self.client2)
        self.assertEqual(len(self.event_manager.clients), 2)
        self.assertEqual(len(self.event_manager.followers), 0)
        self.event_manager.receive_event(follow_event)
        self.assertEqual(len(self.event_manager.clients), 2)
        self.assertEqual(len(self.event_manager.followers), 1)
        self.assertIn('50', self.event_manager.followers)
        self.assertIn('60', self.event_manager.followers['50'])

    def test_un_follow(self):
        self.event_manager.followers.setdefault('60', set()).add('50')
        response = self.event_manager.u_event('50', '60')
        self.assertEqual(len(self.event_manager.followers['60']), 0)
        self.assertEqual(len(response), 0)  # no one is informed

    def test_broadcast_event(self):
        self.event_manager.add_client(self.client)
        self.event_manager.add_client(self.client2)
        response = self.event_manager.b_event()
        self.assertEqual(len(response), 2)
        self.assertIn(self.client.user_id, response)
        self.assertIn(self.client2.user_id, response)

    def test_status_event(self):
        self.event_manager.followers.setdefault(self.client.user_id, set()).add(self.client2.user_id)
        response = self.event_manager.s_event(self.client.user_id)
        self.assertEqual(len(response), 1)
        self.assertIn(self.client2.user_id, response)

    def test_send_message_event(self):
        self.event_manager.followers.setdefault(self.client.user_id, set()).add(self.client2.user_id)
        response = self.event_manager.p_event(self.client.user_id, self.client2.user_id)
        self.assertEqual(len(response), 1)
        self.assertIn(self.client2.user_id, response)
开发者ID:ashkan18,项目名称:sc,代码行数:73,代码来源:test-event-manager.py


注:本文中的event_manager.EventManager类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。