override asyncio.Protocol
197996
def connection_made(self, transport):
        '''
        
        '''

        self._connected = True
        self.transport = transport

        self.remote_ip, self.port = transport.get_extra_info('peername')[:2]

        logging.debug(
            'Connection made (address: {} port: {})'
            .format(self.remote_ip, self.port))

        self.auth_future = self.send_package(protomap.CPROTO_REQ_AUTH,
                                             data=(self._username,
                                                   self._password,
                                                   self._dbname),
                                             timeout=10)

        self._password = None
        self.on_connection_made()
754476
def execute_process_async(func, *args, **kwargs):
  
  global _GIPC_EXECUTOR
  if _GIPC_EXECUTOR is None:
    _GIPC_EXECUTOR = GIPCExecutor(
      num_procs=settings.node.gipc_pool_size,
      num_greenlets=settings.node.greenlet_pool_size)
  return _GIPC_EXECUTOR.submit(func, *args, **kwargs)
561840
def blockingCallFromGreenlet(*args, **kwargs):
    """"""
    reactor = args[0]
    assert reactor.greenlet != getcurrent(), "can't invoke this in the reactor greenlet"
    func = args[1]
    result = AsyncResult()

    def task():
        try:
            result.set(func(*args[2:], **kwargs))
        except Exception, ex:
            result.set_exception(ex)

    reactor.callFromGreenlet(task)
    value = result.get()
    if isinstance(value, defer.Deferred):
        return waitForDeferred(value)
    else:
        return value
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()
788943
def await_command(self, *args, **kwargs) -> 'asyncio.Future[IrcMessage]':
        
        fut = asyncio.Future()
        @self.on_command(*args, **kwargs)
        async def handler(msg):
            fut.set_result(msg)
        # remove handler when done or cancelled
        fut.add_done_callback(lambda _: self.remove_command_handler(handler))
        return fut
1011857
def request(self, method, params):
        """"""
        identifier = random.randint(1, 1000)
        self._transport.write(jsonrpc_request(method, identifier, params))
        self._buffer[identifier] = {'flag': asyncio.Event()}
        yield from self._buffer[identifier]['flag'].wait()
        result = self._buffer[identifier]['data']
        del self._buffer[identifier]['data']
        return result
13262
def check_async(async_, kwargs, default):
    
    if async_ is not None:
        return async_
    elif 'async' in kwargs:
        warnings.warn(
            '"async" attribute is deprecated. Use "async_" instead.',
            DeprecationWarning,
        )
        return kwargs.pop('async')
    else:
        return default
860101
async def wasSet(self, node, oldv):
        '''
        
        '''
        for func in self.onsets:
            try:
                await s_coro.ornot(func, node, oldv)
            except asyncio.CancelledError:
                raise
            except Exception:
                logger.exception('onset() error for %s' % (self.full,))
400016
async def run_with_reloader(loop, coroutine, cleanup=None, *args, **kwargs):
    

    clear_screen()
    print("🤖  Running in debug mode with live reloading")
    print("    (don't forget to disable it for production)")

    # Create watcher
    handler = Handler(loop)
    watcher = Observer()

    # Setup
    path = realpath(os.getcwd())
    watcher.schedule(handler, path=path, recursive=True)
    watcher.start()

    print("    (watching {})".format(path))

    # Run watcher and coroutine together
    done, pending = await asyncio.wait(
        [coroutine, handler.changed], return_when=asyncio.FIRST_COMPLETED
    )

    # Cleanup
    cleanup and cleanup()
    watcher.stop()

    for fut in done:
        # If change event, then reload
        if isinstance(fut.result(), Event):
            print("Reloading...")
            reload()
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'])
856486
def async_iter(func, args_iter, **kwargs):
    
    iter_count = len(args_iter)
    iter_group = uuid()[1]
    # clean up the kwargs
    options = kwargs.get('q_options', kwargs)
    options.pop('hook', None)
    options['broker'] = options.get('broker', get_broker())
    options['group'] = iter_group
    options['iter_count'] = iter_count
    if options.get('cached', None):
        options['iter_cached'] = options['cached']
    options['cached'] = True
    # save the original arguments
    broker = options['broker']
    broker.cache.set('{}:{}:args'.format(broker.list_key, iter_group), SignedPackage.dumps(args_iter))
    for args in args_iter:
        if not isinstance(args, tuple):
            args = (args,)
        async_task(func, *args, **options)
    return iter_group
