Returns Quorum's search results.

 This method should be used to gather Resque worker results, or user
 supplied query params.
168761
def search
      data = Job.search(params)

      # Respond with :json, :txt (tab delimited Blast results), or GFF3.
      respond_with data.flatten!(1) do |format|
        format.json {
          render :json => Quorum::JobSerializer.as_json(data)
        }
        format.gff {
          render :text => Quorum::JobSerializer.as_gff(data)
        }
        format.txt {
          render :text => Quorum::JobSerializer.as_txt(data)
        }
      end
    end
182616
def users(self):
        
        existing_users = self.existing_users()
        existing_user_ids = [x['id'] for x in existing_users]

        # Only add search results that are not already members
        sharing = getMultiAdapter((self.my_workspace(), self.request),
                                  name='sharing')
        search_results = sharing.user_search_results()
        users = existing_users + [x for x in search_results
                                  if x['id'] not in existing_user_ids]

        users.sort(key=lambda x: safe_unicode(x["title"]))
        return users
444503
def search! query, operations = [], &block
      result = @agent_page.search query

      # FIXME on every object
      result = operations.reduce(result) do |tmp, op|
        tmp.__send__ op
      end if result

      yield result if block_given?

      result
    end
186937
def _get_query_result(query, raw_result, **kwargs):
        
        if raw_result:
            return query(**kwargs)
        if kwargs:
            return QueryResult(query, **kwargs)

        return query.result
840750
public List<CmsSearchResult> getSearchResult() {

        if ((m_cms != null)
            && (m_result == null)
            && (m_parameters.getIndex() != null)
            && (m_parameters.isIgnoreQuery()
                || CmsStringUtil.isNotEmpty(m_parameters.getQuery())
                || CmsStringUtil.isNotEmpty(m_parameters.getParsedQuery())
                || (m_parameters.getFieldQueries() != null))) {

            if (!m_parameters.isIgnoreQuery()
                && CmsStringUtil.isEmpty(m_parameters.getParsedQuery())
                && (getQueryLength() > 0)) {

                if (m_parameters.getFieldQueries() != null) {
                    // check all field queries if the length of the query is ok
                    for (CmsSearchParameters.CmsSearchFieldQuery fq : m_parameters.getFieldQueries()) {
                        for (String keyword : fq.getSearchTerms()) {
                            if (CmsStringUtil.isEmpty(keyword) || (keyword.trim().length() < getQueryLength())) {

                                m_lastException = new CmsSearchException(
                                    Messages.get().container(
                                        Messages.ERR_QUERY_TOO_SHORT_1,
                                        new Integer(getQueryLength())));

                                return null;
                            }
                        }
                    }

                } else if (m_parameters.getQuery().trim().length() < getQueryLength()) {

                    m_lastException = new CmsSearchException(
                        Messages.get().container(Messages.ERR_QUERY_TOO_SHORT_1, new Integer(getQueryLength())));

                    return null;
                }
            }

            try {

                CmsSearchResultList result = m_parameters.getSearchIndex().search(m_cms, getParameters());

                if (result.size() > 0) {

                    m_result = result;
                    m_searchResultCount = result.getHitCount();
                    m_categoriesFound = result.getCategories();

                    // re-caluclate the number of pages for this search result
                    m_pageCount = m_searchResultCount / m_parameters.getMatchesPerPage();
                    if ((m_searchResultCount % m_parameters.getMatchesPerPage()) != 0) {
                        m_pageCount++;
                    }

                    // re-calculate the URLs to browse forward and backward in the search result
                    String url = m_cms.getRequestContext().getUri() + m_parameters.toQueryString() + "&searchPage=";
                    if (m_parameters.getSearchPage() > 1) {
                        m_prevUrl = url + (m_parameters.getSearchPage() - 1);
                    }
                    if (m_parameters.getSearchPage() < m_pageCount) {
                        m_nextUrl = url + (m_parameters.getSearchPage() + 1);
                    }
                } else {
                    m_result = Collections.emptyList();
                    m_searchResultCount = 0;
                    m_categoriesFound = null;
                    m_pageCount = 0;
                    m_prevUrl = null;
                    m_nextUrl = null;
                }
            } catch (Exception exc) {

                if (LOG.isDebugEnabled()) {
                    LOG.debug(Messages.get().getBundle().key(Messages.LOG_SEARCHING_FAILED_0), exc);
                }

                m_result = null;
                m_searchResultCount = 0;
                m_pageCount = 0;

                m_lastException = exc;
            }
        }

        return m_result;
    }
222401
def query(query):
    '''
    
    '''

    # send the query to the Gaia archive
    with warnings.catch_warnings() :
        warnings.filterwarnings("ignore")

        _gaia_job = astroquery.gaia.Gaia.launch_job(query)

        # return the table of results
        return _gaia_job.get_results()
