func hasProperty(a, b int) bool { stra := strconv.Itoa(a) strb := strconv.Itoa(b) num := uint8(0) den := uint8(0) if stra[0] == strb[0] { num = stra[1] den = strb[1] } else if stra[0] == strb[1] { num = stra[1] den = strb[0] } else if stra[1] == strb[1] && stra[1] != uint8(48) { num = stra[0] den = strb[0] } else if stra[1] == strb[0] { num = stra[0] den = strb[1] } else { return false } newa, _ := strconv.Atof64(string(num)) newb, _ := strconv.Atof64(string(den)) if float64(a)/float64(b) == newa/newb { return true } return false }
// GetOrderBook retrieves the limit order book. func GetOrderBook(c appengine.Context) (x xgen.OrderBook, err os.Error) { defer func() { if e, ok := recover().(os.Error); ok { err = e } }() var b OrderBook err = restapi.GetJson(c, JsonDepth, &b) check(err) for _, ask := range b.Asks { var o xgen.Order o.Price, err = strconv.Atof64(ask[Price]) check(err) o.Amount, err = strconv.Atof64(ask[Amount]) check(err) x.SellTree = append(x.SellTree, o) } for _, bid := range b.Bids { var o xgen.Order o.Price, err = strconv.Atof64(bid[Price]) check(err) o.Amount, err = strconv.Atof64(bid[Amount]) check(err) x.BuyTree = append(x.BuyTree, o) } if !x.Validate() { panic("Invalid Depth") } sort.Sort(x.BuyTree) sort.Sort(x.SellTree) x.BuyTree.Reverse() return }
// Parses a string representation of a LV++ coordinate into a struct holding a SwissCoord coordinate value. // The reference ellipsoid of Swisscoord datum is always the GRS80 ellipsoid. func ASwissCoordToStruct(coord string) (*SwissCoord, os.Error) { compact := strings.ToUpper(strings.TrimSpace(coord)) var rights, heights string var coordType, oldcoordType SwissCoordType var right, height float64 var err os.Error L1: for i, index := 0, 0; i < 2; i++ { index = strings.Index(compact, " ") if index == -1 { index = len(compact) } switch compact[:2] { case "X:": coordType = LV03 heights = compact[2:index] case "Y:": coordType = LV03 rights = compact[2:index] case "E:": coordType = LV95 rights = compact[2:index] case "N:": coordType = LV95 heights = compact[2:index] default: err = os.EINVAL break L1 } if oldcoordType != coordType { err = os.EINVAL break L1 } if i == 1 { break L1 } compact = compact[index+len(" "):] compact = strings.TrimLeft(compact, " ") oldcoordType = coordType } if err == nil { right, err = strconv.Atof64(rights) if err == nil { height, err = strconv.Atof64(heights) if err == nil { return &SwissCoord{Easting: right, Northing: height, CoordType: coordType, el: cartconvert.Bessel1841Ellipsoid}, nil } } } return nil, err }
func (h OpenOrders) convert() (o xgen.OpenOrders) { // Convert campbx.OpenOrders to xgen.OpenOrders var err os.Error o.Sell = make(map[string]xgen.OpenOrder) o.Buy = make(map[string]xgen.OpenOrder) for _, order := range h.Buy { if order.Oid != "" { var t xgen.OpenOrder t.Date = time.Seconds() // Should use time.Parse to convert order.DateEntered to Unix time t.Price, err = strconv.Atof64(order.Price) check(err) t.Amount, err = strconv.Atof64(order.Quantity) check(err) o.Buy[order.Oid] = t } } for _, order := range h.Sell { if order.Oid != "" { var t xgen.OpenOrder t.Date = time.Seconds() // Should use time.Parse to convert order.DateEntered to Unix time t.Price, err = strconv.Atof64(order.Price) check(err) t.Amount, err = strconv.Atof64(order.Quantity) check(err) o.Sell[order.Oid] = t } } return }
func ReadCoef() Coef { var c Coef c[0], _ = strconv.Atof64(os.Args[1]) c[1], _ = strconv.Atof64(os.Args[2]) c[2], _ = strconv.Atof64(os.Args[3]) return c }
func (p byQuality) Less(i, j int) bool { qi := float64(1) if s, ok := p[i].Param["q"]; ok { qi, _ = strconv.Atof64(s) } qj := float64(1) if s, ok := p[j].Param["q"]; ok { qj, _ = strconv.Atof64(s) } return qj < qi }
// Tests if value 1 is greater than value2. The values are converted to double before comparison. // Always returns false if number format is unexpected. func (f Gt) Cmp(v1, v2 interface{}) bool { d1, err := strconv.Atof64(fmt.Sprint(v1)) if err != nil { return false } d2, err := strconv.Atof64(fmt.Sprint(v2)) if err != nil { return false } return d1 > d2 }
// Parses a string representation of a BMN-Coordinate into a struct holding a BMN coordinate value. // The reference ellipsoid of BMN coordinates is always the Bessel ellipsoid. func ABMNToStruct(bmncoord string) (*BMNCoord, os.Error) { compact := strings.ToUpper(strings.TrimSpace(bmncoord)) var rights, heights string var meridian BMNMeridian var right, height float64 var err os.Error L1: for i, index := 0, 0; i < 3; i++ { index = strings.Index(compact, " ") if index == -1 { index = len(compact) } switch i { case 0: switch compact[:index] { case "M28": meridian = BMNM28 case "M31": meridian = BMNM31 case "M34": meridian = BMNM34 default: err = os.EINVAL break L1 } case 1: rights = compact[:index] case 2: heights = compact[:index] break L1 } compact = compact[index+len(" "):] compact = strings.TrimLeft(compact, " ") } if err == nil { right, err = strconv.Atof64(rights) if err == nil { height, err = strconv.Atof64(heights) if err == nil { return &BMNCoord{Right: right, Height: height, Meridian: meridian, el: cartconvert.Bessel1841MGIEllipsoid}, nil } } } return nil, err }
func parseTestOutput(stderr string) (res *Stats) { res = new(Stats) for _, line := range strings.Split(stderr, "\n") { line = strings.TrimSpace(line) if asmInstrsRegexp.MatchString(line) { ss := asmInstrsRegexp.FindStringSubmatch(line) if len(ss) != 2 { log.Printf("parseTestOutput: could not parse AsmInstrs statistic for line=[%s]", line) continue } var err os.Error if res.AsmInstrs, err = strconv.Atoi(ss[1]); err != nil { log.Printf("parseTestOutput: could not parse int value of AsmInstrs statistic "+ "for line=[%s], matched substring=[%s], err: %v", line, ss[1], err) continue } } if stackSpaceRegexp.MatchString(line) { ss := stackSpaceRegexp.FindStringSubmatch(line) if len(ss) != 2 { log.Printf("parseTestOutput: could not parse StackSpace statistic for line=[%s]", line) continue } var err os.Error if res.StackSpace, err = strconv.Atoi(ss[1]); err != nil { log.Printf("parseTestOutput: could not parse int value of StackSpace statistic "+ "for line=[%s], matched substring=[%s], err: %v", line, ss[1], err) continue } } if execTimeRegexp.MatchString(line) { ss := execTimeRegexp.FindStringSubmatch(line) if len(ss) != 3 { log.Printf("parseTestOutput: could not parse ExecTime statistic for line=[%s]", line) continue } var err os.Error if res.Seconds, err = strconv.Atof64(ss[1]); err != nil { log.Printf("parseTestOutput: could not parse int value of Seconds statistic "+ "for line=[%s], matched substring=[%s], err: %v", line, ss[1], err) continue } if res.WallSeconds, err = strconv.Atof64(ss[2]); err != nil { log.Printf("parseTestOutput: could not parse int value of WallSeconds statistic "+ "for line=[%s], matched substring=[%s], err: %v", line, ss[2], err) continue } } } return }
func (q *QuotaQuery) CheckValid() os.Error { var err os.Error if q.low, err = strconv.Atof64(q.lowStr); err != nil { return err } if q.high, err = strconv.Atof64(q.highStr); err != nil { return err } if q.low > q.high { return os.NewError("value low > high\n") } return nil }
// GetBalance retrieves the account balance. func GetBalance(c appengine.Context, login xgen.Credentials) (x xgen.Balance, err os.Error) { defer func() { if e, ok := recover().(os.Error); ok { err = e } }() var b Balance err = restapi.PostJson(c, JsonBalance, map[string][]string{"name": {login.Username}, "pass": {login.Password}}, &b) check(err) x[xgen.BTC], err = strconv.Atof64(b.BTC) check(err) x[xgen.USD], err = strconv.Atof64(b.USD) return }
func chooseMediaType(providedStrings []string, accept string) string { bestScore := -1.0 bestMatch := "" accepts := splitAcceptString(accept) providedSets := splitAcceptArray(providedStrings) for _, acceptMatch := range accepts { for i, provided := range providedSets { if (acceptMatch.thetype == provided.thetype || acceptMatch.thetype == "*") && (acceptMatch.subtype == provided.subtype || acceptMatch.subtype == "*") { score := 100.0 if len(provided.subtype) > 0 && len(acceptMatch.subtype) > 0 && (provided.subtype == acceptMatch.subtype || acceptMatch.subtype == "*") { score += 10.0 } for k, v := range acceptMatch.parameters { if k != "q" { if v2, ok := provided.parameters[k]; ok && v == v2 { score += 1.0 } } } if q, ok := acceptMatch.parameters["q"]; ok { if qf, err := strconv.Atof64(q); err != nil { score *= qf } } if score > bestScore { bestScore = score bestMatch = providedStrings[i] } } } } return bestMatch }
func (self *String) Float() (f float64) { var err os.Error if f, err = strconv.Atof64(string(*self)); err != nil { panic(err) } return f }
func AsFloat64(v interface{}) (float64, os.Error) { switch value := v.(type) { default: return 0, os.NewError(fmt.Sprintf("unexpected type: %T", value)) case int: return float64(value), nil case int8: return float64(value), nil case int16: return float64(value), nil case int32: return float64(value), nil case int64: return float64(value), nil case uint: return float64(value), nil case uint8: return float64(value), nil case uint16: return float64(value), nil case uint32: return float64(value), nil case uint64: return float64(value), nil case float32: return float64(value), nil case float64: return float64(value), nil case string: return strconv.Atof64(value) } panic(fmt.Sprintf("unsupported type: %s", reflect.ValueOf(v).Type().Name())) }
func scan(v *yystype) (output int) { i := s.Scan() switch i { case scanner.Ident: switch s.TokenText() { case "for": output = tfor case "range": output = trange default: output = ident } v.s = s.TokenText() case scanner.String, scanner.RawString: output = atom text := s.TokenText() v.i = text[1 : len(text)-1] case scanner.Int: output = atom v.i, _ = strconv.Atoi(s.TokenText()) case scanner.Float: output = atom v.i, _ = strconv.Atof64(s.TokenText()) case scanner.EOF: output = eof default: output = i } return }
func decodeColumn(idx int, field *mysql.Field, val interface{}) (interface{}, os.Error) { var dec interface{} var err os.Error switch v := val.(type) { case int64: return v, nil case []byte: switch field.Type { case mysql.FIELD_TYPE_TINY, mysql.FIELD_TYPE_SHORT, mysql.FIELD_TYPE_YEAR, mysql.FIELD_TYPE_INT24, mysql.FIELD_TYPE_LONG, mysql.FIELD_TYPE_LONGLONG: if field.Flags&mysql.FLAG_UNSIGNED != 0 { dec, err = strconv.Atoui64(string(v)) } else { dec, err = strconv.Atoi64(string(v)) } if err != nil { return nil, fmt.Errorf("mysql: strconv.Atoi64 error on field %d: %v", idx, err) } case mysql.FIELD_TYPE_FLOAT, mysql.FIELD_TYPE_DOUBLE: dec, err = strconv.Atof64(string(v)) if err != nil { return nil, fmt.Errorf("mysql: strconv.Atof64 error on field %d: %v", idx, err) } case mysql.FIELD_TYPE_DECIMAL, mysql.FIELD_TYPE_NEWDECIMAL, mysql.FIELD_TYPE_VARCHAR, mysql.FIELD_TYPE_VAR_STRING, mysql.FIELD_TYPE_STRING: dec = string(v) default: return nil, fmt.Errorf("row[%d] was a []byte but unexpected field type %d", idx, field.Type) } return dec, nil } return nil, fmt.Errorf("expected row[%d] contents to be a []byte, got %T for field type %d", idx, val, field.Type) }
// Get node value as float64 func (this *Node) F64(namespace, name string) float64 { if node := rec_SelectNode(this, namespace, name); node != nil && node.Value != "" { n, _ := strconv.Atof64(node.Value) return n } return 0 }
func main() { var p Point var erx, ery os.Error p.x, erx = strconv.Atof64(flag.Arg(0)) p.y, ery = strconv.Atof64(flag.Arg(1)) if erx != nil { fmt.Printf("Error: %s\n", erx) } else if ery != nil { fmt.Printf("Error: %s\n", ery) } else { fmt.Printf("p.x is %.1f\n", p.x) fmt.Printf("p.y is %.1f\n", p.y) fmt.Printf("Distance from origin: %.1f\n", Distance(p)) } }
func main() { for true { r := bufio.NewReader(os.Stdin) s, err := r.ReadString('\n') if err == os.EOF { break } s = strings.TrimRight(s, "\n") a := strings.Split(s, " ") f := a[0] x, err := strconv.Atof64(a[1]) switch f { case "erf": fmt.Println(math.Erf(x)) case "expm1": fmt.Println(math.Expm1(x)) case "phi": fmt.Println(phi.Phi(x)) case "NormalCDFInverse": fmt.Println(normal_cdf_inverse.NormalCDFInverse(x)) case "Gamma": fmt.Println(math.Gamma(x)) case "LogGamma": r, _ := math.Lgamma(x) fmt.Println(r) case "LogFactorial": fmt.Println(log_factorial.LogFactorial(int(x))) default: fmt.Println("Unknown function: " + f) return } } }
func (rs *ResultSet) float64(ord int) (value float64, isNull bool) { if rs.conn.LogLevel >= LogVerbose { defer rs.conn.logExit(rs.conn.logEnter("*ResultSet.float64")) } isNull = rs.isNull(ord) if isNull { return } val := rs.values[ord] switch rs.fields[ord].format { case textFormat: // strconv.Atof64 does not handle NaN if string(val) == "NaN" { value = math.NaN() } else { var err os.Error value, err = strconv.Atof64(string(val)) panicIfErr(err) } case binaryFormat: value = math.Float64frombits(binary.BigEndian.Uint64(val)) } return }
func makeLevel(status *abc.Status, args map[string]interface{}) Widget { level, err := strconv.Atof64(args["1"].(string)) if err != nil { panic("bad frequency") } return Level(float32(level), 0) }
func (self FitsHeaderItem) AsFloat() float64 { value, err := strconv.Atof64(self.first_token()) if err == nil { return value } return math.NaN() }
func (rs *ResultSet) float64(ord int) (value float64, isNull bool) { if rs.conn.LogLevel >= LogVerbose { defer rs.conn.logExit(rs.conn.logEnter("*ResultSet.float64")) } isNull = rs.isNull(ord) if isNull { return } val := rs.values[ord] switch rs.fields[ord].format { case textFormat: // strconv.Atof64 does not handle "-Infinity" and "Infinity" valStr := string(val) switch valStr { case "-Infinity": value = math.Inf(-1) case "Infinity": value = math.Inf(1) default: var err os.Error value, err = strconv.Atof64(valStr) panicIfErr(err) } case binaryFormat: value = math.Float64frombits(binary.BigEndian.Uint64(val)) } return }
// Get attribute value as float64 func (this *Node) Af64(namespace, name string) float64 { if s := this.As(namespace, name); s != "" { n, _ := strconv.Atof64(s) return n } return 0 }
// Base to read strings. func (q *Question) _baseReadString(prompt, defaultAnswer string, def hasDefault) (answer string, err os.Error) { line := q.getLine(prompt, defaultAnswer, def) for { answer, err = line.Read() if err != nil { return "", err } if answer != "" { // === Check if it is a number if _, err := strconv.Atoi(answer); err == nil { goto _error } if _, err := strconv.Atof64(answer); err == nil { goto _error } return answer, nil } if def != _DEFAULT_NO { return defaultAnswer, nil } continue _error: fmt.Fprintf(output, "%s%v: the value has to be a string\r\n", QuestionErrPrefix, answer) } return }
// Scan parses the values of the current result row (set using Result.Next) // into the given arguments. func (r *Result) Scan(args ...interface{}) os.Error { if len(args) != r.ncols { return os.NewError(fmt.Sprintf("incorrect argument count for Result.Scan: have %d want %d", len(args), r.ncols)) } for i, v := range args { if int(C.PQgetisnull(r.res, C.int(r.currRow), C.int(i))) == 1 { continue } val := C.GoString(C.PQgetvalue(r.res, C.int(r.currRow), C.int(i))) switch v := v.(type) { case *[]byte: if !strings.HasPrefix(val, "\\x") { return argErr(i, "[]byte", "invalid byte string format") } buf, err := hex.DecodeString(val[2:]) if err != nil { return argErr(i, "[]byte", err.String()) } *v = buf case *string: *v = val case *bool: *v = val == "t" case *int: x, err := strconv.Atoi(val) if err != nil { return argErr(i, "int", err.String()) } *v = x case *int64: x, err := strconv.Atoi64(val) if err != nil { return argErr(i, "int64", err.String()) } *v = x case *float32: x, err := strconv.Atof32(val) if err != nil { return argErr(i, "float32", err.String()) } *v = x case *float64: x, err := strconv.Atof64(val) if err != nil { return argErr(i, "float64", err.String()) } *v = x case *time.Time: x, _, err := ParseTimestamp(val) if err != nil { return argErr(i, "time.Time", err.String()) } *v = *x default: return os.NewError("unsupported type in Scan: " + reflect.TypeOf(v).String()) } } return nil }
// Base to read float numbers. func (q *Question) _baseReadFloat(prompt string, defaultAnswer float64, def hasDefault) (answer float64, err os.Error) { line := q.getLine( prompt, strconv.Ftoa64(defaultAnswer, QuestionFloatFmt, QuestionFloatPrec), def, ) for { input, err := line.Read() if err != nil { return 0.0, err } if input == "" && def != _DEFAULT_NO { return defaultAnswer, nil } answer, err = strconv.Atof64(input) if err != nil { fmt.Fprintf(output, "%s%q: the value has to be a float\r\n", QuestionErrPrefix, input) continue } else { return answer, nil } } return }
// ParseTime parses the time interval from s, and returns it // as nanoseconds, if it is representable in seconds (with // isNanoSeconds true), or sample count (with isNanoSeconds false) // if not. func ParseTime(s string) (t Time, err os.Error) { endi := strings.LastIndexFunc(s, isDigit) + 1 if endi == 0 { return Time{}, os.NewError("invalid number") } number, suffix := s[0:endi], s[endi:] var mult int64 switch suffix { case "s", "": mult = 1e9 case "ms": mult = 1e6 case "us": mult = 1e3 case "ns": mult = 1 case "x": // samples mult = 1 } // use exact arithmetic if we can d, err := strconv.Atoi64(number) if err != nil { f, err := strconv.Atof64(number) if err != nil { return Time{}, err } d = int64(f * float64(mult)) } else { d *= mult } return Time{d, suffix != "x"}, nil }
func Btof64(buff []byte) (num float64, e Error) { num, ce := strconv.Atof64(bytes.NewBuffer(buff).String()) if ce != nil { e = NewErrorWithCause(SYSTEM_ERR, "Expected a parsable byte representation of a float64", ce) } return }
func SimulationHandler(w http.ResponseWriter, r *http.Request) { vars := strings.Split(r.URL.Path[5:], "/", 3) if len(vars) != 3 { io.WriteString(w, "Invalid Simulation Parameters") return } //TODO: Help user realize their errors spawnTime, err := strconv.Atof64(vars[0]) if err != nil { spawnTime = 60 } numNurse, err := strconv.Atoi(vars[1]) if err != nil { numNurse = 1 } numDoc, err := strconv.Atoi(vars[2]) if err != nil { numDoc = 1 } fmt.Println("Running Requested Simulation....") fmt.Println(spawnTime, numNurse, numDoc) h := NewHospital(spawnTime, numNurse, numDoc) h = <-h.StartSimulation() fmt.Println("Simulation Completed....") io.WriteString(w, compilePage(h.Patients)) }