Golang flag.Uint64类(方法)实例源码

下面列出了Golang flag.Uint64 类(方法)源码代码实例,从而了解它的用法。

作者:goatcm    项目:goat-cor   
func decodeRefArg(name, typeName string) (interface{}, error) {
	switch strings.ToLower(typeName) {
	case "*bool":
		newValue := flag.Bool(name, app.DefaultBoolValue, name)
		return newValue, nil
	case "bool":
		newValue := flag.Bool(name, app.DefaultBoolValue, name)
		return *newValue, nil

	case "*string":
		newValue := flag.String(name, app.DefaultStringValue, name)
		return *newValue, nil
	case "string":
		newValue := flag.String(name, app.DefaultStringValue, name)
		return *newValue, nil

	case "*time.duration":
		newValue := flag.Duration(name, app.DefaultDurationValue, name)
		return *newValue, nil
	case "time.duration":
		newValue := flag.Duration(name, app.DefaultDurationValue, name)
		return *newValue, nil

	case "*float64":
		newValue := flag.Float64(name, app.DefaultFloat64Value, name)
		return *newValue, nil
	case "float64":
		newValue := flag.Float64(name, app.DefaultFloat64Value, name)
		return *newValue, nil

	case "*int":
		newValue := flag.Int(name, app.DefaultIntValue, name)
		return *newValue, nil
	case "int":
		newValue := flag.Int(name, app.DefaultIntValue, name)
		return *newValue, nil

	case "*int64":
		newValue := flag.Int64(name, app.DefaultInt64Value, name)
		return *newValue, nil
	case "int64":
		newValue := flag.Int64(name, app.DefaultInt64Value, name)
		return *newValue, nil

	case "*uint":
		newValue := flag.Uint(name, app.DefaultUIntValue, name)
		return *newValue, nil
	case "uint":
		newValue := flag.Uint(name, app.DefaultUIntValue, name)
		return *newValue, nil

	case "*uint64":
		newValue := flag.Uint64(name, app.DefaultUInt64Value, name)
		return *newValue, nil
	case "uint64":
		newValue := flag.Uint64(name, app.DefaultUInt64Value, name)
		return *newValue, nil
	}
	return nil, fmt.Errorf("unknow type %s for argument %s", typeName, name)
}

作者:Team-IVIa    项目:IVIag-g   
func main() {
	maxPics := flag.Int64("max", -1, "Max count of pics to download (not implemented)")
	downloaders := flag.Uint64("dl", 1, "Number of simultaneous manga downloader")
	workers := flag.Uint64("worker", 3, "Number of simultaneous archive worker per downloader")
	fetchers := flag.Uint64("fetch", 4, "Number of simultaneous image fetcher per worker")
	flag.Parse()
	mangas := flag.Args()

	targets := make(chan uint64, len(mangas))

	logfile, err := os.OpenFile("log.txt", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		return
	}
	defer logfile.Close()
	logfile.WriteString(fmt.Sprintf(`======================================================
Fetch started at %v
======================================================
Targets supplied: %v
`, time.Now(), mangas))
	log.SetOutput(io.MultiWriter(os.Stdout, logfile))

	for _, manga := range mangas {
		m, err := strconv.ParseUint(manga, 10, 64)
		if err != nil {
			log.Fatal(err)
		}
		log.Println("Adding download target:", m)
		targets <- m
	}

	if len(mangas) == 0 {
		fmt.Println("Please input space-seperated manga ID.")
		fmt.Println("Manga ID: http://marumaru.in/b/manga/{ID}")
		os.Exit(1)
	}

	if *fetchers == 0 || *workers == 0 || *maxPics == 0 || *downloaders == 0 {
		fmt.Println("Invalid argument supplied")
		os.Exit(1)
	}
	doc, err := goquery.NewDocument(MangaPrefix)
	if err == nil && doc.Find("title").First().Text()[:7] == "You are" {
		UpdateCookie(doc)
	}
	wg := new(sync.WaitGroup)
	wg.Add(int(*downloaders))
	for i := uint64(0); i < *downloaders; i++ {
		dl := new(Downloader)
		dl.Init(*workers, *fetchers, *maxPics)
		go dl.Start(targets, wg)
	}
	close(targets)
	wg.Wait()
	log.Print("All tasks were done.")
}

