// AddTimeSample adds a time sample that is used when determining the median
// time of the added samples.
//
// This function is safe for concurrent access and is part of the
// MedianTimeSource interface implementation.
774673
func (m *medianTime) AddTimeSample(sourceID string, timeVal time.Time) {
	m.mtx.Lock()
	defer m.mtx.Unlock()

	// Don't add time data from the same source.
	if _, exists := m.knownIDs[sourceID]; exists {
		return
	}
	m.knownIDs[sourceID] = struct{}{}

	// Truncate the provided offset to seconds and append it to the slice
	// of offsets while respecting the maximum number of allowed entries by
	// replacing the oldest entry with the new entry once the maximum number
	// of entries is reached.
	now := time.Unix(time.Now().Unix(), 0)
	offsetSecs := int64(timeVal.Sub(now).Seconds())
	numOffsets := len(m.offsets)
	if numOffsets == maxMedianTimeEntries && maxMedianTimeEntries > 0 {
		m.offsets = m.offsets[1:]
		numOffsets--
	}
	m.offsets = append(m.offsets, offsetSecs)
	numOffsets++

	// Sort the offsets so the median can be obtained as needed later.
	sortedOffsets := make([]int64, numOffsets)
	copy(sortedOffsets, m.offsets)
	sort.Sort(int64Sorter(sortedOffsets))

	offsetDuration := time.Duration(offsetSecs) * time.Second
	log.Debugf("Added time sample of %v (total: %v)", offsetDuration,
		numOffsets)

	// NOTE: The following code intentionally has a bug to mirror the
	// buggy behavior in Bitcoin Core since the median time is used in the
	// consensus rules.
	//
	// In particular, the offset is only updated when the number of entries
	// is odd, but the max number of entries is 200, an even number.  Thus,
	// the offset will never be updated again once the max number of entries
	// is reached.

	// The median offset is only updated when there are enough offsets and
	// the number of offsets is odd so the middle value is the true median.
	// Thus, there is nothing to do when those conditions are not met.
	if numOffsets < 5 || numOffsets&0x01 != 1 {
		return
	}

	// At this point the number of offsets in the list is odd, so the
	// middle value of the sorted offsets is the median.
	median := sortedOffsets[numOffsets/2]

	// Set the new offset when the median offset is within the allowed
	// offset range.
	if math.Abs(float64(median)) < maxAllowedOffsetSecs {
		m.offsetSecs = median
	} else {
		// The median offset of all added time data is larger than the
		// maximum allowed offset, so don't use an offset.  This
		// effectively limits how far the local clock can be skewed.
		m.offsetSecs = 0

		if !m.invalidTimeChecked {
			m.invalidTimeChecked = true

			// Find if any time samples have a time that is close
			// to the local time.
			var remoteHasCloseTime bool
			for _, offset := range sortedOffsets {
				if math.Abs(float64(offset)) < similarTimeSecs {
					remoteHasCloseTime = true
					break
				}
			}

			// Warn if none of the time samples are close.
			if !remoteHasCloseTime {
				log.Warnf("Please check your date and time " +
					"are correct!  btcd will not work " +
					"properly with an invalid time")
			}
		}
	}

	medianDuration := time.Duration(m.offsetSecs) * time.Second
	log.Debugf("New time offset: %v", medianDuration)
}
726187
func TimestampLess(i *timestamp.Timestamp, j *timestamp.Timestamp) bool {
	if j == nil {
		return false
	}
	if i == nil {
		return true
	}
	if i.Seconds < j.Seconds {
		return true
	}
	if i.Seconds > j.Seconds {
		return false
	}
	return i.Nanos < j.Nanos
}
1001249
func (a *AzureMonitor) Add(m telegraf.Metric) {
	// Azure Monitor only supports aggregates 30 minutes into the past and 4
	// minutes into the future. Future metrics are dropped when pushed.
	t := m.Time()
	tbucket := time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), 0, 0, t.Location())
	if tbucket.Before(a.timeFunc().Add(-time.Minute * 30)) {
		a.MetricOutsideWindow.Incr(1)
		return
	}

	// Azure Monitor doesn't have a string value type, so convert string fields
	// to dimensions (a.k.a. tags) if enabled.
	if a.StringsAsDimensions {
		for _, f := range m.FieldList() {
			if v, ok := f.Value.(string); ok {
				m.AddTag(f.Key, v)
			}
		}
	}

	for _, f := range m.FieldList() {
		fv, ok := convert(f.Value)
		if !ok {
			continue
		}

		// Azure Monitor does not support fields so the field name is appended
		// to the metric name.
		name := m.Name() + "-" + sanitize(f.Key)
		id := hashIDWithField(m.HashID(), f.Key)

		_, ok = a.cache[tbucket]
		if !ok {
			// Time bucket does not exist and needs to be created.
			a.cache[tbucket] = make(map[uint64]*aggregate)
		}

		// Fetch existing aggregate
		var agg *aggregate
		agg, ok = a.cache[tbucket][id]
		if !ok {
			agg := &aggregate{
				name:  name,
				min:   fv,
				max:   fv,
				sum:   fv,
				count: 1,
			}
			for _, tag := range m.TagList() {
				dim := dimension{
					name:  tag.Key,
					value: tag.Value,
				}
				agg.dimensions = append(agg.dimensions, dim)
			}
			agg.updated = true
			a.cache[tbucket][id] = agg
			continue
		}

		if fv < agg.min {
			agg.min = fv
		}
		if fv > agg.max {
			agg.max = fv
		}
		agg.sum += fv
		agg.count++
		agg.updated = true
	}
}
7406
func (dt DateTime) Add(duration time.Duration) DateTime {
	t := dt.t.Add(toSeconds(duration))
	return DateTime{t: t}
}
1268019
func (r *Timing) Add(duration time.Duration) {
	b := r.getCurrentBucket()

	r.Mutex.Lock()
	defer r.Mutex.Unlock()

	b.Durations = append(b.Durations, duration)
	r.removeOldBuckets()
}
41106
func (samplerOptions) SamplingRefreshInterval(samplingRefreshInterval time.Duration) SamplerOption {
	return func(o *samplerOptions) {
		o.samplingRefreshInterval = samplingRefreshInterval
	}
}
439611
func (b *bdpEstimator) timesnap(d [8]byte) {
	if bdpPing.data != d {
		return
	}
	b.sentAt = time.Now()
}
605128
func (b *BatchBuilder) Timestamp(t time.Time) *BatchBuilder {
	b.using.Timestamp(t)
	return b
}
938944
func (d *Distribution) Add(sample float64) {
	i := d.b.Bucket(sample)
	if i >= len(d.buckets) {
		d.buckets = append(d.buckets, make([]int64, i-len(d.buckets)+1)...)
	}
	d.buckets[i]++
	d.sum += sample
	d.count++
	if i > d.lastNonZeroBucket {
		d.lastNonZeroBucket = i
	}
}
161015
func CreateTimestamp(time_point []string) Timestamp {
	year, _ := strconv.Atoi(time_point[0])
	month, _ := strconv.Atoi(time_point[1])
	day, _ := strconv.Atoi(time_point[2])
	hour, _ := strconv.Atoi(time_point[3])
	min, _ := strconv.Atoi(time_point[4])
	sec, milliSec, microSec, nanoSec, picoSec := secondFragments(time_point[5])

	return Timestamp{
		Year:     year,
		Month:    month,
		Day:      day,
		Hour:     hour,
		Min:      min,
		Sec:      sec,
		MilliSec: milliSec,
		MicroSec: microSec,
		NanoSec:  nanoSec,
		PicoSec:  picoSec,
	}
}
201204
func Timing(name string, value time.Duration, resolution time.Duration, tags map[string]string, opts ...SampleOption) *SSFSample {
	time := float32(value / resolution)
	return Histogram(name, time, tags, append(opts, TimeUnit(resolution))...)
}
1052714
func (v *Value) ToTimestamp() (t time.Time, ok bool) {
	switch v.vType {
	case typeTimestamp:
		return v.value.(time.Time), true
	}
	return t, false
}
706477
func (e Encoder) AppendTime(dst []byte, t time.Time, unused string) []byte {
	utc := t.UTC()
	if utc.Nanosecond() == 0 {
		return appendIntegerTimestamp(dst, utc)
	}
	return e.appendFloatTimestamp(dst, utc)
}
104597
func (t *Timedelta) Add(t2 *Timedelta) Timedelta {
	return Timedelta{
		Days:         t.Days + t2.Days,
		Seconds:      t.Seconds + t2.Seconds,
		Microseconds: t.Microseconds + t2.Microseconds,
		Milliseconds: t.Milliseconds + t2.Milliseconds,
		Minutes:      t.Minutes + t2.Minutes,
		Hours:        t.Hours + t2.Hours,
		Weeks:        t.Weeks + t2.Weeks,
	}
}
1094576
func Timestamp(t time.Time) *timestamp.Timestamp {
	return &timestamp.Timestamp{
		Seconds: t.Unix(),
		Nanos:   int32(t.Nanosecond()),
	}
}
60109
func localTimeTooltip(innerText string, ifZero string, t time.Time) template.HTML {
	return localTimeCommon(ifZero, t, "tooltip-only", innerText)
}
236858
func AddTime(ctx context.Context, now time.Time) context.Context {
	return context.WithValue(ctx, requestTime, now)
}