Exemple #1
2
/**
 * 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
}
Exemple #2
0
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
	}
}
Exemple #3
0
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,
	})
}
Exemple #4
0
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
	}
}
Exemple #5
0
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)
}
Exemple #6
0
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
}
Exemple #7
0
// +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
}
Exemple #8
0
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)
}
Exemple #9
0
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))
	}
}
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)
}
Exemple #11
0
// 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
}
Exemple #12
0
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
}
Exemple #13
0
// 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
}
Exemple #14
0
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
}
Exemple #15
0
// 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)
}
Exemple #16
0
func discoveryOpts(clusterOpts map[string]string) (time.Duration, time.Duration, error) {
	var (
		heartbeat = defaultDiscoveryHeartbeat
		ttl       = defaultDiscoveryTTLFactor * defaultDiscoveryHeartbeat
	)

	if hb, ok := clusterOpts["discovery.heartbeat"]; ok {
		h, err := strconv.Atoi(hb)
		if err != nil {
			return time.Duration(0), time.Duration(0), err
		}
		heartbeat = time.Duration(h) * time.Second
		ttl = defaultDiscoveryTTLFactor * heartbeat
	}

	if tstr, ok := clusterOpts["discovery.ttl"]; ok {
		t, err := strconv.Atoi(tstr)
		if err != nil {
			return time.Duration(0), time.Duration(0), err
		}
		ttl = time.Duration(t) * time.Second

		if _, ok := clusterOpts["discovery.heartbeat"]; !ok {
			h := int(t / defaultDiscoveryTTLFactor)
			heartbeat = time.Duration(h) * time.Second
		}

		if ttl <= heartbeat {
			return time.Duration(0), time.Duration(0),
				fmt.Errorf("discovery.ttl timer must be greater than discovery.heartbeat")
		}
	}

	return heartbeat, ttl, nil
}
Exemple #17
0
// ParseHTTPVersion parses a HTTP version string.
// "HTTP/1.0" returns (1, 0, true).
func ParseHTTPVersion(vers string) (major, minor int, ok bool) {
	const Big = 1000000 // arbitrary upper bound
	switch vers {
	case "HTTP/1.1":
		return 1, 1, true
	case "HTTP/1.0":
		return 1, 0, true
	}
	if !strings.HasPrefix(vers, "HTTP/") {
		return 0, 0, false
	}
	dot := strings.Index(vers, ".")
	if dot < 0 {
		return 0, 0, false
	}
	major, err := strconv.Atoi(vers[5:dot])
	if err != nil || major < 0 || major > Big {
		return 0, 0, false
	}
	minor, err = strconv.Atoi(vers[dot+1:])
	if err != nil || minor < 0 || minor > Big {
		return 0, 0, false
	}
	return major, minor, true
}
Exemple #18
0
func main() {
	var separator string
	flag.StringVar(&separator, "s", "\n", "Element separator")
	flag.Parse()

	var first, last int
	var err error

	if len(flag.Args()) == 1 {
		first = 1
		if last, err = strconv.Atoi(flag.Args()[0]); err != nil {
			fmt.Println(err)
			return
		}
	} else if len(flag.Args()) == 2 {
		if first, err = strconv.Atoi(flag.Args()[0]); err != nil {
			fmt.Println(err)
			return
		}
		if last, err = strconv.Atoi(flag.Args()[1]); err != nil {
			fmt.Println(err)
			return
		}
	}

	for i := first; i <= last; i++ {
		fmt.Printf("%d%s", i, separator)
	}
}
Exemple #19
0
func intOp(op token.Token, x, y *BasicLit, combine bool) (*BasicLit, error) {
	out := &BasicLit{
		Kind: x.Kind,
	}
	l, err := strconv.Atoi(x.Value)
	if err != nil {
		return out, err
	}
	r, err := strconv.Atoi(y.Value)
	if err != nil {
		return out, err
	}
	var t int
	switch op {
	case token.ADD:
		t = l + r
	case token.SUB:
		t = l - r
	case token.QUO:
		// Sass division can create floats, so much treat
		// ints as floats then test for fitting inside INT
		fl, fr := float64(l), float64(r)
		if math.Remainder(fl, fr) != 0 {
			return floatOp(op, x, y, combine)
		}
		t = l / r
	case token.MUL:
		t = l * r
	default:
		panic("unsupported intOp" + op.String())
	}
	out.Value = strconv.Itoa(t)
	return out, nil
}
Exemple #20
0
func TestQuickUnion(t *testing.T) {
	file, err := os.Open("tinyUF.txt")
	if err != nil {
		t.Errorf("Error opening File")
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	scanner.Split(bufio.ScanWords)
	scanner.Scan()
	size, _ := strconv.Atoi(scanner.Text())

	uf := initQuickUnionUF(size)

	for scanner.Scan() {
		x, _ := strconv.Atoi(scanner.Text())
		scanner.Scan()
		y, _ := strconv.Atoi(scanner.Text())
		uf.union(x, y)
	}

	if conn := uf.connected(6, 1); conn != true {
		t.Errorf("Error")
	}
}
func main() {

	//With ParseFloat, this 64 tells how many bits of precision to parse.
	f, _ := strconv.ParseFloat("1.234", 64)
	fmt.Println(f)

	//For ParseInt, the 0 means infer the base from the string. 64 requires that the result fit in 64 bits.
	i, _ := strconv.ParseInt("123", 0, 64)
	fmt.Println(i)

	//ParseInt will recognize hex-formatted numbers.
	d, _ := strconv.ParseInt("0x1c8", 0, 64)
	fmt.Println(d)

	//A ParseUint is also available.
	u, _ := strconv.ParseUint("789", 0, 64)
	fmt.Println(u)

	//Atoi is a convenience function for basic base-10 int parsing.
	k, _ := strconv.Atoi("135")
	fmt.Println(k)

	//Parse functions return an error on bad input.
	_, e := strconv.Atoi("wat")
	fmt.Println(e)
}
Exemple #22
0
// 加载更多link
func discover_loadMoreLink(ctx *goku.HttpContext) goku.ActionResulter {
	page, err := strconv.Atoi(ctx.Get("page"))
	success, hasmore := false, false
	errorMsgs, html := "", ""
	if err == nil && page > 1 {
		ot := ctx.Get("o")
		if ot == "" {
			ot = "hot"
		}
		dt, _ := strconv.Atoi(ctx.Get("dt"))
		links, _ := models.LinkForHome_GetByPage(ot, dt, page, golink.PAGE_SIZE)
		if links != nil && len(links) > 0 {
			ctx.ViewData["Links"] = models.Link_ToVLink(links, ctx)
			vr := ctx.RenderPartial("loadmorelink", nil)
			vr.Render(ctx, vr.Body)
			html = vr.Body.String()
			hasmore = len(links) >= golink.PAGE_SIZE
		}
		success = true
	} else {
		errorMsgs = "参数错误"
	}
	r := map[string]interface{}{
		"success": success,
		"errors":  errorMsgs,
		"html":    html,
		"hasmore": hasmore,
	}
	return ctx.Json(r)
}
Exemple #23
0
func (this *baseController) Prepare() {
	this.options = models.GetOptions()
	this.right = "right.html"
	this.Data["options"] = this.options
	this.Data["latestblog"] = models.GetLatestBlog()
	this.Data["hotblog"] = models.GetHotBlog()
	this.Data["hidejs"] = `<!--[if lt IE 9]>
  <script src="/views/double/js/modernizr.js"></script>
  <![endif]-->`

	var (
		pagesize int
		err      error
		page     int
	)

	if page, err = strconv.Atoi(this.Ctx.Input.Param(":page")); err != nil || page < 1 {
		page = 1
	}

	if pagesize, err = strconv.Atoi(this.getOption("pagesize")); err != nil || pagesize < 1 {
		pagesize = 10
	}
	this.page = page
	this.pagesize = pagesize
}
// Split a version into parts.
// "1.2.3-beta.2" -> []int{1, 2, 3}, []interface{}{"beta", 2}
func versionParts(v string) ([]int, []interface{}) {
	if strings.HasPrefix(v, "v") || strings.HasPrefix(v, "V") {
		// Strip initial 'v' or 'V' prefix if present.
		v = v[1:]
	}
	parts := strings.SplitN(v, "+", 2)
	parts = strings.SplitN(parts[0], "-", 2)
	fields := strings.Split(parts[0], ".")

	release := make([]int, len(fields))
	for i, s := range fields {
		v, _ := strconv.Atoi(s)
		release[i] = v
	}

	var prerelease []interface{}
	if len(parts) > 1 {
		fields = strings.Split(parts[1], ".")
		prerelease = make([]interface{}, len(fields))
		for i, s := range fields {
			v, err := strconv.Atoi(s)
			if err == nil {
				prerelease[i] = v
			} else {
				prerelease[i] = s
			}
		}
	}

	return release, prerelease
}
Exemple #25
0
func onRequest(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	f := &Frame{xrange, yrange}
	{
		v, err := strconv.ParseFloat(req.FormValue("xr"), 64)
		if err == nil {
			f.xrange = v
		}
		v, err = strconv.ParseFloat(req.FormValue("yr"), 64)
		if err == nil {
			f.yrange = v
		}
	}
	i := &Image{width, height}
	{
		v, err := strconv.Atoi(req.FormValue("w"))
		if err == nil {
			i.width = v
		}
		v, err = strconv.Atoi(req.FormValue("h"))
		if err == nil {
			i.height = v
		}
	}
	run(w, f, i)
}
// ParsePage reads "page" and "page_size" from a set of parameters and
// parses them into offset and limit values.
//
// It assumes that the params will be coming from a set of query
// parameters, and that the page and page_size values will be of type
// []string, since that's the default for query parameters.  It will
// simply read the first value from each slice, ignoring extra values.
func ParsePage(params objx.Map, defaultPageSize int) (offset, limit int, err error) {
	limit = defaultPageSize

	sizeVal, sizeOk := params["page_size"]
	pageVal, pageOk := params["page"]

	if sizeOk {
		sizeSlice := sizeVal.([]string)
		sizeStr := sizeSlice[0]
		var pageSize int
		pageSize, err = strconv.Atoi(sizeStr)
		if err != nil {
			return
		}
		limit = pageSize
	}

	if pageOk {
		pageSlice := pageVal.([]string)
		pageStr := pageSlice[0]
		var page int
		page, err = strconv.Atoi(pageStr)
		if err != nil {
			return
		}
		offset = (page - 1) * limit
	}

	return
}
Exemple #27
0
func main() {
	flag.Parse()
	b, err := parseFile(fmt.Sprintf("%s/%s.txt", *dir, *month))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Total:", b.Total)
	fmt.Println("Remaining:", b.Remaining)
	mon := *month
	year, err := strconv.Atoi(mon[0:4])
	if err != nil {
		log.Fatal(err)
	}
	m, err := strconv.Atoi(mon[4:6])
	if err != nil {
		log.Fatal(err)
	}
	rpd := b.Remaining / float64(daysIn(time.Month(m), year)-time.Now().Day())
	fmt.Printf("Remaining/day: %.2f\n", rpd)
	top := map[string]float64{}
	for _, t := range b.Transactions {
		top[t.Name] += t.Cost
	}
	fmt.Println("Top costs:")
	pl := sortMapByValue(top)
	for _, p := range pl {
		fmt.Printf("\t%s: %.2f\n", p.Key, p.Value)
	}
}
Exemple #28
0
// Takes care of dropping privileges to the desired user
func changeUser(u string) {
	if u == "" {
		return
	}
	userent, err := utils.UserLookup(u)
	if err != nil {
		log.Fatalf("Unable to find user %v: %v", u, err)
	}

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

	if err := syscall.Setgid(gid); err != nil {
		log.Fatalf("setgid failed: %v", err)
	}
	if err := syscall.Setuid(uid); err != nil {
		log.Fatalf("setuid failed: %v", err)
	}
}
func (t *SimpleChaincode) init(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var err error

	if len(args) != 4 {
		return nil, errors.New("Incorrect number of arguments. Expecting 4")
	}

	// Initialize the chaincode
	A = args[0]
	Aval, err = strconv.Atoi(args[1])
	if err != nil {
		return nil, errors.New("Expecting integer value for asset holding")
	}
	B = args[2]
	Bval, err = strconv.Atoi(args[3])
	if err != nil {
		return nil, errors.New("Expecting integer value for asset holding")
	}
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}
Exemple #30
0
func CreateBlog(rw http.ResponseWriter, r *http.Request, enc encoding.Encoder, dtx *apicontext.DataContext) string {
	var b blog_model.Blog
	var err error

	b.Title = r.FormValue("title")
	b.Slug = r.FormValue("slug")
	b.Text = r.FormValue("text")
	b.PublishedDate, err = time.Parse(timeFormat, r.FormValue("publishedDate"))
	b.UserID, err = strconv.Atoi(r.FormValue("userID"))
	b.MetaTitle = r.FormValue("metaTitle")
	b.MetaDescription = r.FormValue("metaDescription")
	b.Keywords = r.FormValue("keywords")
	b.Active, err = strconv.ParseBool(r.FormValue("active"))
	categoryIDs := r.Form["categoryID"]
	for _, v := range categoryIDs {
		var bc blog_model.BlogCategory
		bc.Category.ID, err = strconv.Atoi(v)
		b.BlogCategories = append(b.BlogCategories, bc)
	}

	err = b.Create(dtx)
	if err != nil {
		apierror.GenerateError("Trouble creating blog", err, rw, r)
	}
	return encoding.Must(enc.Encode(b))
}