当前位置: 首页>>代码示例>>Golang>>正文


Golang strconv.Atoi函数代码示例

本文整理汇总了Golang中strconv.Atoi函数的典型用法代码示例。如果您正苦于以下问题:Golang Atoi函数的具体用法?Golang Atoi怎么用?Golang Atoi使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Atoi函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: parse_split

/**
 * parse split chars and return value
 */
func parse_split(split string) (id byte, value int, err error) {
	split = strings.ToLower(split)
	switch split {
	case "day":
		id, value = SPLIT_DAY, 1
	default:
		if strings.HasSuffix(split, "hour") {
			id = SPLIT_HOUR
			value, err = strconv.Atoi(strings.TrimSuffix(split, "hour"))
			//fix illegal hour
			if err == nil && (value < 1 || value > 23) {
				value = 1
			}
		} else if strings.HasSuffix(split, "min") {
			id = SPLIT_MIN
			value, err = strconv.Atoi(strings.TrimSuffix(split, "min"))
			//fix illegal minute
			if err == nil && (value > 60 || value < 5) {
				value = 5
			}
		} else if strings.HasSuffix(split, "m") {
			id = SPLIT_SIZE
			value, err = strconv.Atoi(strings.TrimSuffix(split, "m"))
			//fix illegal size
			if err == nil && value < 1 {
				value = 1
			}
		} else {
			err = errors.New("unknow split")
		}
	}
	return
}
开发者ID:miffa,项目名称:glog-1,代码行数:36,代码来源:glog.go

示例2: getTeamMembers

func getTeamMembers(c *Context, w http.ResponseWriter, r *http.Request) {
	params := mux.Vars(r)

	offset, err := strconv.Atoi(params["offset"])
	if err != nil {
		c.SetInvalidParam("getTeamMembers", "offset")
		return
	}

	limit, err := strconv.Atoi(params["limit"])
	if err != nil {
		c.SetInvalidParam("getTeamMembers", "limit")
		return
	}

	if c.Session.GetTeamByTeamId(c.TeamId) == nil {
		if !HasPermissionToTeamContext(c, c.TeamId, model.PERMISSION_MANAGE_SYSTEM) {
			return
		}
	}

	if result := <-Srv.Store.Team().GetMembers(c.TeamId, offset, limit); result.Err != nil {
		c.Err = result.Err
		return
	} else {
		members := result.Data.([]*model.TeamMember)
		w.Write([]byte(model.TeamMembersToJson(members)))
		return
	}
}
开发者ID:sunchips,项目名称:platform,代码行数:30,代码来源:team.go

示例3: getDBNeed

func (s *apiService) getDBNeed(w http.ResponseWriter, r *http.Request) {
	qs := r.URL.Query()

	folder := qs.Get("folder")

	page, err := strconv.Atoi(qs.Get("page"))
	if err != nil || page < 1 {
		page = 1
	}
	perpage, err := strconv.Atoi(qs.Get("perpage"))
	if err != nil || perpage < 1 {
		perpage = 1 << 16
	}

	progress, queued, rest, total := s.model.NeedFolderFiles(folder, page, perpage)

	// Convert the struct to a more loose structure, and inject the size.
	sendJSON(w, map[string]interface{}{
		"progress": s.toNeedSlice(progress),
		"queued":   s.toNeedSlice(queued),
		"rest":     s.toNeedSlice(rest),
		"total":    total,
		"page":     page,
		"perpage":  perpage,
	})
}
开发者ID:xduugu,项目名称:syncthing,代码行数:26,代码来源:gui.go

示例4: displayZoneTop