329277
def find(self, query=None, limit=None):
        
        results = []
        query = query or {}

        # TODO: When indexes are implemented, we'll need to intelligently hit one of the
        # index stores so we don't do a full table scan
        cursor = self.db.execute("select id, data from %s" % self.name)
        apply = partial(self._apply_query, query)

        for match in filter(apply, starmap(self._load, cursor.fetchall())):
            results.append(match)

            # Just return if we already reached the limit
            if limit and len(results) == limit:
                return results

        return results
107536
def get(self, key, recursive=False, sorted=False, quorum=False,
            wait=False, wait_index=None, timeout=None):
        """"""
        url = self.make_key_url(key)
        params = self.build_args({
            'recursive': (bool, recursive or None),
            'sorted': (bool, sorted or None),
            'quorum': (bool, quorum or None),
            'wait': (bool, wait or None),
            'waitIndex': (int, wait_index),
        })
        if timeout is None:
            # Try again when :exc:`TimedOut` thrown.
            while True:
                try:
                    try:
                        res = self.session.get(url, params=params)
                    except:
                        self.erred()
                except (TimedOut, ChunkedEncodingError):
                    continue
                else:
                    break
        else:
            try:
                res = self.session.get(url, params=params, timeout=timeout)
            except ChunkedEncodingError:
                raise TimedOut
            except:
                self.erred()
        return self.wrap_response(res)
538906
def search(self, search_phrase, limit=None):
        

        query, query_params = self._make_query_from_terms(search_phrase, limit=limit)

        self._parsed_query = (str(query), query_params)

        assert isinstance(query, TextClause)

        datasets = {}

        def make_result(vid=None, b_score=0, p_score=0):
            res = DatasetSearchResult()
            res.b_score = b_score
            res.p_score = p_score
            res.partitions = set()
            res.vid = vid
            return res

        if query_params:
            results = self.execute(query, **query_params)

            for result in results:
                vid, dataset_score = result

                datasets[vid] = make_result(vid, b_score=dataset_score)


        logger.debug('Extending datasets with partitions.')

        for partition in self.backend.partition_index.search(search_phrase):

            if partition.dataset_vid not in datasets:
                datasets[partition.dataset_vid] = make_result(partition.dataset_vid)

            datasets[partition.dataset_vid].p_score += partition.score
            datasets[partition.dataset_vid].partitions.add(partition)

        return list(datasets.values())
146650
def search(self, read_cache=True, ssl_verify=True, recid=None, **kwparams):
        
        parse_results = False
        of = kwparams.get('of', "")
        if of == "":
            parse_results = True
            of = "xm"
            kwparams['of'] = of
        params = kwparams
        cache_key = (json.dumps(params), parse_results)

        if cache_key not in self.cached_queries or \
                not read_cache:
            if recid:
                results = requests.get(self.server_url + '/record/' + recid,
                                       params=params, cookies=self.cookies,
                                       stream=True, verify=ssl_verify,
                                       allow_redirects=True)
                if results.history:
                    new_recid = urlparse(results.url).path.split('/')[-1]
                    raise InvenioConnectorServerError('The record has been'
                                                      'merged with recid ' +
                                                      new_recid)
            else:
                results = requests.get(self.server_url + "/search",
                                       params=params, cookies=self.cookies,
                                       stream=True, verify=ssl_verify)
            if 'youraccount/login' in results.url:
                # Current user not able to search collection
                raise InvenioConnectorAuthError(
                    "You are trying to search a restricted collection. "
                    "Please authenticate yourself.\n")
        else:
            return self.cached_queries[cache_key]

        if parse_results:
            # FIXME: we should not try to parse if results is string
            parsed_records = self._parse_results(results.raw,
                                                 self.cached_records)
            self.cached_queries[cache_key] = parsed_records
            return parsed_records
        else:
            # pylint: disable=E1103
            # The whole point of the following code is to make sure we can
            # handle two types of variable.
            try:
                res = results.content
            except AttributeError:
                res = results
            # pylint: enable=E1103

            if of == "id":
                try:
                    if isinstance(res, binary_type):
                        # Transform to list
                        res = [int(recid.strip()) for record_id in
                               res.decode('utf-8').strip("[]").split(",")
                               if record_id.strip() != ""]
                    res.reverse()
                except (ValueError, AttributeError):
                    res = []
            self.cached_queries[cache_key] = res
            return res
1242837
def search(query)
      get('/v1/search'.freeze, { q: query })
    rescue => e
      logger.warn "API v1 - Search failed #{e.backtrace}"
      { 'results' => catalog(query) }
    end
670343
def _search(self, limit, format):
        '''
        
        '''
        limit = min(limit, self.MAX_SEARCH_PER_QUERY)
        payload = {
          'q' : self.query,
          'count' : limit, #currently 50 is max per search.
          'offset': self.current_offset,
        }
        payload.update(self.CUSTOM_PARAMS)

        headers = { 'Ocp-Apim-Subscription-Key' : self.api_key }
        if not self.silent_fail:
            QueryChecker.check_web_params(payload, headers)
        response = requests.get(self.QUERY_URL, params=payload, headers=headers)
        json_results = self.get_json_results(response)
        packaged_results = [NewsResult(single_result_json) for single_result_json in json_results["value"]]
        self.current_offset += min(50, limit, len(packaged_results))
        return packaged_results
