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) }
func main() { total := flag.Int64("total", 0, "Total block size in MB") block := flag.Int64("block", 100, "block init size in MB [dd bs]. count will be 1") parallel := flag.Int64("parallel", 2, "size") device := flag.String("device", "/dev/xvdf", "name") offset := flag.Int64("offset", 0, "starting offset that will be used to skip") flag.Parse() p := make(chan bool, *parallel) c := *offset for c*(*block) < *total { go func(c int64) { ifd := fmt.Sprintf("if=%s", *device) of := fmt.Sprintf("of=/dev/null") bs := fmt.Sprintf("bs=%dM", *block) count := fmt.Sprintf("count=1") skip := fmt.Sprintf("skip=%d", c) out, err := exec.Command("dd", ifd, of, bs, count, skip).CombinedOutput() if err != nil { log.Println(err, out) } <-p }(c) p <- true c++ fmt.Println("offset:", c, "total:", c*(*block), "MB") } for i := int64(0); i < *parallel; i++ { p <- true } }
func main() { lat := flag.Float64("lat", 0, "latitude of occurrence") lng := flag.Float64("lng", 0, "longitude of occurrence") explain := flag.Bool("explain", true, "print useful information") date := flag.Int64("date", 0, "unix second: 1467558491") period := flag.Int64("period", 14, "number of days into the past to generate weather: 14") flag.Parse() store, err := noaa.NewWeatherStore( "/Users/mph/Desktop/phenograph-raw-data/stations.txt", "/Users/mph/Desktop/phenograph-raw-data/ghcnd_all/ghcnd_all", false, ) if err != nil { panic(err) } records, err := store.Nearest( *lat, *lng, noaa.Elements{noaa.ElementTMAX, noaa.ElementPRCP, noaa.ElementTMIN}, noaa.TimesFromUnixArray(*date, *period), *explain, ) if err != nil { panic(err) } fmt.Println("RECORDS", utils.JsonOrSpew(records)) return }
func main() { // get all the vars numNewpix := flag.Int64("numnewpix", -1, "Mandatory -- The number of NewPix to click for, 0 for infinite, negative for displaying help.") xserver := flag.String("xserver", os.Getenv("DISPLAY"), "Which X server to send the clicks to (defaults to the one this command is ran from).") startpix := flag.Int64("currentpix", 1, "Which pix the game is on.") npbotmNP := flag.Int64("npbotmnp", 400, "How many mNP the NewPixBots need to avoid being ninja'd (0 if there's no ninja).") helpwanted := flag.Bool("help", false, "Print the help message.") flag.Parse() // verify parameter validity and display help if anything's invalid (or if help's requested) if *helpwanted || *numNewpix < 0 || *startpix < 1 || *npbotmNP < 0 { usage() os.Exit(1) } // make clicker ch := make(chan bool, 1) go cmdRepeater(ch, func() *exec.Cmd { return clickNCmd(5, *xserver) }) // finish current newpix curpix := *startpix var margin int64 = 3 // how many extra mNP on either side of newpixbot ninja'ing time to wait wakemNP := *npbotmNP + margin sleepmNP := 1000 - margin if mNP := currentmNP(curpix); mNP < sleepmNP { clickLoopIteration(curpix, wakemNP, sleepmNP, ch) } for curpix++; curpix < *startpix+*numNewpix; curpix++ { clickLoopIteration(curpix, wakemNP, sleepmNP, ch) } }
func main() { providersFile := flag.String("providers_file", "providers.json", "Path to oembed providers json file") workerCount := flag.Int64("worker_count", 1000, "Amount of workers to start") host := flag.String("host", "localhost", "Host to listen on") port := flag.Int("port", 8000, "Port to listen on") maxHTMLBytesToRead := flag.Int64("html_bytes_to_read", 50000, "How much data to read from URL if it's an html page") maxBinaryBytesToRead := flag.Int64("binary_bytes_to_read", 4096, "How much data to read from URL if it's NOT an html page") waitTimeout := flag.Int("wait_timeout", 7, "How much time to wait for/fetch response from remote server") whiteListRanges := flag.String("whitelist_ranges", "", "What IP ranges to allow. Example: 178.25.32.1/8") blackListRanges := flag.String("blacklist_ranges", "", "What IP ranges to disallow. Example: 178.25.32.1/8") flag.Parse() buf, err := ioutil.ReadFile(*providersFile) if err != nil { panic(err) } var whiteListNetworks []*net.IPNet if len(*whiteListRanges) > 0 { if whiteListNetworks, err = stringsToNetworks(strings.Split(*whiteListRanges, " ")); err != nil { panic(err) } } var blackListNetworks []*net.IPNet if len(*blackListRanges) > 0 { if blackListNetworks, err = stringsToNetworks(strings.Split(*blackListRanges, " ")); err != nil { panic(err) } } oe := oembed.NewOembed() oe.ParseProviders(bytes.NewReader(buf)) workers := make([]tunny.TunnyWorker, *workerCount) for i := range workers { p := url2oembed.NewParser(oe) p.MaxHTMLBodySize = *maxHTMLBytesToRead p.MaxBinaryBodySize = *maxBinaryBytesToRead p.WaitTimeout = time.Duration(*waitTimeout) * time.Second p.BlacklistedIPNetworks = blackListNetworks p.WhitelistedIPNetworks = whiteListNetworks workers[i] = &(apiWorker{Parser: p}) } pool, err := tunny.CreateCustomPool(workers).Open() if err != nil { log.Fatal(err) } defer pool.Close() workerPool = pool startServer(*host, *port, *waitTimeout) }
func init() { depthPtr = flag.Int64("depth", 50, "sets the number of rows (and hash functions) in the CMSketch") widthPtr = flag.Int64("width", 80, "sets the number of columns in the CMSketch") efactorPtr = flag.Int64("efactor", 10, "number of elements = depth*width*efactor") NumProcsPtr := flag.Int64("procs", 1, "number of concurrent worker processes") flag.Parse() numProcs = *NumProcsPtr }
func main() { channel_pairs := flag.Int("channel_pairs", 4, "channel_pairs") count := flag.Int64("count", 1000000, "iterations") blocking_count := flag.Int64("blocking_count", 10000, "blocking iterations") flag.Parse() run_test("buffer = 1024", *channel_pairs, 1024, *count) run_test("blocking", *channel_pairs, 0, *blocking_count) }
func main() { queryPtr := flag.String("query", "", "Query to run. E.g. \"MAP field_1, field_2 REDUCE ON field_1\"") startPtr := flag.Int64("start", 0, "Start date (in seconds)") endPtr := flag.Int64("end", time.Now().Unix(), "End date (in seconds)") flag.Parse() startTm := time.Unix(*startPtr, 0) endTm := time.Unix(*endPtr, 0) startFile := GenerateFileName(startTm) endFile := GenerateFileName(endTm) dirname := "data" + string(filepath.Separator) query := bytes.NewBufferString(*queryPtr) p := NewParser(query) mapper, reducer, err := p.Parse() if err != nil { panic(err) } d, err := os.Open(dirname) if err != nil { fmt.Println(err) os.Exit(1) } defer d.Close() files, err := d.Readdir(-1) if err != nil { fmt.Println(err) os.Exit(1) } for _, f := range files { if startFile <= f.Name() && f.Name() <= endFile { if file, err := os.Open(dirname + f.Name()); err == nil { scanFile(file, mapper) } else { log.Fatal(err) } } } if reducer.Key == "" { if resultStr, err := json.Marshal(mapped); err != nil { panic(err) } else { fmt.Printf("%s", resultStr) } } else { _reduce(*reducer) if resultStr, err := json.Marshal(reduced); err != nil { panic(err) } else { fmt.Printf("%s", resultStr) } } }
func parseFlags() (load, blockSize *float64, numBlocks, numIterations *int64) { load = flag.Float64("load", 0.0, "load percentage") blockSize = flag.Float64("bs", bls.DEFAULT_BLOCK_SIZE, "block size") numBlocks = flag.Int64("nb", bls.DEFAULT_NUM_BLOCKS, "number of blocks") numIterations = flag.Int64("ni", bls.DEFAULT_NUM_ITERATIONS, "number of iterations") flag.Parse() return }
func get_cli() (*prefs, bool) { def_streams := int64(runtime.NumCPU()) preferences := &prefs{} encryptCmd := flag.Bool("encrypt", false, "") decryptCmd := flag.Bool("decrypt", false, "") streams := flag.Int64("s", def_streams, "Num of streams") filename := flag.String("f", "", "File need to encrypt/decrypt") chunk_size := flag.Int64("c", 1, "Size of chunk in Kb") key := flag.String("k", "", "Key file, required for decryption") output := flag.String("o", "", "Resulting file") flag.Parse() if *encryptCmd && !*decryptCmd { preferences.Command = ENCRYPT_CMD } else if *decryptCmd && !*encryptCmd { preferences.Command = DECRYPT_CMD } else { fmt.Println("You have to choose decrypt or encrypt command!") return nil, false } if _, err := os.Stat(*filename); len(*filename) == 0 || os.IsNotExist(err) { fmt.Printf("Invalid input file path %q\n\t%v\n", *filename, err) return nil, false } preferences.Filename = *filename if *streams <= 0 { *streams = def_streams } preferences.Streams = *streams if *chunk_size <= 0 { fmt.Println("Chunk size has to be more then 0") return nil, false } preferences.Chunk_Size = (*chunk_size) * pow_int64(2, 10) if len(*key) == 0 { fmt.Println("Invalid keyfile path") return nil, false } preferences.KeyFilename = *key if len(*output) == 0 { fmt.Println("Invalid resulting file path") return nil, false } preferences.OutputFilename = *output file_info, err := os.Stat(preferences.Filename) check(err) preferences.FileLen = file_info.Size() return preferences, true }
func main() { num := flag.Int64("num", 0, "number of numbers") max := flag.Int64("max", 0, "max number") flag.Parse() r := rand.New(rand.NewSource(1)) i := int64(0) for i = 0; i < *num; i++ { fmt.Printf("%d\n", r.Int63n(*max+1)) } return }
// 获取外部参数 func Flag() { // 分类说明 flag.String("c . . . . . . . . . . . . .. . . . . . . . . . . only for cmd . . . . . . . . . . . . . .. . . . . . . . . . c", "cmd", "\r\n") // 自定义输入 keywordflag = flag.String("c_keyword", "", " <自定义输入 选填 多关键词以 \",\" 隔开>") // 蜘蛛列表 spiderflag = flag.String("c_spider", "", func() string { var spiderlist string for k, v := range app.LogicApp.GetSpiderLib() { spiderlist += " {" + strconv.Itoa(k) + "} " + v.GetName() + " " + v.GetDescription() + "\r\n" } return " <蜘蛛列表 选择多蜘蛛以 \",\" 间隔>\r\n" + spiderlist }()) // 输出方式 outputflag = flag.String("c_output", app.LogicApp.GetOutputLib()[0], func() string { var outputlib string for _, v := range app.LogicApp.GetOutputLib() { outputlib += "{" + v + "} " } return " <输出方式> " + strings.TrimRight(outputlib, " ") }()) // 并发协程数 threadflag = flag.Int("c_thread", cache.Task.ThreadNum, " <并发协程> {1~99999}\n") // 平均暂停时间 pauseflag = flag.Int64("c_pause", cache.Task.Pausetime, " <平均暂停时间/ms> {>=100} ") // 代理IP更换频率 proxyflag = flag.Int64("c_proxy", cache.Task.ProxyMinute, " <代理IP更换频率/m 为0时不使用代理> {>=0} ") // 分批输出 dockerflag = flag.Int("c_docker", cache.Task.DockerCap, " <分批输出> {1~5000000}") // 采集页数 maxpageflag = flag.Int64("c_maxpage", 0, " <采集页数> {>=0}") // 继承之前的去重记录 successInheritflag = flag.Bool("c_inherit_y", true, " <继承并保存成功记录 {true/false}>") failureInheritflag = flag.Bool("c_inherit_n", true, " <继承并保存失败记录 {true/false}>") // 备注说明 flag.String( "c_z", "cmd-example", " pholcus -a_ui=cmd -c_spider=3,8 -c_output=csv -c_thread=20 -c_docker=5000 -c_pause=300 -c_proxy=0 -c_keyword=pholcus,golang -c_maxpage=10 -c_inherit_y=true -c_inherit_n=true\r\n", ) }
func main() { var port = flag.Int("port", 80, `port, default is 80`) var isDebug = flag.Bool("debug", false, `debug, default is false`) var centerId = flag.Int64("center", 0, `centerId, default is 0`) var workerId = flag.Int64("worker", 0, `workerId, default is 0`) var twepoch = flag.Int64("twepoch", 0, `twepoch, default is 0`) flag.Parse() generator, _ = id.NewId(*workerId, *centerId, *twepoch) colorize.IsDebug = *isDebug colorize.Info(`going to run :%d`, *port) http.HandleFunc("/", RequestHanler) http.ListenAndServe(fmt.Sprintf(":%d", *port), nil) }
func main() { // get command line flags coresToPegPtr = flag.Int64("coresToPeg", 0, "how many CPU cores would you like to artificially peg to 100% usage") flag.Parse() // this will help us poll the OS to get system statistics stats := NewStats() runtime.GOMAXPROCS(runtime.NumCPU()) // WARNING: each call to burnCPU() will peg one core // of your machine to 100% // If you have code you'd like to drop in to this example, // just run "go yourCode()" instead of "go burnCPU() for i := *coresToPegPtr; i > 0; i-- { fmt.Println("pegging one more CPU core.") go burnCPU() } for { stats.GatherStats(true) stats.PrintStats() // This next line lets out see the jsonified object // produced by systemstat // printJson(stats, false) time.Sleep(3 * time.Second) } }
func init() { atomSizeUsage := "atom size (1, 2, or 3)" atomSize := flag.Uint("atomsize", 1, atomSizeUsage) carrierUsage := "path to message carrier" carrier := flag.String("carrier", "", carrierUsage) inputUsage := "path to input; can be - for standard in" input := flag.String("input", "-", inputUsage) boxUsage := "use size-checking encapsulation format" box := flag.Bool("box", false, boxUsage) offsetUsage := "read/write offset" offset := flag.Int64("offset", 0, offsetUsage) flag.Parse() if *atomSize < 1 || *atomSize > 3 { log.Fatalf("atom size must be 1, 2, or 3") } if *offset < 0 { log.Fatalf("offset must be positive") } state = new(cmd.State) state.Ctx = steg.NewCtx(uint8(*atomSize)) state.Carrier, state.CarrierSize = getCarrier(*carrier) state.Input, state.InputSize = getInput(*input) state.Box = *box state.Offset = *offset }
func main() { targetPath := flag.String("t", "", "Target image (PNG) path") seed := flag.Int64("seed", time.Now().UTC().UnixNano(), "Seed for RNG") flag.Parse() rand.Seed(*seed) var conf Configuration // Solution max depth conf.MaxDepth = 4 //13 // Load the target image var err error conf.ImgTarget, err = imgut.Load(*targetPath) if err != nil { fmt.Println("ERROR: Cannot load image", *targetPath) panic("Cannot load image") } // Set terminals and functionals conf.Functionals = rr.Functionals conf.Terminals = rr.Terminals // Search with hill climbing sol := hc.HillClimbing(&conf) fmt.Println("Hill climbing finito", sol, sol.Fitness()) // Save solution somewhere outPath := "hc_best.png" fmt.Println("Saving best as", outPath) sol.Fitness() sol.(*Solution).ImgTemp.WritePNG(outPath) }
func loadflags() (flags, error) { credp := flag.String("credentials", "", "path to credentials file") fp := flag.String("file-path", "", "path of file to be archived") colp := flag.String("collection", "", "collection name") keyp := flag.String("key", "", "key name") sp := flag.Int64("slices-size", defaultSliceSize, "maximum size of each slice of the file to be archived") hp := flag.Int("connections", defaultConnections, "Max number of open HTTP connections") flag.Parse() if *fp == "" { return flags{}, fmt.Errorf( "you must specify the path to a file to be archived") } if *keyp == "" { return flags{}, fmt.Errorf("you must specify a key") } if *sp == 0 { *sp = defaultSliceSize } if *hp == 0 { *hp = defaultConnections } return flags{*credp, *fp, *colp, *keyp, *sp, *hp}, nil }
func main() { size := flag.Int("psize", 500, "physical size of the square image") vpx := flag.Float64("x", 0, "x coordinate of the center of the image") vpy := flag.Float64("y", 0, "y coordinate of the center of the image") d := flag.Float64("size", 2, "size of the represented part of the plane") filename := flag.String("name", "image", "name of the image file produced (w/o extension") numberOfProcs := flag.Int("procs", 2, "number of procs to use") seed := flag.Int64("seed", 42, "seed for the random number generator") cols := flag.Bool("with-colors", false, "whether there is colors") flag.Parse() runtime.GOMAXPROCS(*numberOfProcs) withColors = *cols if *cols { initColors(*seed) } file, err := os.Open(*filename+".png", os.O_RDWR|os.O_CREAT, 0666) if err != nil { panic("error with opening file \"" + *filename + "\"") } im := image.NewRGBA(*size, *size) ch := make(chan point, 1000) Start(im, 2, *vpx, *vpy, *d, ch) handleChans(im, ch) png.Encode(file, im) }
func LoadConfig() { configPath := flag.String("config", "./config.yml", "config file path") port := flag.String("port", "default", "port to bind to") duration := flag.Int64("duration", 0, "duration to operation on") cpuprofile := flag.Bool("cpuprofile", false, "write cpu profile to file") flag.Parse() absolutePath, _ := filepath.Abs(*configPath) c, err := yaml.ReadFile(absolutePath) if err != nil { panic(err) } root, _ := c.Get("root") if *port == "default" { *port, _ = c.Get("port") } numRetentions, _ := c.Count("retentions") retentions := make([]Retention, numRetentions) for i := 0; i < numRetentions; i++ { retention, _ := c.Get("retentions[" + strconv.Itoa(i) + "]") parts := strings.Split(retention, " ") d, _ := strconv.ParseInt(parts[0], 0, 64) n, _ := strconv.ParseInt(parts[1], 0, 64) retentions[i] = Retention{d, n, d * n} } p, _ := c.Get("redis.port") redisPort, _ := strconv.Atoi(p) redisHost, _ := c.Get("redis.host") Config = Configuration{*port, root, retentions, redisHost, redisPort, *duration} ProfileCPU = *cpuprofile }
func main() { mode = flag.String("m", "tcp", "portguard work mode: tcp or udp") debug = flag.Bool("d", false, "debug mode, print log to stderr") portCacheDuration = flag.Int64("duration", 120, "port cache duration") flag.Usage = usage flag.Parse() if *debug { mainLogger = log.New(io.Writer(os.Stderr), "", log.Ldate|log.Lmicroseconds) } else { var err error if mainLogger, err = syslog.NewLogger(syslog.LOG_ERR|syslog.LOG_LOCAL7, log.Ldate|log.Lmicroseconds); err != nil { logMain(true, "open syslog failed:%s", err.Error()) } } args := flag.Args() if len(args) > 0 { readConfigFile(args[0]) } configGuard() configEcho() if *mode == "tcp" { tcpGuard() } else if *mode == "udp" { udpGuard() } else { fmt.Fprintf(os.Stderr, "don't support mode: %s\n", *mode) } }
func (runner *_Runner) FlagInt(name string, fullname string, defaultVal int64, description string) Runner { runner.checkName(name, fullname) runner.flagInt[name] = flag.Int64(name, defaultVal, description) return runner }
func main() { host := flag.String("host", "api.tsinghua.io", "Host of the server") port := flag.Int("port", 443, "Port of the server") certFile := flag.String("cert", "", "Certificate file.") keyFile := flag.String("key", "", "key file.") windowMin := flag.Int64("window", 15, "Window size of the rate limit (in minutes).") rate := flag.Int("rate", 900, "Max requests per window per IP.") flag.Parse() api := api.New( handlers.CompressHandler, util.HeadersHandler, util.NewLimiter(*windowMin*60, *rate).Handler(), ) api.AddResource("/semester", resource.Semester) api.AddResource("/users/me", resource.Profile) api.AddResource("/users/me/attended", resource.Attended) api.AddResource("/courses/{id}/announcements", resource.CourseAnnouncements) api.AddResource("/courses/{id}/files", resource.CourseFiles) api.AddResource("/courses/{id}/assignments", resource.CourseAssignments) api.AddResource("/courses/{id}/materials", resource.CourseMaterials) addr := *host + ":" + strconv.Itoa(*port) glog.Infof("windowMin = %d, rate = %d", *windowMin, *rate) glog.Infof("Starting server on %s", addr) err := http.ListenAndServeTLS(addr, *certFile, *keyFile, api) glog.Fatalf("Shutting down: %s", err) }
func main() { runtime.GOMAXPROCS(runtime.NumCPU()) // Use all the machine's cores log.SetFlags(0) var timeoutOpt *int64 = flag.Int64("timeout", 0, "seconds (0 means no timeout)") flag.Parse() if *timeoutOpt < 0 || *timeoutOpt > 240 { log.Fatalln("timeout must be in the range [0,240] seconds") } args := flag.Args() if len(args) < 1 { log.Fatalln("a regexp to match must be specified") } pattern := args[0] files := args[1:] if len(files) < 1 { log.Fatalln("must provide at least one filename") } if lineRx, err := regexp.Compile(pattern); err != nil { log.Fatalf("invalid regexp: %s\n", err) } else { var timeout int64 = 1e9 * 60 * 10 // 10 minutes! if *timeoutOpt != 0 { timeout = *timeoutOpt * 1e9 } grep(timeout, lineRx, commandLineFiles(files)) } }
func main() { size := flag.Int64("size", 10000, "size in bits of bit vector") flag.Parse() fmt.Println("Vector size:", *size, "bits") fmt.Println("Estimated result:", readStdin(*size)) }
func init() { defaultConnection := os.Getenv("SRVTMR_CONNECTION") if len(defaultConnection) == 0 { defaultConnection = "postgres://[email protected]:5432/sethammons?sslmode=disable" } var defaultPort int var err error defaultPortStr := os.Getenv("PORT") if len(defaultPortStr) == 0 { log.Println("using default 5000, ", defaultPortStr) defaultPort = 5000 } else { defaultPort, err = strconv.Atoi(defaultPortStr) } if err != nil { log.Fatal("Unable to obtain port: ", err) } CONNECTION = flag.String("connection", defaultConnection, "postgres://[user]:[pw]@[host]:[port]/[database]?sslmode=[mode]") PORT = flag.Int64("port", int64(defaultPort), "port to use; default 5000") READ_COUNT = 0 WRITE_COUNT = 0 }
// getFlags will define the variables that can be found in the command line (via the flags package) func (c *GetConf) getFlags() error { // parse command line if flag.Parsed() { return errors.New("getconf.getFlags: flags already parsed") } else { //fl := flag.NewFlagSet("flag", flag.ContinueOnError) for _, v := range c.allOptions { if v.flagName == "" { v.flagName = strings.ToLower(v.name) } switch v.oType { case reflect.Int: flag.Int(v.flagName, 0, "") case reflect.Int64: flag.Int64(v.flagName, 0, "") case reflect.Float64: flag.Float64(v.flagName, 0, "") case reflect.Bool: flag.Bool(v.flagName, false, "") case reflect.String: flag.String(v.flagName, "", "") } } } return nil }
func main() { limitFl := flag.Int64("limit", 10240, "Page read size limit") flag.Parse() for _, urlStr := range os.Args[1:] { resp, err := http.Get(urlStr) if err != nil { log.Fatal("cannot GET url", "url", urlStr, "error", err.Error()) } defer resp.Body.Close() b, err := ioutil.ReadAll(io.LimitReader(resp.Body, *limitFl)) if err != nil { log.Fatal("cannot read HTTP response", "url", urlStr, "error", err.Error()) } s := html.UnescapeString(string(b)) doc, err := readability.NewDocument(s) if err != nil { log.Fatal("cannot parse page", "error", err.Error()) } fmt.Println(doc.Content()) } }
func init() { flag.StringVar(&host, "host", "localhost", "Host for toxiproxy's API to listen on") flag.StringVar(&port, "port", "8474", "Port for toxiproxy's API to listen on") seed := flag.Int64("seed", time.Now().UTC().UnixNano(), "Seed for randomizing toxics with") flag.Parse() rand.Seed(*seed) }
func main() { notAWinner := false game := NewGame() game.Add("Chet") game.Add("Pat") game.Add("Sue") // hardcoding seed seed := flag.Int64("seed", 1, "seed number to use for random number generator") flag.Parse() rand.Seed(*seed) for { game.Roll(rand.Intn(5) + 1) if rand.Intn(9) == 7 { notAWinner = game.WrongAnswer() } else { notAWinner = game.WasCorrectlyAnswered() } if !notAWinner { break } } fmt.Println("seed", *seed) }
func parseArgs() *args { var blocksize = flag.Int64("blocksize", 32768, "Read/write blocksize, defaults to 32KB") flag.Usage = usage flag.Parse() positional := flag.Args() if len(positional) < 2 { usage() } info, err := os.Stat(positional[0]) handleError(err) if !info.IsDir() { fail(positional[0] + " is not a directory") } gb, err := strconv.ParseUint(positional[1], 10, 32) handleError(err) return &args{ gb: int(gb), bytes: int64(uint64(math.Pow10(9)) * uint64(gb)), dir: positional[0], blocksize: *blocksize, } }