Exemple #1
0
func (o *VueObjet) ReadCsvPlante(cells []string, brut bool) (err error) {
	if len(cells) < 8 {
		err = errors.New(fmt.Sprintf("pas assez de champs (%d)", len(cells)))
		return
	}
	if o.X, err = Atoi16(cells[1]); err != nil {
		return
	}
	if o.Y, err = Atoi16(cells[2]); err != nil {
		return
	}
	o.Type = "plante"
	o.Quantité, _ = strconv.Atoui(cells[4])
	o.Label = fmt.Sprintf("%d %s", o.Quantité, cells[5])
	if o.Quantité > 1 {
		o.Label += "s de "
	} else {
		o.Label += " de "
	}
	o.Label += cells[6]
	if brut {
		o.Label += " (plante brute)"
	} else {
		o.Label += " (plante préparée)"
	}
	if o.IdType, err = strconv.Atoui(cells[8]); err != nil {
		return
	}
	return
}
Exemple #2
0
func (o *VueObjet) ReadCsvGraine(cells []string) (err error) {
	if len(cells) < 6 {
		err = errors.New(fmt.Sprintf("pas assez de champs (%d)", len(cells)))
		return
	}
	if o.X, err = Atoi16(cells[1]); err != nil {
		return
	}
	if o.Y, err = Atoi16(cells[2]); err != nil {
		return
	}
	o.Type = "graine"
	o.Quantité, _ = strconv.Atoui(cells[4])
	o.Label = fmt.Sprintf("%d %s", o.Quantité, "graine")
	if o.Quantité > 1 {
		o.Label += "s de "
	} else {
		o.Label += " de "
	}
	o.Label += cells[5]
	if o.IdType, err = strconv.Atoui(cells[6]); err != nil {
		return
	}
	return
}
Exemple #3
0
func bye(ctx *web.Context) string {
	timeStr := ctx.Request.Params["t"]
	sampleStr := ctx.Request.Params["s"]
	times, _ := strconv.Atoui(timeStr)
	if times > 1000 {
		if times > 20000 {
			return "Hi,Chamberlain"
		}
		return "您...是种马吗?\n"
	}

	if times == 0 {
		times = 100
	}

	samples, _ := strconv.Atoui(sampleStr)
	if samples > 10000 {
		return "靠,真bt,有必要这么多次吗\n"
	}

	if samples == 0 {
		samples = 1000
	}

	return fmt.Sprintf("根据%d次平均取样,在%d中挑你碰到的第%d个最好就从了吧\n", samples, times, calcRate(uint32(times), uint32(samples)))
}
// Convert a string with format hh:mm:ss to a uint with seconds
func toSeconds(str string) (sec uint, err os.Error) {
	h, err := strconv.Atoui(str[0:2])
	toSecondsCheck(err)
	m, err := strconv.Atoui(str[3:5])
	toSecondsCheck(err)
	s, err := strconv.Atoui(str[6:8])
	toSecondsCheck(err)

	return h*3600 + m*60 + s, nil
}
Exemple #5
0
// charge un fichier de diplo (il vaut mieux partir d'un graphe vide avant de charger un jeu de fichiers)
func (g *DiploGraph) ReadDiploGraph(r *bufio.Reader, ascii bool, subjectIsTroll bool) error {
	line, err := r.ReadString('\n') // TODO : utiliser r.ReadLine() plutôt que r.ReadString('\n')
	for err == nil {
		tokens := strings.SplitN(line, ";", 6)
		if len(tokens) < 5 {
			fmt.Println("Ligne invalide")
			continue
		}
		sid, _ := strconv.Atoui(tokens[0])
		eIsTroll := false
		if tokens[1] == "T" {
			eIsTroll = true
		}
		eid, _ := strconv.Atoui(tokens[2])
		v := new(DiploVertice)
		sn := getOrCreateNode(g.Guilds, sid)
		sn.IsTroll = subjectIsTroll
		var en *DiploNode
		if eIsTroll {
			en = getOrCreateNode(g.Trolls, eid)
			en.IsTroll = true
		} else {
			en = getOrCreateNode(g.Guilds, eid)
		}
		v.Start = sn
		v.End = en
		sn.Starts = AddVertice(sn.Starts, v)
		en.Ends = AddVertice(en.Ends, v)
		v.Text = strings.Trim(tokens[3], " ")
		if ascii {
			v.Text = AsciiToUTF8([]uint8(v.Text))
		}
		if tokens[4] == "ENNEMI" {
			v.Foe = true
		}
		g.Vertices[v.Key()] = v
		line, err = r.ReadString('\n')
		//~ if subjectIsTroll { // DEBUG de la diplo troll
		//~ fmt.Println(v.ColoredText())
		//~ }
	}
	if err != io.EOF {
		fmt.Println("Erreur au parsage de la diplo :")
		fmt.Println(err)
		return err
	}
	return nil
}
Exemple #6
0
func (o *VueObjet) ReadCsvElement(cells []string) (err error) {
	if len(cells) < 6 {
		err = errors.New(fmt.Sprintf("pas assez de champs (%d)", len(cells)))
		return
	}
	if o.X, err = Atoi16(cells[1]); err != nil {
		return
	}
	if o.Y, err = Atoi16(cells[2]); err != nil {
		return
	}
	o.Type = strings.ToLower(cells[4])
	o.Quantité, _ = strconv.Atoui(cells[5])

	o.Label = fmt.Sprintf("%d %s", o.Quantité, o.Type)
	// lignes suivantes provisoires
	if o.Quantité > 1 {
		if len(cells) > 6 {
			o.Label += cells[6]
		} else {
			o.Label += "s"
		}
	}
	return
}
Exemple #7
0
// Executes an FTP command.
// Sends the command to the server.
// Returns the response code, the response text from the server, and any errors.
// The response code will be zero if an error is encountered.
// The response string will be the empty string if an error is encountered.
func (c *Connection) Cmd(command string, arg string) (code uint, response string, err os.Error) {
	// Format command to be sent to the server.
	formattedCommand := command + " " + arg + CRLF

	// Send command to the server.
	_, err = c.control.Write([]byte(formattedCommand))
	if err != nil {
		return 0, "", err
	}

	// Process the response.
	reader := bufio.NewReader(c.control)
	regex := regexp.MustCompile("[0-9][0-9][0-9] ")
	for {
		ln, err := reader.ReadString('\n')
		if err != nil {
			return 0, "", err
		}

		response += ln
		if regex.MatchString(ln) {
			break
		}
	}
	code, err = strconv.Atoui(response[0:3])
	if err != nil {
		return 0, response, err
	}
	return code, response, err
}
Exemple #8
0
// Dials up a remote FTP server.
// host should be in the form of address:port e.g. myserver:21 or myserver:ftp
// Returns a pointer to a Connection
func Dial(host string) (*Connection, os.Error) {
	if host == "" {
		return nil, os.NewError("FTP Connection Error: Host can not be blank!")
	}
	if !hasPort(host) {
		return nil, os.NewError("FTP Connection Error: Host must have a port! e.g. host:21")
	}
	conn, err := net.Dial("tcp", "", host)
	if err != nil {
		return nil, err
	}
	// Upon connect, most servers respond with a welcome message.
	// The welcome message contains a status code, just like any other command.
	// TODO: Handle servers with no welcome message.
	welcomeMsg := make([]byte, 1024)
	_, err = conn.Read(welcomeMsg)
	if err != nil {
		return nil, os.NewError("Couldn't read the server's initital connection information. Error: " + err.String())
	}
	code, err := strconv.Atoui(string(welcomeMsg[0:3]))
	err = checkResponseCode(2, code)
	if err != nil {
		return nil, os.NewError("Couldn't read the server's Welcome Message. Error: " + err.String())
	}
	// This doesn't work for IPv6 addresses.
	hostParts := strings.Split(host, ":", 2)
	return &Connection{conn, hostParts[0]}, nil
}
Exemple #9
0
// TODO: should args be []interface{} ?
func (obj *GTPObject) parseLine(line string) (empty, hasId bool, id uint, commandName string, args []string) {
	line = obj.preprocessLine(line)
	empty = false
	if line == "" {
		return true, false, 0, "", nil
	}
	split := strings.Split(line, " ", -1)
	// Check if the first part is an id
	hasId = false
	//fmt.Printf("%v\n", split)
	if i, err := strconv.Atoui(split[0]); err == nil {
		// fmt.Printf("Atoui(%s) = %d\n", split[0], i)
		// fmt.Printf("err: %s\n", err)
		hasId = true
		id = i
		split = split[1:len(split)]
	}
	//fmt.Printf("%v\n", split)
	// If there is nothing after the id, the line is treated as if it were empty.
	if len(split) == 0 {
		return true, false, 0, "", nil
	}
	commandName = split[0]
	split = split[1:len(split)]
	args = make([]string, len(split))
	for index, arg := range split {
		args[index] = arg
	}

	return
}
Exemple #10
0
// cmd executes an NNTP command:
// It sends the command given by the format and arguments, and then
// reads the response line. If expectCode > 0, the status code on the
// response line must match it. 1 digit expectCodes only check the first
// digit of the status code, etc.
func (c *Conn) cmd(expectCode uint, format string, args ...interface{}) (code uint, line string, err os.Error) {
	if c.close {
		return 0, "", ProtocolError("connection closed")
	}
	if c.br != nil {
		if err := c.br.discard(); err != nil {
			return 0, "", err
		}
		c.br = nil
	}
	if _, err := fmt.Fprintf(c.conn, format+"\r\n", args); err != nil {
		return 0, "", err
	}
	line, err = c.r.ReadString('\n')
	if err != nil {
		return 0, "", err
	}
	line = strings.TrimSpace(line)
	if len(line) < 4 || line[3] != ' ' {
		return 0, "", ProtocolError("short response: " + line)
	}
	code, err = strconv.Atoui(line[0:3])
	if err != nil {
		return 0, "", ProtocolError("invalid response code: " + line)
	}
	line = line[4:]
	if 1 <= expectCode && expectCode < 10 && code/100 != expectCode ||
		10 <= expectCode && expectCode < 100 && code/10 != expectCode ||
		100 <= expectCode && expectCode < 1000 && code != expectCode {
		err = Error{code, line}
	}
	return
}
Exemple #11
0
func (f *Frequency) setField(fieldName, val string) {
	// log.Println("setField", fieldName, value)
	switch fieldName {
	case "trip_id":
		f.Trip = f.feed.Trips[val]
		break
	case "start_time":
		v, err := timeOfDayStringToSeconds(val)
		if err != nil {
			panic(err.String() + val)
		}
		f.StartTime = v
		break
	case "end_time":
		v, err := timeOfDayStringToSeconds(val)
		if err != nil {
			panic(err)
		}
		f.EndTime = v
		break
	case "headway_secs":
		v, _ := strconv.Atoui(val)
		f.HeadwaySecs = v
		break
	}
}
Exemple #12
0
func (jsonObj *JSONMap) GetUInt(name string) (i int, r bool) {
	i = 0
	r = false
	val := jsonObj.mapp.MapIndex(reflect.ValueOf(name))

	if val.IsValid() && !val.IsNil() {
		if val.Kind() == reflect.Interface {
			if v, err := strconv.Atoui(val.Elem().String()); err == nil {
				i = int(v)
				r = true
			} else if val.Elem().Kind() == reflect.Uint {
				i = int(val.Elem().Uint())
				r = true
			} else if val.Elem().Kind() == reflect.Int {
				i = int(val.Elem().Int())
				r = true
			} else if val.Elem().Kind() == reflect.Float64 || val.Elem().Kind() == reflect.Float32 {
				i = int(val.Elem().Float())
				r = true
			}
		}
	}

	return i, r
}
Exemple #13
0
// number = int_lit [ "p" int_lit ] .
//
func (p *gcParser) parseNumber() Const {
	// mantissa
	sign, val := p.parseInt()
	mant, ok := new(big.Int).SetString(sign+val, 10)
	assert(ok)

	if p.lit == "p" {
		// exponent (base 2)
		p.next()
		sign, val = p.parseInt()
		exp, err := strconv.Atoui(val)
		if err != nil {
			p.error(err)
		}
		if sign == "-" {
			denom := big.NewInt(1)
			denom.Lsh(denom, exp)
			return Const{new(big.Rat).SetFrac(mant, denom)}
		}
		if exp > 0 {
			mant.Lsh(mant, exp)
		}
		return Const{new(big.Rat).SetInt(mant)}
	}

	return Const{mant}
}
Exemple #14
0
// Parses a response for the OAuth dance and sets the appropriate fields
// in o for the request type.
func (o *OAuth) parseResponse(status int, body io.Reader, requestType int) os.Error {
	//dump, _ := http.DumpResponse(resp, true)
	//fmt.Fprintf(os.Stderr, "%s\n", dump)
	r := bodyString(body)

	if status == 401 {
		return &danceError{
			What:  r,
			Where: fmt.Sprintf("parseResponse(requestType=%d)", requestType),
		}
	}

	params := parseParams(r)

	switch requestType {
	case TempCredentialReq:
		o.requestToken = params["oauth_token"]
		o.requestSecret = params["oauth_token_secret"]
		if confirmed, ok := params["oauth_callback_confirmed"]; !ok ||
			confirmed != "true" {
			return &callbackError{o.Callback}
		}
	case TokenReq:
		o.accessToken = params["oauth_token"]
		o.accessSecret = params["oauth_token_secret"]
		o.userId, _ = strconv.Atoui(params["user_id"])
		o.userName = params["screen_name"]
	default:
		return &implementationError{
			What:  "requestType=" + strconv.Itoa(requestType),
			Where: "OAuth\xb7parseResponse()",
		}
	}
	return nil
}
Exemple #15
0
func Command(cmd string) []string {
	command := []byte(strings.ToLower(cmd))
	if what_time.Match(command) {
		current_time := time.LocalTime()
		formatted_time := current_time.Format(time.Kitchen)
		return []string{formatted_time}
	} else if who_are_you.Match(command) {
		return []string{"I am Gopher, I'm here to help."}
	} else if cmd == "gopher quit" {
		os.Exit(0)
	} else if matches := gist.FindSubmatch(command); matches != nil {
		for _, match := range matches {
			fmt.Printf("Match: %s\n", string(match))
		}

		if len(matches) > 1 {
			gist_id, err := strconv.Atoui(string(matches[1]))
			if err != nil {
				fmt.Printf("Could not parse the gist_id: %s\n", string(matches[1]))
				return []string{}
			}
			gist_file := strings.TrimSpace(string(matches[2]))
			fmt.Printf("Gist file: %s\n", gist_file)
			gist_content := GetGist(gist_id, gist_file)
			fmt.Printf("Gist Content: %s\n", gist_content)
			return gist_content
		}
		return []string{}
	} else if matches := hoogle.FindSubmatch([]byte(cmd)); matches != nil {
		return Hoogle(strings.Fields(string(matches[1])))
	} else if matches := man_page.FindSubmatch([]byte(cmd)); matches != nil {
		return Manpage(strings.Fields(string(matches[1])))
	}
	return []string{"Dunno what you are asking me. WTF dude?"}
}
Exemple #16
0
func checkTime(time *Time, test *ParseTest, t *testing.T) {
	// The time should be Thu Feb  4 21:00:57 PST 2010
	if test.yearSign*time.Year != 2010 {
		t.Errorf("%s: bad year: %d not %d", test.name, time.Year, 2010)
	}
	if time.Month != 2 {
		t.Errorf("%s: bad month: %d not %d", test.name, time.Month, 2)
	}
	if time.Day != 4 {
		t.Errorf("%s: bad day: %d not %d", test.name, time.Day, 4)
	}
	if time.Hour != 21 {
		t.Errorf("%s: bad hour: %d not %d", test.name, time.Hour, 21)
	}
	if time.Minute != 0 {
		t.Errorf("%s: bad minute: %d not %d", test.name, time.Minute, 0)
	}
	if time.Second != 57 {
		t.Errorf("%s: bad second: %d not %d", test.name, time.Second, 57)
	}
	// Nanoseconds must be checked against the precision of the input.
	nanosec, err := strconv.Atoui("012345678"[:test.fracDigits] + "000000000"[:9-test.fracDigits])
	if err != nil {
		panic(err)
	}
	if time.Nanosecond != int(nanosec) {
		t.Errorf("%s: bad nanosecond: %d not %d", test.name, time.Nanosecond, nanosec)
	}
	if test.hasTZ && time.ZoneOffset != -28800 {
		t.Errorf("%s: bad tz offset: %d not %d", test.name, time.ZoneOffset, -28800)
	}
	if test.hasWD && time.Weekday != 4 {
		t.Errorf("%s: bad weekday: %d not %d", test.name, time.Weekday, 4)
	}
}
Exemple #17
0
// Get attribute value as uint
func (this *Node) Au(namespace, name string) uint {
	if s := this.As(namespace, name); s != "" {
		n, _ := strconv.Atoui(s)
		return n
	}
	return 0
}
Exemple #18
0
func (t *Transfer) setField(fieldName, val string) {
	// log.Println("setField", fieldName, value)
	switch fieldName {
	case "from_stop_id":
		t.FromStopId = val
		break
	case "to_stop_id":
		t.ToStopId = val
		break
	case "route_long_name":
		v, _ := strconv.Atoi(val) // Should panic on error !
		t.MinTransferTime = v
		break
	case "route_type":
		v, _ := strconv.Atoui(val) // Should panic on error !
		if v == 0 {
			t.TransferType = TransferRecommended
		} else if v == 1 {
			t.TransferType = TransferDepartingWaitsForArriving
		} else if v == 2 {
			t.TransferType = TransferRequiresMinTransferTime
		} else if v == 3 {
			t.TransferType = TransferImpossible
		}
		break
	}
}
Exemple #19
0
// Get node value as uint
func (this *Node) U(namespace, name string) uint {
	if node := rec_SelectNode(this, namespace, name); node != nil && node.Value != "" {
		n, _ := strconv.Atoui(node.Value)
		return n
	}
	return 0
}
Exemple #20
0
func (t *Trip) setField(fieldName, val string) {
	// log.Println("setField", fieldName, value)
	switch fieldName {
	case "trip_id":
		t.Id = val
		break
	case "route_id":
		t.Route = t.feed.Routes[val]
		break
	case "service_id":
		t.serviceId = val
		break
	case "trip_headsign":
		t.Headsign = val
		break
	case "trip_short_name":
		t.ShortName = val
		break
	case "direction_id":
		v, _ := strconv.Atoui(val) // Should panic on error !
		if v == 0 {
			t.Direction = DirectionOut
		} else if v == 1 {
			t.Direction = DirectionIn
		}
		break
	case "block_id":
		t.BlockId = val
		break
	case "shape_id":
		t.ShapeId = val
		break
	}
}
Exemple #21
0
func (o *VuePosition) ReadCsv(cells []string) (err error) {
	if len(cells) < 11 {
		err = errors.New(fmt.Sprintf("pas assez de champs (%d)", len(cells)))
		return
	}
	o.readCsvPoint(cells)
	if o.XMin, err = Atoi16(cells[4]); err != nil {
		return
	}
	if o.XMax, err = Atoi16(cells[5]); err != nil {
		return
	}
	if o.YMin, err = Atoi16(cells[6]); err != nil {
		return
	}
	if o.YMax, err = Atoi16(cells[7]); err != nil {
		return
	}
	if o.IdBraldun, err = strconv.Atoui(cells[8]); err != nil {
		return
	}
	if o.VueNbCases, err = strconv.Atoi(cells[9]); err != nil {
		return
	}
	if o.VueBm, err = strconv.Atoi(cells[10]); err != nil {
		return
	}
	return
}
func (me *ServerConf) Load(path string) os.Error {
	bytes, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}
	list := strings.Split(string(bytes), "\n")
	for i := 0; i < len(list); i++ {
		if strings.HasPrefix(list[i], "DatabaseAddress:") {
			me.databaseAddress = parseSetting(list[i], "DatabaseAddress")
		} else if strings.HasPrefix(list[i], "CookieSecret:") {
			me.cookieSecret = parseSetting(list[i], "CookieSecret")
		} else if strings.HasPrefix(list[i], "Database:") {
			me.database = parseSetting(list[i], "Database")
		} else if strings.HasPrefix(list[i], "WebHome:") {
			me.webHome = parseSetting(list[i], "WebHome")
		} else if strings.HasPrefix(list[i], "WebRoot:") {
			me.webRoot = parseSetting(list[i], "WebRoot")
		} else if strings.HasPrefix(list[i], "WebPort:") {
			me.webPort, err = strconv.Atoui(parseSetting(list[i], "WebPort"))
			if err != nil {
				me.webPort = 8080
			}
		}
	}
	return nil
}
Exemple #23
0
func GwtChar(reg *Registry, strtable, payload []string, partype string, idxv int) (interface{}, int, os.Error) {
	v, err := strconv.Atoui(payload[idxv])
	if err != nil {
		return nil, 1, err
	}

	return uint8(v), 1, nil
}
Exemple #24
0
func (this ParamList) U(i int, defval uint) uint {
	if -1 < i && i < len(this) {
		if v, err := strconv.Atoui(this[i]); err == nil {
			return v
		}
	}
	return defval
}
Exemple #25
0
func scanAndReadUint(s *scanner.Scanner) uint {
	s.Scan()
	tok, err := strconv.Atoui(s.TokenText())
	if err != nil {
		log.Panic(err)
	}
	return tok
}
Exemple #26
0
func GetFormValueAsUint(hr *http.Request, name string) uint {
	values := hr.Form[name]
	if len(values) > 0 {
		v, _ := strconv.Atoui(values[0])
		return v
	}
	return 0
}
Exemple #27
0
func (this *Section) U(key string, defval uint) uint {
	if v, ok := this.Pairs[key]; ok {
		if n, err := strconv.Atoui(v); err == nil {
			return n
		}
	}
	return defval
}
Exemple #28
0
func (o *VueObjet) ReadCsvMunition(cells []string) (err error) {
	if len(cells) < 8 {
		err = errors.New(fmt.Sprintf("pas assez de champs (%d)", len(cells)))
		return
	}
	if o.X, err = Atoi16(cells[1]); err != nil {
		return
	}
	if o.Y, err = Atoi16(cells[2]); err != nil {
		return
	}
	o.Type = "munition"
	o.Quantité, _ = strconv.Atoui(cells[6])
	o.Label = fmt.Sprintf("%d %s", o.Quantité, cells[5])
	o.IdType, _ = strconv.Atoui(cells[7])
	return
}
Exemple #29
0
func (o *VueEchoppe) ReadCsv(cells []string) (err error) {
	if len(cells) < 9 {
		err = errors.New(fmt.Sprintf("pas assez de champs (%d)", len(cells)))
		return
	}
	o.X, _ = Atoi16(cells[1])
	o.Y, _ = Atoi16(cells[2])
	o.Z, _ = Atoi16(cells[3])
	if o.Id, err = strconv.Atoui(cells[4]); err != nil {
		return
	}
	o.Nom = cells[5]
	o.Métier = cells[6]
	if o.IdBraldun, err = strconv.Atoui(cells[8]); err != nil {
		return
	}
	return
}
Exemple #30
0
func (o *VueRoute) ReadCsv(cells []string) (err error) {
	if len(cells) < 6 {
		err = errors.New(fmt.Sprintf("pas assez de champs (%d)", len(cells)))
		return
	}
	o.readCsvPoint(cells)
	o.IdRoute, _ = strconv.Atoui(cells[4])
	o.TypeRoute = cells[5]
	return
}