TODO move to search module
768547
def index_items(with_pagination = true)
      conditions = Search::Conditions::List.new(params, model_info.data_items)
      conditions.paginate = nil unless with_pagination
      if params[:rel_class] && params[:rel_id] && params[:rel_getter]
        related_info = RademadeAdmin::Model::Graph.instance.model_info(params[:rel_class])
        @related_model = related_info.query_adapter.find(params[:rel_id])
        conditions.base_items = @related_model.send(params[:rel_getter])
      end
      Search::Searcher.new(model_info).search(conditions)
    end
788106
def search(self, start_ts, end_ts):
        """"""
        query = '_ts: [%s TO %s]' % (start_ts, end_ts)
        return self._stream_search(query)
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)
192113
def getSearch(self):
        """"""
        return Search(self.getColumns(), Sitools2Abstract.getBaseUrl(self) + self.getUri())
457372
def find_this(search, filename=MODULE_PATH):
    """"""
    if not search:
        return
    for line in open(str(filename)).readlines():
        if search.lower() in line.lower():
            line = line.split("=")[1].strip()
            if "'" in line or '"' in line or '"""' in line:
                line = line.replace("'", "").replace('"', '').replace('"""', '')
            return line
1219970
function search(user, pass, userArray) {
      return _.findWhere(userArray, { user: user, pass: pass });
    }
