Searches for words or sentences containing a search phrase
192439
def search(query, files, mode='sentence', regex=False):
    ''''''
    out = []
    sentences = convert_timestamps(files)

    if mode == 'fragment':
        out = fragment_search(query, sentences, regex)
    elif mode == 'word':
        out = word_search(query, sentences, regex)
    elif mode == 'franken':
        out = franken_sentence(query, files)
    else:
        out = sentence_search(query, sentences, regex)


    return out
1239703
def search(self, search_phrase, limit=None):
        """"""
        from ambry.identity import ObjectNumber
        from ambry.orm.exc import NotFoundError
        from ambry.library.search_backends.base import SearchTermParser

        results = []

        stp = SearchTermParser()

        # Because of the split between searching for partitions and bundles, some terms don't behave right.
        # The source term should be a limit on everything, but it isn't part of the partition doc,
        # so we check for it here.
        parsed_terms = stp.parse(search_phrase)

        for r in self.search_datasets(search_phrase, limit):
            vid = r.vid or ObjectNumber.parse(next(iter(r.partitions))).as_dataset

            r.vid = vid

            try:
                r.bundle = self.library.bundle(r.vid)

                if 'source' not in parsed_terms or parsed_terms['source'] in r.bundle.dataset.source:
                    results.append(r)
            except NotFoundError:
                pass

        return sorted(results, key=lambda r : r.score, reverse=True)
370887
def findOODWords(isleDict, wordList):
    '''
    
    '''
    oodList = []
    for word in wordList:
        try:
            isleDict.lookup(word)
        except WordNotInISLE:
            oodList.append(word)
                
    oodList = list(set(oodList))
    oodList.sort()
    
    return oodList
1113071
def search(context, keywords, module, raw, kind):
    
    logging.info(_('Entering search mode'))
    sense = context.obj['sense']
    func = sense.query_names if module else sense.query_info
    none = True
    for keyword in keywords:
        output = func(keyword, raw, kind)
        if output:
            none = False
            print(output)
        else:
            logging.warning(_('No results: %s'), keyword)
    sys.exit(1 if none else 0)
495548
def search(self, sentence):
        
        if sentence.__class__.__name__ == "Sentence":
            pass
        elif isinstance(sentence, list) or sentence.__class__.__name__ == "Text":
            a=[]; [a.extend(self.search(s)) for s in sentence]; return a
        elif isinstance(sentence, basestring):
            sentence = Sentence(sentence)
        elif isinstance(sentence, Match) and len(sentence) > 0:
            sentence = sentence[0].sentence.slice(sentence[0].index, sentence[-1].index + 1)
        a = []
        v = self._variations()
        u = {}
        m = self.match(sentence, _v=v)
        while m:
            a.append(m)
            m = self.match(sentence, start=m.words[-1].index+1, _v=v, _u=u)
        return a
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()
788106
def search(self, start_ts, end_ts):
        """"""
        query = '_ts: [%s TO %s]' % (start_ts, end_ts)
        return self._stream_search(query)
1253418
function( text2search, noSearchPhrase, noSearchResult ) {

  Array.call( this );

  /**
   * Gets the text to search.
   * @type {string|null}
   */
  this.text2search = text2search || null;

  /**
   * Gets a message to display when search phrase is missing.
   * @type {string}
   */
  this.noSearchPhrase = noSearchPhrase;

  /**
   * Gets a message to display when search did not found the text in the contents.
   * @type {string}
   */
  this.noSearchResult = noSearchResult;
}
458047
def search(pattern, text):
    ''
    return re.compile(str(pattern)).search(str(text))
335198
def search():
    """"""
    pattern = flask.request.args.get('pattern', "*").strip().lower()

    # if the pattern contains "in:<collection>" (eg: in:builtin),
    # filter results to only that (or those) collections
    # This was kind-of hacked together, but seems to work well enough
    collections = [c["name"].lower() for c in current_app.kwdb.get_collections()]
    words = []
    filters = []
    if pattern.startswith("name:"):
        pattern = pattern[5:].strip()
        mode = "name"
    else:
        mode="both"

    for word in pattern.split(" "):
        if word.lower().startswith("in:"):
            filters.extend([name for name in collections if name.startswith(word[3:])])
        else:
            words.append(word)
    pattern = " ".join(words)

    keywords = []
    for keyword in current_app.kwdb.search(pattern, mode):
        kw = list(keyword)
        collection_id = kw[0]
        collection_name = kw[1].lower()
        if len(filters) == 0 or collection_name in filters:
            url = flask.url_for(".doc_for_library", collection_id=kw[0], keyword=kw[2])
            row_id = "row-%s.%s" % (keyword[1].lower(), keyword[2].lower().replace(" ","-"))
            keywords.append({"collection_id": keyword[0],
                             "collection_name": keyword[1],
                             "name": keyword[2],
                             "synopsis": keyword[3],
                             "version": __version__,
                             "url": url,
                             "row_id": row_id
                         })

    keywords.sort(key=lambda kw: kw["name"])
    return flask.render_template("search.html",
                                 data={"keywords": keywords,
                                       "version": __version__,
                                       "pattern": pattern
                                   })
