// page fetches the intialURL, and follows "next" links
516607
func (p *provider) page(initialURL, token string, newObj func() interface{}, processObj func(interface{}) error) error {
	// track urls we've fetched to avoid cycles
	url := initialURL
	fetchedURLs := sets.NewString(url)
	for {
		// fetch and process
		obj := newObj()
		links, err := p.getJSON(url, token, obj)
		if err != nil {
			return err
		}
		if err := processObj(obj); err != nil {
			return err
		}

		// see if we need to page
		// https://developer.github.com/v3/#link-header
		url = links["next"]
		if len(url) == 0 {
			// no next URL, we're done paging
			break
		}
		if fetchedURLs.Has(url) {
			// break to avoid a loop
			break
		}
		// remember to avoid a loop
		fetchedURLs.Insert(url)
	}
	return nil
}
1064763
func GetPage(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")
	var col, page, total string
	if !Require(w, r, "col", &col) {
		return
	}
	if !Require(w, r, "page", &page) {
		return
	}
	if !Require(w, r, "total", &total) {
		return
	}
	totalPage, err := strconv.Atoi(total)
	if err != nil || totalPage < 1 {
		http.Error(w, fmt.Sprintf("Invalid total page number '%v'.", totalPage), 400)
		return
	}
	pageNum, err := strconv.Atoi(page)
	if err != nil || pageNum < 0 || pageNum >= totalPage {
		http.Error(w, fmt.Sprintf("Invalid page number '%v'.", page), 400)
		return
	}
	dbcol := HttpDB.Use(col)
	if dbcol == nil {
		http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
		return
	}
	docs := make(map[string]interface{})
	dbcol.ForEachDocInPage(pageNum, totalPage, func(id int, doc []byte) bool {
		var docObj map[string]interface{}
		if err := json.Unmarshal(doc, &docObj); err == nil {
			docs[strconv.Itoa(id)] = docObj
		}
		return true
	})
	resp, err := json.Marshal(docs)
	if err != nil {
		http.Error(w, fmt.Sprint(err), 500)
		return
	}
	w.Write(resp)
}
595511
func (it *LinksTo) Next(ctx context.Context) bool {
	for {
		graph.NextLogIn(it)
		it.runstats.Next += 1
		if it.nextIt.Next(ctx) {
			it.runstats.ContainsNext += 1
			it.result = it.nextIt.Result()
			return graph.NextLogOut(it, true)
		}

		// If there's an error in the 'next' iterator, we save it and we're done.
		it.err = it.nextIt.Err()
		if it.err != nil {
			return false
		}

		// Subiterator is empty, get another one
		if !it.primaryIt.Next(ctx) {
			// Possibly save error
			it.err = it.primaryIt.Err()

			// We're out of nodes in our subiterator, so we're done as well.
			return graph.NextLogOut(it, false)
		}
		it.nextIt.Close()
		it.nextIt = it.qs.QuadIterator(it.dir, it.primaryIt.Result())

		// Continue -- return the first in the next set.
	}
}
332216
func (p *Paginater) Pages() []*Page {
	if p.numPages == 0 {
		return []*Page{}
	} else if p.numPages == 1 && p.TotalPages() == 1 {
		// Only show current page.
		return []*Page{{1, true}}
	}

	// Total page number is less or equal.
	if p.TotalPages() <= p.numPages {
		pages := make([]*Page, p.TotalPages())
		for i := range pages {
			pages[i] = &Page{i + 1, i+1 == p.current}
		}
		return pages
	}

	numPages := p.numPages
	maxIdx := numPages - 1
	offsetIdx := 0
	hasMoreNext := false

	// Check more previous and next pages.
	previousNum := getMiddleIdx(p.numPages) - 1
	if previousNum > p.current-1 {
		previousNum -= previousNum - (p.current - 1)
	}
	nextNum := p.numPages - previousNum - 1
	if p.current+nextNum > p.TotalPages() {
		delta := nextNum - (p.TotalPages() - p.current)
		nextNum -= delta
		previousNum += delta
	}

	offsetVal := p.current - previousNum
	if offsetVal > 1 {
		numPages++
		maxIdx++
		offsetIdx = 1
	}

	if p.current+nextNum < p.TotalPages() {
		numPages++
		hasMoreNext = true
	}

	pages := make([]*Page, numPages)

	// There are more previous pages.
	if offsetIdx == 1 {
		pages[0] = &Page{-1, false}
	}
	// There are more next pages.
	if hasMoreNext {
		pages[len(pages)-1] = &Page{-1, false}
	}

	// Check previous pages.
	for i := 0; i < previousNum; i++ {
		pages[offsetIdx+i] = &Page{i + offsetVal, false}
	}

	pages[offsetIdx+previousNum] = &Page{p.current, true}

	// Check next pages.
	for i := 1; i <= nextNum; i++ {
		pages[offsetIdx+previousNum+i] = &Page{p.current + i, false}
	}

	return pages
}
648456
func (p *Pagination) FirstPage() bool {
	return p == nil || p.ForceFirstPage || (len(p.Next) == 0 && len(p.Previous) == 0)
}
1078497
func (p *Pages) GetURL() string {
	if p == nil || p.URL == nil {
		return ""
	}
	return *p.URL
}
717795
func (h *HTTPBin) Links(w http.ResponseWriter, r *http.Request) {
	parts := strings.Split(r.URL.Path, "/")
	if len(parts) != 3 && len(parts) != 4 {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}

	n, err := strconv.Atoi(parts[2])
	if err != nil || n < 0 || n > 256 {
		http.Error(w, "Invalid link count", http.StatusBadRequest)
		return
	}

	// Are we handling /links/<n>/<offset>? If so, render an HTML page
	if len(parts) == 4 {
		offset, err := strconv.Atoi(parts[3])
		if err != nil {
			http.Error(w, "Invalid offset", http.StatusBadRequest)
		}
		doLinksPage(w, r, n, offset)
		return
	}

	// Otherwise, redirect from /links/<n> to /links/<n>/0
	r.URL.Path = r.URL.Path + "/0"
	w.Header().Set("Location", r.URL.String())
	w.WriteHeader(http.StatusFound)
}
329011
func (into *ListOptions) GetNextPage(from interface{}) error {
	if reflect.TypeOf(from).Kind() != reflect.Slice {
		return fmt.Errorf("provided interface{} does not represent a slice")
	}

	slice := reflect.ValueOf(from)
	if slice.Len() == 0 {
		return fmt.Errorf("provided interface{} is a zero sized slice")
	}

	lastElem := slice.Index(slice.Len() - 1).Interface()
	has, _ := reflections.HasField(lastElem, "Number")
	if !has {
		return fmt.Errorf("last element of the provided slice does not have a Number attribute")
	}

	value, err := reflections.GetField(lastElem, "Number")
	if err != nil {
		return err
	}

	// We rely on travis sending us numbers representations here
	// so no real need to check for errors
	number, _ := strconv.ParseUint(value.(string), 10, 64)
	into.AfterNumber = uint(math.Max(float64(number), 0))

	return nil
}
137316
func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) {
	p := tx.page(pgid)

	// Execute function.
	fn(p, depth)

	// Recursively loop over children.
	if (p.flags & branchPageFlag) != 0 {
		for i := 0; i < int(p.count); i++ {
			elem := p.branchPageElement(uint16(i))
			tx.forEachPage(elem.pgid, depth+1, fn)
		}
	}
}
346862
func (c *Context) NextURL(defaultURL ...string) string {
	next := c.GetNextURL()
	if len(next) == 0 {
		next = c.U(defaultURL...)
	}
	return next
}
120162
func (r *Request) NextPage() *Request {
	logDeprecatedf(r.Config.Logger, &logDeprecatedNextPage,
		"Request.NextPage deprecated. Use Pagination type for configurable pagination of API operations")

	tokens := r.nextPageTokens()
	if len(tokens) == 0 {
		return nil
	}

	data := reflect.New(reflect.TypeOf(r.Data).Elem()).Interface()
	nr := New(r.Config, r.ClientInfo, r.Handlers, r.Retryer, r.Operation, awsutil.CopyOf(r.Params), data)
	for i, intok := range nr.Operation.InputTokens {
		awsutil.SetValueAtPath(nr.Params, intok, tokens[i])
	}
	return nr
}
939266
func (c *MachinesListCall) NextPageToken(nextPageToken string) *MachinesListCall {
	c.urlParams_.Set("nextPageToken", nextPageToken)
	return c
}
264846
func (p Pages) Next(cur Page) Page {
	for x, c := range p {
		if c.Eq(cur) {
			if x < len(p)-1 {
				return p[x+1]
			}
			// TODO(bep) consider return nil here to get it line with the other Nexts
			return p[0]
		}
	}
	return nil
}
1032117
func (p *Pager) URL() template.HTML {
	return template.HTML(p.paginationURLFactory(p.PageNumber()))
}
696205
func (l Links) Next(href string, args ...interface{}) Links {
	return l.Link("next", href, args...)
}
401462
func (exp *explorerUI) ParametersPage(w http.ResponseWriter, r *http.Request) {
	params := exp.ChainParams
	addrPrefix := types.AddressPrefixes(params)
	actualTicketPoolSize := int64(params.TicketPoolSize * params.TicketsPerBlock)

	exp.pageData.RLock()
	var maxBlockSize int64
	if exp.pageData.BlockchainInfo != nil {
		maxBlockSize = exp.pageData.BlockchainInfo.MaxBlockSize
	} else {
		maxBlockSize = int64(params.MaximumBlockSizes[0])
	}
	exp.pageData.RUnlock()

	type ExtendedParams struct {
		MaximumBlockSize     int64
		ActualTicketPoolSize int64
		AddressPrefix        []types.AddrPrefix
	}

	str, err := exp.templates.execTemplateToString("parameters", struct {
		*CommonPageData
		ExtendedParams
	}{
		CommonPageData: exp.commonData(r),
		ExtendedParams: ExtendedParams{
			MaximumBlockSize:     maxBlockSize,
			AddressPrefix:        addrPrefix,
			ActualTicketPoolSize: actualTicketPoolSize,
		},
	})

	if err != nil {
		log.Errorf("Template execute failure: %v", err)
		exp.StatusPage(w, defaultErrorCode, defaultErrorMessage, "", ExpStatusError)
		return
	}
	w.Header().Set("Content-Type", "text/html")
	w.WriteHeader(http.StatusOK)
	io.WriteString(w, str)
}
269689
func (n navigator) url() (string, error) {
	url := n.rootUri

	for _, link := range n.path {
		links, err := n.getLinks(url)
		if err != nil {
			return "", fmt.Errorf("Error getting links (%s, %v): %v", url, links, err)
		}

		if _, ok := links.Items[link.rel]; !ok {
			return "", LinkNotFoundError{link.rel, links.Items}
		}

		url, err = links.HrefParams(link.rel, link.params)
		if err != nil {
			return "", fmt.Errorf("Error getting url (%v, %v): %v", link.rel, link.params, err)
		}

		if url == "" {
			return "", InvalidUrlError{url}
		}

		url, err = makeAbsoluteIfNecessary(url, n.rootUri)
		if err != nil {
			return "", fmt.Errorf("Error making url absolute: %v", err)
		}
	}

	return url, nil
}