1043453
async def _asyncio_send(loop, req, *, timeout=10, max_redirects=10):
    """"""
    if not any(h.lower() == 'user-agent' for h in req.headers):
        req = req.with_headers({'User-Agent': _ASYNCIO_USER_AGENT})
    url = urllib.parse.urlsplit(
        req.url + '?' + urllib.parse.urlencode(req.params))
    open_ = partial(asyncio.open_connection, url.hostname, loop=loop)
    connect = open_(443, ssl=True) if url.scheme == 'https' else open_(80)
    reader, writer = await connect
    try:
        headers = '\r\n'.join([
            '{} {} HTTP/1.1'.format(req.method, url.path + '?' + url.query),
            'Host: ' + url.hostname,
            'Connection: close',
            'Content-Length: {}'.format(len(req.content or b'')),
            '\r\n'.join(starmap('{}: {}'.format, req.headers.items())),
        ])
        writer.write(b'\r\n'.join([headers.encode('latin-1'),
                                   b'', req.content or b'']))
        response_bytes = BytesIO(
            await asyncio.wait_for(reader.read(), timeout=timeout))
    finally:
        writer.close()
    resp = HTTPResponse(_SocketAdaptor(response_bytes),
                        method=req.method, url=req.url)
    resp.begin()
    status = resp.getcode()
    if 300 <= status < 400 and 'Location' in resp.headers and max_redirects:
        new_url = urllib.parse.urljoin(req.url, resp.headers['Location'])
        return await _asyncio_send(
            loop, req.replace(url=new_url),
            timeout=timeout,
            max_redirects=max_redirects-1)
    return Response(status, content=resp.read(), headers=resp.headers)
597983
def coerce_to_synchronous(func):
    '''
    
    '''
    if inspect.iscoroutinefunction(func):
        @functools.wraps(func)
        def sync_wrapper(*args, **kwargs):
            loop = asyncio.get_event_loop()
            try:
                loop.run_until_complete(func(*args, **kwargs))
            finally:
                loop.close()
        return sync_wrapper
    return func
971337
def synchronised(func):
        """"""

        # pylint: disable=E0213
        def Wrapper(main_obj, *args, **kwargs):
            main_obj._lock.acquire()  # pylint: disable=W0212
            try:
                return func(main_obj, *args, **kwargs)  # pylint: disable=E1102
            finally:
                main_obj._lock.release()  # pylint: disable=W0212

        return Wrapper
15935
def delegate(self, fn, *args, **kwargs):
        """"""
        callback = functools.partial(fn, *args, **kwargs)
        coro = self.loop.run_in_executor(self.subexecutor, callback)
        return asyncio.ensure_future(coro)
193107
def _trigger_event(self, event, *args, **kwargs):
        """"""
        run_async = kwargs.pop('run_async', False)
        if event in self.handlers:
            if run_async:
                return self.start_background_task(self.handlers[event], *args)
            else:
                try:
                    return self.handlers[event](*args)
                except:
                    self.logger.exception(event + ' handler error')
1020271
async def run_async(self, endpoint: str):
        
        self._connect(endpoint)

        # spawn an initial listen task
        listen_task = asyncio.ensure_future(self._socket.recv_multipart())
        task_list = [listen_task]

        while True:
            dones, pendings = await asyncio.wait(task_list, return_when=asyncio.FIRST_COMPLETED)

            # grab one "done" task to handle
            task_list, done_list = list(pendings), list(dones)
            done = done_list.pop()
            task_list += done_list

            if done == listen_task:
                try:
                    # empty_frame may either be:
                    # 1. a single null frame if the client is a REQ socket
                    # 2. an empty list (ie. no frames) if the client is a DEALER socket
                    identity, *empty_frame, msg = done.result()
                    request = from_msgpack(msg)

                    # spawn a processing task
                    task_list.append(asyncio.ensure_future(
                        self._process_request(identity, empty_frame, request)))
                except Exception as e:
                    if self.serialize_exceptions:
                        _log.exception('Exception thrown in Server run loop during request '
                                       'reception: {}'.format(str(e)))
                    else:
                        raise e
                finally:
                    # spawn a new listen task
                    listen_task = asyncio.ensure_future(self._socket.recv_multipart())
                    task_list.append(listen_task)
            else:
                # if there's been an exception during processing, consider reraising it
                try:
                    done.result()
                except Exception as e:
                    if self.serialize_exceptions:
                        _log.exception('Exception thrown in Server run loop during request '
                                       'dispatch: {}'.format(str(e)))
                    else:
                        raise e