404920
def _search(self, search_terms, begins_with=None):
        

        kwargs = dict(
            ProjectionExpression='#id',
            ExpressionAttributeNames={"#id": "_id"})

        if len(search_terms) > 0:
            kwargs['FilterExpression'] = reduce(
                lambda x, y: x & y,
                [Attr('tags').contains(arg) for arg in search_terms])

        if begins_with:
            if 'FilterExpression' in kwargs:
                kwargs['FilterExpression'] = kwargs[
                    'FilterExpression'] & Key('_id').begins_with(begins_with)

            else:
                kwargs['FilterExpression'] = Key(
                    '_id').begins_with(begins_with)

        while True:
            res = self._table.scan(**kwargs)
            for r in res['Items']:
                yield r['_id']
            if 'LastEvaluatedKey' in res:
                kwargs['ExclusiveStartKey'] = res['LastEvaluatedKey']
            else:
                break
1098570
def search(self, term):
        
        packages = {}
        results = self._execute_pip(['search', term], log=False)  # Don't want to log searches
        for result in results.split(linesep):
            try:
                name, description = result.split(six.u(' - '), 1)
            except ValueError:
                # '-' not in result so unable to split into tuple;
                # this could be from a multi-line description
                continue
            else:
                name = name.strip()
                if len(name) == 0:
                    continue
                packages[name] = description.split(six.u('<br'), 1)[0].strip()
        return packages
397083
def search(self, string, default=None):
        """"""
        default = default if default else []
        result = [item[1] for item in self.container if item[0].search(string)]
        if self.ensure_mapping:
            assert len(result) < 2, "%s matches more than one pattern: %s" % (
                string,
                result,
            )
        return result if result else default
949386
def highlight_matches(self):
        """"""
        if self.is_code_editor and self.highlight_button.isChecked():
            text = self.search_text.currentText()
            words = self.words_button.isChecked()
            regexp = self.re_button.isChecked()
            self.editor.highlight_found_results(text, words=words,
                                                regexp=regexp)
70198
function getKeyphrases(results, maximum) {
  var stemmedPhrases = {}
  var initialWords = []
  var stemmedPhrase
  var index
  var length
  var otherIndex
  var keyword
  var matches
  var phrase
  var stems
  var score
  var first
  var match

  // Iterate over all grouped important words...
  for (keyword in results) {
    matches = results[keyword].matches
    length = matches.length
    index = -1

    // Iterate over every occurence of a certain keyword...
    while (++index < length) {
      phrase = findPhrase(matches[index])
      stemmedPhrase = stemmedPhrases[phrase.value]
      first = phrase.nodes[0]

      match = {
        nodes: phrase.nodes,
        parent: matches[index].parent
      }

      // If we've detected the same stemmed phrase somewhere.
      if (own.call(stemmedPhrases, phrase.value)) {
        // Add weight per phrase to the score of the phrase.
        stemmedPhrase.score += stemmedPhrase.weight

        // If this is the first time we walk over the phrase (exact match but
        // containing another important word), add it to the list of matching
        // phrases.
        if (initialWords.indexOf(first) === -1) {
          initialWords.push(first)
          stemmedPhrase.matches.push(match)
        }
      } else {
        otherIndex = -1
        score = -1
        stems = phrase.stems

        initialWords.push(first)

        // For every stem in phrase, add its score to score.
        while (stems[++otherIndex]) {
          score += results[stems[otherIndex]].score
        }

        stemmedPhrases[phrase.value] = {
          score: score,
          weight: score,
          stems: stems,
          value: phrase.value,
          matches: [match]
        }
      }
    }
  }

  for (stemmedPhrase in stemmedPhrases) {
    phrase = stemmedPhrases[stemmedPhrase]

    // Modify its score to be the rounded result of multiplying it with the
    // number of occurances, and dividing it by the ammount of words in the
    // phrase.
    phrase.score = Math.round(
      (phrase.score * phrase.matches.length) / phrase.stems.length
    )
  }

  return filterResults(stemmedPhrases, maximum)
}
808494
def filter_stopwords(phrase):
    """"""
    if not isinstance(phrase, list):
        phrase = phrase.split()

    stopwords = ['the', 'a', 'in', 'to']
    return [word.lower() for word in phrase if word.lower() not in stopwords]
219664
def candidates(text):
        
        for Pmatch in finditer(TARGET, text):
            # the punctuation mark itself
            P = Pmatch.group(1)
            # is it a boundary?
            B = bool(match(NEWLINE, Pmatch.group(5)))
            # L & R
            start = Pmatch.start()
            end = Pmatch.end()
            Lmatch = search(LTOKEN, text[max(0, start - BUFSIZE):start])
            if not Lmatch:  # this happens when a line begins with '.'
                continue
            L = word_tokenize(" " + Lmatch.group(1))[-1]
            Rmatch = search(RTOKEN, text[end:end + BUFSIZE])
            if not Rmatch:  # this happens at the end of the file, usually
                continue
            R = word_tokenize(Rmatch.group(1) + " ")[0]
            # complete observation
            yield Observation(L, P, R, B, end)