// Handles all cases from https://nagios-plugins.org/doc/guidelines.html#THRESHOLDFORMAT
432157
func parseThreshold(threshold string) (min float64, max float64, err error) {
	thresh := strings.Split(threshold, ":")
	switch len(thresh) {
	case 1:
		max, err = strconv.ParseFloat(string(thresh[0]), 64)
		if err != nil {
			return 0, 0, ErrBadThresholdFormat
		}

		return 0, max, nil
	case 2:
		if thresh[0] == "~" {
			min = MinFloat64
		} else {
			min, err = strconv.ParseFloat(string(thresh[0]), 64)
			if err != nil {
				min = 0
			}
		}

		if thresh[1] == "" {
			max = MaxFloat64
		} else {
			max, err = strconv.ParseFloat(string(thresh[1]), 64)
			if err != nil {
				return 0, 0, ErrBadThresholdFormat
			}
		}
	default:
		return 0, 0, ErrBadThresholdFormat
	}

	return
}
227976
func handleExtensionsInits(p *Params) gqlerrors.FormattedErrors {
	errs := gqlerrors.FormattedErrors{}
	for _, ext := range p.Schema.extensions {
		func() {
			// catch panic from an extension init fn
			defer func() {
				if r := recover(); r != nil {
					errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.Init: %v", ext.Name(), r.(error))))
				}
			}()
			// update context
			p.Context = ext.Init(p.Context, p)
		}()
	}
	return errs
}
1364419
func ValidateFilterRuleValue(value string) error {
	for _, segment := range strings.Split(value, "/") {
		if segment == "." || segment == ".." {
			return &ErrInvalidFilterValue{value}
		}
	}

	if len(value) <= 1024 && utf8.ValidString(value) && !strings.Contains(value, `\`) {
		return nil
	}

	return &ErrInvalidFilterValue{value}
}
235038
func formatRateReset(d time.Duration) string {
	isNegative := d < 0
	if isNegative {
		d *= -1
	}
	secondsTotal := int(0.5 + d.Seconds())
	minutes := secondsTotal / 60
	seconds := secondsTotal - minutes*60

	var timeString string
	if minutes > 0 {
		timeString = fmt.Sprintf("%dm%02ds", minutes, seconds)
	} else {
		timeString = fmt.Sprintf("%ds", seconds)
	}

	if isNegative {
		return fmt.Sprintf("[rate limit was reset %v ago]", timeString)
	}
	return fmt.Sprintf("[rate reset in %v]", timeString)
}
169329
func handleExtensionsParseDidStart(p *Params) ([]gqlerrors.FormattedError, parseFinishFuncHandler) {
	fs := map[string]ParseFinishFunc{}
	errs := gqlerrors.FormattedErrors{}
	for _, ext := range p.Schema.extensions {
		var (
			ctx      context.Context
			finishFn ParseFinishFunc
		)
		// catch panic from an extension's parseDidStart functions
		func() {
			defer func() {
				if r := recover(); r != nil {
					errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ParseDidStart: %v", ext.Name(), r.(error))))
				}
			}()
			ctx, finishFn = ext.ParseDidStart(p.Context)
			// update context
			p.Context = ctx
			fs[ext.Name()] = finishFn
		}()
	}
	return errs, func(err error) []gqlerrors.FormattedError {
		errs := gqlerrors.FormattedErrors{}
		for name, fn := range fs {
			func() {
				// catch panic from a finishFn
				defer func() {
					if r := recover(); r != nil {
						errs = append(errs, gqlerrors.FormatError(fmt.Errorf("%s.ParseFinishFunc: %v", name, r.(error))))
					}
				}()
				fn(err)
			}()
		}
		return errs
	}
}
581819
func (b *Buffer) TrimExcess() {
	threshold := float64(len(b.array)) * 0.9
	if b.size < int(threshold) {
		b.SetCapacity(b.size)
	}
}
654690
func FileFormat(path string) (Format, error) {
	if !fileExists(path) {
		return "", ErrInvalidPath
	}
	f, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer f.Close()
	var triedWav bool
	var triedAif bool

	ext := strings.ToLower(filepath.Ext(path))
	switch ext {
	case ".wav", ".wave":
		triedWav = true
		d := wav.NewDecoder(f)
		if d.IsValidFile() {
			return Wav, nil
		}
	case ".aif", ".aiff":
		triedAif = true
		d := aiff.NewDecoder(f)
		if d.IsValidFile() {
			return Aif, nil
		}
	}
	// extension doesn't match, let's try again
	f.Seek(0, 0)
	if !triedWav {
		wd := wav.NewDecoder(f)
		if wd.IsValidFile() {
			return Wav, nil
		}
		f.Seek(0, 0)
	}
	if !triedAif {
		ad := aiff.NewDecoder(f)
		if ad.IsValidFile() {
			return Aif, nil
		}
	}
	return Unknown, nil
}
774165
func ParseExpression(in string) (threshold.Predicate, error) {
	p, err := predicate.NewParser(predicate.Def{
		Operators: predicate.Operators{
			AND: threshold.AND,
			OR:  threshold.OR,
			EQ:  threshold.EQ,
			NEQ: threshold.NEQ,
			LT:  threshold.LT,
			LE:  threshold.LE,
			GT:  threshold.GT,
			GE:  threshold.GE,
		},
		Functions: map[string]interface{}{
			"LatencyAtQuantileMS": latencyAtQuantile,
			"NetworkErrorRatio":   networkErrorRatio,
			"ResponseCodeRatio":   responseCodeRatio,
		},
	})
	if err != nil {
		return nil, err
	}
	out, err := p.Parse(in)
	if err != nil {
		return nil, err
	}
	pr, ok := out.(threshold.Predicate)
	if !ok {
		return nil, fmt.Errorf("expected predicate, got %T", out)
	}
	return pr, nil
}
815458
func (m *ThresholdTrigger) Validate() error {
	if m == nil {
		return nil
	}

	if val := m.GetValue(); val < 0 || val > 1 {
		return ThresholdTriggerValidationError{
			field:  "Value",
			reason: "value must be inside range [0, 1]",
		}
	}

	return nil
}
1084951
func (ci *callInfo) verboseFormat() string {
	return fmt.Sprintf("[%s] (%s:%s:%d)", ci.packageName, ci.fileName, ci.funcName, ci.line)
}
537699
func (i *Index) SearchRegexp(re string, threshold int) ([]*Result, error) {
	matcher, err := regexp.Compile(re)
	if err != nil {
		return []*Result{}, err
	}
	buf := []*Result{}
	for k, v := range i.lines {
		ind := matcher.FindStringIndex(v)
		if len(ind) == 0 {
			continue
		}
		if score := i.calcScore(ind[0], v); ind[0] >= 0 && score < threshold {
			parts := strings.Split(k, verSep) // Remove version, if it is there.
			buf = append(buf, &Result{Name: parts[0], Score: score, Chart: i.charts[k]})
		}
	}
	return buf, nil
}
559232
func HandlerProcess(_ *logrus.Entry, _ *CustomFormatter) (interface{}, error) {
	return os.Getpid(), nil
}
318517
func parseThresholdStatements(statements map[string]string) ([]evictionapi.Threshold, error) {
	if len(statements) == 0 {
		return nil, nil
	}
	results := []evictionapi.Threshold{}
	for signal, val := range statements {
		result, err := parseThresholdStatement(evictionapi.Signal(signal), val)
		if err != nil {
			return nil, err
		}
		if result != nil {
			results = append(results, *result)
		}
	}
	return results, nil
}
1120323
func (b *BlockChain) ThresholdState(deploymentID uint32) (ThresholdState, error) {
	b.chainLock.Lock()
	state, err := b.deploymentState(b.bestChain.Tip(), deploymentID)
	b.chainLock.Unlock()

	return state, err
}
213598
func UnixFormatter(p Priority, hostname, tag, content string) string {
	timestamp := time.Now().Format(time.Stamp)
	msg := fmt.Sprintf("<%d>%s %s[%d]: %s",
		p, timestamp, tag, os.Getpid(), content)
	return msg
}
1355414
func (f *Fpdf) TransformScaleX(scaleWd, x, y float64) {
	f.TransformScale(scaleWd, 100, x, y)
}
955794
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
	data := make(Fields)
	for k, v := range entry.Data {
		data[k] = v
	}
	prefixFieldClashes(data, f.FieldMap, entry.HasCaller())
	keys := make([]string, 0, len(data))
	for k := range data {
		keys = append(keys, k)
	}

	var funcVal, fileVal string

	fixedKeys := make([]string, 0, 4+len(data))
	if !f.DisableTimestamp {
		fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime))
	}
	fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel))
	if entry.Message != "" {
		fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg))
	}
	if entry.err != "" {
		fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError))
	}
	if entry.HasCaller() {
		if f.CallerPrettyfier != nil {
			funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
		} else {
			funcVal = entry.Caller.Function
			fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
		}

		if funcVal != "" {
			fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc))
		}
		if fileVal != "" {
			fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile))
		}
	}

	if !f.DisableSorting {
		if f.SortingFunc == nil {
			sort.Strings(keys)
			fixedKeys = append(fixedKeys, keys...)
		} else {
			if !f.isColored() {
				fixedKeys = append(fixedKeys, keys...)
				f.SortingFunc(fixedKeys)
			} else {
				f.SortingFunc(keys)
			}
		}
	} else {
		fixedKeys = append(fixedKeys, keys...)
	}

	var b *bytes.Buffer
	if entry.Buffer != nil {
		b = entry.Buffer
	} else {
		b = &bytes.Buffer{}
	}

	f.terminalInitOnce.Do(func() { f.init(entry) })

	timestampFormat := f.TimestampFormat
	if timestampFormat == "" {
		timestampFormat = defaultTimestampFormat
	}
	if f.isColored() {
		f.printColored(b, entry, keys, data, timestampFormat)
	} else {

		for _, key := range fixedKeys {
			var value interface{}
			switch {
			case key == f.FieldMap.resolve(FieldKeyTime):
				value = entry.Time.Format(timestampFormat)
			case key == f.FieldMap.resolve(FieldKeyLevel):
				value = entry.Level.String()
			case key == f.FieldMap.resolve(FieldKeyMsg):
				value = entry.Message
			case key == f.FieldMap.resolve(FieldKeyLogrusError):
				value = entry.err
			case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller():
				value = funcVal
			case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller():
				value = fileVal
			default:
				value = data[key]
			}
			f.appendKeyValue(b, key, value)
		}
	}

	b.WriteByte('\n')
	return b.Bytes(), nil
}