// rebalance removes dead shards from the Ring.
967723
func (c *ringShards) rebalance() {
	c.mu.RLock()
	shards := c.shards
	c.mu.RUnlock()

	hash := newConsistentHash(c.opt)
	var shardsNum int
	for name, shard := range shards {
		if shard.IsUp() {
			hash.Add(name)
			shardsNum++
		}
	}

	c.mu.Lock()
	c.hash = hash
	c.len = shardsNum
	c.mu.Unlock()
}
1229354
func (p *ChainMonitor) ReorgHandler() {
	defer p.wg.Done()
out:
	for {
		//keepon:
		select {
		case reorgData, ok := <-p.reorgChan:
			p.mtx.Lock()
			if !ok {
				p.mtx.Unlock()
				log.Warnf("Reorg channel closed.")
				break out
			}

			newHeight, oldHeight := reorgData.NewChainHeight, reorgData.OldChainHeight
			newHash, oldHash := reorgData.NewChainHead, reorgData.OldChainHead

			log.Infof("Reorganize started. NEW head block %v at height %d.",
				newHash, newHeight)
			log.Infof("Reorganize started. OLD head block %v at height %d.",
				oldHash, oldHeight)

			// Switch to the side chain.
			stakeDBTipHeight, stakeDBTipHash, err := p.switchToSideChain(reorgData)
			if err != nil {
				log.Errorf("switchToSideChain failed: %v", err)
			}
			if stakeDBTipHeight != newHeight {
				log.Errorf("stakeDBTipHeight is %d, expected %d",
					stakeDBTipHeight, newHeight)
			}
			if *stakeDBTipHash != newHash {
				log.Errorf("stakeDBTipHash is %d, expected %d",
					stakeDBTipHash, newHash)
			}

			p.mtx.Unlock()

			reorgData.WG.Done()

		case <-p.ctx.Done():
			log.Debugf("Got quit signal. Exiting stakedb reorg notification handler.")
			break out
		}
	}
}
33461
func GetBalanceTransaction(id string, params *stripe.BalanceTransactionParams) (*stripe.BalanceTransaction, error) {
	return getC().GetBalanceTransaction(id, params)
}
317629
func (c *stateObject) AddBalance(amount *big.Int) {
	// EIP158: We must check emptiness for the objects such that the account
	// clearing (0,0,0 objects) can take effect.
	if amount.Sign() == 0 {
		if c.empty() {
			c.touch()
		}

		return
	}
	c.SetBalance(new(big.Int).Add(c.Balance(), amount))
}
657457
func (api *KrakenApi) Balance() (*BalanceResponse, error) {
	resp, err := api.queryPrivate("Balance", url.Values{}, &BalanceResponse{})
	if err != nil {
		return nil, err
	}

	return resp.(*BalanceResponse), nil
}
71468
func (api *API) GetBalances(addresses Hashes, threshold uint64, tips ...Hash) (*Balances, error) {
    if err := Validate(ValidateAddresses(false, addresses...)); err != nil {
		return nil, err
	}

	if threshold > 100 {
		return nil, ErrInvalidThreshold
	}

	cleanedAddrs, err := checksum.RemoveChecksums(addresses)
	if err != nil {
		return nil, err
	}

	cmd := &GetBalancesCommand{
		Addresses: cleanedAddrs,
		Threshold: threshold,
		Command:   Command{GetBalancesCmd},
		Tips:      tips,
	}
	rsp := &GetBalancesResponse{}
	if err := api.provider.Send(cmd, rsp); err != nil {
		return nil, err
	}
	balances := &Balances{
		Balances:  make([]uint64, len(rsp.Balances)),
		Milestone: rsp.Milestone, MilestoneIndex: rsp.MilestoneIndex,
	}
	for i, s := range rsp.Balances {
		num, err := strconv.ParseUint(s, 10, 64)
		if err != nil {
			return nil, err
		}
		balances.Balances[i] = num
	}
	return balances, err
}
1204831
func (m *Manager) ResetRebalanceTimer() {
	m.Lock()
	defer m.Unlock()
	m.rebalanceTimer.Reset(clientRPCMinReuseDuration)
}
138683
func (t *AvailService) NodeBalancers() (*NodeBalancersResponse, error) {
	u := &url.Values{}
	v := NodeBalancersResponse{}
	if err := t.client.do("avail.nodebalancers", u, &v.Response); err != nil {
		return nil, err
	}
	v.NodeBalancers = make([]NodeBalancer, 5)
	if err := json.Unmarshal(v.RawData, &v.NodeBalancers); err != nil {
		return nil, err
	}
	return &v, nil
}
1317580
func ErrFunderBalanceDust(commitFee, funderBalance,
	minBalance int64) ReservationError {
	return ReservationError{
		fmt.Errorf("Funder balance too small (%v) with fee=%v sat, "+
			"minimum=%v sat required", funderBalance,
			commitFee, minBalance),
	}
}
1046301
func (s *LoadBalancerService) DeleteLoadBalancer(p *DeleteLoadBalancerParams) (*DeleteLoadBalancerResponse, error) {
	resp, err := s.cs.newRequest("deleteLoadBalancer", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DeleteLoadBalancerResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}
1314002
func (swap *Swap) Balance() int {
	defer swap.lock.Unlock()
	swap.lock.Lock()
	return swap.balance
}
245693
func (c *Client) NodeBalancerUpdate(nbID int, label *string, throttle *int) error {
	args := make(map[string]interface{})
	args["NodeBalancerID"] = nbID
	args["Label"] = label
	args["ClientConnThrottle"] = throttle

	_, err := c.apiCall("nodebalancer.update", args)
	if err != nil {
		return err
	}

	return nil
}
140112
func (c *Cloud) UpdateLoadBalancer(clusterName string, service *v1.Service, nodes []*v1.Node) error {
	instances, err := c.getInstancesByNodeNamesCached(nodeNames(nodes))
	if err != nil {
		return err
	}

	loadBalancerName := cloudprovider.GetLoadBalancerName(service)
	lb, err := c.describeLoadBalancer(loadBalancerName)
	if err != nil {
		return err
	}

	if lb == nil {
		return fmt.Errorf("Load balancer not found")
	}

	err = c.ensureLoadBalancerInstances(orEmpty(lb.LoadBalancerName), lb.Instances, instances)
	if err != nil {
		return nil
	}

	err = c.updateInstanceSecurityGroupsForLoadBalancer(lb, instances)
	if err != nil {
		return err
	}

	return nil
}
481013
func (r Rope) isBalanced() bool {
	if r.node == nil || r.node == emptyNode {
		return true
	}

	len := r.Len()
	maxDepth := reverseFib(len)
	return int(r.node.depth()) <= maxDepth
}
871521
func WithBalancer(value balancer.Balancer) options.Opt {
	return func(p options.Params) {
		if setter, ok := p.(balancerSetter); ok {
			setter.SetBalancer(value)
		}
	}
}
779875
func (s *ServiceController) lockedUpdateLoadBalancerHosts(service *v1.Service, hosts []*v1.Node) error {
	if !wantsLoadBalancer(service) {
		return nil
	}

	// This operation doesn't normally take very long (and happens pretty often), so we only record the final event
	err := s.balancer.UpdateLoadBalancer(context.TODO(), s.clusterName, service, hosts)
	if err == nil {
		// If there are no available nodes for LoadBalancer service, make a EventTypeWarning event for it.
		if len(hosts) == 0 {
			s.eventRecorder.Eventf(service, v1.EventTypeWarning, "UnAvailableLoadBalancer", "There are no available nodes for LoadBalancer service %s/%s", service.Namespace, service.Name)
		} else {
			s.eventRecorder.Event(service, v1.EventTypeNormal, "UpdatedLoadBalancer", "Updated load balancer with new hosts")
		}
		return nil
	}

	// It's only an actual error if the load balancer still exists.
	if _, exists, err := s.balancer.GetLoadBalancer(context.TODO(), s.clusterName, service); err != nil {
		klog.Errorf("External error while checking if load balancer %q exists: name, %v", s.balancer.GetLoadBalancerName(context.TODO(), s.clusterName, service), err)
	} else if !exists {
		return nil
	}

	s.eventRecorder.Eventf(service, v1.EventTypeWarning, "LoadBalancerUpdateFailed", "Error updating load balancer with new hosts %v: %v", nodeNames(hosts), err)
	return err
}
562279
func (pgb *ChainDB) AddressBalance(address string) (bal *dbtypes.AddressBalance, cacheUpdated bool, err error) {
	// Check the cache first.
	bestHash, height := pgb.BestBlock()
	var validHeight *cache.BlockID
	bal, validHeight = pgb.AddressCache.Balance(address)
	if bal != nil && *bestHash == validHeight.Hash {
		return
	}

	busy, wait, done := pgb.CacheLocks.bal.TryLock(address)
	if busy {
		// Let others get the wait channel while we wait.
		// To return stale cache data if it is available:
		// utxos, _ := pgb.AddressCache.UTXOs(address)
		// if utxos != nil {
		// 	return utxos, nil
		// }
		<-wait

		// Try again, starting with the cache.
		return pgb.AddressBalance(address)
	}

	// We will run the DB query, so block others from doing the same. When query
	// and/or cache update is completed, broadcast to any waiters that the coast
	// is clear.
	defer done()

	// Cache is empty or stale, so query the DB.
	ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
	defer cancel()
	bal, err = RetrieveAddressBalance(ctx, pgb.db, address)
	if err != nil {
		err = pgb.replaceCancelError(err)
		return
	}

	// Update the address cache.
	cacheUpdated = pgb.AddressCache.StoreBalance(address, bal,
		cache.NewBlockID(bestHash, height))
	return
}