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 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 torrentBar(t *torrent.Torrent) { bar := uiprogress.AddBar(1) bar.AppendCompleted() bar.AppendFunc(func(*uiprogress.Bar) (ret string) { select { case <-t.GotInfo(): default: return "getting info" } if t.Seeding() { return "seeding" } else if t.BytesCompleted() == t.Info().TotalLength() { return "completed" } else { return fmt.Sprintf("downloading (%s/%s)", humanize.Bytes(uint64(t.BytesCompleted())), humanize.Bytes(uint64(t.Info().TotalLength()))) } }) bar.PrependFunc(func(*uiprogress.Bar) string { return t.Name() }) go func() { <-t.GotInfo() bar.Total = int(t.Info().TotalLength()) for { bc := t.BytesCompleted() bar.Set(int(bc)) time.Sleep(time.Second) } }() }
func downloadImage(u, output string) error { url, err := url.Parse(u) if err != nil { return err } _, filename := filepath.Split(url.Path) out, err := os.Create(filepath.Join(output, filename)) if err != nil { return err } defer out.Close() resp, err := http.Get(u) if err != nil { return err } defer resp.Body.Close() sum := 0 bar := uiprogress.AddBar(int(resp.ContentLength)).AppendCompleted().PrependElapsed() bar.PrependFunc(func(b *uiprogress.Bar) string { return strutil.Resize(humanize.Bytes(uint64(sum))+"/"+humanize.Bytes(uint64(resp.ContentLength))+" "+filename+": ", 42) }) for { written, err := io.CopyN(out, resp.Body, 4096) sum += int(written) bar.Set(sum) if err != nil { return err } } }
func (p *Pomodoro) Run(duration int) bool { tick := time.NewTicker(time.Second / 10) p.running = true p.bar = uiprogress.AddBar(10 * duration).AppendCompleted().PrependElapsed() /*.PrependFunc(func(b *uiprogress.Bar) string { return p.msg + ": " })*/ defer func() { tick.Stop() p.running = false p.done = make(chan struct{}, 0) }() for { select { case <-tick.C: p.bar.Set(p.bar.Current() + 1) if p.bar.Current() >= 10*duration { p.running = false close(p.done) return true } case <-p.done: return false } } }
func newBar(name string, steps int) *BuildBar { buildBar := BuildBar{name: name} bar := uiprogress.AddBar(steps).AppendCompleted() bar.PrependFunc(func(b *uiprogress.Bar) string { return strutil.Resize(buildBar.name+": "+buildBar.currentStep, 20) }) buildBar.bar = bar return &buildBar }
// 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 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 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() { 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 ExampleDecoratorFunc() { var steps = []string{"downloading source", "installing deps", "compiling", "packaging", "seeding database", "deploying", "staring servers"} bar := uiprogress.AddBar(len(steps)) // prepend the current step to the bar bar.PrependFunc(func(b *uiprogress.Bar) string { return "app: " + steps[b.Current()-1] }) for bar.Incr() { time.Sleep(time.Millisecond) } }
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 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() }
func deploy(app string, wg *sync.WaitGroup) { defer wg.Done() bar := uiprogress.AddBar(len(steps)).AppendCompleted().PrependElapsed() bar.Width = 100 // prepend the deploy step to the bar bar.PrependFunc(func(b *uiprogress.Bar) string { return strutil.Resize(app+": "+steps[b.Current()-1], 22) }) rand.Seed(500) for bar.Incr() { time.Sleep(time.Millisecond * time.Duration(rand.Intn(2000))) } }
func upload(bucket *backblaze.Bucket, file string, meta map[string]string) (*backblaze.File, error) { stat, err := os.Stat(file) if err != nil { return nil, err } reader, err := os.Open(file) if err != nil { return nil, err } defer reader.Close() var r io.Reader = reader if opts.Verbose { bar := uiprogress.AddBar(int(stat.Size())) // TODO Stop bar refresh when complete if stat.Size() > 1024*100 { start := time.Now() elapsed := time.Duration(1) count := 0 bar.AppendFunc(func(b *uiprogress.Bar) string { count++ if count < 2 { return "" } // elapsed := b.TimeElapsed() if b.Current() < b.Total { elapsed = time.Now().Sub(start) } speed := uint64(float64(b.Current()) / elapsed.Seconds()) return humanize.IBytes(speed) + "/sec" }) } bar.AppendCompleted() bar.PrependFunc(func(b *uiprogress.Bar) string { return fmt.Sprintf("%10s", humanize.IBytes(uint64(b.Total))) }) bar.PrependFunc(func(b *uiprogress.Bar) string { return strutil.Resize(file, 50) }) bar.Width = 20 r = &progressReader{bar, reader} } return bucket.UploadFile(filepath.Base(file), meta, r) }
func download(fileInfo *backblaze.File, reader io.ReadCloser, path string) error { defer reader.Close() err := os.MkdirAll(filepath.Dir(path), 0777) if err != nil { return err } writer, err := os.Create(path) if err != nil { return err } defer writer.Close() var w io.Writer = writer if opts.Verbose { bar := uiprogress.AddBar(int(fileInfo.ContentLength)) bar.AppendFunc(func(b *uiprogress.Bar) string { speed := (float32(b.Current()) / 1024) / float32(b.TimeElapsed().Seconds()) return fmt.Sprintf("%7.2f KB/s", speed) }) bar.AppendCompleted() bar.PrependFunc(func(b *uiprogress.Bar) string { return fmt.Sprintf("%10d", b.Total) }) bar.PrependFunc(func(b *uiprogress.Bar) string { return strutil.Resize(fileInfo.Name, 50) }) bar.Width = 20 w = &progressWriter{bar, writer} } sha := sha1.New() tee := io.MultiWriter(sha, w) _, err = io.Copy(tee, reader) if err != nil { return err } // Check SHA sha1Hash := hex.EncodeToString(sha.Sum(nil)) if sha1Hash != fileInfo.ContentSha1 { return errors.New("Downloaded data does not match SHA1 hash") } return nil }
func download(fileInfo *backblaze.File, reader io.ReadCloser, path string, o *Get) error { defer reader.Close() var writer = ioutil.Discard if !o.Discard { err := os.MkdirAll(filepath.Dir(path), 0777) if err != nil { return err } file, err := os.Create(path) if err != nil { return err } defer file.Close() writer = file } if opts.Verbose { bar := uiprogress.AddBar(int(fileInfo.ContentLength)) if fileInfo.ContentLength > 1024*100 { start := time.Now() elapsed := time.Duration(1) count := 0 bar.AppendFunc(func(b *uiprogress.Bar) string { count++ if count < 2 { return "" } // elapsed := b.TimeElapsed() if b.Current() < b.Total { elapsed = time.Now().Sub(start) } speed := uint64(float64(b.Current()) / elapsed.Seconds()) return humanize.IBytes(speed) + "/sec" }) } bar.AppendCompleted() bar.PrependFunc(func(b *uiprogress.Bar) string { return fmt.Sprintf("%10s", humanize.IBytes(uint64(b.Total))) }) bar.PrependFunc(func(b *uiprogress.Bar) string { return strutil.Resize(fileInfo.Name, 50) }) bar.Width = 20 writer = &progressWriter{bar, writer} } sha := sha1.New() tee := io.MultiWriter(sha, writer) _, err := io.Copy(tee, reader) if err != nil { return err } // Check SHA sha1Hash := hex.EncodeToString(sha.Sum(nil)) if sha1Hash != fileInfo.ContentSha1 { return errors.New("Downloaded data does not match SHA1 hash") } return nil }
if err != nil { log.Debug(err.Error()) log.Error("Could not deploy script") } if err != nil { log.Fatal(err.Error()) } log.Infof("Script deployed to %d mailboxes (%d bytes)", len(resp.Mailboxes), len(data)) log.Infof("Deployment name: %s", resp.Deployment) if cmd.Flag("no-results").Value.String() == "true" { return } bar := uiprogress.AddBar(len(resp.Mailboxes)) bar.AppendCompleted() bar.PrependElapsed() uiprogress.Start() var pollStart = time.Now() stats, err := client.PollDeployment(resp.Deployment, func(stats *api.DeploymentStats) bool { messagesProcessed := stats.MessageCount - stats.PendingCount bar.Set(int(messagesProcessed)) if time.Since(pollStart) > time.Duration(deployTimeout)*time.Second { return false } if stats.PendingCount == 0 { return false } else { return true