Full text, in-book search.
491033
def in_book_search(request):
    """"""
    results = {}

    args = request.matchdict
    ident_hash = args['ident_hash']

    args['search_term'] = request.params.get('q', '')
    query_type = request.params.get('query_type', '')
    combiner = ''
    if query_type:
        if query_type.lower() == 'or':
            combiner = '_or'

    id, version = split_ident_hash(ident_hash)
    args['uuid'] = id
    args['version'] = version

    with db_connect() as db_connection:
        with db_connection.cursor() as cursor:
            cursor.execute(SQL['get-collated-state'], args)
            res = cursor.fetchall()
            if res and res[0][0]:
                statement = SQL['get-in-collated-book-search']
            else:
                statement = SQL['get-in-book-search']
            cursor.execute(statement.format(combiner=combiner), args)
            res = cursor.fetchall()

            results['results'] = {'query': [],
                                  'total': len(res),
                                  'items': []}
            results['results']['query'] = {
                'id': ident_hash,
                'search_term': args['search_term'],
            }
            for uuid, version, title, snippet, matches, rank in res:
                results['results']['items'].append({
                    'rank': '{}'.format(rank),
                    'id': '{}@{}'.format(uuid, version),
                    'title': '{}'.format(title),
                    'snippet': '{}'.format(snippet),
                    'matches': '{}'.format(matches),
                })

    resp = request.response
    resp.status = '200 OK'
    resp.content_type = 'application/json'
    resp.body = json.dumps(results)

    return resp
1261895
def find(self, text):
        """"""
        for key, value in self:
            if (text in key) or (text in value):
                print(key, value)
1159849
def __search_book_html(self, anywords, page):
        
        _params = {
            'dt': 'ALL',
            'cl': 'ALL',
            'dp': '20',
            'sf': 'M_PUB_YEAR',
            'ob': 'DESC',
            'sm': 'table',
            'dept': 'ALL',
            'ecx': '0',
            'anywords': '',  # not anywords..
            'page': 1
        }

        _headers = {
            'Host': 'lib.wyu.edu.cn',
            'Referer': 'http://lib.wyu.edu.cn/opac/search.aspx',
            'Accept-Language': ':zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4'
        }

        # url要对中文编码..
        _params['anywords'] = anywords.decode('utf-8').encode('gbk')
        _params['page'] = page
        r = requests.get(url=WyuLibrary.url_search, headers=_headers, params=_params, timeout=self._timeout)
        # _.d(r.content.decode(_.get_charset(r.content)))
        return r.content.decode(_.get_charset(r.content))
1282000
def find(im_source, im_search):
    '''
    
    '''
    r = find_all(im_source, im_search, maxcnt=1)
    return r[0] if r else None
355541
def in_book_search_highlighted_results(request):
    """"""
    results = {}

    args = request.matchdict
    ident_hash = args['ident_hash']

    page_ident_hash = args['page_ident_hash']
    try:
        page_uuid, _ = split_ident_hash(page_ident_hash)
    except IdentHashShortId as e:
        page_uuid = get_uuid(e.id)
    except IdentHashMissingVersion as e:
        page_uuid = e.id
    args['page_uuid'] = page_uuid

    args['search_term'] = request.params.get('q', '')

    query_type = request.params.get('query_type', '')
    combiner = ''
    if query_type:
        if query_type.lower() == 'or':
            combiner = '_or'

    # Get version from URL params
    id, version = split_ident_hash(ident_hash)
    args['uuid'] = id
    args['version'] = version

    with db_connect() as db_connection:
        with db_connection.cursor() as cursor:
            cursor.execute(SQL['get-collated-state'], args)
            res = cursor.fetchall()
            if res and res[0][0]:
                statement = SQL['get-in-collated-book-search-full-page']
            else:
                statement = SQL['get-in-book-search-full-page']
            cursor.execute(statement.format(combiner=combiner), args)
            res = cursor.fetchall()

            results['results'] = {'query': [],
                                  'total': len(res),
                                  'items': []}
            results['results']['query'] = {
                'search_term': args['search_term'],
                'collection_id': ident_hash,
            }
            for uuid, version, title, headline, rank in res:
                results['results']['items'].append({
                    'rank': '{}'.format(rank),
                    'id': '{}'.format(page_ident_hash),
                    'title': '{}'.format(title),
                    'html': '{}'.format(headline),
                })

    resp = request.response
    resp.status = '200 OK'
    resp.content_type = 'application/json'
    resp.body = json.dumps(results)

    return resp
