Consistent-Hash algorithm for calculating server id.

@param client {Object} rpc client.
@param serverType {String} rpc target serverType.
@param msg {Object} rpc message.
@param cb {Function} cb(err, serverId).
779396
function chRoute(client, serverType, msg, cb) {
    const servers = client._station.serversMap[serverType];
    if (!servers || !servers.length) {
        utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`));
        return;
    }
    let con;
    if (!client.chParam) {
        client.chParam = {};
    }
    if (client.chParam[serverType]) {
        con = client.chParam[serverType].consistentHash;
    } else {
        client.opts.station = client._station;
        con = new ConsistentHash(servers, client.opts);
    }
    const hashFieldIndex = client.opts.hashFieldIndex;
    const field = msg.args[hashFieldIndex] || JSON.stringify(msg);
    utils.invokeCallback(cb, null, con.getNode(field));
    client.chParam[serverType] = { consistentHash: con };
}
1092420
public void serviceName_server_id_PUT(String serviceName, Long id, OvhServer body) throws IOException {
		String qPath = "/sslGateway/{serviceName}/server/{id}";
		StringBuilder sb = path(qPath, serviceName, id);
		exec(qPath, "PUT", sb.toString(), body);
	}
336259
public void addScannerServers(final int query_index, final int id, 
      final Set<String> servers) {
    Map<Integer, Set<String>> query_servers = scanner_servers.get(query_index);
    if (query_servers == null) {
      query_servers = new ConcurrentHashMap<Integer, Set<String>>(
          Const.SALT_WIDTH() > 0 ? Const.SALT_BUCKETS() : 1);
      scanner_servers.put(query_index, query_servers);
    }
    query_servers.put(id, servers);
  }
895945
public static int cusolverSpScsreigsHost(
        cusolverSpHandle handle, 
        int m, 
        int nnz, 
        cusparseMatDescr descrA, 
        Pointer csrValA, 
        Pointer csrRowPtrA, 
        Pointer csrColIndA, 
        cuComplex left_bottom_corner, 
        cuComplex right_upper_corner, 
        Pointer num_eigs)
    {
        return checkResult(cusolverSpScsreigsHostNative(handle, m, nnz, descrA, csrValA, csrRowPtrA, csrColIndA, left_bottom_corner, right_upper_corner, num_eigs));
    }
1224994
private void serverKeyExchange(RSA_ServerKeyExchange mesg)
            throws IOException, GeneralSecurityException {
        if (debug != null && Debug.isOn("handshake")) {
            mesg.print(System.out);
        }
        if (!mesg.verify(serverKey, clnt_random, svr_random)) {
            fatalSE(Alerts.alert_handshake_failure,
                "server key exchange invalid");
            // NOTREACHED
        }
        ephemeralServerKey = mesg.getPublicKey();
    }
180089
function do_msgid_header (cb) {
        const msgid = trans.header.get('message-id');
        const mmatch = /@([^>]+)>/.exec(msgid);
        if (mmatch) {
            return plugin.do_lookups(connection, cb, mmatch[1], 'msgid');
        }
        cb();
    }
972738
function version(cb) {

  function _cb(err, result, response) {
    if (err) {
      cb(err);
    } else if (response.headers['x-jenkins']) {
      cb(null, response.headers['x-jenkins']);
    } else {
      cb(new Error(text.__('Not a Jenkins server')));
    }
  }
  this.remoteAccessApi.headJenkins(_cb);
}
1178043
def sync_header_chain(cls, path, bitcoind_server, last_block_id ):
        
        current_block_id = SPVClient.height( path )
        if current_block_id is None:
            assert USE_TESTNET
            current_block_id = -1

        assert (current_block_id >= 0 and USE_MAINNET) or USE_TESTNET

        if current_block_id < last_block_id:
          
            if USE_MAINNET:
                log.debug("Synchronize %s to %s" % (current_block_id, last_block_id))
            else:
                log.debug("Synchronize testnet %s to %s" % (current_block_id + 1, last_block_id ))

            # need to sync
            if current_block_id >= 0:
                prev_block_header = SPVClient.read_header( path, current_block_id )
                prev_block_hash = prev_block_header['hash']

            else:
                # can only happen when in testnet
                prev_block_hash = GENESIS_BLOCK_HASH_TESTNET

            # connect 
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            # timeout (10 min)
            sock.settimeout(600)

            bitcoind_port = 8333
            if ":" in bitcoind_server:
                p = bitcoind_server.split(":")
                bitcoind_server = p[0]
                bitcoind_port = int(p[1])

            log.debug("connect to %s:%s" % (bitcoind_server, bitcoind_port))
            sock.connect( (bitcoind_server, bitcoind_port) )

            client = BlockHeaderClient( sock, path, prev_block_hash, last_block_id )

            # get headers
            client.run()

            # verify headers
            if SPVClient.height(path) < last_block_id:
                raise Exception("Did not receive all headers up to %s (only got %s)" % (last_block_id, SPVClient.height(path)))

            # defensive: make sure it's *exactly* that many blocks 

            rc = SPVClient.verify_header_chain( path )
            if not rc:
                raise Exception("Failed to verify headers (stored in '%s')" % path)

        log.debug("synced headers from %s to %s in %s" % (current_block_id, last_block_id, path))
        return True
512492
function wrrRoute(client, serverType, msg, cb) {
    const servers = client._station.serversMap[serverType];
    if (!servers || !servers.length) {
        utils.invokeCallback(cb, new Error(`rpc servers not exist with serverType: ${serverType}`));
        return;
    }
    let index;
    let weight;
    if (!client.wrrParam) {
        client.wrrParam = {};
    }
    if (client.wrrParam[serverType]) {
        index = client.wrrParam[serverType].index;
        weight = client.wrrParam[serverType].weight;
    } else {
        index = -1;
        weight = 0;
    }
    const getMaxWeight = () => {
        let maxWeight = -1;
        for (let i = 0; i < servers.length; i++) {
            const server = client._station.servers[servers[i]];
            if (!!server.weight && server.weight > maxWeight) {
                maxWeight = server.weight;
            }
        }
        return maxWeight;
    };
    while (true) {      // eslint-disable-line
        index = (index + 1) % servers.length;
        if (index === 0) {
            weight -= 1;
            if (weight <= 0) {
                weight = getMaxWeight();
                if (weight <= 0) {
                    utils.invokeCallback(cb, new Error('rpc wrr route get invalid weight.'));
                    return;
                }
            }
        }
        const server = client._station.servers[servers[index]];
        if (server.weight >= weight) {
            client.wrrParam[serverType] = { index: index, weight: weight };
            utils.invokeCallback(cb, null, server.id);
            return;
        }
    }
}
151926
@Override
    @Deprecated
    public void loadServerInstances(final String serverGroup, final AsyncCallback<List<ServerInstance>> callback) {
        final List<ServerInstance> instancesOfGroup = new LinkedList<ServerInstance>();
        loadHostsAndServerInstances(new SimpleCallback<List<HostInfo>>() {
            @Override
            public void onSuccess(final List<HostInfo> result) {
                for (HostInfo host : result) {
                    List<ServerInstance> instances = host.getServerInstances();
                    for (ServerInstance instance : instances) {
                        if (serverGroup == null) {
                            instancesOfGroup.add(instance);
                        } else if (instance.getGroup().equals(instance.getGroup())) {
                            instancesOfGroup.add(instance);
                        }
                    }
                }
                callback.onSuccess(instancesOfGroup);
            }
        });
    }
253894
private void joinSelf(ServerHeartbeat server,
                        String extAddress, int extPort,
                        String address, int port,
                        String serverHash)
  {
    if (server != _serverSelf) {
      throw new IllegalStateException(L.l("Invalid self: {0} vs {1}", 
                                          server, _serverSelf));
    }
    
    if (! serverHash.equals(_serverSelf.getMachineHash())) {
      throw new IllegalStateException(L.l("Invalid server hash {0} against {1}:{2}({3})",
                                          _serverSelf,
                                          address, port, 
                                          serverHash));
    }
    
    if (port != _serverSelf.port()) {
      throw new IllegalStateException(L.l("Invalid server port {0} against {1}:{2}({3})",
                                          _serverSelf,
                                          address, port, 
                                          serverHash));
    }
    
    boolean isSSL = false;
    ServerHeartbeat extServer = getCluster().createServer(extAddress, extPort, isSSL);
    
    server.setExternalServer(extServer);
    
    server.setMachineHash(serverHash);

    server.getRack().update(server.getUpdate());
    
    heartbeatStart(server);
    
    updateHubHeartbeatSelf();
    
    //_podService.updatePodsFromHeartbeat();
    
    log.fine("join self " + server);
  }
1100648
def rpc(self, request, args):
        
        if request.method != 'POST':
            return self.error(405, request)
        payload = request.get_data(as_text=True) or '{}'
        request_method = request.args.get('method')
        if not request_method:
            return self.error(
                400, request,
                message="A query string parameter method= is missing."
            )
        name_map = self.service.__nirum_method_names__
        try:
            method_facial_name = name_map.behind_names[request_method]
        except KeyError:
            return self.error(
                400,
                request,
                message="Service doesn't have procedure named '{}'.".format(
                    request_method
                )
            )
        try:
            service_method = getattr(self.service, method_facial_name)
        except AttributeError:
            return self.error(
                400,
                request,
                message="Service has no procedure '{}'.".format(
                    request_method
                )
            )
        if not callable(service_method):
            return self.error(
                400, request,
                message="Remote procedure '{}' is not callable.".format(
                    request_method
                )
            )
        try:
            request_json = json.loads(payload)
        except ValueError:
            return self.error(
                400,
                request,
                message="Invalid JSON payload: '{}'.".format(payload)
            )
        type_hints = self.service.__nirum_service_methods__[method_facial_name]
        try:
            arguments = self._parse_procedure_arguments(
                type_hints,
                request_json
            )
        except (NirumProcedureArgumentValueError,
                NirumProcedureArgumentRequiredError) as e:
            return self.error(400, request, message=str(e))
        method_error_types = self.service.__nirum_method_error_types__
        if not callable(method_error_types):  # generated by older compiler
            method_error_types = method_error_types.get
        method_error = method_error_types(method_facial_name, ())
        try:
            result = service_method(**arguments)
        except method_error as e:
            return self._raw_response(400, serialize_meta(e))
        return_type = type_hints['_return']
        if type_hints.get('_v', 1) >= 2:
            return_type = return_type()
        if not self._check_return_type(return_type, result):
            return self.error(
                400,
                request,
                message="Incorrect return type '{0}' "
                        "for '{1}'. expected '{2}'.".format(
                            typing._type_repr(result.__class__),
                            request_method,
                            typing._type_repr(return_type)
                        )
            )
        else:
            return self._raw_response(200, serialize_meta(result))
1210097
def key_type(key, host=None, port=None, db=None, password=None):
    '''
    
    '''
    server = _connect(host, port, db, password)
    return server.type(key)
757041
function validateAddrs (msg, streamHandler, type, cb) {
    try {
      msg.dstPeer.addrs.forEach((addr) => {
        return multiaddr(addr)
      })
    } catch (err) {
      writeResponse(streamHandler, type === proto.CircuitRelay.Type.HOP
        ? proto.CircuitRelay.Status.HOP_DST_MULTIADDR_INVALID
        : proto.CircuitRelay.Status.STOP_DST_MULTIADDR_INVALID)
      return cb(err)
    }

    try {
      msg.srcPeer.addrs.forEach((addr) => {
        return multiaddr(addr)
      })
    } catch (err) {
      writeResponse(streamHandler, type === proto.CircuitRelay.Type.HOP
        ? proto.CircuitRelay.Status.HOP_SRC_MULTIADDR_INVALID
        : proto.CircuitRelay.Status.STOP_SRC_MULTIADDR_INVALID)
      return cb(err)
    }

    return cb(null)
  }
797673
def call_rpc(self, rpc_id, payload=bytes()):
        
        if rpc_id < 0 or rpc_id > 0xFFFF:
            raise RPCInvalidIDError("Invalid RPC ID: {}".format(rpc_id))

        if rpc_id not in self._rpcs:
            raise RPCNotFoundError("rpc_id: {}".format(rpc_id))

        return self._rpcs[rpc_id](payload)
167198
public static byte[] calcNewAddr(byte[] addr, byte[] nonce) {

        byte[] encSender = RLP.encodeElement(addr);
        byte[] encNonce = RLP.encodeBigInteger(new BigInteger(1, nonce));

        return sha3omit12(RLP.encodeList(encSender, encNonce));
    }
681183
function checkServer(hostname, port, cb) {
      const self = this;
      //console.log(`[${this.counter}] checkServer`);

      if (self.status !== Status.STARTING) return;

      setTimeout(function _checkServer_fire() {
        http.request({
          method: 'HEAD',
          hostname: hostname,
          port: port
        }, function _checkServer_httpCallback(res) {
          const statusCodeType = Number(res.statusCode.toString()[0]);

          if ([2, 3, 4].indexOf(statusCodeType) !== -1) {
            return cb(true);
          } else if (statusCodeType === 5) {
            console.log(
              'Server docroot returned 500-level response. Please check ' +
              'your configuration for possible errors.'
            );
            return cb(true);
          }

          checkServer.call(self, hostname, port, cb);
        }).on('error', function _checkServer_httpError(err) {
          // back off after 1s
          if (++self.checkServerTries > 20) {
            console.log('PHP server not started. Retrying...');
            return cb(false);
          }
          checkServer.call(self, hostname, port, cb);
        }).end();
      }, 15);
    }