return the top wiki search result for the term
194648
def wiki(searchterm):
    """"""
    searchterm = quote(searchterm)

    url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json"
    url = url.format(searchterm)

    result = requests.get(url).json()

    pages = result["query"]["search"]

    # try to reject disambiguation pages
    pages = [p for p in pages if 'may refer to' not in p["snippet"]]

    if not pages:
        return ""

    page = quote(pages[0]["title"].encode("utf8"))
    link = "http://en.wikipedia.org/wiki/{0}".format(page)

    r = requests.get(
        "http://en.wikipedia.org/w/api.php?format=json&action=parse&page={0}".
        format(page)).json()
    soup = BeautifulSoup(r["parse"]["text"]["*"], "html5lib")
    p = soup.find('p').get_text()
    p = p[:8000]

    return u"{0}\n{1}".format(p, link)
670437
def identifierSearches(self,
                           ids=None,
                           LIMIT=25,
                           _print=True,
                           crawl=False):
        """"""
        url_base = self.base_url + '/api/1/term/view/{id}' + '?key=' + self.api_key
        urls = [url_base.format(id=str(_id)) for _id in ids]
        return self.get(
            urls=urls,
            LIMIT=LIMIT,
            action='Searching For Terms',
            crawl=crawl,
            _print=_print)
518428
def get_top_tags(self, limit=None):
        """"""

        doc = self._request(self.ws_prefix + ".getTopTags", True)

        elements = doc.getElementsByTagName("tag")
        seq = []

        for element in elements:
            tag_name = _extract(element, "name")
            tagcount = _extract(element, "count")

            seq.append(TopItem(Tag(tag_name, self.network), tagcount))

        if limit:
            seq = seq[:limit]

        return seq
487987
def get_terms(self, name, revision=None):
        
        url = '{}terms/{}'.format(self.url, name)
        if revision:
            url = '{}?revision={}'.format(url, revision)
        json = make_request(url, timeout=self.timeout, client=self._client)
        try:
            # This is always a list of one element.
            data = json[0]
            return Term(name=data['name'],
                        title=data.get('title'),
                        revision=data['revision'],
                        created_on=datetime.datetime.strptime(
                            data['created-on'],
                            "%Y-%m-%dT%H:%M:%SZ"
                            ),
                        content=data['content'])
        except (KeyError, TypeError, ValueError, IndexError) as err:
            log.info(
                'cannot process terms: invalid JSON response: {!r}'.format(
                    json))
            raise ServerError(
                'unable to get terms for {}: {}'.format(name, err))
1253750
def query_most(num=8, kind='1'):
        '''
        
        '''
        return TabWiki.select().where(
            TabWiki.kind == kind
        ).order_by(
            TabWiki.view_count.desc()
        ).limit(num)
420099
def get_results_range(self):
        
        spec = self.context.getResultsRange()
        if spec:
            return dicts_to_dict(spec, "keyword")
        return ResultsRangeDict()
1306727
def items_top_get(self, keyword, nick=None):
        ''''''
        request = TOPRequest('xxxxx.xxxxx.tools.items.top.get')
        request['keyword'] = keyword
        if nick!=None: request['nick'] = nick
        self.create(self.execute(request), models={'result':RankedItem})
        return self.result
845882
def query_term(self, term, verbose=False):
        """"""
        if term not in self:
            sys.stderr.write("Term %s not found!\n" % term)
            return

        rec = self[term]
        if verbose:
            print(rec)
            sys.stderr.write("all parents: {}\n".format(
                repr(rec.get_all_parents())))
            sys.stderr.write("all children: {}\n".format(
                repr(rec.get_all_children())))
        return rec
1120317
def esearch(self, db, term):
        
        esr = ESearchResult(self._qs.esearch({'db': db, 'term': term}))
        if esr.count > esr.retmax:
            logger.warning("NCBI found {esr.count} results, but we truncated the reply at {esr.retmax}"
                        " results; see https://github.com/biocommons/eutils/issues/124/".format(esr=esr))
        return esr
