// SearchPages will get issues from all pages in a search
//
// JIRA API docs: https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-query-issues
775234
func (s *IssueService) SearchPages(jql string, options *SearchOptions, f func(Issue) error) error {
	if options == nil {
		options = &SearchOptions{
			StartAt:    0,
			MaxResults: 50,
		}
	}

	if options.MaxResults == 0 {
		options.MaxResults = 50
	}

	issues, resp, err := s.Search(jql, options)
	if err != nil {
		return err
	}

	for {
		for _, issue := range issues {
			err = f(issue)
			if err != nil {
				return err
			}
		}

		if resp.StartAt+resp.MaxResults >= resp.Total {
			return nil
		}

		options.StartAt += resp.MaxResults
		issues, resp, err = s.Search(jql, options)
		if err != nil {
			return err
		}
	}
}
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
}
189351
func (tracker *issueTracker) searchIssues(
	queryFormat string,
	v ...interface{},
) ([]*github.Issue, error) {

	logger := log.V(log.Debug)

	// Format the query.
	query := fmt.Sprintf(queryFormat, v...)

	// Since GH API does not allow OR queries, we need to send a concurrent request
	// for every item in tracker.config.StoryLabels label list.
	ch := make(chan *searchResult, len(tracker.config.StoryLabels))
	for _, label := range tracker.config.StoryLabels {
		go func(label string) {
			// We are only interested in issues for the given repository.
			innerQuery := fmt.Sprintf(`%v type:issue repo:%v/%v label:"%v"`,
				query, tracker.config.GitHubOwner, tracker.config.GitHubRepository, label)

			task := "Search GitHub: " + innerQuery

			if logger {
				logger.Go(task)
			}

			searchOpts := &github.SearchOptions{}
			searchOpts.Page = 1
			searchOpts.PerPage = 50

			var (
				acc      []*github.Issue
				searched int
			)

			client := tracker.newClient()

			for {
				// Fetch another page.
				var (
					result *github.IssuesSearchResult
					err    error
				)
				withRequestAllocated(func() {
					result, _, err = client.Search.Issues(innerQuery, searchOpts)
				})
				if err != nil {
					ch <- &searchResult{nil, errs.NewError(task, err)}
					return
				}

				// Check the issues for exact string match.
				for i := range result.Issues {
					acc = append(acc, &result.Issues[i])
				}

				// Check whether we have reached the end or not.
				searched += len(result.Issues)
				if searched == *result.Total {
					ch <- &searchResult{acc, nil}
					return
				}

				// Check the next page in the next iteration.
				searchOpts.Page += 1
			}
		}(label)
	}

	// Collect the results.
	var issues []*github.Issue
	for i := 0; i < cap(ch); i++ {
		res := <-ch
		if err := res.err; err != nil {
			return nil, err
		}
		issues = append(issues, res.issues...)
	}

	// Make sure there are no duplicates in the list.
	return dedupeIssues(issues), nil
}
190240
func (hs *HTTPServer) SearchTeams(c *m.ReqContext) Response {
	perPage := c.QueryInt("perpage")
	if perPage <= 0 {
		perPage = 1000
	}
	page := c.QueryInt("page")
	if page < 1 {
		page = 1
	}

	var userIdFilter int64
	if hs.Cfg.EditorsCanAdmin && c.OrgRole != m.ROLE_ADMIN {
		userIdFilter = c.SignedInUser.UserId
	}

	query := m.SearchTeamsQuery{
		OrgId:        c.OrgId,
		Query:        c.Query("query"),
		Name:         c.Query("name"),
		UserIdFilter: userIdFilter,
		Page:         page,
		Limit:        perPage,
	}

	if err := bus.Dispatch(&query); err != nil {
		return Error(500, "Failed to search Teams", err)
	}

	for _, team := range query.Result.Teams {
		team.AvatarUrl = dtos.GetGravatarUrlWithDefault(team.Email, team.Name)
	}

	query.Result.Page = page
	query.Result.PerPage = perPage

	return JSON(200, query.Result)
}
1165407
func (p *Pager) PageGroups() PagesGroup {
	if len(p.paginatedElements) == 0 {
		return paginatorEmptyPageGroups
	}

	if groups, ok := p.element().(PagesGroup); ok {
		return groups
	}

	return paginatorEmptyPageGroups
}
1164675
func (si *SolrInterface) Search(q *Query) *Search {
	return NewSearch(si.conn, q)
}
9003
func (c *Client) SearchShards(indices ...string) *SearchShardsService {
	return NewSearchShardsService(c).Index(indices...)
}
1175110
func (d *DMI) SearchByType(id int) ([]Record, error) {
	return d.GenericSearchBy("DMIType", strconv.Itoa(id))
}
495579
func (c *Client) SearchQueries(ctx context.Context, options *SearchQueryOptions) (*QuerySearch, error) {
	if options == nil || options.Query == "" {
		return nil, ErrInvalidQuery
	}

	var querySearch QuerySearch

	req, err := c.NewRequest("GET", querySearchPath, options, nil)
	if err != nil {
		return nil, err
	}

	if err := c.Do(ctx, req, &querySearch); err != nil {
		return nil, err
	}

	return &querySearch, nil
}
791814
func (i *Instagram) SearchUsers(query string) (*SearchUsers, error) {

	endpoint := APIURL + "/users/search/?ig_sig_key_version=" + SIGKEYVERSION +
		"&is_typeahead=true&query=" + query + "&rank_token=" + i.rankToken

	resp, err := i.request("GET", endpoint, nil)
	if err != nil {
		return nil, err
	}

	var object *SearchUsers
	err = json.Unmarshal(resp, &object)
	if err != nil {
		return nil, err
	}

	return object, nil
}
612532
func (firewalls *Firewalls) listPages(ctx context.Context, zone string, page int) (list []*Firewall, err error) {
	response, err := httpDo(ctx, firewalls.Options, "GET", apiURL("/zones/%s/firewall/access_rules/rules?page=%d&per_page=50", zone, page), nil)
	if err != nil {
		return
	}
	defer response.Body.Close()
	result, err := readResponse(response.Body)
	if err != nil {
		return
	}
	err = json.Unmarshal(result.Result, &list)
	if err != nil {
		return
	}
	if result.ResultInfo == nil || page >= result.ResultInfo.TotalPages {
		return
	}
	next, err := firewalls.listPages(ctx, zone, page+1)
	if err != nil {
		return
	}
	return append(list, next...), nil
}
611803
func (e SearchService) Indexes() (data map[string]string, err error) {
	err = e.client.magicRequestDecoder("GET", "search", nil, &data)
	return
}
379602
func (h *handler) fetchDocumentByPages(pages []blob.Ref) (*document, error) {
	return h.fetchDocumentFunc(pages, h.searchDocumentByPages)
}
858653
func (exp *explorerUI) MarketPage(w http.ResponseWriter, r *http.Request) {
	str, err := exp.templates.execTemplateToString("market", struct {
		*CommonPageData
		DepthMarkets []string
		StickMarkets map[string]string
		XcState      *exchanges.ExchangeBotState
	}{
		CommonPageData: exp.commonData(r),
		XcState:        exp.getExchangeState(),
	})

	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)
}
485197
func (c *Cluster) SearchQuery(q SearchQuery, opts *SearchQueryOptions) (*SearchResults, error) {
	if opts == nil {
		opts = &SearchQueryOptions{}
	}
	ctx := opts.Context
	if ctx == nil {
		ctx = context.Background()
	}

	var span opentracing.Span
	if opts.ParentSpanContext == nil {
		span = opentracing.GlobalTracer().StartSpan("ExecuteSearchQuery",
			opentracing.Tag{Key: "couchbase.service", Value: "fts"})
	} else {
		span = opentracing.GlobalTracer().StartSpan("ExecuteSearchQuery",
			opentracing.Tag{Key: "couchbase.service", Value: "fts"}, opentracing.ChildOf(opts.ParentSpanContext))
	}
	defer span.Finish()

	provider, err := c.getHTTPProvider()
	if err != nil {
		return nil, err
	}

	return c.searchQuery(ctx, span.Context(), q, opts, provider)
}
486083
func (s *Server) SearchNodes(c context.Context, n *pb.Node) (*pb.SearchResult, error) {
	s.RLock()
	defer s.RUnlock()

	var filter []string
	if n.Id != 0 {
		filter = append(filter, fmt.Sprintf("id=%d", n.Id))
	}
	if n.Meta != "" {
		filter = append(filter, fmt.Sprintf("meta~=%s", n.Meta))
	}
	if len(n.Tiers) > 0 {
		for _, v := range n.Tiers {
			filter = append(filter, fmt.Sprintf("tier~=%s", v))
		}
	}
	if len(n.Addresses) > 0 {
		for _, v := range n.Addresses {
			filter = append(filter, fmt.Sprintf("address~=%s", v))
		}
	}
	s.ctxlog.Println("filter:", filter)
	nodes, err := s.r.Nodes().Filter(filter)
	res := make([]*pb.Node, len(nodes))
	if err != nil {
		return &pb.SearchResult{Nodes: res}, err
	}
	for i, n := range nodes {
		if n == nil {
			continue
		}
		res[i] = &pb.Node{
			Id:        n.ID(),
			Active:    n.Active(),
			Capacity:  n.Capacity(),
			Tiers:     n.Tiers(),
			Addresses: n.Addresses(),
			Meta:      n.Meta(),
			Conf:      n.Config(),
		}
	}
	return &pb.SearchResult{Nodes: res}, nil
}
375180
func (r *SearchRequest) Routings(routings ...string) *SearchRequest {
	if routings != nil {
		routings := strings.Join(routings, ",")
		r.routing = &routings
	} else {
		r.routing = nil
	}
	return r
}