Consumes any remaining body and updates keep-alive status
421963
def fixup() # :nodoc:
      begin
        body{|chunk| }   # read remaining body
      rescue HTTPStatus::Error => ex
        @logger.error("HTTPRequest#fixup: #{ex.class} occurred.")
        @keep_alive = false
      rescue => ex
        @logger.error(ex)
        @keep_alive = false
      end
    end
829652
async def _keepalive(self):
        '''
            
        '''
        while self.protocol:
            vers = await self.RPC('server.version')
            logger.debug("Server version: " + repr(vers))

            # Five minutes isn't really enough anymore; looks like
            # servers are killing 2-minute old idle connections now.
            # But decreasing interval this seems rude.
            await asyncio.sleep(600)
408963
function consumeBody(body) {
  if (this[DISTURBED]) {
    return Body.Promise.reject(new Error(`body used already for: ${this.url}`));
  }

  this[DISTURBED] = true;

  // body is null
  if (this.body === null) {
    return Body.Promise.resolve(Buffer.alloc(0));
  }

  // body is string
  if (typeof this.body === 'string') {
    return Body.Promise.resolve(Buffer.from(this.body));
  }

  // body is blob
  if (this.body instanceof Blob) {
    return Body.Promise.resolve(this.body.buffer);
  }

  // body is buffer
  if (Buffer.isBuffer(this.body)) {
    return Body.Promise.resolve(this.body);
  }

  // istanbul ignore if: should never happen
  if (!(this.body instanceof Stream)) {
    return Body.Promise.resolve(Buffer.alloc(0));
  }

  // body is stream
  // get ready to actually consume the body
  let accum = [];
  let accumBytes = 0;
  let abort = false;

  return new Body.Promise((resolve, reject) => {
    let resTimeout;

    // allow timeout on slow response body
    if (this.timeout) {
      resTimeout = setTimeout(() => {
        abort = true;
        reject(new FetchError(`Response timeout while trying to fetch ${this.url} (over ${this.timeout}ms)`, 'body-timeout'));
      }, this.timeout);
    }

    // handle stream error, such as incorrect content-encoding
    this.body.on('error', err => {
      reject(new FetchError(`Invalid response body while trying to fetch ${this.url}: ${err.message}`, 'system', err));
    });

    this.body.on('data', chunk => {
      if (abort || chunk === null) {
        return;
      }

      if (this.size && accumBytes + chunk.length > this.size) {
        abort = true;
        reject(new FetchError(`content size at ${this.url} over limit: ${this.size}`, 'max-size'));
        return;
      }

      accumBytes += chunk.length;
      accum.push(chunk);
    });

    this.body.on('end', () => {
      if (abort) {
        return;
      }

      clearTimeout(resTimeout);
      resolve(Buffer.concat(accum));
    });
  });
}
251891
def _flush(self, commit=True, using=None):
        
        if commit:
            # XXX: multi-set?
            if self._uses_savepoints():
                self._commit_all_savepoints(using)
            c = self.local.mget('%s_%s_*' %
                                (self.prefix, self._trunc_using(using)))
            for key, value in c.items():
                self.cache_backend.set(key, value, self.timeout)
        else:
            if self._uses_savepoints():
                self._rollback_all_savepoints(using)
        self._clear(using)
        self._clear_sid_stack(using)
759091
def patch_keepalive_run():
    
    _run = luigi.worker.KeepAliveThread.run

    def run(self):
        # do not run the keep-alive loop when sandboxed
        if os.getenv("LAW_SANDBOX_SWITCHED") == "1":
            self.stop()
        else:
            _run(self)

    luigi.worker.KeepAliveThread.run = run
82540
def perform
      future do
        status, headers, body = call(rack_env_defaults)
        response = Weary::Response.new body, status, headers
        yield response if block_given?
        response
      end
    end
7261
protected synchronized void maintenance() {
        // first of all we're checking, if all consumers were already registered. if not - just no-op.
        if (positions.size() < expectedConsumers) {
            log.trace("Skipping maintanance due to not all expected consumers shown up: [{}] vs [{}]", positions.size(), expectedConsumers);
            return;
        }

        // now we should get minimal id of consumed update
        val minIdx = maxAppliedIndexEverywhere();
        val allPositions = new long[positions.size()];
        int cnt = 0;
        for (val p:positions.values())
            allPositions[cnt++] = p.get();

        log.trace("Min idx: {}; last deleted index: {}; stored updates: {}; positions: {}", minIdx, lastDeletedIndex.get(), updates.size(), allPositions);

        // now we're checking, if there are undeleted updates between
        if (minIdx > lastDeletedIndex.get()) {
            // delete everything between them
            for (long e = lastDeletedIndex.get(); e < minIdx; e++) {
                updates.remove(e);
            }

            // now, making sure we won't try to delete stuff twice
            lastDeletedIndex.set(minIdx);
            //System.gc();
        }
    }
1089288
def update_status sig=0
      pid_int = Integer("#{ @pid }")
      begin
        Process::kill sig, pid_int
        true
      rescue Errno::ESRCH
        false
      end
    end
556046
synchronized void statusUpdate(float progress,
                                 String state, 
                                 Counters counters) {
    setProgress(progress);
    setStateString(state);
    setCounters(counters);
  }
1007004
def update_status(self, reset=False):
        """"""
        if self.healthy_update_timer and not reset:
            return

        # get device features only once
        if not self.device_features:
            self.handle_features(self.get_features())

        # Get status from device to register/keep alive UDP
        self.handle_status()

        # Schedule next execution
        self.setup_update_timer()
