func generateGIF(filenames []string, outPath string) error { fmt.Printf("Generating GIF in %s\n", outPath) uiprogress.Start() bar := uiprogress.AddBar(len(filenames)).AppendCompleted() anim := gif.GIF{LoopCount: len(filenames)} for _, filename := range filenames { reader, err := os.Open(filename) if err != nil { return err } defer reader.Close() img, _, err := image.Decode(reader) if err != nil { return err } bounds := img.Bounds() drawer := draw.FloydSteinberg palettedImg := image.NewPaletted(bounds, palette.Plan9) drawer.Draw(palettedImg, bounds, img, image.ZP) anim.Image = append(anim.Image, palettedImg) anim.Delay = append(anim.Delay, *delay) bar.Incr() } file, err := os.Create(outPath) defer file.Close() if err != nil { return err } encodeErr := gif.EncodeAll(file, &anim) if encodeErr != nil { return encodeErr } return nil }
func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) tagflag.Parse(&opts, tagflag.SkipBadTypes()) clientConfig := opts.Config if opts.Mmap { clientConfig.TorrentDataOpener = func(info *metainfo.Info) torrent.Data { ret, err := mmap.TorrentData(info, "") if err != nil { log.Fatalf("error opening torrent data for %q: %s", info.Name, err) } return ret } } client, err := torrent.NewClient(&clientConfig) if err != nil { log.Fatalf("error creating client: %s", err) } defer client.Close() http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { client.WriteStatus(w) }) uiprogress.Start() addTorrents(client) if client.WaitAll() { log.Print("downloaded ALL the torrents") } else { log.Fatal("y u no complete torrents?!") } if opts.Seed { select {} } }
func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) tagflag.Parse(&opts, tagflag.SkipBadTypes()) clientConfig := opts.Config if opts.Mmap { clientConfig.DefaultStorage = storage.NewMMap("") } client, err := torrent.NewClient(&clientConfig) if err != nil { log.Fatalf("error creating client: %s", err) } defer client.Close() http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { client.WriteStatus(w) }) uiprogress.Start() addTorrents(client) if client.WaitAll() { log.Print("downloaded ALL the torrents") } else { log.Fatal("y u no complete torrents?!") } if opts.Seed { select {} } }
func main() { runtime.GOMAXPROCS(runtime.NumCPU()) // use all available cpu cores // create a new bar and prepend the task progress to the bar and fanout into 1k go routines count := 1000 bar := uiprogress.AddBar(count).AppendCompleted().PrependElapsed() bar.PrependFunc(func(b *uiprogress.Bar) string { return fmt.Sprintf("Task (%d/%d)", b.Current(), count) }) uiprogress.Start() var wg sync.WaitGroup // fanout into 1k go routines for i := 0; i < count; i++ { wg.Add(1) go func() { defer wg.Done() time.Sleep(time.Millisecond * time.Duration(rand.Intn(500))) bar.Incr() }() } time.Sleep(time.Second) // wait for a second for all the go routines to finish wg.Wait() uiprogress.Stop() }
func NewPomodoro() *Pomodoro { pomodoro := Pomodoro{ done: make(chan struct{}, 0), } sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) go func() { for { select { case <-pomodoro.done: case <-sig: if pomodoro.running { pomodoro.Stop() } else { os.Exit(0) } } } }() uiprogress.Start() return &pomodoro }
func main() { log.SetFlags(log.LstdFlags | log.Lshortfile) tagflag.Parse(&flags) var clientConfig torrent.Config if flags.Mmap { clientConfig.DefaultStorage = storage.NewMMap("") } if flags.Addr != nil { clientConfig.ListenAddr = flags.Addr.String() } client, err := torrent.NewClient(&clientConfig) if err != nil { log.Fatalf("error creating client: %s", err) } defer client.Close() // Write status on the root path on the default HTTP muxer. This will be // bound to localhost somewhere if GOPPROF is set, thanks to the envpprof // import. http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { client.WriteStatus(w) }) uiprogress.Start() addTorrents(client) if client.WaitAll() { log.Print("downloaded ALL the torrents") } else { log.Fatal("y u no complete torrents?!") } if flags.Seed { select {} } }
// Save method persist (save or update) the chain on the disk func (c *Chain) Save() { var cn = c.collection if c.collection == "" { cn = timeName() c.collection = cn } sess, coll := model.Connect(cn) defer sess.Close() ks := c.Keys() sort.Strings(ks) var wg sync.WaitGroup var workForce = 5 ch := make(chan model.NewNodeInfo, workForce) for i := 0; i < workForce; i++ { wg.Add(1) go func() { defer wg.Done() var ni model.NewNodeInfo var more bool for { ni, more = <-ch if more { model.NewNode(ni).Save(coll) } else { return } } }() } count := len(ks) bar := uiprogress.AddBar(count) bar.AppendCompleted() bar.PrependElapsed() bar.PrependFunc(func(b *uiprogress.Bar) string { return fmt.Sprintf("Node (%d/%d)", b.Current(), count) }) uiprogress.Start() for _, x := range ks { ch <- model.NewNodeInfo{x, c.chain[x]} bar.Incr() } uiprogress.Stop() close(ch) wg.Wait() }
func (o *Get) Execute(args []string) error { client, err := Client() if err != nil { return err } bucket, err := client.Bucket(opts.Bucket) if err != nil { return err } if bucket == nil { return errors.New("Bucket not found: " + opts.Bucket) } uiprogress.Start() pool := make(chan bool, o.Threads) group := sync.WaitGroup{} var downloadError error for _, file := range args { // TODO handle wildcards fileInfo, reader, err := bucket.DownloadFileByName(file) if err != nil { downloadError = err break } // Get a ticket to process a download pool <- true if downloadError != nil { break } // Start next parallel download group.Add(1) go func(fileInfo *backblaze.File, reader io.ReadCloser, path string) { err := download(fileInfo, reader, path) if err != nil { fmt.Println(err) downloadError = err } // Allow next entry into pool group.Done() <-pool }(fileInfo, reader, file) } group.Wait() return downloadError }
func Example() { uiprogress.Start() // start rendering bar := uiprogress.AddBar(100) // Add a new bar // optionally, append and prepend completion and elapsed time bar.AppendCompleted() bar.PrependElapsed() for bar.Incr() { time.Sleep(time.Millisecond * 20) } }
func Generate() { cfg := Conf{} var fId, mail, pass, name, hueser string var speed time.Duration reader := bufio.NewReader(os.Stdin) fmt.Println("Your facebook id:") fmt.Scanln(&fId) cfg.UserId = fId fmt.Println("Your facebook mail:") fmt.Scanln(&mail) cfg.Mail = mail fmt.Println("Your facebook password:"******"Please authorize this program, by linking it on your bridge now; you've got 15 seconds.") uiprogress.Start() bar := uiprogress.AddBar(15000 / 100).AppendCompleted().PrependElapsed() for bar.Incr() { time.Sleep(100 * time.Millisecond) } hueser, err = bridge.CreateUser(mail) checkErr(err) cfg.Hueser = hueser fmt.Println("Name of your light:") name, err = reader.ReadString('\n') checkErr(err) cfg.Name = name[:len(name)-2] fmt.Println("Blink speed of the light:") fmt.Scanln(&speed) cfg.Speed = speed byteArr, _ := json.Marshal(cfg) file, err := os.Create("config.json") checkErr(err) _, err = file.Write(byteArr) checkErr(err) }
func main() { fmt.Println("apps: deployment started: app1, app2") uiprogress.Start() var wg sync.WaitGroup wg.Add(1) go deploy("app1", &wg) wg.Add(1) go deploy("app2", &wg) wg.Wait() fmt.Println("apps: successfully deployed: app1, app2") }
func main() { uiprogress.Start() // start rendering bar := uiprogress.AddBar(100) // Add a new bar // optionally, append and prepend completion and elapsed time bar.AppendCompleted() bar.PrependElapsed() for i := 1; i <= bar.Total; i++ { bar.Set(i) time.Sleep(time.Millisecond * 10) } }
func performDeploy(args []string) error { if len(args) != 1 { return errors.New("deploy takes only 1 argument - Marathon's application definition file") } path := args[0] renderedConfig, err := appconfig.Render(environment, path) if dryRun { fmt.Println("Rendered app specification") fmt.Println(renderedConfig) return err } var configMap map[string]interface{} util.JsonDecode(renderedConfig, &configMap) appName := configMap["id"].(string) fmt.Println("Deploying " + appName + " from " + path) deployment, err := marathon.Deploy(appName, renderedConfig, force) if err != nil { return err } // Do fancy UI updates on the screen uiprogress.Start() defer uiprogress.Stop() bar := uiprogress.AddBar(timeoutInSeconds + 1) bar.AppendCompleted() bar.PrependElapsed() bar.PrependFunc(func(b *uiprogress.Bar) string { return appName + " deploying" }) for bar.Incr() { time.Sleep(time.Millisecond * 1000) if bar.Current()%15 == 0 { // check the deployment stauts only every 15 seconds stillDeploying, err := marathon.IsStillDeploying(deployment) if err != nil { return err } if !stillDeploying { bar.Set(timeoutInSeconds) time.Sleep(time.Millisecond * 20) // wait for a few ms to refresh the output fmt.Println("Deployment completed") return nil } } } return errors.New("[ERROR] App deployment timed out. Check Marathon UI for more details") }
func main() { fmt.Println("apps: deployment started...") uiprogress.Start() var wg sync.WaitGroup apps := 1 for apps < 4 { wg.Add(1) go deploy("app "+strconv.Itoa(apps), &wg) apps += apps } wg.Wait() fmt.Println("apps: successfully deployed...") }
// Execute the put command func (o *Put) Execute(args []string) error { client, err := Client() if err != nil { return err } bucket, err := client.Bucket(opts.Bucket) if err != nil { return err } if bucket == nil { return errors.New("Bucket not found: " + opts.Bucket) } uiprogress.Start() tasks := make(chan string, o.Threads) group := sync.WaitGroup{} // Create workers for i := 0; i < o.Threads; i++ { group.Add(1) go func() { for file := range tasks { _, err := upload(bucket, file, o.Meta) if err != nil { fmt.Println(err) } // TODO handle termination on error } group.Done() }() } for _, file := range args { tasks <- file } close(tasks) group.Wait() return nil }
func ExampleProgress_AddBar() { waitTime := time.Millisecond * 100 uiprogress.Start() var wg sync.WaitGroup bar1 := uiprogress.AddBar(20).AppendCompleted().PrependElapsed() wg.Add(1) // update the progress bars concurrently using a go routine go func() { defer wg.Done() for i := 1; i <= bar1.Total; i++ { bar1.Set(i) time.Sleep(waitTime) } }() bar2 := uiprogress.AddBar(100).AppendCompleted().PrependElapsed() wg.Add(1) go func() { defer wg.Done() for i := 1; i <= bar2.Total; i++ { bar2.Set(i) time.Sleep(waitTime) } }() time.Sleep(time.Second) bar3 := uiprogress.AddBar(20).PrependElapsed().AppendCompleted() wg.Add(1) go func() { defer wg.Done() for i := 1; i <= bar3.Total; i++ { bar3.Set(i) time.Sleep(waitTime) } }() // wait for a collection of goroutines to finish wg.Wait() }
func main() { waitTime := time.Millisecond * 100 uiprogress.Start() var wg sync.WaitGroup bar1 := uiprogress.AddBar(20).AppendCompleted().PrependElapsed() wg.Add(1) go func() { defer wg.Done() for i := 1; i <= bar1.Total; i++ { bar1.Set(i) time.Sleep(waitTime) } }() bar2 := uiprogress.AddBar(40).AppendCompleted().PrependElapsed() wg.Add(1) go func() { defer wg.Done() for i := 1; i <= bar2.Total; i++ { bar2.Set(i) time.Sleep(waitTime) } }() time.Sleep(time.Second) bar3 := uiprogress.AddBar(20).PrependElapsed().AppendCompleted() wg.Add(1) go func() { defer wg.Done() for i := 1; i <= bar3.Total; i++ { bar3.Set(i) time.Sleep(waitTime) } }() wg.Wait() }
func ExampleProgress_AddBar() { waitTime := time.Millisecond * 100 uiprogress.Start() // start the progress bars in go routines var wg sync.WaitGroup bar1 := uiprogress.AddBar(20).AppendCompleted().PrependElapsed() wg.Add(1) go func() { defer wg.Done() for bar1.Incr() { time.Sleep(waitTime) } }() bar2 := uiprogress.AddBar(40).AppendCompleted().PrependElapsed() wg.Add(1) go func() { defer wg.Done() for bar2.Incr() { time.Sleep(waitTime) } }() time.Sleep(time.Second) bar3 := uiprogress.AddBar(20).PrependElapsed().AppendCompleted() wg.Add(1) go func() { defer wg.Done() for i := 1; i <= bar3.Total; i++ { bar3.Set(i) time.Sleep(waitTime) } }() // wait for all the go routines to finish wg.Wait() }
// Execute the get command func (o *Get) Execute(args []string) error { client, err := Client() if err != nil { return err } bucket, err := client.Bucket(opts.Bucket) if err != nil { return err } if bucket == nil { return errors.New("Bucket not found: " + opts.Bucket) } uiprogress.Start() tasks := make(chan string, o.Threads) group := sync.WaitGroup{} outDir := "." outName := "" info, err := os.Stat(o.Output) if err == nil { if info.IsDir() { outDir = o.Output } else if len(args) > 1 { return errors.New("Single (existing) output file specified for multiple targets: " + o.Output) } else { outName = o.Output } } else if os.IsNotExist(err) { parent := filepath.Dir(o.Output) info, err := os.Stat(parent) if os.IsNotExist(err) || !info.IsDir() { return errors.New("Directory does not exist: " + parent) } if len(args) > 1 { outDir = o.Output } else { outName = o.Output } } else { return err } // Create workers for i := 0; i < o.Threads; i++ { group.Add(1) go func() { for file := range tasks { fileInfo, reader, err := bucket.DownloadFileByName(file) if err != nil { fmt.Println(err) // TODO terminate on errors } name := file if outName != "" { name = outName } path := filepath.Join(outDir, name) err = download(fileInfo, reader, path, o) if err != nil { fmt.Println(err) // TODO remove file if partially downloaded? } // TODO handle termination on error } group.Done() }() } for _, file := range args { // TODO handle wildcards tasks <- file } close(tasks) group.Wait() return nil }
var err error switch arguments.request.ResponseGroup { case pbapi.ResponseGroupHighResolution: result, err = pbapi.QueryHighResolution(arguments.request) case pbapi.ResponseGroupImageDetails: result, err = pbapi.QueryImageDetails(arguments.request) default: log.Fatalf("Unknown response group: %s", arguments.request.ResponseGroup) } if err != nil { log.Fatal(err) } uiprogress.Start() wg := &sync.WaitGroup{} downloadChan := make(chan string) defer close(downloadChan) initWorkerThreads(args[0], wg, downloadChan) switch realResult := result.(type) { case *pbapi.HighResolutionResponse: for _, hit := range realResult.Hits { switch arguments.size { case og: downloadChan <- hit.ImageURL case lg: downloadChan <- hit.FullHDURL case md:
func main() { writeConfig := flag.Bool("write-config", false, "write config to project folder") readConfig := flag.Bool("read-config", true, "use project config") genLove := flag.Bool("L", false, "generate .love") genOSX := flag.Bool("O", false, "generate mac app") genWin := flag.Bool("W", false, "generate windows app") //uploadToItch := flag.Bool("itch", false, "upload releases to itch") var folder string flag.StringVar(&folder, "folder", ".", "project folder") var projectName string flag.StringVar(&projectName, "name", "project", "project name") flag.Parse() folder, err := filepath.Abs(folder) if err != nil { panic(err) } if !pathExists(filepath.Join(folder, "main.lua")) { fmt.Println("[!] didn't find main.lua") fmt.Println(" in", folder) fmt.Println(" aborting!") return } fmt.Println("wiping releases folder") os.RemoveAll(filepath.Join(folder, "releases")) ensureExists(filepath.Join(folder, "releases")) ensureExists(filepath.Join(folder, "release-downloads")) options := Options{path: folder, ProjectName: projectName} didReadConfig := false if *readConfig { if !pathExists(filepath.Join(folder, "love-release-go.json")) { fmt.Println("didnt find love-release-go.json") } else { options.readConfig() didReadConfig = true fmt.Println("reading config from file... ignoring flags") } } if !didReadConfig { options.Build.Love = *genLove options.Build.OSX = *genOSX options.Build.Win = *genWin } options.fixIntegrity() fmt.Println(options) if *writeConfig { options.writeConfig() } var wg sync.WaitGroup wg.Add(3) uiprogress.Start() go buildLove(&options, &wg) go buildWindows(&options, &wg) go buildOSX(&options, &wg) wg.Wait() time.Sleep(time.Millisecond * 100) uiprogress.Stop() close(log) { i := 0 for s := range log { if i == 0 { fmt.Println("\nWarnings:") } fmt.Println("-", s) i++ } } }