func (this *Zktop) displayZoneTop(zkzone *zk.ZkZone) {
	if this.batchMode {
		this.Ui.Output(fmt.Sprintf("%s %s", zkzone.Name(), bjtime.NowBj()))
	} else {
		this.Ui.Output(color.Green(zkzone.Name()))
	}

	header := "VER             SERVER           PORT M  OUTST            RECVD             SENT CONNS  ZNODES LAT(MIN/AVG/MAX)"
	this.Ui.Output(header)

	stats := zkzone.RunZkFourLetterCommand("stat")
	sortedHosts := make([]string, 0, len(stats))
	for hp, _ := range stats {
		sortedHosts = append(sortedHosts, hp)
	}
	sort.Strings(sortedHosts)

	for _, hostPort := range sortedHosts {
		host, port, err := net.SplitHostPort(hostPort)
		if err != nil {
			panic(err)
		}

		stat := zk.ParseStatResult(stats[hostPort])
		if stat.Mode == "" {
			if this.batchMode {
				stat.Mode = "E"
			} else {
				stat.Mode = color.Red("E")
			}
		} else if stat.Mode == "L" && !this.batchMode {
			stat.Mode = color.Blue(stat.Mode)
		}
		var sentQps, recvQps int
		if lastRecv, present := this.lastRecvs[hostPort]; present {
			r1, _ := strconv.Atoi(stat.Received)
			r0, _ := strconv.Atoi(lastRecv)
			recvQps = (r1 - r0) / int(this.refreshInterval.Seconds())

			s1, _ := strconv.Atoi(stat.Sent)
			s0, _ := strconv.Atoi(this.lastSents[hostPort])
			sentQps = (s1 - s0) / int(this.refreshInterval.Seconds())
		}
		this.Ui.Output(fmt.Sprintf("%-15s %-15s %5s %1s %6s %16s %16s %5s %7s %s",
			stat.Version,                                 // 15
			host,                                         // 15
			port,                                         // 5
			stat.Mode,                                    // 1
			stat.Outstanding,                             // 6
			fmt.Sprintf("%s/%d", stat.Received, recvQps), // 16
			fmt.Sprintf("%s/%d", stat.Sent, sentQps),     // 16
			stat.Connections,                             // 5
			stat.Znodes,                                  // 7
			stat.Latency,
		))

		this.lastRecvs[hostPort] = stat.Received
		this.lastSents[hostPort] = stat.Sent
	}
}
开发者ID:funkygao,项目名称:gafka,代码行数:60,代码来源:zktop.go

示例5: schedules

