예제 #1
0
func (p *file) parse(name string) bool {
	var num uint64
	var tail string
	_, err := fmt.Sscanf(name, "%d.%s", &num, &tail)
	if err == nil {
		switch tail {
		case "log":
			p.t = TypeLog
		case "sst":
			p.t = TypeTable
		case "dbtmp":
			p.t = TypeTemp
		default:
			return false
		}
		p.num = num
		return true
	}
	n, _ := fmt.Sscanf(name, "MANIFEST-%d%s", &num, &tail)
	if n == 1 {
		p.t = TypeManifest
		p.num = num
		return true
	}

	return false
}
예제 #2
0
파일: ui.go 프로젝트: gbin/screencastinator
func (ttyfd TTY) readCursorPosition() (int, int) {
	ttyfd.write(READ_CURSOR_POSITION)
	var chr byte
	var nb []byte = make([]byte, 0)
	var x, y int

	chr, _, _ = ttyfd.Readchr()
	if chr != ESC_CHR {
		return 0, 0 // something failed !
	}
	chr, _, _ = ttyfd.Readchr()
	if chr != '[' {
		return 0, 0 // something failed !
	}

	for chr != ';' {
		chr, _, _ = ttyfd.Readchr()
		nb = append(nb, chr)
	}
	fmt.Sscanf(string(nb), "%d", &x)
	nb = make([]byte, 0)
	for chr != 'R' {
		chr, _, _ = ttyfd.Readchr()
		nb = append(nb, chr)
	}
	fmt.Sscanf(string(nb), "%d", &y)
	return x, y

}
예제 #3
0
파일: client.go 프로젝트: mpdroog/smtpw
/*
The "put" command is for any process that wants to insert a job into the queue.
It comprises a command line followed by the job body:

put <pri> <delay> <ttr> <bytes>\r\n
<data>\r\n

It inserts a job into the client's currently used tube (see the "use" command
below).

 - <pri> is an integer < 2**32. Jobs with smaller priority values will be
   scheduled before jobs with larger priorities. The most urgent priority is 0;
   the least urgent priority is 4,294,967,295.

 - <delay> is an integer number of seconds to wait before putting the job in
   the ready queue. The job will be in the "delayed" state during this time.

 - <ttr> -- time to run -- is an integer number of seconds to allow a worker
   to run this job. This time is counted from the moment a worker reserves
   this job. If the worker does not delete, release, or bury the job within
   <ttr> seconds, the job will time out and the server will release the job.
   The minimum ttr is 1. If the client sends 0, the server will silently
   increase the ttr to 1.

 - <bytes> is an integer indicating the size of the job body, not including the
   trailing "\r\n". This value must be less than max-job-size (default: 2**16).

 - <data> is the job body -- a sequence of bytes of length <bytes> from the
   previous line.

After sending the command line and body, the client waits for a reply, which
may be:

 - "INSERTED <id>\r\n" to indicate success.

   - <id> is the integer id of the new job

 - "BURIED <id>\r\n" if the server ran out of memory trying to grow the
   priority queue data structure.

   - <id> is the integer id of the new job

 - "EXPECTED_CRLF\r\n" The job body must be followed by a CR-LF pair, that is,
   "\r\n". These two bytes are not counted in the job size given by the client
   in the put command line.

 - "JOB_TOO_BIG\r\n" The client has requested to put a job with a body larger
   than max-job-size bytes.

 - "DRAINING\r\n" This means that the server has been put into "drain mode"
   and is no longer accepting new jobs. The client should try another server
   or disconnect and try again later.
*/
func (this *BeanstalkdClient) Put(priority uint32, delay, ttr time.Duration, data []byte) (id uint64, err error) {
	cmd := fmt.Sprintf("put %d %d %d %d\r\n", priority, uint64(delay.Seconds()), uint64(ttr.Seconds()), len(data))
	cmd = cmd + string(data) + string(crnl)

	_, reply, err := this.sendReply(cmd)

	if err != nil {
		return 0, err
	}

	switch {
	case strings.Index(reply, "INSERTED") == 0:
		var id uint64
		_, perr := fmt.Sscanf(reply, "INSERTED %d\r\n", &id)
		return id, perr
	case strings.Index(reply, "BURIED") == 0:
		var id uint64
		_, perr := fmt.Sscanf(reply, "BURIED %d\r\n", &id)
		return id, perr
	case reply == "EXPECTED_CRLF\r\n":
		return 0, errExpectedCrlf
	case reply == "JOB_TOO_BIG\r\n":
		return 0, errJobTooBig
	case reply == "DRAINING\r\n":
		return 0, errDraining
	default:
		return 0, this.parseError(reply)
	}

}
예제 #4
0
파일: block.go 프로젝트: pombredanne/bar
func BlockStorageFactory(opts map[string]string) (res Storage, err error) {
	op := &BlockStorageOptions{"data", 2, 32, 32}
	var ok bool
	var tmp string

	if tmp, ok = opts["root"]; ok {
		op.Root = tmp
	}
	if tmp, ok = opts["split"]; ok {
		if _, err = fmt.Sscanf(tmp, "%d", op.Split); err != nil {
			return
		}
	}
	if tmp, ok = opts["max-files"]; ok {
		if _, err = fmt.Sscanf(tmp, "%d", op.MaxFiles); err != nil {
			return
		}
	}
	if tmp, ok = opts["pool"]; ok {
		if _, err = fmt.Sscanf(tmp, "%d", op.PoolSize); err != nil {
			return
		}
	}

	res = NewBlockStorage(op)
	return
}
예제 #5
0
// Example custom option callback
func MyParseCallback(spec *options.OptionSpec, option string, argument *string) {
	if argument != nil {
		switch spec.GetCanonical(option) {
		case "input-encoding":
			in = *argument
		case "output-encoding":
			out = *argument
		case "repeat":
			fmt.Sscanf(*argument, "%d", &r)
		case "cookie-chance":
			fmt.Sscanf(*argument, "%f", &c)
			cInt = int64(c * 1000)
		default:
			spec.PrintUsageAndExit("Unknown option: " + option)
		}
	} else {
		switch spec.GetCanonical(option) {
		case "number":
			n = true
		case "escape":
			e = true
		case "verbose":
			v++
		default:
			if option == "help" {
				spec.PrintUsageAndExit("") // No error
			} else {
				spec.PrintUsageAndExit("Unknown option: " + option)
			}
		}
	}
}
예제 #6
0
파일: utils.go 프로젝트: GloriaH/docker
func ParseRelease(release string) (*KernelVersionInfo, error) {
	var (
		kernel, major, minor, parsed int
		flavor, partial              string
	)

	// Ignore error from Sscanf to allow an empty flavor.  Instead, just
	// make sure we got all the version numbers.
	parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial)
	if parsed < 2 {
		return nil, errors.New("Can't parse kernel version " + release)
	}

	// sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64
	parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor)
	if parsed < 1 {
		flavor = partial
	}

	return &KernelVersionInfo{
		Kernel: kernel,
		Major:  major,
		Minor:  minor,
		Flavor: flavor,
	}, nil
}
예제 #7
0
// LoadString loads a hex representation (including checksum) of an unlock hash
// into an unlock hash object. An error is returned if the string is invalid or
// fails the checksum.
func (uh *UnlockHash) LoadString(strUH string) error {
	// Check the length of strUH.
	if len(strUH) != crypto.HashSize*2+UnlockHashChecksumSize*2 {
		return ErrUnlockHashWrongLen
	}

	// Decode the unlock hash.
	var byteUnlockHash []byte
	var checksum []byte
	_, err := fmt.Sscanf(strUH[:crypto.HashSize*2], "%x", &byteUnlockHash)
	if err != nil {
		return err
	}

	// Decode and verify the checksum.
	_, err = fmt.Sscanf(strUH[crypto.HashSize*2:], "%x", &checksum)
	if err != nil {
		return err
	}
	expectedChecksum := crypto.HashBytes(byteUnlockHash)
	if !bytes.Equal(expectedChecksum[:UnlockHashChecksumSize], checksum) {
		return ErrInvalidUnlockHashChecksum
	}

	copy(uh[:], byteUnlockHash[:])
	return nil
}
예제 #8
0
func main() {
	data, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer data.Close()

	var (
		n, id  int
		x, y   float64
		places []place
		path   []int
	)
	scanner := bufio.NewScanner(data)
	for scanner.Scan() {
		t := strings.Fields(scanner.Text())
		fmt.Sscan(t[0], &id)
		fmt.Sscanf(t[len(t)-2], "(%f,", &x)
		fmt.Sscanf(t[len(t)-1], "%f)", &y)
		places = append(places, place{id, x, y})
		path = append(path, n)
		n++
	}
	shortestPath, _ := findPath(path, []int{}, 0, tour(places, path), len(path), places)
	for _, i := range shortestPath {
		fmt.Println(places[i].id)
	}
}
예제 #9
0
파일: 1B.go 프로젝트: giter/codeforces-ans
func main() {

	var n int
	fmt.Scanf("%d\n", &n)
	re := regexp.MustCompile("(R\\d+C\\d+)|(([A-Z]+)(\\d+))")

	for i := 0; i < n; i++ {

		var k string
		fmt.Scanf("%s\n", &k)

		ss := re.FindStringSubmatch(k)

		if len(ss[1]) > 0 {
			var a, b int
			fmt.Sscanf(ss[1], "R%dC%d", &a, &b)
			fmt.Printf("%s%d\n", itos(b), a)
		}

		if len(ss[2]) > 0 {
			a := ss[3]
			var b int
			fmt.Sscanf(ss[4], "%d", &b)
			fmt.Printf("R%dC%d\n", b, stoi(a))
		}
	}

}
예제 #10
0
func main() {
	cgreader.RunStaticPrograms(
		cgreader.GetFileList("../../input/horse_dual_%d.txt", 3),
		cgreader.GetFileList("../../output/horse_dual_%d.txt", 3),
		true,
		func(input <-chan string, output chan string) {
			var n int
			fmt.Sscanf(<-input, "%d", &n)

			horses := make([]int, n)
			for i := range horses {
				fmt.Sscanf(<-input, "%d", &horses[i])
			}

			sort.Sort(intArray(horses))

			D := math.MaxInt32
			for i := 1; i < n; i++ {
				x := horses[i-1] - horses[i]

				if x < 0 {
					x *= -1
				}

				if x < D {
					D = x
				}
			}

			output <- fmt.Sprintf("%d", D)
		})
}
예제 #11
0
파일: client.go 프로젝트: cdshann/minimega
func ParseKeyEvent(arg string) (*KeyEvent, error) {
	var key string
	var down bool

	_, err := fmt.Sscanf(arg, _KeyEventFmt, &down, &key)
	if err != nil {
		return nil, err
	}

	m := &KeyEvent{}

	m.Key, err = xStringToKeysym(key)
	if err != nil {
		fmt.Println(err.Error())
		_, err = fmt.Sscanf(key, "%U", &m.Key)
		if err != nil {
			fmt.Println(err.Error())
			return nil, fmt.Errorf("unknown key: `%s`", key)
		}
	}

	if down {
		m.DownFlag = 1
	}

	return m, nil
}
예제 #12
0
func IntBytes(arg string) (bool, int, []byte) {
	if !BytesRE.MatchString(arg) {
		return false, -1, nil
	}

	r := make([]byte, 0)

	for _, segment := range strings.Split(arg, " ", -1) {
		var n byte

		switch len(segment) {
		case 2:
			_, err := fmt.Sscanf(segment, "%x", &n)
			if err != nil {
				return false, -1, nil
			}
			r = append(r, n)
		case 4:
			_, err := fmt.Sscanf(segment[0:2], "%x", &n)
			if err != nil {
				return false, -1, nil
			}
			r = append(r, n)
			_, err = fmt.Sscanf(segment[2:], "%x", &n)
			if err != nil {
				return false, -1, nil
			}
			r = append(r, n)
		default:
			return false, -1, nil
		}
	}

	return true, -1, r
}
예제 #13
0
func lsusb(path string) error {
	f, err := os.Open(path)
	if err != nil {
		return nil
	}
	defer f.Close()

	var bus, dev, pid, vid, i int
	s := bufio.NewScanner(f)
	for s.Scan() {
		line := s.Text()
		n1, _ := fmt.Sscanf(line, "BUSNUM=%d\n", &bus)
		n2, _ := fmt.Sscanf(line, "DEVNUM=%d\n", &dev)
		n3, _ := fmt.Sscanf(line, "PRODUCT=%x/%x\n", &pid, &vid)
		if n1 != 0 || n2 != 0 || n3 != 0 {
			i++
		}
		if i == 3 {
			devices = append(devices, Device{bus, dev, pid, vid})
			break
		}
	}

	return nil
}
예제 #14
0
// WatchdogEnabled checks whether the service manager expects watchdog keep-alive notifications and
// returns the timeout value in µs. A timeout value of 0 signifies no notifications are expected.
func WatchdogEnabled() (time.Duration, error) {
	spid := os.Getenv("WATCHDOG_PID")
	if spid != "" {
		pid := 0
		n, err := fmt.Sscanf(spid, "%d", &pid)
		if err != nil {
			return 0, err
		}
		if n != 1 {
			return 0, errors.New("could not scan WATCHDOG_PID")
		}
		if pid != os.Getpid() {
			return 0, nil
		}
	}

	sttl := os.Getenv("WATCHDOG_USEC")
	if sttl == "" {
		return 0, errors.New("missing WATCHDOG_USEC")
	}
	ttl := uint64(0)
	n, err := fmt.Sscanf(sttl, "%d", &ttl)
	if err != nil {
		return 0, err
	}
	if n != 1 {
		return 0, errors.New("could not scan WATCHDOG_USEC")
	}
	return time.Duration(ttl) * time.Microsecond, nil
}
예제 #15
0
파일: import.go 프로젝트: lanior/upc
func stringRangeWorker(rangeRepr string, ch chan int) {
	for _, part := range strings.Split(rangeRepr, ",") {
		var from, to int
		var err error

		data := []byte(part)
		if match := numberRe.FindSubmatch(data); match != nil {
			fmt.Sscanf(string(match[1]), "%d", &from)
			to = from
		} else if match := rangeRe.FindSubmatch(data); match != nil {
			fmt.Sscanf(string(match[1]), "%d", &from)
			fmt.Sscanf(string(match[2]), "%d", &to)
		} else {
			break
		}

		if err != nil {
			break
		}

		for i := from; i <= to; i++ {
			ch <- i
		}
	}
	close(ch)
}
예제 #16
0
func ParseGameState(lines []string) *PlanetWars {
	pw := &PlanetWars{make([]*Planet, len(lines)), make([]*Fleet, len(lines))}
	pNum, fNum := 0, 0

	for _, ln := range lines {

		switch ln[0] {
		case 'P':
			p := &Planet{ID: pNum}
			read, e := fmt.Sscanf(ln[2:], "%f %f %d %d %d", &p.X, &p.Y, &p.Owner, &p.NumShips, &p.GrowthRate)

			if read < 5 || e != nil {
				log.Stderrf("Bad line in input: %s\n", ln)
			}
			pw.Planets[pNum] = p
			pNum++
		case 'F':
			f := &Fleet{ID: fNum}
			read, e := fmt.Sscanf(ln[2:], "%d %d %d %d %d", &f.Owner, &f.NumShips, &f.Source, &f.Dest, &f.TripLength, &f.TurnsRemaining)

			if read < 5 || e != nil {
				log.Stderrf("Bad line in input: %s\n", ln)
			}
			pw.Fleets[fNum] = f
			fNum++
		default:
			log.Stderr("Error parsing gamestate: First char of line not 'P' or 'F'\n")
			return nil
		}
	}

	pw.Fleets = pw.Fleets[0:fNum]
	pw.Planets = pw.Planets[0:pNum]
	return pw
}
예제 #17
0
func main() {
	cgreader.RunStaticPrograms(
		cgreader.GetFileList("../../input/tan_network_%d.txt", 6),
		cgreader.GetFileList("../../output/tan_network_%d.txt", 6),
		true,
		func(input <-chan string, output chan string) {
			// this block could be ommited when solo-running
			minCost = math.MaxUint16
			routes, finalRoute = nil, nil

			start, stop := GetInput(input), GetInput(input)
			hashMap = make(map[uint32]string)
			identifierMap = make(map[string]uint32)
			stationsMC = make(map[uint32]uint16)

			var ns, nr uint32
			fmt.Sscanf(<-input, "%d", &ns)
			stations := make(map[uint32]Station)
			for i := uint32(0); i < ns; i++ {
				station := GetInput(input)
				info := strings.Split(station, ",")
				hashMap[i] = info[0]
				identifierMap[info[0]] = i
				stations[i] = Station{
					info[1][1 : len(info[1])-1],
					ToFloat(info[3]),
					ToFloat(info[4])}
			}

			startHash, finalHash = identifierMap[start], identifierMap[stop]

			if startHash == finalHash {
				output <- stations[startHash].name
				return
			}

			fmt.Sscanf(<-input, "%d", &nr)
			routes = make(map[uint32][]Destination)
			for i := uint32(0); i < nr; i++ {
				route := GetInput(input)
				ra, ro := string(route[:4]), string(route[14:])
				ha, ho := identifierMap[ra], identifierMap[ro]

				a, b := stations[ha], stations[ho]
				cost := GetCost(a.latitude, b.latitude, a.longitude, b.longitude)

				routes[ha] = append(routes[ha], Destination{ho, cost})
			}

			TravelRecursive(0, append(make([]uint32, 0), startHash))

			if finalRoute == nil {
				output <- "IMPOSSIBLE\n"
			} else {
				for _, hash := range finalRoute {
					output <- fmt.Sprintln(stations[hash].name)
				}
			}
		})
}
예제 #18
0
// formatCompleteOutput will format the message m as an completed message.
func formatCompleteOutput(m *jsonmessage.JSONMessage) string {
	if strings.HasPrefix(m.Status, "The push refers to a repository") {
		return "Pushing to registry"
	}

	if strings.HasPrefix(m.Status, "Pushing repository") &&
		strings.HasSuffix(m.Status, "tags)") {
		tags := 0
		registry := ""
		fmt.Sscanf(m.Status, "Pushing repository %s (%d tags)", &registry, &tags)
		return fmt.Sprintf("Pushing %d tag(s)", tags)
	}

	if strings.HasPrefix(m.Status, "Pushing tag for rev [") &&
		strings.HasSuffix(m.Status, "};") {
		image := ""
		registry := ""
		fmt.Sscanf(m.Status, "Pushing tag for rev [%s] on {%s};", &image, &registry)
		image = strings.TrimSuffix(image, "]")
		return fmt.Sprintf("Pushing tag for image: %s", image)
	}

	if m.ID != "" {
		return fmt.Sprintf("%s: %s", m.Status, m.ID)
	}

	return m.Status
}
예제 #19
0
func main() {
	data, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer data.Close()
	scanner := bufio.NewScanner(data)
	for scanner.Scan() {
		s := strings.Split(scanner.Text(), ",")
		var l, m int
		fmt.Sscanf(strings.TrimSpace(s[0]), "%d", &m)
		for _, i := range s {
			var v int
			fmt.Sscanf(strings.TrimSpace(i), "%d", &v)
			if v > m {
				m = v
			}
			if v+l > m {
				m = v + l
			}
			if v+l > 0 {
				l += v
			} else {
				l = 0
			}
		}
		fmt.Println(m)
	}
}
예제 #20
0
파일: svgrid.go 프로젝트: sara62/centrifugo
// placepic puts a SVG file at a location
func placepic(x, y int, filename string) (int, int) {
	var (
		s             SVG
		width, height int
		wunit, hunit  string
	)
	f, err := os.Open(filename)
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		return 0, 0
	}
	defer f.Close()
	if err := xml.NewDecoder(f).Decode(&s); err != nil {
		fmt.Fprintf(os.Stderr, "Unable to parse (%v)\n", err)
		return 0, 0
	}

	// read the width and height, including any units
	// if there are errors use 10 as a default
	nw, _ := fmt.Sscanf(s.Width, "%d%s", &width, &wunit)
	if nw < 1 {
		width = 10
	}
	nh, _ := fmt.Sscanf(s.Height, "%d%s", &height, &hunit)
	if nh < 1 {
		height = 10
	}
	canvas.Group(`clip-path="url(#pic)"`, fmt.Sprintf(`transform="translate(%d,%d)"`, x, y))
	canvas.ClipPath(`id="pic"`)
	canvas.Rect(0, 0, width, height)
	canvas.ClipEnd()
	io.WriteString(canvas.Writer, s.Doc)
	canvas.Gend()
	return width, height
}
예제 #21
0
func main() {
	var n, k int
	data, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	defer data.Close()
	scanner := bufio.NewScanner(data)
	for scanner.Scan() {
		var v []int
		t := strings.Split(scanner.Text(), " | ")
		fmt.Sscanf(t[1], "%d", &n)
		u := strings.Fields(t[0])
		for _, i := range u {
			fmt.Sscanf(i, "%d", &k)
			v = append(v, k)
		}
		for i := 0; i < len(v)-n; i++ {
			sort.Ints(v[i : i+n+1])
		}
		for ix, i := range v {
			u[ix] = fmt.Sprint(i)
		}
		fmt.Println(strings.Join(u, " "))
	}
}
예제 #22
0
func TestScanTerm(t *testing.T) {
	var i1, i2 Int
	n, err := fmt.Sscanf("42 -17", "%v %v", &i1, &i2)
	if err != nil {
		t.Fatal(err.Error())
	}
	if n != 2 || i1 != Int(42) || i2 != Int(-17) {
		t.Fatal("incomplete parse")
	}

	var s1, s2 Str
	n, err = fmt.Sscanf(`"a" "b"`, "%v %v", &s1, &s2)
	if err != nil {
		t.Fatal(err.Error())
	}
	if n != 2 || s1 != Str("a") || s2 != Str("b") {
		t.Fatal("incomplete parse")
	}

	var p Prin
	n, err = fmt.Sscanf(key[0]+`.A(1).B("2", "3")`, "%v", &p)
	if err != nil {
		t.Fatal(err.Error())
	}
	p2 := Prin{Type: "key", KeyHash: Bytes([]byte("abc")), Ext: SubPrin{
		PrinExt{"A", []Term{Int(1)}},
		PrinExt{"B", []Term{Str("2"), Str("#")}},
	}}
	if n != 1 || p2.Identical(p) {
		t.Fatal("incomplete parse")
	}
}
예제 #23
0
파일: scap.go 프로젝트: thijzert/sslprobe
func main() {
	if len(os.Args) < 3 {
		fmt.Fprintf(os.Stderr, "Usage: %s {LISTEN_PORT} {HOST} [{PORT}]\n", os.Args[0])
		os.Exit(1)
	}

	listen = 0
	fmt.Sscanf(os.Args[1], "%d", &listen)
	host = os.Args[2]
	port = 443
	if len(os.Args) > 3 {
		fmt.Sscanf(os.Args[3], "%d", &port)
	}

	ln, err := net.Listen("tcp", fmt.Sprintf(":%d", listen))
	if err != nil {
		panic(err)
	}

	fmt.Printf("Listening on port %d\n", listen)
	fmt.Printf("Passing through to:    %s:%d\n", host, port)
	for {
		conn, err := ln.Accept()
		if err != nil {
			panic(err)
		}

		// Do this synchronously in order to only write one session to stdout at a time.
		// TODO: write each session to a different file.
		err = session_capture(conn)
		if err != nil {
			panic(err)
		}
	}
}
예제 #24
0
func TestParsePred(t *testing.T) {
	predtests := []string{
		`P(42)`,
		`Foo()`,
		`Pred(1, 2, 3)`,
		`Foo(1, "a", ` + key[0] + `)`,
		`Foo()`,
	}

	for _, s := range predtests {
		var x Pred
		n, err := fmt.Sscanf(s, "%v", &x)
		if err != nil {
			t.Fatal(err.Error())
		}
		if n != 1 {
			t.Fatal("incomplete parse")
		}
		if s != "Foo()" && x.String() != s {
			t.Fatalf("bad print: %v vs %s", x.String(), s)
		}
	}

	s := predtests[0] + " " + predtests[1] + " " + predtests[2] + " " + predtests[3]
	var w, x, y, z Pred
	n, err := fmt.Sscanf(s, "%v %v %v %v", &w, &x, &y, &z)
	if err != nil {
		t.Fatal(err.Error())
	}
	if n != 4 {
		t.Fatal("incomplete parse")
	}
}
예제 #25
0
func main() {
	cgreader.RunStaticProgram(
		"../../input/mime_types_5.txt",
		"../../output/mime_types_5.txt",
		true,
		func(input <-chan string, output chan string) {
			var n, m int
			fmt.Sscanf(<-input, "%d", &n)
			fmt.Sscanf(<-input, "%d", &m)

			types := make(map[string]string)
			for i := 0; i < n; i++ {
				var key, value string
				fmt.Sscanf(<-input, "%s %s", &key, &value)
				types[strings.ToLower(key)] = value
			}

			for i := 0; i < m; i++ {
				var path string
				fmt.Sscanf(<-input, "%s", &path)
				path = strings.ToLower(path)

				if strings.Contains(path, ".") {
					sp := strings.Split(path, ".")
					if value, ok := types[sp[len(sp)-1]]; ok {
						output <- fmt.Sprintf("%s\n", value)
					} else {
						output <- fmt.Sprintln("UNKNOWN")
					}
				} else {
					output <- fmt.Sprintln("UNKNOWN")
				}
			}
		})
}
예제 #26
0
func TestParseShortForm(t *testing.T) {
	for _, s := range formtests {
		var x, y AnyForm
		_, err := fmt.Sscanf("("+s+")", "%v", &x)
		if err != nil {
			t.Fatal(err)
		}
		if x.Form.String() != x.Form.ShortString() {
			t.Fatalf("bad short string: %s vs %s", x.Form.String(), x.Form.ShortString())
		}

		longstr := `"abcdefghijklmnopqrstuvwxyz"`
		shortstr := `"abcdefghij"...`
		short := strings.Replace(s, `"a"`, longstr, -1)
		fmt.Sscanf("("+short+")", "%v", &y)
		shortened := strings.Replace(x.Form.String(), `"a"`, shortstr, -1)
		if shortened != y.Form.ShortString() {
			t.Fatalf("bad short string: %s vs %s", y.Form.ShortString(), shortened)
		}

		if y.Form.String() != fmt.Sprintf("%v", y.Form) {
			t.Fatalf("bad long format: %s vs %s", x.Form.String(), fmt.Sprintf("%v", x.Form))
		}
		if shortened != fmt.Sprintf("%s", y.Form) {
			t.Fatalf("bad short format: %s vs %s", shortened, fmt.Sprintf("%s", x.Form))
		}

	}
}
예제 #27
0
func parseTxtInvoice(version, lino int, line string) (invoice *Invoice,
	err error) {
	invoice = &Invoice{}
	var raised, due string
	if version == fileVersion {
		if _, err = fmt.Sscanf(line, "INVOICE ID=%d CUSTOMER=%d "+
			"DEPARTMENT=%s RAISED=%s DUE=%s PAID=%t", &invoice.Id,
			&invoice.CustomerId, &invoice.DepartmentId, &raised, &due,
			&invoice.Paid); err != nil {
			return nil, fmt.Errorf("invalid invoice %v line %d", err, lino)
		}
	} else {
		if _, err = fmt.Sscanf(line, "INVOICE ID=%d CUSTOMER=%d "+
			"RAISED=%s DUE=%s PAID=%t", &invoice.Id,
			&invoice.CustomerId, &raised, &due, &invoice.Paid); err != nil {
			return nil, fmt.Errorf("invalid invoice %v line %d", err, lino)
		}
	}
	if invoice.Raised, err = time.Parse(dateFormat, raised); err != nil {
		return nil, fmt.Errorf("invalid raised %v line %d", err, lino)
	}
	if invoice.Due, err = time.Parse(dateFormat, due); err != nil {
		return nil, fmt.Errorf("invalid due %v line %d", err, lino)
	}
	if i := strings.Index(line, noteSep); i > -1 {
		invoice.Note = strings.TrimSpace(line[i+len(noteSep):])
	}
	if version < fileVersion {
		updateInvoice(invoice)
	}
	return invoice, nil
}
예제 #28
0
func TestParseTerm(t *testing.T) {
	for i, s := range termtests {
		var x AnyTerm
		n, err := fmt.Sscanf(s, "%v", &x)
		if err != nil {
			t.Fatal(err.Error())
		}
		if n != 1 {
			t.Fatal("incomplete parse")
		}
		if (i < len(termtests)-2) != (x.Term.String() == s) {
			t.Fatalf("bad print: %v vs %v", x.Term.String(), s)
		}
	}

	s := termtests[0] + " " + termtests[3] + " " + termtests[4] + " " + termtests[6]
	var w, x, y, z AnyTerm
	n, err := fmt.Sscanf(s, "%v %v %v %v", &w, &x, &y, &z)
	if err != nil {
		t.Fatal(err.Error())
	}
	if n != 4 {
		t.Fatal("incomplete parse")
	}
}
예제 #29
0
func (f *file) parse(name string) bool {
	var num uint64
	var tail string
	_, err := fmt.Sscanf(name, "%d.%s", &num, &tail)
	if err == nil {
		switch tail {
		case "log":
			f.t = TypeJournal
		case "ldb", "sst":
			f.t = TypeTable
		default:
			return false
		}
		f.num = num
		return true
	}
	n, _ := fmt.Sscanf(name, "MANIFEST-%d%s", &num, &tail)
	if n == 1 {
		f.t = TypeManifest
		f.num = num
		return true
	}

	return false
}
예제 #30
0
/*
Put a job.

It inserts a job into the client's currently used tube.

data is job body.

pri is an integer < 2**32. Jobs with smaller priority values will be
scheduled before jobs with larger priorities. The most urgent priority is 0;
the least urgent priority is 4,294,967,295.

delay is time to wait before putting the job in
the ready queue. The job will be in the "delayed" state during this time.

ttr -- time to run -- is time to allow a worker
to run this job. This time is counted from the moment a worker reserves
this job. If the worker does not delete, release, or bury the job within
ttr time, the job will time out and the server will release the job.
The minimum ttr is 1 second. If the client sends 0 second, the server will silently
increase the ttr to 1 second
*/
func (c *Conn) Put(data []byte, pri uint32, delay, ttr time.Duration) (uint64, error) {
	cmd := fmt.Sprintf("put %d %d %d %d\r\n", pri, uint64(delay.Seconds()), uint64(ttr.Seconds()), len(data))
	cmd = cmd + string(data) + "\r\n"

	resp, err := sendGetResp(c, cmd)
	if err != nil {
		return 0, err
	}

	//parse Put response
	switch {
	case strings.Index(resp, "INSERTED") == 0:
		var id uint64
		_, parseErr := fmt.Sscanf(resp, "INSERTED %d\r\n", &id)
		return id, parseErr
	case strings.Index(resp, "BURIED") == 0:
		var id uint64
		fmt.Sscanf(resp, "BURIED %d\r\n", &id)
		return id, errBuried
	case resp == "EXPECTED_CRLF\r\n":
		return 0, errExpectedCrlf
	case resp == "JOB_TOO_BIG\r\n":
		return 0, errJobTooBig
	case resp == "DRAINING\r\n":
		return 0, errDraining
	default:
		return 0, parseCommonError(resp)
	}
}