作者:tehner    项目:bgpinjecto   
func main() {
	duration := flag.Uint64("duration", 3600, "Time to sleep before exit")
	asn := flag.Uint64("ASN", 65101, "Our AS number")
	rid := flag.Uint64("RID", 1, "Our router's ID")
	cfg := flag.String("cfg", "./inj.cfg", "Our configuration file")
	flag.Parse()
	fmt.Println("starting to inject bgp routes")
	to := make(chan bgp2go.BGPProcessMsg)
	from := make(chan bgp2go.BGPProcessMsg)
	bgpContext := bgp2go.BGPContext{ASN: uint32(*asn), RouterID: uint32(*rid)}
	go bgp2go.StartBGPProcess(to, from, bgpContext)
	ReadFile(*cfg, to)
	time.Sleep(time.Duration(*duration) * time.Second)
	fmt.Println("i've slept enough. waking up...")
}

作者:willhit    项目:noms-ol   
func main() {
	// use [from/to/by] or [from/iterations]
	nFrom := flag.Uint64("from", 1e2, "start iterations from this number")
	nTo := flag.Uint64("to", 1e4, "run iterations until arriving at this number")
	nBy := flag.Uint64("by", 1, "increment each iteration by this number")
	nIncrements := flag.Uint64("iterations", 0, "number of iterations to execute")
	encodingType := flag.String("encoding", "string", "encode/decode as 'string', 'binary', 'binary-int', 'binary-varint'")
	flag.Parse()

	flag.Usage = func() {
		fmt.Printf("%s\n", os.Args[0])
		flag.PrintDefaults()
		return
	}

	t0 := time.Now()
	nBytes := uint64(0)
	nIterations := uint64(0)

	encoderDecoder := getEncoder(*encodingType)
	startingLoop := newBigFloat(*nFrom)

	var endLoop *big.Float
	var incrementer *big.Float

	if *nIncrements > 0 {
		// using from/iterations flags
		fmt.Printf("encoding: %v from: %v iterations: %v\n", *encodingType, *nFrom, *nIncrements)

		incrementer = newBigFloat(1)
		n := newBigFloat(*nIncrements)
		endLoop = n.Add(n, startingLoop)
	} else {
		// using from/to/by flags
		fmt.Printf("encoding: %v from: %v to: %v by: %v\n", *encodingType, *nFrom, *nTo, *nBy)
		incrementer = newBigFloat(*nBy)
		endLoop = newBigFloat(*nTo)
	}

	for i := startingLoop; i.Cmp(endLoop) < 0; i = i.Add(i, incrementer) {
		nIterations++
		nBytes += runTest(encoderDecoder, i)
	}

	t1 := time.Now()
	d := t1.Sub(t0)
	fmt.Printf("IO  %s (%v nums) in %s (%s/s)\n", humanize.Bytes(nBytes), humanize.Comma(int64(nIterations)), d, humanize.Bytes(uint64(float64(nBytes)/d.Seconds())))
}

作者:janstenpickl    项目:etcd-dockerhost   
func main() {
	keyname := flag.String("keyname", "hosts", "Etcd keyname under which to record containers' hostnames/IP")
	ttl := flag.Uint64("ttl", 172800, "Time to live of the host entry")
	dockerAPIPort := flag.String("port", "4243", "Docker API Port")
	interval := flag.Duration("interval", 10, "Docker API to Etcd sync interval")
	//etcdHost := flag.String("etcd_host", "127.0.0.1", "Etcd host")
	//etcdPort := flag.String("etcd_port", "4001", "Etcd port")
	concurrency := flag.Int("concurrency", 1, "Number of worker threads")

	flag.Parse()

	//etcdCluster := []string{"http://" + *etcdHost + ":" + *etcdPort}
	etcdClient := etcd.NewClient()
	//etcdClient.SetCluster(etcdCluster)

	dockerClient, err := docker.NewClient("http://127.0.0.1:" + *dockerAPIPort)
	if err != nil {
		log.Fatal(err)
	}

	var c = make(chan string, *concurrency)

	for i := 0; i < *concurrency; i++ {
		go inspectAndSet(c, etcdClient, dockerClient, keyname, ttl)
	}

	loop(c, dockerClient, interval)

}

