// https://github.com/gogs/go-gogs-client/wiki/Repositories#search-repositories
502365
func Search(c *context.APIContext) {
	opts := &models.SearchRepoOptions{
		Keyword:  path.Base(c.Query("q")),
		OwnerID:  c.QueryInt64("uid"),
		PageSize: convert.ToCorrectPageSize(c.QueryInt("limit")),
		Page:     c.QueryInt("page"),
	}

	// Check visibility.
	if c.IsLogged && opts.OwnerID > 0 {
		if c.User.ID == opts.OwnerID {
			opts.Private = true
		} else {
			u, err := models.GetUserByID(opts.OwnerID)
			if err != nil {
				c.JSON(500, map[string]interface{}{
					"ok":    false,
					"error": err.Error(),
				})
				return
			}
			if u.IsOrganization() && u.IsOwnedBy(c.User.ID) {
				opts.Private = true
			}
			// FIXME: how about collaborators?
		}
	}

	repos, count, err := models.SearchRepositoryByName(opts)
	if err != nil {
		c.JSON(500, map[string]interface{}{
			"ok":    false,
			"error": err.Error(),
		})
		return
	}

	if err = models.RepositoryList(repos).LoadAttributes(); err != nil {
		c.JSON(500, map[string]interface{}{
			"ok":    false,
			"error": err.Error(),
		})
		return
	}

	results := make([]*api.Repository, len(repos))
	for i := range repos {
		results[i] = repos[i].APIFormat(nil)
	}

	c.SetLinkHeader(int(count), opts.PageSize)
	c.JSON(200, map[string]interface{}{
		"ok":   true,
		"data": results,
	})
}
908185
func (this *Client) Search(args SearchArgs, resp interface{}) error {
	return this.InvokeByAnyMethod(http.MethodGet, "", "/search", args, resp)
}
1310565
func (db *DB) Search(query, sortBy string, offset, count int) ([]*Doc, error) {
	var docs []*Doc
	err := db.store.Select(db.meta, &docs, `where "ID" in (select "ID" from "rsc.io/rsc/scancab/database.text" where "rsc.io/rsc/scancab/database.text" match ?) order by `+sortBy+` limit ? offset ?`, query, count, offset)
	if err != nil {
		return nil, err
	}
	return docs, nil
}
979508
func (r *RepositoriesService) All(uri *Hyperlink, params M) (repos []Repository,
	result *Result) {
	if uri == nil && len(params) == 0 {
		uri = &UserRepositoriesURL
	} else if uri == nil {
		uri = &AllRepositoriesURL
	}
	url, err := uri.Expand(params)
	if err != nil {
		return nil, &Result{Err: err}
	}
	result = r.client.get(url, &repos)
	return
}
1086950
func (r *lsRun) parseSearchRequests(ctx context.Context, args []string) ([]*pb.SearchBuildsRequest, error) {
	baseReq, err := r.parseBaseRequest(ctx)
	if err != nil {
		return nil, err
	}

	if len(args) == 0 {
		return []*pb.SearchBuildsRequest{baseReq}, nil
	}

	ret := make([]*pb.SearchBuildsRequest, len(args))
	for i, path := range args {
		ret[i] = proto.Clone(baseReq).(*pb.SearchBuildsRequest)
		var err error
		if ret[i].Predicate.Builder, err = r.parsePath(path); err != nil {
			return nil, fmt.Errorf("invalid path %q: %s", path, err)
		}
	}
	return ret, nil
}
1133999
func (r *SearchRequest) FetchSource(fetchSource bool) *SearchRequest {
	r.searchSource = r.searchSource.FetchSource(fetchSource)
	return r
}
611049
func (cli *Client) ImageSearch(ctx context.Context, term string, options types.ImageSearchOptions) ([]registry.SearchResult, error) {
	var results []registry.SearchResult
	query := url.Values{}
	query.Set("term", term)
	query.Set("limit", fmt.Sprintf("%d", options.Limit))

	if options.Filters.Len() > 0 {
		filterJSON, err := filters.ToJSON(options.Filters)
		if err != nil {
			return results, err
		}
		query.Set("filters", filterJSON)
	}

	resp, err := cli.tryImageSearch(ctx, query, options.RegistryAuth)
	defer ensureReaderClosed(resp)
	if errdefs.IsUnauthorized(err) && options.PrivilegeFunc != nil {
		newAuthHeader, privilegeErr := options.PrivilegeFunc()
		if privilegeErr != nil {
			return results, privilegeErr
		}
		resp, err = cli.tryImageSearch(ctx, query, newAuthHeader)
	}
	if err != nil {
		return results, err
	}

	err = json.NewDecoder(resp.body).Decode(&results)
	return results, err
}
711027
func (IS *InvertedSuffix) Search(Query []byte) (int, int) {
	low := 0
	high := len(IS.WordIndex)
	n := len(Query)
	for a := 0; a < n; a++ {
		c := Query[a]
		oldlow := low
		oldhigh := high
		i := low
		j := high
		// Raise the lower-bound
		for i < j {
			h := (i + j) >> 1
			Index := IS.WordIndex[h]
			Word := IS.Words[Index]
			Length := len(Word)
			d := IS.SuffixIndex[h] + a
			if d >= Length {
				i = h + 1
			} else {
				e := Word[d]
				if e < c {
					i = h + 1
				} else {
					j = h
					if e > c {
						high = h
					}
				}
			}
		}
		low = i
		if low == high {
			break
		}
		j = high
		if low == oldlow && high == oldhigh {
			// nothing to do here: Word[IS.SuffixIndex[(i + j) >> 1] + a] == c
			continue
		}
		// Lower the upper-bound
		for i < j {
			h := (i + j) >> 1
			Index := IS.WordIndex[h]
			Word := IS.Words[Index]
			Length := len(Word)
			d := IS.SuffixIndex[h] + a
			if d >= Length {
				i = h + 1
			} else {
				e := Word[d]
				if e <= c {
					i = h + 1
					if e < c {
						low = i
					}
				} else {
					j = h
				}
			}
		}
		high = j
		if low == high {
			break
		}
	}
	return low, high
}
551606
func (s *DefaultService) Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) {
	// TODO Use ctx when searching for repositories
	if err := validateNoScheme(term); err != nil {
		return nil, err
	}

	indexName, remoteName := splitReposSearchTerm(term)

	// Search is a long-running operation, just lock s.config to avoid block others.
	s.mu.Lock()
	index, err := newIndexInfo(s.config, indexName)
	s.mu.Unlock()

	if err != nil {
		return nil, err
	}

	// *TODO: Search multiple indexes.
	endpoint, err := NewV1Endpoint(index, userAgent, http.Header(headers))
	if err != nil {
		return nil, err
	}

	var client *http.Client
	if authConfig != nil && authConfig.IdentityToken != "" && authConfig.Username != "" {
		creds := NewStaticCredentialStore(authConfig)
		scopes := []auth.Scope{
			auth.RegistryScope{
				Name:    "catalog",
				Actions: []string{"search"},
			},
		}

		modifiers := Headers(userAgent, nil)
		v2Client, foundV2, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes)
		if err != nil {
			if fErr, ok := err.(fallbackError); ok {
				logrus.Errorf("Cannot use identity token for search, v2 auth not supported: %v", fErr.err)
			} else {
				return nil, err
			}
		} else if foundV2 {
			// Copy non transport http client features
			v2Client.Timeout = endpoint.client.Timeout
			v2Client.CheckRedirect = endpoint.client.CheckRedirect
			v2Client.Jar = endpoint.client.Jar

			logrus.Debugf("using v2 client for search to %s", endpoint.URL)
			client = v2Client
		}
	}

	if client == nil {
		client = endpoint.client
		if err := authorizeClient(client, authConfig, endpoint); err != nil {
			return nil, err
		}
	}

	r := newSession(client, authConfig, endpoint)

	if index.Official {
		localName := remoteName
		if strings.HasPrefix(localName, "library/") {
			// If pull "library/foo", it's stored locally under "foo"
			localName = strings.SplitN(localName, "/", 2)[1]
		}

		return r.SearchRepositories(localName, limit)
	}
	return r.SearchRepositories(remoteName, limit)
}
1338374
func (a *BooleanArray) search(v int64) int {
	// Define: f(x) → a.Timestamps[x] < v
	// Define: f(-1) == true, f(n) == false
	// Invariant: f(lo-1) == true, f(hi) == false
	lo := 0
	hi := a.Len()
	for lo < hi {
		mid := int(uint(lo+hi) >> 1)
		if a.Timestamps[mid] < v {
			lo = mid + 1 // preserves f(lo-1) == true
		} else {
			hi = mid // preserves f(hi) == false
		}
	}

	// lo == hi
	return lo
}
1035284
func (c *Client) ArtifactSearch(opts *ArtifactSearchOpts) ([]*ArtifactVersion, error) {
	log.Printf("[INFO] searching artifacts: %#v", opts)

	params := make(map[string]string)
	if opts.Version != "" {
		params["version"] = opts.Version
	}
	if opts.Build != "" {
		params["build"] = opts.Build
	}

	i := 1
	for k, v := range opts.Metadata {
		prefix := fmt.Sprintf("metadata.%d.", i)
		params[prefix+"key"] = k
		if v != MetadataAnyValue {
			params[prefix+"value"] = v
		}

		i++
	}

	endpoint := fmt.Sprintf("/api/v1/artifacts/%s/%s/%s/search",
		opts.User, opts.Name, opts.Type)
	request, err := c.Request("GET", endpoint, &RequestOptions{
		Params: params,
	})
	if err != nil {
		return nil, err
	}

	response, err := checkResp(c.HTTPClient.Do(request))
	if err != nil {
		return nil, err
	}

	var w artifactSearchWrapper
	if err := decodeJSON(response, &w); err != nil {
		return nil, err
	}

	return w.Versions, nil
}
808711
func SearchBy(query string, by By) ([]Pkg, error) {
	return searchBy(query, by.String())
}
1038092
func (r *GormSearchRepository) search(ctx context.Context, sqlSearchQueryParameter string, workItemTypes []uuid.UUID, start *int, limit *int, spaceID *string) ([]workitem.WorkItemStorage, int, error) {
	db := r.db.Model(workitem.WorkItemStorage{}).Where("tsv @@ query")
	if start != nil {
		if *start < 0 {
			return nil, 0, errors.NewBadParameterError("start", *start)
		}
		db = db.Offset(*start)
	}
	if limit != nil {
		if *limit <= 0 {
			return nil, 0, errors.NewBadParameterError("limit", *limit)
		}
		db = db.Limit(*limit)
	}
	if len(workItemTypes) > 0 {
		// restrict to all given types and their subtypes
		query := fmt.Sprintf("%[1]s.type in ("+
			"select distinct subtype.id from %[2]s subtype "+
			"join %[2]s supertype on subtype.path <@ supertype.path "+
			"where supertype.id in (?))", workitem.WorkItemStorage{}.TableName(), workitem.WorkItemType{}.TableName())
		db = db.Where(query, workItemTypes)
	}

	db = db.Select("count(*) over () as cnt2 , *").Order(workitem.Column(workitem.WorkItemStorage{}.TableName(), "execution_order") + " desc")
	db = db.Joins(", to_tsquery('english', ?) as query, ts_rank(tsv, query) as rank", sqlSearchQueryParameter)
	if spaceID != nil {
		db = db.Where("space_id=?", *spaceID)
	}
	db = db.Order(fmt.Sprintf("rank desc,%s.updated_at desc", workitem.WorkItemStorage{}.TableName()))

	rows, err := db.Rows()
	defer closeable.Close(ctx, rows)
	if err != nil {
		return nil, 0, errs.Wrapf(err, "failed to execute search query")
	}

	result := []workitem.WorkItemStorage{}
	value := workitem.WorkItemStorage{}
	columns, err := rows.Columns()
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err": err,
		}, "failed to get column names")
		return nil, 0, errors.NewInternalError(ctx, errs.Wrap(err, "failed to get column names"))
	}

	// need to set up a result for Scan() in order to extract total count.
	var count int
	var ignore interface{}
	columnValues := make([]interface{}, len(columns))

	for index := range columnValues {
		columnValues[index] = &ignore
	}
	columnValues[0] = &count
	first := true

	for rows.Next() {
		db.ScanRows(rows, &value)
		if first {
			first = false
			if err = rows.Scan(columnValues...); err != nil {
				log.Error(ctx, map[string]interface{}{
					"err": err,
				}, "failed to scan rows")
				return nil, 0, errors.NewInternalError(ctx, errs.Wrap(err, "failed to scan rows"))
			}
		}
		result = append(result, value)

	}
	if first {
		// means 0 rows were returned from the first query,
		count = 0
	}
	log.Info(ctx, nil, "Search results: %d matches", count)
	return result, count, nil
	//*/
}
316757
func (c *Client) UidSearch(criteria *imap.SearchCriteria) (uids []uint32, err error) {
	return c.search(true, criteria)
}
209685
func (s MultiWeightedSearcher) Search(precise bool, terms ...string) (ComponentMatches, []error) {
	componentMatches := ComponentMatches{}
	var errs []error
	for _, searcher := range s {
		matches, err := searcher.Search(precise, terms...)
		if len(err) > 0 {
			errs = append(errs, err...)
			continue
		}
		for _, match := range matches {
			match.Score += searcher.Weight
			componentMatches = append(componentMatches, match)
		}
	}
	sort.Sort(ScoredComponentMatches(componentMatches))
	return componentMatches, errs
}
674573
func (c *Client) Search(query string, all bool) ([]*Printer, error) {
	var mr multipartRequest
	mr.init()
	if query != "" {
		mr.WriteField("q", query)
	}
	if all {
		mr.WriteField("connection_status", "ALL")
	}
	var resp printersResponse
	err := jsonRPC(&c.auth, "POST", cloudprintURL+"/search", &mr, &resp)
	if err != nil {
		return nil, fmt.Errorf("Search: %v", err)
	}
	var list []*Printer
	for _, desc := range resp.Printers {
		list = append(list, desc.Printer())
	}
	return list, nil
}
462373
func (c *Client) SearchSubtitles(params *[]interface{}) (Subtitles, error) {
	res := struct {
		Data Subtitles `xmlrpc:"data"`
	}{}

	if err := c.Call("SearchSubtitles", *params, &res); err != nil {
		if strings.Contains(err.Error(), "type mismatch") {
			return nil, err
		}
	}
	return res.Data, nil
}