Example #1
1
func xmlToSocketLogWriter(filename string, props []xmlProperty, enabled bool) (SocketLogWriter, bool) {
	endpoint := ""
	protocol := "udp"

	for _, prop := range props {
		switch prop.Name {
		case "endpoint":
			endpoint = strings.Trim(prop.Value, " \r\n")
		case "protocol":
			protocol = strings.Trim(prop.Value, " \r\n")
		default:
			fmt.Fprintf(os.Stderr, "LoadConfiguration: Warning: Unknown property \"%s\" for file filter in %s\n", prop.Name, filename)
		}
	}

	if len(endpoint) == 0 {
		fmt.Fprintf(os.Stderr, "LoadConfiguration: Error: Required property \"%s\" for file filter missing in %s\n", "endpoint", filename)
		return nil, false
	}

	if !enabled {
		return nil, true
	}

	return NewSocketLogWriter(protocol, endpoint), true
}
Example #2
1
// identityConfig initializes a new identity.
func identityConfig(out io.Writer, nbits int) (Identity, error) {
	// TODO guard higher up
	ident := Identity{}
	if nbits < 1024 {
		return ident, errors.New("Bitsize less than 1024 is considered unsafe.")
	}

	fmt.Fprintf(out, "generating %v-bit RSA keypair...", nbits)
	sk, pk, err := ci.GenerateKeyPair(ci.RSA, nbits)
	if err != nil {
		return ident, err
	}
	fmt.Fprintf(out, "done\n")

	// currently storing key unencrypted. in the future we need to encrypt it.
	// TODO(security)
	skbytes, err := sk.Bytes()
	if err != nil {
		return ident, err
	}
	ident.PrivKey = base64.StdEncoding.EncodeToString(skbytes)

	id, err := peer.IDFromPublicKey(pk)
	if err != nil {
		return ident, err
	}
	ident.PeerID = id.Pretty()
	fmt.Fprintf(out, "peer identity: %s\n", ident.PeerID)
	return ident, nil
}
Example #3
1
func (p *Addr) printText(w io.Writer, codeblockEnd int) {
	switch p.Type {
	case None:
	case Reg, Xmm:
		name := p.Value.(Register).String()
		io.WriteString(w, name)
	case Ind:
		name := p.Value.(Register).String()
		if p.Disp != 0 {
			fmt.Fprintf(w, "%x+(%s)", p.Disp, name)
		} else {
			fmt.Fprintf(w, "(%s)", name)
		}
	case Rel8, Rel16, Rel32:
		if codeblockEnd != 0 {
			// We know where we are, print the absolute jump point.
			blk := int64(codeblockEnd) + p.valueInt64()
			fmt.Fprintf(w, "%s:(%06x)", p.Name, blk)
		} else {
			fmt.Fprintf(w, "%s:(%x)", p.Name, p.Value)
		}
	case Imm8, Imm16, Imm32, Imm64:
		fmt.Fprintf(w, "0x%x", p.Value)
	case Label:
		fmt.Fprint(w, p.Name)
	default:
		panic(fmt.Sprintf("unknown addr type: %v", p.Type))
	}
}
Example #4
1
func check_fatal(err error) {
	if err != nil {
		fmt.Fprintf(os.Stderr, "**** KURWA!!! ****\n")
		fmt.Fprintf(os.Stderr, "Error encountered was of FATAL. Is of wrong. Gib correct config pl0x.\n")
		panic(err)
	}
}
func postscript(out *bytes.Buffer, name string) {
	fmt.Fprintf(out, "__start_%s()\n", name)
	fmt.Fprintf(out, `{
    local cur prev words cword split
    _init_completion -s || return

    local completions_func
    local c=0
    local flags=()
    local two_word_flags=()
    local flags_with_completion=()
    local flags_completion=()
    local commands=("%s")
    local must_have_one_flag=()
    local must_have_one_noun=()
    local last_command
    local nouns=()

    __handle_word
}

`, name)
	fmt.Fprintf(out, "complete -F __start_%s %s\n", name, name)
	fmt.Fprintf(out, "# ex: ts=4 sw=4 et filetype=sh\n")
}
Example #6
1
File: hand.go Project: bryanwb/kh
func (f *FingerClient) Execute() error {
	f.finger.Start()
	defer f.finger.Stop()
	resp := new(Response)
	Logger.Debugf("Executing finger %s", f.Path)
	methodName := "Finger.Execute"
	if f.args.Flags.Help {
		methodName = "Finger.Help"
	}
	if err := f.finger.Call(methodName, f.args, &resp); err != nil {
		Logger.Debugf(resp.SprintLog())
		return err
	}
	stdout := resp.SprintStdout()
	stderr := resp.SprintStderr()
	fingerLog := resp.SprintLog()
	if stdout != "" {
		fmt.Println(stdout)
	}
	if stderr != "" {
		fmt.Fprintf(os.Stderr, stderr+"\n")
	}
	if fingerLog != "" {
		fmt.Fprintf(os.Stderr, fingerLog+"\n")
	}
	return nil
}
Example #7
1
func urlShortenerMain(client *http.Client, argv []string) {
	if len(argv) != 1 {
		fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx     (to look up details)\n")
		fmt.Fprintf(os.Stderr, "       urlshortener http://example.com/long (to shorten)\n")
		return
	}

	svc, _ := urlshortener.New(client)
	urlstr := argv[0]

	// short -> long
	if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
		url, err := svc.Url.Get(urlstr).Do()
		if err != nil {
			log.Fatalf("URL Get: %v", err)
		}
		fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
		return
	}

	// long -> short
	url, err := svc.Url.Insert(&urlshortener.Url{
		Kind:    "urlshortener#url", // Not really needed
		LongUrl: urlstr,
	}).Do()
	if err != nil {
		log.Fatalf("URL Insert: %v", err)
	}
	fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
}
Example #8
1
// describeObjects prints out information about the objects of a template
func (d *TemplateDescriber) describeObjects(objects []runtime.Object, out *tabwriter.Writer) {
	formatString(out, "Objects", " ")
	indent := "    "
	for _, obj := range objects {
		if d.ObjectDescriber != nil {
			output, err := d.DescribeObject(obj)
			if err != nil {
				fmt.Fprintf(out, "error: %v\n", err)
				continue
			}
			fmt.Fprint(out, output)
			fmt.Fprint(out, "\n")
			continue
		}

		_, kind, _ := d.ObjectTyper.ObjectVersionAndKind(obj)
		meta := kapi.ObjectMeta{}
		meta.Name, _ = d.MetadataAccessor.Name(obj)
		fmt.Fprintf(out, fmt.Sprintf("%s%s\t%s\n", indent, kind, meta.Name))
		//meta.Annotations, _ = d.MetadataAccessor.Annotations(obj)
		//meta.Labels, _ = d.MetadataAccessor.Labels(obj)
		/*if len(meta.Labels) > 0 {
			formatString(out, indent+"Labels", formatLabels(meta.Labels))
		}
		formatAnnotations(out, meta, indent)*/
	}
}
Example #9
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()
}
Example #10
0
// Single mode writes a single condensed line.  Used for debugging comparison with tester/tester.
func (p *props) writeSingle(w io.Writer) {
	fmt.Fprintf(w, `"0","0","1","%d","0","%s",`, p.ftype, escape(p.fname))
	fmt.Fprintf(w, `"%x","%x",`, p.ident, p.dident)
	fmt.Fprintf(w, `"%s","%s","%s",`, p.ext, p.mime, escape(p.bname))
	fmt.Fprintf(w, `"%x",`, p.chash)
	fmt.Fprintf(w, "\"%d\",\"%d\",\"%d\"\n", p.size, p.isize.X, p.isize.Y)
}
Example #11
0
func (c *AppRemove) Run(context *cmd.Context, client cmd.Doer) error {
	appName, err := c.Guess()
	if err != nil {
		return err
	}
	var answer string
	if !*tsuru.AssumeYes {
		fmt.Fprintf(context.Stdout, `Are you sure you want to remove app "%s"? (y/n) `, appName)
		fmt.Fscanf(context.Stdin, "%s", &answer)
		if answer != "y" {
			fmt.Fprintln(context.Stdout, "Abort.")
			return nil
		}
	}
	url := cmd.GetUrl(fmt.Sprintf("/apps/%s", appName))
	request, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		return err
	}
	_, err = client.Do(request)
	if err != nil {
		return err
	}
	fmt.Fprintf(context.Stdout, `App "%s" successfully removed!`+"\n", appName)
	return nil
}
Example #12
0
func (c *AppCreate) Run(context *cmd.Context, client cmd.Doer) error {
	appName := context.Args[0]
	framework := context.Args[1]

	b := bytes.NewBufferString(fmt.Sprintf(`{"name":"%s", "framework":"%s"}`, appName, framework))
	request, err := http.NewRequest("POST", cmd.GetUrl("/apps"), b)
	request.Header.Set("Content-Type", "application/json")
	if err != nil {
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	out := make(map[string]string)
	err = json.Unmarshal(result, &out)
	if err != nil {
		return err
	}
	fmt.Fprintf(context.Stdout, `App "%s" is being created!`+"\n", appName)
	fmt.Fprint(context.Stdout, "Check its status with app-list.\n")
	fmt.Fprintf(context.Stdout, `Your repository for "%s" project is "%s"`+"\n", appName, out["repository_url"])
	return nil
}
Example #13
0
// Load loads the source into the config defined by struct s
func (f *FlagLoader) Load(s interface{}) error {
	strct := structs.New(s)
	structName := strct.Name()

	flagSet := flag.NewFlagSet(structName, flag.ExitOnError)
	f.flagSet = flagSet

	for _, field := range strct.Fields() {
		f.processField(field.Name(), field)
	}

	flagSet.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		flagSet.PrintDefaults()
		fmt.Fprintf(os.Stderr, "\nGenerated environment variables:\n")
		e := &EnvironmentLoader{
			Prefix:    f.EnvPrefix,
			CamelCase: f.CamelCase,
		}
		e.PrintEnvs(s)
		fmt.Println("")
	}

	args := os.Args[1:]
	if f.Args != nil {
		args = f.Args
	}

	return flagSet.Parse(args)
}
Example #14
0
// mkzcgo writes zcgo.go for the go/build package:
//
//	package build
//  var cgoEnabled = map[string]bool{}
//
// It is invoked to write go/build/zcgo.go.
func mkzcgo(dir, file string) {
	// sort for deterministic zcgo.go file
	var list []string
	for plat, hasCgo := range cgoEnabled {
		if hasCgo {
			list = append(list, plat)
		}
	}
	sort.Strings(list)

	var buf bytes.Buffer

	fmt.Fprintf(&buf,
		"// auto generated by go tool dist\n"+
			"\n"+
			"package build\n"+
			"\n"+
			"var cgoEnabled = map[string]bool{\n")
	for _, plat := range list {
		fmt.Fprintf(&buf, "\t%q: true,\n", plat)
	}
	fmt.Fprintf(&buf, "}")

	writefile(buf.String(), file, writeSkipSame)
}
Example #15
0
// Create a new DNS info provider.
func ExampleNewDNSInfoProvider() {

	// create a DNS client
	credentials := APICredentials{"*****@*****.**", "ApItOken"}
	dnsClient, clientError := NewDNSClient(credentials)
	if clientError != nil {
		fmt.Fprintf(os.Stderr, "Unable to create DNS client: %s", clientError.Error())
		os.Exit(1)
	}

	// create a new DNS info provider instance
	dnsInfoProvider := NewDNSInfoProvider(dnsClient)

	// get all domain names
	domainNames, domainNamesError := dnsInfoProvider.GetDomainNames()
	if domainNamesError != nil {
		fmt.Fprintf(os.Stderr, "Unable to fetch domain names: %s", domainNamesError.Error())
		os.Exit(1)
	}

	// print a list all domain names
	for _, domainName := range domainNames {
		fmt.Fprintf(os.Stdout, "%s\n", domainName)
	}
}
Example #16
0
func verifyCertWithSystem(block *pem.Block, add func(*Certificate)) {
	data := pem.EncodeToMemory(block)
	var cmd *exec.Cmd
	if needsTmpFiles() {
		f, err := ioutil.TempFile("", "cert")
		if err != nil {
			fmt.Fprintf(os.Stderr, "can't create temporary file for cert: %v", err)
			return
		}
		defer os.Remove(f.Name())
		if _, err := f.Write(data); err != nil {
			fmt.Fprintf(os.Stderr, "can't write temporary file for cert: %v", err)
			return
		}
		if err := f.Close(); err != nil {
			fmt.Fprintf(os.Stderr, "can't write temporary file for cert: %v", err)
			return
		}
		cmd = exec.Command("/usr/bin/security", "verify-cert", "-c", f.Name(), "-l")
	} else {
		cmd = exec.Command("/usr/bin/security", "verify-cert", "-c", "/dev/stdin", "-l")
		cmd.Stdin = bytes.NewReader(data)
	}
	if cmd.Run() == nil {
		// Non-zero exit means untrusted
		cert, err := ParseCertificate(block.Bytes)
		if err != nil {
			return
		}

		add(cert)
	}
}
Example #17
0
File: print.go Project: zDpxq6/go
func write(buf *bytes.Buffer, e Expr) {
	switch e := e.(type) {
	case literal:
		fmt.Fprintf(buf, "%g", e)

	case Var:
		fmt.Fprintf(buf, "%s", e)

	case unary:
		fmt.Fprintf(buf, "(%c", e.op)
		write(buf, e.x)
		buf.WriteByte(')')

	case binary:
		buf.WriteByte('(')
		write(buf, e.x)
		fmt.Fprintf(buf, " %c ", e.op)
		write(buf, e.y)
		buf.WriteByte(')')

	case call:
		fmt.Fprintf(buf, "%s(", e.fn)
		for i, arg := range e.args {
			if i > 0 {
				buf.WriteString(", ")
			}
			write(buf, arg)
		}
		buf.WriteByte(')')

	default:
		panic(fmt.Sprintf("unknown Expr: %T", e))
	}
}
Example #18
0
// Print command line help and exit application
func usage() {
	fmt.Fprintf(os.Stderr,
		"Usage: domainerator [flags] [prefixes wordlist] [suffixes wordlist] [output file]\n")
	fmt.Fprintf(os.Stderr, "\nFlags:\n")
	flag.PrintDefaults()
	os.Exit(1)
}
func writeListOfPins(w io.Writer, name string, pinNames []string) {
	fmt.Fprintf(w, "static const char* const %s[] = {\n", name)
	for _, pinName := range pinNames {
		fmt.Fprintf(w, "  kSPKIHash_%s,\n", pinName)
	}
	fmt.Fprintf(w, "  NULL,\n};\n")
}
Example #20
0
// buildBenchmark builds the benchmark binary.
func (b *Builder) buildBenchmark(workpath string, update bool) (benchBin, log string, err error) {
	goroot := filepath.Join(workpath, "go")
	gobin := filepath.Join(goroot, "bin", "go") + exeExt
	gopath := filepath.Join(*buildroot, "gopath")
	env := append([]string{
		"GOROOT=" + goroot,
		"GOPATH=" + gopath},
		b.envv()...)
	// First, download without installing.
	args := []string{"get", "-d"}
	if update {
		args = append(args, "-u")
	}
	args = append(args, *benchPath)
	var buildlog bytes.Buffer
	runOpts := []runOpt{runTimeout(*buildTimeout), runEnv(env), allOutput(&buildlog), runDir(workpath)}
	err = run(exec.Command(gobin, args...), runOpts...)
	if err != nil {
		fmt.Fprintf(&buildlog, "go get -d %s failed: %s", *benchPath, err)
		return "", buildlog.String(), err
	}
	// Then, build into workpath.
	benchBin = filepath.Join(workpath, "benchbin") + exeExt
	args = []string{"build", "-o", benchBin, *benchPath}
	buildlog.Reset()
	err = run(exec.Command(gobin, args...), runOpts...)
	if err != nil {
		fmt.Fprintf(&buildlog, "go build %s failed: %s", *benchPath, err)
		return "", buildlog.String(), err
	}
	return benchBin, "", nil
}
Example #21
0
File: out.go Project: jnwhiteh/go
// writeOutput creates stubs for a specific source file to be compiled by 6g
// (The comments here say 6g and 6c but the code applies to the 8 and 5 tools too.)
func (p *Package) writeOutput(f *File, srcfile string) {
	base := srcfile
	if strings.HasSuffix(base, ".go") {
		base = base[0 : len(base)-3]
	}
	base = strings.Map(slashToUnderscore, base)
	fgo1 := creat("_obj/" + base + ".cgo1.go")
	fgcc := creat("_obj/" + base + ".cgo2.c")

	p.GoFiles = append(p.GoFiles, base+".cgo1.go")
	p.GccFiles = append(p.GccFiles, base+".cgo2.c")

	// Write Go output: Go input with rewrites of C.xxx to _C_xxx.
	fmt.Fprintf(fgo1, "// Created by cgo - DO NOT EDIT\n\n")
	fmt.Fprintf(fgo1, "//line %s:1\n", srcfile)
	printer.Fprint(fgo1, fset, f.AST)

	// While we process the vars and funcs, also write 6c and gcc output.
	// Gcc output starts with the preamble.
	fmt.Fprintf(fgcc, "%s\n", f.Preamble)
	fmt.Fprintf(fgcc, "%s\n", gccProlog)

	for _, n := range f.Name {
		if n.FuncType != nil {
			p.writeOutputFunc(fgcc, n)
		}
	}

	fgo1.Close()
	fgcc.Close()
}
Example #22
0
func printHelpCommand(preamble interface{}) {
	if preamble != nil {
		fmt.Fprintf(os.Stdout, "%s\n%s\n", preamble, HELP_MESSAGE)
	} else {
		fmt.Fprintf(os.Stdout, "%s\n", HELP_MESSAGE)
	}
}
Example #23
0
// WriteGPX writes samples to w in GPX format.
func WriteGPX(w io.Writer, samples []Sample) error {
	if _, err := fmt.Fprintf(w, ""+
		"<gpx version=\"1.1\" creator=\"https://github.com/twpayne/go-doarama\">"+
		"<trk>"+
		"<trkseg>"); err != nil {
		return err
	}
	for _, s := range samples {
		if _, err := fmt.Fprintf(w, ""+
			"<trkpt lat=\"%f\" lon=\"%f\">"+
			"<ele>%f</ele>"+
			"<time>%s</time>"+
			"</trkpt>",
			s.Coords.Latitude, s.Coords.Longitude,
			s.Coords.Altitude,
			s.Time.Time().Format("2006-01-02T15:04:05Z")); err != nil {
			return err
		}
	}
	if _, err := fmt.Fprintf(w, ""+
		"</trkseg>"+
		"</trk>"+
		"</gpx>"); err != nil {
		return err
	}
	return nil
}
Example #24
0
func (f *FlagSet) AddFlag(flag *Flag) {
	_, alreadythere := f.formal[flag.Name]
	if alreadythere {
		msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
		fmt.Fprintln(f.out(), msg)
		panic(msg) // Happens only if flags are declared with identical names
	}
	if f.formal == nil {
		f.formal = make(map[string]*Flag)
	}
	f.formal[flag.Name] = flag

	if len(flag.Shorthand) == 0 {
		return
	}
	if len(flag.Shorthand) > 1 {
		fmt.Fprintf(f.out(), "%s shorthand more than ASCII character: %s\n", f.name, flag.Shorthand)
		panic("shorthand is more than one character")
	}
	if f.shorthands == nil {
		f.shorthands = make(map[byte]*Flag)
	}
	c := flag.Shorthand[0]
	old, alreadythere := f.shorthands[c]
	if alreadythere {
		fmt.Fprintf(f.out(), "%s shorthand reused: %q for %s already used for %s\n", f.name, c, flag.Name, old.Name)
		panic("shorthand redefinition")
	}
	f.shorthands[c] = flag
}
func writeRequiredNoun(cmd *Command, out *bytes.Buffer) {
	fmt.Fprintf(out, "    must_have_one_noun=()\n")
	sort.Sort(sort.StringSlice(cmd.ValidArgs))
	for _, value := range cmd.ValidArgs {
		fmt.Fprintf(out, "    must_have_one_noun+=(%q)\n", value)
	}
}
Example #26
0
func createHelpCommand(com *Comandante, w io.Writer) *Command {
	action := func() error {
		// The first parameter passed to the help command should be the
		// command for requested documentation.
		if len(os.Args) < 3 {
			com.printDefaultHelp(w)
		} else {
			cmdName := os.Args[2]
			cmd := com.getCommand(cmdName)

			if cmd != nil && cmdName != "help" {
				fmt.Fprintf(w, "%s %s\n%s", com.binaryName, cmdName, cmd.Documentation)

				if cmd.FlagInit != nil {
					cmd.FlagInit(&cmd.flagSet)

					fmt.Fprintf(w, "\noptions\n")

					cmd.flagSet.SetOutput(w)
					cmd.flagSet.PrintDefaults()
				}
			} else {
				com.printDefaultHelp(w)
			}
		}

		return nil
	}

	cmd := NewCommand("help", "get more information about a command", action)
	return cmd
}
Example #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>

}
Example #28
0
func runLsRanges(cmd *cobra.Command, args []string) {
	if len(args) > 1 {
		mustUsage(cmd)
		return
	}
	var startKey proto.Key
	if len(args) >= 1 {
		startKey = keys.RangeMetaKey(proto.Key(args[0]))
	} else {
		startKey = keys.Meta2Prefix
	}

	kvDB, stopper := makeDBClient()
	defer stopper.Stop()
	rows, err := kvDB.Scan(startKey, keys.Meta2Prefix.PrefixEnd(), maxResults)
	if err != nil {
		fmt.Fprintf(os.Stderr, "scan failed: %s\n", err)
		osExit(1)
		return
	}

	for _, row := range rows {
		desc := &proto.RangeDescriptor{}
		if err := row.ValueProto(desc); err != nil {
			fmt.Fprintf(os.Stderr, "%s: unable to unmarshal range descriptor\n", row.Key)
			continue
		}
		fmt.Printf("%s-%s [%d]\n", desc.StartKey, desc.EndKey, desc.RangeID)
		for i, replica := range desc.Replicas {
			fmt.Printf("\t%d: node-id=%d store-id=%d\n",
				i, replica.NodeID, replica.StoreID)
		}
	}
	fmt.Printf("%d result(s)\n", len(rows))
}
Example #29
0
// HandleListObjectsInfoSuccessfully creates an HTTP handler at `/testContainer` on the test handler mux that
// responds with a `List` response when full info is requested.
func HandleListObjectsInfoSuccessfully(t *testing.T) {
	th.Mux.HandleFunc("/testContainer", func(w http.ResponseWriter, r *http.Request) {
		th.TestMethod(t, r, "GET")
		th.TestHeader(t, r, "X-Auth-Token", fake.TokenID)
		th.TestHeader(t, r, "Accept", "application/json")

		w.Header().Set("Content-Type", "application/json")
		r.ParseForm()
		marker := r.Form.Get("marker")
		switch marker {
		case "":
			fmt.Fprintf(w, `[
      {
        "hash": "451e372e48e0f6b1114fa0724aa79fa1",
        "last_modified": "2009-11-10 23:00:00 +0000 UTC",
        "bytes": 14,
        "name": "goodbye",
        "content_type": "application/octet-stream"
      },
      {
        "hash": "451e372e48e0f6b1114fa0724aa79fa1",
        "last_modified": "2009-11-10 23:00:00 +0000 UTC",
        "bytes": 14,
        "name": "hello",
        "content_type": "application/octet-stream"
      }
    ]`)
		case "hello":
			fmt.Fprintf(w, `[]`)
		default:
			t.Fatalf("Unexpected marker: [%s]", marker)
		}
	})
}
Example #30
0
File: index.go Project: hfeeki/go
func testExpr(b *bufio.Writer, expr string) {
	if *pass == 0 {
		fmt.Fprintf(b, "\ttest(func(){use(%s)}, %q)\n", expr, expr)
	} else {
		fmt.Fprintf(b, "\tuse(%s)  // ERROR \"index|overflow\"\n", expr)
	}
}