Atomically lower active GET count
516555
void lowerActiveGetCount( H2ONode h2o ) {
    assert _key.home();    // Only the HOME node for a key tracks replicas
    assert h2o != H2O.SELF;// Do not track self as a replica
    while( true ) {        // Repeat, in case racing GETs are bumping the counter
      int old = _rwlock.get(); // Read the lock-word
      assert old > 0;      // Since lowering, must be at least 1
      assert old != -1;    // Not write-locked, because we are an active reader
      assert _replicas.contains(h2o._unique_idx); // Self-bit is set
      if( RW_CAS(old,old-1,"rlock-") ) {
        if( old-1 == 0 )   // GET count fell to zero?
          synchronized( this ) { notifyAll(); } // Notify any pending blocked PUTs
        return;            // Repeat until count is lowered
      }
    }
  }
253266
def pop(self, timeout=0):
        
        # use atomic range/remove using multi/exec
        pipe = self.server.pipeline()
        pipe.multi()
        pipe.zrange(self.key, 0, 0).zremrangebyrank(self.key, 0, 0)
        results, count = pipe.execute()
        if results:
            return self._decode_request(results[0])
7935
private void discardIdleConnections() {
        List<Connection<CL>> connections = Lists.newArrayList();
        availableConnections.drainTo(connections);
        activeCount.addAndGet(-connections.size());

        for (Connection<CL> connection : connections) {
            try {
                closedConnections.incrementAndGet();
                connection.close(); // This is usually an async operation
            }
            catch (Throwable t) {
                // TODO
            }
        }
    }
1277381
function isActive() {
    try {
      var key = '___session is active___';
      return session.get(key) || session.set(key, true);
    } catch (err) {
      return false;
    }
  }
1119674
long refreshAndGetTotal() {
		long total = 0;

		for (ResultSubpartition part : partition.getAllPartitions()) {
			total += part.unsynchronizedGetNumberOfQueuedBuffers();
		}

		return total;
	}
632101
def all_active(cls):
        

        prefix = context.get_current_config()["redis_prefix"]
        queues = []
        for key in context.connections.redis.keys():
            if key.startswith(prefix):
                queues.append(Queue(key[len(prefix) + 3:]))

        return queues
1279703
def refresh(self):
        """"""
        keys = [self.name]
        args = [self.value, self.timeout]
        # Redis docs claim EVALs are atomic, and I'm inclined to believe it.
        if hasattr(self, '_refresh_script'):
            return self._refresh_script(keys=keys, args=args) == 1
        else:
            keys_and_args = keys + args
            return self.redis.eval(self.lua_refresh, len(keys), *keys_and_args)
1166455
function getStatic(id, basedir, config, name, lesspaths, done) {
  if (arguments.length === 5) {
    done = lesspaths;
    lesspaths = name;
    name = 'config';
  }
  async.parallel({
    html: function (next) {
      var failhard = !!config.template;
      if (config.template && !config.template.match(/\.html$/)) return next(null, config.template);
      fs.readFile(path.join(basedir, config.template || 'config/' + name + '.html'), 'utf8', function (err, data) {
        next(failhard && err, data);
      });
    },
    js: function (next) {
      var failhard = !!config.script;
      fs.readFile(path.join(basedir, config.script || 'config/' + name + '.js'), 'utf8', function (err, text) {
        if (!failhard && err) return next(null, '');
        next(err, text + '\n//# sourceUrl=' + id + '/' + path.join(basedir, config.script || 'config/' + name + '.js') + '\n');
      });
    },
    css: function (next) {
      var failhard = !!config.style;
      fs.readFile(path.join(basedir, config.style || 'config/' + name + '.less'), 'utf8', function (err, text) {
        if (!failhard && err) return next(null, '');
        var source = '\n/** source: ' + id + '/' + (config.style || 'config/' + name + '.less') + ' **/\n';
        if (err) return next(err);
        if (config.style && config.style.slice(-5) !== '.less') {
          return next(null, text + source);
        }
        var fpath = path.join(basedir, config.style || name + '.less');
        
        less.render(text, {
          paths: [path.dirname(fpath)].concat(lesspaths || []),
          filename: fpath
        }).then(function(output) {
          next(null, output.css + source);
        }, function(error) {
          next(error);
        });
      });
    }
  }, function (err, data) {
    return done(err, data.html, data.css, data.js);
  });
}
116101
def pop_pending_if_empty(self, element):
        """"""
        actions = self.state[self.state['current_step']]['actions']
        elem = self.current_target().tree
        if actions[-1][0] == ('target') and actions[-1][1].tree == elem:
            actions.pop()
            actions.pop()
            actions.pop()
