// WKurtosisMean calculates the kurtosis of a dataset
492070
func WKurtosisMeanSd(w, data Interface, wmean, wsd float64) float64 {

	var wavg, W float64
	Len := data.Len()

	for i := 0; i < Len; i++ {
		wi := w.Get(i)

		if wi > 0 {
			x := (data.Get(i) - wmean) / wsd
			W += wi
			wavg += (x*x*x*x - wavg) * (wi / W)
		}
	}

	return wavg - 3.0 // makes kurtosis zero for a Gaussian
}
886190
func NewBatchedThrottler(maxWorkers, batchingTotal, batchSize int) *Throttler {
	totalJobs := int(math.Ceil(float64(batchingTotal) / float64(batchSize)))
	t := New(maxWorkers, totalJobs)
	t.batchSize = int32(batchSize)
	t.batchingTotal = int32(batchingTotal)
	return t
}
911260
func WKT(input string) interface{} {
	parts := strings.SplitN(input, " ", 2)
	name := parts[0]
	predicate := parseWKTPredicate(parts[1])

	switch name {
	case "POINT":
		if coords, ok := predicate.([]float64); ok {
			return NewPoint(coords)
		}
		return NewPoint(nil)
	case "POLYGON":
		if coords, ok := predicate.([][][]float64); ok {
			return NewPolygon(coords)
		}
		return NewPolygon(nil)
	case "LINESTRING":
		if coords, ok := predicate.([][]float64); ok {
			return NewLineString(coords)
		}
		return NewLineString(nil)
	case "MULTIPOINT":
		switch mpp := predicate.(type) {
		case [][]float64:
			return NewMultiPoint(mpp)
		default:
			fmt.Printf("%T\n", mpp)
			return NewMultiPoint(nil)
		}
	}
	return nil
}
460007
func CalculateLoRaPreambleDuration(symbolDuration time.Duration, preambleNumber int) time.Duration {
	return time.Duration((100*preambleNumber)+425) * symbolDuration / 100
}
187179
func (e *Engine) deleteMeasurement(name []byte) error {
	// Attempt to find the series keys.
	itr, err := e.index.MeasurementSeriesIDIterator(name)
	if err != nil {
		return err
	} else if itr == nil {
		return nil
	}
	defer itr.Close()
	return e.DeleteSeriesRange(tsdb.NewSeriesIteratorAdapter(e.sfile, itr), math.MinInt64, math.MaxInt64)
}
622053
func (fs *Datastore) calculateDiskUsage() error {
	// Try to obtain a previously stored value from disk
	if persDu := fs.readDiskUsageFile(); persDu > 0 {
		fs.diskUsage = persDu
		return nil
	}

	msgDone := make(chan struct{}, 1) // prevent race condition
	msgTimer := time.AfterFunc(diskUsageMessageTimeout, func() {
		fmt.Printf("Calculating datastore size. This might take %s at most and will happen only once\n",
			DiskUsageCalcTimeout.String())
		msgDone <- struct{}{}
	})
	defer msgTimer.Stop()
	deadline := time.Now().Add(DiskUsageCalcTimeout)
	du, accuracy, err := folderSize(fs.path, deadline)
	if err != nil {
		return err
	}
	if !msgTimer.Stop() {
		<-msgDone
	}
	if accuracy == timedoutA {
		fmt.Println("WARN: It took to long to calculate the datastore size")
		fmt.Printf("WARN: The total size (%d) is an estimation. You can fix errors by\n", du)
		fmt.Printf("WARN: replacing the %s file with the right disk usage in bytes and\n",
			filepath.Join(fs.path, DiskUsageFile))
		fmt.Println("WARN: re-opening the datastore")
	}

	fs.storedValue.Accuracy = accuracy
	fs.diskUsage = du
	fs.writeDiskUsageFile(du, true)

	return nil
}
1293711
func (k *Kernel) Normalized() Matrix {
	sum := k.Absum()
	w := k.Width
	h := k.Height
	nk := NewKernel(w, h)

	// avoid division by 0
	if sum == 0 {
		sum = 1
	}

	for i := 0; i < w*h; i++ {
		nk.Matrix[i] = k.Matrix[i] / sum
	}

	return nk
}
180466
func (h *Histogram) ApproxMean() float64 {
	if h.useLocks {
		h.mutex.RLock()
		defer h.mutex.RUnlock()
	}
	divisor := 0.0
	sum := 0.0
	for i := uint16(0); i < h.used; i++ {
		midpoint := h.bvs[i].midpoint()
		cardinality := float64(h.bvs[i].count)
		divisor += cardinality
		sum += midpoint * cardinality
	}
	if divisor == 0.0 {
		return math.NaN()
	}
	return sum / divisor
}
45663
func (user *User) NumericWhitelist() []uint64 {
	var whitelist []uint64
	Db().Model(Whitelist{}).Where(Whitelist{From: user.ID()}).Pluck(`"to"`, &whitelist)
	return append(whitelist, user.ID())
}
614100
func GetSummary(c ConfusionMatrix) string {
	var buffer bytes.Buffer
	w := new(tabwriter.Writer)
	w.Init(&buffer, 0, 8, 0, '\t', 0)

	fmt.Fprintln(w, "Reference Class\tTrue Positives\tFalse Positives\tTrue Negatives\tPrecision\tRecall\tF1 Score")
	fmt.Fprintln(w, "---------------\t--------------\t---------------\t--------------\t---------\t------\t--------")
	for k := range c {
		tp := GetTruePositives(k, c)
		fp := GetFalsePositives(k, c)
		tn := GetTrueNegatives(k, c)
		prec := GetPrecision(k, c)
		rec := GetRecall(k, c)
		f1 := GetF1Score(k, c)

		fmt.Fprintf(w, "%s\t%.0f\t%.0f\t%.0f\t%.4f\t%.4f\t%.4f\n", k, tp, fp, tn, prec, rec, f1)
	}
	w.Flush()
	buffer.WriteString(fmt.Sprintf("Overall accuracy: %.4f\n", GetAccuracy(c)))

	return buffer.String()
}
1122303
func average(name string, fun func(), benchSize int) {
	numThreads := runtime.GOMAXPROCS(-1)
	wp := new(sync.WaitGroup)
	iter := float64(benchSize)
	start := float64(time.Now().UTC().UnixNano())
	// Run function across multiple goroutines
	for i := 0; i < benchSize; i += benchSize / numThreads {
		wp.Add(1)
		go func() {
			defer wp.Done()
			for j := 0; j < benchSize/numThreads; j++ {
				fun()
			}
		}()
	}
	wp.Wait()
	end := float64(time.Now().UTC().UnixNano())
	fmt.Printf("%s %d: %d ns/iter, %d iter/sec\n", name, int(benchSize), int((end-start)/iter), int(1000000000/((end-start)/iter)))
}
1260542
func Wma(inReal []float64, inTimePeriod int) []float64 {

	outReal := make([]float64, len(inReal))

	lookbackTotal := inTimePeriod - 1
	startIdx := lookbackTotal

	if inTimePeriod == 1 {
		copy(outReal, inReal)
		return outReal
	}
	divider := (inTimePeriod * (inTimePeriod + 1)) >> 1
	outIdx := inTimePeriod - 1
	trailingIdx := startIdx - lookbackTotal
	periodSum, periodSub := 0.0, 0.0
	inIdx := trailingIdx
	i := 1
	for inIdx < startIdx {
		tempReal := inReal[inIdx]
		periodSub += tempReal
		periodSum += tempReal * float64(i)
		inIdx++
		i++
	}
	trailingValue := 0.0
	for inIdx < len(inReal) {
		tempReal := inReal[inIdx]
		periodSub += tempReal
		periodSub -= trailingValue
		periodSum += tempReal * float64(inTimePeriod)
		trailingValue = inReal[trailingIdx]
		outReal[outIdx] = periodSum / float64(divider)
		periodSum -= periodSub
		inIdx++
		trailingIdx++
		outIdx++
	}
	return outReal
}
1078597
func (m *StandardMeter) RateMean() float64 {
	m.lock.RLock()
	rateMean := m.snapshot.rateMean
	m.lock.RUnlock()
	return rateMean
}
550401
func (k *KNN) UpdateTrainingSet(trainingSet [][]float64, expectedResults []float64) error {
	if len(trainingSet) == 0 || len(expectedResults) == 0 {
		return fmt.Errorf("Error: length of given data is 0! Need data!")
	}
	if len(trainingSet) != len(expectedResults) {
		return fmt.Errorf("Datasets given do not match in length")
	}

	k.trainingSet = trainingSet
	k.expectedResults = expectedResults

	return nil
}
1048312
func shrunkCovariance(X *mat.Dense) *mat.SymDense {
	n_obs, n_feats := X.Dims()
	size := int(math.Pow(float64(n_feats), 2))
	covs := mat.NewSymDense(n_feats, make([]float64, size, size))
	for j := 0; j < n_feats; j++ {
		// compute the variance for the jth feature
		var points []float64
		for i := 0; i < n_obs; i++ {
			points = append(points, X.At(i, j))
		}
		variance := stat.Variance(points, nil)
		// set the jth diagonal entry to the variance
		covs.SetSym(j, j, variance)
	}
	return covs
}
1221602
func WTssMean(w, data Interface, wmean float64) (res float64) {

	// find the sum of the squares
	n := data.Len()
	for i := 0; i < n; i++ {
		wi := w.Get(i)

		if wi > 0 {
			delta := data.Get(i) - wmean
			res += wi * delta * delta
		}
	}

	return
}
605262
func mean(matrix *mat.Dense) *mat.Dense {
	rows, cols := matrix.Dims()
	meanVector := make([]float64, cols)
	for i := 0; i < cols; i++ {
		sum := mat.Sum(matrix.ColView(i))
		meanVector[i] = sum / float64(rows)
	}
	return mat.NewDense(1, cols, meanVector)
}