112962
function QueryString(search) {
        "use strict";
    
        if (search.substr(0, 1) === '?') {
            search = search.substr(1);
        }
    
        search = search.split('&')
    
        if (search == "") return {};
    
        for (var i = 0; i < search.length; ++i) {
    
            var param = search[i].split('=', 2);
            if (param.length != 2) {
                continue;
            }
    
            this[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
    
        }
    
    }
484689
@Override
    public void _search(String fieldName, String searchTerms) {
        _search(fieldName, searchTerms, SearchOperator.OR);
    }
1344959
function(cb) {
		var todos = [], prevTodos;
		var model = this;

		open().then(function(db){
			var os = db.transaction(["todos"], "readwrite")
				.objectStore("todos");

			var req = os.openCursor();

			req.onsuccess = function(e){
				var cursor = e.target.result;
				if(cursor){
					todos.push(cursor.value);
					cursor.continue();
				} else {
					prevTodos = todos.slice();
					cb.call(model, todos);
					done();
				}
			};

			function done(){
				(todos || []).forEach(function(todo){
					os.put(todo);
				});
				prevTodos.forEach(function(todo){
					if(todos.indexOf(todo) === -1) {
						os["delete"](todo.text);
					}
				});
			}
		});
	  }
854501
private void findGroupBys() {
    if (filters == null || filters.isEmpty()) {
      return;
    }
    
    if ((use_multi_gets && override_multi_get) && !search_query_failure) {
      
    }
    
    row_key_literals = new ByteMap<byte[][]>();
    final int expansion_limit = tsdb.getConfig().getInt(
        "tsd.query.filter.expansion_limit");
    
    Collections.sort(filters);
    final Iterator<TagVFilter> current_iterator = filters.iterator();
    final Iterator<TagVFilter> look_ahead = filters.iterator();
    byte[] tagk = null;
    TagVFilter next = look_ahead.hasNext() ? look_ahead.next() : null;
    int row_key_literals_count = 0;
    while (current_iterator.hasNext()) {
      next = look_ahead.hasNext() ? look_ahead.next() : null;
      int gbs = 0;
      // sorted!
      final ByteMap<Void> literals = new ByteMap<Void>();
      final List<TagVFilter> literal_filters = new ArrayList<TagVFilter>();
      TagVFilter current = null;
      do { // yeah, I'm breakin out the do!!!
        current = current_iterator.next();
        if (tagk == null) {
          tagk = new byte[TSDB.tagk_width()];
          System.arraycopy(current.getTagkBytes(), 0, tagk, 0, TSDB.tagk_width());
        }
        
        if (current.isGroupBy()) {
          gbs++;
        }
        if (!current.getTagVUids().isEmpty()) {
          for (final byte[] uid : current.getTagVUids()) {
            literals.put(uid, null);
          }
          literal_filters.add(current);
        }

        if (next != null && Bytes.memcmp(tagk, next.getTagkBytes()) != 0) {
          break;
        }
        next = look_ahead.hasNext() ? look_ahead.next() : null;
      } while (current_iterator.hasNext() && 
          Bytes.memcmp(tagk, current.getTagkBytes()) == 0);

      if (gbs > 0) {
        if (group_bys == null) {
          group_bys = new ArrayList<byte[]>();
        }
        group_bys.add(current.getTagkBytes());
      }
      
      if (literals.size() > 0) {
        if (literals.size() + row_key_literals_count > expansion_limit) {
          LOG.debug("Skipping literals for " + current.getTagk() + 
              " as it exceedes the limit");
          //has_filter_cannot_use_get = true;
        } else {
          final byte[][] values = new byte[literals.size()][];
          literals.keySet().toArray(values);
          row_key_literals.put(current.getTagkBytes(), values);
          row_key_literals_count += values.length;
          
          for (final TagVFilter filter : literal_filters) {
            filter.setPostScan(false);
          }
        }
      } else {
        row_key_literals.put(current.getTagkBytes(), null);
        // no literal values, just keys, so we can't multi-get
        if (search_query_failure) {
          use_multi_gets = false;
        }
      }
      
      // make sure the multi-get cardinality doesn't exceed our limit (or disable
      // multi-gets)
      if ((use_multi_gets && override_multi_get)) {
        int multi_get_limit = tsdb.getConfig().getInt("tsd.query.multi_get.limit");
        int cardinality = filters.size() * row_key_literals_count;
        if (cardinality > multi_get_limit) {
          use_multi_gets = false;
        } else if (search_query_failure) {
          row_key_literals_list.add(row_key_literals);
        }
        // TODO - account for time as well
      }
    }
  }
587061
def doFind(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND', **params):
		""""""

		self._preFind(WHAT, SORT, SKIP, MAX, LOP)

		for key in params:
			self._addDBParam(key, params[key])

		try:
			return self._doAction('-find')
		except FMServerError as e:
			if e.args[0] in [401, 8]:
				return []
707732
def find( self, flags = 0 ):
        
        # check against the web and text views
        if ( not (self._textEdit or self._webView) ):
            fg = QColor('darkRed')
            bg = QColor('red').lighter(180)
            
            palette = self.palette()
            palette.setColor(palette.Text, fg)
            palette.setColor(palette.Base, bg)
            
            self._searchEdit.setPalette(palette)
            self._searchEdit.setToolTip( 'No Text Edit is linked.' )
            
            return False
        
        if ( self._caseSensitiveCheckbox.isChecked() ):
            flags |= QTextDocument.FindCaseSensitively
        
        if ( self._textEdit and self._wholeWordsCheckbox.isChecked() ):
            flags |= QTextDocument.FindWholeWords
        
        terms = self._searchEdit.text()
        if ( terms != self._lastText ):
            self._lastCursor = QTextCursor()
        
        if ( self._regexCheckbox.isChecked() ):
            terms = QRegExp(terms)
        
        palette = self.palette()
        
        # search on a text edit
        if ( self._textEdit ):
            cursor  = self._textEdit.document().find(terms, 
                                                 self._lastCursor, 
                                                 QTextDocument.FindFlags(flags))
            found   = not cursor.isNull()
            self._lastCursor = cursor
            self._textEdit.setTextCursor(cursor)
        
        elif ( QWebPage ):
            flags = QWebPage.FindFlags(flags)
            flags |= QWebPage.FindWrapsAroundDocument
            
            found = self._webView.findText(terms, flags)
        
        self._lastText = self._searchEdit.text()
        
        if ( not terms or found ):
            fg = palette.color(palette.Text)
            bg = palette.color(palette.Base)
        else:
            fg = QColor('darkRed')
            bg = QColor('red').lighter(180)
        
        palette.setColor(palette.Text, fg)
        palette.setColor(palette.Base, bg)
        
        self._searchEdit.setPalette(palette)
        
        return found
1337395
function Compare () {

    var self = this;

    function compare (current, previous) {

        // all up/down properties are arrays of string.
        var build = {
                up: {
                    createTable: [],
                    dropTable: [],
                    dropTables: [],
                    addColumn: [],
                    changeColumn: [],
                    removeColumn: []
                    //renameTable: [],  // TODO future feature.
                    //renameColumn: [], // TODO future feature.
                    //addIndex: [],     // TODO future feature.
                    //removeIndex: []   // TODO future feature.
                },
                down: {
                    createTable: [],
                    dropTable: [],
                    dropTables: [],
                    addColumn: [],
                    changeColumn: [],
                    removeColumn: []
                    //renameTable: [],  // TODO future feature.
                    //renameColumn: [], // TODO future feature.
                    //addIndex: [],     // TODO future feature.
                    //removeIndex: []   // TODO future feature.
                },
                options: []
            },
            validAttrs = self.migConf.validAttributes,
            excludeAttrs = self.migConf.excludeAttributes,
            typeVariable = self.migConf.typeVariable || 'types',
            modelName = current.name,
            baseTabs = 2;

        function getTabs(int, addBase) {
            var tabs = '';
            if(addBase)
                int += baseTabs;
            while(int){
                tabs += '\t';
                --int;
            }
            return tabs;
        }

        function isValid(attr) {
            return validAttrs.indexOf(attr) !== -1;
        }

        function qwrap(str) {
            return "'" + str + "'";
        }

        function getActions(type) {
            var actions = [];
            _.forEach(type, function (v) {
                if(v.length) actions.push(v);
            });
            return actions;
        }

        function filterAttributes(obj) {
            var clone = _.clone(obj);
            _.forEach(clone, function (v,k) {
                if(!isValid(k))
                delete clone[k];
            });
            return clone;
        }

        function arrayToString(arr, def) {
            var val = '[';
            def = def || undefined;
            if(!arr || !arr.length)
                return def;
            if(!_.isString(arr[0])){
                val += arr.join(',');
            }else {
                _.forEach(arr, function (v) {
                    val += qwrap(v) + ',';
                });
                val = val.slice(0, val.length -1);
            }
            val += ']';
           return val;
        }

        function funcToString(func, level) {
            var split = func.split('\n'),
                tmp = [];
            _.forEach(split, function (v, k) {
                v = v.replace(/^\s+/, '').replace('\r', '');
                if(k +1 === split.length)
                    tmp.push(getTabs(level + 1, true) + v);
                else if(k > 0)
                    tmp.push(getTabs(level + 2, true) + v);
                else tmp.push(v);
            });
            return tmp.join('\n');
        }

        /**
         * Concats all up migration events to string.
         * @private
         * @memberof Compare
         * @returns {string}
         */
        function upToString() {
            var upStr = '',
                ctr = 0,
                items = getActions(build.up),
                tab,
                suffix;
            // build the output string for up.
            _.forEach(items, function (v,k) {
                _.forEach(v, function(item, key){
                    suffix = (ctr < v.length -1) || (k+1 < items.length) ? '\n' : '';
                    tab = ctr > 0 ? getTabs(0, true) : '';
                    upStr += (tab + item + suffix);
                    ctr += 1;
                });
            });
            return upStr;
        }

        /**
         * Concats all down migration events to string.
         * @private
         * @memberof Compare
         * @returns {string}
         */
        function downToString() {
            var dwnStr = '',
                ctr = 0,
                items = getActions(build.down),
                tab,
                suffix;
            // build the output string for down.
            _.forEach(items, function (v,k) {
                _.forEach(v, function(item, key){
                    suffix = (ctr < v.length -1) || (k+1 < items.length) ? '\n' : '';
                    tab = ctr > 0 ? getTabs(0, true) : '';
                    dwnStr += (tab + item + suffix);
                    ctr += 1;
                });
            });
            return dwnStr;
        }

        /**
         * Recurse child options concat to string.
         * @private
         * @memberof Compare
         * @param {object} obj - the child object.
         * @returns {string}
         */
        function recurseChildOptions(obj, level){
            var child = '',
                len = Object.keys(obj).length,
                ctr = 0,
                prefix;
            level = level || 1;
            for(var prop in obj) {
                if(obj.hasOwnProperty(prop)){
                    var tab = getTabs(level +1, true),
                        val;
                    prefix = ctr > 0 ? ',\n' : '';
                    if(_.isPlainObject(obj[prop])){
                        if(!_.isEmpty(obj[prop])){
                            var subChild = recurseChildOptions(obj[prop], level + 1);
                            if(subChild && subChild.length)
                                child += (tab + prop + ': { \n' + subChild + '\n' + tab + '}');
                        }
                    } else {
                        if(_.isArray(obj[prop])){
                            val = arrayToString(obj[prop]);
                            if(val){
                                tab = ctr === 0 ? getTabs(level) : getTabs(level +1, true);
                                child += (prefix + tab + prop + ': ' + arrayToString(obj[prop]));
                            }
                        } else {
                            var isFunc;
                            val = obj[prop];
                            isFunc = _.isFunction(val);
                            if(_.isString(val)){
                                val = "'" + val.toString() + "'";
                            } else {
                                val = val.toString();
                                if(isFunc)
                                    val = funcToString(val, level);
                            }
                            child += (prefix + tab + prop + ': ' + val);
                        }
                    }
                    ctr +=1;
                }
            }
            return child;
        }

        /**
         * Parse options for create model migrations.
         * @private
         * @memberof Compare
         * @param {object} obj - the object of options.
         */
        function parseOptions(obj) {
            var ctr = 0,
                tab = getTabs(1, true);
            for(var prop in obj) {
                if(obj.hasOwnProperty(prop)){
                    if(_.isPlainObject(obj[prop])){
                        if(!_.isEmpty(obj[prop])){
                            var child = recurseChildOptions(obj[prop]);
                            if(child && child.length)
                                build.options.push(tab + prop + ': { \n' + child + ' \n' + tab + '}');
                        }
                    } else {
                        if(_.isArray(obj[prop])){
                            build.options.push(tab + prop + ': ' + arrayToString(obj[prop]));
                        } else {
                            var val = obj[prop];
                            if(_.isString(val))
                                val = qwrap(val);
                            else
                                val = val.toString();
                            build.options.push(tab + prop + ': ' + val);
                        }
                    }
                }
                ctr +=1;
            }

        }

        /**
         * Converts a property's atttributes to string.
         * @private
         * @memberof Compare
         * @param {object} obj - the object of attributes.
         * @param {object} prevObj - the previous object of attributes from last snapshot.
         * @returns {string}
         */
        function attributesToString(obj, prevObj, level) {
            var attrs = '',
                prefix,
                tab;
            level = level || 1;
            tab = getTabs(level, true);
            _.forEach(obj, function (v, k) {
                if(excludeAttrs.indexOf(k) === -1){
                    var prev = prevObj && prevObj[k] !== undefined ? prevObj[k] : undefined;
                    prefix = attrs.length ? ',\n' : '';
                    if(_.isPlainObject(v)){
                        var subAttr = attributesToString(v, prev, level +1);
                        if(subAttr && subAttr.length)
                            attrs += (prefix + tab + k + ': {\n' + subAttr + '\n' + tab + '}');
                    } else {
                        if(prev !== v){
                            var val = k === 'type' ? 'types.' + v : v;
                            if(_.isArray(val))
                                val = arrayToString(val);
                            if(_.isFunction(val)){
                                val = funcToString(val.toString(), 2);
                            }
                            attrs += (prefix + tab + k + ': ' + val);
                        }
                    }
                }
            });

            return attrs;
        }

        /**
         * Iterate table/model properties and compare or create new.
         * @private
         * @memberof Compare
         */
        function compareMigration(){

            var tab

            // the model/table already exists.
            if(previous){

                tab = getTabs(0, true),

                // compare to previous table checking for
                // any dropped columns.
                _.forEach(previous.attributes, function (v,k) {
                    if (v._modelAttribute) {
                        var curCol = current && current.attributes ? current.attributes[k] : undefined,
                            removeAttrs;
                        // if curCol is undefined it was removed.
                        if(!curCol){
                            removeAttrs = attributesToString(filterAttributes(v));
                            if(removeAttrs) {
                                build.up.removeColumn.push(
                                        'migration.removeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ');'
                                );
                                build.down.addColumn.push(
                                        'migration.addColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        tab + '{\n'+ removeAttrs + '\n' + tab + '});'
                                );
                            }
                        }
                    }

                });

                // iterate current defined attrs
                // looking for adds & changes.
                _.forEach(current.attributes, function (v,k) {

                    if(v._modelAttribute){
                        // check if is new column or existing.
                        var prevCol = previous.attributes ? previous.attributes[k] : undefined,
                            prevAttrs, curAttrs;

                        if(prevCol){

                            curAttrs = attributesToString(filterAttributes(v), filterAttributes(prevCol));
                            prevAttrs = attributesToString(filterAttributes(prevCol), filterAttributes(v));

                            if(curAttrs) {
                                build.up.changeColumn.push(
                                        'migration.changeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        tab + '{\n' + curAttrs + '\n' + tab + '});'
                                );
                            }

                            if(prevAttrs) {
                                build.down.changeColumn.push(
                                        'migration.changeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        tab + '{\n' +  prevAttrs + '\n' + tab +'});'
                                );
                            }

                        } else {

                            curAttrs = attributesToString(filterAttributes(v));
                            // column needs to be added.

                            if(curAttrs) {
                                build.up.addColumn.push(
                                        'migration.addColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ',\n' +
                                        '{\n' + curAttrs + '\n' + tab + '});'
                                );
                                build.down.removeColumn.push(
                                        'migration.removeColumn(' + qwrap(modelName) + ', ' + qwrap(k) + ');'
                                );
                            }

                        }
                    }

                    ctr += 1;

                });

            }

            // this is a new model/table.
            else {

                // this is a new table so we need to parse options.
                var newAttrs = [],
                    ctr = 0,
                    attrTab = getTabs(1, true),
                    newOpts;

                tab = getTabs(0, true);

                parseOptions(current.options);
                newOpts = build.options.join(',\n')

                _.forEach(current.attributes, function (v,k) {

                    //if (v._modelAttribute) {
                        var attrs = attributesToString(filterAttributes(v), null, 2);
                        if(attrs) newAttrs.push(attrTab + k + ': {\n' + attrs + '\n' + attrTab + '}');
                    //}
                    ctr +=1;
                });

                build.up.createTable.push(
                        'migration.createTable(' + qwrap(modelName) + ',\n' +
                        tab + '{\n' + newAttrs.join(',\n') + '\n' + tab + '},\n' +
                        tab + '{\n' + newOpts + '\n' + tab + '});'
                );
                build.down.dropTable.push('migration.dropTable(' + qwrap(modelName) + ');');

            }

            build.up.toString = upToString;
            build.down.toString = downToString;
        }

        // parse properties attributes & options.
        compareMigration();

        return build;

    };

    return compare;

}
237400
function SearchResultItem(rangeResult) {
        this.name = rangeResult.name;
        this.textRange = new TextRange(rangeResult.document, rangeResult.lineStart, rangeResult.lineEnd);
        // this.$listItem is assigned in load()
    }
