Connect to the realtime event API and start yielding events.
961486
async def rtm(self) -> AsyncIterator[Event]:
        """"""
        response = cast(RTMStart, await self.api("rtm.start"))

        self.me = Auto.generate(response.self_, "Me", recursive=False)
        self.team = Auto.generate(response.team, "Team", recursive=False)
        self.channels.fill(Channel.build(item) for item in response.channels)
        self.users.fill(User.build(item) for item in response.users)
        self.groups.fill(Group.build(item) for item in response.groups)

        log.debug(
            f"received {len(self.users)} users, {len(self.channels)} channels "
            f"and {len(self.groups)} groups from rtm.start"
        )

        async with self.session.ws_connect(response["url"]) as ws:
            async for msg in ws:
                event: Event = Event.generate(msg.json(), recursive=False)

                if event.type == "goodbye":
                    break

                yield event
1078176
def post_events(self, events):

        

        url = "{0}/{1}/projects/{2}/events".format(self.base_url, self.api_version,
                                                   self.project_id)
        headers = utilities.headers(self.write_key)
        payload = json.dumps(events)
        response = self.fulfill(HTTPMethods.POST, url, data=payload, headers=headers, timeout=self.post_timeout)
        self._error_handling(response)
        return self._get_response_json(response)
23346
def _setup_eventloop(self):
        
        if os.name == 'nt':
            self.eventloop = asyncio.ProactorEventLoop()
        else:
            self.eventloop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.eventloop)
        if os.name == 'posix' and isinstance(threading.current_thread(), threading._MainThread):
            asyncio.get_child_watcher().attach_loop(self.eventloop)
793792
def start(sync_event_source, loop=None):
    """"""

    if not loop:
        loop = asyncio.get_event_loop()

    event_source = asyncio.Queue(loop=loop)

    bridge = threading.Thread(target=_multiprocessing_to_asyncio,
                              args=(sync_event_source, event_source, loop),
                              daemon=True)
    bridge.start()

    app = init_app(event_source, loop=loop)
    aiohttp.web.run_app(app,
                        host=config['wsserver']['host'],
                        port=config['wsserver']['port'])
1158947
def init(self):
        """"""
        # Wrap callback methods in appropriate ctypefunc instances so
        # that the Pulseaudio C API can call them
        self._context_notify_cb = pa_context_notify_cb_t(
            self.context_notify_cb)
        self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
        self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
        self._success_cb = pa_context_success_cb_t(self.success_cb)
        self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)

        # Create the mainloop thread and set our context_notify_cb
        # method to be called when there's updates relating to the
        # connection to Pulseaudio
        _mainloop = pa_threaded_mainloop_new()
        _mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
        context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))

        pa_context_set_state_callback(context, self._context_notify_cb, None)
        pa_context_connect(context, None, 0, None)
        pa_threaded_mainloop_start(_mainloop)

        self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
        self.sinks = []
1163909
def start(token, client_id, loop, on_ready_handler=None):
    """"""
    import discord
    import asyncio

    # Create client
    logger.debug("Creating Discord client")
    asyncio.set_event_loop(loop)
    client = discord.Client()
    from . import _client
    _client.client = client

    from .. import datatools
    if datatools.has_data():
        data = datatools.get_data()
    else:
        # Create a blank data file
        data = {"discord": {}}

    # Save default server info to data
    if "servers" not in data["discord"]:
        data["discord"]["servers"] = {}

    # Save default key info to data
    if "keys" not in data["discord"]:
        data["discord"]["keys"] = {}

    # Save logger info to data
    if "log_level" not in data:
        data["log_level"] = "DEBUG"

    data["discord"]["token"] = token
    data["discord"]["client_id"] = client_id
    datatools.write_data(data)

    # Import event handlers
    logger.debug("Importing event handlers")
    event_handlers = _get_event_handlers()

    # Create event handler combiner
    logger.debug("Compiling event handlers")

    def create_event_handler(event_handler_type):
        async def func(*args, **kwargs):
            for module_event_handler in event_handlers[event_handler_type]:
                # Check for errors in the module event
                try:
                    module_event_handler_func = getattr(module_event_handler,
                                                        event_handler_type)
                    await module_event_handler_func(*args, **kwargs)
                except Exception as module_exception:
                    logger.error("An error occured in '{}'".format(module_event_handler))
                    logger.exception(module_exception)

            if on_ready_handler is not None and event_handler_type == "on_ready":
                await on_ready_handler()

        func.__name__ = event_handler_type
        return func

    # Register event handlers
    logger.debug("Registering event handlers into client")
    for event_handler in event_handlers.keys():
        client.event(create_event_handler(event_handler))

    # Run the client loop
    logger.info("Connecting to Discord")
    try:
        client.loop.run_until_complete(client.login(token))
    except Exception as e:
        logger.exception(e)
        logger.critical("Could not connect to Discord")
    else:
        logger.debug("Running the bot")
        try:
            client.loop.run_until_complete(client.connect())
        except KeyboardInterrupt:
            client.loop.run_until_complete(client.logout())
            pending = asyncio.Task.all_tasks(loop=client.loop)
            gathered = asyncio.gather(*pending, loop=client.loop)
            try:
                gathered.cancel()
                client.loop.run_until_complete(gathered)

                # we want to retrieve any exceptions to make sure that
                # they don't nag us about it being un-retrieved.
                gathered.exception()
            except Exception as e:
                logger.exception(e)
        except Exception as e:
            logger.exception(e)
            pending = asyncio.Task.all_tasks(loop=client.loop)
            gathered = asyncio.gather(*pending, loop=client.loop)
            gathered.exception()
        finally:
            try:
                client.loop.run_until_complete(client.logout())
            except Exception as e:
                logger.exception(e)

            logger.critical("Bot stopped\n")
            client.loop.close()
