Exemplo n.º 1
0
func init() {
	flag.IntVar(&qsConfig.PoolSize, "queryserver-config-pool-size", DefaultQsConfig.PoolSize, "query server connection pool size, connection pool is used by regular queries (non streaming, not in a transaction)")
	flag.IntVar(&qsConfig.StreamPoolSize, "queryserver-config-stream-pool-size", DefaultQsConfig.StreamPoolSize, "query server stream pool size, stream pool is used by stream queries: queries that return results to client in a streaming fashion")
	flag.IntVar(&qsConfig.TransactionCap, "queryserver-config-transaction-cap", DefaultQsConfig.TransactionCap, "query server transaction cap is the maximum number of transactions allowed to happen at any given point of a time for a single vttablet. E.g. by setting transaction cap to 100, there are at most 100 transactions will be processed by a vttablet and the 101th transaction will be blocked (and fail if it cannot get connection within specified timeout)")
	flag.Float64Var(&qsConfig.TransactionTimeout, "queryserver-config-transaction-timeout", DefaultQsConfig.TransactionTimeout, "query server transaction timeout (in seconds), a transaction will be killed if it takes longer than this value")
	flag.IntVar(&qsConfig.MaxResultSize, "queryserver-config-max-result-size", DefaultQsConfig.MaxResultSize, "query server max result size, maximum number of rows allowed to return from vttablet for non-streaming queries.")
	flag.IntVar(&qsConfig.MaxDMLRows, "queryserver-config-max-dml-rows", DefaultQsConfig.MaxDMLRows, "query server max dml rows per statement, maximum number of rows allowed to return at a time for an upadte or delete with either 1) an equality where clauses on primary keys, or 2) a subselect statement. For update and delete statements in above two categories, vttablet will split the original query into multiple small queries based on this configuration value. ")
	flag.IntVar(&qsConfig.StreamBufferSize, "queryserver-config-stream-buffer-size", DefaultQsConfig.StreamBufferSize, "query server stream buffer size, the maximum number of bytes sent from vttablet for each stream call.")
	flag.IntVar(&qsConfig.QueryCacheSize, "queryserver-config-query-cache-size", DefaultQsConfig.QueryCacheSize, "query server query cache size, maximum number of queries to be cached. vttablet analyzes every incoming query and generate a query plan, these plans are being cached in a lru cache. This config controls the capacity of the lru cache.")
	flag.Float64Var(&qsConfig.SchemaReloadTime, "queryserver-config-schema-reload-time", DefaultQsConfig.SchemaReloadTime, "query server schema reload time, how often vttablet reloads schemas from underlying MySQL instance in seconds. vttablet keeps table schemas in its own memory and periodically refreshes it from MySQL. This config controls the reload time.")
	flag.Float64Var(&qsConfig.QueryTimeout, "queryserver-config-query-timeout", DefaultQsConfig.QueryTimeout, "query server query timeout (in seconds), this is the query timeout in vttablet side. If a query takes more than this timeout, it will be killed.")
	flag.Float64Var(&qsConfig.TxPoolTimeout, "queryserver-config-txpool-timeout", DefaultQsConfig.TxPoolTimeout, "query server transaction pool timeout, it is how long vttablet waits if tx pool is full")
	flag.Float64Var(&qsConfig.IdleTimeout, "queryserver-config-idle-timeout", DefaultQsConfig.IdleTimeout, "query server idle timeout (in seconds), vttablet manages various mysql connection pools. This config means if a connection has not been used in given idle timeout, this connection will be removed from pool. This effectively manages number of connection objects and optimize the pool performance.")
	flag.BoolVar(&qsConfig.StrictMode, "queryserver-config-strict-mode", DefaultQsConfig.StrictMode, "allow only predictable DMLs and enforces MySQL's STRICT_TRANS_TABLES")
	// tableacl related configurations.
	flag.BoolVar(&qsConfig.StrictTableAcl, "queryserver-config-strict-table-acl", DefaultQsConfig.StrictTableAcl, "only allow queries that pass table acl checks")
	flag.BoolVar(&qsConfig.EnableTableAclDryRun, "queryserver-config-enable-table-acl-dry-run", DefaultQsConfig.EnableTableAclDryRun, "If this flag is enabled, tabletserver will emit monitoring metrics and let the request pass regardless of table acl check results")
	flag.StringVar(&qsConfig.TableAclExemptACL, "queryserver-config-acl-exempt-acl", DefaultQsConfig.TableAclExemptACL, "an acl that exempt from table acl checking (this acl is free to access any vitess tables).")
	flag.BoolVar(&qsConfig.TerseErrors, "queryserver-config-terse-errors", DefaultQsConfig.TerseErrors, "prevent bind vars from escaping in returned errors")
	flag.BoolVar(&qsConfig.EnablePublishStats, "queryserver-config-enable-publish-stats", DefaultQsConfig.EnablePublishStats, "set this flag to true makes queryservice publish monitoring stats")
	flag.StringVar(&qsConfig.StatsPrefix, "stats-prefix", DefaultQsConfig.StatsPrefix, "prefix for variable names exported via expvar")
	flag.StringVar(&qsConfig.DebugURLPrefix, "debug-url-prefix", DefaultQsConfig.DebugURLPrefix, "debug url prefix, vttablet will report various system debug pages and this config controls the prefix of these debug urls")
	flag.StringVar(&qsConfig.PoolNamePrefix, "pool-name-prefix", DefaultQsConfig.PoolNamePrefix, "pool name prefix, vttablet has several pools and each of them has a name. This config specifies the prefix of these pool names")
	flag.BoolVar(&qsConfig.EnableAutoCommit, "enable-autocommit", DefaultQsConfig.EnableAutoCommit, "if the flag is on, a DML outsides a transaction will be auto committed.")
}
Exemplo n.º 2
0
func main() {
	var (
		in     string
		out    string
		force  bool
		xScale float64
		yScale float64
	)
	flag.StringVar(&in, "i", "", "path to input text file. If unspecified or "+
		"set to '-', stdin is used")
	flag.StringVar(&out, "o", "", "path to output SVG file. If unspecified or "+
		"set to '-', stdout is used")
	flag.BoolVar(&force, "f", false, "overwrite existing output file")
	flag.Float64Var(&xScale, "x", asciiart.XScale,
		"number of pixels to scale each unit on the x-axis to")
	flag.Float64Var(&yScale, "y", asciiart.YScale,
		"number of pixels to scale each unit on the y-axis to")
	flag.Parse()
	if flag.NArg() != 0 {
		usage()
	}
	// work around defer not working after os.Exit()
	if err := aa2svgMain(out, in, force, xScale, yScale); err != nil {
		fatal(err)
	}
}
Exemplo n.º 3
0
func initFlags() {
	flag.BoolVar(&flagTest, "test", false, "Don't change any orders. Just output.")
	flag.StringVar(&flagExchange, "exchange", "bitstamp", "Exchange to connect to.")
	flag.StringVar(&flagApiKey, "api_key", "", "Bitstamp API key")
	flag.StringVar(&flagApiSecret, "api_secret", "", "Bitstamp API secret")
	flag.StringVar(&flagClientId, "client_id", "", "Bitstamp client ID")
	flag.Float64Var(
		&flagSpread, "spread", 2.0, "Percentage distance between buy/sell price")
	flag.Float64Var(
		&flagBtcRatio, "btc_ratio", 0.5, "Ratio of capital that should be BTC")
	flag.BoolVar(
		&flagFeeRound, "fee_round", false,
		"Round order size up such that the fee is an integer number of cents.")
	flag.Float64Var(
		&flagOffsetUsd, "offset_usd", 0,
		"Offset the USD balance before determining which orders to make.")
	flag.Float64Var(
		&flagOffsetBtc, "offset_btc", 0,
		"Offset the BTC balance before determining which orders to make.")
	flag.Float64Var(
		&flagMinAmount, "min_amount", 0,
		"Minimum amount of BTC to buy/sell")
	flag.BoolVar(
		&flagFeeAlwaysUsd, "fee_always_usd", false,
		"Whether the fee is always paid from USD. "+
			"Otherwise it's paid from BTC if BTC are bought.")
	flag.Parse()

	if flagApiKey == "" || flagApiSecret == "" {
		fmt.Printf("--api_key and --api_secret must be specified\n")
		os.Exit(1)
	}
}
Exemplo n.º 4
0
func init() {
	flag.StringVar(&in, "in", "", "file name of a BAM file to be processed.")
	flag.StringVar(&format, "format", "svg", "specifies the output format of the example: eps, jpg, jpeg, pdf, png, svg, and tiff.")
	flag.Var(&highlight, "highlight", "comma separated set of chromosome names to highlight.")
	flag.StringVar(&palname, "palette", "Set1", "specify the palette name for highlighting.")
	flag.Float64Var(&maxTrace, "tracemax", 0, "set the maximum value for the outer trace if not zero.")
	flag.Float64Var(&maxCounts, "countmax", 0, "set the maximum value for the inner trace if not zero.")
	help := flag.Bool("help", false, "output this usage message.")
	flag.Parse()
	if *help {
		flag.Usage()
		os.Exit(0)
	}
	if in == "" {
		flag.Usage()
		os.Exit(1)
	}
	for _, s := range []string{"eps", "jpg", "jpeg", "pdf", "png", "svg", "tiff"} {
		if format == s {
			return
		}
	}
	flag.Usage()
	os.Exit(1)
}
Exemplo n.º 5
0
func init() {
	flag.StringVar(&in, "in", "", "BAM file to be processed.")
	flag.StringVar(&annot, "annot", "", "file name of a GFF file containing annotations.")
	flag.Float64Var(&thresh, "thresh", 1, "log score threshold for inclusion of feature.")
	flag.Var(&classes, "class", "comma separated set of annotation classes to analyse.")
	flag.BoolVar(&pretty, "pretty", true, "outfile JSON data indented.")
	flag.IntVar(&minLength, "min", 20, "minimum length read considered.")
	flag.IntVar(&maxLength, "max", 35, "maximum length read considered.")
	flag.IntVar(&minId, "minid", 90, "minimum percentage identity for mapped bases.")
	flag.IntVar(&minQ, "minQ", 20, "minimum per-base sequence quality.")
	flag.Float64Var(&minAvQ, "minAvQ", 30, "minimum average per-base sequence quality.")
	flag.IntVar(&mapQ, "mapQ", 0, "minimum mapping quality [0, 255).")
	flag.IntVar(&binLength, "bin", 1e7, "bin length.")
	help := flag.Bool("help", false, "output this usage message.")
	flag.Parse()
	mapQb = byte(mapQ)
	if *help {
		flag.Usage()
		os.Exit(0)
	}
	if in == "" || !annotOK(annot, classes) || mapQ < 0 || mapQ > 254 {
		flag.Usage()
		os.Exit(1)
	}
}
Exemplo n.º 6
0
func init() {
	//assign flags
	flag.IntVar(&size, "size", 1000, "usage: -size 1000")
	flag.IntVar(&length, "length", 100000, "usage: -length 1000")
	flag.IntVar(&etime, "time", 1000, "usage: -time 1000")
	flag.IntVar(&sampleSize, "samplesize", 100, "usage: -samplesize 1000")
	flag.IntVar(&stepSize, "stepsize", 1000, "usage: -stepsize 1000")
	flag.IntVar(&maxL, "maxl", 1000, "usage: -maxl 1000")
	flag.IntVar(&fragment, "fragment", 1000, "usage: -fragment 1000")
	flag.Float64Var(&mutationRate, "mutation", 1, "usage: -mutation 1e-8")
	flag.Float64Var(&transferRate, "transfer", 0, "usage: -transfer 1e-9")
	flag.StringVar(&prex, "prex", "default", "usage: -prex default")
	flag.StringVar(&dir, "out", "out", "usage: -dir out")

	// parse flags
	flag.Parse()
	log.SetPrefix(prex + ":")

	// get start time
	tnow = time.Now()
	log.Printf("Begin at %v\n", tnow.Format("Mon Jan 2 15:04:05"))

	// init population
	pop = fwd.NewSeqPopulation(size, length, fragment, mutationRate, transferRate)
	//log.Println("Population: ", pop)
	log.Println("Population initialized.")

	// determine how many cpus that we can use
	ncpu := runtime.NumCPU()
	runtime.GOMAXPROCS(ncpu)
	log.Println("Number of CPU used: ", ncpu)
}
Exemplo n.º 7
0
func handleUpdate() error {
	var api string
	flag.StringVar(&api, "api", "", "Binding host:port for http/artifact server. Optional if SM_API env is set.")
	flag.StringVar(&statsd.Config.ProducerProperties, "producer.properties", "", "Producer.properties file name.")
	flag.StringVar(&statsd.Config.Topic, "topic", "", "Topic to produce data to.")
	flag.StringVar(&statsd.Config.Transform, "transform", "", "Transofmation to apply to each metric. none|avro|proto")
	flag.StringVar(&statsd.Config.SchemaRegistryUrl, "schema.registry.url", "", "Avro Schema Registry url for transform=avro")
	flag.Float64Var(&statsd.Config.Cpus, "cpu", 0.1, "CPUs per task")
	flag.Float64Var(&statsd.Config.Mem, "mem", 64, "Mem per task")

	flag.Parse()

	if err := resolveApi(api); err != nil {
		return err
	}

	request := statsd.NewApiRequest(statsd.Config.Api + "/api/update")
	request.AddParam("producer.properties", statsd.Config.ProducerProperties)
	request.AddParam("topic", statsd.Config.Topic)
	request.AddParam("transform", statsd.Config.Transform)
	request.AddParam("schema.registry.url", statsd.Config.SchemaRegistryUrl)
	request.AddParam("cpu", strconv.FormatFloat(statsd.Config.Cpus, 'E', -1, 64))
	request.AddParam("mem", strconv.FormatFloat(statsd.Config.Mem, 'E', -1, 64))
	response := request.Get()

	fmt.Println(response.Message)

	return nil
}
Exemplo n.º 8
0
// Responsible for loading up our config.json && || all the command lines switches. The way this is setup
// will be order specific on the command line. Only exception to this rule is env-vars (see EnvVars()).
//
// E.g.
//
// # address will override config.json if it is defined in config.json.
// mesos-runonce -config=config.json -address=address
//
// # config.json will override address if it is defined in config.json.
// mesos-runonce -address=address -config=config.json
func loadConfig() *Config {
	cfg := new(Config)

	flag.BoolVar(&cfg.Task.Docker.ForcePullImage, "force-pull", false, "Boolean for forcing pull of image before run.")
	flag.Float64Var(&cfg.Task.Docker.Cpus, "cpus", 1.0, "How many CPUs to use.")
	flag.Float64Var(&cfg.Task.Docker.Mem, "mem", 10, "How much memory to use.")
	flag.IntVar(&cfg.TaskCount, "task-count", 1, "Total task count to run.")
	flag.StringVar(&cfg.Runonce.Address, "address", "127.0.0.1", "Address for mesos to callback on.")
	flag.StringVar(&cfg.Runonce.AuthPrincipal, "principal", "", "Mesos authentication principal.")
	flag.StringVar(&cfg.Runonce.AuthProvider, "authentication-provider", sasl.ProviderName, fmt.Sprintf("Authentication provider to use, default is SASL that supports mechanisms: %+v", mech.ListSupported()))
	flag.StringVar(&cfg.Runonce.AuthSecretFile, "secret-file", "", "Mesos authentication secret file.")
	flag.StringVar(&cfg.Runonce.Master, "master", "127.0.0.1:5050", "Master address <ip:port>")
	flag.StringVar(&cfg.Runonce.MesosRunasUser, "user", "root", "Mesos user to run tasks as.")
	flag.StringVar(&cfg.Runonce.MesosRole, "role", "", "Mesos role to run tasks with.")
	flag.StringVar(&cfg.Task.Docker.Cmd, "docker-cmd", "", "Docker command to run.")
	flag.StringVar(&cfg.Task.Docker.EnvString, "env-vars", "", "Docker env vars for the container. E.g. -env-vars='{\"env\":{\"FOO\":\"bar\"}}'")
	flag.StringVar(&cfg.Task.Docker.Image, "docker-image", "", "Docker image to run.")
	flag.StringVar(&cfg.Task.Id, "task-id", "", "Mesos task id to identify the task.")
	flag.StringVar(&cfg.Task.Name, "task-name", "", "Mesos task name to label the task.")
	flag.UintVar(&cfg.Runonce.BindingPort, "port", 0, "Port for address to use for mesos to callback.")
	flag.Var(cfg, "config", "Runonce config of JSON. See spec in config.go for details.")

	flag.Parse()

	return cfg
}
Exemplo n.º 9
0
func init() {
	flag.Float64Var(&size, "s", 40, "bubble size")
	flag.Float64Var(&niter, "n", 200, "number of iterations")
	flag.Float64Var(&opacity, "o", 0.5, "opacity")
	flag.Parse()
	rand.Seed(int64(time.Now().Nanosecond()) % int64(1e9))
}
Exemplo n.º 10
0
func main() {
	runtime.GOMAXPROCS(2)
	var xmin, ymin, xmax, ymax float64
	var zoomlevel, maptype, max_zoomlevel int
	var filename string

	flag.Float64Var(&xmin, "xmin", 55.397945, "Minimum longitude")
	flag.Float64Var(&xmax, "xmax", 55.402741, "Maximum longitude")
	flag.Float64Var(&ymin, "ymin", 25.291090, "Minimum latitude")
	flag.Float64Var(&ymax, "ymax", 25.292889, "Maximum latitude")
	flag.StringVar(&filename, "filename", "/path/to/file.mbtile", "Output file to generate")
	flag.IntVar(&zoomlevel, "zoomlevel", 19, "Zoom level")
	flag.IntVar(&maptype, "maptype", 0, "0 for Google, 1 for OSM, 2 for mapbox satellite street")
	flag.IntVar(&max_zoomlevel, "max_zoomlevel", MAX_ZOOM_LEVEL, "Maximum zoomlevel to which tiles should be added")
	flag.Parse()

	proj := NewProjection(xmin, ymin, xmax, ymax, zoomlevel, max_zoomlevel)
	tiles := proj.TileList()
	log.Println("Filename: ", filename, " Zoom level ", zoomlevel, "-", max_zoomlevel, "  Number of tiles ", len(tiles))

	db, err := prepareDatabase(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	err = setupMBTileTables(db)
	if err != nil {
		log.Fatal(err)
	}

	inputPipe := make(chan Tile, len(tiles))
	tilePipe := make(chan Tile, len(tiles))
	outputPipe := make(chan Tile, len(tiles))

	for w := 0; w < 20; w++ {
		go tileFetcher(inputPipe, tilePipe, maptype)
	}

	for w := 0; w < 1; w++ {
		go mbTileWorker(db, tilePipe, outputPipe)
	}

	for _, tile := range tiles {
		inputPipe <- tile
	}

	// Waiting to complete the creation of db.
	for i := 0; i < len(tiles); i++ {
		<-outputPipe
	}

	err = optimizeDatabase(db)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Generated ", filename)

}
Exemplo n.º 11
0
func PhaseMain() {
	var a, b float64
	flag.Float64Var(&a, "a", 0.1, "para for logistic map")
	flag.Float64Var(&b, "b", 0.3, "para for logistic map")
	flag.Parse()
	fmt.Printf("Para a: %f, b: %f\n", a, b)
	PhaseGraph(a, b)
}
Exemplo n.º 12
0
func init() {
	width, height = openvg.Init()
	flag.Float64Var(&size, "s", float64(width)*.05, "bubble size")
	flag.IntVar(&niter, "n", width/6, "number of iterations")
	flag.Float64Var(&opacity, "o", 0.5, "opacity")
	flag.Parse()
	rand.Seed(int64(time.Now().Nanosecond()) % 1e9)
}
Exemplo n.º 13
0
func main() {
	var l1weight float64
	var l2weight float64
	var feature_num int
	var m int
	var tol float64
	var quiet bool
	var feature_file string
	var output_file string
	flag.Float64Var(&l1weight, "l1weight", 1.0, "coefficient of l1 regularizer (default is 1)")
	flag.Float64Var(&l2weight, "l2weight", 0.0, "coefficient of l2 regularizer(default is 0)")
	flag.IntVar(&m, "m", 10, "sets L-BFGS memory parameter (default is 10)")
	flag.IntVar(&feature_num, "num", 5, "total feature count")
	flag.Float64Var(&tol, "tol", 0.0001, " sets convergence tolerance (default is 1e-4)")
	flag.BoolVar(&quiet, "quiet", false, "Suppress all output information")
	flag.StringVar(&feature_file, "input", "./testdata", "the path of input feature file")
	flag.StringVar(&output_file, "output", "./model", "the path of output model file")
	flag.Parse()
	fmt.Println("feature_num:", feature_num, "  l1weight:", l1weight)
	lr := owlqn.NewLogisticRegression(feature_file, feature_num)

	obj := owlqn.NewLogisticRegressionObjective(lr, float32(l2weight))

	init := make([]float32, feature_num)
	for i := 0; i < len(init); i++ {
		init[i] = rand.Float32()
	}
	result := make([]float32, feature_num)
	opt := owlqn.NewOWLQN(quiet)
	fmt.Println("init:", init)
	opt.Minimize(obj, init, result, float32(l1weight), float32(tol), m)

	nonZero := 0
	for i := 0; i < feature_num; i++ {
		if result[i] != 0.0 {
			nonZero++
		}
	}
	fmt.Printf("Finished train,%d/%d nonZero weight\n", nonZero, feature_num)
	fmt.Println("result:", result)

	f, err := os.Create(output_file)
	if err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}
	defer f.Close()
	br := bufio.NewWriter(f)
	br.WriteString("feature_num=" + strconv.FormatInt(int64(feature_num), 10) + "\n")
	br.WriteString("l1weight=" + strconv.FormatFloat(float64(l1weight), 'f', 4, 32) + "\n")
	br.Flush()
	for i := 0; i < feature_num; i++ {
		res := strconv.FormatFloat(float64(result[i]), 'f', 4, 32)
		br.WriteString(res + "\n")
		br.Flush()
	}

}
Exemplo n.º 14
0
// init sets up command flags
func init() {
	flag.BoolVar(&localfile, "f", false, "read from local files")
	flag.BoolVar(&postlink, "p", false, "link to original post")
	flag.Float64Var(&ncols, "nc", 5, "number of columns")
	flag.Float64Var(&gutter, "g", 5, "gutter (pixels)")
	flag.Float64Var(&thumbwidth, "tw", 75, "thumbnail width")
	flag.Float64Var(&piclimit, "n", 30, "picture limit")
	flag.StringVar(&filtertag, "tag", "", "filter tag")
	flag.Parse()
}
Exemplo n.º 15
0
func init() {
	flag.StringVar(&algSuffix, "algorithm", "sp", "the algorithm suffix to use")
	flag.StringVar(&constrained, "constrained", "", "name of constraint to pass")
	flag.IntVar(&intConstrained, "intConstrained", 0, "int value of constraint")
	flag.Float64Var(&upperLat, "upperLat", 54.0, "upper latitude")
	flag.Float64Var(&lowerLat, "lowerLat", 47.0, "lower latitude")
	flag.Float64Var(&leftLon, "leftLon", 5.9, "left longitude")
	flag.Float64Var(&rightLon, "rightLon", 14.9, "right longitude")
	flag.UintVar(&numPoints, "numPoints", 2, "number of points in request")
	rand.Seed(42) // So we get always the same points
}
Exemplo n.º 16
0
func getArgs() args {
	params := args{}
	flag.UintVar(&params.sheeplecnt, "sheeple", 0, "Number of sheeple")
	flag.UintVar(&params.tvcnt, "tv", 0, "Number of TVs")
	flag.UintVar(&params.itermax, "iterations", 100, "Number of iterations")
	flag.Float64Var(&params.width, "width", 10, "Torus width")
	flag.Float64Var(&params.height, "height", 10, "Torus height")
	flag.StringVar(&params.beliefs, "beliefs", "A,B,C", "Comma separated belief list")
	flag.Parse()
	return params
}
Exemplo n.º 17
0
Arquivo: ltr.go Projeto: stanim/svgof
// init sets up the command line flags.
func init() {
	flag.BoolVar(&poster, "poster", false, "poster style")
	flag.BoolVar(&opacity, "opacity", false, "opacity style")
	flag.BoolVar(&row, "row", false, "display is a single row")
	flag.BoolVar(&col, "col", false, "display in a single column")
	flag.BoolVar(&offset, "offset", false, "display in a row, even layers offset")
	flag.Float64Var(&width, "width", stdwidth, "image width")
	flag.Float64Var(&height, "height", stdheight, "image height")
	flag.StringVar(&title, "title", "", "title")
	flag.Parse()
}
Exemplo n.º 18
0
func main() {
	cd, err := NewCheckDocker("")
	if err != nil {
		nagios.Critical(err)
	}

	var dockerEndpoint string

	flag.StringVar(&dockerEndpoint, "base-url", "http://localhost:2375", "The Base URL for the Docker server")
	flag.Float64Var(&cd.WarnMetaSpace, "warn-meta-space", 100, "Warning threshold for Metadata Space")
	flag.Float64Var(&cd.CritMetaSpace, "crit-meta-space", 100, "Critical threshold for Metadata Space")
	flag.Float64Var(&cd.WarnDataSpace, "warn-data-space", 100, "Warning threshold for Data Space")
	flag.Float64Var(&cd.CritDataSpace, "crit-data-space", 100, "Critical threshold for Data Space")
	flag.StringVar(&cd.ImageId, "image-id", "", "An image ID that must be running on the Docker server")
	flag.StringVar(&cd.ContainerName, "container-name", "", "The name of a container that must be running on the Docker server")
	flag.StringVar(&cd.TLSCertPath, "tls-cert", "", "Path to TLS cert file.")
	flag.StringVar(&cd.TLSKeyPath, "tls-key", "", "Path to TLS key file.")
	flag.StringVar(&cd.TLSCAPath, "tls-ca", "", "Path to TLS CA file.")

	flag.Parse()

	err = cd.setupClient(dockerEndpoint)
	if err != nil {
		nagios.Critical(err)
	}

	err = cd.GetData()
	if err != nil {
		nagios.Critical(err)
	}

	baseStatus := &nagios.NagiosStatus{fmt.Sprintf("Total Containers: %v", len(cd.dockerContainersData)), nagios.NAGIOS_OK}

	statuses := make([]*nagios.NagiosStatus, 0)

	driver := cd.dockerInfoData.Get("Driver")

	// Unfortunately, Metadata Space and Data Space information is only available on devicemapper
	if driver == "devicemapper" {
		statuses = append(statuses, cd.CheckMetaSpace(cd.WarnMetaSpace, cd.CritMetaSpace))
		statuses = append(statuses, cd.CheckDataSpace(cd.WarnDataSpace, cd.CritDataSpace))
	}

	if cd.ImageId != "" {
		statuses = append(statuses, cd.CheckImageContainerIsInGoodShape(cd.ImageId))
	}

	if cd.ContainerName != "" {
		statuses = append(statuses, cd.CheckNamedContainerIsInGoodShape(cd.ContainerName))
	}

	baseStatus.Aggregate(statuses)
	nagios.ExitWithStatus(baseStatus)
}
Exemplo n.º 19
0
func init() {
	flag.Usage = usage

	flag.StringVar(&filename, "o", "fractal.png", "output filename.")
	flag.IntVar(&width, "width", 1920, "image width.")
	flag.IntVar(&height, "height", 1080, "image height.")
	flag.Float64Var(&iterations, "i", 1000, "number of iterations.")
	flag.Float64Var(&zoom, "z", 1, "zoom level.")
	flag.Float64Var(&centerReal, "cr", 0, "real value of center offset.")
	flag.Float64Var(&centerImag, "ci", 0, "imaginary value of center offset.")
	flag.StringVar(&colorScheme, "t", "smooth", "color scheme")
}
Exemplo n.º 20
0
func parseArguments(args *commandLine) {
	flag.UintVar(&args.iterateLimit, "iterateLimit", 255, "Maximum number of iterations")
	flag.Float64Var(&args.divergeLimit, "divergeLimit", 4.0, "Limit where function is said to diverge to infinity")
	flag.UintVar(&args.width, "imageWidth", 800, "Width of output PNG")
	flag.UintVar(&args.height, "imageHeight", 600, "Height of output PNG")
	flag.StringVar(&args.filename, "filename", "mandelbrot.png", "Name of output PNG")
	flag.Float64Var(&args.xOffset, "xOffset", -1.5, "Leftmost position of complex plane projected onto PNG image")
	flag.Float64Var(&args.yOffset, "yOffset", 1.0, "Topmost position of complex plane projected onto PNG image")
	flag.Float64Var(&args.zoom, "zoom", 1.0, "Look into the eyeball")
	flag.StringVar(&args.mode, "mode", "sequential", "Render mode")
	flag.Parse()
}
Exemplo n.º 21
0
func main() {
	flag.BoolVar(&options.verbose, "verbose", false, "Print a bunch of debugging information as we run")
	flag.BoolVar(&options.debug, "debug", false, "Dump intermediate images for debugging")
	flag.IntVar(&options.threshold, "threshold", 100, "Number of pixels below which differences are ignored")
	flag.Float64Var(&options.gamma, "gamma", 2.2, "Value to convert rgb into linear space")
	flag.Float64Var(&options.luminance, "luminance", 100.0, "White luminance (default 100 cdm^-2)")
	flag.BoolVar(&options.luminanceOnly, "luminanceOnly", false, "Only consider luminance; ignore color in the comparision")
	flag.Float64Var(&options.colorFactor, "colorFactor", 1.0, "How much of color to use (0.0 = ignore color, 1.0 = use it all)")
	flag.IntVar(&options.downsample, "downsample", 0, "How many powers of 2 to down sample the images")
	flag.StringVar(&options.output_fname, "output", "", "Write differences to the given filename")
	flag.Float64Var(&options.fov, "fov", 45.0, "Field of View subtended by the image (0.1 to 89.9)")

	flag.Parse()

	files := flag.Args()

	if len(files) != 2 {
		fmt.Println("I need two files to compare (I got", len(files), "files)")
		os.Exit(1)
	}

	if options.verbose {
		log.Println("I'm going to compare", files[0], "and", files[1])
	}

	images := loadImages(files)

	options.output = nil

	if options.output_fname != "" {
		options.output = MakeFloatGrayImage(images[0].Bounds().Max.X, images[0].Bounds().Max.Y)
	}

	if options.verbose {
		log.Println("Everything looks good, let's do the compare.")
	}

	result, num_pixels_different := Yee_Compare(images[0], images[1])

	if result {
		log.Println("Image compare succeeded!")
	} else {
		log.Println("Image compare failed.")
	}

	if num_pixels_different > 0 && options.output != nil {
		log.Printf("Writing differing pixels to %s", options.output_fname)
		options.output.Dump(options.output_fname)
	}

}
Exemplo n.º 22
0
func parseCommandLine() *options {
	var options options
	flag.Usage = usage
	flag.Float64Var(&options.criticalThreshold, "critical", 0, "Critical threshold")
	flag.Var(newDimensionsValue([]cloudwatch.Dimension{}, &options.dimensions), "dimension", "The dimensions of the metric")
	flag.StringVar(&options.metricName, "metric-name", "", "The name of the metric")
	flag.StringVar(&options.namespace, "namespace", "", "The namespace of the metric")
	flag.IntVar(&options.period, "period", 60, "The length in seconds for aggregation")
	flag.Var(newRegionValue(aws.Region{}, &options.region), "region", "AWS region")
	flag.StringVar(&options.statistic, "statistic", "", "The statistic of the metric")
	flag.Float64Var(&options.warningThreshold, "warning", 0, "Warning threshold")
	flag.Parse()
	return &options
}
Exemplo n.º 23
0
Arquivo: util.go Projeto: jnb666/gogp
// ParseFlags reads command flags and sets no. of threads and random seed.
func ParseFlags(opts *Options) {
	flag.IntVar(&opts.MaxGen, "gens", opts.MaxGen, "maximum no. of generations")
	flag.IntVar(&opts.TournSize, "tournsize", opts.TournSize, "tournament size")
	flag.IntVar(&opts.PopSize, "popsize", opts.PopSize, "population size")
	flag.IntVar(&opts.Threads, "threads", opts.Threads, "number of parallel threads")
	flag.Int64Var(&opts.Seed, "seed", opts.Seed, "random seed - set randomly if <= 0")
	flag.Float64Var(&opts.TargetFitness, "target", opts.TargetFitness, "target fitness")
	flag.Float64Var(&opts.CrossoverProb, "cxprob", opts.CrossoverProb, "crossover probability")
	flag.Float64Var(&opts.MutateProb, "mutprob", opts.MutateProb, "mutation probability")
	flag.BoolVar(&opts.Plot, "plot", opts.Plot, "serve plot data via http")
	flag.BoolVar(&opts.Verbose, "v", opts.Verbose, "print out best individual so far")
	flag.Parse()
	gp.SetSeed(opts.Seed)
	runtime.GOMAXPROCS(opts.Threads)
}
Exemplo n.º 24
0
func init() {
	_opts = &Options{}
	flag.StringVar(&_opts.master, "master", "local", "master of Mesos: local, host[:port], or mesos://")
	flag.IntVar(&_opts.parallel, "p", 0, "number of processes")
	flag.Float64Var(&_opts.cpus, "c", 1.0, "cpus used per task")
	flag.Float64Var(&_opts.mem, "M", 128.0, "memory used per task")
	flag.StringVar(&_opts.group, "g", "", "which group of machine")

	flag.Float64Var(&_opts.err, "err", 0.0, "acceptable ignored error record ratio (0.01%)")
	flag.StringVar(&_opts.snapshot_dir, "snapshot_dir", "", "shared dir to keep snapshot of RDDs")
	flag.StringVar(&_opts.conf, "conf", "", "path for configuration file")

	flag.StringVar(&_opts.process_child, "process_child", "", "not use by human.")
	flag.StringVar(&_opts.mesos_executor, "mesos_executor", "", "not use by human.")
}
Exemplo n.º 25
0
func main() {

	verbose = 0
	warn_level := 10.00
	crit_level := 5.00
	username := ""
	password := ""

	flag.Usage = usage
	flag.IntVar(&verbose, "verbose", 0, "verbosity level (0-3)")
	flag.Float64Var(&warn_level, "warning", 100.00, "warn when balance is below this value")
	flag.Float64Var(&crit_level, "critical", 25.00, "critical when balance is below this value")
	flag.StringVar(&username, "username", "", "API Username")
	flag.StringVar(&password, "password", "", "API Password")
	flag.Parse()

	if verbose >= 3 {
		fmt.Println("Verbosity level:", verbose)
		fmt.Println("Warning level:", warn_level)
		fmt.Println("Critical level:", crit_level)
	}

	balance, err := get_balance(username, password)
	if err != nil {
		fmt.Println("Balance Unknown:", err)
		os.Exit(3)
	}

	if verbose >= 2 {
		fmt.Println("Balance:", balance)
	}

	// check if balance is below critical threshold
	if balance <= crit_level {
		fmt.Printf("Balance Critical - $%.2f\n", balance)
		os.Exit(2)
	}

	// check if balance is below warning threshold
	if balance <= warn_level {
		fmt.Printf("Balance Warning - $%.2f\n", balance)
		os.Exit(1)
	}

	// balance must be ok
	fmt.Printf("Balance OK - $%.2f\n", balance)
	os.Exit(0)
}
Exemplo n.º 26
0
func (c *cover) setOptions() {
	flag.BoolVar(&c.set, "cover", false, "Use the cover tool.")
	flag.BoolVar(&c.open, "open", true,
		"Open the results of the cover tool on the browser.")
	flag.Float64Var(&c.threshold,
		"threshold", defaultThreshold, "The accepted code coverage threshold.")
}
Exemplo n.º 27
0
func init() {
	potentialQueues := os.Getenv("WORKER_QUEUES")
	potentialConcurrency := os.Getenv("WORKER_CONCURRENCY")

	concurrency = 25

	if potentialConcurrency != "" {
		tmp, _ := strconv.ParseInt(potentialConcurrency, 10, 32)
		concurrency = int(tmp)
	}

	flag.StringVar(&queuesString, "queues", potentialQueues, "a comma-separated list of Resque queues")
	flag.Float64Var(&intervalFloat, "interval", 5.0, "sleep interval when no jobs are found")
	flag.IntVar(&concurrency, "concurrency", concurrency, "the maximum number of concurrently executing jobs")
	flag.IntVar(&connections, "connections", 2, "the maximum number of connections to the Redis database")

	redisProvider := os.Getenv("REDIS_PROVIDER")
	var redisEnvUri string
	if redisProvider != "" {
		redisEnvUri = os.Getenv(redisProvider)
	} else {
		redisEnvUri = os.Getenv("REDIS_URL")
	}
	if redisEnvUri == "" {
		redisEnvUri = "redis://localhost:6379/"
	}

	flag.StringVar(&uri, "uri", redisEnvUri, "the URI of the Redis server")
	flag.StringVar(&namespace, "namespace", "resque:", "the Redis namespace")
	flag.BoolVar(&exitOnComplete, "exit-on-complete", false, "exit when the queue is empty")
	flag.BoolVar(&useNumber, "use-number", false, "use json.Number instead of float64 when decoding numbers in JSON. will default to true soon")
}
Exemplo n.º 28
0
func main() {

	// Set up and parse command-line args.
	runtime.GOMAXPROCS(runtime.NumCPU())
	flag.StringVar(&host, "host", "127.0.0.1", "")
	flag.Float64Var(&numSeconds, "num-seconds", 10, "")
	flag.IntVar(&numClients, "num-clients", 1, "")
	flag.IntVar(&numChannels, "num-channels", 50, "")
	flag.IntVar(&messageSize, "message-size", 20, "")
	flag.BoolVar(&useRedis, "redis", false, "")
	flag.BoolVar(&quiet, "quiet", false, "")
	flag.Parse()
	for i := 0; i < numChannels; i++ {
		channels = append(channels, strconv.Itoa(i))
	}

	// Create publisher/subscriber goroutines, pausing to allow
	// publishers to hit full throttle
	RunWorkers(Publisher)
	time.Sleep(1 * time.Second)
	RunWorkers(Subscriber)

	// Consume metrics until --num-seconds has passed, and display
	// the median value.
	metrics := GetMetrics()
	sort.Ints(metrics)
	fmt.Println("Num clients", numClients, "median", metrics[len(metrics)/2], "msg/sec")

}
Exemplo n.º 29
0
func init() {
	flag.IntVar(&size, "size", 1000000, "population size")
	flag.IntVar(&sample, "sample", 2, "sample size")
	flag.IntVar(&length, "genome", 10000, "genome length")
	flag.IntVar(&fragment, "frag", 100, "fragment length (ratio)")
	flag.IntVar(&repeats, "rep", 1000, "repeats")
	flag.IntVar(&maxl, "maxl", 100, "maxl")
	flag.Float64Var(&transfer, "transfer", 1e-6, "transfer rate")
	flag.Float64Var(&mutation, "mutation", 1e-8, "mutation rate")
	flag.StringVar(&prefix, "prefix", "", "prefix")

	flag.Parse()
	if maxl < 2*fragment {
		maxl = 2 * fragment
	}
}
Exemplo n.º 30
0
func init() {
	// config.Path
	//flag.StringVar(&path , "path" , "" , "path")
	flag.StringVar(&path, "u", "", "Target URL.")

	// config.NumConns
	//flag.IntVar(&conns , "num-conns" , 0 , "num-conns")
	flag.IntVar(&conns, "n", 0, "Total number of connections.")

	// config.Rate
	flag.Float64Var(&rate, "r", 0, "Connection rate (per second).")

	// config.Verbose
	//flag.BoolVar(&verbose , "verbose" , false , "verbose")
	flag.BoolVar(&verbose, "v", false, "Print verbose messaging.")

	flag.BoolVar(&version, "version", false, "Show version infomration.")

	flag.Parse()

	if version {
		fmt.Printf("goperf version %v\n", perf.Version)
		os.Exit(0)
	}

	if path == "" || conns == 0 {
		flag.Usage()
		os.Exit(0)
	}
}