// chance returns the selection probability for a known address.  The priority
// depends upon how recently the address has been seen, how recently it was last
// attempted and how often attempts to connect to it have failed.
190832
func (ka *KnownAddress) chance() float64 {
	now := time.Now()
	lastAttempt := now.Sub(ka.lastattempt)

	if lastAttempt < 0 {
		lastAttempt = 0
	}

	c := 1.0

	// Very recent attempts are less likely to be retried.
	if lastAttempt < 10*time.Minute {
		c *= 0.01
	}

	// Failed attempts deprioritise.
	for i := ka.attempts; i > 0; i-- {
		c /= 1.5
	}

	return c
}
1263829
func (s *MatcherSession) AllocateRetrieval() (uint, bool) {
	fetcher := make(chan uint)

	select {
	case <-s.quit:
		return 0, false
	case s.matcher.retrievers <- fetcher:
		bit, ok := <-fetcher
		return bit, ok
	}
}
827437
func (beng BernoulliGenerator) Bernoulli_P(p float64) bool {
	if !(0.0 <= p && p <= 1.0) {
		panic(fmt.Sprintf("Invalid probability: %.2f", p))
	}
	return beng.uniform.Float64() < p
}
728706
func GetRandomBytes(len int) ([]byte, error) {
	key := make([]byte, len)

	// TODO: rand could fill less bytes then len
	_, err := rand.Read(key)
	if err != nil {
		return nil, errors.Wrap(err, "error getting random bytes")
	}

	return key, nil
}
1307790
func (m *MonotonicEntropy) random() (inc uint64, err error) {
	if m.inc <= 1 {
		return 1, nil
	}

	// Fast path for using a underlying rand.Rand directly.
	if m.rng != nil {
		// Range: [1, m.inc)
		return 1 + uint64(m.rng.Int63n(int64(m.inc))), nil
	}

	// bitLen is the maximum bit length needed to encode a value < m.inc.
	bitLen := bits.Len64(m.inc)

	// byteLen is the maximum byte length needed to encode a value < m.inc.
	byteLen := uint(bitLen+7) / 8

	// msbitLen is the number of bits in the most significant byte of m.inc-1.
	msbitLen := uint(bitLen % 8)
	if msbitLen == 0 {
		msbitLen = 8
	}

	for inc == 0 || inc >= m.inc {
		if _, err = io.ReadFull(m.Reader, m.rand[:byteLen]); err != nil {
			return 0, err
		}

		// Clear bits in the first byte to increase the probability
		// that the candidate is < m.inc.
		m.rand[0] &= uint8(int(1<<msbitLen) - 1)

		// Convert the read bytes into an uint64 with byteLen
		// Optimized unrolled loop.
		switch byteLen {
		case 1:
			inc = uint64(m.rand[0])
		case 2:
			inc = uint64(binary.LittleEndian.Uint16(m.rand[:2]))
		case 3, 4:
			inc = uint64(binary.LittleEndian.Uint32(m.rand[:4]))
		case 5, 6, 7, 8:
			inc = uint64(binary.LittleEndian.Uint64(m.rand[:8]))
		}
	}

	// Range: [1, m.inc)
	return 1 + inc, nil
}
122192
func (a *AddrManager) GetAddress() *KnownAddress {
	// Protect concurrent access.
	a.mtx.Lock()
	defer a.mtx.Unlock()

	if a.numAddresses() == 0 {
		return nil
	}

	// Use a 50% chance for choosing between tried and new table entries.
	if a.nTried > 0 && (a.nNew == 0 || a.rand.Intn(2) == 0) {
		// Tried entry.
		large := 1 << 30
		factor := 1.0
		for {
			// pick a random bucket.
			bucket := a.rand.Intn(len(a.addrTried))
			if a.addrTried[bucket].Len() == 0 {
				continue
			}

			// Pick a random entry in the list
			e := a.addrTried[bucket].Front()
			for i :=
				a.rand.Int63n(int64(a.addrTried[bucket].Len())); i > 0; i-- {
				e = e.Next()
			}
			ka := e.Value.(*KnownAddress)
			randval := a.rand.Intn(large)
			if float64(randval) < (factor * ka.chance() * float64(large)) {
				log.Tracef("Selected %v from tried bucket",
					NetAddressKey(ka.na))
				return ka
			}
			factor *= 1.2
		}
	} else {
		// new node.
		// XXX use a closure/function to avoid repeating this.
		large := 1 << 30
		factor := 1.0
		for {
			// Pick a random bucket.
			bucket := a.rand.Intn(len(a.addrNew))
			if len(a.addrNew[bucket]) == 0 {
				continue
			}
			// Then, a random entry in it.
			var ka *KnownAddress
			nth := a.rand.Intn(len(a.addrNew[bucket]))
			for _, value := range a.addrNew[bucket] {
				if nth == 0 {
					ka = value
				}
				nth--
			}
			randval := a.rand.Intn(large)
			if float64(randval) < (factor * ka.chance() * float64(large)) {
				log.Tracef("Selected %v from new bucket",
					NetAddressKey(ka.na))
				return ka
			}
			factor *= 1.2
		}
	}
}
932110
func (r *Random) Select(pool HostPool, request *http.Request) *UpstreamHost {

	// Because the number of available hosts isn't known
	// up front, the host is selected via reservoir sampling
	// https://en.wikipedia.org/wiki/Reservoir_sampling
	var randHost *UpstreamHost
	count := 0
	for _, host := range pool {
		if !host.Available() {
			continue
		}

		// (n % 1 == 0) holds for all n, therefore randHost
		// will always get assigned a value if there is
		// at least 1 available host
		count++
		if (rand.Int() % count) == 0 {
			randHost = host
		}
	}
	return randHost
}
27494
func (lbp *Random) Choose(peers []fab.Peer) (fab.Peer, error) {
	if len(peers) == 0 {
		logger.Warn("No peers to choose from!")
		return nil, nil
	}

	index := rand.Intn(len(peers))
	logger.Debugf("Choosing peer at index %d", index)
	return peers[index], nil
}
92915
func (a *APIDefinition) RandomGenerator() *RandomGenerator {
	if a.rand == nil {
		a.rand = NewRandomGenerator(a.Name)
	}
	return a.rand
}
878508
func (r *RiskServiceCalculationResult) GetProbabilityDecimalOrScore() *float64 {
	if r.ProbabilityDecimal != nil {
		return r.ProbabilityDecimal
	} else if r.Score != nil {
		f := float64(*r.Score)
		return &f
	}
	return nil
}
762929
func Slot(key string) int {
	if key == "" {
		return RandomSlot()
	}
	key = Key(key)
	return int(crc16sum(key)) % slotNumber
}
71598
func RandModOrder(rng *amcl.RAND) *FP256BN.BIG {
	// curve order q
	q := FP256BN.NewBIGints(FP256BN.CURVE_Order)

	// Take random element in Zq
	return FP256BN.Randomnum(q, rng)
}
1210389
func Random() Balancer {
	logger.Debugf("Creating Random balancer")
	return func(peers []fab.Peer) []fab.Peer {
		logger.Debugf("Load balancing %d peers using Random strategy...", len(peers))

		balancedPeers := make([]fab.Peer, len(peers))
		for i, index := range rand.Perm(len(peers)) {
			balancedPeers[i] = peers[index]
		}
		return balancedPeers
	}
}
948465
func (bi *bucketInternal) GetRandom(valuePtr interface{}) (string, Cas, error) {
	return bi.b.getRandom(valuePtr)
}
1317786
func randomInprocEndpoint() (string, error) {
	rnd := make([]byte, 10)
	if _, err := rand.Read(rnd); err != nil {
		return "", err
	}
	return "inproc://rnd" + string(rnd), nil
}
560840
func (a Address) Locality() string {
	var locality string

	if a.City != "" {
		locality = a.City
	} else if a.Town != "" {
		locality = a.Town
	} else if a.Village != "" {
		locality = a.Village
	}

	return locality
}
243777
func (e *Endpoint) GetValidAddress() (WeightedAddress, bool) {
	for i := 0; i < len(e.Addresses); i++ {
		we := e.Addresses[i]

		if we.HasExpired() {
			e.Addresses = append(e.Addresses[:i], e.Addresses[i+1:]...)
			i--
			continue
		}

		return we, true
	}

	return WeightedAddress{}, false
}