targetStrの部分文字列とsearchStrを比較する searchStrが空文字列の場合は比較しないでfalseを返す
966502
function checkSubStr(targetStr, pos, searchStr) {
  if (searchStr === "" || pos < 0 || pos + searchStr.length > targetStr.length) {
    return false;
  }
  return targetStr.substr(pos, searchStr.length) === searchStr;
}
1144408
function parseQueryStr(url) {
      if (!contains(url, '?')) return {};
      var queryStr = url.substring(url.lastIndexOf('?') + 1);
      if (queryStr === '') return {};
      var querys = queryStr.split('&'), params = {}, i = -1;
      while (++i < querys.length) {
        var kw = querys[i].split('=')
          , decode = decodeURIComponent;
        params[decode(kw[0])] = decode(kw[1] || '');
      }
      return params;
    }
829481
def processGif(searchStr):
    '''
    
    '''
    
    # Sanitizing searchStr
    # TODO: Find a better way to do this
    searchStr.replace('| ', ' ')
    searchStr.replace('|', ' ')
    searchStr.replace(', ', ' ')
    searchStr.replace(',', ' ')
    searchStr.rstrip()
    searchStr = searchStr.strip('./?\'!,')
    searchStr = searchStr.replace(' ', '+')

    if searchStr is None or searchStr == '':
        print("No search parameters specified!")
        return no_search_params

    api_url = 'http://api.giphy.com/v1/gifs/search'
    api_key = 'dc6zaTOxFJmzC'

    payload = {
        'q': searchStr,
        'limit': 1,
        'api_key': api_key,
    }

    r = requests.get(api_url, params=payload)
    parsed_json = json.loads(r.text)
    # print(parsed_json)

    if len(parsed_json['data']) == 0:
        print("Couldn't find suitable match for gif! :(")
        return -1

    else:               # Success!
        imgURL = parsed_json['data'][0]['images']['fixed_height']['url']
        # print(imgURL)
        return imgURL
509446
def _getDataFromRegPolData(search_string, policy_data, return_value_name=False):
    '''
    
    '''
    value = None
    values = []
    encoded_semicolon = ';'.encode('utf-16-le')
    if return_value_name:
        values = {}
    if search_string:
        registry = Registry()
        if len(search_string.split(encoded_semicolon)) >= 3:
            vtype = registry.vtype_reverse[ord(search_string.split(encoded_semicolon)[2].decode('utf-32-le'))]
        else:
            vtype = None
        search_string = re.escape(search_string)
        matches = re.finditer(search_string, policy_data, re.IGNORECASE)
        matches = [m for m in matches]
        if matches:
            for match in matches:
                pol_entry = policy_data[match.start():(policy_data.index(']'.encode('utf-16-le'),
                                                                         match.end())
                                                       )
                                        ].split(encoded_semicolon)
                if len(pol_entry) >= 2:
                    valueName = pol_entry[1].decode('utf-16-le').rstrip(chr(0))
                if len(pol_entry) >= 5:
                    value = pol_entry[4]
                    if vtype == 'REG_DWORD' or vtype == 'REG_QWORD':
                        if value:
                            if vtype == 'REG_DWORD':
                                for v in struct.unpack(b'I', value):
                                    value = v
                            elif vtype == 'REG_QWORD':
                                for v in struct.unpack(b'Q', value):
                                    value = v
                        else:
                            value = 0
                    elif vtype == 'REG_MULTI_SZ':
                        value = value.decode('utf-16-le').rstrip(chr(0)).split(chr(0))
                    else:
                        value = value.decode('utf-16-le').rstrip(chr(0))
                if return_value_name:
                    log.debug('we want value names and the value')
                    values[valueName] = value
                elif len(matches) > 1:
                    log.debug('we have multiple matches, we will return a list')
                    values.append(value)
    if values:
        value = values

    return value
