Ejemplo n.º 1
1
// Create three folders for each id
// mnt, layers, and diff
func (a *Driver) Create(id, parent, mountLabel string, storageOpt map[string]string) error {

	if len(storageOpt) != 0 {
		return fmt.Errorf("--storage-opt is not supported for aufs")
	}

	if err := a.createDirsFor(id); err != nil {
		return err
	}
	// Write the layers metadata
	f, err := os.Create(path.Join(a.rootPath(), "layers", id))
	if err != nil {
		return err
	}
	defer f.Close()

	if parent != "" {
		ids, err := getParentIds(a.rootPath(), parent)
		if err != nil {
			return err
		}

		if _, err := fmt.Fprintln(f, parent); err != nil {
			return err
		}
		for _, i := range ids {
			if _, err := fmt.Fprintln(f, i); err != nil {
				return err
			}
		}
	}

	return nil
}
Ejemplo n.º 2
1
//line fitted_type.got:17
func drawFittedTableQLetters(rSeq, qSeq alphabet.QLetters, index alphabet.Index, table []int, a [][]int) {
	tw := tabwriter.NewWriter(os.Stdout, 0, 0, 0, ' ', tabwriter.AlignRight|tabwriter.Debug)
	fmt.Printf("rSeq: %s\n", rSeq)
	fmt.Printf("qSeq: %s\n", qSeq)
	fmt.Fprint(tw, "\tqSeq\t")
	for _, l := range qSeq {
		fmt.Fprintf(tw, "%c\t", l)
	}
	fmt.Fprintln(tw)

	r, c := rSeq.Len()+1, qSeq.Len()+1
	fmt.Fprint(tw, "rSeq\t")
	for i := 0; i < r; i++ {
		if i != 0 {
			fmt.Fprintf(tw, "%c\t", rSeq[i-1].L)
		}

		for j := 0; j < c; j++ {
			p := pointerFittedQLetters(rSeq, qSeq, i, j, table, index, a, c)
			if p != "" {
				fmt.Fprintf(tw, "%s % 3v\t", p, table[i*c+j])
			} else {
				fmt.Fprintf(tw, "%v\t", table[i*c+j])
			}
		}
		fmt.Fprintln(tw)
	}
	tw.Flush()
}
Ejemplo n.º 3
0
func printColors() {
	ansi.DisableColors(false)
	stdout := colorable.NewColorableStdout()

	bgColors := []string{
		"",
		":black",
		":red",
		":green",
		":yellow",
		":blue",
		":magenta",
		":cyan",
		":white",
	}

	keys := []string{}
	for fg := range ansi.Colors {
		_, err := strconv.Atoi(fg)
		if err != nil {
			keys = append(keys, fg)
		}
	}
	sort.Strings(keys)

	for _, fg := range keys {
		for _, bg := range bgColors {
			fmt.Fprintln(stdout, padColor(fg, []string{"" + bg, "+b" + bg, "+bh" + bg, "+u" + bg}))
			fmt.Fprintln(stdout, padColor(fg, []string{"+uh" + bg, "+B" + bg, "+Bb" + bg /* backgrounds */, "" + bg + "+h"}))
			fmt.Fprintln(stdout, padColor(fg, []string{"+b" + bg + "+h", "+bh" + bg + "+h", "+u" + bg + "+h", "+uh" + bg + "+h"}))
		}
	}
}
Ejemplo n.º 4
0
func (s *SnapSuite) TestDisconnectEverythingFromSpecificSlot(c *C) {
	s.RedirectClientToTestServer(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Path {
		case "/v2/interfaces":
			c.Check(r.Method, Equals, "POST")
			c.Check(DecodedRequestBody(c, r), DeepEquals, map[string]interface{}{
				"action": "disconnect",
				"plugs": []interface{}{
					map[string]interface{}{
						"snap": "",
						"plug": "",
					},
				},
				"slots": []interface{}{
					map[string]interface{}{
						"snap": "consumer",
						"slot": "slot",
					},
				},
			})
			fmt.Fprintln(w, `{"type":"async", "status-code": 202, "change": "zzz"}`)
		case "/v2/changes/zzz":
			c.Check(r.Method, Equals, "GET")
			fmt.Fprintln(w, `{"type":"sync", "result":{"ready": true, "status": "Done"}}`)
		default:
			c.Fatalf("unexpected path %q", r.URL.Path)
		}
	})
	rest, err := Parser().ParseArgs([]string{"disconnect", "consumer:slot"})
	c.Assert(err, IsNil)
	c.Assert(rest, DeepEquals, []string{})
	c.Assert(s.Stdout(), Equals, "")
	c.Assert(s.Stderr(), Equals, "")
}
Ejemplo n.º 5
0
func printUsageErrorAndExit(message string) {
	fmt.Fprintln(os.Stderr, "ERROR:", message)
	fmt.Fprintln(os.Stderr)
	fmt.Fprintln(os.Stderr, "Available command line options:")
	flag.PrintDefaults()
	os.Exit(64)
}
Ejemplo n.º 6
0
// handleBootstrapError cleans up after a failed bootstrap.
func handleBootstrapError(err error, ctx environs.BootstrapContext, inst instance.Instance, env environs.Environ) {
	if err == nil {
		return
	}

	logger.Errorf("bootstrap failed: %v", err)
	ch := make(chan os.Signal, 1)
	ctx.InterruptNotify(ch)
	defer ctx.StopInterruptNotify(ch)
	defer close(ch)
	go func() {
		for _ = range ch {
			fmt.Fprintln(ctx.GetStderr(), "Cleaning up failed bootstrap")
		}
	}()

	if inst != nil {
		fmt.Fprintln(ctx.GetStderr(), "Stopping instance...")
		if stoperr := env.StopInstances(inst.Id()); stoperr != nil {
			logger.Errorf("cannot stop failed bootstrap instance %q: %v", inst.Id(), stoperr)
		} else {
			// set to nil so we know we can safely delete the state file
			inst = nil
		}
	}
	// We only delete the bootstrap state file if either we didn't
	// start an instance, or we managed to cleanly stop it.
	if inst == nil {
		if rmerr := bootstrap.DeleteStateFile(env.Storage()); rmerr != nil {
			logger.Errorf("cannot delete bootstrap state file: %v", rmerr)
		}
	}
}
Ejemplo n.º 7
0
func actionUserPasswd(c *cli.Context) {
	api, user := mustUserAPIAndName(c)
	ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
	currentUser, err := api.GetUser(ctx, user)
	cancel()
	if currentUser == nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
	pass, err := speakeasy.Ask("New password: "******"Error reading password:"******"Password updated\n")
}
Ejemplo n.º 8
0
func TestGetCSVFailParseSep(t *testing.T) {
	defer testRetryWhenDone().Reset()

	reqCount := 0
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if reqCount > 0 {
			w.Header().Add("Content-type", "application/json")
			fmt.Fprintln(w, `gomeetup,city`)
			fmt.Fprintln(w, `yes,Sydney`)
			fmt.Fprintln(w, `yes,San Francisco`)
			fmt.Fprintln(w, `yes,Stockholm`)
		} else {
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintln(w, `ERROR 500`)
		}
		reqCount++
	}))
	defer ts.Close()
	url := ts.URL + "/test.csv"
	defer os.Remove(getCacheFileID(url))

	want := [][]string{[]string{"gomeetup", "city"}, []string{"yes", "Sydney"}, []string{"yes", "San Francisco"}, []string{"yes", "Stockholm"}}
	have := GetCSV(",", url)
	assert.NotNil(t, have)
	if have != nil {
		assert.EqualValues(t, want, have)
	}
}
Ejemplo n.º 9
0
func (c *clusterClient) enumerate(context *cli.Context) {
	c.clusterOptions(context)
	jsonOut := context.GlobalBool("json")
	outFd := os.Stdout
	fn := "enumerate"

	cluster, err := c.manager.Enumerate()
	if err != nil {
		cmdError(context, fn, err)
		return
	}

	if jsonOut {
		fmtOutput(context, &Format{Cluster: &cluster})
	} else {
		w := new(tabwriter.Writer)
		w.Init(outFd, 12, 12, 1, ' ', 0)

		fmt.Fprintln(w, "ID\t IMAGE\t STATUS\t NAMES\t NODE")
		for _, n := range cluster.Nodes {
			for _, c := range n.Containers {
				fmt.Fprintln(w, c.ID, "\t", c.Image, "\t", c.Status, "\t",
					c.Names, "\t", n.Ip)
			}
		}

		fmt.Fprintln(w)
		w.Flush()
	}
}
Ejemplo n.º 10
0
Archivo: new.go Proyecto: huaguzi/revel
func newApp(args []string) {
	// check for proper args by count
	if len(args) == 0 {
		errorf("No import path given.\nRun 'revel help new' for usage.\n")
	}
	if len(args) > 2 {
		errorf("Too many arguments provided.\nRun 'revel help new' for usage.\n")
	}

	// checking and setting go paths
	initGoPaths()

	// checking and setting application
	setApplicationPath(args)

	// checking and setting skeleton
	setSkeletonPath(args)

	// copy files to new app directory
	copyNewAppFiles()

	// goodbye world
	fmt.Fprintln(os.Stdout, "Your application is ready:\n  ", appPath)
	fmt.Fprintln(os.Stdout, "\nYou can run it with:\n   revel run", importPath)
}
Ejemplo n.º 11
0
func main() {
	if len(os.Args) < 4 {
		fmt.Fprintln(os.Stderr, "Usage: say-phones <output> <voice>",
			"<phones ...>")
		os.Exit(1)
	}
	phones := make([]gospeech.Phone, 0, len(os.Args)-3)
	for _, str := range os.Args[3:] {
		p, err := gospeech.ParsePhone(str)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Invalid phone: "+str)
			os.Exit(1)
		}
		phones = append(phones, p)
	}
	voice, err := gospeech.LoadVoice(os.Args[2])
	if err != nil {
		fmt.Fprintln(os.Stderr, "Failed to load voice:", err)
		os.Exit(1)
	}
	sound := gospeech.SynthesizePhones(phones, voice)
	if err := wav.WriteFile(sound, os.Args[1]); err != nil {
		fmt.Fprintln(os.Stderr, "Failed to write output:", err)
		os.Exit(1)
	}
}
Ejemplo n.º 12
0
func describeServiceAccount(serviceAccount *api.ServiceAccount, tokens []api.Secret) (string, error) {
	return tabbedString(func(out io.Writer) error {
		fmt.Fprintf(out, "Name:\t%s\n", serviceAccount.Name)
		fmt.Fprintf(out, "Labels:\t%s\n", formatLabels(serviceAccount.Labels))

		if len(serviceAccount.Secrets) == 0 {
			fmt.Fprintf(out, "Secrets:\t<none>\n")
		} else {
			prefix := "Secrets:"
			for _, s := range serviceAccount.Secrets {
				fmt.Fprintf(out, "%s\t%s\n", prefix, s)
				prefix = "        "
			}
			fmt.Fprintln(out)
		}

		if len(tokens) == 0 {
			fmt.Fprintf(out, "Tokens: \t<none>\n")
		} else {
			prefix := "Tokens: "
			for _, t := range tokens {
				fmt.Fprintf(out, "%s\t%s\n", prefix, t.Name)
				prefix = "        "
			}
			fmt.Fprintln(out)
		}

		return nil
	})
}
Ejemplo n.º 13
0
func Branch(repo *libgit.Repository, args []string) {
	switch len(args) {
	case 0:
		branches, err := repo.GetBranches()
		if err != nil {
			fmt.Fprintln(os.Stderr, "Could not get list of branches.")
			return
		}
		head := getHeadBranch(repo)
		for _, b := range branches {
			if head == b {
				fmt.Print("* ")
			} else {
				fmt.Print("  ")
			}
			fmt.Println(b)
		}
	case 1:
		if head, err := getHeadId(repo); err == nil {
			if cerr := libgit.CreateBranch(repo.Path, args[0], head); cerr != nil {
				fmt.Fprintf(os.Stderr, "Could not create branch: %s\n", cerr.Error())
			}
		} else {
			fmt.Fprintf(os.Stderr, "Could not create branch: %s\n", err.Error())
		}
	default:
		fmt.Fprintln(os.Stderr, "Usage: go-git branch [branchname]")
	}

}
Ejemplo n.º 14
0
func main() {
	var bb bytes.Buffer
	fmt.Fprintf(&bb, "// go run gentest.go\n")
	fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n")
	fmt.Fprintf(&bb, "package ipv6_test\n\n")
	for _, r := range registries {
		resp, err := http.Get(r.url)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		defer resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url)
			os.Exit(1)
		}
		if err := r.parse(&bb, resp.Body); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		fmt.Fprintf(&bb, "\n")
	}
	b, err := format.Source(bb.Bytes())
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	os.Stdout.Write(b)
}
Ejemplo n.º 15
0
func (d AsyncGofunge93Debugger) Debug(ip IP) {
	inst := d.AsyncGofunge93.code[ip.Dim(1)][ip.Dim(0)];
	if d.printCoords {
		fmt.Fprintf(os.Stderr, "\n%c (%v, %v)", inst, ip.Dim(0), ip.Dim(1));
	}
	if d.printStack {
		fmt.Fprintf(os.Stderr, "\n%v", d.AsyncGofunge93.stack.v.Data());
	}
	if d.printTrace {
		fmt.Fprint(os.Stderr, "\n");
		for i, row := range d.AsyncGofunge93.code {
			if int32(i) == ip.Dim(1) {
				fmt.Fprint(os.Stderr, string(row[0:ip.Dim(0)]));
				fmt.Fprint(os.Stderr, "█");
				fmt.Fprintln(os.Stderr, string(row[ip.Dim(0)+1:len(row)]));
			}
			else {
				fmt.Fprintln(os.Stderr, string(row));
			}
		}
	}
	if d.pause {
		os.Stdin.Read(make([]byte, 1));
	}
}
Ejemplo n.º 16
0
func logSetup() {
	level, err := log.LevelInt(*f_loglevel)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	color := true
	if runtime.GOOS == "windows" {
		color = false
	}

	if *f_log {
		log.AddLogger("stdio", os.Stderr, level, color)
	}

	if *f_logfile != "" {
		err := os.MkdirAll(filepath.Dir(*f_logfile), 0755)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		logfile, err := os.OpenFile(*f_logfile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		log.AddLogger("file", logfile, level, false)
	}
}
Ejemplo n.º 17
0
func TestGetJSONFailParse(t *testing.T) {
	defer testRetryWhenDone().Reset()

	reqCount := 0
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if reqCount > 0 {
			w.Header().Add("Content-type", "application/json")
			fmt.Fprintln(w, `{"gomeetup":["Sydney", "San Francisco", "Stockholm"]}`)
		} else {
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintln(w, `ERROR 500`)
		}
		reqCount++
	}))
	defer ts.Close()
	url := ts.URL + "/test.json"
	defer os.Remove(getCacheFileID(url))

	want := map[string]interface{}{"gomeetup": []interface{}{"Sydney", "San Francisco", "Stockholm"}}
	have := GetJSON(url)
	assert.NotNil(t, have)
	if have != nil {
		assert.EqualValues(t, want, have)
	}
}
Ejemplo n.º 18
0
// Delete deletes a single FeaturepropPub record with an executor.
// Delete will match against the primary key column to find the record to delete.
func (o *FeaturepropPub) Delete(exec boil.Executor) error {
	if o == nil {
		return errors.New("chado: no FeaturepropPub provided for delete")
	}

	if err := o.doBeforeDeleteHooks(exec); err != nil {
		return err
	}

	args := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), featurepropPubPrimaryKeyMapping)
	sql := "DELETE FROM \"featureprop_pub\" WHERE \"featureprop_pub_id\"=$1"

	if boil.DebugMode {
		fmt.Fprintln(boil.DebugWriter, sql)
		fmt.Fprintln(boil.DebugWriter, args...)
	}

	_, err := exec.Exec(sql, args...)
	if err != nil {
		return errors.Wrap(err, "chado: unable to delete from featureprop_pub")
	}

	if err := o.doAfterDeleteHooks(exec); err != nil {
		return err
	}

	return nil
}
Ejemplo n.º 19
0
func main() {
	bi := bufio.NewReader(os.Stdin)
	bo := bufio.NewWriter(os.Stdout)

	var n int
	fmt.Fscanln(bi, &n)

	w := true

	for i := 0; i < n; i++ {
		var a int
		fmt.Fscan(bi, &a)
		if a/2%2 == 0 {
			w = !w
		}
	}

	if w {
		fmt.Fprintln(bo, "Daenerys")
	} else {
		fmt.Fprintln(bo, "Stannis")
	}

	bo.Flush()
}
Ejemplo n.º 20
0
func showSub(writer io.Writer, sub *Sub) {
	if sub.isInsecure {
		fmt.Fprintln(writer, "  <tr style=\"background-color:yellow\">")
	} else {
		fmt.Fprintln(writer, "  <tr>")
	}
	subURL := fmt.Sprintf("http://%s:%d/",
		strings.SplitN(sub.String(), "*", 2)[0], constants.SubPortNumber)
	fmt.Fprintf(writer, "    <td><a href=\"%s\">%s</a></td>\n", subURL, sub)
	sub.herd.showImage(writer, sub.mdb.RequiredImage, true)
	sub.herd.showImage(writer, sub.mdb.PlannedImage, false)
	sub.showBusy(writer)
	fmt.Fprintf(writer, "    <td><a href=\"showSub?%s\">%s</a></td>\n",
		sub.mdb.Hostname, sub.publishedStatus.html())
	timeNow := time.Now()
	showSince(writer, sub.pollTime, sub.startTime)
	showDuration(writer, sub.lastScanDuration, false)
	showSince(writer, timeNow, sub.lastPollSucceededTime)
	showSince(writer, timeNow, sub.lastUpdateTime)
	showSince(writer, timeNow, sub.lastSyncTime)
	showDuration(writer, sub.lastConnectDuration, false)
	showDuration(writer, sub.lastShortPollDuration, !sub.lastPollWasFull)
	showDuration(writer, sub.lastFullPollDuration, sub.lastPollWasFull)
	showDuration(writer, sub.lastComputeUpdateCpuDuration, false)
	fmt.Fprintln(writer, "  </tr>")
}
Ejemplo n.º 21
0
// Create three folders for each id
// mnt, layers, and diff
func (a *Driver) Create(id, parent string) error {
	if err := a.createDirsFor(id); err != nil {
		return err
	}
	// Write the layers metadata
	f, err := os.Create(path.Join(a.rootPath(), "layers", id))
	if err != nil {
		return err
	}
	defer f.Close()

	if parent != "" {
		ids, err := getParentIds(a.rootPath(), parent)
		if err != nil {
			return err
		}

		if _, err := fmt.Fprintln(f, parent); err != nil {
			return err
		}
		for _, i := range ids {
			if _, err := fmt.Fprintln(f, i); err != nil {
				return err
			}
		}
	}
	a.active[id] = &data{}
	return nil
}
Ejemplo n.º 22
0
func (cmd *esxcli) formatTable(res *Response) {
	fields := res.Info.Hints.Fields()

	tw := tabwriter.NewWriter(os.Stdout, len(fields), 0, 2, ' ', 0)

	var hr []string
	for _, name := range fields {
		hr = append(hr, strings.Repeat("-", len(name)))
	}

	fmt.Fprintln(tw, strings.Join(fields, "\t"))
	fmt.Fprintln(tw, strings.Join(hr, "\t"))

	for _, vals := range res.Values {
		var row []string

		for _, name := range fields {
			key := strings.Replace(name, " ", "", -1)
			if val, ok := vals[key]; ok {
				row = append(row, strings.Join(val, ", "))
			} else {
				row = append(row, "")
			}
		}

		fmt.Fprintln(tw, strings.Join(row, "\t"))
	}

	_ = tw.Flush()
}
Ejemplo n.º 23
0
func main() {
	flag.Parse()

	pkg := flag.Arg(0)

	if safeFlag && !isInternal(pkg) {
		fmt.Fprintln(os.Stderr, "Safe mode only allows unexporting objects from internal packages")
		return
	}

	// Finds all packages that import this one in the workspace
	ctxt := &build.Default
	u, err := unexporter.ForPackage(ctxt, pkg)
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		return
	}
	u.ExcludedNames = strings.Split(excludes, `,`)

	if listFlag {
		listObjects(u)
	} else if usesFlag {
		listUses(u)
	}

	if listFlag || usesFlag {
		return
	}

	if !interactiveFlag {
		u.Unexport()
	} else {
		interactiveUnexport(u)
	}
}
Ejemplo n.º 24
0
func main() {
	input := flag.Arg(0)

	if len(input) == 0 {
		fmt.Fprintln(os.Stderr, "Please provide an input file. (amberc input.amber)")
		os.Exit(1)
	}

	cmp := amber.New()
	cmp.PrettyPrint = prettyPrint
	cmp.LineNumbers = lineNumbers

	err := cmp.ParseFile(input)

	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	err = cmp.CompileWriter(os.Stdout)

	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Ejemplo n.º 25
0
func changePassword(args []string) {
	if passwd == nil {
		pw, err := gopass.GetPass("   Current password: "******"" {
			fmt.Fprintln(os.Stderr, "Invalid password")
			return
		}
	}
	services, err := loadServices(getPasswd())
	gobro.CheckErr(err, "Password invalid")
	pw2, err := gopass.GetPass("   New Password: "******"" {
		fmt.Fprintln(os.Stderr, "Invalid password")
		return
	}
	pw3, err := gopass.GetPass("   Repeat Password: "******"" {
		fmt.Fprintln(os.Stderr, "Invalid password")
		return
	}
	if pw2 != pw3 {
		fmt.Fprintln(os.Stderr, "Passwords don't match")
		return
	}
	saveServices(pw2, services)
	passwd = &pw2
}
Ejemplo n.º 26
0
func listRefresh() error {
	cli := Client()
	snaps, _, err := cli.Find(&client.FindOptions{
		Refresh: true,
	})
	if err != nil {
		return err
	}
	if len(snaps) == 0 {
		fmt.Fprintln(Stderr, i18n.G("All snaps up to date."))
		return nil
	}

	sort.Sort(snapsByName(snaps))

	w := tabWriter()
	defer w.Flush()

	fmt.Fprintln(w, i18n.G("Name\tVersion\tRev\tDeveloper\tNotes"))
	for _, snap := range snaps {
		fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", snap.Name, snap.Version, snap.Revision, snap.Developer, NotesFromRemote(snap, nil))
	}

	return nil
}
Ejemplo n.º 27
0
// This example displays the results of Dec.Round with each of the Rounders.
//
func ExampleRounder() {
	var vals = []struct {
		x string
		s inf.Scale
	}{
		{"-0.18", 1}, {"-0.15", 1}, {"-0.12", 1}, {"-0.10", 1},
		{"-0.08", 1}, {"-0.05", 1}, {"-0.02", 1}, {"0.00", 1},
		{"0.02", 1}, {"0.05", 1}, {"0.08", 1}, {"0.10", 1},
		{"0.12", 1}, {"0.15", 1}, {"0.18", 1},
	}

	var rounders = []struct {
		name    string
		rounder inf.Rounder
	}{
		{"RoundDown", inf.RoundDown}, {"RoundUp", inf.RoundUp},
		{"RoundCeil", inf.RoundCeil}, {"RoundFloor", inf.RoundFloor},
		{"RoundHalfDown", inf.RoundHalfDown}, {"RoundHalfUp", inf.RoundHalfUp},
		{"RoundHalfEven", inf.RoundHalfEven}, {"RoundExact", inf.RoundExact},
	}

	fmt.Println("The results of new(inf.Dec).Round(x, s, inf.RoundXXX):\n")
	w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
	fmt.Fprint(w, "x\ts\t|\t")
	for _, r := range rounders {
		fmt.Fprintf(w, "%s\t", r.name[5:])
	}
	fmt.Fprintln(w)
	for _, v := range vals {
		fmt.Fprintf(w, "%s\t%d\t|\t", v.x, v.s)
		for _, r := range rounders {
			x, _ := new(inf.Dec).SetString(v.x)
			z := new(inf.Dec).Round(x, v.s, r.rounder)
			fmt.Fprintf(w, "%d\t", z)
		}
		fmt.Fprintln(w)
	}
	w.Flush()

	// Output:
	// The results of new(inf.Dec).Round(x, s, inf.RoundXXX):
	//
	//      x s | Down   Up Ceil Floor HalfDown HalfUp HalfEven Exact
	//  -0.18 1 | -0.1 -0.2 -0.1  -0.2     -0.2   -0.2     -0.2 <nil>
	//  -0.15 1 | -0.1 -0.2 -0.1  -0.2     -0.1   -0.2     -0.2 <nil>
	//  -0.12 1 | -0.1 -0.2 -0.1  -0.2     -0.1   -0.1     -0.1 <nil>
	//  -0.10 1 | -0.1 -0.1 -0.1  -0.1     -0.1   -0.1     -0.1  -0.1
	//  -0.08 1 |  0.0 -0.1  0.0  -0.1     -0.1   -0.1     -0.1 <nil>
	//  -0.05 1 |  0.0 -0.1  0.0  -0.1      0.0   -0.1      0.0 <nil>
	//  -0.02 1 |  0.0 -0.1  0.0  -0.1      0.0    0.0      0.0 <nil>
	//   0.00 1 |  0.0  0.0  0.0   0.0      0.0    0.0      0.0   0.0
	//   0.02 1 |  0.0  0.1  0.1   0.0      0.0    0.0      0.0 <nil>
	//   0.05 1 |  0.0  0.1  0.1   0.0      0.0    0.1      0.0 <nil>
	//   0.08 1 |  0.0  0.1  0.1   0.0      0.1    0.1      0.1 <nil>
	//   0.10 1 |  0.1  0.1  0.1   0.1      0.1    0.1      0.1   0.1
	//   0.12 1 |  0.1  0.2  0.2   0.1      0.1    0.1      0.1 <nil>
	//   0.15 1 |  0.1  0.2  0.2   0.1      0.1    0.2      0.2 <nil>
	//   0.18 1 |  0.1  0.2  0.2   0.1      0.2    0.2      0.2 <nil>

}
Ejemplo n.º 28
0
func (f textResultFormatter) format(result testResult) error {

	if _, err := fmt.Fprintf(f.w, "- %s\t(category: %s)\t[%s]\t(%v)\n", result.Path, result.Category, result.Result, result.Duration); err != nil {
		return err
	}

	// Output log messages if we failed
	if result.isFailure() {
		if result.Message != "" {
			if _, err := fmt.Fprintf(f.w, " ERROR in %s: %s\n", result.FailPoint, result.Message); err != nil {
				return err
			}
		}
		if result.Log != nil && len(result.Log) > 0 {
			fmt.Fprintln(f.w, "  Messages:")
			for _, msg := range result.Log {
				if _, err := fmt.Fprintln(f.w, "  ", msg); err != nil {
					return err
				}
			}
		}

		fmt.Fprintln(f.w, "")

	}

	return f.w.Flush()
}
Ejemplo n.º 29
0
func print256Colors() {
	ansi.DisableColors(false)
	stdout := colorable.NewColorableStdout()

	bgColors := []string{""}
	for i := 0; i < 256; i++ {
		key := fmt.Sprintf(":%d", i)
		bgColors = append(bgColors, key)
	}

	keys := []string{}
	for fg := range ansi.Colors {
		n, err := strconv.Atoi(fg)
		if err == nil {
			keys = append(keys, fmt.Sprintf("%3d", n))
		}
	}
	sort.Strings(keys)

	for _, fg := range keys {
		for _, bg := range bgColors {
			fmt.Fprintln(stdout, padColor(fg, []string{"" + bg, "+b" + bg, "+u" + bg}))
			fmt.Fprintln(stdout, padColor(fg, []string{"+B" + bg, "+Bb" + bg}))
		}
	}
}
Ejemplo n.º 30
0
func raw_tx(w http.ResponseWriter, r *http.Request) {
	if !ipchecker(r) {
		return
	}

	defer func() {
		if r := recover(); r != nil {
			fmt.Fprintln(w, "Error")
			if err, ok := r.(error); ok {
				fmt.Fprintln(w, err.Error())
			}
		}
	}()

	r.ParseForm()
	if len(r.Form["id"]) == 0 {
		fmt.Println("No id given")
		return
	}

	txid := btc.NewUint256FromString(r.Form["id"][0])
	fmt.Fprintln(w, "TxID:", txid.String())
	if tx, ok := network.TransactionsToSend[txid.Hash]; ok {
		s, _, _, _, _ := usif.DecodeTx(tx.Tx)
		w.Write([]byte(s))
	} else {
		fmt.Fprintln(w, "Not found")
	}
}