1002339
def paginate(self, request, offset=0, limit=None):
        """"""
        return self.collection.offset(offset).limit(limit), self.collection.count()
186796
def run_fn_atomically(self, request):
        """"""
        fn = serializer.loads_fn(request[Msgs.info])
        args, kwargs = request[Msgs.args], request[Msgs.kwargs]
        with self.mutate_safely():
            self.reply(fn(self.state, *args, **kwargs))
1077692
function decreaseBufferPool () {
  if (bufferPool.length > 50 * 1024) {
    if (counter === 1 || notDecreased > counter * 2) {
      const minSliceLen = Math.floor(bufferPool.length / 10)
      const sliceLength = minSliceLen < bufferOffset
        ? bufferOffset
        : minSliceLen
      bufferOffset = 0
      bufferPool = bufferPool.slice(sliceLength, bufferPool.length)
    } else {
      notDecreased++
      counter--
    }
  } else {
    clearInterval(interval)
    counter = 0
    notDecreased = 0
    interval = null
  }
}
375983
private void ensureAvailable(int index) {
        if (data.get(index) != null) {
            // Already have this item.
            return;
        }
        if (client == null) {
            throw new RuntimeException("no remoting client configured");
        }
        Object result;
        int start = index;
        int count;
        if (mode.equals(MODE_ONDEMAND)) {
            // Only get requested item
            count = 1;
        } else if (mode.equals(MODE_FETCHALL)) {
            // Get remaining items
            count = totalCount - cursor;
        } else if (mode.equals(MODE_PAGE)) {
            // Get next page
            // TODO: implement prefetching of multiple pages
            count = 1;
            for (int i = 1; i < pageSize; i++) {
                if (this.data.get(start + i) == null) {
                    count += 1;
                }
            }
        } else {
            // Default to "ondemand"
            count = 1;
        }

        result = client.invokeMethod(serviceName + ".getRecords", new Object[] { id, start + 1, count });
        if (!(result instanceof RecordSetPage)) {
            throw new RuntimeException("expected RecordSetPage but got " + result);
        }

        RecordSetPage page = (RecordSetPage) result;
        if (page.getCursor() != start + 1) {
            throw new RuntimeException("expected offset " + (start + 1) + " but got " + page.getCursor());
        }

        List<List<Object>> data = page.getData();
        if (data.size() != count) {
            throw new RuntimeException("expected " + count + " results but got " + data.size());
        }

        // Store received items
        for (int i = 0; i < count; i++) {
            this.data.add(start + i, data.get(i));
        }
    }
999311
def active_io(self, iocb):
        """"""
        if _debug: IOController._debug("active_io %r", iocb)

        # requests should be idle or pending before coming active
        if (iocb.ioState != IDLE) and (iocb.ioState != PENDING):
            raise RuntimeError("invalid state transition (currently %d)" % (iocb.ioState,))

        # change the state
        iocb.ioState = ACTIVE
236849
function throttle(func, /* istanbul ignore next */ limit = 200) {
  let wait = false;

  return () => {
    if (!wait) {
      func.call();
      wait = true;
      setTimeout(() => {
        wait = false;
      }, limit);
    }
  };
}
830325
def persist_atomic_operations(operations)
      if persisted? && operations && !operations.empty?
        selector = atomic_selector
        _root.collection.find(selector).update_one(positionally(selector, operations), session: _session)
      end
    end
266783
def active_inactive(self):
        """"""
        active_indices = []
        inactive_indices = []
        for index, active in enumerate(self.active):
            if active:
                active_indices.append(index)
            else:
                inactive_indices.append(index)
        return active_indices, inactive_indices