作者:foutais    项目:xtypekey   
func main() {
	log.SetFlags(log.Lshortfile)

	flagDelay := flag.Uint64("d", 0, "delay between keystrokes (milliseconds)")
	flag.Usage = func() {
		fmt.Fprintln(os.Stderr,
			"Send keys to the active X11 window\n"+
				"Usage:\n"+
				"  xtypekeys [ -d <num> ] \"<string>\" \"<string>\"\n\n"+
				"Example:\n"+
				"  xtypekeys -d 10 \"[Control]t\" \"[Control]k\" \\\n"+
				"                    \"search this\" \\\n"+
				"                    \"[Return]\"\n"+
				"Options:")
		flag.PrintDefaults()
	}
	flag.Parse()

	temporize = func() {
		time.Sleep(time.Duration(*flagDelay) * time.Millisecond)
	}

	if err := x.OpenDisplay(); err != nil {
		log.Fatal(err)
	}
	defer x.CloseDisplay()
	typeStrings(flag.Args())
}

作者:rajatgoe    项目:slimcach   
func main() {
	defaultSize := bucket.BucketSize * uint64(bucket.MaxOpen)

	path := flag.String("disk", "", "File path to setup as persistent storage")
	size := flag.Uint64("size", defaultSize, "Size of persistent storage")
	flag.Parse()

	f, err := os.Create(*path)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	err = f.Truncate(int64(*size))
	if err != nil {
		panic(err)
	}

	err = bucket.Create("/cache-buckets", *size)
	if err != nil {
		panic(err)
	}

	// We expect values to be at least 1KB
	err = hashtable.Create("/cache-hashtable", *size/1024)
	if err != nil {
		panic(err)
	}
}

作者:vy    项目:prox   
func main() {
	c := flag.Uint64("c", 1, "Concurrency")
	flag.Parse()
	log.Printf("Running... with concurrency: %v\n", *c)
	log.Fatal(http.Serve(throttle.NewListener("0:8080", *c),
		http.HandlerFunc(HelloHandler)))
}

作者:phzf    项目:RI   
func main() {

	cpath := flag.String("c", "config.ini", "Sets the configuration .ini file used.")
	flag.Parse()
	// CLI arguments

	conf := config.ReadConfig(*cpath)

	mem := flag.Uint64("m", conf.Server.Memory, "Sets the maximum memory to be used for caching images in bytes. Does not account for memory consumption of other things.")
	imagick.Initialize()
	defer imagick.Terminate()

	log.Println("Server starting...")
	logging.Debug("Debug enabled")

	server, handler, ln := NewServer(8005, *mem, conf)
	handler.started = time.Now()
	err := server.Serve(ln)
	end := time.Now()

	// Get number of requests
	requests := strconv.FormatUint((*handler).requests, 10)

	// Calculate the elapsed time
	duration := end.Sub(handler.started)
	log.Println("Server requests: " + requests)
	log.Println("Server uptime: " + duration.String())

	// Log errors
	if err != nil {
		log.Fatal(err)
	}
}

作者:netmarkj    项目:mackerel-agent-plugin   
func main() {
	optHost := flag.String("host", "localhost", "Hostname")
	optPort := flag.String("port", "64738", "Port")
	optTimeout := flag.Uint64("timeout", 1000, "Timeout (ms)")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	var murmur MurmurPlugin

	murmur.Host = fmt.Sprintf("%s:%s", *optHost, *optPort)
	murmur.Timeout = *optTimeout
	helper := mp.NewMackerelPlugin(murmur)

	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = fmt.Sprintf("/tmp/mackerel-plugin-murmur-%s-%s", *optHost, *optPort)
	}

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
}

作者:justinwal    项目:sli   
func main() {
	var client = flag.String("c", "", "soundcloud client id")
	var uid = flag.Uint64("u", 0, "soundcloud user id")
	var debug = flag.Bool("d", false, "debug")

	flag.Parse()

	if *client == "" {
		error("client id required")
	}

	if *uid == 0 {
		error("user id required")
	}

	unauthenticatedAPI := &soundcloud.Api{
		ClientId: *client,
	}

	tracks, err := unauthenticatedAPI.User(*uid).AllFavorites()
	if err != nil {
		if *debug {
			panic(err)
		}
		os.Exit(1)
	}

	for _, track := range tracks {
		fmt.Println(track.PermalinkUrl)
	}
}