1337480
function getSearchMatches(contents, queryExpr) {
    if (!contents) {
        return;
    }
    // Quick exit if not found or if we hit the limit
    if (foundMaximum || contents.search(queryExpr) === -1) {
        return [];
    }

    var match, lineNum, line, ch, totalMatchLength, matchedLines, numMatchedLines, lastLineLength, endCh,
        padding, leftPadding, rightPadding, highlightOffset, highlightEndCh,
        lines   = contents.split("\n"),
        matches = [];

    while ((match = queryExpr.exec(contents)) !== null) {
        lineNum          = offsetToLineNum(lines, match.index);
        line             = lines[lineNum];
        ch               = match.index - contents.lastIndexOf("\n", match.index) - 1;  // 0-based index
        matchedLines     = match[0].split("\n");
        numMatchedLines  = matchedLines.length;
        totalMatchLength = match[0].length;
        lastLineLength   = matchedLines[matchedLines.length - 1].length;
        endCh            = (numMatchedLines === 1 ? ch + totalMatchLength : lastLineLength);
        highlightEndCh   = (numMatchedLines === 1 ? endCh : line.length);
        highlightOffset  = 0;

        if (highlightEndCh <= MAX_DISPLAY_LENGTH) {
            // Don't store more than 200 chars per line
            line = line.substr(0, Math.min(MAX_DISPLAY_LENGTH, line.length));
        } else if (totalMatchLength > MAX_DISPLAY_LENGTH) {
            // impossible to display the whole match
            line = line.substr(ch, ch + MAX_DISPLAY_LENGTH);
            highlightOffset = ch;
        } else {
            // Try to have both beginning and end of match displayed
            padding = MAX_DISPLAY_LENGTH - totalMatchLength;
            rightPadding = Math.floor(Math.min(padding / 2, line.length - highlightEndCh));
            leftPadding = Math.ceil(padding - rightPadding);
            highlightOffset = ch - leftPadding;
            line = line.substring(highlightOffset, highlightEndCh + rightPadding);
        }

        matches.push({
            start:       {line: lineNum, ch: ch},
            end:         {line: lineNum + numMatchedLines - 1, ch: endCh},

            highlightOffset: highlightOffset,

            // Note that the following offsets from the beginning of the file are *not* updated if the search
            // results change. These are currently only used for multi-file replacement, and we always
            // abort the replace (by shutting the results panel) if we detect any result changes, so we don't
            // need to keep them up to date. Eventually, we should either get rid of the need for these (by
            // doing everything in terms of line/ch offsets, though that will require re-splitting files when
            // doing a replace) or properly update them.
            startOffset: match.index,
            endOffset:   match.index + totalMatchLength,

            line:        line,
            result:      match,
            isChecked:   true
        });

        // We have the max hits in just this 1 file. Stop searching this file.
        // This fixed issue #1829 where code hangs on too many hits.
        // Adds one over MAX_RESULTS_IN_A_FILE in order to know if the search has exceeded
        // or is equal to MAX_RESULTS_IN_A_FILE. Additional result removed in SearchModel
        if (matches.length > MAX_RESULTS_IN_A_FILE) {
            queryExpr.lastIndex = 0;
            break;
        }

        // Pathological regexps like /^/ return 0-length matches. Ensure we make progress anyway
        if (totalMatchLength === 0) {
            queryExpr.lastIndex++;
        }
    }

    return matches;
}
58851
function startSearch() {
  iface.question('Enter search: ', function (query) {
    // Get the results of our query
    var matches = fileFinder.query(query),
        len = matches.length;

    // If no results were found
    if (len === 0) {
      console.log('No results found for: ' + query);
      startSearch();
    } else if (len === 1) {
      var item = matches[0];
    // If there is one, skip to go
      console.log('Opening: ' + item);
      fileFinder.open(item);

      // Begin the search again
      startSearch();
    } else {
    // Otherwise, list options
      console.log('');
      console.log('----------------');
      console.log('Search Results');
      console.log('----------------');
      for (i = 0; i < len; i++) {
        console.log(i + ': ' + matches[i]);
      }

      // Ask for a number
      iface.question('Which item would you like to open? ', function (numStr) {
        var num = +numStr,
            item;

        // If the number is not NaN and we were not given an empty string
        if (num === num && numStr !== '') {
          // and if it is in our result set
          if (num >= 0 && num < len) {
            // Open it
            item = matches[num];
            console.log('Opening: ' + item);
            fileFinder.open(item);
          }
        } else {
        // Otherwise, if there was a word in there so we are assuming it was 'rescan'
          // Rescan
          console.log('Rescanning...');
          fileFinder.scan();
        }

        // Begin the search again
        startSearch();
      });
    }
  });
}
646287
function handleSearchText(searchText, previousSearchText) {
      self.index = -1;
      // do nothing on init
      if (searchText === previousSearchText) return;
      else if (self.selectedItem && self.displayProperty1) {
        setLoading(false);
        if (self.selectedItem[self.displayProperty1] !== searchText) {
          self.selectedItem = null;
          self.hidden = shouldHide();
          if (self.itemList && self.itemListCopy) {
            self.itemList = angular.copy(self.itemListCopy);
          }
        }
      }
      else if (self.remoteMethod) {
        fetchResults(searchText);
      }
      else if (self.itemList) {
        self.itemList = $filter('filter')(self.itemListCopy, searchText);
      }
    }