338053
def search(self, event):
        """"""

        try:
            data, schema, user, client = self._get_args(event)
        except AttributeError:
            return

        # object_filter['$text'] = {'$search': str(data['search'])}
        if data.get('fulltext', False) is True:
            object_filter = {
                'name': {
                    '$regex': str(data['search']),
                    '$options': '$i'
                }
            }
        else:
            if isinstance(data['search'], dict):
                object_filter = data['search']
            else:
                object_filter = {}

        if 'fields' in data:
            fields = data['fields']
        else:
            fields = []

        skip = data.get('skip', 0)
        limit = data.get('limit', 0)
        sort = data.get('sort', None)
        # page = data.get('page', 0)
        # count = data.get('count', 0)
        #
        # if page > 0 and count > 0:
        #     skip = page * count
        #     limit = count

        if 'subscribe' in data:
            self.log('Subscription:', data['subscribe'], lvl=verbose)
            do_subscribe = data['subscribe'] is True
        else:
            do_subscribe = False

        object_list = []

        size = objectmodels[schema].count(object_filter)

        if size > WARNSIZE and (limit > 0 and limit > WARNSIZE):
            self.log("Getting a very long (", size, ") list of items for ", schema,
                     lvl=warn)

        opts = schemastore[schema].get('options', {})
        hidden = opts.get('hidden', [])

        self.log("object_filter: ", object_filter, ' Schema: ', schema,
                 "Fields: ", fields,
                 lvl=verbose)

        options = {}
        if skip > 0:
            options['skip'] = skip
        if limit > 0:
            options['limit'] = limit
        if sort is not None:
            options['sort'] = []
            for item in sort:
                key = item[0]
                direction = item[1]
                direction = ASCENDING if direction == 'asc' else DESCENDING
                options['sort'].append([key, direction])

        cursor = objectmodels[schema].find(object_filter, **options)

        for item in cursor:
            if not self._check_permissions(user, 'list', item):
                continue
            self.log("Search found item: ", item, lvl=verbose)

            try:
                list_item = {'uuid': item.uuid}
                if fields in ('*', ['*']):
                    item_fields = item.serializablefields()
                    for field in hidden:
                        item_fields.pop(field, None)
                    object_list.append(item_fields)
                else:
                    if 'name' in item._fields:
                        list_item['name'] = item.name

                    for field in fields:
                        if field in item._fields and field not in hidden:
                            list_item[field] = item._fields[field]
                        else:
                            list_item[field] = None

                    object_list.append(list_item)

                if do_subscribe:
                    self._add_subscription(item.uuid, event)
            except Exception as e:
                self.log("Faulty object or field: ", e, type(e),
                         item._fields, fields, lvl=error, exc=True)
        # self.log("Generated object search list: ", object_list)

        result = {
            'component': 'hfos.events.objectmanager',
            'action': 'search',
            'data': {
                'schema': schema,
                'list': object_list,
                'size': size
            }
        }

        self._respond(None, result, event)
63204
def main():
    
    args = command_line()

    # TODO: Decouple Book interface and implementation
    query = Book(
        title=args.title,
        author=args.author,
        max_results=args.max,
        language_code=args.language,
        fields=('title', 'authors', 'imageLinks', 'categories', 'description'),
    )

    if args.verbose:
        print('Request URL:')
        print(query.url)
        print(query.__dict__)

    # Temporary Display Interface
    books = query.json.get('items', None)
    if not books:
        raise AttributeError('Web Request Failed')

    for book in books:
        info = book['volumeInfo']

        # Retrieve ISBN/Reference Info
        if 'industryIdentifiers' in info:
            identifiers = dict([(ref['type'], ref['identifier']) for ref in info['industryIdentifiers']])

            # Prefer ISBN 13 over ISBN 10
            if 'ISBN_13' in identifiers:
                isbn_id, isbn = 'ISBN_13', identifiers['ISBN_13']
            else:
                isbn_id, isbn = identifiers.popitem()

        else:
            isbn_id, isbn = 'ISBN_##', 'N/A'

        # Format/Print
        display = 'Title: {title}\nAuthor: {authors}\n{isbn_id}: {isbn}\n'.format(
            title=info['title'],
            authors=', '.join(info.get('authors', ['N/A'])),
            isbn_id=isbn_id,
            isbn=isbn,
        )

        print(display)
