// buildMaxMin builds the AggFunc implementation for function "MAX" and "MIN".
10553
func buildMaxMin(aggFuncDesc *aggregation.AggFuncDesc, ordinal int, isMax bool) AggFunc {
	base := baseMaxMinAggFunc{
		baseAggFunc: baseAggFunc{
			args:    aggFuncDesc.Args,
			ordinal: ordinal,
		},
		isMax: isMax,
	}

	evalType, fieldType := aggFuncDesc.RetTp.EvalType(), aggFuncDesc.RetTp
	if fieldType.Tp == mysql.TypeBit {
		evalType = types.ETString
	}
	switch aggFuncDesc.Mode {
	case aggregation.DedupMode:
	default:
		switch evalType {
		case types.ETInt:
			if mysql.HasUnsignedFlag(fieldType.Flag) {
				return &maxMin4Uint{base}
			}
			return &maxMin4Int{base}
		case types.ETReal:
			switch fieldType.Tp {
			case mysql.TypeFloat:
				return &maxMin4Float32{base}
			case mysql.TypeDouble:
				return &maxMin4Float64{base}
			}
		case types.ETDecimal:
			return &maxMin4Decimal{base}
		case types.ETString:
			return &maxMin4String{base}
		case types.ETDatetime, types.ETTimestamp:
			return &maxMin4Time{base}
		case types.ETDuration:
			return &maxMin4Duration{base}
		case types.ETJson:
			return &maxMin4JSON{base}
		}
	}
	return nil
}
1161350
func buildBitXor(aggFuncDesc *aggregation.AggFuncDesc, ordinal int) AggFunc {
	base := baseAggFunc{
		args:    aggFuncDesc.Args,
		ordinal: ordinal,
	}
	return &bitXorUint64{baseBitAggFunc{base}}
}
149775
func (b *boundedBuilder) Build(t Type, v interface{}) (*Literal, error) {
	switch v.(type) {
	case string:
		if l := len(v.(string)); l > b.max {
			return nil, fmt.Errorf("literal.Build: cannot create literal due to size of %v (%d>%d)", v, l, b.max)
		}
	case []byte:
		if l := len(v.([]byte)); l > b.max {
			return nil, fmt.Errorf("literal.Build: cannot create literal due to size of %v (%d>%d)", v, l, b.max)
		}
	}
	return defaultBuilder.Build(t, v)
}
773787
func Minmax(target uint32, internalformat uint32, sink bool) {
	C.glowMinmax(gpMinmax, (C.GLenum)(target), (C.GLenum)(internalformat), (C.GLboolean)(boolToInt(sink)))
}
1353526
func (fng *FakeNumberGenerator) RandomLineNumberMinMax(min, max uint16) uint16 {
	return uint16(fng.Rand.Intn(int(max)-int(min))) + min
}
504082
func interpolationFuncMin() ast.Function {
	return ast.Function{
		ArgTypes:     []ast.Type{ast.TypeFloat},
		ReturnType:   ast.TypeFloat,
		Variadic:     true,
		VariadicType: ast.TypeFloat,
		Callback: func(args []interface{}) (interface{}, error) {
			min := args[0].(float64)

			for i := 1; i < len(args); i++ {
				min = math.Min(min, args[i].(float64))
			}

			return min, nil
		},
	}
}
64074
func (a *maxMinEliminator) eliminateMaxMin(p LogicalPlan) {
	// We don't need to guarantee that the child of it is a data source. This transformation won't be worse than previous.
	if agg, ok := p.(*LogicalAggregation); ok {
		// We only consider case with single max/min function.
		if len(agg.AggFuncs) != 1 || len(agg.GroupByItems) != 0 {
			return
		}
		f := agg.AggFuncs[0]
		if f.Name != ast.AggFuncMax && f.Name != ast.AggFuncMin {
			return
		}

		child := p.Children()[0]
		ctx := p.context()

		// If there's no column in f.GetArgs()[0], we still need limit and read data from real table because the result should NULL if the below is empty.
		if len(expression.ExtractColumns(f.Args[0])) > 0 {
			// If it can be NULL, we need to filter NULL out first.
			if !mysql.HasNotNullFlag(f.Args[0].GetType().Flag) {
				sel := LogicalSelection{}.Init(ctx)
				isNullFunc := expression.NewFunctionInternal(ctx, ast.IsNull, types.NewFieldType(mysql.TypeTiny), f.Args[0])
				notNullFunc := expression.NewFunctionInternal(ctx, ast.UnaryNot, types.NewFieldType(mysql.TypeTiny), isNullFunc)
				sel.Conditions = []expression.Expression{notNullFunc}
				sel.SetChildren(p.Children()[0])
				child = sel
			}

			// Add Sort and Limit operators.
			// For max function, the sort order should be desc.
			desc := f.Name == ast.AggFuncMax
			// Compose Sort operator.
			sort := LogicalSort{}.Init(ctx)
			sort.ByItems = append(sort.ByItems, &ByItems{f.Args[0], desc})
			sort.SetChildren(child)
			child = sort
		}

		// Compose Limit operator.
		li := LogicalLimit{Count: 1}.Init(ctx)
		li.SetChildren(child)

		// If no data in the child, we need to return NULL instead of empty. This cannot be done by sort and limit themselves.
		// Since now it's almost one row returned, a agg operator is okay to do this.
		p.SetChildren(li)
		return
	}

	for _, child := range p.Children() {
		a.eliminateMaxMin(child)
	}
}
212773
func minmax(thread *Thread, fn *Builtin, args Tuple, kwargs []Tuple) (Value, error) {
	if len(args) == 0 {
		return nil, fmt.Errorf("%s requires at least one positional argument", fn.Name())
	}
	var keyFunc Callable
	if err := UnpackArgs(fn.Name(), nil, kwargs, "key?", &keyFunc); err != nil {
		return nil, err
	}
	var op syntax.Token
	if fn.Name() == "max" {
		op = syntax.GT
	} else {
		op = syntax.LT
	}
	var iterable Value
	if len(args) == 1 {
		iterable = args[0]
	} else {
		iterable = args
	}
	iter := Iterate(iterable)
	if iter == nil {
		return nil, fmt.Errorf("%s: %s value is not iterable", fn.Name(), iterable.Type())
	}
	defer iter.Done()
	var extremum Value
	if !iter.Next(&extremum) {
		return nil, fmt.Errorf("%s: argument is an empty sequence", fn.Name())
	}

	var extremeKey Value
	var keyargs Tuple
	if keyFunc == nil {
		extremeKey = extremum
	} else {
		keyargs = Tuple{extremum}
		res, err := Call(thread, keyFunc, keyargs, nil)
		if err != nil {
			return nil, err
		}
		extremeKey = res
	}

	var x Value
	for iter.Next(&x) {
		var key Value
		if keyFunc == nil {
			key = x
		} else {
			keyargs[0] = x
			res, err := Call(thread, keyFunc, keyargs, nil)
			if err != nil {
				return nil, err
			}
			key = res
		}

		if ok, err := Compare(op, key, extremeKey); err != nil {
			return nil, err
		} else if ok {
			extremum = x
			extremeKey = key
		}
	}
	return extremum, nil
}
876444
func vectorMin(v mat.Vector) float64 {
	n_obs, _ := v.Dims()
	min := v.At(0, 0)
	for i := 0; i < n_obs; i++ {
		if v.At(i, 0) < min {
			min = v.At(i, 0)
		}
	}
	return min
}
688258
func buildBitAnd(aggFuncDesc *aggregation.AggFuncDesc, ordinal int) AggFunc {
	base := baseAggFunc{
		args:    aggFuncDesc.Args,
		ordinal: ordinal,
	}
	return &bitAndUint64{baseBitAggFunc{base}}
}
1247618
func (q *BaseQueryBuilder) BuildLimit(limit int64, offset int64) string {
	if limit < 0 && offset > 0 {
		// most DBMS requires LIMIT when OFFSET is present
		limit = 9223372036854775807 // 2^63 - 1
	}

	sql := ""
	if limit >= 0 {
		sql = fmt.Sprintf("LIMIT %v", limit)
	}
	if offset <= 0 {
		return sql
	}
	if sql != "" {
		sql += " "
	}
	return sql + fmt.Sprintf("OFFSET %v", offset)
}
1298110
func (_m *API) BuildContent(ctx context.Context, scm source.Source, opts *types.BuildOptions) (io.ReadCloser, error) {
	ret := _m.Called(ctx, scm, opts)

	var r0 io.ReadCloser
	if rf, ok := ret.Get(0).(func(context.Context, source.Source, *types.BuildOptions) io.ReadCloser); ok {
		r0 = rf(ctx, scm, opts)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(io.ReadCloser)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(context.Context, source.Source, *types.BuildOptions) error); ok {
		r1 = rf(ctx, scm, opts)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
856917
func buildFirstRow(aggFuncDesc *aggregation.AggFuncDesc, ordinal int) AggFunc {
	base := baseAggFunc{
		args:    aggFuncDesc.Args,
		ordinal: ordinal,
	}

	evalType, fieldType := aggFuncDesc.RetTp.EvalType(), aggFuncDesc.RetTp
	if fieldType.Tp == mysql.TypeBit {
		evalType = types.ETString
	}
	switch aggFuncDesc.Mode {
	case aggregation.DedupMode:
	default:
		switch evalType {
		case types.ETInt:
			return &firstRow4Int{base}
		case types.ETReal:
			switch fieldType.Tp {
			case mysql.TypeFloat:
				return &firstRow4Float32{base}
			case mysql.TypeDouble:
				return &firstRow4Float64{base}
			}
		case types.ETDecimal:
			return &firstRow4Decimal{base}
		case types.ETDatetime, types.ETTimestamp:
			return &firstRow4Time{base}
		case types.ETDuration:
			return &firstRow4Duration{base}
		case types.ETString:
			return &firstRow4String{base}
		case types.ETJson:
			return &firstRow4JSON{base}
		}
	}
	return nil
}
322446
func (b *Builder) Build() (abbrev, aranges, frame, info, line, pubnames, ranges, str, loc []byte, err error) {
	b.TagClose()

	if len(b.tagStack) > 0 {
		err = fmt.Errorf("unbalanced TagOpen/TagClose %d", len(b.tagStack))
		return
	}

	abbrev = b.makeAbbrevTable()
	info = b.info.Bytes()
	binary.LittleEndian.PutUint32(info, uint32(len(info)-4))
	loc = b.loc.Bytes()

	return
}
322160
func (c *Client) ListUnspentMinMax(minConf, maxConf int) ([]btcjson.ListUnspentResult, error) {
	return c.ListUnspentMinMaxAsync(minConf, maxConf).Receive()
}
980363
func SetMaxMsgsz(n int) error {
	if initVersionError != nil {
		return initVersionError
	}
	if initContextError != nil {
		return initContextError
	}
	return defaultCtx.SetMaxMsgsz(n)
}
902145
func Argmax(a []float64) int {
	var f float64
	var max int
	var set bool
	for i, v := range a {
		if !set {
			f = v
			max = i
			set = true

			continue
		}

		// TODO: Maybe error instead of this?
		if math.IsNaN(v) || math.IsInf(v, 1) {
			max = i
			f = v
			break
		}

		if v > f {
			max = i
			f = v
		}
	}
	return max
}