495444
function instantSearch() {

    const q = $("#searchbox").val();
    if (q === '')
        return;

    const matcher = "/matcher?beginsWith=" + q;
    const request = host + matcher;

    console.debug(request);

    $.getJSON(request, '', {})
        .done(data => {

            $("#searchbox").autocomplete({
                source: data,
                select: (event) => {
                    event.stopPropagation();
                    $("#search").trigger("click");
                }
            });
        })
        .fail((d, textStatus, error) => {

            const err = d.status + " " + error + " -> message: " + d.responseText;
            bootstrapAlert.error(err);
            console.error(`Search request failed: \n ${err}`);
        });
}
433780
public StrBuilder replaceAll(final String searchStr, final String replaceStr) {
        final int searchLen = (searchStr == null ? 0 : searchStr.length());
        if (searchLen > 0) {
            final int replaceLen = (replaceStr == null ? 0 : replaceStr.length());
            int index = indexOf(searchStr, 0);
            while (index >= 0) {
                replaceImpl(index, index + searchLen, searchLen, replaceStr, replaceLen);
                index = indexOf(searchStr, index + replaceLen);
            }
        }
        return this;
    }
878672
function predicate(str) {
                var prefix = fs.readFileSync(prefixTestFile, "utf8");
                var postfix = fs.readFileSync(postfixTestFile, "utf8");
                fs.writeFileSync(tmpTestFile, prefix + str + postfix, "utf8");
                process.stdout.write('.');
                var result = shelljs.exec("gtimeout 30s node " + tmpTestFile+ " > /dev/null 2>&1");
                if (result.code !== 0) {
                    return MAX_COST + 1;
                } else {
                    var results = JSON.parse(fs.readFileSync(resultFile, "utf8"));
                    if (results.featuresCovered[i]) {
                        if (results.modified) {
                            console.log("New feature splitting test found: " + str);
                            console.log("Writing test to " + newTestFileName + newTestIndex + ".js. Ignoring the test.");
                            fs.writeFileSync(newTestFileName + newTestIndex + ".js", prefix + str + postfix, "utf8");
                            return MAX_COST + 1;
                        } else {
                            var curMin = Object.keys(results.featuresCovered).length;
                            if (min > curMin) {
                                min = curMin;
                            }
                            console.log("Found a passing test");
                            console.log(str);
                            return curMin;
                        }
                    } else {
                        return MAX_COST + 1;
                    }
                }
            }