1159885
def search(self):
        ""
        form = forms.HomeForm()
        bbm_filter = bs_filters.BookmarkBukuFilter(
            all_keywords=False, deep=form.deep.data, regex=form.regex.data)
        op_text = bbm_filter.operation()
        values_combi = sorted(itertools.product([True, False], repeat=3))
        for idx, (all_keywords, deep, regex) in enumerate(values_combi):
            if deep == form.deep.data and regex == form.regex.data and not all_keywords:
                choosen_idx = idx
        url_op_text = op_text.replace(', ', '_').replace('  ', ' ').replace(' ', '_')
        key = ''.join(['flt', str(choosen_idx), '_buku_', url_op_text])
        kwargs = {key: form.keyword.data}
        url = url_for('bookmark.index_view', **kwargs)
        return redirect(url)
1002620
def fcomplete(text, state):
    """"""

    text = os.path.expanduser(text)
    head, tail = os.path.split(text)

    search_dir = os.path.join('.', head)
    candidates = [s for s in os.listdir(search_dir) if s.startswith(tail)]

    if state >= len(candidates):
        return None

    if len(candidates) == 1:
        fn = os.path.join(head, candidates[0])
        if not os.path.isdir(fn):
            return fn + ' '
        return fn + '/'

    return os.path.join(head, candidates[state])
637197
def full_keywords(soup):
    ""
    if not raw_parser.author_keywords(soup):
        return []
    return list(map(node_contents_str, raw_parser.author_keywords(soup)))
574007
def listing_searchable_text(instance):
    
    # get all snapshots
    snapshots = get_snapshots(instance)
    # extract all snapshot values, because we are not interested in the
    # fieldnames (keys)
    values = map(lambda s: s.values(), snapshots)
    # prepare a set of unified catalog data
    catalog_data = set()
    # values to skip
    skip_values = ["None", "true", "True", "false", "False"]
    # internal uid -> title cache
    uid_title_cache = {}

    # helper function to recursively unpack the snapshot values
    def append(value):
        if isinstance(value, (list, tuple)):
            map(append, value)
        elif isinstance(value, (dict)):
            map(append, value.items())
        elif isinstance(value, basestring):
            # convert unicode to UTF8
            if isinstance(value, unicode):
                value = api.safe_unicode(value).encode("utf8")
            # skip single short values
            if len(value) < 2:
                return
            # flush non meaningful values
            if value in skip_values:
                return
            # flush ISO dates
            if re.match(DATE_RX, value):
                return
            # fetch the title
            if re.match(UID_RX, value):
                if value in uid_title_cache:
                    value = uid_title_cache[value]
                else:
                    title_or_id = get_title_or_id_from_uid(value)
                    uid_title_cache[value] = title_or_id
                    value = title_or_id
            catalog_data.add(value)

    # extract all meaningful values
    for value in itertools.chain(values):
        append(value)

    return " ".join(catalog_data)
1207725
def search(self, query, delegate, args=None, extra_args=None):
        """"""
        if args is None:
            args = {}
        args['q'] = query
        return self.__doDownloadPage(self.search_url + '?' + self._urlencode(args),
            txml.Feed(delegate, extra_args), agent=self.agent)
192113
def getSearch(self):
        """"""
        return Search(self.getColumns(), Sitools2Abstract.getBaseUrl(self) + self.getUri())
96503
def query(self,query_string,toprint=False):
		""""""
		qq=SearchTerm(query_string)
		matchcount=0
		matches=[]
		for word in self.words():
			for match in word.search(qq):
				matches.append(match)
				matchcount+=1
				if "Word" in str(type(match)):
					matchstr=""
				else:
					matchstr=str(match)
				if toprint:
					word.om(makeminlength(str(matchcount),int(being.linelen/6))+"\t"+makeminlength(str(word),int(being.linelen))+"\t"+matchstr)
		return matches
1347612
def search(query, index=INDEX_NAME, doc_type=DOC_TYPE):
    
    results = raw_query(query, index=index, doc_type=doc_type)
    return [r['_source'] for r in results]
714351
function search(options, callback) {
  var queryURI = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=' + options.terms + '&retmode=json&retmax=' + (options.count || 10);
  utils.retrieve(queryURI, callback);
}
1310811
def search(self, term=None, category=None, pages=1, url=search_url,
				sort=None, order=None):
		""""""

		if not self.current_url:
			self.current_url = url

		if self.current_url == Search.base_url:
			# Searching home page so no formatting
			results = self._get_results(self.current_url)
			self._add_results(results)
		else:

			search = self._format_search(term, category)
			sorting = self._format_sort(sort, order)

			# Now get the results.
			for i in range(pages):
				results = self._get_results(search + "/" + str(self._current_page) +
											"/" + sorting)
				self._add_results(results)
				self._current_page += 1
			self._current_page -= 1