703061
function sync() {
    syncDom.setAttribute('data-sync-state', 'syncing');
    var opts = {continuous: true, complete: syncError};
    db.replicate.to(remoteCouch, opts);
    db.replicate.from(remoteCouch, opts);
  }
82198
public void updateOccupantStatus (BodyObject body, final byte status)
    {
        // no need to NOOP
        if (body.status != status) {
            // update the status in their body object
            body.setStatus(status);
            body.getLocal(BodyLocal.class).statusTime = System.currentTimeMillis();
        }

        updateOccupantInfo(body, new OccupantInfo.Updater<OccupantInfo>() {
            public boolean update (OccupantInfo info) {
                if (info.status == status) {
                    return false;
                }
                info.status = status;
                return true;
            }
        });
    }
1175774
private void keepAlive(boolean retryOnFailure) {
    long sessionId = state.getSessionId();

    // If the current sessions state is unstable, reset the connection before sending a keep-alive.
    if (state.getState() == Session.State.UNSTABLE)
      connection.reset();

    KeepAliveRequest request = KeepAliveRequest.builder()
      .withSession(sessionId)
      .withCommandSequence(state.getCommandResponse())
      .withEventIndex(state.getEventIndex())
      .build();

    state.getLogger().trace("{} - Sending {}", sessionId, request);
    connection.<KeepAliveRequest, KeepAliveResponse>sendAndReceive(request).whenComplete((response, error) -> {
      if (state.getState() != Session.State.CLOSED) {
        if (error == null) {
          state.getLogger().trace("{} - Received {}", sessionId, response);
          // If the request was successful, update the address selector and schedule the next keep-alive.
          if (response.status() == Response.Status.OK) {
            connection.reset(response.leader(), response.members());
            state.setState(Session.State.OPEN);
            scheduleKeepAlive();
          }
          // If the session is unknown, immediate expire the session.
          else if (response.error() == CopycatError.Type.UNKNOWN_SESSION_ERROR) {
            state.setState(Session.State.EXPIRED);
          }
          // If a leader is still set in the address selector, unset the leader and attempt to send another keep-alive.
          // This will ensure that the address selector selects all servers without filtering on the leader.
          else if (retryOnFailure && connection.leader() != null) {
            connection.reset(null, connection.servers());
            keepAlive(false);
          }
          // If no leader was set, set the session state to unstable and schedule another keep-alive.
          else {
            state.setState(Session.State.UNSTABLE);
            scheduleKeepAlive();
          }
        }
        // If a leader is still set in the address selector, unset the leader and attempt to send another keep-alive.
        // This will ensure that the address selector selects all servers without filtering on the leader.
        else if (retryOnFailure && connection.leader() != null) {
          connection.reset(null, connection.servers());
          keepAlive(false);
        }
        // If no leader was set, set the session state to unstable and schedule another keep-alive.
        else {
          state.setState(Session.State.UNSTABLE);
          scheduleKeepAlive();
        }
      }
    });
  }
1002585
private void _updateStatus() {
        boolean doneWithoutErrors = true;
        boolean doneWithErrors = true;
        boolean finishedOne = false;
        if (_status == Status.DONE || _status == Status.ERROR) {
            return;
        }
        for (AsyncBatchedMetricQuery query: _queries) {
            Status status = query.getStatus();
            if (status == Status.PROCESSING) {
                _status = Status.PROCESSING;
                return;
            }
            boolean queryFinished = (status == Status.DONE || status == Status.ERROR);
            if (queryFinished) {
                finishedOne = true;
            }
            doneWithErrors &= queryFinished;
            doneWithoutErrors &= (status == Status.DONE);
        }
        if (!doneWithoutErrors && doneWithErrors) {
            _status = Status.ERROR;
        } else if (doneWithoutErrors) {
            _status = Status.DONE;
        } else if (finishedOne) {
            _status = Status.PROCESSING;
        } else {
            _status = Status.QUEUED;
        }
    }
152401
def on_open(self, ws):
        """"""
        def keep_alive(interval):
            while True:
                time.sleep(interval)
                self.ping()

        start_new_thread(keep_alive, (self.keep_alive_interval, ))
289042
def __serve_forever(self):
        
        # Start a counter used to compute the time needed for
        # update and export the stats
        counter = Counter()

        # Update stats
        self.stats.update()
        logger.debug('Stats updated in {} seconds'.format(counter.get()))

        # Export stats
        counter_export = Counter()
        self.stats.export(self.stats)
        logger.debug('Stats exported in {} seconds'.format(counter_export.get()))

        # Patch for issue1326 to avoid < 0 refresh
        adapted_refresh = self.refresh_time - counter.get()
        adapted_refresh = adapted_refresh if adapted_refresh > 0 else 0

        # Display stats
        # and wait refresh_time - counter
        if not self.quiet:
            # The update function return True if an exit key 'q' or 'ESC'
            # has been pressed.
            ret = not self.screen.update(self.stats, duration=adapted_refresh)
        else:
            # Nothing is displayed
            # Break should be done via a signal (CTRL-C)
            time.sleep(adapted_refresh)
            ret = True

        return ret
1296922
def is_alive(self):
        
        response = self.get_monitoring_heartbeat()
        if response.status_code == 200 and response.content == 'alive':
            return True

        return False