Run the main loop

    server is a limbo Server object
    test_loop, if present, is a number of times to run the loop
355463
def loop(server, test_loop=None):
    
    try:
        loops_without_activity = 0
        while test_loop is None or test_loop > 0:
            start = time.time()
            loops_without_activity += 1

            events = server.slack.rtm_read()
            for event in events:
                loops_without_activity = 0
                logger.debug("got {0}".format(event))
                response = handle_event(event, server)

                # The docs (https://api.slack.com/docs/message-threading)
                # suggest looking for messages where `thread_ts` != `ts`,
                # but I can't see anywhere that it would make a practical
                # difference. If a message is part of a thread, respond to
                # that thread.
                thread_ts = None
                if 'thread_ts' in event:
                    thread_ts = event['thread_ts']

                while response:
                    # The Slack API documentation says:
                    #
                    # Clients should limit messages sent to channels to 4000
                    # characters, which will always be under 16k bytes even
                    # with a message comprised solely of non-BMP Unicode
                    # characters at 4 bytes each.
                    #
                    # but empirical testing shows that I'm getting disconnected
                    # at 4000 characters and even quite a bit lower. Use 1000
                    # to be safe
                    server.slack.rtm_send_message(event["channel"],
                                                  response[:1000], thread_ts)
                    response = response[1000:]

            # Run the loop hook. This doesn't send messages it receives,
            # because it doesn't know where to send them. Use
            # server.slack.post_message to send messages from a loop hook
            run_hook(server.hooks, "loop", server)

            # The Slack RTM API docs say:
            #
            # > When there is no other activity clients should send a ping
            # > every few seconds
            #
            # So, if we've gone >5 seconds without any activity, send a ping.
            # If the connection has broken, this will reveal it so slack can
            # quit
            if loops_without_activity > 5:
                server.slack.ping()
                loops_without_activity = 0

            end = time.time()
            runtime = start - end
            time.sleep(max(1 - runtime, 0))

            if test_loop:
                test_loop -= 1
    except KeyboardInterrupt:
        if os.environ.get("LIMBO_DEBUG"):
            import ipdb
            ipdb.set_trace()
        raise
877857
def run
      if PryDebugger.current_remote_server
        raise 'Already running a pry-remote session!'
      else
        PryDebugger.current_remote_server = self
      end

      setup
      Pry.start @object, {
        :input  => client.input_proxy,
        :output => client.output
      }
    end
343811
def run(&block)
      sync do
        raise Shells::AlreadyRunning if running?
        self.run_flag = true
      end

      begin
        run_hook :on_before_run

        debug 'Connecting...'
        connect

        debug 'Starting output buffering...'
        buffer_output

        debug 'Starting session thread...'
        self.session_thread = Thread.start(self) do |sh|
          begin
            begin
              debug 'Executing setup...'
              sh.instance_eval { setup }
              debug 'Executing block...'
              block.call sh
            ensure
              debug 'Executing teardown...'
              sh.instance_eval { teardown }
            end
          rescue Shells::QuitNow
            # just exit the session.
          rescue =>e
            # if the exception is handled by the hook no further processing is required, otherwise we store the exception
            # to propagate it in the main thread.
            unless sh.run_hook(:on_exception, e) == :break
              sh.sync { sh.instance_eval { self.session_exception = e } }
            end
          end
        end

        # process the input buffer while the thread is alive and the shell is active.
        debug 'Entering IO loop...'
        io_loop do
          if active?
            begin
              if session_thread.status    # not dead
                # process input from the session.
                unless wait_for_output
                  inp = next_input
                  if inp
                    send_data inp
                    self.wait_for_output = (options[:unbuffered_input] == :echo)
                  end
                end

                # continue running the IO loop
                true
              elsif session_exception
                # propagate the exception.
                raise session_exception.class, session_exception.message, session_exception.backtrace
              else
                # the thread has exited, but no exception exists.
                # regardless, the IO loop should now exit.
                false
              end
            rescue IOError
              if ignore_io_error
                # we were (sort of) expecting the IO error, so just tell the IO loop to exit.
                false
              else
                raise
              end
            end
          else
            # the shell session is no longer active, tell the IO loop to exit.
            false
          end
        end
      rescue
        # when an error occurs, try to disconnect, but ignore any further errors.
        begin
          debug 'Disconnecting...'
          disconnect
        rescue
          # ignore
        end
        raise
      else
        # when no error occurs, try to disconnect and propagate any errors (unless we are ignoring IO errors).
        begin
          debug 'Disconnecting...'
          disconnect
        rescue IOError
          raise unless ignore_io_error
        end
      ensure
        # cleanup
        run_hook :on_after_run
        self.run_flag = false
      end

      self
    end