338004
def search(self, query, search_fields=None):
        

        # ### DETERMINE FIELDS TO SEARCH ###

        # Use search_fields arg if given, otherwise use search_fields
        # initially configured by the manager class.
        if search_fields:
            self._search_fields = search_fields_to_dict(search_fields)
        if not self._search_fields:
            return self.none()

        # ### BUILD LIST OF TERMS TO SEARCH FOR ###

        # Remove extra spaces, put modifiers inside quoted terms.
        terms = " ".join(query.split()).replace("+ ", "+")     \
                                       .replace('+"', '"+')    \
                                       .replace("- ", "-")     \
                                       .replace('-"', '"-')    \
                                       .split('"')
        # Strip punctuation other than modifiers from terms and create
        # terms list, first from quoted terms and then remaining words.
        terms = [("" if t[0:1] not in "+-" else t[0:1]) + t.strip(punctuation)
            for t in terms[1::2] + "".join(terms[::2]).split()]
        # Remove stop words from terms that aren't quoted or use
        # modifiers, since words with these are an explicit part of
        # the search query. If doing so ends up with an empty term
        # list, then keep the stop words.
        terms_no_stopwords = [t for t in terms if t.lower() not in
            settings.STOP_WORDS]
        get_positive_terms = lambda terms: [t.lower().strip(punctuation)
            for t in terms if t[0:1] != "-"]
        positive_terms = get_positive_terms(terms_no_stopwords)
        if positive_terms:
            terms = terms_no_stopwords
        else:
            positive_terms = get_positive_terms(terms)
        # Append positive terms (those without the negative modifier)
        # to the internal list for sorting when results are iterated.
        if not positive_terms:
            return self.none()
        else:
            self._search_terms.update(positive_terms)

        # ### BUILD QUERYSET FILTER ###

        # Create the queryset combining each set of terms.
        excluded = [reduce(iand, [~Q(**{"%s__icontains" % f: t[1:]}) for f in
            self._search_fields.keys()]) for t in terms if t[0:1] == "-"]
        required = [reduce(ior, [Q(**{"%s__icontains" % f: t[1:]}) for f in
            self._search_fields.keys()]) for t in terms if t[0:1] == "+"]
        optional = [reduce(ior, [Q(**{"%s__icontains" % f: t}) for f in
            self._search_fields.keys()]) for t in terms if t[0:1] not in "+-"]
        queryset = self
        if excluded:
            queryset = queryset.filter(reduce(iand, excluded))
        if required:
            queryset = queryset.filter(reduce(iand, required))
        # Optional terms aren't relevant to the filter if there are
        # terms that are explicitly required.
        elif optional:
            queryset = queryset.filter(reduce(ior, optional))
        return queryset.distinct()
389986
@Override
    public List<?> getResultList() {
        if (log.isDebugEnabled())
            log.debug("JPA Query: " + getJPAQuery());

        // get luence query
        String q = luceneQuery;
        if (null == q) {
            q = KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata);
        }

        if (log.isDebugEnabled())
            log.debug("Lucene Query: " + q);

        EntityMetadata m = kunderaQuery.getEntityMetadata();
        Client client = persistenceDelegeator.getClient(m);

        handlePostEvent();
        Map<String, Object> searchFilter = client.getIndexManager().search(m.getEntityClazz(), q, -1, maxResult);

        if (kunderaQuery.isAliasOnly()) {
            String[] primaryKeys = searchFilter.values().toArray(new String[] {});
            return persistenceDelegeator.find(m.getEntityClazz(), primaryKeys);
        } else {
            return persistenceDelegeator.find(m.getEntityClazz(), searchFilter);

        }

    }
50073
def search(self, search):
        
        search = search.replace('/', ' ')  # zenodo can't handle '/' in search query
        params = {'q': search}
        return self._get_records(params)
1083375
def get(self, **kwargs):
        
        results = self.search(**kwargs)
        # If there are multiple matches, prefer exact matches on api_version
        if len(results) > 1 and kwargs.get('api_version'):
            results = [
                result for result in results if result.group_version == kwargs['api_version']
            ]
        # If there are multiple matches, prefer non-List kinds
        if len(results) > 1 and not all([isinstance(x, ResourceList) for x in results]):
            results = [result for result in results if not isinstance(result, ResourceList)]
        if len(results) == 1:
            return results[0]
        elif not results:
            raise ResourceNotFoundError('No matches found for {}'.format(kwargs))
        else:
            raise ResourceNotUniqueError('Multiple matches found for {}: {}'.format(kwargs, results))
122791
def get_query(self, q, request):
        
        return Project.objects.filter(
            Q(pid__icontains=q)
            | Q(name__icontains=q)
        )