955244
def search( self ):
        
        QApplication.instance().setOverrideCursor(Qt.WaitCursor)
        
        terms = nativestring(self.uiSearchTXT.text())
        
        html = []
        
        entry_html = '<a href="%(url)s">%(title)s</a><br/>'\
                     '<small>%(url)s</small>'
        
        for i in range(self.uiContentsTREE.topLevelItemCount()):
            item = self.uiContentsTREE.topLevelItem(i)
            
            results = item.search(terms)
            results.sort(lambda x, y: cmp(y['strength'], x['strength']))
            for item in results:
                html.append( entry_html % item )
        
        if ( not html ):
            html.append('<b>No results were found for %s</b>' % terms)
        
        self.uiSearchWEB.setHtml(SEARCH_HTML % '<br/><br/>'.join(html))
        
        QApplication.instance().restoreOverrideCursor()
1132784
def cat_top_keywords(self, session, cat, up=True,  offset=0, offsets=[]):
        ''''''
        print 'CAT:%s, level:%s'%(str(cat), str(cat.level))
        print 'OFFSET: %d'%offset
        response = []
        if not offsets or offset==0: 
            url = 'http://top.taobao.com/level3.php?cat=%s&level3=%s&show=focus&up=%s&offset=%d'%(cat.parent.cid, '' if cat.level==2 else str(cat.cid), 'true' if up else '', offset)
            print url
            rs = self.fetch(url)
            if not rs: return response
            soup = BeautifulSoup(rs.content, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=hexentityMassage)
            response = self.parse_cat_top_keywords(soup, offset)
        if offset==0:
            offsets = self.get_cat_top_keywords_pages(soup, offset)
            print 'OFFSETS: %s'%offsets
        if offsets:
            rs = []
            threadPool = ThreadPool(len(offsets) if len(offsets)<=5 else 5)
            for idx, page_offset in enumerate(offsets):
                page_url = 'http://top.taobao.com/level3.php?cat=%s&level3=%s&show=focus&up=%s&offset=%d'%(cat.parent.cid, '' if cat.level==2 else str(cat.cid), 'true' if up else '', page_offset)
                next_page = 'True' if idx == (len(offsets)-1) else 'False'
                threadPool.run(self.fetch, callback=None, url=page_url, config=dict(get_next=next_page, offset=page_offset))
            pages = threadPool.killAllWorkers(None)
            #print 'RESPONSES: %s'%pages
            for p in pages:
                if not p: continue
                soup2 = BeautifulSoup(p.content, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=hexentityMassage)
                offset2 = int(p.config['offset'])
                response += self.parse_cat_top_keywords(soup2, offset2)
                print 'GOT: %d'%offset2
                if p.config['get_next'] != 'True': continue
                offsets = self.get_cat_top_keywords_pages(soup2, offset2)
                print offsets
                if not offsets: continue
                response += self.cat_top_keywords(session, cat, up, offset2, offsets)
        #return sorted(response, key=itemgetter('pos')) if response else []
        #print "RETURN:%d"%offset
        for k in response:
            new_keyword = models.Keyword(k['name'].decode('utf-8'))
            new_keyword.categories.append(cat)
            session.add(new_keyword)
            try:
                session.commit()
            except IntegrityError:
                session.rollback()
                new_keyword = session.query(models.Keyword).filter(models.Keyword.name == k['name']).first()
                new_keyword.categories.append(cat)
                session.commit()
                print 'Duplicate %s'%new_keyword
        return response
1242378
def get_search(self):
        """"""
        old_search = self.get_session_value('search', '')
        search = self.get_and_save_value('search', '')
        if old_search != search:
            self.page = 1
            self.get_session_value('page', self.page)
        return search
302372
def search_url(self, searchterm):
        
        return self.__search(type_attribute=self.__mispurltypes(), value=searchterm)
905913
private function getSuggestedTerms()
    {
        $terms = array_map(
            function (\Magento\Search\Model\Autocomplete\Item $termItem) {
                return $termItem->getTitle();
            },
            $this->termDataProvider->getItems()
        );

        return $terms;
    }
