// Search sets the search matches in input
190612
func (i *ComponentInput) Search() error {
	if i.Searcher == nil {
		return ErrNoMatch{Value: i.Value, Qualifier: "no searcher defined"}
	}
	matches, err := i.Searcher.Search(false, i.Value)
	if matches != nil {
		i.SearchMatches = matches
	}
	return errors.NewAggregate(err)
}
454146
func (v *Validator) Match(field string, regex *regexp.Regexp) *ValidationResult {
	if !regex.MatchString(v.data.Get(field)) {
		return v.addMatchError(field)
	} else {
		return validationOk
	}
}
30311
func (m *RegexpMatcher) Matches(p Policy, haystack []string, needle string) (bool, error) {
	var reg *regexp.Regexp
	var err error
	for _, h := range haystack {

		// This means that the current haystack item does not contain a regular expression
		if strings.Count(h, string(p.GetStartDelimiter())) == 0 {
			// If we have a simple string match, we've got a match!
			if h == needle {
				return true, nil
			}

			// Not string match, but also no regexp, continue with next haystack item
			continue
		}

		if reg = m.get(h); reg != nil {
			if reg.MatchString(needle) {
				return true, nil
			}
			continue
		}

		reg, err = compiler.CompileRegex(h, p.GetStartDelimiter(), p.GetEndDelimiter())
		if err != nil {
			return false, errors.WithStack(err)
		}

		m.set(h, reg)
		if reg.MatchString(needle) {
			return true, nil
		}
	}
	return false, nil
}
1187458
func (c *FakeEvents) Search(scheme *runtime.Scheme, objOrRef runtime.Object) (*v1.EventList, error) {
	action := core.NewRootListAction(eventsResource, eventsKind, metav1.ListOptions{})
	if c.ns != "" {
		action = core.NewListAction(eventsResource, eventsKind, c.ns, metav1.ListOptions{})
	}
	obj, err := c.Fake.Invokes(action, &v1.EventList{})
	if obj == nil {
		return nil, err
	}

	return obj.(*v1.EventList), err
}
1285105
func (s *UserService) Search(query string, params *UserSearchParams) ([]User, *http.Response, error) {
	if params == nil {
		params = &UserSearchParams{}
	}
	params.Query = query
	users := new([]User)
	apiError := new(APIError)
	resp, err := s.sling.New().Get("search.json").QueryStruct(params).Receive(users, apiError)
	return *users, resp, relevantError(err, *apiError)
}
782875
func (n *node) search(line string) *Template {
	separator := n.separator
	return n.recursiveSearch(strings.Split(line, separator))
}
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
}
848273
func (s ImageImportSearcher) Search(precise bool, terms ...string) (ComponentMatches, []error) {
	var errs []error
	isi := &imagev1.ImageStreamImport{}
	for _, term := range terms {
		if term == "__imageimport_fail" {
			errs = append(errs, fmt.Errorf("unable to find the specified docker import: %s", term))
			continue
		}
		isi.Spec.Images = append(isi.Spec.Images, imagev1.ImageImportSpec{
			From:         corev1.ObjectReference{Kind: "DockerImage", Name: term},
			ImportPolicy: imagev1.TagImportPolicy{Insecure: s.AllowInsecure},
		})
	}
	isi.Name = "newapp"
	result, err := s.Client.Create(isi)
	if err != nil {
		if err == imageapi.ErrImageStreamImportUnsupported && s.Fallback != nil {
			return s.Fallback.Search(precise, terms...)
		}
		return nil, []error{fmt.Errorf("can't lookup images: %v", err)}
	}

	componentMatches := ComponentMatches{}
	for i, image := range result.Status.Images {
		term := result.Spec.Images[i].From.Name
		if image.Status.Status != metav1.StatusSuccess {
			klog.V(4).Infof("image import failed: %#v", image)
			switch image.Status.Reason {
			case metav1.StatusReasonInternalError:
				// try to find the cause of the internal error
				if image.Status.Details != nil && len(image.Status.Details.Causes) > 0 {
					for _, c := range image.Status.Details.Causes {
						klog.Warningf("Docker registry lookup failed: %s", c.Message)
					}
				} else {
					klog.Warningf("Docker registry lookup failed: %s", image.Status.Message)
				}
			case metav1.StatusReasonInvalid, metav1.StatusReasonUnauthorized, metav1.StatusReasonNotFound:
			default:
				errs = append(errs, fmt.Errorf("can't look up Docker image %q: %s", term, image.Status.Message))
			}
			continue
		}
		ref, err := imageapi.ParseDockerImageReference(term)
		if err != nil {
			klog.V(4).Infof("image import failed, can't parse ref %q: %v", term, err)
			continue
		}
		if len(ref.Tag) == 0 {
			ref.Tag = imageapi.DefaultImageTag
		}
		if len(ref.Registry) == 0 {
			ref.Registry = "Docker Hub"
		}

		if err := imageutil.ImageWithMetadata(image.Image); err != nil {
			errs = append(errs, err)
			continue
		}

		dockerImage, ok := image.Image.DockerImageMetadata.Object.(*dockerv10.DockerImage)
		if !ok {
			continue
		}

		match := &ComponentMatch{
			Value:       term,
			Argument:    fmt.Sprintf("--docker-image=%q", term),
			Name:        term,
			Description: descriptionFor(dockerImage, term, ref.Registry, ref.Tag),
			Score:       0,
			DockerImage: dockerImage,
			ImageTag:    ref.Tag,
			Insecure:    s.AllowInsecure,
			Meta:        map[string]string{"registry": ref.Registry, "direct-tag": "1"},
		}
		klog.V(2).Infof("Adding %s as component match for %q with score %v", match.Description, term, match.Score)
		componentMatches = append(componentMatches, match)
	}
	return componentMatches, errs
}
570039
func (m *GormIdentityRepository) Search(ctx context.Context, q string, start int, limit int) ([]Identity, int, error) {

	db := m.db.Model(&Identity{})
	db = db.Offset(start)
	db = db.Limit(limit)
	// FIXME : returning the identities.id just for the sake of consistency with the other User APIs.
	db = db.Select("count(*) over () as cnt2 ,identities.id as identity_id,identities.username,users.*")
	db = db.Joins("LEFT JOIN users ON identities.user_id = users.id")
	db = db.Where("LOWER(users.full_name) like ?", "%"+strings.ToLower(q)+"%")
	db = db.Or("users.email like ?", "%"+strings.ToLower(q)+"%")
	db = db.Or("lower(identities.username) like ?", "%"+strings.ToLower(q)+"%")
	db = db.Group("identities.id,identities.username,users.id")
	//db = db.Preload("user")

	rows, err := db.Rows()
	defer closeable.Close(ctx, rows)
	if err != nil {
		return nil, 0, err
	}

	result := []Identity{}
	value := Identity{}
	columns, err := rows.Columns()
	if err != nil {
		return nil, 0, errors.NewInternalError(ctx, err)
	}

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

	for index := range columnValues {
		columnValues[index] = &ignore
	}
	columnValues[0] = &count
	// FIXME When our User Profile endpoints start giving "user" response
	// instead of "identity" response, the identity.ID would be less relevant.

	for rows.Next() {
		columnValues[1] = &identityID
		columnValues[2] = &identityUsername
		db.ScanRows(rows, &value.User)

		if err = rows.Scan(columnValues...); err != nil {
			return nil, 0, errors.NewInternalError(ctx, err)
		}

		value.ID, err = uuid.FromString(identityID)
		if err != nil {
			return nil, 0, errors.NewInternalError(ctx, err)
		}

		value.Username = identityUsername

		result = append(result, value)
	}

	return result, count, nil
}
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)
}
1089331
func (s *Store) Search(ctx context.Context, key schema.AMKey, ttl, start, end uint32) ([]chunk.IterGen, error) {
	log.Debugf("btStore: fetching chunks for metric %s in range %d %d", key, start, end)
	_, span := tracing.NewSpan(ctx, s.tracer, "BigtableStore.Search")
	defer span.Finish()
	tags.SpanKindRPCClient.Set(span)
	tags.PeerService.Set(span, "bigtable")

	itgens := make([]chunk.IterGen, 0)
	if start > end {
		tracing.Failure(span)
		tracing.Error(span, errStartBeforeEnd)
		return itgens, errStartBeforeEnd
	}

	// limit number of inflight requests
	log.Debugf("btStore: waiting for Search slot. len=%d cap=%d", len(s.readLimiter), cap(s.readLimiter))
	pre := time.Now()
	if !s.readLimiter.Acquire(ctx) {
		return itgens, errCtxCanceled
	}
	log.Debug("btStore: acquired a Search slot")
	btblGetWaitDuration.Value(time.Since(pre))

	startMonth := start / Month_sec   // starting row has to be at, or before, requested start
	endMonth := (end - 1) / Month_sec // ending row has to include the last point we might need (end-1)

	// unfortunately in the database we only have the t0's of all chunks.
	// this means we can easily make sure to include the correct last chunk (just query for a t0 < end, the last chunk will contain the last needed data)
	// but it becomes hard to find which should be the first chunk to include. we can't just query for start <= t0 because then we will miss some data at
	// the beginning. We can't assume we know the chunkSpan so we can't just calculate the t0 >= (start - <some-predefined-number>) because ChunkSpans
	// may change over time.
	// We effectively need all chunks with a t0 > start, as well as the last chunk with a t0 <= start.
	// Bigtable doesn't allow us to fetch the most recent chunk older then start, so instead we just fetch from (start - maxChunkSpan) to enure we get the data. This
	// will usually result in more data being fetched then is needed, but that is an acceptable tradeoff.
	adjustedStart := start - uint32(s.cfg.MaxChunkSpan.Seconds())

	// chunkspans are aligned with Month_sec.  If start is > startMonth*Month_sec then the T0 of the chunk that start is in will also be >= startMonth*Month_sec.
	adjustedStart = util.Max(adjustedStart, startMonth*Month_sec)

	agg := "raw"
	var intervalHint uint32
	if key.Archive > 0 {
		agg = key.Archive.String()
		intervalHint = key.Archive.Span()
	}
	// filter the results to just the agg method (Eg raw, min_60, max_1800, etc..) and the timerange we want.
	// we fetch all columnFamilies (which are the different TTLs).  Typically there will be only one columnFamily
	// that has data, unless the TTL of the agg has changed.  In which case we want all columnFamilies anyway.
	filter := bigtable.ChainFilters(
		bigtable.ColumnFilter(agg),
		bigtable.TimestampRangeFilterMicros(bigtable.Timestamp(int64(adjustedStart)*1e6), bigtable.Timestamp(int64(end)*1e6)),
	)

	firstRow := formatRowKey(key, startMonth)
	lastRow := formatRowKey(key, endMonth+1) // bigtable.RowRange is start inclusive, end exclusive
	rr := bigtable.NewRange(firstRow, lastRow)
	var err error
	rowCount := 0
	pre = time.Now()
	queryCtx, cancel := context.WithTimeout(ctx, s.cfg.ReadTimeout)
	reqErr := s.tbl.ReadRows(queryCtx, rr, func(row bigtable.Row) bool {
		rowCount++
		chunks := 0
		var itgen chunk.IterGen
		for _, items := range row {
			for _, rItem := range items {
				chunkSizeAtLoad.Value(len(rItem.Value))
				if len(rItem.Value) < 2 {
					log.Errorf("btStore: bigtable readRows error. %s", err)
					err = errChunkTooSmall
					return false
				}
				itgen, err = chunk.NewIterGen(uint32(rItem.Timestamp/1e6), intervalHint, rItem.Value)
				if err != nil {
					log.Errorf("btStore: unable to create chunk from bytes. %s", err)
					return false
				}
				chunks++

				// This function is called serially so we don't need synchronization here
				itgens = append(itgens, itgen)
			}
		}
		btblChunksPerRow.Value(chunks)

		return true
	}, bigtable.RowFilter(filter))
	cancel()
	btblRowsPerResponse.Value(rowCount)
	btblGetExecDuration.Value(time.Since(pre))

	// free a slot in the readLimiter
	s.readLimiter.Release()

	if reqErr != nil {
		log.Errorf("btStore: bigtable readRows error. %s", reqErr)
		err = reqErr
	}
	if err != nil {
		tracing.Failure(span)
		tracing.Error(span, err)
		btblReadError.Inc()
	}
	// TODO: do we need to ensure that itgens is sorted by chunk T0?
	sort.Sort(chunk.IterGensAsc(itgens))
	return itgens, err
}
399623
func (t *redBlackTree) Search(key keytype) (valuetype, bool) {
	if t.root == nil {
		return nil, false
	}
	return t.root.search(key)
}
382441
func (c *MockStore) Search(ctx context.Context, metric schema.AMKey, ttl, start, end uint32) ([]chunk.IterGen, error) {
	var itgens, res []chunk.IterGen
	var ok bool

	if itgens, ok = c.results[metric]; !ok {
		return res, errors.New("metric not found")
	}

	for _, itgen := range itgens {
		// start is inclusive, end is exclusive
		if itgen.T0 < end && itgen.EndTs() > start && start < end {
			res = append(res, itgen)
		}
	}

	return res, nil
}
771645
func (s SeqSet) search(q uint32) (i int, ok bool) {
	min, max := 0, len(s.Set)-1
	for min < max {
		if mid := (min + max) >> 1; s.Set[mid].Less(q) {
			min = mid + 1
		} else {
			max = mid
		}
	}
	if max < 0 || s.Set[min].Less(q) {
		return len(s.Set), false // q is the new largest value
	}
	return min, s.Set[min].Contains(q)
}
250264
func NewSearchMatch(MatchType *SearchMatchType, Metadata IsMetadata) *SearchMatch {
	s := new(SearchMatch)
	s.MatchType = MatchType
	s.Metadata = Metadata
	return s
}
96759
func NewSearchResult(Matches []*SearchMatch, More bool, Start uint64) *SearchResult {
	s := new(SearchResult)
	s.Matches = Matches
	s.More = More
	s.Start = Start
	return s
}
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,
	})
}