作者:leochenciphe    项目:eagl   
func main() {
	var (
		listen  = flag.String("listen", ":7800", "Server listen address.")
		name    = flag.String("test.name", "unknown", "Name of the test to run.")
		path    = flag.String("test.path", "/", "Path to hit on the targets")
		rate    = flag.Uint64("test.rate", defaultRate, "Number of requests to send during test duration.")
		timeout = flag.Duration("test.timeout", defaultTimeout, "Time until a request is discarded")

		ts = targets{}
	)
	flag.Var(&ts, "test.target", `Target to hit by the test with the following format: -test.target="NAME:address/url"`)
	flag.Parse()

	if *listen == "" || len(ts) == 0 {
		flag.Usage()
		os.Exit(1)
	}

	var (
		test     = newTest(*name, *path, *rate, defaultInterval, *timeout, ts)
		registry = newRegistry(prometheus.Labels{"test": test.name})
		resultc  = make(chan result)
	)

	test.run(resultc)
	go registry.collect(resultc)

	http.Handle("/metrics", prometheus.Handler())

	log.Printf("Starting server on %s", *listen)
	log.Fatal(http.ListenAndServe(*listen, nil))
}

作者:gsdocke    项目:gsrunne   
func (runner *_Runner) Milliseconds(name string, fullname string, defaultVal uint64, description string) Runner {
	runner.checkName(name, fullname)

	runner.flagMilliseconds[name] = flag.Uint64(name, defaultVal, description)

	return runner
}

作者:qinlodesta    项目:freestor   
func main() {
	nTotal := flag.Uint64("n", math.MaxUint64, "number of times to perform a read and write operation")
	initialProcess := flag.String("initial", "", "Process to ask for the initial view")
	retryProcess := flag.String("retry", "", "Process to ask for a newer view")
	flag.Parse()

	freestoreClient, err := client.New(getInitialViewFunc(*initialProcess), getFurtherViewsFunc(*retryProcess))
	if err != nil {
		log.Fatalln("FATAL:", err)
	}

	var finalValue interface{}
	for i := uint64(0); i < *nTotal; i++ {
		startRead := time.Now()
		finalValue, err = freestoreClient.Read()
		endRead := time.Now()
		if err != nil {
			log.Fatalln(err)
		}

		startWrite := time.Now()
		err = freestoreClient.Write(finalValue)
		endWrite := time.Now()
		if err != nil {
			log.Fatalln(err)
		}

		if i%1000 == 0 {
			fmt.Printf("%v: Read %v (%v)-> Write (%v)\n", i, finalValue, endRead.Sub(startRead), endWrite.Sub(startWrite))
		} else {
			fmt.Printf(".")
		}
	}
}

作者:surma-dum    项目:nandcp   
func main() {
	var (
		wordsize  = flag.Uint64("wordsize", 32, "Word size of CPU")
		numCycles = flag.Uint64("cycles", 1000000, "Number of cycles to emulate")
		dumpStart = flag.Uint64("dumpStart", 0, "Start word of memory dump")
		dumpEnd   = flag.Uint64("dumpEnd", 0, "End word of memory dump")
	)
	flag.Parse()

	if flag.NArg() != 1 {
		flag.PrintDefaults()
		fmt.Println("\nExpected file to read ('-' for stdin)")
		return
	}
	if 64%*wordsize != 0 {
		flag.PrintDefaults()
		fmt.Println("\nWord size must be a multiple of 64")
		return
	}
	in := os.Stdin
	if f := flag.Arg(0); f != "-" {
		var err error
		in, err = os.Open(f)
		if err != nil {
			log.Fatalf("Error openening %s: %s", f, err)
		}
	}

	sbm, err := bitMemoryFromFile(in)
	if err != nil {
		log.Fatalf("Error reading input: %s", err)
	}
	sbm.WordSize = *wordsize
	sbm.AlignMemory()

	cpu := &libnandcpu.NandCPU{BitMemory: sbm}
	for i := uint64(0); i < *numCycles; i++ {
		cpu.Step()
	}
	// wordsize/4 = Number of hex digits per word
	pattern := fmt.Sprintf("%%%02dX\n", *wordsize/4)
	for i := *dumpStart; i < *dumpEnd; i++ {
		fmt.Printf(pattern, sbm.Word(i))
	}
}