421871
def _start_event_client(self):
        """"""
        event_client = SnippetClient(package=self.package, ad=self._ad)
        event_client.host_port = self.host_port
        event_client.device_port = self.device_port
        event_client.connect(self.uid,
                             jsonrpc_client_base.JsonRpcCommand.CONTINUE)
        return event_client
166581
def connect(self):
        '''
        
        '''
        if self.connected:
            raise RuntimeError(
                '{} is connected already'.format(self.__class__.__name__))
        if self.closed:
            raise RuntimeError(
                '{} is closed already'.format(self.__class__.__name__))
        self.connected = True
        self._connect()
323381
function subscribeToEvents() {
    const socket = _socket.get(this);

    function onEventApiError(error) {
        dbg('Event API connection error: ' + JSON.stringify(error));
    }

    socket.on('pong', (latency) => {
        dbg(`Event API latency: ${latency} ms`);
    });
    socket.on('connect_error', onEventApiError);
    socket.on('error', onEventApiError);
    socket.on('disconnect', onEventApiError);
    socket.on('reconnect_error', onEventApiError);
    socket.on('reconnect_failed', () => {
        onEventApiError('Reconnecting to the Event API failed');
    });

    socket.on('new_receipt', receiptJSON => {
        const receipt = Receipt.from(receiptJSON, _provider.get(this));
        _eventEmitter.get(this).emit(EventNames.newReceipt, receipt);
    });
}
997255
def run(self):
        '''
        '''

        self.connect()
        while True:
            for event in self.slack_client.rtm_read():
                logger.debug(event)
                if 'type' in event and event['type'] in self.supported_events:
                    event_type = event['type']
                    dispatcher = self.supported_events[event_type]
                    message = dispatcher(event)
                    logger.debug(message)
                    self.baseplate.tell(message)
            self.keepalive()
            time.sleep(0.1)
        return
918081
def run(self):
        
        listener = EventServer(self.address, EventNotifyHandler)
        log.info("Event listener running on %s", listener.server_address)
        # Listen for events until told to stop
        while not self.stop_flag.is_set():
            listener.handle_request()
576686
def trigger_event(self, event, client, args, force_dispatch=False):
        """"""
        self.controller.process_event(event, client, args, force_dispatch=force_dispatch)
1155363
def listen(cls, event, func):
        """"""
        signal(event).connect(func, sender=cls)
535081
def emit_event(self, event):
        """"""
        with self._lock:
            listeners = list(self._event_listeners)

        for cb in list(self._event_listeners):
            # noinspection PyBroadException
            try:
                cb(event)
            except:
                # Don't let exceptions from callbacks kill our thread of execution
                logger.exception("Event callback resulted in unhandled exception")
1004519
def invoke(self):
        

        # Don't sleep a hook if it has never run
        if self.timeout_milliseconds > 0:
            self.ready_time = (
                datetime.now() +
                timedelta(milliseconds=self.timeout_milliseconds))

        self.callback(self.callback_args)
42747
def main():
    """"""
    # Parse command line args.
    _parse_args()
    LOG.info("Starting: %s", __service_id__)

    # Subscribe to state change events.
    # FIXME(BMo) This API is unfortunate as it looks like we are only
    # subscribing to sdp_state events.
    LOG.info('Subscribing to state change events (subscriber = %s)',
             __service_name__)
    sdp_state = SDPState()
    _ = sdp_state.subscribe(subscriber=__service_name__)

    # Initialise the service.
    _ = _init(sdp_state)
    LOG.info('Finished initialising!')

    # Enter a pseudo event-loop (using Sched) to monitor for state change
    # events
    # (Also random set services into a fault or alarm state if enabled)
    LOG.info('Responding to state change events ...')
    try:
        _process_state_change_events()
    except ValueError as error:
        LOG.critical('Value error: %s', str(error))
    except KeyboardInterrupt as err:
        LOG.debug('Keyboard Interrupt %s', err)
    LOG.info('Exiting!')
717347
def connect(self, autospawn=False, wait=False):
		''''''
		if self._loop_closed:
			raise PulseError('Eventloop object was already'
				' destroyed and cannot be reused from this instance.')
		if self.connected is not None: self._ctx_init()
		flags, self.connected = 0, None
		if not autospawn: flags |= c.PA_CONTEXT_NOAUTOSPAWN
		if wait: flags |= c.PA_CONTEXT_NOFAIL
		try: c.pa.context_connect(self._ctx, self.server, flags, None)
		except c.pa.CallError: self.connected = False
		while self.connected is None: self._pulse_iterate()
		if self.connected is False: raise PulseError('Failed to connect to pulseaudio server')