func schedules(w http.ResponseWriter, r *http.Request) {
	minUnits, err := strconv.Atoi(r.FormValue("minUnits"))
	if err != nil {
		minUnits = 0
	}

	maxUnits, err := strconv.Atoi(r.FormValue("maxUnits"))
	if err != nil {
		maxUnits = math.MaxInt32
	}

	schedules, err := generateSchedulesJSON([]byte(r.FormValue("classes")),
		minUnits, maxUnits)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	t, err := texttemplate.ParseFiles("schedules.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	t.Execute(w, schedules)
}
开发者ID:mitchellwrosen,项目名称:passx,代码行数:27,代码来源:handler.go

示例6: compareTo

func (me Version) compareTo(other Version) int {
	var (
		meTab    = strings.Split(string(me), ".")
		otherTab = strings.Split(string(other), ".")
	)

	max := len(meTab)
	if len(otherTab) > max {
		max = len(otherTab)
	}
	for i := 0; i < max; i++ {
		var meInt, otherInt int

		if len(meTab) > i {
			meInt, _ = strconv.Atoi(meTab[i])
		}
		if len(otherTab) > i {
			otherInt, _ = strconv.Atoi(otherTab[i])
		}
		if meInt > otherInt {
			return 1
		}
		if otherInt > meInt {
			return -1
		}
	}
	return 0
}
开发者ID:bb4242,项目名称:systemd-docker,代码行数:28,代码来源:version.go

示例7: timeOffsetStrToInt

// +0700 -> 07*60*60 + 30*60
func timeOffsetStrToInt(s string) (int, error) {
	if len(s) != 5 {
		return 0, errInvalidOffset
	}

	if s[0] != '+' && s[0] != '-' {
		return 0, errInvalidOffset
	}

	hStr, mStr := s[1:3], s[3:5]
	h, err := strconv.Atoi(hStr)
	if err != nil {
		return 0, err
	}

	m, err := strconv.Atoi(mStr)
	if err != nil {
		return 0, err
	}
	switch s[0] {
	case '+':
		return h*60*60 + m*60, nil
	case '-':
		return -h*60*60 - m*60, nil
	}
	return 0, errInvalidOffset
}
开发者ID:gophergala2016,项目名称:wdate,代码行数:28,代码来源:convert.go

示例8: main

func main() {
	flag.Parse()
	args := flag.Args()
	num_iters, _ := strconv.Atoi(args[0])
	num_workers, _ := strconv.Atoi(args[1])
	mutex := &sync.Mutex{}
	x := 0

	done := make(chan bool)

	for i := 0; i < num_workers; i++ {
		go func() {
			for j := 0; j < num_iters; j++ {
				mutex.Lock()
				x++
				mutex.Unlock()
			}
			done <- true
		}()
	}

	for i := 0; i < num_workers; i++ {
		<-done
	}

	fmt.Printf("%d\n", x)
}
开发者ID:scottgw,项目名称:quicksilver,代码行数:27,代码来源:main.go

示例9: user

func user(res http.ResponseWriter, req *http.Request) {
	LogRequest(req)
	params := req.URL.Query()
	if len(params["facebook_id"]) > 0 {
		facebook_id_int, _ := strconv.Atoi(params["facebook_id"][0])
		// facebook id is present
		facebook_id := int64(facebook_id_int)
		user := UserFromFB(facebook_id)
		if user.Id == 0 {
			// no such user
			NoSuchUser(res)
			return
		}
		user_json := ToJson(user)
		fmt.Fprintf(res, string(user_json))
	} else if len(params["id"]) > 0 {
		owner_id_int, _ := strconv.Atoi(params["id"][0])
		owner_id := int64(owner_id_int)
		user := UserFromID(owner_id)
		if user.Facebook_id == 0 {
			// no such user
			NoSuchUser(res)
			return
		}
		user_json := ToJson(user)
		fmt.Fprintf(res, string(user_json))
	} else {
		var errors = map[string]string{
			"error": "Missing facebook_id or id",
		}
		e_json := ToJson(errors)
		fmt.Fprintf(res, string(e_json))
	}
}
开发者ID:JustinTulloss,项目名称:yobs,代码行数:34,代码来源:yobs.go

示例10: main

func main() {
	s := bufio.NewScanner(bufio.NewReader(os.Stdin))
	s.Split(bufio.ScanWords)

	s.Scan()
	m, _ := strconv.Atoi(s.Text())
	s.Scan()
	n, _ := strconv.Atoi(s.Text())

	a := make([][]int, m)
	for i := 0; i < m; i++ {
		a[i] = make([]int, n)
		for j := 0; j < n; j++ {
			s.Scan()
			a[i][j], _ = strconv.Atoi(s.Text())
		}
	}

	max := 0

	for i := 0; i < m; i++ {
		for j := 0; j < n; j++ {
			if a[i][j] == 1 {
				v := mark(a, i, j, m, n)
				if max < v {
					max = v
				}
			}
		}
	}

	Println(max)
}
开发者ID:AlexAtNet,项目名称:galgo,代码行数:33,代码来源:connected-cell-in-a-grid.go

示例11: Load

// Load decode Lllvar field from bytes
func (l *Lllvar) Load(raw []byte, encoder, lenEncoder, length int) (read int, err error) {
	// parse length head:
	var contentLen int
	switch lenEncoder {
	case ASCII:
		read = 3
		contentLen, err = strconv.Atoi(string(raw[:read]))
		if err != nil {
			return 0, errors.New(ERR_PARSE_LENGTH_FAILED + ": " + string(raw[:3]))
		}
	case rBCD:
		fallthrough
	case BCD:
		read = 2
		contentLen, err = strconv.Atoi(string(bcdr2Ascii(raw[:read], 3)))
		if err != nil {
			return 0, errors.New(ERR_PARSE_LENGTH_FAILED + ": " + string(raw[:2]))
		}
	default:
		return 0, errors.New(ERR_INVALID_LENGTH_ENCODER)
	}
	if len(raw) < (read + contentLen) {
		return 0, errors.New(ERR_BAD_RAW)
	}
	// parse body:
	l.Value = raw[read : read+contentLen]
	read += contentLen
	if encoder != ASCII {
		return 0, errors.New(ERR_INVALID_ENCODER)
	}

	return read, nil
}
开发者ID:Ayvan,项目名称:iso8583,代码行数:34,代码来源:field.go

示例12: getValidationRules

func getValidationRules(m reflect.StructField) (map[string]interface{}, error) {
	tags := make(map[string]interface{})

	if tagType := m.Tag.Get(TypeTag); tagType != "" {
		switch tagType {
		case EmailTag:
			tags[EmailTag] = true
		case PhoneIndiaTag:
			tags[PhoneIndiaTag] = true
		}
	}

	if tagVal := m.Tag.Get(EmailTag); tagVal != "" {
		boolVal, err := strconv.ParseBool(tagVal)
		if err != nil {
			panic(err)
		}
		if boolVal {
			tags[EmailTag] = boolVal
		}
	}

	if tagVal := m.Tag.Get(RequiredTag); tagVal != "" {
		boolVal, err := strconv.ParseBool(tagVal)
		if err != nil {
			panic(err)
		}
		if boolVal {
			tags[RequiredTag] = boolVal
		}
	}

	if tagVal := m.Tag.Get(PhoneIndiaTag); tagVal != "" {
		boolVal, err := strconv.ParseBool(tagVal)
		if err != nil {
			panic(err)
		}
		if boolVal {
			tags[PhoneIndiaTag] = boolVal
		}
	}

	if tagVal := m.Tag.Get(MaxLenTag); tagVal != "" {
		maxLen, err := strconv.Atoi(tagVal)

		if err == nil {
			tags[MaxLenTag] = maxLen
		}
	}

	if tagVal := m.Tag.Get(MinLenTag); tagVal != "" {
		minLen, err := strconv.Atoi(tagVal)

		if err == nil {
			tags[MinLenTag] = minLen
		}
	}

	return tags, nil
}
开发者ID:peek4y,项目名称:gomod,代码行数:60,代码来源:tags.go

示例13: changeUser

// Takes care of dropping privileges to the desired user
func changeUser(args *DockerInitArgs) error {
	if args.user == "" {
		return nil
	}
	userent, err := utils.UserLookup(args.user)
	if err != nil {
		return fmt.Errorf("Unable to find user %v: %v", args.user, err)
	}

	uid, err := strconv.Atoi(userent.Uid)
	if err != nil {
		return fmt.Errorf("Invalid uid: %v", userent.Uid)
	}
	gid, err := strconv.Atoi(userent.Gid)
	if err != nil {
		return fmt.Errorf("Invalid gid: %v", userent.Gid)
	}

	if err := syscall.Setgid(gid); err != nil {
		return fmt.Errorf("setgid failed: %v", err)
	}
	if err := syscall.Setuid(uid); err != nil {
		return fmt.Errorf("setuid failed: %v", err)
	}

	return nil
}
开发者ID:kelsieflynn,项目名称:docker,代码行数:28,代码来源:sysinit.go

示例14: buildCriteria

func (*MessagesController) buildCriteria(ctx *gin.Context) *models.MessageCriteria {
	c := models.MessageCriteria{}
	skip, e := strconv.Atoi(ctx.DefaultQuery("skip", "0"))
	if e != nil {
		skip = 0
	}
	c.Skip = skip
	limit, e2 := strconv.Atoi(ctx.DefaultQuery("limit", "100"))
	if e2 != nil {
		limit = 10
	}

	c.Limit = limit
	c.TreeView = ctx.Query("treeView")
	c.IDMessage = ctx.Query("idMessage")
	c.InReplyOfID = ctx.Query("inReplyOfID")
	c.InReplyOfIDRoot = ctx.Query("inReplyOfIDRoot")
	c.AllIDMessage = ctx.Query("allIDMessage")
	c.Text = ctx.Query("text")
	c.Label = ctx.Query("label")
	c.NotLabel = ctx.Query("notLabel")
	c.AndLabel = ctx.Query("andLabel")
	c.Tag = ctx.Query("tag")
	c.NotTag = ctx.Query("notTag")
	c.AndTag = ctx.Query("andTag")
	c.DateMinCreation = ctx.Query("dateMinCreation")
	c.DateMaxCreation = ctx.Query("dateMaxCreation")
	c.DateMinUpdate = ctx.Query("dateMinUpdate")
	c.DateMaxUpdate = ctx.Query("dateMaxUpdate")
	c.Username = ctx.Query("username")
	return &c
}
开发者ID:vmalguy,项目名称:tat,代码行数:32,代码来源:messages.go

示例15: tileHandler

// tileHandler implements a tile renderer for use with the Google Maps JavaScript API.
// See http://code.google.com/apis/maps/documentation/javascript/maptypes.html#ImageMapTypes
func tileHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)

	x, _ := strconv.Atoi(r.FormValue("x"))
	y, _ := strconv.Atoi(r.FormValue("y"))
	z, _ := strconv.Atoi(r.FormValue("z"))

	w.Header().Set("Content-Type", "image/png")

	// Try memcache first.
	key := fmt.Sprintf("mandelbrot:%d/%d/%d", x, y, z)
	if z < maxMemcacheLevel {
		if item, err := memcache.Get(c, key); err == nil {
			w.Write(item.Value)
			return
		}
	}

	b := render(x, y, z)
	if z < maxMemcacheLevel {
		memcache.Set(c, &memcache.Item{
			Key:        key,
			Value:      b,
			Expiration: 3600, // TTL = 1 hour
		})
	}

	w.Header().Set("Content-Length", strconv.Itoa(len(b)))
	w.Write(b)
}
开发者ID:ashokgelal,项目名称:gorilla,代码行数:32,代码来源:mandelbrot.go


注:本文中的strconv.Atoi函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。