1064066
def run(self):
        
        self._stop = False # Allow re-starting the event loop
        while not self._stop:
            try:
                self._buffer += self.socket.recv(4096)
            except socket.error:
                raise

            lines = self._buffer.split("\n")
            self._buffer = lines.pop() # Last line may not have been fully read
            for line in lines:
                line = line.rstrip("\r")
                _log.debug("%s --> %s", self.server.host, line)
                self.dispatch_event("LINE", line)
                self.dispatch_event("ACTIVITY")
73361
public void run() {

		try {
			while (true) {
				//server thread blocks until a client connects
				Socket socket = server.accept();

				System.out.println(new LogEntry("client (" + socket.getInetAddress().getHostAddress() + ") attempts to connect..."));
				Connection c = establishConnection(socket);
				updateConnectedClients(c);
			}
		} catch (IOException ioe) {
			System.out.println(new LogEntry("server forced to stop with message " + ioe.getClass().getName() + ' ' + ioe.getMessage()));
		} catch (Throwable t) {
			System.out.println(new LogEntry(Level.CRITICAL, "server forced to stop with message " + t.getClass().getName() + ' ' + t.getMessage(), t));
		}
	}
1363188
def server_main(loop, path):
    """"""
    loop.fork()
    logger.debug('forked function')
    sigintwatcher = pyev.Signal(signal.SIGINT, loop, lambda watcher, events: logger.info('interrupt ignored'))
    sigintwatcher.start()
    sigtermwatcher = pyev.Signal(signal.SIGTERM, loop, server_stop)
    sigtermwatcher.start()
    adder = AdderService()
    dispatcher = ObjectDispatch(adder)
    pickle_factory = PickleProtocolFactory(dispatcher)
    pickle_server = UnixServer(loop, pickle_factory, path)
    pickle_server.start()
    msgpack_factory = MsgPackProtocolFactory(dispatcher)
    msgpack_server = UnixServer(loop, msgpack_factory, path + '_mp')
    msgpack_server.start()

    logger.debug('running server loop')

    import cProfile
    cProfile.runctx('loop.loop()', None, {'loop':loop}, 'server_profile')

    logger.debug('server unlooped')
1373186
def run(self):
        
        while True:
            path, params = self.path_queue.get()
            errors = run(path, **params)
            self.result_queue.put(errors)
            self.path_queue.task_done()
258403
def main_loop(self, timeout=None):
        
        if self.trigger_event.wait(timeout):
            try:
                self.func()
            except Exception as e:
                self.logger.warning("Got an exception running {func}: {e}".format(func=self.func, e=str(e)))
            finally:
                self.trigger_event.clear()
346874
def run_loop(&block)
      acquired = false
      begin
        until shutdown_pending?
          # The usual situation
          if relock_every != 0
            i ||= 0
            # 0 % anything is 0, so we always try to get the lock on the first loop.
            if (i %= relock_every) == 0
              acquired = lock_function.call(@name)
            end
          else
            # With relock_every set to 0, only acquire the lock once.
            # Hope you're sure that lock beongs to you.
            acquired ||= lock_function.call(@name)
            i = 0 # no point in incrementing something we don't check.
          end

          yield if acquired

          # Sleep one second at a time so we can quickly respond to
          # shutdown requests.
          sleep_for.times do
            sleep(1) unless shutdown_pending?
          end
          i += 1
        end # loop
      rescue ::Interrupt => ex
        log "shutting down after interrupt: #{ex.class} - #{ex.message}"
        shutdown_soon # Always shut down from an Interrupt, even mid-restart.
        return
      rescue ::Exception => ex
        error "restarting after error: #{ex.class} - #{ex.message}"
        error "backtrace: #{ex.backtrace.join("\n")}"
        restart_soon # Restart if we run into an exception.
      end # begin block
    end
175033
def run(self):
        
        server_address = (self.host, self.port)
        threading = True
        if threading:
            httpd_cls = type('WSGIServer', (ThreadingMixIn, WSGIServer), {})
        else:
            httpd_cls = WSGIServer
        self.httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=False)
        wsgi_handler = get_internal_wsgi_application()
        self.httpd.set_app(wsgi_handler)
        self.is_ready.set()
        self.httpd.serve_forever()
445266
def _start_loop(self):
        """"""
        # Create our main loop, get our bus, and add the signal handler
        loop = GObject.MainLoop()
        bus = SystemBus()
        manager = bus.get(".NetworkManager")
        manager.onPropertiesChanged = self._vpn_signal_handler

        # Loop forever
        loop.run()