186460
@Nullable
  public static String getLastToken (@Nullable final String sStr, final char cSearch)
  {
    final int nIndex = getLastIndexOf (sStr, cSearch);
    return nIndex == StringHelper.STRING_NOT_FOUND ? sStr : sStr.substring (nIndex + 1);
  }
306563
final public void standardSearch(
		String[] words,
		WebSiteRequest req,
		HttpServletResponse response,
		List<SearchResult> results,
		AoByteArrayOutputStream bytes,
		List<WebPage> finishedPages
	) throws ServletException, IOException, SQLException {
		if(!finishedPages.contains(this)) {
			String title = null;
			String description = null;
			String author = null;

			// The counted matches will go here
			int totalMatches = 0;
			int size;

			// Search the byte data only if not able to index
			long mySearchLastModified = getSearchLastModified();
			if (mySearchLastModified == -1) {
				title = getTitle();
				description = getDescription();
				author = getAuthor();
				String keywords = getKeywords();

				// Get the HTML content
				bytes.reset();
				ChainWriter out = new ChainWriter(bytes);
				try {
					doGet(out, null, response);
				} finally {
					out.flush();
					out.close();
				}
				byte[] content = bytes.getInternalByteArray();
				size = bytes.size();

				int len = words.length;
				for (int c = 0; c < len; c++) {
					String word = words[c];
					int wordMatch =
						// Add the keywords with weight 10
						StringUtility.countOccurrences(keywords, word) * 10

						// Add the description with weight 5
						+StringUtility.countOccurrences(description, word) * 5

						// Add the title with weight 5
						+StringUtility.countOccurrences(title, word) * 5

						// Add the content with weight 1
						+StringUtility.countOccurrences(content, size, word)

						// Add the author with weight 1
						+StringUtility.countOccurrences(author, word);

					if (wordMatch == 0) {
						totalMatches = 0;
						break;
					}
					totalMatches += wordMatch;
				}

				if (totalMatches > 0) {
					size += keywords.length() + description.length() + title.length() + author.length();
				}
			} else {
				// Rebuild the search index if no longer valid
				if (mySearchLastModified != this.searchLastModified) {
					// Only synchronize for index rebuild
					synchronized (this) {
						if (mySearchLastModified != this.searchLastModified) {
							title = getTitle();
							description = getDescription();
							author = getAuthor();
							String keywords = getKeywords();

							// Get the HTML content
							bytes.reset();
							ChainWriter out = new ChainWriter(bytes);
							try {
								doGet(out, null, null);
							} catch(NullPointerException err) {
								getLogger().log(Level.WARNING, null, err);
							} finally {
								out.flush();
								out.close();
							}
							byte[] bcontent = bytes.getInternalByteArray();
							size = bytes.size();
							String content = new String(bcontent, 0, size);

							// Remove all the indexed words
							searchWords.clear();
							searchCounts.clear();

							// Add the keywords with weight 10
							addSearchWords(keywords, 10);

							// Add the description with weight 5
							addSearchWords(description, 5);

							// Add the title with weight 5
							addSearchWords(title, 5);

							// Add the content with weight 1
							addSearchWords(content, 1);

							// Add the author with weight 1
							addSearchWords(author, 1);

							searchByteCount = size + keywords.length() + description.length() + title.length() + author.length();
							//searchWords.trimToSize();
							//searchCounts.trimToSize();
							this.searchLastModified = mySearchLastModified;
						}
					}
				}

				// Count the words from the index
				int searchWordsSize = searchWords.size();

				int len = words.length;
				for (int c = 0; c < len; c++) {
					String word = words[c];

					// Count through each word
					int wordMatch = 0;
					for (int d = 0; d < searchWordsSize; d++) {
						String searchWord = searchWords.get(d);
						int count = StringUtility.countOccurrences(searchWord, word);
						if (count > 0) wordMatch += count * searchCounts.get(d)[0];
					}

					if (wordMatch == 0) {
						totalMatches = 0;
						break;
					}
					totalMatches += wordMatch;
				}

				// Use the cached size
				size = searchByteCount;
			}

			if (totalMatches > 0) {
				float probability=
					totalMatches
					/ (
						size <= 0
						? 1.0f :
						((float)Math.log(size))
					)
				;
				results.add(
					new SearchResult(
						req.getContextPath()+req.getURL(this),
						probability,
						title == null ? getTitle() : title,
						description == null ? getDescription() : description,
						author == null ? getAuthor() : author
					)
				);
			}

			// Flag as done
			finishedPages.add(this);

			// Search recursively
			WebPage[] myPages = getCachedPages(req);
			int len = myPages.length;
			for (int c = 0; c < len; c++) myPages[c].search(words, req, response, results, bytes, finishedPages);
		}
	}
