// updateMaxRate recalculates the current max rate and updates all
// threadThrottlers accordingly.
// The rate changes when the number of thread changes or a module updated its
// max rate.
10129
func (t *Throttler) updateMaxRate() {
	// Set it to infinite initially.
	maxRate := int64(math.MaxInt64)

	// Find out the new max rate (minimum among all modules).
	for _, m := range t.modules {
		if moduleMaxRate := m.MaxRate(); moduleMaxRate < maxRate {
			maxRate = moduleMaxRate
		}
	}

	// Set the new max rate on each thread.
	t.mu.Lock()
	defer t.mu.Unlock()
	threadsRunning := len(t.runningThreads)
	if threadsRunning == 0 {
		// Throttler is done. Set rates don't matter anymore.
		return
	}

	if maxRate != ZeroRateNoProgess && maxRate < int64(threadsRunning) {
		log.Warningf("Set maxRate is less than the number of threads (%v). To prevent threads from starving, maxRate was increased from: %v to: %v.", threadsRunning, maxRate, threadsRunning)
		maxRate = int64(threadsRunning)
	}
	maxRatePerThread := maxRate / int64(threadsRunning)
	// Distribute the remainder of the division across all threads.
	remainder := maxRate % int64(threadsRunning)
	remainderPerThread := make(map[int]int64, threadsRunning)
	for id := 0; remainder > 0; {
		remainderPerThread[id]++
		remainder--
		id++
	}

	for threadID := range t.runningThreads {
		t.threadThrottlers[threadID].setMaxRate(maxRatePerThread + remainderPerThread[threadID])
	}
	t.threadRunningsLastUpdate = threadsRunning
}
1031478
func (s *UpdateFlowSourceInput) SetMaxLatency(v int64) *UpdateFlowSourceInput {
	s.MaxLatency = &v
	return s
}
369455
func (soc *Socket) SetRate(value int64) error {
	return soc.setInt64(C.ZMQ_RATE, value)
}
612140
func (s *ThrottleSettings) SetRateLimit(v float64) *ThrottleSettings {
	s.RateLimit = &v
	return s
}
283710
func (c *Client) SetMaxRetries(retries int) {
	c.modifyLock.RLock()
	c.config.modifyLock.Lock()
	defer c.config.modifyLock.Unlock()
	c.modifyLock.RUnlock()

	c.config.MaxRetries = retries
}
759670
func (s *MaintenanceWindowTask) SetMaxConcurrency(v string) *MaintenanceWindowTask {
	s.MaxConcurrency = &v
	return s
}
341251
func (p *PerKeyThroughput) updateMaps() {
	// make a local copy of the sample counters for calculation
	p.lock.Lock()
	tmpCounts := p.currentCounts
	p.currentCounts = make(map[string]int)
	p.lock.Unlock()
	// short circuit if no traffic
	numKeys := len(tmpCounts)
	if numKeys == 0 {
		// no traffic the last 30s. clear the result map
		p.lock.Lock()
		defer p.lock.Unlock()
		p.savedSampleRates = make(map[string]int)
		return
	}
	actualPerKeyRate := p.PerKeyThroughputPerSec * p.ClearFrequencySec
	// for each key, calculate sample rate by dividing counted events by the
	// desired number of events
	newSavedSampleRates := make(map[string]int)
	for k, v := range tmpCounts {
		rate := int(math.Max(1, (float64(v) / float64(actualPerKeyRate))))
		newSavedSampleRates[k] = rate
	}
	// save newly calculated sample rates
	p.lock.Lock()
	defer p.lock.Unlock()
	p.savedSampleRates = newSavedSampleRates
}
1006942
func (ct *costTracker) updateStats(code, amount, servingTime, realCost uint64) {
	avg := reqAvgTimeCost[code]
	avgTime := avg.baseCost + amount*avg.reqCost
	select {
	case ct.gfUpdateCh <- gfUpdate{float64(avgTime), float64(servingTime)}:
	default:
	}
	if makeCostStats {
		realCost <<= 4
		l := 0
		for l < 9 && realCost > avgTime {
			l++
			realCost >>= 1
		}
		atomic.AddUint64(&ct.stats[code][l], 1)
	}
}
705533
func (opts *Options) SetRateLimitDelayMaxMilliseconds(value uint) {
	C.rocksdb_options_set_rate_limit_delay_max_milliseconds(opts.c, C.uint(value))
}
51533
func (r *Response) RateLimit() int {
	value, _ := strconv.Atoi(r.HttpResponse.Header.Get("X-RateLimit-Limit"))
	return value
}
391343
func (s *ListOfferingsInput) SetMaximumFramerate(v string) *ListOfferingsInput {
	s.MaximumFramerate = &v
	return s
}
533261
func (s *H264QvbrSettings) SetMaxAverageBitrate(v int64) *H264QvbrSettings {
	s.MaxAverageBitrate = &v
	return s
}
1119422
func (s *UpdateRateBasedRuleInput) SetRateLimit(v int64) *UpdateRateBasedRuleInput {
	s.RateLimit = &v
	return s
}
694422
func (s *StringCodeGenerator) Feedrate(feedrate float64) {
	s.put(fmt.Sprintf("F%s", floatToString(feedrate, s.Precision)))
}
576931
func (dl *downloader) rateLimit(ctx context.Context, f func() error) error {
	const (
		msgRateLimitExceeded          = "Rate Limit Exceeded"
		msgUserRateLimitExceeded      = "User Rate Limit Exceeded"
		msgUserRateLimitExceededShort = "userRateLimitExceeded"
	)

	// Ensure a 1 minute try limit.
	ctx, cancel := context.WithTimeout(ctx, time.Minute)
	defer cancel()
	for {
		if err := dl.rate.Wait(ctx); err != nil {
			log.Printf("gphotos: rate limit failure: %v", err)
			return err
		}
		err := f()
		if err == nil {
			return nil
		}
		ge, ok := err.(*googleapi.Error)
		if !ok || ge.Code != 403 {
			return err
		}
		if ge.Message == "" {
			var ok bool
			for _, e := range ge.Errors {
				if ok = e.Reason == msgUserRateLimitExceededShort; ok {
					break
				}
			}
			// For some cases, googleapi does not parse the returned JSON
			// properly, so we have to fall back to check the original text.
			//
			// Usually this is a "User Rate Limit Exceeded", but that's
			// also a "Rate Limit Exceeded", and we're interested just in the
			// fact, not the cause.
			if !ok && !strings.Contains(ge.Body, msgRateLimitExceeded) {
				return err
			}
		}
		// Some arbitrary sleep.
		log.Printf("gphotos: sleeping for 5s after 403 error, presumably due to a rate limit")
		time.Sleep(5 * time.Second)
		log.Printf("gphotos: retrying after sleep...")
	}
}
407656
func (s *ListOfferingsInput) SetMaximumBitrate(v string) *ListOfferingsInput {
	s.MaximumBitrate = &v
	return s
}
416698
func (r *Response) RateLimitReset() time.Time {
	value, _ := strconv.ParseInt(r.HttpResponse.Header.Get("X-RateLimit-Reset"), 10, 64)
	return time.Unix(value, 0)
}