119941
def running(self):
        
        r = self._client._redis
        flag = '{}:flag'.format(self._queue)
        if bool(r.exists(flag)):
            return r.ttl(flag) is None

        return False
970264
def run(self):
        

        if self._main_loop:
            return

        self._interface_added_signal = self._bus.add_signal_receiver(
            self._interfaces_added,
            dbus_interface='org.freedesktop.DBus.ObjectManager',
            signal_name='InterfacesAdded')

        # TODO: Also listen to 'interfaces removed' events?

        self._properties_changed_signal = self._bus.add_signal_receiver(
            self._properties_changed,
            dbus_interface=dbus.PROPERTIES_IFACE,
            signal_name='PropertiesChanged',
            arg0='org.bluez.Device1',
            path_keyword='path')

        def disconnect_signals():
            for device in self._devices.values():
                device.invalidate()
            self._properties_changed_signal.remove()
            self._interface_added_signal.remove()

        self._main_loop = GObject.MainLoop()
        try:
            self._main_loop.run()
            disconnect_signals()
        except Exception:
            disconnect_signals()
            raise
931900
def run_server(server)
      grpc_server = server.server

      t = Thread.new { grpc_server.run }
      grpc_server.wait_till_running

      begin
        yield
      ensure
        grpc_server.stop
        sleep(0.1) until grpc_server.stopped?
        t.join
      end
    end
101530
def main(argv=sys.argv[1:], loop=None):
    """"""
    args = docopt(__doc__, argv=argv,
                  version=pkg_resources.require('rflink')[0].version)

    level = logging.ERROR
    if args['-v']:
        level = logging.INFO
    if args['-v'] == 2:
        level = logging.DEBUG
    logging.basicConfig(level=level)

    if not loop:
        loop = asyncio.get_event_loop()

    host = args['--host']
    port = args['--port']
    baud = args['--baud']
    listenport = args['--listenport']

    proxy = RFLinkProxy(port=port, host=host, baud=baud, loop=loop)

    server_coro = asyncio.start_server(
        proxy.client_connected_callback,
        host="",
        port=listenport,
        loop=loop,
    )

    server = loop.run_until_complete(server_coro)
    addr = server.sockets[0].getsockname()
    log.info('Serving on %s', addr)

    conn_coro = proxy.connect()
    loop.run_until_complete(conn_coro)

    proxy.closing = False
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        proxy.closing = True

        # cleanup server
        server.close()
        loop.run_until_complete(server.wait_closed())

        # cleanup server connections
        writers = [i[1] for i in list(clients)]
        for writer in writers:
            writer.close()
            if sys.version_info >= (3, 7):
                loop.run_until_complete(writer.wait_closed())

        # cleanup RFLink connection
        proxy.transport.close()

    finally:
        loop.close()
1130389
def run(self):
        

        try:
            self.__options.callbacks.request_in_thread_before_start(self.__queue_item)
        except Exception as e:
            print(e)

        new_requests = []
        failed = False

        try:
            handler = Handler(self.__options, self.__queue_item)
            new_requests = handler.get_new_requests()

            try:
                self.__queue_item.response.raise_for_status()
            except Exception:
                if self.__queue_item.request.parent_raised_error:
                    failed = True
                else:
                    for new_request in new_requests:
                        new_request.parent_raised_error = True

        except Exception as e:
            failed = True

            error_message = "Setting status of '{}' to '{}' because of an HTTP error.".format(
                self.__queue_item.request.url,
                QueueItem.STATUS_ERRORED
            )

            DebugHelper.output(self.__options, error_message)
            DebugHelper.output(self.__options, e)

            try:
                self.__options.callbacks.request_on_error(self.__queue_item, str(e))
            except Exception as e:
                print(e)

        for new_request in new_requests:
            new_request.parent_url = self.__queue_item.request.url

        try:
            self.__options.callbacks.request_in_thread_after_finish(self.__queue_item)
        except Exception as e:
            print(e)

        with self.__callback_lock:
            self.__callback(self.__queue_item, new_requests, failed)
365210
def run(self):
        ''''''
        with spawn_output_reader() as (stdout_capture, stdout_thread):
            with spawn_output_reader() as (stderr_capture, stderr_thread):
                context = starter_iocontext(stdout_capture, stderr_capture)
                status = self._exec(context)
        stdout_bytes = stdout_thread.join()
        stderr_bytes = stderr_thread.join()
        result = Result(status.code, stdout_bytes, stderr_bytes)
        if is_checked_error(status):
            raise StatusError(result, self)
        return result