// AggregateWithSeedT is the typed version of AggregateWithSeed.
//
//   - f is of type "func(TAccumulate, TSource) TAccumulate"
//
// NOTE: AggregateWithSeed has better performance than
// AggregateWithSeedT.
351359
func (q Query) AggregateWithSeedT(seed interface{},
	f interface{}) interface{} {
	fGenericFunc, err := newGenericFunc(
		"AggregateWithSeed", "f", f,
		simpleParamValidator(newElemTypeSlice(new(genericType), new(genericType)), newElemTypeSlice(new(genericType))),
	)
	if err != nil {
		panic(err)
	}

	fFunc := func(result interface{}, current interface{}) interface{} {
		return fGenericFunc.Call(result, current)
	}

	return q.AggregateWithSeed(seed, fFunc)
}
903837
func (a *CompositeAggregation) Source() (interface{}, error) {
	// Example:
	// {
	//     "aggs" : {
	//         "my_composite_agg" : {
	//             "composite" : {
	//                 "sources": [
	//				      {"my_term": { "terms": { "field": "product" }}},
	//				      {"my_histo": { "histogram": { "field": "price", "interval": 5 }}},
	//				      {"my_date": { "date_histogram": { "field": "timestamp", "interval": "1d" }}},
	//                 ],
	//                 "size" : 10,
	//                 "after" : ["a", 2, "c"]
	//             }
	//         }
	//     }
	// }
	//
	// This method returns only the { "histogram" : { ... } } part.

	source := make(map[string]interface{})
	opts := make(map[string]interface{})
	source["composite"] = opts

	sources := make([]interface{}, len(a.sources))
	for i, s := range a.sources {
		src, err := s.Source()
		if err != nil {
			return nil, err
		}
		sources[i] = src
	}
	opts["sources"] = sources

	if a.size != nil {
		opts["size"] = *a.size
	}

	if a.after != nil {
		opts["after"] = a.after
	}

	// AggregationBuilder (SubAggregations)
	if len(a.subAggregations) > 0 {
		aggsMap := make(map[string]interface{})
		source["aggregations"] = aggsMap
		for name, aggregate := range a.subAggregations {
			src, err := aggregate.Source()
			if err != nil {
				return nil, err
			}
			aggsMap[name] = src
		}
	}

	// Add Meta data if available
	if len(a.meta) > 0 {
		source["meta"] = a.meta
	}

	return source, nil
}
247378
func AggregateGoroutines(funcs ...func() error) Aggregate {
	errChan := make(chan error, len(funcs))
	for _, f := range funcs {
		go func(f func() error) { errChan <- f() }(f)
	}
	errs := make([]error, 0)
	for i := 0; i < cap(errChan); i++ {
		if err := <-errChan; err != nil {
			errs = append(errs, err)
		}
	}
	return NewAggregate(errs)
}
1277678
func (a *AggFuncDesc) GetAggFunc(ctx sessionctx.Context) Aggregation {
	aggFunc := aggFunction{AggFuncDesc: a}
	switch a.Name {
	case ast.AggFuncSum:
		return &sumFunction{aggFunction: aggFunc}
	case ast.AggFuncCount:
		return &countFunction{aggFunction: aggFunc}
	case ast.AggFuncAvg:
		return &avgFunction{aggFunction: aggFunc}
	case ast.AggFuncGroupConcat:
		var s string
		var err error
		var maxLen uint64
		s, err = variable.GetSessionSystemVar(ctx.GetSessionVars(), variable.GroupConcatMaxLen)
		if err != nil {
			panic(fmt.Sprintf("Error happened when GetAggFunc: no system variable named '%s'", variable.GroupConcatMaxLen))
		}
		maxLen, err = strconv.ParseUint(s, 10, 64)
		if err != nil {
			panic(fmt.Sprintf("Error happened when GetAggFunc: illegal value for system variable named '%s'", variable.GroupConcatMaxLen))
		}
		return &concatFunction{aggFunction: aggFunc, maxLen: maxLen}
	case ast.AggFuncMax:
		return &maxMinFunction{aggFunction: aggFunc, isMax: true}
	case ast.AggFuncMin:
		return &maxMinFunction{aggFunction: aggFunc, isMax: false}
	case ast.AggFuncFirstRow:
		return &firstRowFunction{aggFunction: aggFunc}
	case ast.AggFuncBitOr:
		return &bitOrFunction{aggFunction: aggFunc}
	case ast.AggFuncBitXor:
		return &bitXorFunction{aggFunction: aggFunc}
	case ast.AggFuncBitAnd:
		return &bitAndFunction{aggFunction: aggFunc}
	default:
		panic("unsupported agg function")
	}
}
809001
func AggMax(cols ...string) Aggregator {
	max := func(xs []float64) float64 {
		_, x := stats.Bounds(xs)
		return x
	}
	return aggFn(max, "max ", cols...)
}
915945
func (t *Table) groupRangeReduce(i, j int, alias map[string]string, acc map[string]Accumulator) (Row, error) {
	t.mu.Lock()
	defer t.mu.Unlock()
	if i > j {
		return nil, fmt.Errorf("cannot aggregate empty ranges [%d, %d)", i, j)
	}
	// Initialize the range and accumulator results.
	rng := t.Data[i:j]
	vaccs := make(map[string]interface{})
	// Reset the accumulators.
	for _, a := range acc {
		a.Reset()
	}
	// Aggregate the range using the provided aggregators.
	for _, r := range rng {
		for b, a := range acc {
			av, err := a.Accumulate(r[b])
			if err != nil {
				return nil, err
			}
			vaccs[b] = av
		}
	}
	// Create a new row based on the resulting aggregations with the proper
	// binding aliasing and the non aggregated values.
	newRow := Row{}
	for b, v := range rng[0] {
		acc, ok := vaccs[b]
		if !ok {
			if a, ok := alias[b]; ok {
				newRow[a] = v
			} else {
				newRow[b] = v
			}
		} else {
			a, ok := alias[b]
			if !ok {
				return nil, fmt.Errorf("aggregated bindings require and alias; binding %s missing alias", b)
			}
			// Accumulators currently only can return numeric literals.
			switch acc.(type) {
			case int64:
				l, err := literal.DefaultBuilder().Build(literal.Int64, acc)
				if err != nil {
					return nil, err
				}
				newRow[a] = &Cell{L: l}
			case float64:
				l, err := literal.DefaultBuilder().Build(literal.Float64, acc)
				if err != nil {
					return nil, err
				}
				newRow[a] = &Cell{L: l}
			default:
				return nil, fmt.Errorf("aggregation of binding %s returned unknown value %v or type", b, acc)
			}
		}
	}
	return newRow, nil
}
1025514
func AggMin(cols ...string) Aggregator {
	min := func(xs []float64) float64 {
		x, _ := stats.Bounds(xs)
		return x
	}
	return aggFn(min, "min ", cols...)
}
202839
func (query Query) MustAggregate(mode string, field string, out interface{}) {
	must(query.Aggregate(mode, field, out))
}
1029633
func (e *hashAggExec) aggregate(value [][]byte) error {
	err := e.evalCtx.decodeRelatedColumnVals(e.relatedColOffsets, value, e.row)
	if err != nil {
		return errors.Trace(err)
	}
	// Get group key.
	gk, gbyKeyRow, err := e.getGroupKey()
	if err != nil {
		return errors.Trace(err)
	}
	if _, ok := e.groups[string(gk)]; !ok {
		e.groups[string(gk)] = struct{}{}
		e.groupKeys = append(e.groupKeys, gk)
		e.groupKeyRows = append(e.groupKeyRows, gbyKeyRow)
	}
	// Update aggregate expressions.
	aggCtxs := e.getContexts(gk)
	for i, agg := range e.aggExprs {
		err = agg.Update(aggCtxs[i], e.evalCtx.sc, chunk.MutRowFromDatums(e.row).ToRow())
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}
1218705
func (a *AggregateStatsRequest) ReadFrom(r io.Reader) (int64, error) {
	return encoding.ReadFrom(r, &a.Table, &defaultPad3,
		&a.OutPort, &a.OutGroup, &defaultPad4, &a.Cookie,
		&a.CookieMask, &a.Match)
}
268441
func (o *VPort) AggregateMetadatas(info *bambou.FetchingInfo) (AggregateMetadatasList, *bambou.Error) {

	var list AggregateMetadatasList
	err := bambou.CurrentSession().FetchChildren(o, AggregateMetadataIdentity, &list, info)
	return list, err
}
1152843
func (m *Accumulator) PushWithf(fmtstr string, err error, args ...interface{}) {
	if err != nil {
		m.Pushf(fmtstr, append([]interface{}{err}, args...)...)
	}
}
454104
func (a *FiltersAggregation) Source() (interface{}, error) {
	// Example:
	//	{
	//  "aggs" : {
	//    "messages" : {
	//      "filters" : {
	//        "filters" : {
	//          "errors" :   { "term" : { "body" : "error"   }},
	//          "warnings" : { "term" : { "body" : "warning" }}
	//        }
	//      }
	//    }
	//  }
	//	}
	// This method returns only the (outer) { "filters" : {} } part.

	source := make(map[string]interface{})
	filters := make(map[string]interface{})
	source["filters"] = filters

	if len(a.unnamedFilters) > 0 && len(a.namedFilters) > 0 {
		return nil, errors.New("elastic: use either named or unnamed filters with FiltersAggregation but not both")
	}

	if len(a.unnamedFilters) > 0 {
		arr := make([]interface{}, len(a.unnamedFilters))
		for i, filter := range a.unnamedFilters {
			src, err := filter.Source()
			if err != nil {
				return nil, err
			}
			arr[i] = src
		}
		filters["filters"] = arr
	} else {
		dict := make(map[string]interface{})
		for key, filter := range a.namedFilters {
			src, err := filter.Source()
			if err != nil {
				return nil, err
			}
			dict[key] = src
		}
		filters["filters"] = dict
	}

	// AggregationBuilder (SubAggregations)
	if len(a.subAggregations) > 0 {
		aggsMap := make(map[string]interface{})
		source["aggregations"] = aggsMap
		for name, aggregate := range a.subAggregations {
			src, err := aggregate.Source()
			if err != nil {
				return nil, err
			}
			aggsMap[name] = src
		}
	}

	// Add Meta data if available
	if len(a.meta) > 0 {
		source["meta"] = a.meta
	}

	return source, nil
}
702159
func withFallbacks(v Value, vFallback Value) Value {
	vAttr := v.attributesWithValues()
	fbAttr := vFallback.attributesWithValues()
	for k, v := range fbAttr {
		if _, ok := vAttr[k]; !ok {
			vAttr[k] = v
		}
	}
	return fromAttributes(vAttr)
}
8122
func (i *Image) WithDigest(digest digest.Digest) (err error) {
	i.Digest = digest
	i.named, err = reference.WithDigest(i.named, digest)
	return err
}
504508
func NewAggregate(errs ...error) error {
	// filter out possible nil values
	var nonNils []error
	for _, err := range errs {
		if err != nil {
			nonNils = append(nonNils, err)
		}
	}
	if len(nonNils) == 0 {
		return nil
	}
	return wrapWithDepth(aggregate(nonNils), 2)
}
683595
func (s *Sensu) GetAggregateIssued(check string, issued string, summarize bool, result bool) (map[string]interface{}, error) {
	// FIXME Aggregate Not handling summarize/result
	return s.get(fmt.Sprintf("aggregate/%s/%s", check, issued))
}