作者:JeffreyLeeL    项目:jeffreyleeli.github.i   
func main() {
	var (
		n = flag.Uint64("n", 1000, "Upper limit: not included")
	)

	flag.Parse()

	fmt.Println(multipleSumBelow(*n))
}

作者:tychofreema    项目:go-example   
func main() {
	workers := flag.Uint64("workers", 0, "max integer to try")
	rng := flag.Uint64("range", 0, "max integer to try")
	flag.Parse()

	partialResults := make(chan float64, 1000000)
	quit := make(chan bool)

	go accumulateResult(*workers, partialResults, quit)

	for i := uint64(0); i < *workers; i++ {
		makeWorker((0 == ((i * *rng) % 2)),
			float64(i**rng),
			float64((i+1)**rng-1),
			partialResults)
	}
	<-quit
}

作者:crankycode    项目:hek   
func main() {
	udpAddr := flag.String("udpaddr", "127.0.0.1:5565", "UDP address string")
	udpFdInt := flag.Uint64("udpfd", 0, "UDP socket file descriptor")
	maxprocs := flag.Int("maxprocs", 1, "Go runtime MAXPROCS value")
	pprofName := flag.String("pprof", "", "pprof output file path")
	poolSize := flag.Int("poolsize", 1000, "Pipeline pool size")
	decoder := flag.String("decoder", "json", "Default decoder")
	flag.Parse()
	udpFdIntPtr := uintptr(*udpFdInt)

	runtime.GOMAXPROCS(*maxprocs)

	if *pprofName != "" {
		profFile, err := os.Create(*pprofName)
		if err != nil {
			log.Fatalln(err)
		}
		pprof.StartCPUProfile(profFile)
		defer pprof.StopCPUProfile()
	}

	config := pipeline.GraterConfig{}

	udpInput := pipeline.NewUdpInput(*udpAddr, &udpFdIntPtr)
	var inputs = map[string]pipeline.Input{
		"udp": udpInput,
	}
	config.Inputs = inputs

	jsonDecoder := pipeline.JsonDecoder{}
	gobDecoder := pipeline.GobDecoder{}
	var decoders = map[string]pipeline.Decoder{
		"json": &jsonDecoder,
		"gob":  &gobDecoder,
	}
	config.Decoders = decoders
	config.DefaultDecoder = *decoder

	outputNames := []string{"counter"}
	namedOutputFilter := pipeline.NewNamedOutputFilter(outputNames)
	config.FilterChains = map[string][]pipeline.Filter{
		"default": {namedOutputFilter},
	}
	config.DefaultFilterChain = "default"

	counterOutput := pipeline.NewCounterOutput()
	logOutput := pipeline.LogOutput{}
	var outputs = map[string]pipeline.Output{
		"counter": counterOutput,
		"log":     &logOutput,
	}
	config.Outputs = outputs
	config.DefaultOutputs = []string{}
	config.PoolSize = *poolSize

	pipeline.Run(&config)
}

作者:letthewookieewi    项目:heatma   
func main() {
	pname := flag.String("name", "unnamed", "The name of the colorscheme.")
	pw := flag.Uint64("w", 40, "Width of the pictures of the colorscheme.")
	ph := flag.Uint64("h", 1024, "Height (number of levels) of the colorscheme.")
	flag.Parse()

	if flag.NArg() < 2*2 || flag.NArg()%2 != 0 {
		flag.Usage()
		log.Fatal("Need at least two gradient keypoints!")
	}

	keypoints := GradientTable{}
	for i := 0; i < flag.NArg(); i += 2 {
		keypoints = append(keypoints, GradientTableEntry{MustParseHex(flag.Arg(i)), MustParseFloatZeroOne(flag.Arg(i + 1))})
	}

	CreateColorschemes(keypoints, *pname, int(*pw), int(*ph))
}

作者:NirmataOS    项目:go-envfla   
// UInt64 creates a new entry in the flag set with UInt64 value.
// The environment value used as a default, if it exists
func UInt64(flagName, envName string, value uint64, usage string) *uint64 {
	verifyNames(flagName, envName)
	envValStr := lookupEnv(envName)
	if envValStr != "" {
		value, _ = strconv.ParseUint(envValStr, 10, 64)
	}

	flag.Uint64(flagName, value, usage)
	return pflag.Uint64(flagName, value, usage)
}


问题


面经


文章

微信
公众号

扫码关注公众号