Ejemplo n.º 1
0
func main() {
	maxSideLength := flag.Float64("max", 1, "maximum side length")
	minSideLength := flag.Float64("min", 1, "minimum side length")
	flag.Parse()

	cuboidStream := make(chan Cuboid, NUM_CONCURRENT_CUBOID_SEARCHES)
	perfectCuboid := make(chan Cuboid)
	wg := new(sync.WaitGroup)

	go waitForPerfectCuboid(perfectCuboid)
	go distributeCuboids(cuboidStream, perfectCuboid, wg)

	fmt.Printf("Searching for a perfect cuboid with side lengths between %d and %d...", int(*minSideLength), int(*maxSideLength))

	x := 1.0
	for x <= *maxSideLength {
		y := 1.0
		for y <= *maxSideLength {
			z := 1.0
			for z <= *maxSideLength {
				if x >= *minSideLength || y >= *minSideLength || z >= *minSideLength {
					wg.Add(1)
					cuboid := Cuboid{Length: x, Width: y, Height: z}
					cuboidStream <- cuboid
				}
				z += 1
			}
			y += 1
		}
		x += 1
	}

	wg.Wait()
	fmt.Println(" done.")
}
Ejemplo n.º 2
0
func main() {
	debug := flag.Bool("debug", false, "debug on")
	threaded := flag.Bool("threaded", true, "debug on")
	delcache_ttl := flag.Float64("deletion_cache_ttl", 5.0, "Deletion cache TTL in seconds.")
	branchcache_ttl := flag.Float64("branchcache_ttl", 5.0, "Branch cache TTL in seconds.")
	deldirname := flag.String(
		"deletion_dirname", "GOUNIONFS_DELETIONS", "Directory name to use for deletions.")
	flag.Parse()

	if len(flag.Args()) < 2 {
		fmt.Println("Usage:\n  main MOUNTPOINT RW-DIRECTORY RO-DIRECTORY ...")
		os.Exit(2)
	}

	ufsOptions := unionfs.UnionFsOptions{
		DeletionCacheTTLSecs: *delcache_ttl,
		BranchCacheTTLSecs:   *branchcache_ttl,
		DeletionDirName:      *deldirname,
	}

	ufs, err := unionfs.NewUnionFsFromRoots(flag.Args()[1:], &ufsOptions)
	if err != nil {
		log.Fatal("Cannot create UnionFs", err)
		os.Exit(1)
	}
	mountState, _, err := fuse.MountFileSystem(flag.Arg(0), ufs, nil)
	if err != nil {
		log.Fatal("Mount fail:", err)
	}

	mountState.Debug = *debug
	mountState.Loop(*threaded)
}
Ejemplo n.º 3
0
func main() {

	// Set up flags.
	wFlag := flag.Int("w", 640, "width of the image in pixels")
	hFlag := flag.Int("h", 480, "height of the image in pixels")
	xMinFlag := flag.Float64("x-min", -2.0, "minimum x value to plot")
	xMaxFlag := flag.Float64("x-max", 2.0, "maximum x value to plot")
	bailoutFlag := flag.Int("bailout", 100, "maximum iteration bailout")

	// Handle the flags.
	flag.Parse()

	// Main logic.
	acc := newAccumulator(*wFlag, *hFlag, *xMinFlag, *xMaxFlag)
	const numSamples = 1e8
	for acc.getCount() < numSamples {
		log.Print(acc.getCount())
		accumulateSeqence(*bailoutFlag, acc)
	}

	img := acc.toImage()
	f, err := os.Create("out.png")
	if err != nil {
		log.Fatal(err)
	}
	if err := png.Encode(f, img); err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 4
0
func main() {
	drinks := flag.Float64("drinks", 2.5, "How many drinks consumed")
	weight := flag.Float64("weight", 70.0, "Body weight in kilograms")
	hours := flag.Float64("hours", 2.0, "How many hours it took to drink")
	gender := flag.String("gender", "male", "Specify male or female")

	flag.Usage = func() {
		fmt.Println(`
  NAME:

    inebriati

  DESCRIPTION:

    Calculates estimated blood ethanol concentration (EBAC) 

  COMMANDS:

    -drinks              Number of standard drinks comsumed.
    -weight              Weight in kiligrams.
    -hours               Drinking period in hours.
    -gender              Select male or female.
`[1:])
	}

	flag.Parse()

	i := inebriati.New(*drinks, *weight, *hours, *gender)
	i.Calc()

	fmt.Println(i)
}
Ejemplo n.º 5
0
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)
}
Ejemplo n.º 6
0
func handleAddConsumer() error {
	id := stripArgument()
	if id == "" {
		return errors.New("No task id supplied to add")
	}
	var (
		api = flag.String("api", "", "API host:port")
		cpu = flag.Float64("cpu", 0.1, "CPUs per task")
		mem = flag.Float64("mem", 128, "Mem per task")
	)
	ParseFlags("add")
	if err := resolveApi(*api); err != nil {
		return err
	}

	if *executor == "" {
		return errors.New("Executor name required")
	}

	request := framework.NewApiRequest(framework.Config.Api + "/api/add")
	request.PutString("type", framework.TaskTypeConsumer)
	request.PutString("id", id)
	request.PutFloat("cpu", *cpu)
	request.PutFloat("mem", *mem)
	request.PutString("executor", *executor)

	response := request.Get()

	fmt.Println(response.Message)

	return nil
}
Ejemplo n.º 7
0
Archivo: od.go Proyecto: kisom/laserod
func main() {
	diameter := flag.Float64("d", 9.0, "beam diameter in millimetres")
	power := flag.Float64("p", 1.0, "laser power in watts")
	flag.Parse()

	if *diameter <= 0.0 {
		fmt.Println("Beam diameter must be a positive number greater than zero.")
		return
	}

	*diameter /= 1000.0 // convert mm to m
	ba := beamArea(*diameter)
	pd := powerDensity(ba, *power)
	od := opticalDensity(pd)
	fmt.Printf("Beam area: %f m^2\nPower density: %f W/m^2\n", ba, pd)
	if od == -1 {
		fmt.Println("Couldn't determine the appropriate optical density rating.")
		fmt.Println("Please consult EN207 for the appopriate PPE.")
	} else if od == 11 {
		fmt.Printf("Your optical density requirements are above the ")
		fmt.Printf("standard requirements. Please consult EN207.\n")
	} else {
		fmt.Printf("Based on your laser's power and beam diameter, ")
		fmt.Printf("you should use eyewear with an OD of %d.\n", od)
	}
}
func main() {

	var data = flag.String("data", "", "The data directory where WOF data lives, required")
	var cache_size = flag.Int("cache_size", 1024, "The number of WOF records with large geometries to cache")
	var cache_trigger = flag.Int("cache_trigger", 2000, "The minimum number of coordinates in a WOF record that will trigger caching")

	var lat = flag.Float64("latitude", 0.0, "")
	var lon = flag.Float64("longitude", 0.0, "")

	var loglevel = flag.String("loglevel", "info", "...")

	flag.Parse()

	logger := log.NewWOFLogger("[wof-breaches] ")
	logger.AddLogger(os.Stdout, *loglevel)

	idx, _ := rtree.NewIndex(*data, *cache_size, *cache_trigger, logger)

	for _, path := range flag.Args() {

		logger.Info("indexing %s", path)
		idx.IndexGeoJSONFile(path)
	}

	results := idx.GetIntersectsByLatLon(*lat, *lon)
	inflated := idx.InflateSpatialResults(results)

	for _, r := range inflated {
		logger.Info("%v", r)
	}
}
Ejemplo n.º 9
0
func main() {
	// do the actual parsing
	flag.Var(&listenersFlag, "l", "Which ports to listen on")
	flag.Var(&connectorsFlag, "c", "Which addresses to try to connect to")
	flag.BoolVar(&infoptr, "v", false, "Turn on verbose mode")
	flag.BoolVar(&debugptr, "vv", false, "Turn on extra verbose mode")
	retryPeriod = time.Duration(1000 * (*flag.Float64("rp", 5.0,
		"Retry rate for double connections")))
	connPeriod = time.Duration(1000 * (*flag.Float64("cp", 0.5,
		"Retry rate for double connections, on success")))
	flag.Parse()

	debug("Number of listeners: " + fmt.Sprint(len(listenersFlag)))
	debug("Number of connectors: " + fmt.Sprint(len(connectorsFlag)))
	// check a possibly temporary condition
	if len(listenersFlag)+len(connectorsFlag) != 2 {
		errmsg(1, "Strictly 2 connections allowed")
	}

	if len(listenersFlag) == 1 && len(connectorsFlag) == 1 {
		listenOne(normalizeAddr(listenersFlag[0]),
			normalizeAddr(connectorsFlag[0]))
	}
	if len(listenersFlag) == 2 && len(connectorsFlag) == 0 {
		listenTwo(normalizeAddr(listenersFlag[0]),
			normalizeAddr(listenersFlag[1]))
	}
	if len(listenersFlag) == 0 && len(connectorsFlag) == 2 {
		connectTwo(normalizeAddr(connectorsFlag[0]),
			normalizeAddr(connectorsFlag[1]))
	}
}
Ejemplo n.º 10
0
func main() {
	count := flag.Int("count", 5, "The number of pings to send")
	wait := flag.Float64("wait", 15, "The amount of time to wait for all pings to come back in seconds")
	interval := flag.Float64("interval", 2, "The interval to wait between pings in seconds")
	repeat := flag.Int("repeat", 30, "Repeat the whole process every x seconds")
	socket := flag.String("socket", "/tmp/ping-monitor.sock", "Unix socket to create/listen on")

	flag.Parse()

	if len(flag.Args()) < 1 {
		os.Stderr.WriteString("Must supply at least one IP address!\n")
		os.Exit(1)
	}

	h := &httpmetrics.Handler{
		Socket:     *socket,
		Registries: make(map[string]*metrics.Registry),
	}

	pi := &PingInfo{
		Count:      *count,
		Wait:       *wait,
		Interval:   *interval,
		Repeat:     *repeat,
		Hosts:      flag.Args(),
		Registries: &(h.Registries),
	}

	InitPing(pi)

	if err := h.CreateServer(); err != nil {
		panic(err)
	}
}
Ejemplo n.º 11
0
func TestParse_Global(t *testing.T) {
	resetForTesting("")

	os.Setenv(envTestPrefix+"D", "EnvD")
	os.Setenv(envTestPrefix+"E", "true")
	os.Setenv(envTestPrefix+"F", "5.5")

	flagA := flag.Bool("a", false, "")
	flagB := flag.Float64("b", 0.0, "")
	flagC := flag.String("c", "", "")

	flagD := flag.String("d", "", "")
	flagE := flag.Bool("e", false, "")
	flagF := flag.Float64("f", 0.0, "")

	parse(t, "./testdata/global.ini", envTestPrefix)
	if !*flagA {
		t.Errorf("flagA found %v, expected true", *flagA)
	}
	if *flagB != 5.6 {
		t.Errorf("flagB found %v, expected 5.6", *flagB)
	}
	if *flagC != "Hello world" {
		t.Errorf("flagC found %v, expected 'Hello world'", *flagC)
	}
	if *flagD != "EnvD" {
		t.Errorf("flagD found %v, expected 'EnvD'", *flagD)
	}
	if !*flagE {
		t.Errorf("flagE found %v, expected true", *flagE)
	}
	if *flagF != 5.5 {
		t.Errorf("flagF found %v, expected 5.5", *flagF)
	}
}
Ejemplo n.º 12
0
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
}
Ejemplo n.º 13
0
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)
}
Ejemplo n.º 14
0
func main() {
	var seq_file = flag.String("s", "", "Specify a file containing the sequence.")
	var rl = flag.Int("l", 100, "Read length.")
	var coverage = flag.Float64("c", 2.0, "Coverage")
	var error_rate = flag.Float64("e", 0.01, "Error rate.")
	flag.BoolVar(&Debug, "debug", false, "Turn on debug mode.")
	flag.Parse()
	read_len := int(*rl)
	if *seq_file != "" {
		if *coverage > 0 && read_len > 0 {
			idx := fmi.New(*seq_file)
			num_of_reads := int(*coverage * float64(idx.LEN) / float64(read_len))
			read_indices := make([]int, num_of_reads)
			the_read := make([]byte, read_len)
			var rand_pos int

			for i := 0; i < num_of_reads; i++ {
				rand_pos = int(rand_gen.Intn(int(idx.LEN - read_len)))
				if justN(rand_pos, int(read_len)) {
					i--
					continue
				}

				read_indices = idx.Repeat(rand_pos, read_len)
				var errors []int
				if int(rand_pos+read_len) >= len(fmi.SEQ) {
					panic("Read may be shorter than wanted.")
				}

				copy(the_read, fmi.SEQ[rand_pos:rand_pos+read_len])
				for k := 0; k < len(the_read); k++ {
					if rand_gen.Float64() < *error_rate {
						the_read[k] = random_error(the_read[k])
						errors = append(errors, k)
					}
				}
				if Debug {
					for j := 0; j < int(rand_pos); j++ {
						fmt.Printf(" ")
					}
				}
				fmt.Printf("%s %d ", the_read, len(read_indices))
				for j := 0; j < len(read_indices); j++ {
					fmt.Printf("%d ", read_indices[j])
				}
				fmt.Printf("%d", len(errors))
				for j := 0; j < len(errors); j++ {
					fmt.Printf(" %d", errors[j])
				}
				fmt.Println()
			}
		} else {
			idx := fmi.New(*seq_file)
			idx.Save(*seq_file)
		}
	} else {
		fmt.Println("Must provide sequence file")
	}
}
Ejemplo n.º 15
0
func main() {
	var ohms = flag.Float64("r", 0, "ohms")
	var watts = flag.Float64("w", 0, "watts")
	var amps = flag.Float64("a", 0, "amps")
	var volts = flag.Float64("v", 0, "volts")
	flag.Parse()
	fmt.Printf("O: %f\tW: %f\tA: %f\tV: %f\n", *ohms, *watts, *amps, *volts)
}
Ejemplo n.º 16
0
func init() {

	img_width = flag.Int("w", 1280, "The width of the resulting image.")
	img_height = flag.Int("h", 800, "The height of the resulting image.")
	mset_x_ctr = flag.Float64("x", -0.75, "The center of the image with respect to the x-axis of the Mandelbrot Set, between -2.5 and 1.")
	mset_y_ctr = flag.Float64("y", 0, "The center of the image with respect to the y-axis of the Mandelbrot Set, between -1 and 1.")
	zoom = flag.Float64("z", 1, "Zoom factor.")
	max_iterations = flag.Int64("i", 1000, "The number of iterations to perform before considering a coordinate going to infinity.")
}
Ejemplo n.º 17
0
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
}
Ejemplo n.º 18
0
func main() {
	var (
		width        = flag.Int("w", 1024, "width")
		top          = flag.Int("top", 50, "top")
		left         = flag.Int("left", 100, "left margin")
		vp           = flag.Int("vp", 512, "visualization point")
		vw           = flag.Int("vw", 300, "visual area width")
		bh           = flag.Int("bh", 20, "bar height")
		smax         = flag.Float64("sm", 10, "maximum speedup")
		dmax         = flag.Float64("dm", 100, "maximum delta")
		title        = flag.String("title", "", "title")
		speedcolor   = flag.String("scolor", "green", "speedup color")
		regresscolor = flag.String("rcolor", "red", "regression color")
		style        = flag.String("style", "bar", "set the style (bar or inline)")
		lines        = flag.Bool("line", false, "show lines between entries")
		coldata      = flag.Bool("col", false, "show data in a single column")
	)
	flag.Parse()

	g := geometry{
		width:      *width,
		top:        *top,
		left:       *left,
		vp:         *vp,
		vwidth:     *vw,
		barHeight:  *bh,
		title:      *title,
		scolor:     *speedcolor,
		rcolor:     *regresscolor,
		style:      *style,
		dolines:    *lines,
		coldata:    *coldata,
		speedupmax: *smax,
		deltamax:   *dmax,
	}

	// For every named file or stdin, render the SVG in memory, accumulating the height.
	var b bytes.Buffer
	canvas := svg.New(&b)
	height := 0
	if len(flag.Args()) > 0 {
		for _, f := range flag.Args() {
			height = process(canvas, f, g)
			g.top = height + 50
		}
	} else {
		height = process(canvas, "", g)
	}
	g.height = height + 15

	// Write the rendered SVG to stdout
	out := svg.New(os.Stdout)
	out.Start(g.width, g.height)
	out.Rect(0, 0, g.width, g.height, "fill:white;stroke-width:2px;stroke:lightgray")
	b.WriteTo(os.Stdout)
	out.End()
}
Ejemplo n.º 19
0
Archivo: main.go Proyecto: eliq/go-fuse
func main() {
	debug := flag.Bool("debug", false, "debug on")
	hardlinks := flag.Bool("hardlinks", false, "support hardlinks")
	delcache_ttl := flag.Float64("deletion_cache_ttl", 5.0, "Deletion cache TTL in seconds.")
	branchcache_ttl := flag.Float64("branchcache_ttl", 5.0, "Branch cache TTL in seconds.")
	deldirname := flag.String(
		"deletion_dirname", "GOUNIONFS_DELETIONS", "Directory name to use for deletions.")
	hide_readonly_link := flag.Bool("hide_readonly_link", true,
		"Hides READONLY link from the top mountpoints. "+
			"Enabled by default.")
	portableInodes := flag.Bool("portable-inodes", false,
		"Use sequential 32-bit inode numbers.")

	flag.Parse()

	if len(flag.Args()) < 2 {
		fmt.Println("Usage:\n  main MOUNTPOINT BASEDIR")
		os.Exit(2)
	}
	ufsOptions := unionfs.UnionFsOptions{
		DeletionCacheTTL: time.Duration(*delcache_ttl * float64(time.Second)),
		BranchCacheTTL:   time.Duration(*branchcache_ttl * float64(time.Second)),
		DeletionDirName:  *deldirname,
	}
	options := unionfs.AutoUnionFsOptions{
		UnionFsOptions: ufsOptions,
		Options: nodefs.Options{
			EntryTimeout:    time.Second,
			AttrTimeout:     time.Second,
			NegativeTimeout: time.Second,
			Owner:           fuse.CurrentOwner(),
		},
		UpdateOnMount: true,
		PathNodeFsOptions: pathfs.PathNodeFsOptions{
			ClientInodes: *hardlinks,
		},
		HideReadonly: *hide_readonly_link,
	}
	fsOpts := nodefs.Options{
		PortableInodes: *portableInodes,
	}
	gofs := unionfs.NewAutoUnionFs(flag.Arg(1), options)
	pathfs := pathfs.NewPathNodeFs(gofs, nil)
	state, conn, err := nodefs.MountRoot(flag.Arg(0), pathfs.Root(), &fsOpts)
	if err != nil {
		fmt.Printf("Mount fail: %v\n", err)
		os.Exit(1)
	}

	pathfs.SetDebug(*debug)
	conn.SetDebug(*debug)
	state.SetDebug(*debug)

	state.Serve()
	time.Sleep(1 * time.Second)
}
Ejemplo n.º 20
0
func main() {
	var pv = flag.Float64("pv", 0, "Present Value")
	var r = flag.Float64("r", 0, "Interest Rate")
	var n = flag.Int("n", 0, "Number of periods")
	var c = flag.Bool("c", false, "Compounded Interest")
	var d = flag.Int("d", 4, "Digits after the decimal point")
	flag.Parse()
	f := F.Fee(*pv, *r, *n, *c)
	println(strconv.FormatFloat(f, 'f', *d, 64))
}
Ejemplo n.º 21
0
// Generates the golden files. See test/sounds_test.go for actual test.
func main() {
	// Singlethreaded for now...
	runtime.GOMAXPROCS(4)

	// Parse flags...
	sampleRate := s.CyclesPerSecond
	minFreq := flag.Float64("minFreq", 110.0, "minimum frequency")
	maxFreq := flag.Float64("maxFreq", 14080.0, "maximum frequency")
	bpo := flag.Int("bpo", 24, "Buckets per octave")
	flag.Parse()

	remainingArgs := flag.Args()
	if len(remainingArgs) < 1 || len(remainingArgs) > 2 {
		panic("Required: <input> [<input>] filename arguments")
	}
	inputFile := remainingArgs[0]
	inputFile2 := inputFile
	if len(remainingArgs) == 2 {
		inputFile2 = remainingArgs[1]
	}

	inputSound := f.Read(inputFile)
	// inputSound := s.NewTimedSound(s.NewSineWave(440.0), 1000)
	inputSound.Start()
	defer inputSound.Stop()

	// minFreq, maxFreq, bpo := 110.0, 14080.0, 24
	params := cq.NewCQParams(sampleRate, *minFreq, *maxFreq, *bpo)
	constantQ := cq.NewConstantQ(params)
	cqInverse := cq.NewCQInverse(params)
	latency := constantQ.OutputLatency + cqInverse.OutputLatency

	// Two inputs version - TODO, switch back to input + output.
	inputSound2 := f.Read(inputFile2)
	inputSound2.Start()
	defer inputSound2.Stop()
	constantQ2 := cq.NewConstantQ(params)

	startTime := time.Now()
	// TODO: Skip the first 'latency' samples for the stream.
	fmt.Printf("TODO: Skip latency (= %d) samples)\n", latency)
	columns := constantQ.ProcessChannel(inputSound.GetSamples())
	columns2 := constantQ2.ProcessChannel(inputSound2.GetSamples())
	samples := cqInverse.ProcessChannel(mergeChannels(columns, columns2))
	asSound := s.WrapChannelAsSound(samples)

	// if outputFile != "" {
	// f.Write(asSound, outputFile)
	// } else {
	output.Play(asSound)
	// }

	elapsedSeconds := time.Since(startTime).Seconds()
	fmt.Printf("elapsed time (not counting init): %f sec\n", elapsedSeconds)
}
Ejemplo n.º 22
0
func main() {
	version := flag.Bool("version", false, "print version number")
	debug := flag.Bool("debug", false, "debug on")
	hardlinks := flag.Bool("hardlinks", false, "support hardlinks")
	delcache_ttl := flag.Float64("deletion_cache_ttl", 5.0, "Deletion cache TTL in seconds.")
	branchcache_ttl := flag.Float64("branchcache_ttl", 5.0, "Branch cache TTL in seconds.")
	deldirname := flag.String(
		"deletion_dirname", "GOUNIONFS_DELETIONS", "Directory name to use for deletions.")
	flag.Parse()

	if *version {
		fmt.Println(fuse.Version())
		os.Exit(0)
	}

	if len(flag.Args()) < 2 {
		fmt.Println("Usage:\n  main MOUNTPOINT BASEDIR")
		os.Exit(2)
	}
	ufsOptions := unionfs.UnionFsOptions{
		DeletionCacheTTL: time.Duration(*delcache_ttl * float64(time.Second)),
		BranchCacheTTL:   time.Duration(*branchcache_ttl * float64(time.Second)),
		DeletionDirName:  *deldirname,
	}
	options := unionfs.AutoUnionFsOptions{
		UnionFsOptions: ufsOptions,
		FileSystemOptions: fuse.FileSystemOptions{
			EntryTimeout:    time.Second,
			AttrTimeout:     time.Second,
			NegativeTimeout: time.Second,
			Owner:           fuse.CurrentOwner(),
		},
		UpdateOnMount: true,
		PathNodeFsOptions: fuse.PathNodeFsOptions{
			ClientInodes: *hardlinks,
		},
	}

	fmt.Printf("AutoUnionFs - Go-FUSE Version %v.\n", fuse.Version())
	gofs := unionfs.NewAutoUnionFs(flag.Arg(1), options)
	pathfs := fuse.NewPathNodeFs(gofs, nil)
	state, conn, err := fuse.MountNodeFileSystem(flag.Arg(0), pathfs, nil)
	if err != nil {
		fmt.Printf("Mount fail: %v\n", err)
		os.Exit(1)
	}

	pathfs.Debug = *debug
	conn.Debug = *debug
	state.Debug = *debug

	gofs.SetMountState(state)

	state.Loop()
}
Ejemplo n.º 23
0
Archivo: ivc.go Proyecto: namsyvo/IVC
func ReadInputInfo() *ivc.ParaInfo {
	var genome_file = flag.String("R", "", "reference genome file")
	var var_prof_file = flag.String("V", "", "variant profile file")
	var idx_dir = flag.String("I", "", "index directory")
	var read_file_1 = flag.String("1", "", "pairend read file, first end")
	var read_file_2 = flag.String("2", "", "pairend read file, second end")
	var var_call_file = flag.String("O", "", "variant call output file")
	var search_mode = flag.Int("mode", 0, "searching mode for finding seeds (1: random (default), 2: deterministic)")
	var start_pos = flag.Int("start", 0, "starting position on reads for finding seeds")
	var search_step = flag.Int("step", 0, "step for searching in deterministic mode")
	var max_snum = flag.Int("maxs", 0, "maximum number of seeds")
	var max_psnum = flag.Int("maxp", 0, "maximum number of paired-seeds")
	var min_slen = flag.Int("lmin", 0, "minimum length of seeds")
	var max_slen = flag.Int("lmax", 0, "maximum length of seeds")
	var dist_thres = flag.Float64("d", 0, "threshold of alignment distances")
	var iter_num = flag.Int("r", 0, "maximum number of iterations")
	var sub_cost = flag.Float64("s", 0, "substitution cost")
	var gap_open = flag.Float64("o", 0, "gap open cost")
	var gap_ext = flag.Float64("e", 0, "gap extension cost")
	var proc_num = flag.Int("t", 0, "maximum number of CPUs")
	var debug_mode = flag.Bool("debug", false, "turn on debug mode.")
	flag.Parse()

	_, genome_file_name := path.Split(*genome_file)
	multi_seq_file_name := path.Join(*idx_dir, genome_file_name) + ".mgf"
	rev_multi_seq_file_name := path.Join(*idx_dir, genome_file_name) + ".rev.mgf"
	_, var_prof_file_name := path.Split(*var_prof_file)
	var_prof_index_file_name := path.Join(*idx_dir, var_prof_file_name) + ".idx"

	para_info := new(ivc.ParaInfo)
	para_info.Ref_file = multi_seq_file_name
	para_info.Var_prof_file = var_prof_index_file_name
	para_info.Index_file = multi_seq_file_name + ".index/"
	para_info.Rev_index_file = rev_multi_seq_file_name + ".index/"
	para_info.Read_file_1 = *read_file_1
	para_info.Read_file_2 = *read_file_2
	para_info.Var_call_file = *var_call_file
	para_info.Search_mode = *search_mode
	para_info.Start_pos = *start_pos
	para_info.Search_step = *search_step
	para_info.Max_snum = *max_snum
	para_info.Max_psnum = *max_psnum
	para_info.Min_slen = *min_slen
	para_info.Max_slen = *max_slen
	para_info.Dist_thres = *dist_thres
	para_info.Iter_num = *iter_num
	para_info.Sub_cost = *sub_cost
	para_info.Gap_open = *gap_open
	para_info.Gap_ext = *gap_ext
	para_info.Proc_num = *proc_num
	para_info.Debug_mode = *debug_mode

	return para_info
}
Ejemplo n.º 24
0
Archivo: benchviz.go Proyecto: rzh/svgo
func main() {
	var (
		width        = flag.Int("w", 1024, "width")
		top          = flag.Int("top", 50, "top")
		left         = flag.Int("left", 100, "left margin")
		vp           = flag.Int("vp", 512, "visualization point")
		vw           = flag.Int("vw", 300, "visual area width")
		bh           = flag.Int("bh", 20, "bar height")
		smax         = flag.Float64("sm", 10, "maximum speedup")
		dmax         = flag.Float64("dm", 100, "maximum delta")
		title        = flag.String("title", "", "title")
		speedcolor   = flag.String("scolor", "green", "speedup color")
		regresscolor = flag.String("rcolor", "red", "regression color")
		style        = flag.String("style", "bar", "set the style (bar or inline)")
		lines        = flag.Bool("line", false, "show lines between entries")
		coldata      = flag.Bool("col", false, "show data in a single column")
		coltitle     = flag.Bool("coltitle", true, "show title for columns")
	)
	flag.Parse()

	g := geometry{
		width:              *width,
		top:                *top,
		left:               *left,
		vp:                 *vp,
		vwidth:             *vw,
		barHeight:          *bh,
		title:              *title,
		scolor:             *speedcolor,
		rcolor:             *regresscolor,
		style:              *style,
		dolines:            *lines,
		coldata:            *coldata,
		speedupmax:         *smax,
		deltamax:           *dmax,
		coltitle:           *coltitle,
		coltitle_not_print: true,
	}
	var svg_buffer bytes.Buffer
	canvas_b := svg.New(&svg_buffer)
	var _height int

	if len(flag.Args()) > 0 {
		for _, f := range flag.Args() {
			_height = process(canvas_b, f, g)
		}
	} else {
		_height = process(canvas_b, "", g)
	}
	canvas := svg.New(os.Stdout)
	canvas.Start(g.width, _height)
	svg_buffer.WriteTo(os.Stdout)
	canvas.End()
}
Ejemplo n.º 25
0
func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	rand.Seed(int64(time.Now().Nanosecond()))

	path = flag.String("path", "./brot.png", "Output filename")
	center_x = flag.Float64("x", -.5, "X center on mandelbrot plane")
	center_y = flag.Float64("y", 0, "Y center on mandelbrot plane")
	zoom = flag.Float64("zoom", 1, "Zoom Multiplier")
	width = flag.Int("width", 500, "Width of final image")
	height = flag.Int("height", 500, "Height of final iage")
	iter = flag.Int("iter", 150, "Escape analysis iterations")
	limit = flag.Float64("limit", 1000, "Limit for escape analysis")
	interesting = flag.Bool("interesting", false, "Use preselected interesting parameters")
}
Ejemplo n.º 26
0
Archivo: main.go Proyecto: lht/go-fuse
func main() {
	version := flag.Bool("version", false, "print version number")
	debug := flag.Bool("debug", false, "debug on")
	threaded := flag.Bool("threaded", true, "threading on")
	delcache_ttl := flag.Float64("deletion_cache_ttl", 5.0, "Deletion cache TTL in seconds.")
	branchcache_ttl := flag.Float64("branchcache_ttl", 5.0, "Branch cache TTL in seconds.")
	deldirname := flag.String(
		"deletion_dirname", "GOUNIONFS_DELETIONS", "Directory name to use for deletions.")
	flag.Parse()

	if *version {
		fmt.Println(fuse.Version())
		os.Exit(0)
	}

	if len(flag.Args()) < 2 {
		fmt.Println("Usage:\n  main MOUNTPOINT BASEDIR")
		os.Exit(2)
	}
	ufsOptions := unionfs.UnionFsOptions{
		DeletionCacheTTLSecs: *delcache_ttl,
		BranchCacheTTLSecs:   *branchcache_ttl,
		DeletionDirName:      *deldirname,
	}
	options := unionfs.AutoUnionFsOptions{
		UnionFsOptions: ufsOptions,
		FileSystemOptions: fuse.FileSystemOptions{
			EntryTimeout:    1.0,
			AttrTimeout:     1.0,
			NegativeTimeout: 1.0,
			Owner:           fuse.CurrentOwner(),
		},
		UpdateOnMount: true,
	}

	gofs := unionfs.NewAutoUnionFs(flag.Arg(1), options)
	pathfs := fuse.NewPathNodeFs(gofs)
	state, conn, err := fuse.MountNodeFileSystem(flag.Arg(0), pathfs, nil)
	if err != nil {
		fmt.Printf("Mount fail: %v\n", err)
		os.Exit(1)
	}

	pathfs.Debug = *debug
	conn.Debug = *debug
	state.Debug = *debug
	state.Loop(*threaded)
}
Ejemplo n.º 27
0
func TestParse_GlobalAndCustomOverwrite(t *testing.T) {
	resetForTesting("-a=true", "-b=5", "-c=Hello")
	flagA := flag.Bool("a", false, "")
	flagB := flag.Float64("b", 0.0, "")
	flagC := flag.String("c", "", "")

	name := "custom"
	custom := flag.NewFlagSet(name, flag.ExitOnError)
	flagD := custom.String("d", "", "")

	Register(name, custom)
	parse(t, "./testdata/globalandcustom.ini", "")
	if !*flagA {
		t.Errorf("flagA found %v, expected true", *flagA)
	}
	if *flagB != 5.0 {
		t.Errorf("flagB found %v, expected 5.0", *flagB)
	}
	if *flagC != "Hello" {
		t.Errorf("flagC found %v, expected 'Hello'", *flagC)
	}
	if *flagD != "Hello d" {
		t.Errorf("flagD found %v, expected 'Hello d'", *flagD)
	}
}
Ejemplo n.º 28
0
func main() {
	numCPU := runtime.NumCPU()
	runtime.GOMAXPROCS(numCPU)

	obliteration := flag.Int("concurrency", 10, "threads and connections to use for load generation")
	host := flag.String("zk", "master.mesos:2181", "host:port for zk")
	size := flag.Int("size", 1024, "bytes per key written")
	ratio := flag.Float64("ratio", 0.2, "0 to 1 ratio of reads to writes.  0 is all writes, 1 is all reads.")
	flag.Parse()

	value := gen(*size)

	conns := []*zk.Conn{}
	for i := 0; i < *obliteration; i++ {
		cli, _, err := zk.Connect([]string{*host}, 5*time.Second)
		if err != nil {
			fmt.Printf("error connecting to zk: %v\n", err)
			os.Exit(1)
		}
		conns = append(conns, cli)
	}

	doRpc := func() {
		cli := conns[rand.Intn(len(conns))]
		bench(cli, value, *ratio)
	}

	loghisto.PrintBenchmark("benchmark1234", uint(*obliteration), doRpc)
}
Ejemplo n.º 29
0
func main() {
	title := flag.String("title", "", "영화 이름")      // 명령줄 옵션을 받은 뒤 문자열로 저장
	runtime := flag.Int("runtime", 0, "상영 시간")      // 명령줄 옵션을 받은 뒤 정수로 저장
	rating := flag.Float64("rating", 0.0, "평점")     // 명령줄 옵션을 받은 뒤 실수로 저장
	release := flag.Bool("release", false, "개봉 여부") // 명령줄 옵션을 받은 뒤 불로 저장

	flag.Parse() // 명령줄 옵션의 내용을 각 자료형별로 분석

	if flag.NFlag() == 0 { // 명령줄 옵션의 개수가 0개이면
		flag.Usage() // 명령줄 옵션 기본 사용법 출력
		return
	}

	fmt.Printf(
		"영화 이름: %s\n상영 시간: %d분\n평점: %f\n",
		*title, // 포인터이므로 값을 꺼낼 때는 역참조 사용
		*runtime,
		*rating,
	) // 명령줄 옵션으로 받은 값을 출력

	if *release == true {
		fmt.Println("개봉 여부: 개봉")
	} else {
		fmt.Println("개봉 여부: 미개봉")
	}
}
Ejemplo n.º 30
0
func main() {
	var (
		port          = flag.String("port", "8080", "Port to bind HTTP listener")
		declineAmount = flag.Float64("decline", 100, "Decline payments over certain amount")
	)
	flag.Parse()

	// Mechanical stuff.
	errc := make(chan error)
	ctx := context.Background()

	handler, logger := payment.WireUp(ctx, float32(*declineAmount))

	// Create and launch the HTTP server.
	go func() {
		logger.Log("transport", "HTTP", "port", *port)
		errc <- http.ListenAndServe(":"+*port, handler)
	}()

	// Capture interrupts.
	go func() {
		c := make(chan os.Signal)
		signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
		errc <- fmt.Errorf("%s", <-c)
	}()

	logger.Log("exit", <-errc)
}