// GenerateIV generates a new random 256 bit IV from the provided source
// of randomness. If random is nil the default PRNG of the system
// (crypto/rand) is used.
552476
func GenerateIV(random io.Reader) (iv [32]byte) {
	if random == nil {
		random = rand.Reader
	}
	if _, err := io.ReadFull(random, iv[:]); err != nil {
		logger.CriticalIf(context.Background(), errOutOfEntropy)
	}
	return iv
}
241
func Generate(pidfile string, chDel <-chan struct{}) error {
	f, err := os.OpenFile(pidfile, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer f.Close()
	fmt.Fprintln(f, os.Getpid())
	if chDel != nil {
		go func() {
			select {
			case <-chDel:
				os.Remove(pidfile)
			}
		}()
	}
	return nil
}
578664
func (g RandomKeyGenerate) KeyGenerate() (ByteSource, error) {
	buf := make([]byte, g.keysize)
	if _, err := io.ReadFull(rand.Reader, buf); err != nil {
		return nil, errors.Wrap(err, "failed to read from rand.Reader")
	}
	return ByteKey(buf), nil
}
428643
func randomIDGenerator() func() ID {
	seed, err := binary.ReadVarint(bufio.NewReader(crand.Reader))
	if err != nil {
		seed = int64(time.Now().Nanosecond())
	}
	var (
		mu  sync.Mutex
		rng = rand.New(rand.NewSource(seed))
	)
	return func() ID {
		mu.Lock()
		defer mu.Unlock()
		id := make([]byte, 16)
		rng.Read(id)
		return encodeID(id)
	}
}
922372
func GenerateIDWithAlg(customIDgenAlg string, payload []byte) (string, error) {
	if customIDgenAlg == "" {
		customIDgenAlg = defaultAlg
	}
	var alg = availableIDgenAlgs[customIDgenAlg]
	if alg.hashFun != nil {
		return alg.hashFun(payload), nil
	}
	return "", fmt.Errorf("Wrong ID generation algorithm was given: %s", customIDgenAlg)
}
92915
func (a *APIDefinition) RandomGenerator() *RandomGenerator {
	if a.rand == nil {
		a.rand = NewRandomGenerator(a.Name)
	}
	return a.rand
}
1371532
func RandomID(a ID, n int) (b ID) {
	if n == 0 {
		return a
	}
	// flip bit at position n, fill the rest with random bits
	b = a
	pos := len(a) - n/8 - 1
	bit := byte(0x01) << (byte(n%8) - 1)
	if bit == 0 {
		pos++
		bit = 0x80
	}
	b[pos] = a[pos]&^bit | ^a[pos]&bit // TODO: randomize end bits
	for i := pos + 1; i < len(a); i++ {
		b[i] = byte(rand.Intn(255))
	}
	return b
}
85466
func Uint64(v interface{}) (uint64, bool) {

	switch reflect.TypeOf(v).Kind() {
	case reflect.Uint:
		return uint64(v.(uint)), true
	case reflect.Uint8:
		return uint64(v.(uint8)), true
	case reflect.Uint16:
		return uint64(v.(uint16)), true
	case reflect.Uint32:
		return uint64(v.(uint32)), true
	case reflect.Uint64:
		return v.(uint64), true
	}

	return 0, false
}
423629
func (g *GifGenerator) Generate(input string, output string) (err error) {
	// virtual terminal
	var state = terminal.State{}
	vt, err := terminal.Create(&state, ioutil.NopCloser(bytes.NewBuffer([]byte{})))
	if err != nil {
		return
	}
	defer vt.Close()
	vt.Resize(g.Col, g.Row)

	// play and capture
	var (
		images []*image.Paletted
		delays []int
	)
	err = g.TtyPlay(input, vt, func(diff int32) (err error) {
		delay := int(float64(diff)/g.Speed) / 10000
		if delay > 0 {
			var img *image.Paletted
			img, err = g.Capture(&state)
			if err != nil {
				return
			}
			images = append(images, img)
			delays = append(delays, delay)
		}
		return nil
	})
	if err != nil {
		return
	}

	// generate gif file
	outFile, err := os.Create(output)
	if err != nil {
		return
	}
	defer outFile.Close()
	opts := gif.GIF{
		Image: images,
		Delay: delays,
	}
	if g.NoLoop {
		opts.LoopCount = 1
	}
	err = gif.EncodeAll(outFile, &opts)
	if err != nil {
		return
	}
	return nil
}
1339263
func GenerateKey(rand io.Reader, curve elliptic.Curve, params *ECIESParams) (prv *PrivateKey, err error) {
	pb, x, y, err := elliptic.GenerateKey(curve, rand)
	if err != nil {
		return
	}
	prv = new(PrivateKey)
	prv.PublicKey.X = x
	prv.PublicKey.Y = y
	prv.PublicKey.Curve = curve
	prv.D = new(big.Int).SetBytes(pb)
	if params == nil {
		params = ParamsFromCurve(curve)
	}
	prv.PublicKey.Params = params
	return
}
79321
func GenerateRandomBytes(size int) ([]byte, error) {
	buf := make([]byte, size)
	if _, err := rand.Read(buf); err != nil {
		return nil, fmt.Errorf("failed to read random bytes: %v", err)
	}
	return buf, nil
}
600686
func GenerateLenUUID(i int) (string, error) {
	if i < 0 {
		i = 2<<29 + i
	}
	return FormatUUID(fmt.Sprintf("%x", i))
}
1060053
func (g *Generator) Uint64(cardinality int) uint64 {
	z, ok := g.zs[cardinality]
	if !ok {
		// We subtract one from cardinality because rand.Zipf generates values
		// in [0, imax], but the expectation from funcs like rand.Intn is to
		// generate values in [0, n). Also since we can generate 0, this means
		// that the actual cardinality of the values we can return matches
		// "cardinality".
		imax := uint64(cardinality) - 1
		v := 0.05 * float64(imax)
		if v < 1.0 {
			v = 1.0
		}
		z = rand.NewZipf(g.r, 1.1, v, imax)
		g.zs[cardinality] = z
	}
	return z.Uint64()
}
111998
func (g *genProtoIDL) GenerateType(c *generator.Context, t *types.Type, w io.Writer) error {
	sw := generator.NewSnippetWriter(w, c, "$", "$")
	b := bodyGen{
		locator: &protobufLocator{
			namer:    c.Namers["proto"].(ProtobufFromGoNamer),
			tracker:  g.imports,
			universe: c.Universe,

			localGoPackage: g.localGoPackage.Package,
		},
		localPackage: g.localPackage,

		omitGogo:       g.omitGogo,
		omitFieldTypes: g.omitFieldTypes,

		t: t,
	}
	switch t.Kind {
	case types.Alias:
		return b.doAlias(sw)
	case types.Struct:
		return b.doStruct(sw)
	default:
		return b.unknown(sw)
	}
}
647922
func (s *Service) Generate(ctx context.Context, req *influxdb.OnboardingRequest) (*influxdb.OnboardingResults, error) {
	isOnboarding, err := s.IsOnboarding(ctx)
	if err != nil {
		return nil, err
	}
	if !isOnboarding {
		return nil, &influxdb.Error{
			Code: influxdb.EConflict,
			Msg:  "onboarding has already been completed",
		}
	}

	if err := req.Valid(); err != nil {
		return nil, err
	}

	u := &influxdb.User{Name: req.User}
	o := &influxdb.Organization{Name: req.Org}
	bucket := &influxdb.Bucket{
		Name:            req.Bucket,
		RetentionPeriod: time.Duration(req.RetentionPeriod) * time.Hour,
	}
	mapping := &influxdb.UserResourceMapping{
		ResourceType: influxdb.OrgsResourceType,
		UserType:     influxdb.Owner,
	}
	auth := &influxdb.Authorization{
		Description: fmt.Sprintf("%s's Token", u.Name),
		Permissions: influxdb.OperPermissions(),
		Token:       req.Token,
	}

	err = s.kv.Update(ctx, func(tx Tx) error {
		if err := s.createUser(ctx, tx, u); err != nil {
			return err
		}

		if err := s.setPassword(ctx, tx, u.Name, req.Password); err != nil {
			return err
		}

		if err := s.createOrganization(ctx, tx, o); err != nil {
			return err
		}

		bucket.OrgID = o.ID
		if err := s.createBucket(ctx, tx, bucket); err != nil {
			return err
		}

		mapping.ResourceID = o.ID
		mapping.UserID = u.ID
		if err := s.createUserResourceMapping(ctx, tx, mapping); err != nil {
			return err
		}

		auth.UserID = u.ID
		auth.OrgID = o.ID
		if err := s.createAuthorization(ctx, tx, auth); err != nil {
			return err
		}

		return s.putOnboardingStatus(ctx, tx, true)
	})
	if err != nil {
		return nil, err
	}

	return &influxdb.OnboardingResults{
		User:   u,
		Org:    o,
		Bucket: bucket,
		Auth:   auth,
	}, nil
}
432755
func generateID(l int) string {
	const (
		// ensures we backoff for less than 450ms total. Use the following to
		// select new value, in units of 10ms:
		// 	n*(n+1)/2 = d -> n^2 + n - 2d -> n = (sqrt(8d + 1) - 1)/2
		maxretries = 9
		backoff    = time.Millisecond * 10
	)

	var (
		totalBackoff time.Duration
		count        int
		retries      int
		size         = (l*5 + 7) / 8
		u            = make([]byte, size)
	)
	// TODO: Include time component, counter component, random component

	for {
		// This should never block but the read may fail. Because of this,
		// we just try to read the random number generator until we get
		// something. This is a very rare condition but may happen.
		b := time.Duration(retries) * backoff
		time.Sleep(b)
		totalBackoff += b

		n, err := io.ReadFull(rand.Reader, u[count:])
		if err != nil {
			if retryOnError(err) && retries < maxretries {
				count += n
				retries++
				logger.Errorf("error generating version 4 uuid, retrying: %v", err)
				continue
			}

			// Any other errors represent a system problem. What did someone
			// do to /dev/urandom?
			panic(fmt.Errorf("error reading random number generator, retried for %v: %v", totalBackoff.String(), err))
		}

		break
	}

	s := base32.StdEncoding.EncodeToString(u)

	return s[:l]
}
1337633
func (p *pool) generatePID() uint32 {
	atomic.AddUint32(&p.pidCounter, 1)
	return p.pidCounter
}