func AsString(v interface{}) (string, os.Error) { switch value := v.(type) { default: return "", os.NewError(fmt.Sprintf("unexpected type: %T", value)) case int: return strconv.Itoa(value), nil case int8: return strconv.Itoa(int(value)), nil case int16: return strconv.Itoa(int(value)), nil case int32: return strconv.Itoa(int(value)), nil case int64: return strconv.Itoa64(value), nil case uint: return strconv.Uitoa(value), nil case uint8: return strconv.Uitoa(uint(value)), nil case uint16: return strconv.Uitoa(uint(value)), nil case uint32: return strconv.Uitoa(uint(value)), nil case uint64: return strconv.Uitoa64(value), nil case float32: return strconv.Ftoa32(value, 'g', -1), nil case float64: return strconv.Ftoa64(value, 'g', -1), nil case string: return value, nil } panic(fmt.Sprintf("unsupported type: %s", reflect.ValueOf(v).Type().Name())) }
func valueToString(v reflect.Value) (string, os.Error) { if v == nil { return "null", nil } switch v := v.(type) { case *reflect.PtrValue: return valueToString(reflect.Indirect(v)) case *reflect.InterfaceValue: return valueToString(v.Elem()) case *reflect.BoolValue: x := v.Get() if x { return "true", nil } else { return "false", nil } case *reflect.IntValue: return strconv.Itoa(v.Get()), nil case *reflect.Int8Value: return strconv.Itoa(int(v.Get())), nil case *reflect.Int16Value: return strconv.Itoa(int(v.Get())), nil case *reflect.Int32Value: return strconv.Itoa(int(v.Get())), nil case *reflect.Int64Value: return strconv.Itoa64(v.Get()), nil case *reflect.UintValue: return strconv.Uitoa(v.Get()), nil case *reflect.Uint8Value: return strconv.Uitoa(uint(v.Get())), nil case *reflect.Uint16Value: return strconv.Uitoa(uint(v.Get())), nil case *reflect.Uint32Value: return strconv.Uitoa(uint(v.Get())), nil case *reflect.Uint64Value: return strconv.Uitoa64(v.Get()), nil case *reflect.UintptrValue: return strconv.Uitoa64(uint64(v.Get())), nil case *reflect.FloatValue: return strconv.Ftoa(v.Get(), 'g', -1), nil case *reflect.Float32Value: return strconv.Ftoa32(v.Get(), 'g', -1), nil case *reflect.Float64Value: return strconv.Ftoa64(v.Get(), 'g', -1), nil case *reflect.StringValue: return v.Get(), nil case *reflect.SliceValue: typ := v.Type().(*reflect.SliceType) if _, ok := typ.Elem().(*reflect.Uint8Type); ok { return string(v.Interface().([]byte)), nil } } return "", os.NewError("Unsupported type") }
func cdmValuesCell(min uint, max uint) string { if min == max { return "<td>" + strconv.Uitoa(min) + "</td>" } if max == 0 { return "<td>" + strconv.Uitoa(min) + " - +∞</td>" } return "<td>" + strconv.Uitoa(min) + " - " + strconv.Uitoa(max) + "</td>" }
func (g Grid) String() string { rowStrings := make([]string, g.Height+1) rowStrings[0] = strings.Join([]string{strconv.Uitoa(g.Width), strconv.Uitoa(g.Height)}, " ") for y := uint(0); y < g.Height; y++ { row := make([]string, g.Width) for x := uint(0); x < g.Width; x++ { row[x] = strconv.Uitoa(uint(g.Get(x, y))) } rowStrings[y+1] = strings.Join(row, " ") } return strings.Join(rowStrings, "\n") }
func (char *CdmChar) Print(name string) { fmt.Println(" " + name + " :") fmt.Println(" text : \"" + char.Text + "\"") if char.Min != 0 { fmt.Println(" min : " + strconv.Uitoa(char.Min)) } if char.Max != 0 { fmt.Println(" max : " + strconv.Uitoa(char.Max)) } if char.Value != 0 { fmt.Println(" value : " + strconv.Uitoa(char.Value)) } }
func CountColor(png io.Reader) int { var pic image.Image var color image.Color pic, e := p.Decode(png) if e != nil { fmt.Printf("Error %v\n", e) return 0 } cnt := 0 colormap := make(map[string]int) for y := 0; y < pic.Bounds().Size().Y; y++ { for x := 0; x < pic.Bounds().Size().X; x++ { color = pic.At(x, y) r, g, b, _ := color.RGBA() key := "" if uint8(r) < 10 { key += "00" + strconv.Uitoa(uint(uint8(r))) } else if uint8(r) < 100 { key += "0" + strconv.Uitoa(uint(uint8(r))) } else { key += strconv.Uitoa(uint(uint8(r))) } if uint8(g) < 10 { key += "00" + strconv.Uitoa(uint(uint8(g))) } else if uint8(g) < 100 { key += "0" + strconv.Uitoa(uint(uint8(g))) } else { key += strconv.Uitoa(uint(uint8(g))) } if uint8(b) < 10 { key += "00" + strconv.Uitoa(uint(uint8(b))) } else if uint8(b) < 100 { key += "0" + strconv.Uitoa(uint(uint8(b))) } else { key += strconv.Uitoa(uint(uint8(b))) } if val, exist := colormap[key]; exist { colormap[key] = val + 1 } else { colormap[key] = 1 cnt++ } } } return cnt }
func addUintsNV(c []NameValue, label string, min uint, max uint) []NameValue { if min == 0 && max == 0 { return c } n := len(c) c = c[0 : n+1] if max == 0 { c[n] = NameValue{label, strconv.Uitoa(min) + " - ?"} } else if min == max { c[n] = NameValue{label, strconv.Uitoa(min)} } else { c[n] = NameValue{label, strconv.Uitoa(min) + " - " + strconv.Uitoa(max)} } return c }
func (p *Place) String() string { str := strconv.Uitoa(p.Id) + ") " + p.Name + " nominated by " + p.Nominator.Name + " [" + strconv.Uitoa(p.Votes) + " votes]" for _, person := range p.People { str += "\n - " + person.String() } return str }
/** * Prepare sql statement */ func (stmt *MySQLStatement) Prepare(sql string) (err os.Error) { mysql := stmt.mysql if mysql.Logging { log.Print("Prepare statement called") } // Lock mutex and defer unlock mysql.mutex.Lock() defer mysql.mutex.Unlock() // Reset error/sequence vars mysql.reset() stmt.reset() // Send command err = stmt.command(COM_STMT_PREPARE, sql) if err != nil { return } if mysql.Logging { log.Print("[" + strconv.Uitoa(uint(mysql.sequence-1)) + "] Sent prepare command to server") } // Get result packet(s) for { // Get result packet err = stmt.getPrepareResult() if err != nil { return } // Break when end of field packets reached if stmt.result.fieldsEOF { break } } stmt.prepared = true return }
// un résultat sans auteur (0) ni dateCdm (valeur 0) signifie qu'on n'a pas la réponse à la question func (store *MysqlStore) GetBlessure(db *mysql.Client, numMonstre uint, trollId int, amis []int) (blessure uint, auteurCDM int, dateCDM int64, err os.Error) { sql := "select blessure, author, date_adition from cdm where" sql += " num_monstre=" + strconv.Uitoa(numMonstre) + " and" sql += " author in (" + strconv.Itoa(trollId) for _, id := range amis { sql += "," + strconv.Itoa(id) } sql += ") order by date_adition desc limit 1" err = db.Query(sql) if err != nil { return } result, err := db.UseResult() if err != nil { return } row := result.FetchRow() db.FreeResult() if row == nil { return } blessure = fieldAsUint(row[0]) auteurCDM = fieldAsInt(row[1]) dateCDM = fieldAsInt64(row[2]) return }
/** * Reset statement */ func (stmt *MySQLStatement) Reset() (err os.Error) { mysql := stmt.mysql if mysql.Logging { log.Print("Reset statement called") } // Lock mutex and defer unlock mysql.mutex.Lock() defer mysql.mutex.Unlock() // Check statement has been prepared if !stmt.prepared { stmt.error(CR_NO_PREPARE_STMT, CR_NO_PREPARE_STMT_STR) err = os.NewError("Statement must be prepared to use this function") return } // Reset error/sequence vars mysql.reset() stmt.reset() // Send command err = stmt.command(COM_STMT_RESET, stmt.StatementId) if err != nil { return } if mysql.Logging { log.Print("[" + strconv.Uitoa(uint(mysql.sequence-1)) + "] Sent reset statement command to server") } err = stmt.getResetResult() if err != nil { return } stmt.paramsRebound = true return }
/** * Send long data packet */ func (stmt *MySQLStatement) SendLongData(num uint16, data string) (err os.Error) { mysql := stmt.mysql if mysql.Logging { log.Print("Send long data called") } // Check statement has been prepared if !stmt.prepared { stmt.error(CR_NO_PREPARE_STMT, CR_NO_PREPARE_STMT_STR) err = os.NewError("Statement must be prepared to use this function") return } // Lock mutex and defer unlock mysql.mutex.Lock() defer mysql.mutex.Unlock() // Reset error/sequence vars mysql.reset() stmt.reset() // Construct packet pkt := new(packetLongData) pkt.sequence = mysql.sequence pkt.command = COM_STMT_SEND_LONG_DATA pkt.statementId = stmt.StatementId pkt.paramNumber = num pkt.data = data err = pkt.write(mysql.writer) if err != nil { stmt.error(CR_MALFORMED_PACKET, CR_MALFORMED_PACKET_STR) return } mysql.sequence++ if mysql.Logging { log.Print("[" + strconv.Uitoa(uint(mysql.sequence-1)) + "] " + "Sent long data packet to server") } return }
func (p *Person) String() string { str := p.Name if p.CanDrive { str += " [" + strconv.Uitoa(p.NumSeats) + " seats]" } return str }
// lit un compte en base. Renvoie nil si le compte n'existe pas en base. // Sinon l'appelant est responsable de l'ouverture et de la fermeture de la connexion qu'il fournit func (store *MysqlStore) GetCompte(db *mysql.Client, trollId uint) (c *Compte, err os.Error) { if trollId == 0 { fmt.Println("GetCompte> trollId invalide") return } sql := "select statut, mdp_restreint, pv_max, pv_actuels, x, y, z, fatigue, pa, vue, prochain_tour, duree_tour, mise_a_jour" sql += " from compte where id=" + strconv.Uitoa(trollId) err = db.Query(sql) if err != nil { return } result, err := db.UseResult() if err != nil { return } defer result.Free() row := result.FetchRow() if row == nil { return } c = rowToCompte(trollId, row) return }
// returns length of response & payload & err func (b *Broker) readResponse(conn *net.TCPConn) (uint32, []byte, os.Error) { reader := bufio.NewReader(conn) length := make([]byte, 4) lenRead, err := io.ReadFull(reader, length) if err != nil { return 0, []byte{}, err } if lenRead != 4 || lenRead < 0 { return 0, []byte{}, os.NewError("invalid length of the packet length field") } expectedLength := binary.BigEndian.Uint32(length) messages := make([]byte, expectedLength) lenRead, err = io.ReadFull(reader, messages) if err != nil { return 0, []byte{}, err } if uint32(lenRead) != expectedLength { return 0, []byte{}, os.NewError(fmt.Sprintf("Fatal Error: Unexpected Length: %d expected: %d", lenRead, expectedLength)) } errorCode := binary.BigEndian.Uint16(messages[0:2]) if errorCode != 0 { return 0, []byte{}, os.NewError(strconv.Uitoa(uint(errorCode))) } return expectedLength, messages[2:], nil }
func RunWebServer(line *util.ChannelLine) { util.WebOut = line web.SetLogger(log.New(new(dummy), "", 0)) web.Config.CookieSecret = util.Settings.CookieSecret() web.Get("/Liberator/(.*)", get) web.Get("/(.*)", index) web.Post("/Liberator/(.*)", post) web.Run("0.0.0.0:" + strconv.Uitoa(util.Settings.WebPort())) }
func (cdm *CDM) Print() { fmt.Println(" CDM-------------------------------") fmt.Println(" ID : " + strconv.Uitoa(cdm.NumMonstre)) fmt.Println(" Nom : " + cdm.NomComplet) fmt.Println(" Sexe : " + cdm.Mâle.GenderString()) for name, char := range cdm.Chars { char.Print(name) } }
func addUintNV(c []NameValue, label string, v uint) []NameValue { if v == 0 { return c } n := len(c) c = c[0 : n+1] c[n] = NameValue{label, strconv.Uitoa(v)} return c }
func (v *Version) String() string { s := "" for i, p := range v.Parts { if i > 0 { s += "." } s += strconv.Uitoa(p) } return s }
func main() { flag.Parse() t := &LunchTracker{NewPoll()} rpc.Register(t) rpc.HandleHTTP() l, e := net.Listen("tcp", ":"+strconv.Uitoa(*port)) if e != nil { log.Exit("listen error:", e) } http.Serve(l, nil) }
func (p *Place) String() string { nomName := "nobody" if p.Nominator != nil { nomName = p.Nominator.Name } str := strconv.Itoa(p.Id) + ") " + p.Name + " : " + nomName + " [" + strconv.Uitoa(p.Votes) + " votes]" for _, person := range p.People { str += "\n - " + person.String() } return str }
// formatNano formats a fractional second, as nanoseconds. func formatNano(nanosec, n int) string { // User might give us bad data. Make sure it's positive and in range. // They'll get nonsense output but it will have the right format. s := strconv.Uitoa(uint(nanosec) % 1e9) // Zero pad left without fmt. if len(s) < 9 { s = "000000000"[:9-len(s)] + s } if n > 9 { n = 9 } return "." + s[:n] }
// Corresponds to the "CreateHIT" operation of the Mechanical Turk // API, using an existing "hit type". http://goo.gl/cDBRc Currently only // supports "external" questions (see "HIT" struct above). If // "maxAssignments" or "requesterAnnotation" are the zero value for // their types, they will not be included in the request. func (mt *MTurk) CreateHITOfType(hitTypeId string, q ExternalQuestion, lifetimeInSeconds uint, maxAssignments uint, requesterAnnotation string) (h *HIT, err os.Error) { params := make(map[string]string) params["HITTypeId"] = hitTypeId params["Question"], err = xmlEncode(&q) if err != nil { return } params["LifetimeInSeconds"] = strconv.Uitoa(lifetimeInSeconds) if maxAssignments != 0 { params["MaxAssignments"] = strconv.Uitoa(maxAssignments) } if requesterAnnotation != "" { params["RequesterAnnotation"] = requesterAnnotation } var response CreateHITResponse err = mt.query(params, "CreateHIT", &response) if err == nil { h = &response.HIT } return }
func CountColor(reader io.Reader) int { var count = map[string]int{} decodedPng, error := png.Decode(reader) if error == nil { var rect image.Rectangle = decodedPng.Bounds() for i := 0; i < rect.Size().X; i++ { for j := 0; j < rect.Size().Y; j++ { var pixel image.Color = decodedPng.At(i, j) var r, g, b, _ uint32 = pixel.RGBA() var key uint = (uint)((r << 16) + (g << 8) + (b)) if _, ok := count[strconv.Uitoa(key)]; ok { count[strconv.Uitoa(key)]++ } else { count[strconv.Uitoa(key)] = 1 } } } } return len(count) }
func formatReflectValue(x reflect.Value) (string, os.Error) { /* if !x.CanSet() { return "", ErrorCantSet } */ var ( errc os.Error kind = x.Kind() //vintstr string ) switch kind { // Format pointers to standard types. case reflect.String: return x.Interface().(string), nil case reflect.Int: return strconv.Itoa(x.Interface().(int)), nil case reflect.Int8: return strconv.Itoa64(int64(x.Interface().(int8))), nil case reflect.Int16: return strconv.Itoa64(int64(x.Interface().(int16))), nil case reflect.Int32: return strconv.Itoa64(int64(x.Interface().(int32))), nil case reflect.Int64: return strconv.Itoa64(x.Interface().(int64)), nil case reflect.Uint: return strconv.Uitoa(x.Interface().(uint)), nil case reflect.Uint8: return strconv.Uitoa64(uint64(x.Interface().(uint8))), nil case reflect.Uint16: return strconv.Uitoa64(uint64(x.Interface().(uint16))), nil case reflect.Uint32: return strconv.Uitoa64(uint64(x.Interface().(uint32))), nil case reflect.Uint64: return strconv.Uitoa64(x.Interface().(uint64)), nil case reflect.Float32: return strconv.Ftoa32(x.Interface().(float32), FloatFmt, FloatPrec), nil case reflect.Float64: return strconv.Ftoa64(x.Interface().(float64), FloatFmt, FloatPrec), nil case reflect.Complex64: fallthrough case reflect.Complex128: errc = ErrorUnimplemented case reflect.Bool: return strconv.Btoa(x.Interface().(bool)), nil default: errc = ErrorFieldType } return "", errc }
func (cdm *CDM) ComputeSHA1() []byte { unhash := "cdm_v3" unhash += strconv.Uitoa(cdm.NumMonstre) unhash += cdm.NomComplet unhash += cdm.Mâle.GenderString() unhash += cdm.Famille_text // parce qu'elle n'est pas toujours dans les Chars for key, value := range cdm.Chars { unhash += key + value.Text } fmt.Println(" UNHASH : " + unhash) var h hash.Hash = sha1.New() h.Write([]byte(unhash)) return h.Sum() }
// Corresponds to the "CreateHIT" operation of the Mechanical Turk // API. http://goo.gl/cDBRc Currently only supports "external" // questions (see "HIT" struct above). If "keywords", "maxAssignments", // "qualificationRequirement" or "requesterAnnotation" are the zero // value for their types, they will not be included in the request. func (mt *MTurk) CreateHIT(title, description string, question ExternalQuestion, reward Price, assignmentDurationInSeconds, lifetimeInSeconds uint, keywords string, maxAssignments uint, qualificationRequirement *QualificationRequirement, requesterAnnotation string) (h *HIT, err os.Error) { params := make(map[string]string) params["Title"] = title params["Description"] = description params["Question"], err = xmlEncode(&question) println("sending question", params["Question"]) if err != nil { return } params["Reward.1.Amount"] = reward.Amount params["Reward.1.CurrencyCode"] = reward.CurrencyCode params["AssignmentDurationInSeconds"] = strconv.Uitoa(assignmentDurationInSeconds) params["LifetimeInSeconds"] = strconv.Uitoa(lifetimeInSeconds) if keywords != "" { params["Keywords"] = keywords } if maxAssignments != 0 { params["MaxAssignments"] = strconv.Uitoa(maxAssignments) } if qualificationRequirement != nil { params["QualificationRequirement"], err = xmlEncode(qualificationRequirement) if err != nil { return } } if requesterAnnotation != "" { params["RequesterAnnotation"] = requesterAnnotation } var response CreateHITResponse err = mt.query(params, "CreateHIT", &response) if err == nil { h = &response.HIT } return }
/* DelRelationship(relationship id uint) returns any errors raised as os.Error you can pass in more than 1 id */ func (this *Neo4j) DelRelationship(id ...uint) os.Error { this.Method = "delete" url := this.URL + "/relationship/" for _, i := range id { // delete each relationship for every id passed in _, err := this.send(url+strconv.Uitoa(i), "") if err != nil { return err } } errorList := map[int]os.Error{ 404: os.NewError("Relationship not found."), } return this.NewError(errorList) }
func (client *Client) bpop(cmd string, keys []string, timeoutSecs uint) (*string, []byte, os.Error) { args := append(keys, strconv.Uitoa(timeoutSecs)) res, err := client.sendCommand(cmd, args...) if err != nil { return nil, nil, err } kv := res.([][]byte) // Check for timeout if len(kv) != 2 { return nil, nil, nil } k := string(kv[0]) v := kv[1] return &k, v, nil }
// supprime la vue de trollID puis sauvegarde des observations reçues par SOAP de MH, observées juste maintenant par trollId func (store *MysqlStore) CleanAndSaveSoapItems(db *mysql.Client, trollId uint, items []*SoapItem) (err error) { seconds := time.Seconds() sql := "delete from observation where auteur=" + strconv.Uitoa(trollId) stmt, err := db.Prepare(sql) if err != nil { return } err = stmt.Execute() if err != nil { return } stmt.FreeResult() // nécessaire ? sql = "insert into observation" sql += " (auteur, num, date, type, nom, x, y, z)" sql += " values ( ?, ?, ?, ?, ?, ?, ?, ?)" stmt, err = db.Prepare(sql) if err != nil { return } defer stmt.FreeResult() for _, i := range items { //~ fmt.Printf(" saving %+v\n", i) var t string if i.Type == "TROLL" { t = "troll" } else if i.Type == "MONSTRE" { t = "monstre" } else if i.Type == "LIEU" { t = "lieu" } else if i.Type == "TRESOR" { t = "tresor" } else { continue } err = stmt.BindParams(trollId, i.Numero, seconds, t, i.Nom, i.PositionX, i.PositionY, i.PositionN) if err != nil { return } err = stmt.Execute() } return }