995000
public function getSearchResults()
    {
        // fetch the search results
        $limit = $this->db->getLimit();
        $rows = $this->db->getSearchResults();

        // TODO: Check how Sphinx handles this, seems to return full result set
        if (count($rows) > $limit[1]) {
            $rows = array_slice($rows, $limit[0], $limit[1]);
        }

        // set number of results
        $this->numberOfResults = $this->db->getAmountOfSearchResults();

        // count search phrase in ke_search statistic tables
        if ($this->conf['countSearchPhrases']) {
            $this->countSearchPhrase($this->sword, $this->swords, $this->numberOfResults, $this->tagsAgainst);
        }

        // render "no results" text and stop here
        if ($this->numberOfResults == 0) {
            $this->setNoResultsText();
        }

        // set switch for too short words
        $this->fluidTemplateVariables['wordsTooShort'] = $this->hasTooShortWords ? 1 : 0;

        // init counter and loop through the search results
        $resultCount = 1;
        $this->searchResult = GeneralUtility::makeInstance(Searchresult::class, $this);

        $this->fluidTemplateVariables['resultrows'] = array();
        if (is_array($rows)) {
            foreach ($rows as $row) {
                $this->searchResult->setRow($row);

                $tempMarkerArray = array(
                    'orig_uid' => $row['orig_uid'],
                    'orig_pid' => $row['orig_pid'],
                    'title_text' => $row['title'],
                    'content_text' => $row['content'],
                    'title' => $this->searchResult->getTitle(),
                    'teaser' => $this->searchResult->getTeaser(),
                );

                // hook for additional markers in result row
                if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['ke_search']['additionalResultMarker'])) {
                    // make curent row number available to hook
                    $this->currentRowNumber = $resultCount;
                    foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['ke_search']['additionalResultMarker'] as $_classRef) {
                        $_procObj = &GeneralUtility::makeInstance($_classRef);
                        $_procObj->additionalResultMarker($tempMarkerArray, $row, $this);
                    }
                    unset($this->currentRowNumber);
                }

                // add type marker
                // for file results just use the "file" type, not the file extension (eg. "file:pdf")
                list($type) = explode(':', $row['type']);
                $tempMarkerArray['type'] = str_replace(' ', '_', $type);

                // use the markers array as a base for the fluid template values
                $resultrowTemplateValues = $tempMarkerArray;

                // set result url
                $resultUrl = $this->searchResult->getResultUrl($this->conf['renderResultUrlAsLink']);
                $resultrowTemplateValues['url'] = $resultUrl;

                // set result numeration
                $resultNumber = $resultCount
                    + ($this->piVars['page'] * $this->conf['resultsPerPage'])
                    - $this->conf['resultsPerPage'];
                $resultrowTemplateValues['number'] = $resultNumber;

                // set date (formatted and raw as a timestamp)
                $resultDate = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $row['sortdate']);
                $resultrowTemplateValues['date'] = $resultDate;
                $resultrowTemplateValues['date_timestamp'] = $row['sortdate'];

                // show tags?
                $tags = $row['tags'];
                $tags = str_replace('#', ' ', $tags);
                $resultrowTemplateValues['tags'] = $tags;

                // set preview image and/or type icons
                // for files we have the corresponding entry in sys_file as "orig_uid" available (not sys_file_reference)
                // for pages and news we have to fetch the file reference uid
                if ($type == 'file') {
                    $resultrowTemplateValues['filePreviewId'] = $row['orig_uid'];
                    $resultrowTemplateValues['treatIdAsReference'] = 0;
                } else {
                    $resultrowTemplateValues['filePreviewId'] = $this->getFileReference($row);
                    $resultrowTemplateValues['treatIdAsReference'] = 1;
                }

                // get the icon for the current record type
                $resultrowTemplateValues['typeIconPath'] = $this->getTypeIconPath($row['type']);

                // set end date for cal events
                if ($type == 'cal') {
                    $resultrowTemplateValues['cal'] = $this->getCalEventEnddate($row['orig_uid']);
                }

                // add result row to the variables array
                $this->fluidTemplateVariables['resultrows'][] = $resultrowTemplateValues;

                // increase result counter
                $resultCount++;
            }
        }
    }
362571
def get_term(id, opts = {})
      data, _status_code, _headers = get_term_with_http_info(id, opts)
      return data
    end
1336206
def search(self, term, keywords=None, sortAscending=True):
        
        if sortAscending:
            direction = 'ASC'
        else:
            direction = 'DESC'

        return [_SQLiteResultWrapper(r[0]) for r in
                self.store.querySQL(self.searchSQL % (direction,), (term,))]