// Generate reads the video given by videoRef from src and writes its thumbnail image to w.
556367
func (s *Service) Generate(videoRef blob.Ref, w io.Writer, src blob.Fetcher) error {

	if s.gate != nil {
		s.gate.Start()
		defer s.gate.Done()
	}

	ln, err := netutil.ListenOnLocalRandomPort()
	if err != nil {
		return err
	}
	defer ln.Close()

	videoURI := &url.URL{
		Scheme: "http",
		Host:   ln.Addr().String(),
		Path:   videoRef.String(),
	}

	cmdErrc := make(chan error, 1)
	cmd := buildCmd(s.thumbnailer, videoURI, w)
	cmdErrOut, err := cmd.StderrPipe()
	if err != nil {
		return err
	}
	if err := cmd.Start(); err != nil {
		return err
	}
	defer cmd.Process.Kill()
	go func() {
		out, err := ioutil.ReadAll(cmdErrOut)
		if err != nil {
			cmdErrc <- err
			return
		}
		cmd.Wait()
		if cmd.ProcessState.Success() {
			cmdErrc <- nil
			return
		}
		cmdErrc <- fmt.Errorf("thumbnail subprocess failed:\n%s", out)
	}()

	servErrc := make(chan error, 1)
	go func() {
		servErrc <- http.Serve(ln, createVideothumbnailHandler(videoRef, src))
	}()

	select {
	case err := <-cmdErrc:
		return err
	case err := <-servErrc:
		return err
	case <-s.timer():
		return errTimeout
	}
}
1206511
func Generate(targetDir, targetSrc string, pool int, dynamic bool) error {
	filterPath := filepath.Join(targetDir, IgnoreFile)
	filter := filter.LoadFilter(filterPath)
	var hashes HashSet
	var err error
	if pool < 2 {
		hashes, err = HashDirectory(targetDir)
	} else {
		if dynamic {
			pool *= runtime.NumCPU()
		}
		hashes, err = HashDirectoryAsync(targetDir, pool)
	}
	if err != nil {
		log.Critical("failed to hash directory:", err)
		return err
	}
	filtered := FilterHashes(hashes, filter)
	return Write(targetDir, targetSrc, filtered)
}
75057
func Generate(w http.ResponseWriter, r *http.Request, opts ...GenerateOption) {
	o := &GenerateOptions{
		name:   XSRFCookieName,
		path:   "/",
		domain: "",
		maxAge: 0,
	}
	for _, opt := range opts {
		opt(o)
	}
	if !hasCookie(r, o.name) || o.force {
		http.SetCookie(w, &http.Cookie{
			Name:   o.name,
			Value:  newKey(),
			Path:   o.path,
			Domain: o.domain,
			Secure: r.TLS != nil,
			MaxAge: o.maxAge,
		})
	}
}
128648
func (d *dataset) generate(dir string, limit int, test bool) {
	d.once.Do(func() {
		// Mark the dataset generated after we're done. This is needed for remote
		defer atomic.StoreUint32(&d.done, 1)

		csize := cacheSize(d.epoch*epochLength + 1)
		dsize := datasetSize(d.epoch*epochLength + 1)
		seed := seedHash(d.epoch*epochLength + 1)
		if test {
			csize = 1024
			dsize = 32 * 1024
		}
		// If we don't store anything on disk, generate and return
		if dir == "" {
			cache := make([]uint32, csize/4)
			generateCache(cache, d.epoch, seed)

			d.dataset = make([]uint32, dsize/4)
			generateDataset(d.dataset, d.epoch, cache)

			return
		}
		// Disk storage is needed, this will get fancy
		var endian string
		if !isLittleEndian() {
			endian = ".be"
		}
		path := filepath.Join(dir, fmt.Sprintf("full-R%d-%x%s", algorithmRevision, seed[:8], endian))
		logger := log.New("epoch", d.epoch)

		// We're about to mmap the file, ensure that the mapping is cleaned up when the
		// cache becomes unused.
		runtime.SetFinalizer(d, (*dataset).finalizer)

		// Try to load the file from disk and memory map it
		var err error
		d.dump, d.mmap, d.dataset, err = memoryMap(path)
		if err == nil {
			logger.Debug("Loaded old ethash dataset from disk")
			return
		}
		logger.Debug("Failed to load old ethash dataset", "err", err)

		// No previous dataset available, create a new dataset file to fill
		cache := make([]uint32, csize/4)
		generateCache(cache, d.epoch, seed)

		d.dump, d.mmap, d.dataset, err = memoryMapAndGenerate(path, dsize, func(buffer []uint32) { generateDataset(buffer, d.epoch, cache) })
		if err != nil {
			logger.Error("Failed to generate mapped ethash dataset", "err", err)

			d.dataset = make([]uint32, dsize/2)
			generateDataset(d.dataset, d.epoch, cache)
		}
		// Iterate over all previous instances and delete old ones
		for ep := int(d.epoch) - limit; ep >= 0; ep-- {
			seed := seedHash(uint64(ep)*epochLength + 1)
			path := filepath.Join(dir, fmt.Sprintf("full-R%d-%x%s", algorithmRevision, seed[:8], endian))
			os.Remove(path)
		}
	})
}
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
}
1083432
func (gc Client) Generate() error {
	if err := commons.CheckDuplicatedTitleTypes(gc.apiDef); err != nil {
		return err
	}
	// helper package
	gh := goramlHelper{
		packageName: "goraml",
		packageDir:  "goraml",
	}
	if err := gh.generate(gc.TargetDir); err != nil {
		return err
	}

	// generate struct
	if err := generateAllStructs(gc.apiDef, gc.TargetDir); err != nil {
		return err
	}

	// libraries
	if err := generateLibraries(gc.libraries, gc.TargetDir, gc.libsRootURLs); err != nil {
		return err
	}

	if err := gc.generateHelperFile(gc.TargetDir); err != nil {
		return err
	}

	if err := gc.generateSecurity(gc.TargetDir); err != nil {
		return err
	}

	if err := gc.generateServices(gc.TargetDir); err != nil {
		return err
	}
	return gc.generateClientFile(gc.TargetDir)
}
127548
func (s *Struct) Generate(dir string) error {
	if s.Enum != nil {
		return s.Enum.generate(dir)
	}

	if err := s.generateEnums(dir); err != nil {
		return err
	}
	filename := filepath.Join(dir, s.Name+".capnp")
	return commons.GenerateFile(s, "./templates/capnp/struct_capnp.tmpl", "struct_capnp", filename, true)
}
579257
func (js jsonSchema) Generate(dir string) error {
	if js.Alias.Builtin {
		return nil // plain builtin type can't be a JSON
	}

	filename := filepath.Join(dir, js.filename())
	ctx := map[string]interface{}{
		"Content": js.String(),
	}
	return commons.GenerateFile(ctx, "./templates/golang/json_schema.tmpl", "json_schema", filename, true)
}
1075922
func (s *Server) Generate() error {
	apiDef := new(raml.APIDefinition)
	// parse the raml file
	dir, fileName := filepath.Split(s.RAMLFile)
	ramlBytes, err := raml.ParseReadFile(dir, fileName, apiDef)
	if err != nil {
		return err
	}

	var generator generator.Server

	switch s.Lang {
	case langGo:
		generator = golang.NewServer(apiDef, s.PackageName, s.APIDocsDir, s.RootImportPath, s.WithMain,
			s.Dir, s.LibRootURLs)
	case langPython:
		generator = python.NewServer(s.Kind, apiDef, s.APIDocsDir, s.Dir, s.WithMain, s.LibRootURLs)
	case langNim:
		generator = nim.NewServer(apiDef, s.APIDocsDir, s.Dir)
	case langTarantool:
		generator = tarantool.NewServer(apiDef, s.APIDocsDir, s.Dir)
	default:
		return errInvalidLang
	}
	err = generator.Generate()
	if err != nil {
		return err
	}

	if s.APIDocsDir == "" {
		return nil
	}

	if s.Lang == langNim {
		s.APIDocsDir = "public/" + s.APIDocsDir
	}

	log.Infof("Generating API Docs to %v", s.APIDocsDir)

	return apidocs.Generate(apiDef, s.RAMLFile, ramlBytes, filepath.Join(s.Dir, s.APIDocsDir), s.LibRootURLs)
}
420205
func (t *treeGenerator) Generate(n int) ([]*triple.Triple, error) {
	var trpls []*triple.Triple
	if n <= 0 {
		return trpls, nil
	}
	root, err := t.newNode(0, "")
	if err != nil {
		return nil, err
	}
	depth := int(math.Log(float64(n)) / math.Log(float64(t.branch)))
	ntrpls, err := t.recurse(root, &n, 0, depth, trpls)
	if err != nil {
		return nil, err
	}
	return ntrpls, nil
}
1226534
func (i *VarAdder) Generate(next ContextHandler) ContextHandler {
	return HandlerFunc(func(ctx context.Context, rw http.ResponseWriter, r *http.Request) {
		next.ServeHTTPC(context.WithValue(ctx, i.Key, i.Value), rw, r)
	})
}
636521
func (s *FileSource) Generate(f *flow.Flow) *flow.Dataset {
	return s.genShardInfos(f).RoundRobin(s.prefix, s.PartitionCount).Map(s.prefix+".Read", registeredMapperReadShard)
}
289501
func Generate() string {
	rand.Seed(time.Now().UTC().UnixNano())

	data := make([]int, 9)
	for i := 0; i < 9; i++ {
		data[i] = rand.Intn(9)
	}
	checkDigit1 := computeCheckDigit(data)
	data = append(data, checkDigit1)
	checkDigit2 := computeCheckDigit(data)
	data = append(data, checkDigit2)

	var cpf string
	for _, value := range data {
		cpf += strconv.Itoa(value)
	}
	return cpf
}
223034
func (g *Generator) Generate() (_ []string, err error) {
	if g.API == nil {
		return nil, fmt.Errorf("missing API definition, make sure design is properly initialized")
	}

	go utils.Catch(nil, func() { g.Cleanup() })

	defer func() {
		if err != nil {
			g.Cleanup()
		}
	}()

	firstNonEmpty := func(args ...string) string {
		for _, value := range args {
			if len(value) > 0 {
				return value
			}
		}
		return ""
	}

	g.Target = firstNonEmpty(g.Target, "client")
	g.ToolDirName = firstNonEmpty(g.ToolDirName, "tool")
	g.Tool = firstNonEmpty(g.Tool, defaultToolName(g.API))

	codegen.Reserved[g.Target] = true

	// Setup output directories as needed
	var pkgDir, toolDir, cliDir string
	{
		if !g.NoTool {
			toolDir = filepath.Join(g.OutDir, g.ToolDirName, g.Tool)
			if _, err = os.Stat(toolDir); err != nil {
				if err = os.MkdirAll(toolDir, 0755); err != nil {
					return
				}
			}

			cliDir = filepath.Join(g.OutDir, g.ToolDirName, "cli")
			if err = os.RemoveAll(cliDir); err != nil {
				return
			}
			if err = os.MkdirAll(cliDir, 0755); err != nil {
				return
			}
		}

		pkgDir = filepath.Join(g.OutDir, g.Target)
		if err = os.RemoveAll(pkgDir); err != nil {
			return
		}
		if err = os.MkdirAll(pkgDir, 0755); err != nil {
			return
		}
	}

	// Setup generation
	var funcs template.FuncMap
	var clientPkg string
	{
		funcs = template.FuncMap{
			"add":                func(a, b int) int { return a + b },
			"cmdFieldType":       cmdFieldType,
			"defaultPath":        defaultPath,
			"escapeBackticks":    escapeBackticks,
			"goify":              codegen.Goify,
			"gotypedef":          codegen.GoTypeDef,
			"gotypedesc":         codegen.GoTypeDesc,
			"gotypename":         codegen.GoTypeName,
			"gotyperef":          codegen.GoTypeRef,
			"gotyperefext":       goTypeRefExt,
			"join":               join,
			"joinStrings":        strings.Join,
			"multiComment":       multiComment,
			"pathParams":         pathParams,
			"pathTemplate":       pathTemplate,
			"signerType":         signerType,
			"tempvar":            codegen.Tempvar,
			"title":              strings.Title,
			"toString":           toString,
			"toValueTypeName":    toValueTypeName,
			"typeName":           typeName,
			"format":             format,
			"handleSpecialTypes": handleSpecialTypes,
		}
		clientPkg, err = codegen.PackagePath(pkgDir)
		if err != nil {
			return
		}
		arrayToStringTmpl = template.Must(template.New("client").Funcs(funcs).Parse(arrayToStringT))
	}

	if !g.NoTool {
		var cliPkg string
		cliPkg, err = codegen.PackagePath(cliDir)
		if err != nil {
			return
		}

		// Generate tool/main.go (only once)
		mainFile := filepath.Join(toolDir, "main.go")
		if _, err := os.Stat(mainFile); err != nil {
			g.genfiles = append(g.genfiles, toolDir)
			if err = g.generateMain(mainFile, clientPkg, cliPkg, funcs); err != nil {
				return nil, err
			}
		}

		// Generate tool/cli/commands.go
		g.genfiles = append(g.genfiles, cliDir)
		if err = g.generateCommands(filepath.Join(cliDir, "commands.go"), clientPkg, funcs); err != nil {
			return
		}
	}

	// Generate client/client.go
	g.genfiles = append(g.genfiles, pkgDir)
	if err = g.generateClient(filepath.Join(pkgDir, "client.go"), clientPkg, funcs); err != nil {
		return
	}

	// Generate client/$res.go and types.go
	if err = g.generateClientResources(pkgDir, clientPkg, funcs); err != nil {
		return
	}

	return g.genfiles, nil
}
615706
func (c Client) Generate(dir string) error {
	globAPIDef = c.APIDef

	// generate helper
	if err := commons.GenerateFile(nil, "./templates/python/client_utils_python.tmpl", "client_utils_python", filepath.Join(dir, "client_utils.py"), true); err != nil {
		return err
	}

	// generate http client
	if err := commons.GenerateFile(nil, c.Template.httpClientFile, c.Template.httpClientName, filepath.Join(dir, "http_client.py"), true); err != nil {
		return err
	}

	if err := c.generateServices(dir); err != nil {
		return err
	}

	if err := c.generateSecurity(dir); err != nil {
		return err
	}

	// python classes
	classes, err := GenerateAllClasses(c.APIDef, dir, false)
	if err != nil {
		return err
	}

	// helper for python classes
	if err := commons.GenerateFile(nil, "./templates/python/client_support.tmpl",
		"client_support", filepath.Join(dir, "client_support.py"), true); err != nil {
		return err
	}

	if c.UnmarshallResponse {
		if err := commons.GenerateFile(nil, "./templates/python/unmarshall_error.tmpl",
			"unmarshall_error", filepath.Join(dir, "unmarshall_error.py"), true); err != nil {
			return err
		}
		if err := commons.GenerateFile(nil, "./templates/python/unhandled_api_error.tmpl",
			"unhandled_api_error", filepath.Join(dir, "unhandled_api_error.py"), true); err != nil {
			return err
		}
	}

	sort.Strings(classes)
	c.Classes = classes
	return commons.GenerateFile(c, c.Template.initFile, c.Template.initName, filepath.Join(dir, "__init__.py"), true)
}
1299881
func (s *CassandraSource) Generate(f *flow.Flow) *flow.Dataset {
	return s.genShardInfos(f).RoundRobin(s.prefix, s.Concurrency).Map(s.prefix+".Read", MapperReadShard)
}
1074619
func (s *mustRunAs) Generate(_ *api.Pod) ([]int64, error) {
	return []int64{s.ranges[0].Min}, nil
}