1027881
function filterData(str, data) {
  data = data || [];
  var ctx = String(str || '').trim();
  var slashParts = ctx.split('/');
  ctx = slashParts.pop();
  var wordParts = String(ctx).trim().split(' ');
  var res = data.filter(function (item) {
    return (strip(item).slice(0, ctx.length) === ctx);
  });
  res = res.map(function (item) {
    var parts = String(item).trim().split(' ');
    if (parts.length > 1) {
      parts = parts.slice(wordParts.length);
      return parts.join(' ');
    }
    return item;
  });
  return res;
}
347238
def search_filename(self, searchterm):
        
        return self.__search(type_attribute=self.__mispfilenametypes(), value=searchterm)
1266777
function searchInFile(row, callback){
		// console.log(row);

		var result = {
			'matched': false,
			'type': row.type,
			'count': 0
		};

		if( _this.cond.matchFileName ){
			if( php.basename(row.path).match( _this.cond.keyword ) ){
				// ファイル名にキーワードマッチング
				result.matched = true;
			}
		}

		if( row.type == 'file' ){
			// ファイルの場合
			fs.readFile( row.path, function( err, bin ){
				if(_this.completed){
					return;
				}

				var result = {
					'matched': false,
					'type': 'file',
					'count': 0
				};
				if(err){
					// エラー
					countDone ++;
					result.error = err;
					_this.cond.error(row.path, result);
					_this.cond.progress(countDone, countTarget);
					callback();
					return;
				}
				bin = bin.toString('UTF8');

				var matched = bin.match( _this.cond.keyword );
				if( matched ){
					// キーワードマッチング
					result.matched = true;
					result.count = matched.length;
				}

				countDone ++;
				if( result.matched ){
					// マッチした場合
					_this.cond.match(row.path, result);
				}else{
					// マッチしなかった場合
					_this.cond.unmatch(row.path, result);
				}
				_this.cond.progress(countDone, countTarget);
				callback();
				return;

			} );
		}else{
			// ディレクトリの場合
			countDone ++;
			if( result.matched ){
				// マッチした場合
				_this.cond.match(row.path, result);
			}else{
				// マッチしなかった場合
				_this.cond.unmatch(row.path, result);
			}
			_this.cond.progress(countDone, countTarget);
			callback();
			return;
		}
	}
665925
function(src, stringToFind, stringToReplace) {

      var temp, index;

      temp = src;
      index = temp.indexOf(stringToFind);

      while (index != -1) {
        temp = temp.replace(stringToFind, stringToReplace);
        index = temp.indexOf(stringToFind);
      }

      return temp;
    }
1046907
function( data, tag, searchData ) {

			var letter, l, depth = 2,
				current = searchData;

			for ( l = 0; l < depth; l++ ) {
				letter = tag.substring(l, l + 1);
				if (!current[letter] ) {
					current[letter] = {};
					current[letter].list = [];
				}
				if ( indexOf(current[letter].list, data) == -1 ) {
					current[letter].list.push(data);
				}
				current = current[letter];
			}
		}