1030930
def search_by_module(search_string, modules, opts={})
    login! unless logged_in?
    
    options = { 
      :offset => nil, 
      :limit => nil, 
    }.merge! opts
    
    json = <<-EOF
      {
        "session": "#{@sugar_session_id}",
        "search_string": "#{search_string}",
        "modules": "#{modules}",
        "offset": #{options[:offset]},
        "max_results": #{options[:limit]}
      }
    EOF
    json.gsub!(/^\s{6}/,'')
    send!(:search_by_module, json)
  end
217131
function doSearch(searchObject, nextPages) {

    savedSearchObject = searchObject;
    if (!files) {
        console.log("no file object found");
        return {};
    }
    results = {};
    numMatches = 0;
    numFiles = 0;
    foundMaximum = false;
    if (!nextPages) {
        exceedsMaximum = false;
        evaluatedMatches = 0;
    }
    var queryObject = parseQueryInfo(searchObject.queryInfo);
    if (searchObject.files) {
        files = searchObject.files;
    }
    if (searchObject.getAllResults) {
        searchObject.maxResultsToReturn = MAX_TOTAL_RESULTS;
    }
    doSearchInFiles(files, queryObject.queryExpr, searchObject.startFileIndex, searchObject.maxResultsToReturn);
    if (crawlComplete && !nextPages) {
        numMatches = getNumMatches(files, queryObject.queryExpr);
    }
    var send_object = {
        "results":  results,
        "foundMaximum":  foundMaximum,
        "exceedsMaximum":  exceedsMaximum
    };

    if (!nextPages) {
        send_object.numMatches = numMatches;
        send_object.numFiles = numFiles;
    }

    if (searchObject.getAllResults) {
        send_object.allResultsAvailable = true;
    }
    return send_object;
}
1082237
function (items, query, fields, exact) {
        var self = this;
        var isTarget = function (fieldName) {
          return fields.indexOf(fieldName) !== -1;
        };
        if (query === '') {
          return items;
        }
        fields = fields || ['name', 'owner', 'description', 'keyword'];
        return _.filter(items, function (item) {
          if ((isTarget('name') && self.matchedInString(query, item.name, exact)) ||
              (isTarget('owner') && self.matchedInString(query, item.owner, exact)) ||
              (isTarget('description') && self.matchedInString(query, item.description, exact)) ||
              (isTarget('keyword') && self.matchedInArray(query, item.keywords, exact))) {
            return true;
          }
          return false;
        });
      }