Beispiel #1
0
func main() {
	screen_width   := 1280;
	screen_height  := 720;
	benchmark_mode := false; //  true -> loop 50 times to benchmark
	
	canvas := canvas.EmptyCanvasImage(screen_width, screen_height, canvas.Color32(0xff000000));
	
	g := new(gyu3d.G3DContext);
	g.SetViewport(gyu3d.StandardViewport(screen_width, screen_height));
	g.SetProjection(
		gyu3d.IdentityM44().SetPerspective(float(screen_width)*0.006, float(screen_height)*0.006, 1.8, 100.0)
	);
	
	lx, ly := .1, -0.3;
	if len(flag.Args()) == 2 {
		lx, _ = strconv.Atof(flag.Args()[0]);
		ly, _ = strconv.Atof(flag.Args()[1]);
	}
	
	g.ResetTransforms();
	g.ViewMatrix.LookAt(0,1,0, -1.2,1.9,7, -0.5,0.9,0);
	g.Update();

	// draw
	drawTestScene(canvas, g, lx, ly, benchmark_mode);

	// export image
	outfile,e := file.WritableFile("./out.png");
	if e == nil {
		png.Encode(outfile, canvas);
		outfile.Close();
	}
	 
	fmt.Printf("done\n");
}
Beispiel #2
0
func parseBranchLength(pi ParserInput, pos int) (float, int) {
	pos = skipWhitespace(pi, pos)

	// expect + consume ':'
	if pi.CharAt(pos) != ':' {
		//throw new RuntimeException("parse error: parseBranchLength expects ':' at " + ptr);
		return 0.0, 0
	} else {

		pos++

		pos = skipWhitespace(pi, pos)

		flen := findFloat(pi, pos)
		if flen == pos {
			fmt.Printf("error: missing float number at %d\n", pos)
		}

		blen, _ := strconv.Atof(pi.Substring(pos, flen))
		pos = flen
		return blen, pos

	}

	panic("unreachable")
}
Beispiel #3
0
func (this *Lexicon) Analyze() {
	tokenizer := strutils.NewStrTokens(this.buffer.String())
outer:
	for tokenizer.HasMoreTokens() {
		token := tokenizer.NextToken()
		//keywords, separators, operators, literals, identifiers
		for _, k := range keywords {
			if k == token {
				this.keywords.Push(token)
				continue outer
			}
		}
		for _, s := range separators {
			if s == token {
				this.separators.Push(token)
				continue outer
			}
		}
		for _, o := range operators {
			if o == token {
				this.operators.Push(token)
				continue outer
			}
		}
		//check if literal
		_, err := strconv.Atof(token)
		if err == nil {
			this.literals.Push(token)
			continue outer
		}
		//if it reaches here, then it is an identifier
		this.identifiers.Push(token)
	}
}
Beispiel #4
0
// Find the best match for a given mime-type against
// a list of media_ranges that have already been
// parsed by ParseMediaRange(). Returns a tuple of
// the fitness value and the value of the 'q' quality
// parameter of the best match, or (-1, 0) if no match
// was found. Just as for QualityParsed(), 'parsedranges'
// must be a list of parsed media ranges.
func FitnessAndQuality(mimetype string, parsedRanges []Mime) (fitness int, quality float) {
	bestfitness := -1
	bestquality := 0.0
	target, _ := ParseMediaRange(mimetype)
	for _, r := range parsedRanges {
		pmatches := 0
		fitness := 0
		if (r.mtype == target.mtype || r.mtype == "*" || target.mtype == "*") &&
			(r.subtype == target.subtype || r.subtype == "*" || target.subtype == "*") {
			fitness += 1
			for key, targetvalue := range target.params {
				if key != "q" {
					if value, ok := r.params[key]; ok && value == targetvalue {
						pmatches++
					}
				}
			}
			fitness += pmatches
			if r.subtype == target.subtype {
				fitness += 10
			}
			if r.mtype == target.mtype {
				fitness += 100
			}
			if fitness > bestfitness {
				bestfitness = fitness
				bestquality, _ = strconv.Atof(r.params["q"])
			}
		}
	}

	return bestfitness, bestquality
}
Beispiel #5
0
func (this *Section) F(key string, defval float) float {
	if v, ok := this.Pairs[key]; ok {
		if f, err := strconv.Atof(v); err == nil {
			return f
		}
	}
	return defval
}
// GetFloat has the same behaviour as GetString but converts the response to float.
func (c *ConfigFile) GetFloat(section string, option string) (value float, err os.Error) {
	sv, err := c.GetString(section, option)
	if err == nil {
		value, err = strconv.Atof(sv)
	}

	return value, err
}
Beispiel #7
0
// Parsuje parametr znajdujacy sie na poczatku frag. Pomija biale znaki przed
// parametrem i usuwa za nim (po wywolaniu frag[0] nie jest bialym znakiem).
func parse1Param(txt *string, lnum *int) (
	par interface{}, err os.Error) {
	frag := *txt

	// Pomijamy biale znaki, ktore moga wystapic przed parametrem.
	err = skipWhite(&frag, lnum)
	if err != nil {
		return
	}

	if frag[0] == '"' || frag[0] == '\'' {
		// Parametrem jest tekst.
		txt_sep := frag[0:1]
		frag = frag[1:]
		if len(frag) == 0 {
			err = ParseErr{*lnum, PARSE_UNEXP_EOF}
			return
		}
		// Parsujemy tekst parametru.
		par, err = parse1(&frag, lnum, txt_sep)
		if err != nil {
			return
		}
	} else if uni.IsDigit(int(frag[0])) ||
		str.IndexRune(seps_num, int(frag[0])) != -1 {
		// Parametrem jest liczba
		ii := findChar(frag, seps_nnum, lnum)
		if ii == -1 {
			err = ParseErr{*lnum, PARSE_UNEXP_EOF}
			return
		}
		var iv int
		iv, err = strconv.Atoi(frag[0:ii])
		if err != nil {
			var fv float
			fv, err = strconv.Atof(frag[0:ii])
			if err != nil {
				err = ParseErr{*lnum, PARSE_BAD_FLOINT}
				return
			}
			par = reflect.NewValue(fv)
		} else {
			par = reflect.NewValue(iv)
		}
		frag = frag[ii:]
	} else {
		par, err = parse1VarFun("", &frag, lnum, false)
		if err != nil {
			return
		}
	}

	// Pomijamy biale znaki, ktore moga wystapic po parametrze.
	err = skipWhite(&frag, lnum)

	*txt = frag
	return
}
Beispiel #8
0
func (d DoubleValue) LoadXML(p *xml.Parser) (ParamValue, os.Error) {
	val, er := readBody(p)
	if er != nil {
		return nil, er
	}
	tempDouble, err := strconv.Atof(val)
	d = DoubleValue(tempDouble)
	return d, err
}
Beispiel #9
0
// Carves up a media range and returns a tuple of the
// (type, subtype, params) where 'params' is a dictionary
// of all the parameters for the media range.
// For example, the media range 'application/*;q=0.5' would
// get parsed into:
//
// ('application', '*', {'q', '0.5'})
//
// In addition this function also guarantees that there
// is a value for 'q' in the params dictionary, filling it
// in with a proper default if necessary.
func ParseMediaRange(mediarange string) (mime Mime, err os.Error) {
	parsed, err := ParseMimeType(mediarange)
	if err != nil {
		return parsed, err
	}
	if q, ok := parsed.params["q"]; ok {
		if val, err := strconv.Atof(q); err != nil || val > 1.0 || val < 0.0 {
			parsed.params["q"] = "1"
		}
	} else {
		parsed.params["q"] = "1"
	}
	return parsed, nil
}
Beispiel #10
0
func readFloat(r io.Reader) (float, os.Error) {
	bits, err := ioutil.ReadAll(io.LimitReader(r, 31))
	if err != nil {
		return 0, err
	}

	// Atof doesn't like trailing 0s
	var i int
	for i = 0; i < len(bits); i++ {
		if bits[i] == 0 {
			break
		}
	}

	return strconv.Atof(string(bits[0:i]))
}
Beispiel #11
0
func f_numify(v *Any) *Any {
	switch i := (*v).(type) {
	case nil:
		return i_0
	case Undef:
		return i_0
	case Int:
		return v
	case Num:
		return v
	case Str:
		// Str can be converted to Int or Num
		s := string((*v).(Str))
		out := ""
		pos := 0
		max := len(s)
		if pos >= max {
			return i_0
		}
		if s[pos] == '+' {
			pos++
		} else if s[pos] == '-' {
			out += s[pos : pos+1]
			pos++
		}
		if pos >= max || s[pos] < '0' || s[pos] > '9' {
			return i_0
		}
		for i := pos; i < len(s); i++ {
			if s[i] >= '0' && s[i] <= '9' {
				out += s[i : i+1]
				pos++
			} else {
				i = len(s)
			}
		}
		if (pos < max && s[pos] == '.') || ((pos+1) < max && (s[pos] == 'e' || s[pos] == 'E') && (s[pos+1] == '+' || s[pos+1] == '-' || (s[pos+1] >= '0' && s[pos+1] <= '9'))) {
			// 123. 123e10
			n, _ := strconv.Atof(s)
			return toNum(n)
		}
		n, _ := strconv.Atoi(out)
		return toInt(n)
	}
	return (*v).(int_er).f_int(Capture{})
}
Beispiel #12
0
Datei: expr.go Projekt: qrush/go
// Find and evaluate a factor
func getFactor() float {
	if digitCheck, _ := regexp.MatchString("[0-9]+(\\.[0-9]+)?", input[0]); digitCheck {
		res, _ := strconv.Atof(input[0])
		pop()
		return res
	} else if input[0] == "(" {
		pop()
		res := getExpr()
		if input[0] != ")" {
			doerror("No closing parenthesis")
		}
		pop()
		return res
	} else {
		doerror(fmt.Sprintf("Misplaced element %s, check syntax", input[0]))
	}
	return 0
}
Beispiel #13
0
func processRow(row string) (d StockData, err os.Error) {
	rowParts := strings.Split(row, ",", -1)
	d.date = rowParts[0]
	var tmp float

	tmp, err = strconv.Atof(rowParts[4])
	if err != nil {
		return
	}
	d.close = tmp

	var tmpInt int
	tmpInt, err = strconv.Atoi(rowParts[5])
	if err != nil {
		return
	}
	d.volume = tmpInt

	return d, nil
}
func (f *floatValue) set(s string) bool {
	v, err := strconv.Atof(s)
	*f.p = v
	return err == nil
}
Beispiel #15
0
func (f *floatValue) Set(s string) bool {
	v, err := strconv.Atof(s)
	*f = floatValue(v)
	return err == nil
}
Beispiel #16
0
func main() {
	flag_help := flag.Bool("help", false, "display this help")
	flag_infile := flag.String("in", "",
		`input file with data. Each row is a data point. First number in
every line must be 1 or -1 and means point class. Next float numbers
are point coordinates.`)

	flag.Parse()

	if *flag_help {
		flag.PrintDefaults()
		return
	}

	// configuring input file
	infile := os.Stdin
	var err os.Error
	if *flag_infile != "" {
		infile, err = os.Open(*flag_infile, os.O_RDONLY, 0000)
		if err != nil {
			panic(err)
		}
	}

	// reading data
	points := make([][]float, 1, 10)
	target := make([]float, 1, 10)
	{
		reader := bufio.NewReader(infile)

		// reading first line
		dimentions := 0
		var err os.Error
		var line string
		line, err = reader.ReadString('\n')
		line = strings.Trim(line, " \t\n")
		chunks := strings.Split(line, "\t", -1)
		if len(chunks) < 3 {
			panic("Too small numbers in a line")
		}

		target[0], err = strconv.Atof(chunks[0])
		if err != nil {
			panic(err)
		}
		dimentions = len(chunks) - 1
		points[0] = make([]float, dimentions)
		for i := 1; i < len(chunks); i++ {
			points[0][i-1], err = strconv.Atof(chunks[i])
			if err != nil {
				panic(err)
			}
		}

		// reading other points
		line, err = reader.ReadString('\n')
		for err == nil || err == os.EOF {
			line = strings.Trim(line, " \t\n")
			if line == "" {
				if err == os.EOF {
					break
				}
				line, err = reader.ReadString('\n')
				continue
			}
			chunks := strings.Split(line, "\t", -1)
			if len(chunks)-1 != dimentions {
				panic("Dimentions mismatch.")
			}

			if len(points)+1 >= cap(points) {
				// resize arrays
				{
					tmp := make([][]float, len(points), 2*len(points))
					copy(tmp, points)
					points = tmp
				}

				{
					tmp := make([]float, len(points), 2*len(points))
					copy(tmp, target)
					target = tmp
				}
			}

			pos := len(points)
			points = points[0 : len(points)+1]
			target = target[0 : len(points)+1]

			target[pos], err = strconv.Atof(chunks[0])
			if err != nil {
				panic(err)
			}
			points[pos] = make([]float, dimentions)
			for i := 1; i < len(chunks); i++ {
				points[pos][i-1], err = strconv.Atof(chunks[i])
				if err != nil {
					panic(err)
				}
			}
			if err == os.EOF {
				break
			}
			line, err = reader.ReadString('\n')
		}
		if err != nil && err != os.EOF {
			panic(err)
		}
	}

	size := len(points)
	C := 5.0

	fmt.Println("Classification started for size", size)

	numChanged := 0
	examineAll := true
	alpha := make([]float, size)

	itersCnt := 0
	for (numChanged > 0) || examineAll {
		itersCnt++
		numChanged = 0
		if examineAll {
			for i, _ := range points {
				numChanged += examineExample(points, target, C, alpha, i)
			}
		} else {
			for i, a := range alpha {
				if a == 0.0 || a == C {
					continue
				}

				numChanged += examineExample(points, target, C, alpha, i)
			}
		}

		if examineAll {
			examineAll = false
		} else if numChanged == 0 {
			examineAll = true
		}
	}

	w, w0 := makeClassificateVector(points, target, alpha)
	errors := 0
	for i := 0; i < len(points)/2; i++ {
		if prod(w, points[i])-w0 >= 0 {
			errors++
		}
	}
	for i := len(points) / 2; i < len(points); i++ {
		if prod(w, points[i])-w0 <= 0 {
			errors++
		}
	}
	if errors > 0 {
		for i, p := range points {
			fmt.Println(i, prod(w, p)-w0)
		}
	}
	fmt.Println("w  =", w)
	fmt.Println("w0 =", w0)
	fmt.Println("iters =", itersCnt)
	fmt.Println("errors =", errors, " /", len(points), " =", float(errors)/float(len(points))*100.0, "%")
}
Beispiel #17
0
func ReadPoints(f io.Reader) (points [][]float, target []float) {
	points = make([][]float, 1, 10)
	target = make([]float, 1, 10)

	reader := bufio.NewReader(f)

	// reading first line
	dimentions := 0
	var err os.Error
	var line string
	line, err = reader.ReadString('\n')
	line = strings.Trim(line, " \t\n")
	chunks := strings.Split(line, "\t", -1)
	if len(chunks) < 3 {
		panic("Too small numbers in a first line.")
	}

	target[0], err = strconv.Atof(chunks[0])
	if err != nil {
		panic(err)
	}
	dimentions = len(chunks) - 1
	points[0] = make([]float, dimentions)
	for i := 1; i < len(chunks); i++ {
		points[0][i-1], err = strconv.Atof(chunks[i])
		if err != nil {
			panic(err)
		}
	}

	// reading other points
	line, err = reader.ReadString('\n')
	for err == nil || err == os.EOF {
		line = strings.Trim(line, " \t\n")
		if line == "" {
			if err == os.EOF {
				break
			}
			line, err = reader.ReadString('\n')
			continue
		}
		chunks := strings.Split(line, "\t", -1)
		if len(chunks)-1 != dimentions {
			panic("Dimentions mismatch.")
		}

		if len(points)+1 >= cap(points) {
			// resize arrays
			{
				tmp := make([][]float, len(points), 2*len(points))
				copy(tmp, points)
				points = tmp
			}

			{
				tmp := make([]float, len(target), 2*len(target))
				copy(tmp, target)
				target = tmp
			}
		}

		pos := len(points)
		points = points[0 : len(points)+1]
		target = target[0 : len(target)+1]

		target[pos], err = strconv.Atof(chunks[0])
		if err != nil {
			panic(err)
		}
		points[pos] = make([]float, dimentions)
		for i := 1; i < len(chunks); i++ {
			points[pos][i-1], err = strconv.Atof(chunks[i])
			if err != nil {
				panic(err)
			}
		}
		if err == os.EOF {
			break
		}
		line, err = reader.ReadString('\n')
	}
	if err != nil && err != os.EOF {
		panic(err)
	}

	return
}
Beispiel #18
0
// TODO: Write tests for the arg checking
func (obj *GTPObject) ExecuteCommand(input string) (result string, quit bool, err Error) {
	empty, hasId, id, commandName, args := obj.parseLine(input)
	if empty {
		return "", false, nil
	}

	gtpCmd, ok := obj.commands[commandName]
	if !ok { // This command is not found
		return obj.formatErrorResponse(hasId, id, "unknown command"), false, nil
	}
	// Check the arguments
	signatureLen := len(gtpCmd.Signature)
	if signatureLen != len(args) {
		return obj.formatErrorResponse(hasId, id, fmt.Sprintf("wrong number of arguments, %d argument(s) expected", signatureLen)), false, nil
	}
	argsToPass := make([]interface{}, len(args))
	for i := 0; i < len(args); i++ {
		// TODO: refactor this!
		// TODO: Do the type conversion (e.g. gtpVertexToPoint) here
		switch gtpCmd.Signature[i] {
		case GTPBool:
			if args[i] != "true" || args[i] != "false" {
				errmsg := fmt.Sprintf("argument %d has to be a boolean", i)
				return obj.formatErrorResponse(hasId, id, errmsg), false, nil
			} else {
				val := true
				if args[i] == "false" {
					val = false
				}
				argsToPass[i] = val
			}
		case GTPColor:
			color, ok := gtpColorToColor(args[i])
			if !ok {
				errmsg := fmt.Sprintf("argument %d has to be a color", i)
				return obj.formatErrorResponse(hasId, id, errmsg), false, nil
			} else {
				argsToPass[i] = color
			}
		case GTPFloat:
			fval, err := strconv.Atof(args[i])
			if err != nil {
				errmsg := fmt.Sprintf("argument %d has to be a float", i)
				return obj.formatErrorResponse(hasId, id, errmsg), false, nil
			} else {
				argsToPass[i] = fval
			}
		case GTPInt:
			ival, err := strconv.Atoui(args[i])
			if err != nil {
				errmsg := fmt.Sprintf("argument %d has to be an unsigned int", i)
				return obj.formatErrorResponse(hasId, id, errmsg), false, nil
			} else {
				argsToPass[i] = ival
			}
		case GTPVertex:
			point, ok, pass := gtpVertexToPoint(args[i])
			if !ok {
				errmsg := fmt.Sprintf("argument %d has to be a vertex", i)
				return obj.formatErrorResponse(hasId, id, errmsg), false, nil
			} else {
				//fmt.Printf("ExecuteCommand: point: %v\n", point)
				argsToPass[i] = *NewVertex(point, pass)
			}
		case GTPString:
			argsToPass[i] = args[i]
		default:
			// This should never happen
			panic("\n\nThe signature of " + commandName + " is set erroneous.\n\n")
		}
	}
	cmdResponse, retQuit, err := gtpCmd.Func(obj, argsToPass)
	if err != nil {
		return obj.formatErrorResponse(hasId, id, cmdResponse), retQuit, nil
	}
	return obj.formatSuccessResponse(hasId, id, cmdResponse), retQuit, nil
}
Beispiel #19
0
// literal consumes a literal from d.data[d.off-1:], decoding into the value v.
// The first byte of the literal has been read already
// (that's how the caller knows it's a literal).
func (d *decodeState) literal(v reflect.Value) {
	// All bytes inside literal return scanContinue op code.
	start := d.off - 1
	op := d.scanWhile(scanContinue)

	// Scan read one byte too far; back up.
	d.off--
	d.scan.undo(op)
	item := d.data[start:d.off]

	// Check for unmarshaler.
	wantptr := item[0] == 'n' // null
	unmarshaler, pv := d.indirect(v, wantptr)
	if unmarshaler != nil {
		err := unmarshaler.UnmarshalJSON(item)
		if err != nil {
			d.error(err)
		}
		return
	}
	v = pv

	switch c := item[0]; c {
	case 'n': // null
		switch v.(type) {
		default:
			d.saveError(&UnmarshalTypeError{"null", v.Type()})
		case *reflect.InterfaceValue, *reflect.PtrValue, *reflect.MapValue:
			v.SetValue(nil)
		}

	case 't', 'f': // true, false
		value := c == 't'
		switch v := v.(type) {
		default:
			d.saveError(&UnmarshalTypeError{"bool", v.Type()})
		case *reflect.BoolValue:
			v.Set(value)
		case *reflect.InterfaceValue:
			v.Set(reflect.NewValue(value))
		}

	case '"': // string
		s, ok := unquote(item)
		if !ok {
			d.error(errPhase)
		}
		switch v := v.(type) {
		default:
			d.saveError(&UnmarshalTypeError{"string", v.Type()})
		case *reflect.StringValue:
			v.Set(s)
		case *reflect.InterfaceValue:
			v.Set(reflect.NewValue(s))
		}

	default: // number
		if c != '-' && (c < '0' || c > '9') {
			d.error(errPhase)
		}
		s := string(item)
		switch v := v.(type) {
		default:
			d.error(&UnmarshalTypeError{"number", v.Type()})
		case *reflect.InterfaceValue:
			n, err := strconv.Atof64(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(reflect.NewValue(n))

		case *reflect.IntValue:
			n, err := strconv.Atoi(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		case *reflect.Int8Value:
			n, err := strconv.Atoi(s)
			if err != nil || int(int8(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(int8(n))
		case *reflect.Int16Value:
			n, err := strconv.Atoi(s)
			if err != nil || int(int16(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(int16(n))
		case *reflect.Int32Value:
			n, err := strconv.Atoi(s)
			if err != nil || int(int32(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(int32(n))
		case *reflect.Int64Value:
			n, err := strconv.Atoi64(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)

		case *reflect.UintValue:
			n, err := strconv.Atoui(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		case *reflect.Uint8Value:
			n, err := strconv.Atoui(s)
			if err != nil || uint(uint8(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(uint8(n))
		case *reflect.Uint16Value:
			n, err := strconv.Atoui(s)
			if err != nil || uint(uint16(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(uint16(n))
		case *reflect.Uint32Value:
			n, err := strconv.Atoui(s)
			if err != nil || uint(uint32(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(uint32(n))
		case *reflect.Uint64Value:
			n, err := strconv.Atoui64(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		case *reflect.UintptrValue:
			n, err := strconv.Atoui64(s)
			if err != nil || uint64(uintptr(n)) != n {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(uintptr(n))

		case *reflect.FloatValue:
			n, err := strconv.Atof(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		case *reflect.Float32Value:
			n, err := strconv.Atof32(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		case *reflect.Float64Value:
			n, err := strconv.Atof64(s)
			if err != nil {
				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
				break
			}
			v.Set(n)
		}
	}
}
Beispiel #20
0
func writeTo(data []byte, val reflect.Value) os.Error {
	s := string(data)
	switch v := val.(type) {
	// if we're writing to an interace value, just set the byte data
	// TODO: should we support writing to a pointer?
	case *reflect.InterfaceValue:
		v.Set(reflect.NewValue(data))
	case *reflect.BoolValue:
		b, err := strconv.Atob(s)
		if err != nil {
			return err
		}
		v.Set(b)
	case *reflect.IntValue:
		i, err := strconv.Atoi(s)
		if err != nil {
			return err
		}
		v.Set(i)
	case *reflect.Int8Value:
		i, err := strconv.Atoi(s)
		if err != nil {
			return err
		}
		v.Set(int8(i))
	case *reflect.Int16Value:
		i, err := strconv.Atoi(s)
		if err != nil {
			return err
		}
		v.Set(int16(i))
	case *reflect.Int32Value:
		i, err := strconv.Atoi(s)
		if err != nil {
			return err
		}
		v.Set(int32(i))
	case *reflect.Int64Value:
		i, err := strconv.Atoi64(s)
		if err != nil {
			return err
		}
		v.Set(i)
	case *reflect.UintValue:
		ui, err := strconv.Atoui(s)
		if err != nil {
			return err
		}
		v.Set(ui)

	case *reflect.Uint8Value:
		ui, err := strconv.Atoui(s)
		if err != nil {
			return err
		}
		v.Set(uint8(ui))
	case *reflect.Uint16Value:
		ui, err := strconv.Atoui(s)
		if err != nil {
			return err
		}
		v.Set(uint16(ui))
	case *reflect.Uint32Value:
		ui, err := strconv.Atoui(s)
		if err != nil {
			return err
		}
		v.Set(uint32(ui))
	case *reflect.Uint64Value:
		ui, err := strconv.Atoui64(s)
		if err != nil {
			return err
		}
		v.Set(ui)
	case *reflect.UintptrValue:
		ui, err := strconv.Atoui64(s)
		if err != nil {
			return err
		}
		v.Set(uintptr(ui))
	case *reflect.FloatValue:
		f, err := strconv.Atof(s)
		if err != nil {
			return err
		}
		v.Set(f)

	case *reflect.Float32Value:
		f, err := strconv.Atof32(s)
		if err != nil {
			return err
		}
		v.Set(f)
	case *reflect.Float64Value:
		f, err := strconv.Atof64(s)
		if err != nil {
			return err
		}
		v.Set(f)

	case *reflect.StringValue:
		v.Set(s)
	case *reflect.SliceValue:
		typ := v.Type().(*reflect.SliceType)
		if _, ok := typ.Elem().(*reflect.Uint8Type); ok {
			v.Set(reflect.NewValue(data).(*reflect.SliceValue))
		}
	}
	return nil
}
Beispiel #21
0
func (s *Stmt) Scan(args ...interface{}) os.Error {
	n := int(C.sqlite3_column_count(s.stmt))
	if n != len(args) {
		return os.NewError("incorrect argument count")
	}

	for i, v := range args {
		n := C.sqlite3_column_bytes(s.stmt, C.int(i))
		p := C.sqlite3_column_blob(s.stmt, C.int(i))

		if p == nil && n > 0 {
			return os.NewError("got nil blob")
		}

		var data []byte
		if n > 0 {
			// fix(jimt): Must make a copy here. Once Stmt.Finalize() is called,
			// this memory becomes invalid. This was done on purpose according
			// to Russ: http://code.google.com/p/gosqlite/issues/detail?id=1
			// I prefer it with the copy statement here. Behaviour otherwise is
			// misleading and cost me 3 hours of hair pulling.
			data = make([]byte, n)
			copy(data, (*[1<<31 - 1]byte)(unsafe.Pointer(p))[0:n])
		}

		switch v := v.(type) {
		case *[]byte:
			*v = data
		case *string:
			*v = string(data)
		case *bool:
			*v = string(data) == "1"
		case *int:
			x, err := strconv.Atoi(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = x
		case *int8:
			x, err := strconv.Atoi(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = int8(x)
		case *int16:
			x, err := strconv.Atoi(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = int16(x)
		case *int32:
			x, err := strconv.Atoi(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = int32(x)
		case *int64:
			x, err := strconv.Atoi64(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int64: " + err.String())
			}
			*v = x
		case *uint:
			x, err := strconv.Atoui(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = x
		case *uint8:
			x, err := strconv.Atoui(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = uint8(x)
		case *uint16:
			x, err := strconv.Atoui(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = uint16(x)
		case *uint32:
			x, err := strconv.Atoui(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int: " + err.String())
			}
			*v = uint32(x)
		case *uint64:
			x, err := strconv.Atoui64(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as int64: " + err.String())
			}
			*v = x
		case *float:
			x, err := strconv.Atof(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as float64: " + err.String())
			}
			*v = x
		case *float32:
			x, err := strconv.Atof32(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as float64: " + err.String())
			}
			*v = x
		case *float64:
			x, err := strconv.Atof64(string(data))
			if err != nil {
				return os.NewError("arg " + strconv.Itoa(i) + " as float64: " + err.String())
			}
			*v = x
		default:
			return os.NewError("unsupported type in Scan: " + reflect.Typeof(v).String())
		}
	}
	return nil
}
Beispiel #22
0
func (vm *NgaroVM) core(ip int) {
	var port [nports]int
	var sp, rsp int
	var tos int
	var data, addr [stackDepth + 2]int
	sp = 2 // to avoid underflows
	defer func() {
		if v := recover(); v != nil {
			if err, ok := v.(os.Error); ok {
				vm.Err <- err
			} else {
				vm.Err <- os.NewError("unknown error:" + fmt.Sprint(v))
			}
		}
	}()
	for ; ip < len(vm.img); ip++ {
		switch vm.img[ip] {
		case Nop:
		case Lit:
			sp++
			ip++
			data[sp] = vm.img[ip]
		case Dup:
			sp++
			data[sp] = tos
		case Drop:
			sp--
		case Swap:
			data[sp], data[sp-1] = data[sp-1], tos
		case Push:
			rsp++
			addr[rsp] = tos
			sp--
		case Pop:
			sp++
			data[sp] = addr[rsp]
			rsp--
		case Call:
			ip++
			rsp++
			addr[rsp] = ip
			ip = vm.img[ip] - 1
		case Jump:
			ip++
			ip = vm.img[ip] - 1
		case Return:
			ip = addr[rsp]
			rsp--
		case GtJump:
			ip++
			if data[sp-1] > tos {
				ip = vm.img[ip] - 1
			}
			sp = sp - 2
		case LtJump:
			ip++
			if data[sp-1] < tos {
				ip = vm.img[ip] - 1
			}
			sp = sp - 2
		case NeJump:
			ip++
			if data[sp-1] != tos {
				ip = vm.img[ip] - 1
			}
			sp = sp - 2
		case EqJump:
			ip++
			if data[sp-1] == tos {
				ip = vm.img[ip] - 1
			}
			sp = sp - 2
		case Fetch:
			data[sp] = vm.img[tos]
		case Store:
			vm.img[tos] = data[sp-1]
			sp = sp - 2
		case Add:
			data[sp-1] += tos
			sp--
		case Sub:
			data[sp-1] -= tos
			sp--
		case Mul:
			data[sp-1] *= tos
			sp--
		case Dinod:
			data[sp] = data[sp-1] / tos
			data[sp-1] = data[sp-1] % tos
		case And:
			data[sp-1] &= tos
			sp--
		case Or:
			data[sp-1] |= tos
			sp--
		case Xor:
			data[sp-1] ^= tos
			sp--
		case ShL:
			data[sp-1] <<= uint(tos)
			sp--
		case ShR:
			data[sp-1] >>= uint(tos)
			sp--
		case ZeroExit:
			if tos == 0 {
				sp--
				ip = addr[rsp]
				rsp--
			}
		case Inc:
			data[sp]++
		case Dec:
			data[sp]--
		case In:
			data[sp] = port[tos]
			port[tos] = 0
		case Out:
			port[0] = 0
			port[tos] = data[sp-1]
			sp = sp - 2
		case Wait:
			sp -= vm.wait(&port, tos, sp, rsp, data[0:])

		case FP + GtJump:
			ip++
			if itof(data[sp-1]) > itof(tos) {
				ip = vm.img[ip] - 1
			}
			sp = sp - 2
		case FP + LtJump:
			ip++
			if itof(data[sp-1]) < itof(tos) {
				ip = vm.img[ip] - 1
			}
			sp = sp - 2
		case FP + Add:
			data[sp-1] = ftoi(itof(data[sp-1]) + itof(tos))
			sp--
		case FP + Sub:
			data[sp-1] = ftoi(itof(data[sp-1]) - itof(tos))
			sp--
		case FP + Mul:
			data[sp-1] = ftoi(itof(data[sp-1]) * itof(tos))
			sp--
		case FP + Dinod:
			data[sp-1] = ftoi(itof(data[sp-1]) / itof(tos))
			sp--
		// TODO: more math operations

		case IOint + In:
			a := readA(vm.img, tos)
			sp++
			if i, err := strconv.Atoi(a); err != nil {
				data[sp] = 0
			} else {
				data[sp-1] = i
				data[sp] = -1
			}
		case IOint + Out:
			fmt.Fprint(vm.Output, tos)
			sp--
		case IOfloat + In:
			a := readA(vm.img, tos)
			sp++
			if f, err := strconv.Atof(a); err != nil {
				data[sp] = 0
			} else {
				data[sp-1] = ftoi(f)
				data[sp] = -1
			}
		case IOfloat + Out:
			fmt.Fprint(vm.Output, itof(tos))
			sp--
		case IOstring + In: // Accept
			var c [1]byte
			var cont func() bool
			if data[sp-1] == -1 {
				cont = func() bool { return c[0] != ' ' && c[0] != '\n' && c[0] != '\t' }
			} else {
				cont = func() bool { return c[0] != byte(data[sp-1]) }
			}
			a := tos
		readInput:
			_, err := vm.Input.Read(c[0:])
			// Skip leading white-space
			for data[sp-1] == -1 && (c[0] == ' ' || c[0] == '\n' || c[0] == '\t') {
				vm.Input.Read(c[0:])
			}
			for ; err == nil && cont(); _, err = vm.Input.Read(c[0:]) {
				vm.img[a] = int(c[0])
				a++
			}
			if err == os.EOF && vm.Input != nil {
				vm.Input.Close()
				vm.Input = vm.Input.Next
				goto readInput
			}
			if err != nil {
				panic(err)
			}
			vm.img[a] = 0
			sp -= 2
		case IOstring + Out:
			i := tos
			for ; i < len(vm.img) && vm.img[i] != 0; i++ {
			}
			fmt.Fprint(vm.Output, string(vm.img[tos:i]))
			sp--

		default:
			rsp++
			addr[rsp] = ip
			ip = vm.img[ip] - 1
		}
		// to avoid segfaults:
		if sp < 2 {
			sp = 2
		}
		tos = data[sp]
	}
}
Beispiel #23
0
func (this *Option) Float() float {
	if v, err := strconv.Atof(this.value); err == nil {
		return v
	}
	return this.defaultval.(float)
}
Beispiel #24
0
	expr.Add(peg.Or{
		peg.Bind(_INT, func(x interface{}) interface{} {
			s := x.(string)
			res, err := strconv.Atoi(s)
			if err != nil {
				num := big.NewInt(0)
				_, ok := num.SetString(s, 10)
				if !ok {
					SystemError(err)
				}
				return num
			}
			return res
		}),
		peg.Bind(_FLOAT, func(x interface{}) interface{} {
			res, err := strconv.Atof(x.(string))
			if err != nil {
				SystemError(err)
			}
			return res
		}),
		peg.Bind(_STR, func(x interface{}) interface{} {
			res, err := strconv.Unquote(x.(string))
			if err != nil {
				SystemError(err)
			}
			return res
		}),
		listExpr(_LSTART, expr, _LEND),
		listExpr(_LSTART2, expr, _LEND2),
		peg.Bind(
Beispiel #25
0
func parseInnerNode(pi ParserInput, pos int) (*tree.LN, int) {

	//fmt.Printf( "parse inner node\n" );

	pos = skipWhitespace(pi, pos)

	if pi.CharAt(pos) != '(' {
		fmt.Printf("error: expected '('\n")
	}
	// consume opening '('
	pos++

	var nl *tree.LN
	nl, pos = parseNode(pi, pos)

	var bll float
	bll, pos = parseBranchLength(pi, pos)

	//     fmt.Printf( "parsing next node %d\n", pos );

	var labell string
	labell, pos = parseBranchLabel(pi, pos)

	pos = skipWhitespace(pi, pos)

	// expect + consume ','
	if pi.CharAt(pos) != ',' {

		fmt.Printf("parse error: parseInnerNode expects ',' at %d\n", pos)
	}
	pos++

	// parse right node + branch length
	var nr *tree.LN
	nr, pos = parseNode(pi, pos)

	var blr float
	blr, pos = parseBranchLength(pi, pos)

	var labelr string
	labelr, pos = parseBranchLabel(pi, pos)

	pos = skipWhitespace(pi, pos)

	if pi.CharAt(pos) == ',' {
		// second comma found: three child nodes == pseudo root
		pos++

		var nx *tree.LN
		nx, pos = parseNode(pi, pos)

		var blx float
		blx, pos = parseBranchLength(pi, pos)

		var labelx string
		labelx, pos = parseBranchLabel(pi, pos)

		pos = skipWhitespace(pi, pos)

		if pi.CharAt(pos) != ')' {
			//            printLocation();
			fmt.Printf("parse error: parseInnerNode (at root) expects ') at %d\n", pos)
		}
		pos++
		pos = skipWhitespace(pi, pos)

		n := tree.CreateLN()

		twiddle(nl, n.Next, bll, labell, n.Data.Support)
		twiddle(nr, n.Next.Next, blr, labelr, n.Data.Support)
		twiddle(nx, n, blx, labelx, n.Data.Support)

		//      fmt.Printf( "twiddle root\n" );

		//                      System.out.printf( "root: %f %f %f\n", nl.data.getSupport(), nr.data.getSupport(), nx.data.getSupport() );
		//                      System.exit(0);
		return n, pos
	} else if pi.CharAt(pos) == ')' {
		// the stuff between the closing '(' and the ':' of the branch length
		// is interpreted as node-label. If the node label corresponds to a float value
		// it is interpreted as branch support (or node support as a rooted-trees-only-please biologist would say)

		pos++
		lend := findEndOfBranch(pi, pos)

		nodeLabel := pi.Substring(pos, lend)
		pos = lend

		//    fmt.Printf( "pos: %d %s\n", pos, nodeLabel );
		isDigit := true
		for i := range nodeLabel {
			isDigit = isDigit && IsDigit(nodeLabel[i])

			if i == 0 {
				isDigit = isDigit && (nodeLabel[i] != '0')
			}
		}

		var support float
		if isDigit {
			support, _ = strconv.Atof(nodeLabel)
		} else {
			support = -1
		}

		n := tree.CreateLN()
		n.Data.Support = support
		//n.data.setNodeLabel(nodeLabel);

		twiddle(nl, n.Next, bll, labell, support)
		twiddle(nr, n.Next.Next, blr, labelr, support)

		return n, pos

	} else {
		fmt.Printf("parse error: parseInnerNode expects ')'or ',' at %d got: %c\n", pos, pi.CharAt(pos))
		return nil, pos
	}

	panic("unreachable")
}