// FleschKincaidEase computes the ease of reading a given text.
// The algorithm is explained in detail here:
// http://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests
422873
func FleschKincaidEase(text string) float64 {
	words := Words(text)
	numWords := float64(len(words))
	numSentences := float64(len(Sentences(text)))
	numSyllables := 0

	for _, word := range words {
		numSyllables += SyllableCount(word)
	}

	return 206.835 - 1.015*(numWords/numSentences) - 84.6*(float64(numSyllables)/numWords)

}
423402
func (p *PolicyAuthorizer) KeyRead(key string) bool {
	// Look for a matching rule
	if rule, ok := getPolicy(key, p.keyRules); ok {
		pr := rule.(RulePolicy)
		if allow, recurse := enforce(pr.aclPolicy, PolicyRead); !recurse {
			return allow
		}
	}

	// No matching rule, use the parent.
	return p.parent.KeyRead(key)
}
537740
func (s *Scanner) scanEscape() rune {
	// http://en.cppreference.com/w/cpp/language/escape
	ch := s.next() // read character after '/'
	switch ch {
	case 'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', '"':
		// nothing to do
	case '0', '1', '2', '3', '4', '5', '6', '7':
		// octal notation
		ch = s.scanDigits(ch, 8, 3)
	case 'x':
		// hexademical notation
		ch = s.scanDigits(s.next(), 16, 2)
	case 'u':
		// universal character name
		ch = s.scanDigits(s.next(), 16, 4)
	case 'U':
		// universal character name
		ch = s.scanDigits(s.next(), 16, 8)
	default:
		s.err("illegal char escape")
	}
	return ch
}
958481
func parseDeltaSeconds(v string) (DeltaSeconds, error) {
	n, err := strconv.ParseUint(v, 10, 32)
	if err != nil {
		if numError, ok := err.(*strconv.NumError); ok {
			if numError.Err == strconv.ErrRange {
				return DeltaSeconds(math.MaxInt32), nil
			}
		}
		return DeltaSeconds(-1), err
	} else {
		if n > math.MaxInt32 {
			return DeltaSeconds(math.MaxInt32), nil
		} else {
			return DeltaSeconds(n), nil
		}
	}
}
1191234
func (c *Config) ReadKiteKey() error {
	key, err := kitekey.Parse()
	if err != nil {
		return err
	}

	return c.ReadToken(key)
}
1233
func (p *Parser) parseKeyAndInferOperator() (string, Operator, error) {
	var operator Operator
	tok, literal := p.consume(Values)
	if tok == DoesNotExistToken {
		operator = DoesNotExistOperator
		tok, literal = p.consume(Values)
	}
	if tok != IdentifierToken {
		err := fmt.Errorf("found '%s', expected: identifier", literal)
		return "", "", err
	}
	if err := validateLabelKey(literal); err != nil {
		return "", "", err
	}
	if t, _ := p.lookahead(Values); t == EndOfStringToken || t == CommaToken {
		if operator != DoesNotExistOperator {
			operator = ExistsOperator
		}
	}
	return literal, operator, nil
}
178456
func (p *Parser) parseResample() (time.Duration, time.Duration, error) {
	var interval time.Duration
	if tok, _, _ := p.ScanIgnoreWhitespace(); tok == EVERY {
		tok, pos, lit := p.ScanIgnoreWhitespace()
		if tok != DURATIONVAL {
			return 0, 0, newParseError(tokstr(tok, lit), []string{"duration"}, pos)
		}

		d, err := ParseDuration(lit)
		if err != nil {
			return 0, 0, &ParseError{Message: err.Error(), Pos: pos}
		}
		interval = d
	} else {
		p.Unscan()
	}

	var maxDuration time.Duration
	if tok, _, _ := p.ScanIgnoreWhitespace(); tok == FOR {
		tok, pos, lit := p.ScanIgnoreWhitespace()
		if tok != DURATIONVAL {
			return 0, 0, newParseError(tokstr(tok, lit), []string{"duration"}, pos)
		}

		d, err := ParseDuration(lit)
		if err != nil {
			return 0, 0, &ParseError{Message: err.Error(), Pos: pos}
		}
		maxDuration = d
	} else {
		p.Unscan()
	}

	// Neither EVERY or FOR were read, so read the next token again
	// so we can return a suitable error message.
	if interval == 0 && maxDuration == 0 {
		tok, pos, lit := p.ScanIgnoreWhitespace()
		return 0, 0, newParseError(tokstr(tok, lit), []string{"EVERY", "FOR"}, pos)
	}
	return interval, maxDuration, nil
}
1250680
func (p *PerfEventMmapPage) Decode(reader io.ReadSeeker) error {
	return decode(p, reader)
}
391764
func scanNumericOrDuration(l *Lexer, doDuration bool) (typ TokenType, ok bool) {
	typ = TokenInteger
	// Optional leading sign.
	hasSign := l.accept("+-")
	peek2 := l.PeekX(2)
	peek2nd := byte(0)
	if len(peek2) == 2 {
		peek2nd = peek2[1]
	}
	//u.Debugf("scanNumericOrDuration?  '%v' peek:%v ", string(peek2), len(peek2))
	if peek2 == "0x" {
		// Hexadecimal.
		if hasSign {
			// No signs for hexadecimals.
			return
		}
		l.acceptRun("0x")
		if !l.acceptRun(hexDigits) {
			// Requires at least one digit.
			return
		}
		if l.accept(".") {
			// No dots for hexadecimals.
			return
		}
	} else {
		// Decimal
		if !l.acceptRun(decDigits) {
			// Requires at least one digit
			return
		}
		if l.accept(".") {
			// Float
			if !l.acceptRun(decDigits) {
				// Requires a digit after the dot.
				return
			}
			typ = TokenFloat
		} else {
			if (!hasSign && l.input[l.start] == '0') ||
				(hasSign && l.input[l.start+1] == '0') {
				switch peek2nd {
				case ' ', '\t', '\n', ',', ')', ';', byte(0):
					return typ, true
				}
				// Integers can't start with 0??
				return
			}
		}
		if l.accept("e") {
			l.accept("+-")
			if !l.acceptRun(decDigits) {
				// A digit is required after the scientific notation.
				return
			}
			typ = TokenFloat
		}
	}

	if doDuration {
		if l.acceptRun("yYmMdDuUsSwW") {
			// duration was found
			typ = TokenDuration
		}
	} else {
		// Next thing must not be alphanumeric.
		if isAlNum(l.Peek()) {
			l.Next()
			return
		}
	}

	ok = true
	return
}
113982
func parseHstore(s string) (k []string, v []Text, err error) {
	if s == "" {
		return
	}

	buf := bytes.Buffer{}
	keys := []string{}
	values := []Text{}
	p := newHSP(s)

	r, end := p.Consume()
	state := hsPre

	for !end {
		switch state {
		case hsPre:
			if r == '"' {
				state = hsKey
			} else {
				err = errors.New("String does not begin with \"")
			}
		case hsKey:
			switch r {
			case '"': //End of the key
				if buf.Len() == 0 {
					err = errors.New("Empty Key is invalid")
				} else {
					keys = append(keys, buf.String())
					buf = bytes.Buffer{}
					state = hsSep
				}
			case '\\': //Potential escaped character
				n, end := p.Consume()
				switch {
				case end:
					err = errors.New("Found EOS in key, expecting character or \"")
				case n == '"', n == '\\':
					buf.WriteRune(n)
				default:
					buf.WriteRune(r)
					buf.WriteRune(n)
				}
			default: //Any other character
				buf.WriteRune(r)
			}
		case hsSep:
			if r == '=' {
				r, end = p.Consume()
				switch {
				case end:
					err = errors.New("Found EOS after '=', expecting '>'")
				case r == '>':
					r, end = p.Consume()
					switch {
					case end:
						err = errors.New("Found EOS after '=>', expecting '\"' or 'NULL'")
					case r == '"':
						state = hsVal
					case r == 'N':
						state = hsNul
					default:
						err = errors.Errorf("Invalid character '%c' after '=>', expecting '\"' or 'NULL'", r)
					}
				default:
					err = errors.Errorf("Invalid character after '=', expecting '>'")
				}
			} else {
				err = errors.Errorf("Invalid character '%c' after value, expecting '='", r)
			}
		case hsVal:
			switch r {
			case '"': //End of the value
				values = append(values, Text{String: buf.String(), Status: Present})
				buf = bytes.Buffer{}
				state = hsNext
			case '\\': //Potential escaped character
				n, end := p.Consume()
				switch {
				case end:
					err = errors.New("Found EOS in key, expecting character or \"")
				case n == '"', n == '\\':
					buf.WriteRune(n)
				default:
					buf.WriteRune(r)
					buf.WriteRune(n)
				}
			default: //Any other character
				buf.WriteRune(r)
			}
		case hsNul:
			nulBuf := make([]rune, 3)
			nulBuf[0] = r
			for i := 1; i < 3; i++ {
				r, end = p.Consume()
				if end {
					err = errors.New("Found EOS in NULL value")
					return
				}
				nulBuf[i] = r
			}
			if nulBuf[0] == 'U' && nulBuf[1] == 'L' && nulBuf[2] == 'L' {
				values = append(values, Text{Status: Null})
				state = hsNext
			} else {
				err = errors.Errorf("Invalid NULL value: 'N%s'", string(nulBuf))
			}
		case hsNext:
			if r == ',' {
				r, end = p.Consume()
				switch {
				case end:
					err = errors.New("Found EOS after ',', expcting space")
				case (unicode.IsSpace(r)):
					r, end = p.Consume()
					state = hsKey
				default:
					err = errors.Errorf("Invalid character '%c' after ', ', expecting \"", r)
				}
			} else {
				err = errors.Errorf("Invalid character '%c' after value, expecting ','", r)
			}
		}

		if err != nil {
			return
		}
		r, end = p.Consume()
	}
	if state != hsNext {
		err = errors.New("Improperly formatted hstore")
		return
	}
	k = keys
	v = values
	return
}
802929
func ParseCSVEstimateFilePrecisionFromReader(r io.ReadSeeker) (int, error) {
	// Creat a basic regexp
	rexp := regexp.MustCompile("[0-9]+(.[0-9]+)?")

	// Scan through the file line-by-line
	maxL := 0

	r.Seek(0, 0)
	scanner := bufio.NewScanner(r)
	lineCount := 0
	for scanner.Scan() {
		if lineCount > 5 {
			break
		}
		line := scanner.Text()
		if len(line) == 0 {
			continue
		}
		if line[0] == '@' {
			continue
		}
		if line[0] == '%' {
			continue
		}
		matches := rexp.FindAllString(line, -1)
		for _, m := range matches {
			p := strings.Split(m, ".")
			if len(p) == 2 {
				l := len(p[len(p)-1])
				if l > maxL {
					maxL = l
				}
			}
		}
		lineCount++
	}
	return maxL, nil
}
491409
func (d *Decoder) parseDescChunk() error {
	if err := d.Read(&d.SampleRate); err != nil {
		return err
	}
	if err := d.Read(&d.FormatID); err != nil {
		return err
	}
	if err := d.Read(&d.FormatFlags); err != nil {
		return err
	}
	if err := d.Read(&d.BytesPerPacket); err != nil {
		return err
	}
	if err := d.Read(&d.FramesPerPacket); err != nil {
		return err
	}
	if err := d.Read(&d.ChannelsPerFrame); err != nil {
		return err
	}
	if err := d.Read(&d.BitsPerChannel); err != nil {
		return err
	}

	return nil
}
1264510
func (t *Tree) parseLenFunc() (Node, error) {
	node := new(FuncNode)

	t.scanner.accept = acceptOneHash
	t.scanner.mode = scanIdent
	switch t.scanner.scan() {
	case tokenIdent:
		node.Name = t.scanner.string()
	default:
		return nil, ErrBadSubstitution
	}

	t.scanner.accept = acceptIdent
	t.scanner.mode = scanIdent
	switch t.scanner.scan() {
	case tokenIdent:
		node.Param = t.scanner.string()
	default:
		return nil, ErrBadSubstitution
	}

	return node, t.consumeRbrack()
}
477435
func (r *decodingReadSeeker) getReadaheadFactor() int64 {
	mb := int64(1 << 20)
	switch {
	case r.size >= 1000*mb:
		return 16
	case r.size >= 500*mb:
		return 8
	default:
		return 4
	}
}
1243048
func ParseDurationFunc() mapstructure.DecodeHookFunc {
	return func(
		f reflect.Type,
		t reflect.Type,
		data interface{}) (interface{}, error) {
		var v time.Duration
		if t != reflect.TypeOf(v) {
			return data, nil
		}

		switch {
		case f.Kind() == reflect.String:
			if dur, err := time.ParseDuration(data.(string)); err != nil {
				return nil, err
			} else {
				v = dur
			}
			return v, nil
		case f == reflect.SliceOf(reflect.TypeOf(uint8(0))):
			s := Uint8ToString(data.([]uint8))
			if dur, err := time.ParseDuration(s); err != nil {
				return nil, err
			} else {
				v = dur
			}
			return v, nil
		default:
			return data, nil
		}
	}
}
868321
func (c *JWTConfig) Decode(isAck bool, data []byte, previousCert interface{}) (claims *ConnectionClaims, nonce []byte, publicKey interface{}, err error) {

	var ackCert interface{}
	var certClaims []string

	token := data

	jwtClaims := &JWTClaims{}

	nonce = make([]byte, NonceLength)

	// Get the token and data from the buffer and validate the certificate
	// Ack packets don't have a certificate and it must be provided in the
	// Decode function. If certificates are distributed out of band we
	// will look in the certPool for the certificate
	if !isAck {
		// We must have at least enough data to get the length
		if len(data) < tokenPosition {
			return nil, nil, nil, errors.New("not enough data")
		}

		tokenLength := int(binary.BigEndian.Uint16(data[0:noncePosition]))
		// Data must be enought to accommodate the token
		if len(data) < tokenPosition+tokenLength+1 {
			return nil, nil, nil, errors.New("invalid token length")
		}

		copy(nonce, data[noncePosition:tokenPosition])

		token = data[tokenPosition : tokenPosition+tokenLength]

		certBytes := data[tokenPosition+tokenLength+1:]

		ackCert, certClaims, err = c.secrets.KeyAndClaims(certBytes)
		if err != nil {
			return nil, nil, nil, fmt.Errorf("invalid public key: %s", err)
		}

		if cachedClaims, cerr := c.tokenCache.Get(string(token)); cerr == nil {
			return cachedClaims.(*ConnectionClaims), nonce, ackCert, nil
		}
	}

	// Parse the JWT token with the public key recovered. If it is an Ack packet
	// use the previous cert.
	jwttoken, err := jwt.ParseWithClaims(string(token), jwtClaims, func(token *jwt.Token) (interface{}, error) { // nolint
		if ackCert != nil {
			return ackCert.(*ecdsa.PublicKey), nil
		}
		if previousCert != nil {
			return previousCert.(*ecdsa.PublicKey), nil
		}
		return nil, fmt.Errorf("Unable to find certificate")
	})

	// If error is returned or the token is not valid, reject it
	if err != nil {
		return nil, nil, nil, fmt.Errorf("unable to parse token: %s", err)
	}
	if !jwttoken.Valid {
		return nil, nil, nil, errors.New("invalid token")
	}

	if !isAck {

		// Handling of compressed tags in a backward compatible manner. If there are claims
		// arriving in the compressed field then we append them to the tags.

		tags := []string{enforcerconstants.TransmitterLabel + "=" + jwtClaims.ConnectionClaims.ID}
		if jwtClaims.ConnectionClaims.T != nil {
			tags = jwtClaims.ConnectionClaims.T.Tags
		}

		if certClaims != nil {
			tags = append(tags, certClaims...)
		}

		// Handle compressed tags
		if c.compressionTagLength != 0 && len(jwtClaims.ConnectionClaims.C) > 0 {

			compressedClaims, err := base64.StdEncoding.DecodeString(jwtClaims.ConnectionClaims.C)
			if err != nil {
				return nil, nil, nil, fmt.Errorf("invalid claims")
			}

			if len(compressedClaims)%c.compressionTagLength != 0 {
				return nil, nil, nil, fmt.Errorf("invalid claims length. compression mismatch %d/%d", len(compressedClaims), c.compressionTagLength)
			}

			for i := 0; i < len(compressedClaims); i = i + c.compressionTagLength {
				tags = append(tags, base64.StdEncoding.EncodeToString(compressedClaims[i:i+c.compressionTagLength]))
			}
		}

		jwtClaims.ConnectionClaims.T = policy.NewTagStoreFromSlice(tags)

		zap.L().Debug("claims (post)", zap.Reflect("jwt", jwtClaims))
	}

	if jwtClaims.ConnectionClaims.H != nil {
		if err := c.verifyClaimsHeader(jwtClaims.ConnectionClaims.H.ToClaimsHeader()); err != nil {
			return nil, nil, nil, err
		}
	}

	c.tokenCache.AddOrUpdate(string(token), jwtClaims.ConnectionClaims)

	return jwtClaims.ConnectionClaims, nonce, ackCert, nil
}
483221
func (m *Mnemonic) Decipher(pass []byte) ([DecipheredCipherSeedSize]byte, error) {

	// Before we attempt to map the mnemonic back to the original
	// ciphertext, we'll ensure that all the word are actually a part of
	// the current default word list.
	for _, word := range m {
		if !strings.Contains(englishWordList, word) {
			emptySeed := [DecipheredCipherSeedSize]byte{}
			return emptySeed, ErrUnknownMnenomicWord{word}
		}
	}

	// If the passphrase wasn't provided, then we'll use the string
	// "aezeed" in place.
	passphrase := pass
	if len(passphrase) == 0 {
		passphrase = defaultPassphrase
	}

	// Next, we'll map the mnemonic phrase back into the original cipher
	// text.
	cipherText := mnemonicToCipherText(m)

	// Finally, we'll attempt to decipher the enciphered seed. The result
	// will be the raw seed minus the ciphertext expansion, external
	// version, and salt.
	return decipherCipherSeed(cipherText, passphrase)
}